From 90dd97d65b743e7734da2bab148b139891dbe37a Mon Sep 17 00:00:00 2001 From: Vamsi Kalagaturu Date: Wed, 7 Oct 2026 11:52:53 +0200 Subject: [PATCH 01/16] Record runs as a store-agnostic record with a PROV view - RunRecord (rec.record) is what rec knows of a run: OSLC state and verdict, times, result and fail trace, program and recording software, trigger, host, agents, sources, repositories, dependencies, resources, artefacts and metrics - Observer(store) records every event once for any store: load the record, change it, save it; a run cancelled in the store does not start, only a run that has not started can be cancelled, and a step logged again replaces its value - A store is any object with load, save, run_ids and close (rec.stores.Store); FileStore keeps a run as its PROV document (fmt="rdf") or its record as JSON (fmt="json"), MariaDBStore as one row with state and verdict columns, migrating the previous release's table - rec.provenance maps a record to PROV with the rdf-utils helpers and back: an unstarted run is a prov:Activity, a started one a prov-ext:Execution associated with rec whose plan is the file defining the run; files are entities, relative paths prov-ext:RelativeLocation under the directory they were logged from - Run records the program it ran, stops the heartbeat before completion, and runs post-run hooks after it, so a hook that raises no longer rewrites the verdict - rdflib and rdf-utils become dependencies; MariaDB stays an extra; observers are replaced by the observer and stores --- .github/workflows/tests.yml | 53 +++++ README.md | 48 ++++- examples/decentral_run.py | 8 +- pyproject.toml | 9 +- rec/__init__.py | 20 ++ rec/observer.py | 136 ++++++++++++ rec/observers/__init__.py | 0 rec/observers/base.py | 29 --- rec/observers/mariadb_observer.py | 229 -------------------- rec/provenance.py | 337 ++++++++++++++++++++++++++++++ rec/record.py | 139 ++++++++++++ rec/run.py | 257 ++++++++++++++--------- rec/stores/__init__.py | 20 ++ rec/stores/file_store.py | 58 +++++ rec/stores/mariadb_store.py | 124 +++++++++++ tests/test_mariadb_store.py | 86 ++++++++ tests/test_run.py | 173 +++++++++++++++ 17 files changed, 1351 insertions(+), 375 deletions(-) create mode 100644 .github/workflows/tests.yml create mode 100644 rec/observer.py delete mode 100644 rec/observers/__init__.py delete mode 100644 rec/observers/base.py delete mode 100644 rec/observers/mariadb_observer.py create mode 100644 rec/provenance.py create mode 100644 rec/record.py create mode 100644 rec/stores/__init__.py create mode 100644 rec/stores/file_store.py create mode 100644 rec/stores/mariadb_store.py create mode 100644 tests/test_mariadb_store.py create mode 100644 tests/test_run.py 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..1f1abca 100644 --- a/README.md +++ b/README.md @@ -11,17 +11,26 @@ In your terminal, go to where you have cloned this repository and install it in pip install -e . ``` -## Examples +Add the MariaDB backend when runs are stored in a database: -The current skeleton of the code allows you to run two examples: The `MariaDBObserver` and a `Run`. +```shell +pip install -e ".[mariadb]" +``` -### Observers +## Examples -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: +### Observers and stores -```shell -python rec/observers/mariadb_observer.py -``` +An `Observer` records the events of any number of runs in a store; every call names the run it is +about, and whoever created the observer closes it once its runs are over. What it records is a +`rec.record.RunRecord`, the same whatever the store: + +- `FileStore(directory, fmt="rdf")` keeps each run as its PROV document, `.ld.json`; + `fmt="json"` keeps the record itself as `.json`. +- `MariaDBStore(db_name, table)` keeps one row per run: the record, with `state` and `verdict` + columns to query runs by. +- Any object with `load(run_id)`, `save(record)`, `run_ids(state=None)` and `close()` is a store + (`rec.stores.Store`). ### Creating a run @@ -31,6 +40,19 @@ The [example](examples/decentral_run.py) shows how to create a run object, attac python examples/decentral_run.py ``` +### What a run records + +`rec.provenance.graph(record)` is the run in PROV on the +[rec and prov-extension vocabularies](https://secorolab.github.io/metamodels/), built with the +rdf-utils PROV helpers, and `rec.provenance.record(graph, run_id)` reads it back. Its lifecycle is +an OSLC Automation state and verdict (`rec.State` and `rec.Verdict`: a run is `queued`, +`in-progress`, `canceled` or `complete`, and once complete `passed`, `failed` or `error`; a +verdict is `unavailable` before that). A run that has not started is a `prov:Activity`; once +started it is a `prov-ext:Execution` associated with rec, whose plan is the file defining the run. +Its host is a `rec:Host`; sources, resources, repositories and dependencies are entities it +`prov:used`; artefacts are what it generated, with checksum and size; scalars are `rec:Metric` +quantities. A relative file path is recorded relative to the directory it was logged from. The +run node is `https://secoro.uni-bremen.de/rec/run/` unless another `base` is given. ## Connecting to MariaDB @@ -43,6 +65,18 @@ MARIADB_HOST="localhost" MARIADB_PORT=3306 ``` +## Tests + +```shell +pip install -e ".[dev]" +pytest +``` + +The conformance test validates a recorded run against the shapes in 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. diff --git a/examples/decentral_run.py b/examples/decentral_run.py index 700d804..a5dc9d8 100644 --- a/examples/decentral_run.py +++ b/examples/decentral_run.py @@ -1,5 +1,6 @@ +from rec.observer import Observer from rec.run import Run -from rec.observers.mariadb_observer import MariaDBObserver +from rec.stores.mariadb_store import MariaDBStore def main(): @@ -10,8 +11,9 @@ def main(): if __name__ == "__main__": - run = Run() + observer = Observer(MariaDBStore()) + run = Run(observers=[observer]) run.main = main - run.observers.append(MariaDBObserver()) run.run() + observer.close() diff --git a/pyproject.toml b/pyproject.toml index 079209c..21f242a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,9 +7,8 @@ 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@main", ] requires-python = ">= 3.12" readme = "README.md" @@ -18,8 +17,8 @@ maintainers = [ ] [project.optional-dependencies] -dev = ["black>=24.4.2"] +mariadb = ["dotenv", "mariadb"] +dev = ["black>=24.4.2", "pytest", "pyshacl"] [tool.setuptools.packages.find] where = ["."] # list of folders that contain the packages (["."] by default) - diff --git a/rec/__init__.py b/rec/__init__.py index e69de29..567d075 100644 --- a/rec/__init__.py +++ b/rec/__init__.py @@ -0,0 +1,20 @@ +"""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" + WARNING = "warning" + FAILED = "failed" + ERROR = "error" diff --git a/rec/observer.py b/rec/observer.py new file mode 100644 index 0000000..1aab8f5 --- /dev/null +++ b/rec/observer.py @@ -0,0 +1,136 @@ +"""Records the events of runs in a store.""" + +import os +import threading +from contextlib import contextmanager +from datetime import datetime +from pathlib import Path, PurePath +from urllib.parse import urlsplit + +from rdf_utils.models.prov import get_pkg_info + +from rec import State, Verdict +from rec.record import ( + Agent, + Dependency, + FileRef, + Generation, + Host, + Metric, + Repository, + RunRecord, + Software, + Usage, +) +from rec.stores import Store + + +class Observer: + """Records the events of any number of runs in one store; every call names its run. + + Whoever creates the observer closes it, once every run it records is over. + """ + + def __init__(self, store: Store): + self.store = store + # A run's heartbeat thread and the run itself change the same record. + self._lock = threading.RLock() + + @contextmanager + def _record(self, run_id: str): + """The run's record as the store holds it, saved back once changed; an error saves nothing.""" + with self._lock: + record = self.store.load(run_id) or RunRecord(run_id) + yield record + self.store.save(record) + + def log_queued_run(self, run_id: str, queued_time: datetime): + with self._record(run_id) as record: + record.state, record.verdict, record.queued_time = State.QUEUED, Verdict.UNAVAILABLE, queued_time + + def log_started_run(self, run_id: str, started_time: datetime, trigger=None, starter=None, program=None): + with self._record(run_id) as record: + if record.state is State.CANCELED: + raise RuntimeError(f"run '{run_id}' was cancelled -- it cannot start") + record.state, record.verdict, record.start_time = State.IN_PROGRESS, Verdict.UNAVAILABLE, started_time + record.trigger, record.starter = trigger, starter + record.program = file_ref(program) if program else None + record.recorder = Software(*get_pkg_info("rec")) + + def log_run_heartbeat(self, run_id: str, beat_time: datetime, result=None): + with self._record(run_id) as record: + record.heartbeat_time = beat_time + if result is not None: + record.result = result + + def log_completed_run(self, run_id: str, completed_time: datetime, result=None): + self._end(run_id, completed_time, Verdict.PASSED, result=result) + + def log_interrupted_run(self, run_id: str, interrupted_time: datetime, fail_trace: str | None = None): + self._end(run_id, interrupted_time, Verdict.ERROR, fail_trace=fail_trace) + + def log_failed_run(self, run_id: str, failed_time: datetime, fail_trace: str | None = None): + self._end(run_id, failed_time, Verdict.FAILED, fail_trace=fail_trace) + + def log_cancelled_run(self, run_id: str, cancelled_time: datetime): + with self._record(run_id) as record: + if record.state not in (State.NEW, State.QUEUED): + raise RuntimeError(f"run '{run_id}' is {record.state} -- only a run that has not started can be cancelled") + record.state, record.verdict, record.end_time = State.CANCELED, Verdict.UNAVAILABLE, cancelled_time + + def log_host_info(self, run_id: str, host_info: dict): + with self._record(run_id) as record: + record.host = Host(host_info.get("hostname"), host_info.get("os"), host_info.get("python"), host_info.get("cpu")) + + def log_sources(self, run_id: str, sources: list): + with self._record(run_id) as record: + record.sources += [file_ref(row["path"], row.get("title"), row.get("sha256"), row.get("size_bytes")) for row in sources] + + def log_repositories(self, run_id: str, repositories: list): + with self._record(run_id) as record: + record.repositories += [Repository(row["name"], row.get("url"), row.get("commit")) for row in repositories] + + def log_dependencies(self, run_id: str, dependencies: list): + with self._record(run_id) as record: + record.dependencies += [Dependency(row["name"], row.get("version")) for row in dependencies] + + def log_scalar(self, run_id: str, metric_name: str, value, step: int | None = None, time: datetime | None = None): + with self._record(run_id) as record: + if step is None: + step = sum(1 for metric in record.metrics if metric.name == metric_name) + # One value per step: logging a step again is a re-measurement, not a second one. + kept = [metric for metric in record.metrics if (metric.name, metric.step) != (metric_name, step)] + record.metrics = [*kept, Metric(metric_name, step, value, time)] + + def add_agent(self, run_id: str, agent_id: str, agent_type: str, name: str | None = None): + with self._record(run_id) as record: + record.agents.append(Agent(agent_id, agent_type, name)) + + def add_resource(self, run_id: str, filename, usage_activity=None, usage_time=None, title=None, sha256=None, size_bytes=None): + with self._record(run_id) as record: + record.resources.append(Usage(file_ref(filename, title, sha256, size_bytes), usage_activity, usage_time)) + + def add_artefact(self, run_id: str, filename, gen_activity=None, generated_time=None, title=None, sha256=None, size_bytes=None): + with self._record(run_id) as record: + record.artefacts.append(Generation(file_ref(filename, title, sha256, size_bytes), gen_activity, generated_time)) + + def close(self): + self.store.close() + + def _end(self, run_id, end_time, verdict, result=None, fail_trace=None): + with self._record(run_id) as record: + record.state, record.verdict, record.end_time = State.COMPLETE, verdict, end_time + if result is not None: + record.result = result + record.fail_trace = fail_trace + + +def file_ref(path, title=None, sha256=None, size_bytes=None) -> FileRef: + """A file as logged: an IRI as given, an absolute path resolved, a relative path from the working directory.""" + path = str(path) + # An IRI's scheme is longer than a drive letter. + if len(urlsplit(path).scheme) > 1: + return FileRef(path, None, title, sha256, size_bytes) + if Path(path).is_absolute(): + return FileRef(str(Path(path).resolve()), None, title, sha256, size_bytes) + return FileRef(PurePath(path).as_posix(), os.getcwd(), title, sha256, size_bytes) 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..55cb326 --- /dev/null +++ b/rec/provenance.py @@ -0,0 +1,337 @@ +"""A run record as PROV on the prov-extension and rec vocabularies, and back.""" + +import json +from urllib.parse import quote, unquote + +from rdf_utils.models.prov import ( + _path_from_file_url, + add_agent, + add_entity, + add_file_entity, + add_relative_location, + load_execution_prov, + load_pkg_prov, +) +from rdflib import XSD, Graph, Literal, Namespace, URIRef +from rdflib.namespace import DCAT, PROV, RDF, RDFS, SDO + +from rec import State, Verdict +from rec.record import ( + Agent, + Dependency, + FileRef, + Generation, + Host, + Metric, + Repository, + RunRecord, + Software, + Usage, +) + +RUN_BASE = "https://secoro.uni-bremen.de/rec/run/" +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#") +SPDX = Namespace("http://spdx.org/rdf/terms#") +QUDT = Namespace("http://qudt.org/schema/qudt/") +DIMENSIONLESS = URIRef("http://qudt.org/vocab/quantitykind/Dimensionless") +UNITLESS = URIRef("http://qudt.org/vocab/unit/UNITLESS") + +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.WARNING: OSLC_AUTO.warning, + 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, + "spdx": SPDX, + "dcat": DCAT, + "schema": SDO, + "qudt": QUDT, + "rdfs": RDFS, + "xsd": XSD, +} + + +def graph(record: RunRecord, base: str = RUN_BASE) -> Graph: + """The run as a `prov:Activity` with its OSLC state; once started, a `prov-ext:Execution` + of its program by the software that recorded it.""" + g = Graph() + for prefix, namespace in PREFIXES.items(): + g.bind(prefix, namespace) + run = URIRef(base + record.run_id) + g.add((run, RDF.type, PROV.Activity)) + g.add((run, OSLC_AUTO.state, STATES[record.state])) + g.add((run, OSLC_AUTO.verdict, VERDICTS[record.verdict])) + for value, predicate in ((record.queued_time, REC["queued-time"]), (record.heartbeat_time, REC["heartbeat-time"])): + if value: + g.add((run, predicate, Literal(value))) + if record.result is not None: + g.add((run, REC.result, Literal(record.result))) + if record.fail_trace: + g.add((run, REC["fail-trace"], Literal(record.fail_trace, datatype=XSD.string))) + + used = [_file(g, run, ref) for ref in record.sources] + for row in record.repositories: + repository = URIRef(f"{run}/repository/{quote(row.name, safe='')}") + add_entity(g, repository) + g.add((repository, RDF.type, SDO.SoftwareSourceCode)) + g.add((repository, RDFS.label, Literal(row.name))) + if row.commit: + g.add((repository, SDO.identifier, Literal(row.commit))) + if row.url: + g.add((repository, SDO.codeRepository, URIRef(row.url))) + used.append(repository) + for row in record.dependencies: + dependency = URIRef(f"{run}/dependency/{quote(row.name, safe='')}") + add_entity(g, dependency) + g.add((dependency, RDF.type, SDO.SoftwareApplication)) + g.add((dependency, RDFS.label, Literal(row.name))) + if row.version: + g.add((dependency, SDO.softwareVersion, Literal(row.version))) + used.append(dependency) + for usage in record.resources: + entity = _file(g, run, usage.file) + activity = URIRef(usage.activity or run) + node = URIRef(f"{run}/usage/{quote(str(activity), safe='')}/{quote(usage.file.path, safe='')}") + g.add((node, RDF.type, PROV.Usage)) + g.add((node, PROV.entity, entity)) + if usage.time: + g.add((node, PROV.atTime, Literal(usage.time))) + g.add((activity, RDF.type, PROV.Activity)) + g.add((activity, PROV.used, entity)) + g.add((activity, PROV.qualifiedUsage, node)) + + if record.start_time: + software = URIRef(f"{run}/software") + load_pkg_prov(g, software, record.recorder.name, record.recorder.version, record.recorder.commit, record.recorder.repository) + association = URIRef(f"{run}/association") + g.add((run, PROV.qualifiedAssociation, association)) + g.add((association, RDF.type, PROV.Association)) + g.add((association, PROV.agent, software)) + if record.program: + plan = _file(g, run, record.program) + g.add((plan, RDF.type, PROV.Plan)) + g.add((association, PROV.hadPlan, plan)) + used.append(plan) + load_execution_prov(g, run, used, software, record.start_time, record.end_time) + else: + for entity in used: + g.add((run, PROV.used, entity)) + if record.end_time: + g.add((run, PROV.endedAtTime, Literal(record.end_time))) + for agent in record.agents: + add_agent(g, URIRef(agent.id), (PROV[agent.type],), agent.name) + g.add((run, PROV.wasAssociatedWith, URIRef(agent.id))) + + if record.trigger: + start = URIRef(f"{run}/start") + g.add((run, PROV.wasStartedBy, URIRef(record.trigger))) + g.add((run, PROV.qualifiedStart, start)) + g.add((start, RDF.type, PROV.Start)) + g.add((start, PROV.entity, URIRef(record.trigger))) + if record.starter: + g.add((start, PROV.hadActivity, URIRef(record.starter))) + if record.host: + host = URIRef(f"{run}/host") + g.add((host, RDF.type, REC.Host)) + g.add((host, RDF.type, PROV.Location)) + for key, predicate in HOST_TERMS.items(): + if getattr(record.host, key): + g.add((host, predicate, Literal(getattr(record.host, key)))) + g.add((run, PROV.atLocation, host)) + + for generation in record.artefacts: + entity = _file(g, run, generation.file) + activity = URIRef(generation.activity or run) + node = URIRef(f"{run}/generation/{quote(str(activity), safe='')}/{quote(generation.file.path, safe='')}") + g.add((activity, RDF.type, PROV.Activity)) + g.add((entity, PROV.wasGeneratedBy, activity)) + g.add((entity, PROV.qualifiedGeneration, node)) + g.add((node, RDF.type, PROV.Generation)) + g.add((node, PROV.activity, activity)) + if generation.time: + g.add((node, PROV.atTime, Literal(generation.time))) + for metric in record.metrics: + node = URIRef(f"{run}/metric/{quote(metric.name, safe='')}/{metric.step}") + add_entity(g, node) + g.add((node, RDF.type, REC.Metric)) + g.add((node, PROV.wasGeneratedBy, run)) + g.add((node, RDFS.label, Literal(metric.name))) + g.add((node, QUDT.hasQuantityKind, DIMENSIONLESS)) + g.add((node, QUDT.value, Literal(metric.value))) + g.add((node, QUDT.unit, UNITLESS)) + g.add((node, REC.step, Literal(metric.step))) + if metric.time: + g.add((node, PROV.generatedAtTime, Literal(metric.time))) + return g + + +def record(g: Graph, run_id: str, base: str = RUN_BASE) -> RunRecord: + """The record ``graph`` wrote; its lists come back sorted, a graph having no order.""" + run = URIRef(base + run_id) + association = g.value(run, PROV.qualifiedAssociation) + plan, software = g.value(association, PROV.hadPlan), g.value(association, PROV.agent) + start = g.value(run, PROV.qualifiedStart) + host = g.value(run, PROV.atLocation) + result = g.value(run, REC.result) + run_usages = {g.value(usage, PROV.entity) for usage in g.objects(run, PROV.qualifiedUsage)} + kinds = {SDO.SoftwareSourceCode, SDO.SoftwareApplication} + return RunRecord( + run_id=run_id, + state=next(state for state, iri in STATES.items() if iri == g.value(run, OSLC_AUTO.state)), + verdict=next(verdict for verdict, iri in VERDICTS.items() if iri == g.value(run, OSLC_AUTO.verdict)), + queued_time=_python(g.value(run, REC["queued-time"])), + start_time=_python(g.value(run, PROV.startedAtTime)), + end_time=_python(g.value(run, PROV.endedAtTime)), + heartbeat_time=_python(g.value(run, REC["heartbeat-time"])), + result=result.toPython() if result is not None else None, + fail_trace=_python(g.value(run, REC["fail-trace"])), + program=_file_ref(g, plan) if plan else None, + recorder=Software( + str(g.value(software, SDO.name)), + _python(g.value(software, SDO.softwareVersion)), + _python(g.value(software, SDO.identifier)), + _python(g.value(software, SDO.codeRepository)), + ) + if software + else None, + trigger=_python(g.value(start, PROV.entity)), + starter=_python(g.value(start, PROV.hadActivity)), + host=Host(**{key: _python(g.value(host, predicate)) for key, predicate in HOST_TERMS.items()}) if host else None, + agents=sorted( + ( + Agent( + str(agent), + next((str(kind).removeprefix(str(PROV)) for kind in g.objects(agent, RDF.type) if kind != PROV.Agent), "Agent"), + _python(g.value(agent, SDO.name)), + ) + for agent in g.objects(run, PROV.wasAssociatedWith) + if agent != software + ), + key=lambda agent: agent.id, + ), + sources=sorted( + ( + _file_ref(g, entity) + for entity in g.objects(run, PROV.used) + if entity != plan and entity not in run_usages and not set(g.objects(entity, RDF.type)) & kinds + ), + key=lambda ref: ref.path, + ), + repositories=sorted( + ( + Repository(str(g.value(node, RDFS.label)), _python(g.value(node, SDO.codeRepository)), _python(g.value(node, SDO.identifier))) + for node in g.subjects(RDF.type, SDO.SoftwareSourceCode) + ), + key=lambda row: row.name, + ), + dependencies=sorted( + ( + Dependency(str(g.value(node, RDFS.label)), _python(g.value(node, SDO.softwareVersion))) + for node in g.subjects(RDF.type, SDO.SoftwareApplication) + ), + key=lambda row: row.name, + ), + resources=sorted( + ( + Usage( + _file_ref(g, g.value(usage, PROV.entity)), + None if activity == run else str(activity), + _python(g.value(usage, PROV.atTime)), + ) + for activity, usage in g.subject_objects(PROV.qualifiedUsage) + ), + key=lambda row: (row.activity or "", row.file.path), + ), + artefacts=sorted( + ( + Generation( + _file_ref(g, entity), + None if g.value(node, PROV.activity) == run else str(g.value(node, PROV.activity)), + _python(g.value(node, PROV.atTime)), + ) + for entity, node in g.subject_objects(PROV.qualifiedGeneration) + ), + key=lambda row: (row.activity or "", row.file.path), + ), + metrics=sorted( + ( + Metric( + str(g.value(node, RDFS.label)), + g.value(node, REC.step).toPython(), + g.value(node, QUDT.value).toPython(), + _python(g.value(node, PROV.generatedAtTime)), + ) + for node in g.subjects(RDF.type, REC.Metric) + ), + key=lambda row: (row.name, row.step), + ), + ) + + +def document(g: Graph) -> dict: + """The graph as JSON-LD, compacted on the vocabularies' prefixes.""" + return json.loads(g.serialize(format="json-ld", context={prefix: str(ns) for prefix, ns in PREFIXES.items()})) + + +def _file(g: Graph, run: URIRef, ref: FileRef) -> URIRef: + entity = URIRef(f"{run}/file/{quote(ref.path, safe='')}") + if ref.root: + location = URIRef(f"{entity}/location") + add_relative_location(g, location, ref.path, ref.root) + else: + location = ref.path + add_file_entity(g, entity, location) + if ref.title: + g.set((entity, RDFS.label, Literal(ref.title))) + if ref.sha256: + checksum = URIRef(f"{entity}/checksum") + g.add((entity, SPDX.checksum, checksum)) + g.add((checksum, RDF.type, SPDX.Checksum)) + g.set((checksum, SPDX.algorithm, SPDX.checksumAlgorithm_sha256)) + g.set((checksum, SPDX.checksumValue, Literal(ref.sha256, datatype=XSD.hexBinary))) + if ref.size_bytes is not None: + g.set((entity, DCAT.byteSize, Literal(ref.size_bytes, datatype=XSD.nonNegativeInteger))) + return entity + + +def _file_ref(g: Graph, entity: URIRef) -> FileRef: + location = g.value(entity, PROV.atLocation) + rel_path = g.value(location, PROV_EXT["rel-path"]) + if rel_path is not None: + path, root = unquote(str(rel_path)), str(_path_from_file_url(str(g.value(location, PROV.atLocation)))) + else: + path, root = str(_path_from_file_url(str(location))) if str(location).startswith("file:") else str(location), None + size = g.value(entity, DCAT.byteSize) + # An xsd:hexBinary's Python value is bytes; the record holds the hex text. + checksum = g.value(g.value(entity, SPDX.checksum), SPDX.checksumValue) + return FileRef( + path, + root, + _python(g.value(entity, RDFS.label)), + str(checksum) if checksum is not None else None, + size.toPython() if size is not None else None, + ) + + +def _python(term): + """A term as the value the record holds: a literal's Python value, an IRI as its string.""" + if term is None: + return None + return term.toPython() if isinstance(term, Literal) else str(term) diff --git a/rec/record.py b/rec/record.py new file mode 100644 index 0000000..538c18b --- /dev/null +++ b/rec/record.py @@ -0,0 +1,139 @@ +"""What rec records of a run, independent of where it is stored.""" + +import json +from dataclasses import asdict, dataclass, field +from datetime import datetime +from typing import Any + +from rec import State, Verdict + +TIMES = ("queued_time", "start_time", "end_time", "heartbeat_time") + + +@dataclass +class FileRef: + """A file as logged: an absolute path, an IRI, or a path relative to ``root``.""" + + path: str + root: str | None = None + title: str | None = None + sha256: str | None = None + size_bytes: int | None = None + + +@dataclass +class Usage: + """A file an activity used; the activity is the run itself when None.""" + + file: FileRef + activity: str | None = None + time: datetime | None = None + + +@dataclass +class Generation: + """A file an activity generated; the activity is the run itself when None.""" + + file: FileRef + activity: str | None = None + time: datetime | None = None + + +@dataclass +class Agent: + id: str + type: str + name: str | None = None + + +@dataclass +class Repository: + name: str + url: str | None = None + commit: str | None = None + + +@dataclass +class Dependency: + name: str + version: str | None = None + + +@dataclass +class Metric: + name: str + step: int + value: float | int + time: datetime | None = None + + +@dataclass +class Software: + """The package that recorded the run, as it was when the run started.""" + + name: str + version: str | None = None + commit: str | None = None + repository: str | None = None + + +@dataclass +class Host: + hostname: str | None = None + os: str | None = None + python: str | None = None + cpu: str | None = None + + +@dataclass +class RunRecord: + run_id: str + state: State = State.NEW + verdict: Verdict = Verdict.UNAVAILABLE + queued_time: datetime | None = None + start_time: datetime | None = None + end_time: datetime | None = None + heartbeat_time: datetime | None = None + result: Any = None + fail_trace: str | None = None + program: FileRef | None = None + recorder: Software | None = None + trigger: str | None = None + starter: str | None = None + host: Host | None = None + agents: list[Agent] = field(default_factory=list) + sources: list[FileRef] = field(default_factory=list) + repositories: list[Repository] = field(default_factory=list) + dependencies: list[Dependency] = field(default_factory=list) + resources: list[Usage] = field(default_factory=list) + artefacts: list[Generation] = field(default_factory=list) + metrics: list[Metric] = field(default_factory=list) + + +def to_json(record: RunRecord) -> str: + """The record as JSON, its times in ISO 8601.""" + return json.dumps(asdict(record), default=datetime.isoformat, indent=2) + + +def from_json(text: str) -> RunRecord: + """The record ``to_json`` wrote.""" + data = json.loads(text) + for row in [data, *data["resources"], *data["artefacts"], *data["metrics"]]: + for key in (*TIMES, "time"): + if row.get(key): + row[key] = datetime.fromisoformat(row[key]) + return RunRecord( + **{key: data[key] for key in ("run_id", "result", "fail_trace", "trigger", "starter", *TIMES)}, + state=State(data["state"]), + verdict=Verdict(data["verdict"]), + program=FileRef(**data["program"]) if data["program"] else None, + recorder=Software(**data["recorder"]) if data["recorder"] else None, + host=Host(**data["host"]) if data["host"] else None, + agents=[Agent(**row) for row in data["agents"]], + sources=[FileRef(**row) for row in data["sources"]], + repositories=[Repository(**row) for row in data["repositories"]], + dependencies=[Dependency(**row) for row in data["dependencies"]], + resources=[Usage(FileRef(**row["file"]), row["activity"], row["time"]) for row in data["resources"]], + artefacts=[Generation(FileRef(**row["file"]), row["activity"], row["time"]) for row in data["artefacts"]], + metrics=[Metric(**row) for row in data["metrics"]], + ) diff --git a/rec/run.py b/rec/run.py index 5a1cbf8..1722774 100644 --- a/rec/run.py +++ b/rec/run.py @@ -1,8 +1,17 @@ import datetime +import inspect +import logging +import platform +import socket import threading -from typing import Sequence +import traceback +from collections.abc import Sequence +from uuid import uuid4 -from rec.observers.base import BaseObserver +from rec import State, Verdict +from rec.observer import Observer + +logger = logging.getLogger(__name__) class IntervalTimer(threading.Thread): @@ -24,46 +33,52 @@ def run(self): self.func() +def host_info(): + """Information about the machine executing a run""" + return { + "hostname": socket.gethostname(), + "os": platform.platform(), + "python": platform.python_version(), + "cpu": platform.processor() or None, + } + + class Run: def __init__( self, - observers: Sequence[BaseObserver] = [], - ingredients: list = [], - run_id: int = None, + observers: Sequence[Observer] = (), + ingredients: list = (), + run_id: str | None = None, scenario=None, - pre_run_hooks: list = [], - post_run_hooks: list = [], + pre_run_hooks: list = (), + post_run_hooks: list = (), **kwargs, ): self._id = run_id - self.observers = observers - self.ingredients = ingredients + self.observers = list(observers) + self.ingredients = list(ingredients) + self.scenario = scenario self.start_time = None self.end_time = None - self.status = None + self.state = None + self.verdict = None self.result = None - self.pre_run_hooks = pre_run_hooks - self.post_run_hooks = post_run_hooks + self.pre_run_hooks = list(pre_run_hooks) + self.post_run_hooks = list(post_run_hooks) - self.heartbeat = None + self._heartbeat = None self.beat_interval = 10 - 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 + @property + def id(self): + """The run's identity, the same in every observer; minted here when the caller gave none""" 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 + self._id = str(uuid4()) + return self._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()) - ) - return elapsed_time + self.end_time = datetime.datetime.now(datetime.UTC) + return self.end_time def _start_heartbeat(self): if self.beat_interval > 0: @@ -80,27 +95,29 @@ def _stop_heartbeat(self): def _emit_heartbeat(self): beat_time = datetime.datetime.now(datetime.UTC) - print("Running....") + logger.debug("Run %s still running, result so far: %s", self.id, self.result) # Update info on observers for observer in self.observers: - observer.log_run_heartbeat(self._id, beat_time, result=self.result) + 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) + self.state, self.verdict = State.CANCELED, Verdict.UNAVAILABLE + cancelled_time = self._stop_time() + logger.info("Cancelled run %s", self.id) # Update info on observers for observer in self.observers: - observer.log_cancelled_run(self._id, cancelled_time) + observer.log_cancelled_run(self.id, cancelled_time) def _emit_queued(self): - self.status = RunStatus.QUEUED + self.state, self.verdict = State.QUEUED, Verdict.UNAVAILABLE queued_time = datetime.datetime.now(datetime.UTC) + logger.info("Queued run %s", self.id) # Update info on observers for observer in self.observers: - observer.log_queued_run(self._id, queued_time) + observer.log_queued_run(self.id, queued_time) def _emit_started(self, trigger=None, starter=None): """ @@ -109,46 +126,47 @@ def _emit_started(self, trigger=None, starter=None): :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) + start_time = datetime.datetime.now(datetime.UTC) + logger.info("Starting run %s", self.id) - # Update info on observers + try: + program = inspect.getfile(type(self)) + except (TypeError, OSError): + # A class typed into an interpreter has no file to name. + program = None + # The stores go first: one of them may hold a cancellation this object never saw. 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)) + observer.log_started_run(self.id, start_time, trigger=trigger, starter=starter, program=program) + self.state, self.verdict = State.IN_PROGRESS, Verdict.UNAVAILABLE + self.start_time = start_time + self.log_host_info(host_info()) def _emit_completed(self): - self.status = RunStatus.COMPLETED - elapsed_time = self._stop_time() - print("Completed after {}".format(elapsed_time)) + self.state, self.verdict = State.COMPLETE, Verdict.PASSED + completed_time = self._stop_time() + logger.info("Completed run %s after %s", self.id, completed_time - self.start_time) # Update info on observers for observer in self.observers: - observer.log_completed_run(self._id, self.stop_time) + observer.log_completed_run(self.id, completed_time, self.result) - def _emit_interrupted(self): - self.status = RunStatus.INTERRUPTED - elapsed_time = self._stop_time() + def _emit_interrupted(self, error=None): + self.state, self.verdict = State.COMPLETE, Verdict.ERROR + interrupted_time = self._stop_time() + logger.warning("Interrupted run %s after %s", self.id, interrupted_time - self.start_time) # Update info on observers for observer in self.observers: - observer.log_interrupted_run(self._id, elapsed_time) + observer.log_interrupted_run(self.id, interrupted_time, _fail_trace(error)) - def _emit_failed(self): - self.status = RunStatus.FAILED - elapsed_time = self._stop_time() + def _emit_failed(self, error=None): + self.state, self.verdict = State.COMPLETE, Verdict.FAILED + failed_time = self._stop_time() + logger.error("Failed run %s after %s", self.id, failed_time - self.start_time, exc_info=error) # Update info on observers for observer in self.observers: - observer.log_failed_run(self._id, elapsed_time) + observer.log_failed_run(self.id, failed_time, _fail_trace(error)) def _execute_hooks(self, hooks): for hook in hooks: @@ -157,34 +175,50 @@ def _execute_hooks(self, hooks): def main(self): pass - def run(self): + def queue(self): + """Record the run as queued, before a runner starts it""" + if self.state is not None: + raise RuntimeError(f"cannot queue a run that is {self.state}") + self._emit_queued() + return self.id + + def cancel(self): + """Cancel a queued run before it starts""" + if self.state is not State.QUEUED: + raise RuntimeError(f"only a queued run can be cancelled, not one that is {self.state}") + self._emit_cancelled() + + def run(self, trigger=None, starter=None): """ A centralized runner can start and complete a run. Decentralized runners should not use this method. + :param trigger: An entity that triggers the run + :param starter: The activity that generated the trigger :return: """ + if self.state is State.CANCELED: + raise RuntimeError("cannot start a cancelled run") + self._emit_started(trigger, starter) 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() + logger.info("Result of run %s: %s", self.id, self.result) self._stop_heartbeat() - self._execute_hooks(self.post_run_hooks) - except KeyboardInterrupt as k: + self._emit_completed() + except KeyboardInterrupt as interrupt: self._stop_heartbeat() - self._emit_interrupted() - except Exception as ex: + self._emit_interrupted(interrupt) + return self.result + except Exception as error: self._stop_heartbeat() - self._emit_failed() - finally: - for observer in self.observers: - observer.close() - + self._emit_failed(error) + return self.result + # After completion: a post-run hook that raises is the caller's error, not the run's. + self._execute_hooks(self.post_run_hooks) return self.result - def log_scalar(self, metric_name, value, step: int = None): + def log_scalar(self, metric_name, value, step: int | None = None): """Log a measurement at runtime :param metric_name: Name of the metric being logged @@ -192,44 +226,55 @@ def log_scalar(self, metric_name, value, step: int = None): :param step: Optional. Integer value representing the iteration number :return: """ - pass + now = datetime.datetime.now(datetime.UTC) + for observer in self.observers: + observer.log_scalar(self.id, metric_name, value, step, now) - def log_sources(self): + def log_sources(self, sources: list): """Log the source code files used to execute this run (e.g., file name/path, md5) + :param sources: rows with a ``path`` and optionally ``title``, ``sha256``, ``size_bytes`` :return: """ - pass + for observer in self.observers: + observer.log_sources(self.id, sources) - def log_repositories(self): + def log_repositories(self, repositories: list): """ Log the git information of the sources used in this run (url, commit/tag, uncommited changes) + :param repositories: rows with a ``name`` and optionally ``url``, ``commit`` :return: """ - pass + for observer in self.observers: + observer.log_repositories(self.id, repositories) - def log_dependencies(self): + def log_dependencies(self, dependencies: list): """ Log the dependencies of the sources used in this run (e.g., package name, version) + :param dependencies: rows with a ``name`` and optionally ``version`` :return: """ - pass + for observer in self.observers: + observer.log_dependencies(self.id, dependencies) - def log_host_info(self): + def log_host_info(self, host_info: dict): """ Log information about the machine executing this run (e.g., cpu, gpu, OS, user, hostname, python version and venv, env variables, etc.) + :param host_info: ``hostname``, ``os``, ``python``, ``cpu``; see :func:`host_info` :return: """ - pass + for observer in self.observers: + observer.log_host_info(self.id, host_info) - def add_agent(self, agent_id: str, agent_type: str, **kwargs): + def add_agent(self, agent_id: str, agent_type: str, name: str | None = None): """ 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: + :param agent_type: The type of agent being added, e.g., SoftwareAgent, Person + :param name: The agent's name; a software agent must have one :return: """ - pass + for observer in self.observers: + observer.add_agent(self.id, agent_id, agent_type, name) def add_resource( self, @@ -237,7 +282,8 @@ def add_resource( usage_activity=None, usage_time=None, title=None, - **kwargs, + sha256=None, + size_bytes=None, ): """ Add a resource to the run @@ -249,11 +295,14 @@ def add_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: + :param sha256: The file's SHA-256 checksum, as hex + :param size_bytes: The file's size :return: """ if usage_time is None: usage_time = datetime.datetime.now(datetime.UTC) + for observer in self.observers: + observer.add_resource(self.id, filename, usage_activity, usage_time, title, sha256, size_bytes) def add_artefact( self, @@ -261,7 +310,8 @@ def add_artefact( gen_activity=None, generated_time=None, title=None, - **kwargs, + sha256=None, + size_bytes=None, ): """ Add an artefact to the run @@ -273,26 +323,29 @@ def add_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: + :param sha256: The file's SHA-256 checksum, as hex + :param size_bytes: The file's size :return: """ if generated_time is None: generated_time = datetime.datetime.now(datetime.UTC) + for observer in self.observers: + observer.add_artefact(self.id, filename, gen_activity, generated_time, title, sha256, size_bytes) def info(self): - """Print out a summary of the run data + """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" + return { + "id": self._id, + "state": self.state, + "verdict": self.verdict, + "start_time": self.start_time.isoformat() if self.start_time else None, + "end_time": self.end_time.isoformat() if self.end_time else None, + "result": self.result, + } + + +def _fail_trace(error): + return "".join(traceback.format_exception(error)) if error is not None else None diff --git a/rec/stores/__init__.py b/rec/stores/__init__.py new file mode 100644 index 0000000..241da06 --- /dev/null +++ b/rec/stores/__init__.py @@ -0,0 +1,20 @@ +"""Where run records are kept: any object with these methods is a store.""" + +from typing import Protocol + +from rec import State +from rec.record import RunRecord + + +class Store(Protocol): + def load(self, run_id: str) -> RunRecord | None: + """The run's record, None for a run the store does not hold.""" + + def save(self, record: RunRecord) -> None: + """Keep the record, replacing the run's previous one.""" + + def run_ids(self, state: State | None = None) -> list[str]: + """The runs the store holds, those in STATE only when given.""" + + def close(self) -> None: + """Release what the store holds open; whoever created it calls this once.""" diff --git a/rec/stores/file_store.py b/rec/stores/file_store.py new file mode 100644 index 0000000..d956838 --- /dev/null +++ b/rec/stores/file_store.py @@ -0,0 +1,58 @@ +"""A store keeping each run as one file in a directory.""" + +import json +from pathlib import Path + +from rdflib import Graph + +from rec import State, provenance +from rec.record import RunRecord, from_json, to_json + +# The file each format keeps a run in: its record, or its PROV document. +SUFFIXES = {"json": ".json", "rdf": ".ld.json"} + + +class FileStore: + def __init__(self, directory, fmt: str = "rdf", base: str = provenance.RUN_BASE): + """ + :param directory: Where the files go; created on first write + :param fmt: ``rdf`` for the run's PROV document, ``json`` for its record as JSON + :param base: IRI base of the run nodes in a PROV document + """ + if fmt not in SUFFIXES: + raise ValueError(f"'{fmt}' is not a file format -- use one of {list(SUFFIXES)}") + self.directory = Path(directory) + self.fmt = fmt + self.base = base + + def path(self, run_id: str) -> Path: + if not run_id or run_id in (".", "..") or Path(run_id).name != run_id: + raise ValueError(f"'{run_id}' is not a file name -- a run id names its file in the directory") + return self.directory / f"{run_id}{SUFFIXES[self.fmt]}" + + def load(self, run_id: str) -> RunRecord | None: + path = self.path(run_id) + if not path.exists(): + return None + if self.fmt == "json": + return from_json(path.read_text()) + return provenance.record(Graph().parse(path, format="json-ld"), run_id, self.base) + + def save(self, record: RunRecord) -> None: + if self.fmt == "json": + text = to_json(record) + else: + text = json.dumps(provenance.document(provenance.graph(record, self.base)), indent=2) + self.directory.mkdir(parents=True, exist_ok=True) + path = self.path(record.run_id) + temporary = path.with_name(f"{path.name}.tmp") + temporary.write_text(text + "\n") + temporary.replace(path) + + def run_ids(self, state: State | None = None) -> list[str]: + suffix = SUFFIXES[self.fmt] + run_ids = sorted(path.name.removesuffix(suffix) for path in self.directory.glob(f"*{suffix}")) + return [run_id for run_id in run_ids if state is None or self.load(run_id).state is state] + + def close(self) -> None: + """Nothing stays open between writes.""" diff --git a/rec/stores/mariadb_store.py b/rec/stores/mariadb_store.py new file mode 100644 index 0000000..b756265 --- /dev/null +++ b/rec/stores/mariadb_store.py @@ -0,0 +1,124 @@ +"""A store keeping each run as one row of a MariaDB table.""" + +import json +import logging +import os +from datetime import datetime + +import mariadb +from dotenv import load_dotenv + +from rec import State, Verdict +from rec.record import RunRecord, from_json, to_json + +logger = logging.getLogger(__name__) + +# The previous release's `status`, as an OSLC state and verdict. +STATUS_LIFECYCLES = { + "QUEUED": (State.QUEUED, Verdict.UNAVAILABLE), + "RUNNING": (State.IN_PROGRESS, Verdict.UNAVAILABLE), + "CANCELLED": (State.CANCELED, Verdict.UNAVAILABLE), + "COMPLETED": (State.COMPLETE, Verdict.PASSED), + "FAILED": (State.COMPLETE, Verdict.FAILED), + "INTERRUPTED": (State.COMPLETE, Verdict.ERROR), + "TIMED_OUT": (State.COMPLETE, Verdict.ERROR), +} + + +class MariaDBStore: + def __init__(self, db_name: str = "logbook", table: str = "logs"): + """ + Store in a MariaDB table, 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 table: Name of the table, one row per run: ``id`` a short number to display, + ``run_id``, ``state`` and ``verdict`` to query by, and ``record`` + """ + load_dotenv() + self.db_name = db_name + self.table = table + 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() + self.cursor.execute( + f""" + CREATE TABLE IF NOT EXISTS {table} ( + id INT AUTO_INCREMENT PRIMARY KEY, + run_id VARCHAR(255) NOT NULL UNIQUE, + state VARCHAR(20) NOT NULL, + verdict VARCHAR(20) NOT NULL, + record LONGTEXT NOT NULL + ) + """ + ) + self.cursor.execute( + "SELECT column_name FROM information_schema.columns WHERE table_schema = ? AND table_name = ?", + (db_name, table), + ) + if "run_id" not in {row[0] for row in self.cursor}: + self._migrate() + + def _migrate(self): + """A table from the previous release gets the run's columns; its own columns stay as they are.""" + self.cursor.execute( + f"ALTER TABLE {self.table} ADD COLUMN run_id VARCHAR(255), ADD COLUMN state VARCHAR(20), " + "ADD COLUMN verdict VARCHAR(20), ADD COLUMN record LONGTEXT, MODIFY status VARCHAR(20) NULL" + ) + self.cursor.execute(f"SELECT id, status, run_info FROM {self.table}") + for number, status, run_info in self.cursor.fetchall(): + # All the previous release recorded besides a run's status: when it was queued or started. + info = json.loads(run_info) if run_info else {} + state, verdict = STATUS_LIFECYCLES.get(status, (State.COMPLETE, Verdict.UNAVAILABLE)) + record = RunRecord( + str(number), + state, + verdict, + queued_time=datetime.fromisoformat(info["queue_time"]) if info.get("queue_time") else None, + start_time=datetime.fromisoformat(info["start_time"]) if info.get("start_time") else None, + ) + self.cursor.execute( + f"UPDATE {self.table} SET run_id = ?, state = ?, verdict = ?, record = ? WHERE id = ?", + (record.run_id, str(state), str(verdict), to_json(record), number), + ) + self.cursor.execute( + f"ALTER TABLE {self.table} MODIFY run_id VARCHAR(255) NOT NULL, ADD UNIQUE (run_id), " + "MODIFY state VARCHAR(20) NOT NULL, MODIFY verdict VARCHAR(20) NOT NULL, MODIFY record LONGTEXT NOT NULL" + ) + logger.info("Migrated table %s: run_id, state, verdict and record added", self.table) + + def load(self, run_id: str) -> RunRecord | None: + self.cursor.execute(f"SELECT record FROM {self.table} WHERE run_id = ?", (run_id,)) + row = self.cursor.fetchone() + return from_json(row[0]) if row else None + + def save(self, record: RunRecord) -> None: + values = (str(record.state), str(record.verdict), to_json(record), record.run_id) + # Not INSERT ... ON DUPLICATE KEY UPDATE: InnoDB spends an `id` on every such update. + if self.number(record.run_id) is None: + self.cursor.execute(f"INSERT INTO {self.table} (state, verdict, record, run_id) VALUES (?, ?, ?, ?)", values) + else: + self.cursor.execute(f"UPDATE {self.table} SET state = ?, verdict = ?, record = ? WHERE run_id = ?", values) + + def run_ids(self, state: State | None = None) -> list[str]: + if state is None: + self.cursor.execute(f"SELECT run_id FROM {self.table} ORDER BY id") + else: + self.cursor.execute(f"SELECT run_id FROM {self.table} WHERE state = ? ORDER BY id", (str(state),)) + return [row[0] for row in self.cursor.fetchall()] + + def number(self, run_id: str) -> int | None: + """The short number the table gave the run, None for a run it does not hold.""" + self.cursor.execute(f"SELECT id FROM {self.table} WHERE run_id = ?", (run_id,)) + row = self.cursor.fetchone() + return row[0] if row else None + + 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..cdef51a --- /dev/null +++ b/tests/test_mariadb_store.py @@ -0,0 +1,86 @@ +import json +import os +from datetime import UTC, datetime +from uuid import uuid4 + +import pytest + +pytest.importorskip("mariadb", reason="the MariaDB driver is an optional extra") +from rec import State, Verdict # noqa: E402 +from rec.observer import Observer # noqa: E402 +from rec.run import Run # noqa: E402 +from rec.stores.file_store import FileStore # noqa: E402 +from rec.stores.mariadb_store import MariaDBStore # noqa: E402 + +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(): + table = f"rec_test_{uuid4().hex}" + db = MariaDBStore(db_name=TEST_DATABASE, table=table) + yield db + db.cursor.execute(f"DROP TABLE IF EXISTS {table}") + db.close() + + +class QuickRun(Run): + def main(self): + self.add_artefact("/tmp/rec data/50% done.json") + self.log_scalar("frames", 1) + return "ok" + + +def test_a_row_keeps_the_whole_record(store, tmp_path): + files = FileStore(tmp_path, fmt="json") + runs = [QuickRun(observers=[Observer(store), Observer(files)], run_id=f"run-{i}") for i in range(3)] + for run in runs: + run.beat_interval = 0 + run.run() + for number, run in enumerate(runs, start=1): + assert store.load(run.id) == files.load(run.id) + assert store.number(run.id) == number + # The state and verdict columns are the record's, to query runs by. + store.cursor.execute(f"SELECT state, verdict FROM {store.table} WHERE run_id = 'run-0'") + assert store.cursor.fetchone() == ("complete", "passed") + assert store.run_ids(State.COMPLETE) == ["run-0", "run-1", "run-2"] + + +def test_a_queued_run_is_cancelled_by_id(store): + QuickRun(observers=[Observer(store)], run_id="queued").queue() + assert store.run_ids(State.IN_PROGRESS) == [] + Observer(MariaDBStore(db_name=TEST_DATABASE, table=store.table)).log_cancelled_run("queued", datetime.now(UTC)) + assert (store.load("queued").state, store.load("queued").verdict) == (State.CANCELED, Verdict.UNAVAILABLE) + + +def test_a_table_from_the_previous_release_is_migrated(store): + table = f"{store.table}_old" + # The table as the previous release created it, and what it recorded of a run. + store.cursor.execute( + f""" + CREATE TABLE {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 + ) + """ + ) + started = datetime(2026, 1, 1, tzinfo=UTC) + store.cursor.execute( + f"INSERT INTO {table} (status, run_info) VALUES ('COMPLETED', ?), ('RUNNING', ?)", + (json.dumps({"start_time": started.isoformat()}), json.dumps({"start_time": started.isoformat()})), + ) + try: + migrated = MariaDBStore(db_name=TEST_DATABASE, table=table) + assert (migrated.load("1").state, migrated.load("1").verdict) == (State.COMPLETE, Verdict.PASSED) + assert migrated.load("1").start_time == started + assert migrated.run_ids(State.IN_PROGRESS) == ["2"] + QuickRun(observers=[Observer(migrated)], run_id="run-new").run() + assert migrated.number("run-new") == 3 + migrated.close() + finally: + store.cursor.execute(f"DROP TABLE IF EXISTS {table}") diff --git a/tests/test_run.py b/tests/test_run.py new file mode 100644 index 0000000..5410f77 --- /dev/null +++ b/tests/test_run.py @@ -0,0 +1,173 @@ +import os +import threading +from datetime import UTC, datetime +from pathlib import Path + +import pytest +from pyshacl import validate +from rdf_utils.models.prov import _path_from_file_url, resolve_location +from rdflib import Graph, Literal, URIRef +from rdflib.namespace import PROV, RDF, RDFS, SDO + +from rec import State, Verdict, provenance +from rec.observer import Observer +from rec.provenance import PROV_EXT, REC +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") + + +class CalibrationRun(Run): + def main(self): + self.add_agent("https://example.org/agent/calibrator", "SoftwareAgent", name="calibrator") + self.log_sources([{"path": "model.ld.json", "sha256": "deadbeef", "size_bytes": 4}]) + self.log_repositories([{"name": "controller", "url": "https://example.org/lab/controller", "commit": "0123abcd"}]) + self.log_dependencies([{"name": "rdflib", "version": "7.7.0"}]) + # One file used by two activities whose IRIs end in the same segment. + self.add_resource("config/robot.yaml", usage_activity="https://example.org/calibration/1") + self.add_resource("config/robot.yaml", usage_activity="https://example.org/verification/1") + # A path with spaces and '%', an IRI, and a path relative to where it is logged. + self.add_artefact("/tmp/rec data/50% done.json") + self.add_artefact("https://example.org/data/scan.bag") + self.add_artefact("results/calibration.json", sha256="deadbeef", size_bytes=4) + self.log_scalar("position-error", 0.5) + self.log_scalar("position-error", 0.3) + return "calibrated" + + +class FailingRun(Run): + def main(self): + raise ValueError("no gripper attached") + + +class InterruptedRun(Run): + def main(self): + raise KeyboardInterrupt + + +@pytest.fixture(params=["json", "rdf"]) +def store(request, tmp_path): + return FileStore(tmp_path / request.param, fmt=request.param) + + +def test_a_completed_run_is_an_execution_of_its_program(store, tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + run = CalibrationRun(observers=[Observer(store)], run_id="run-1") + run.beat_interval = 0 + assert run.run() == "calibrated" + + g = provenance.graph(store.load("run-1")) + ok, _, report = validate(g, shacl_graph=SHAPES, inference="rdfs") + assert ok, report + node = URIRef(provenance.RUN_BASE + "run-1") + assert (node, RDF.type, PROV_EXT.Execution) in g + plan = g.value(g.value(node, PROV.qualifiedAssociation), PROV.hadPlan) + assert _path_from_file_url(str(resolve_location(g, plan))) == Path(__file__).resolve() + assert {str(g.value(agent, SDO.name)) for agent in g.objects(node, PROV.wasAssociatedWith)} == {"rec", "calibrator"} + # A dependency is software the run used, not an agent that ran it. + [dependency] = g.subjects(RDFS.label, Literal("rdflib")) + assert (node, PROV.used, dependency) in g and (dependency, RDF.type, PROV.SoftwareAgent) not in g + artefacts = {str(resolve_location(g, entity)) for entity in g.subjects(PROV.qualifiedGeneration, None)} + assert artefacts == { + "file:///tmp/rec%20data/50%25%20done.json", + "https://example.org/data/scan.bag", + (tmp_path.resolve() / "results/calibration.json").as_uri(), + } + assert len(list(g.subjects(RDF.type, PROV.Usage))) == 2 + assert len(list(g.subjects(RDF.type, REC.Metric))) == 2 + + +def test_a_record_is_the_same_in_every_store(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + as_json, as_rdf = FileStore(tmp_path / "json", fmt="json"), FileStore(tmp_path / "rdf", fmt="rdf") + run = CalibrationRun(observers=[Observer(as_json), Observer(as_rdf)], run_id="run-1") + run.beat_interval = 0 + run.run() + # The run logged its lists in the order a graph reads them back. + assert as_rdf.load("run-1") == as_json.load("run-1") + + +def test_a_queued_run_has_not_executed_yet(store): + CalibrationRun(observers=[Observer(store)], run_id="run-q").queue() + g = provenance.graph(store.load("run-q")) + ok, _, report = validate(g, shacl_graph=SHAPES, inference="rdfs") + assert ok, report + node = URIRef(provenance.RUN_BASE + "run-q") + assert (node, RDF.type, PROV.Activity) in g and (node, RDF.type, PROV_EXT.Execution) not in g + assert g.value(node, PROV.used) is None and g.value(node, REC["queued-time"]) is not None + + +@pytest.mark.parametrize( + ("cls", "verdict", "trace"), + [(FailingRun, Verdict.FAILED, "ValueError: no gripper attached"), (InterruptedRun, Verdict.ERROR, "KeyboardInterrupt")], +) +def test_a_run_that_stops_early_records_how(store, cls, verdict, trace): + run = cls(observers=[Observer(store)], run_id="run-3") + run.beat_interval = 0 + run.run() + record = store.load("run-3") + assert (record.state, record.verdict) == (State.COMPLETE, verdict) + assert trace in record.fail_trace + ok, _, report = validate(provenance.graph(record), shacl_graph=SHAPES, inference="rdfs") + assert ok, report + + +def test_a_post_run_hook_that_raises_leaves_the_run_passed(store): + def broken_hook(): + raise RuntimeError("hook") + + run = CalibrationRun(observers=[Observer(store)], run_id="run-h", post_run_hooks=[broken_hook]) + run.beat_interval = 0 + with pytest.raises(RuntimeError, match="hook"): + run.run() + assert (store.load("run-h").state, store.load("run-h").verdict) == (State.COMPLETE, Verdict.PASSED) + + +def test_only_a_run_that_has_not_started_is_cancelled(store): + queued = CalibrationRun(observers=[Observer(store)], run_id="run-q") + queued.queue() + # A scheduler holding only the store cancels a run it did not create, and the store decides. + Observer(store).log_cancelled_run("run-q", datetime.now(UTC)) + with pytest.raises(RuntimeError, match="cancelled"): + queued.run() + assert (store.load("run-q").state, store.load("run-q").verdict) == (State.CANCELED, Verdict.UNAVAILABLE) + + done = CalibrationRun(observers=[Observer(store)], run_id="run-d") + done.beat_interval = 0 + done.run() + with pytest.raises(RuntimeError, match="has not started"): + Observer(store).log_cancelled_run("run-d", datetime.now(UTC)) + assert store.load("run-d").verdict is Verdict.PASSED + assert store.run_ids(State.CANCELED) == ["run-q"] + + +def test_logging_a_step_again_replaces_its_value(store): + observer = Observer(store) + observer.log_scalar("run-m", "error", 0.5, step=1) + observer.log_scalar("run-m", "error", 0.1, step=1) + assert [(metric.step, metric.value) for metric in store.load("run-m").metrics] == [(1, 0.1)] + + +def test_one_observer_records_many_runs_at_once(store): + """Every run is addressed by its id, and none closes the observer.""" + observer = Observer(store) + runs = [CalibrationRun(observers=[observer], run_id=f"run-{i}") for i in range(6)] + for run in runs: + run.beat_interval = 0.01 + threads = [threading.Thread(target=run.run) for run in runs] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + assert store.run_ids(State.COMPLETE) == sorted(run.id for run in runs) + assert all(len(store.load(run.id).metrics) == 2 for run in runs) + + +@pytest.mark.parametrize("run_id", ["../escape", "/tmp/escape", "nested/run", "", ".", ".."]) +def test_a_run_id_names_a_file_inside_the_directory(store, run_id): + with pytest.raises(ValueError, match="not a file name"): + store.path(run_id) From 7dd71d3fff7dd19562c4a945d7c0161dfccbd61b Mon Sep 17 00:00:00 2001 From: Vamsi Kalagaturu Date: Wed, 7 Oct 2026 15:02:28 +0200 Subject: [PATCH 02/16] Edit runs atomically per store and drop main compatibility - Store.edit(run_id) replaces save: FileStore holds an flock on .lock, MariaDBStore a SELECT ... FOR UPDATE transaction, so a start and a cancel from separate observers cannot both succeed - A run starts only when new or queued, in Run.run and Observer.log_started_run - Run ids are percent-encoded in run IRIs - A list or mapping result is an rdf:JSON literal and reads back as itself - Drop the migration of MariaDBObserver's table and its test - Drop Run's unused ingredients, scenario and **kwargs --- README.md | 13 +++++-- rec/observer.py | 12 ++---- rec/provenance.py | 11 ++++-- rec/run.py | 9 +---- rec/stores/__init__.py | 5 ++- rec/stores/file_store.py | 13 +++++++ rec/stores/mariadb_store.py | 78 ++++++++++--------------------------- tests/test_mariadb_store.py | 30 -------------- 8 files changed, 58 insertions(+), 113 deletions(-) diff --git a/README.md b/README.md index 1f1abca..a54880e 100644 --- a/README.md +++ b/README.md @@ -29,8 +29,11 @@ about, and whoever created the observer closes it once its runs are over. What i `fmt="json"` keeps the record itself as `.json`. - `MariaDBStore(db_name, table)` keeps one row per run: the record, with `state` and `verdict` columns to query runs by. -- Any object with `load(run_id)`, `save(record)`, `run_ids(state=None)` and `close()` is a store - (`rec.stores.Store`). +- Any object with `load(run_id)`, `edit(run_id)`, `run_ids(state=None)` and `close()` is a store + (`rec.stores.Store`). `edit` is a context manager yielding the run's record and keeping it when + the block ends; no other edit of that run, from any process, may interleave, so a cancellation + and a start cannot both succeed. `FileStore` locks with `flock` (POSIX), `MariaDBStore` with + `SELECT ... FOR UPDATE`. ### Creating a run @@ -51,8 +54,10 @@ verdict is `unavailable` before that). A run that has not started is a `prov:Act started it is a `prov-ext:Execution` associated with rec, whose plan is the file defining the run. Its host is a `rec:Host`; sources, resources, repositories and dependencies are entities it `prov:used`; artefacts are what it generated, with checksum and size; scalars are `rec:Metric` -quantities. A relative file path is recorded relative to the directory it was logged from. The -run node is `https://secoro.uni-bremen.de/rec/run/` unless another `base` is given. +quantities; a list or mapping result is an `rdf:JSON` literal. A relative file path is recorded +relative to the directory it was logged from. The run node is +`https://secoro.uni-bremen.de/rec/run/`, the id percent-encoded, unless another `base` is +given. ## Connecting to MariaDB diff --git a/rec/observer.py b/rec/observer.py index 1aab8f5..bd2c11f 100644 --- a/rec/observer.py +++ b/rec/observer.py @@ -18,7 +18,6 @@ Host, Metric, Repository, - RunRecord, Software, Usage, ) @@ -33,16 +32,13 @@ class Observer: def __init__(self, store: Store): self.store = store - # A run's heartbeat thread and the run itself change the same record. + # A run's heartbeat thread and the run itself share the store's connection. self._lock = threading.RLock() @contextmanager def _record(self, run_id: str): - """The run's record as the store holds it, saved back once changed; an error saves nothing.""" - with self._lock: - record = self.store.load(run_id) or RunRecord(run_id) + with self._lock, self.store.edit(run_id) as record: yield record - self.store.save(record) def log_queued_run(self, run_id: str, queued_time: datetime): with self._record(run_id) as record: @@ -50,8 +46,8 @@ def log_queued_run(self, run_id: str, queued_time: datetime): def log_started_run(self, run_id: str, started_time: datetime, trigger=None, starter=None, program=None): with self._record(run_id) as record: - if record.state is State.CANCELED: - raise RuntimeError(f"run '{run_id}' was cancelled -- it cannot start") + if record.state not in (State.NEW, State.QUEUED): + raise RuntimeError(f"run '{run_id}' is {record.state} -- only a run that has not started can start") record.state, record.verdict, record.start_time = State.IN_PROGRESS, Verdict.UNAVAILABLE, started_time record.trigger, record.starter = trigger, starter record.program = file_ref(program) if program else None diff --git a/rec/provenance.py b/rec/provenance.py index 55cb326..f14f33d 100644 --- a/rec/provenance.py +++ b/rec/provenance.py @@ -74,14 +74,17 @@ def graph(record: RunRecord, base: str = RUN_BASE) -> Graph: g = Graph() for prefix, namespace in PREFIXES.items(): g.bind(prefix, namespace) - run = URIRef(base + record.run_id) + run = URIRef(base + quote(record.run_id, safe="")) g.add((run, RDF.type, PROV.Activity)) g.add((run, OSLC_AUTO.state, STATES[record.state])) g.add((run, OSLC_AUTO.verdict, VERDICTS[record.verdict])) for value, predicate in ((record.queued_time, REC["queued-time"]), (record.heartbeat_time, REC["heartbeat-time"])): if value: g.add((run, predicate, Literal(value))) - if record.result is not None: + # A structured result as a JSON literal (JSON-LD 1.1, 4.2.2); a scalar keeps its XSD type. + if isinstance(record.result, (dict, list, tuple)): + g.add((run, REC.result, Literal(json.dumps(record.result), datatype=RDF.JSON))) + elif record.result is not None: g.add((run, REC.result, Literal(record.result))) if record.fail_trace: g.add((run, REC["fail-trace"], Literal(record.fail_trace, datatype=XSD.string))) @@ -184,7 +187,7 @@ def graph(record: RunRecord, base: str = RUN_BASE) -> Graph: def record(g: Graph, run_id: str, base: str = RUN_BASE) -> RunRecord: """The record ``graph`` wrote; its lists come back sorted, a graph having no order.""" - run = URIRef(base + run_id) + run = URIRef(base + quote(run_id, safe="")) association = g.value(run, PROV.qualifiedAssociation) plan, software = g.value(association, PROV.hadPlan), g.value(association, PROV.agent) start = g.value(run, PROV.qualifiedStart) @@ -200,7 +203,7 @@ def record(g: Graph, run_id: str, base: str = RUN_BASE) -> RunRecord: start_time=_python(g.value(run, PROV.startedAtTime)), end_time=_python(g.value(run, PROV.endedAtTime)), heartbeat_time=_python(g.value(run, REC["heartbeat-time"])), - result=result.toPython() if result is not None else None, + result=json.loads(result) if result is not None and result.datatype == RDF.JSON else _python(result), fail_trace=_python(g.value(run, REC["fail-trace"])), program=_file_ref(g, plan) if plan else None, recorder=Software( diff --git a/rec/run.py b/rec/run.py index 1722774..2baf5c4 100644 --- a/rec/run.py +++ b/rec/run.py @@ -47,17 +47,12 @@ class Run: def __init__( self, observers: Sequence[Observer] = (), - ingredients: list = (), run_id: str | None = None, - scenario=None, pre_run_hooks: list = (), post_run_hooks: list = (), - **kwargs, ): self._id = run_id self.observers = list(observers) - self.ingredients = list(ingredients) - self.scenario = scenario self.start_time = None self.end_time = None self.state = None @@ -195,8 +190,8 @@ def run(self, trigger=None, starter=None): :param starter: The activity that generated the trigger :return: """ - if self.state is State.CANCELED: - raise RuntimeError("cannot start a cancelled run") + if self.state not in (None, State.QUEUED): + raise RuntimeError(f"cannot start a run that is {self.state}") self._emit_started(trigger, starter) try: diff --git a/rec/stores/__init__.py b/rec/stores/__init__.py index 241da06..300f56f 100644 --- a/rec/stores/__init__.py +++ b/rec/stores/__init__.py @@ -1,5 +1,6 @@ """Where run records are kept: any object with these methods is a store.""" +from contextlib import AbstractContextManager from typing import Protocol from rec import State @@ -10,8 +11,8 @@ class Store(Protocol): def load(self, run_id: str) -> RunRecord | None: """The run's record, None for a run the store does not hold.""" - def save(self, record: RunRecord) -> None: - """Keep the record, replacing the run's previous one.""" + def edit(self, run_id: str) -> AbstractContextManager[RunRecord]: + """The run's record, new if not held, kept when the block ends; no other edit of the run interleaves and an error keeps nothing.""" def run_ids(self, state: State | None = None) -> list[str]: """The runs the store holds, those in STATE only when given.""" diff --git a/rec/stores/file_store.py b/rec/stores/file_store.py index d956838..3543e4a 100644 --- a/rec/stores/file_store.py +++ b/rec/stores/file_store.py @@ -1,6 +1,8 @@ """A store keeping each run as one file in a directory.""" +import fcntl import json +from contextlib import contextmanager from pathlib import Path from rdflib import Graph @@ -38,6 +40,17 @@ def load(self, run_id: str) -> RunRecord | None: return from_json(path.read_text()) return provenance.record(Graph().parse(path, format="json-ld"), run_id, self.base) + @contextmanager + def edit(self, run_id: str): + 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) + record = self.load(run_id) or RunRecord(run_id) + yield record + self.save(record) + def save(self, record: RunRecord) -> None: if self.fmt == "json": text = to_json(record) diff --git a/rec/stores/mariadb_store.py b/rec/stores/mariadb_store.py index b756265..bd5b5ec 100644 --- a/rec/stores/mariadb_store.py +++ b/rec/stores/mariadb_store.py @@ -1,29 +1,14 @@ """A store keeping each run as one row of a MariaDB table.""" -import json -import logging import os -from datetime import datetime +from contextlib import contextmanager import mariadb from dotenv import load_dotenv -from rec import State, Verdict +from rec import State from rec.record import RunRecord, from_json, to_json -logger = logging.getLogger(__name__) - -# The previous release's `status`, as an OSLC state and verdict. -STATUS_LIFECYCLES = { - "QUEUED": (State.QUEUED, Verdict.UNAVAILABLE), - "RUNNING": (State.IN_PROGRESS, Verdict.UNAVAILABLE), - "CANCELLED": (State.CANCELED, Verdict.UNAVAILABLE), - "COMPLETED": (State.COMPLETE, Verdict.PASSED), - "FAILED": (State.COMPLETE, Verdict.FAILED), - "INTERRUPTED": (State.COMPLETE, Verdict.ERROR), - "TIMED_OUT": (State.COMPLETE, Verdict.ERROR), -} - class MariaDBStore: def __init__(self, db_name: str = "logbook", table: str = "logs"): @@ -58,53 +43,30 @@ def __init__(self, db_name: str = "logbook", table: str = "logs"): ) """ ) - self.cursor.execute( - "SELECT column_name FROM information_schema.columns WHERE table_schema = ? AND table_name = ?", - (db_name, table), - ) - if "run_id" not in {row[0] for row in self.cursor}: - self._migrate() - - def _migrate(self): - """A table from the previous release gets the run's columns; its own columns stay as they are.""" - self.cursor.execute( - f"ALTER TABLE {self.table} ADD COLUMN run_id VARCHAR(255), ADD COLUMN state VARCHAR(20), " - "ADD COLUMN verdict VARCHAR(20), ADD COLUMN record LONGTEXT, MODIFY status VARCHAR(20) NULL" - ) - self.cursor.execute(f"SELECT id, status, run_info FROM {self.table}") - for number, status, run_info in self.cursor.fetchall(): - # All the previous release recorded besides a run's status: when it was queued or started. - info = json.loads(run_info) if run_info else {} - state, verdict = STATUS_LIFECYCLES.get(status, (State.COMPLETE, Verdict.UNAVAILABLE)) - record = RunRecord( - str(number), - state, - verdict, - queued_time=datetime.fromisoformat(info["queue_time"]) if info.get("queue_time") else None, - start_time=datetime.fromisoformat(info["start_time"]) if info.get("start_time") else None, - ) - self.cursor.execute( - f"UPDATE {self.table} SET run_id = ?, state = ?, verdict = ?, record = ? WHERE id = ?", - (record.run_id, str(state), str(verdict), to_json(record), number), - ) - self.cursor.execute( - f"ALTER TABLE {self.table} MODIFY run_id VARCHAR(255) NOT NULL, ADD UNIQUE (run_id), " - "MODIFY state VARCHAR(20) NOT NULL, MODIFY verdict VARCHAR(20) NOT NULL, MODIFY record LONGTEXT NOT NULL" - ) - logger.info("Migrated table %s: run_id, state, verdict and record added", self.table) def load(self, run_id: str) -> RunRecord | None: self.cursor.execute(f"SELECT record FROM {self.table} WHERE run_id = ?", (run_id,)) row = self.cursor.fetchone() return from_json(row[0]) if row else None - def save(self, record: RunRecord) -> None: - values = (str(record.state), str(record.verdict), to_json(record), record.run_id) - # Not INSERT ... ON DUPLICATE KEY UPDATE: InnoDB spends an `id` on every such update. - if self.number(record.run_id) is None: - self.cursor.execute(f"INSERT INTO {self.table} (state, verdict, record, run_id) VALUES (?, ?, ?, ?)", values) - else: - self.cursor.execute(f"UPDATE {self.table} SET state = ?, verdict = ?, record = ? WHERE run_id = ?", values) + @contextmanager + def edit(self, run_id: str): + self.conn.begin() + try: + self.cursor.execute(f"SELECT record FROM {self.table} WHERE run_id = ? FOR UPDATE", (run_id,)) + row = self.cursor.fetchone() + record = from_json(row[0]) if row else RunRecord(run_id) + yield record + values = (str(record.state), str(record.verdict), to_json(record), run_id) + # Not INSERT ... ON DUPLICATE KEY UPDATE: InnoDB spends an `id` on every such update. + if row: + self.cursor.execute(f"UPDATE {self.table} SET state = ?, verdict = ?, record = ? WHERE run_id = ?", values) + else: + self.cursor.execute(f"INSERT INTO {self.table} (state, verdict, record, run_id) VALUES (?, ?, ?, ?)", values) + except BaseException: + self.conn.rollback() + raise + self.conn.commit() def run_ids(self, state: State | None = None) -> list[str]: if state is None: diff --git a/tests/test_mariadb_store.py b/tests/test_mariadb_store.py index cdef51a..a09e65c 100644 --- a/tests/test_mariadb_store.py +++ b/tests/test_mariadb_store.py @@ -1,4 +1,3 @@ -import json import os from datetime import UTC, datetime from uuid import uuid4 @@ -55,32 +54,3 @@ def test_a_queued_run_is_cancelled_by_id(store): assert store.run_ids(State.IN_PROGRESS) == [] Observer(MariaDBStore(db_name=TEST_DATABASE, table=store.table)).log_cancelled_run("queued", datetime.now(UTC)) assert (store.load("queued").state, store.load("queued").verdict) == (State.CANCELED, Verdict.UNAVAILABLE) - - -def test_a_table_from_the_previous_release_is_migrated(store): - table = f"{store.table}_old" - # The table as the previous release created it, and what it recorded of a run. - store.cursor.execute( - f""" - CREATE TABLE {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 - ) - """ - ) - started = datetime(2026, 1, 1, tzinfo=UTC) - store.cursor.execute( - f"INSERT INTO {table} (status, run_info) VALUES ('COMPLETED', ?), ('RUNNING', ?)", - (json.dumps({"start_time": started.isoformat()}), json.dumps({"start_time": started.isoformat()})), - ) - try: - migrated = MariaDBStore(db_name=TEST_DATABASE, table=table) - assert (migrated.load("1").state, migrated.load("1").verdict) == (State.COMPLETE, Verdict.PASSED) - assert migrated.load("1").start_time == started - assert migrated.run_ids(State.IN_PROGRESS) == ["2"] - QuickRun(observers=[Observer(migrated)], run_id="run-new").run() - assert migrated.number("run-new") == 3 - migrated.close() - finally: - store.cursor.execute(f"DROP TABLE IF EXISTS {table}") From f0a1adc15afdb14c75060239535d1822447ecf0d Mon Sep 17 00:00:00 2001 From: Vamsi Kalagaturu Date: Wed, 7 Oct 2026 15:07:44 +0200 Subject: [PATCH 03/16] Match the OSLC spelling when starting a cancelled run - The start refusal names the run's state, canceled, so the test matches "is canceled" --- tests/test_run.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_run.py b/tests/test_run.py index 5410f77..436585e 100644 --- a/tests/test_run.py +++ b/tests/test_run.py @@ -132,7 +132,7 @@ def test_only_a_run_that_has_not_started_is_cancelled(store): queued.queue() # A scheduler holding only the store cancels a run it did not create, and the store decides. Observer(store).log_cancelled_run("run-q", datetime.now(UTC)) - with pytest.raises(RuntimeError, match="cancelled"): + with pytest.raises(RuntimeError, match="is canceled"): queued.run() assert (store.load("run-q").state, store.load("run-q").verdict) == (State.CANCELED, Verdict.UNAVAILABLE) From 16e20af7414019f8356e2ae2d97522f081d4769c Mon Sep 17 00:00:00 2001 From: Vamsi Kalagaturu Date: Wed, 7 Oct 2026 15:20:27 +0200 Subject: [PATCH 04/16] Stop the heartbeat on any exit and drop MariaDBStore.number - The heartbeat stops in a finally around the hooks and main, so SystemExit no longer leaves its non-daemon thread running - MariaDBStore.number had no caller; the id column stays to order runs --- rec/run.py | 13 +++++++------ rec/stores/mariadb_store.py | 8 +------- tests/test_mariadb_store.py | 3 +-- 3 files changed, 9 insertions(+), 15 deletions(-) diff --git a/rec/run.py b/rec/run.py index 2baf5c4..315b405 100644 --- a/rec/run.py +++ b/rec/run.py @@ -195,18 +195,19 @@ def run(self, trigger=None, starter=None): self._emit_started(trigger, starter) try: - self._start_heartbeat() - self._execute_hooks(self.pre_run_hooks) - self.result = self.main() + # Stopped before any outcome is recorded, and on SystemExit too: the thread is not a daemon. + try: + self._start_heartbeat() + self._execute_hooks(self.pre_run_hooks) + self.result = self.main() + finally: + self._stop_heartbeat() logger.info("Result of run %s: %s", self.id, self.result) - self._stop_heartbeat() self._emit_completed() except KeyboardInterrupt as interrupt: - self._stop_heartbeat() self._emit_interrupted(interrupt) return self.result except Exception as error: - self._stop_heartbeat() self._emit_failed(error) return self.result # After completion: a post-run hook that raises is the caller's error, not the run's. diff --git a/rec/stores/mariadb_store.py b/rec/stores/mariadb_store.py index bd5b5ec..966a5f7 100644 --- a/rec/stores/mariadb_store.py +++ b/rec/stores/mariadb_store.py @@ -17,7 +17,7 @@ def __init__(self, db_name: str = "logbook", table: str = "logs"): ``MARIADB_HOST`` and ``MARIADB_PORT`` from the environment or a ``.env`` file :param db_name: Name of the database - :param table: Name of the table, one row per run: ``id`` a short number to display, + :param table: Name of the table, one row per run: ``id`` in the order runs were added, ``run_id``, ``state`` and ``verdict`` to query by, and ``record`` """ load_dotenv() @@ -75,12 +75,6 @@ def run_ids(self, state: State | None = None) -> list[str]: self.cursor.execute(f"SELECT run_id FROM {self.table} WHERE state = ? ORDER BY id", (str(state),)) return [row[0] for row in self.cursor.fetchall()] - def number(self, run_id: str) -> int | None: - """The short number the table gave the run, None for a run it does not hold.""" - self.cursor.execute(f"SELECT id FROM {self.table} WHERE run_id = ?", (run_id,)) - row = self.cursor.fetchone() - return row[0] if row else None - def close(self) -> None: self.cursor.close() self.conn.close() diff --git a/tests/test_mariadb_store.py b/tests/test_mariadb_store.py index a09e65c..5d0beb8 100644 --- a/tests/test_mariadb_store.py +++ b/tests/test_mariadb_store.py @@ -40,9 +40,8 @@ def test_a_row_keeps_the_whole_record(store, tmp_path): for run in runs: run.beat_interval = 0 run.run() - for number, run in enumerate(runs, start=1): + for run in runs: assert store.load(run.id) == files.load(run.id) - assert store.number(run.id) == number # The state and verdict columns are the record's, to query runs by. store.cursor.execute(f"SELECT state, verdict FROM {store.table} WHERE run_id = 'run-0'") assert store.cursor.fetchone() == ("complete", "passed") From 4e9f3e89bcfa0b0d7e680582c7d2f90aa745fca1 Mon Sep 17 00:00:00 2001 From: Vamsi Kalagaturu Date: Wed, 7 Oct 2026 15:34:20 +0200 Subject: [PATCH 05/16] Refuse records and transitions no store can keep - Only a new run can be queued and only a queued run cancelled, so a finished run cannot be queued and run again, and cancelling an unknown id creates nothing - Run queues and cancels only once its stores accept, as it already started - A record with a value JSON cannot keep is refused for every store, so a result or metric no longer passes in one store and fails in another - add_agent accepts only PROV-O's agent classes - MariaDBStore serializes its threads on its one connection; the observer no longer locks --- rec/observer.py | 22 +++++++++++----- rec/run.py | 17 +++++------- rec/stores/mariadb_store.py | 52 +++++++++++++++++++++---------------- tests/test_run.py | 4 +-- 4 files changed, 54 insertions(+), 41 deletions(-) diff --git a/rec/observer.py b/rec/observer.py index bd2c11f..b072025 100644 --- a/rec/observer.py +++ b/rec/observer.py @@ -1,7 +1,6 @@ """Records the events of runs in a store.""" import os -import threading from contextlib import contextmanager from datetime import datetime from pathlib import Path, PurePath @@ -20,9 +19,13 @@ Repository, Software, Usage, + to_json, ) from rec.stores import Store +# PROV-O's agent classes (PROV-O 4.1). +AGENT_TYPES = ("Agent", "SoftwareAgent", "Person", "Organization") + class Observer: """Records the events of any number of runs in one store; every call names its run. @@ -32,16 +35,21 @@ class Observer: def __init__(self, store: Store): self.store = store - # A run's heartbeat thread and the run itself share the store's connection. - self._lock = threading.RLock() @contextmanager def _record(self, run_id: str): - with self._lock, self.store.edit(run_id) as record: + with self.store.edit(run_id) as record: yield record + # Checked for every store, so none keeps a record another could not. + try: + to_json(record) + except TypeError as error: + raise ValueError(f"run '{run_id}' holds a value JSON cannot keep -- {error}") from error def log_queued_run(self, run_id: str, queued_time: datetime): with self._record(run_id) as record: + if record.state is not State.NEW: + raise RuntimeError(f"run '{run_id}' is {record.state} -- only a new run can be queued") record.state, record.verdict, record.queued_time = State.QUEUED, Verdict.UNAVAILABLE, queued_time def log_started_run(self, run_id: str, started_time: datetime, trigger=None, starter=None, program=None): @@ -70,8 +78,8 @@ def log_failed_run(self, run_id: str, failed_time: datetime, fail_trace: str | N def log_cancelled_run(self, run_id: str, cancelled_time: datetime): with self._record(run_id) as record: - if record.state not in (State.NEW, State.QUEUED): - raise RuntimeError(f"run '{run_id}' is {record.state} -- only a run that has not started can be cancelled") + if record.state is not State.QUEUED: + raise RuntimeError(f"run '{run_id}' is {record.state} -- only a queued run can be cancelled") record.state, record.verdict, record.end_time = State.CANCELED, Verdict.UNAVAILABLE, cancelled_time def log_host_info(self, run_id: str, host_info: dict): @@ -99,6 +107,8 @@ def log_scalar(self, run_id: str, metric_name: str, value, step: int | None = No record.metrics = [*kept, Metric(metric_name, step, value, time)] def add_agent(self, run_id: str, agent_id: str, agent_type: str, name: str | None = None): + if agent_type not in AGENT_TYPES: + raise ValueError(f"'{agent_type}' is not a PROV agent type -- use one of {list(AGENT_TYPES)}") with self._record(run_id) as record: record.agents.append(Agent(agent_id, agent_type, name)) diff --git a/rec/run.py b/rec/run.py index 315b405..c2165f1 100644 --- a/rec/run.py +++ b/rec/run.py @@ -97,22 +97,19 @@ def _emit_heartbeat(self): observer.log_run_heartbeat(self.id, beat_time, result=self.result) def _emit_cancelled(self): - self.state, self.verdict = State.CANCELED, Verdict.UNAVAILABLE - cancelled_time = self._stop_time() - logger.info("Cancelled run %s", self.id) - - # Update info on observers + cancelled_time = datetime.datetime.now(datetime.UTC) + # The stores go first, as on start: one of them may refuse. for observer in self.observers: observer.log_cancelled_run(self.id, cancelled_time) + self.state, self.verdict, self.end_time = State.CANCELED, Verdict.UNAVAILABLE, cancelled_time + logger.info("Cancelled run %s", self.id) def _emit_queued(self): - self.state, self.verdict = State.QUEUED, Verdict.UNAVAILABLE queued_time = datetime.datetime.now(datetime.UTC) - logger.info("Queued run %s", self.id) - - # Update info on observers for observer in self.observers: observer.log_queued_run(self.id, queued_time) + self.state, self.verdict = State.QUEUED, Verdict.UNAVAILABLE + logger.info("Queued run %s", self.id) def _emit_started(self, trigger=None, starter=None): """ @@ -265,7 +262,7 @@ def add_agent(self, agent_id: str, agent_type: str, name: str | None = None): """ 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., SoftwareAgent, Person + :param agent_type: A PROV agent class: Agent, SoftwareAgent, Person or Organization :param name: The agent's name; a software agent must have one :return: """ diff --git a/rec/stores/mariadb_store.py b/rec/stores/mariadb_store.py index 966a5f7..5a70fb2 100644 --- a/rec/stores/mariadb_store.py +++ b/rec/stores/mariadb_store.py @@ -1,6 +1,7 @@ """A store keeping each run as one row of a MariaDB table.""" import os +import threading from contextlib import contextmanager import mariadb @@ -32,6 +33,8 @@ def __init__(self, db_name: str = "logbook", table: str = "logs"): ) 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() self.cursor.execute( f""" CREATE TABLE IF NOT EXISTS {table} ( @@ -45,35 +48,38 @@ def __init__(self, db_name: str = "logbook", table: str = "logs"): ) def load(self, run_id: str) -> RunRecord | None: - self.cursor.execute(f"SELECT record FROM {self.table} WHERE run_id = ?", (run_id,)) - row = self.cursor.fetchone() + with self._lock: + self.cursor.execute(f"SELECT record FROM {self.table} WHERE run_id = ?", (run_id,)) + row = self.cursor.fetchone() return from_json(row[0]) if row else None @contextmanager def edit(self, run_id: str): - self.conn.begin() - try: - self.cursor.execute(f"SELECT record FROM {self.table} WHERE run_id = ? FOR UPDATE", (run_id,)) - row = self.cursor.fetchone() - record = from_json(row[0]) if row else RunRecord(run_id) - yield record - values = (str(record.state), str(record.verdict), to_json(record), run_id) - # Not INSERT ... ON DUPLICATE KEY UPDATE: InnoDB spends an `id` on every such update. - if row: - self.cursor.execute(f"UPDATE {self.table} SET state = ?, verdict = ?, record = ? WHERE run_id = ?", values) - else: - self.cursor.execute(f"INSERT INTO {self.table} (state, verdict, record, run_id) VALUES (?, ?, ?, ?)", values) - except BaseException: - self.conn.rollback() - raise - self.conn.commit() + with self._lock: + self.conn.begin() + try: + self.cursor.execute(f"SELECT record FROM {self.table} WHERE run_id = ? FOR UPDATE", (run_id,)) + row = self.cursor.fetchone() + record = from_json(row[0]) if row else RunRecord(run_id) + yield record + values = (str(record.state), str(record.verdict), to_json(record), run_id) + # Not INSERT ... ON DUPLICATE KEY UPDATE: InnoDB spends an `id` on every such update. + if row: + self.cursor.execute(f"UPDATE {self.table} SET state = ?, verdict = ?, record = ? WHERE run_id = ?", values) + else: + self.cursor.execute(f"INSERT INTO {self.table} (state, verdict, record, run_id) VALUES (?, ?, ?, ?)", values) + except BaseException: + self.conn.rollback() + raise + self.conn.commit() def run_ids(self, state: State | None = None) -> list[str]: - if state is None: - self.cursor.execute(f"SELECT run_id FROM {self.table} ORDER BY id") - else: - self.cursor.execute(f"SELECT run_id FROM {self.table} WHERE state = ? ORDER BY id", (str(state),)) - return [row[0] for row in self.cursor.fetchall()] + with self._lock: + if state is None: + self.cursor.execute(f"SELECT run_id FROM {self.table} ORDER BY id") + else: + self.cursor.execute(f"SELECT run_id FROM {self.table} WHERE state = ? ORDER BY id", (str(state),)) + return [row[0] for row in self.cursor.fetchall()] def close(self) -> None: self.cursor.close() diff --git a/tests/test_run.py b/tests/test_run.py index 436585e..dfbdd5f 100644 --- a/tests/test_run.py +++ b/tests/test_run.py @@ -127,7 +127,7 @@ def broken_hook(): assert (store.load("run-h").state, store.load("run-h").verdict) == (State.COMPLETE, Verdict.PASSED) -def test_only_a_run_that_has_not_started_is_cancelled(store): +def test_only_a_queued_run_is_cancelled(store): queued = CalibrationRun(observers=[Observer(store)], run_id="run-q") queued.queue() # A scheduler holding only the store cancels a run it did not create, and the store decides. @@ -139,7 +139,7 @@ def test_only_a_run_that_has_not_started_is_cancelled(store): done = CalibrationRun(observers=[Observer(store)], run_id="run-d") done.beat_interval = 0 done.run() - with pytest.raises(RuntimeError, match="has not started"): + with pytest.raises(RuntimeError, match="only a queued run"): Observer(store).log_cancelled_run("run-d", datetime.now(UTC)) assert store.load("run-d").verdict is Verdict.PASSED assert store.run_ids(State.CANCELED) == ["run-q"] From f33a61a4b1637a18fc6508e11b53fcc6ab23427b Mon Sep 17 00:00:00 2001 From: Vamsi Kalagaturu Date: Wed, 7 Oct 2026 17:55:26 +0200 Subject: [PATCH 06/16] Keep one record in every store and every lifecycle change whole - Queueing, starting, cancelling and ending hold every store's record at once, so a refusal by one store leaves all unchanged; observers sharing a store are refused - Ending a run and its heartbeat require it in progress - The observer keeps lists in one order and refuses a change JSON or PROV would not give back unchanged: lossy JSON values, NaN, empty strings, an entity logged twice - A file is generated once per run (PROV-Constraints generation-uniqueness) - provenance.record reads only the requested run, and a file's IRI includes its root - The heartbeat is a daemon thread, so one stuck on a store cannot keep the process alive - FileStore.save is private to edit - README states the multi-store limits: no two-phase commit, and opposite store orders can deadlock --- README.md | 6 ++++ rec/observer.py | 51 +++++++++++++++++++++++++++---- rec/provenance.py | 38 +++++++++++++++-------- rec/record.py | 14 +++++++-- rec/run.py | 65 +++++++++++++++++++++++----------------- rec/stores/file_store.py | 4 +-- 6 files changed, 128 insertions(+), 50 deletions(-) diff --git a/README.md b/README.md index a54880e..d89caea 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,12 @@ about, and whoever created the observer closes it once its runs are over. What i the block ends; no other edit of that run, from any process, may interleave, so a cancellation and a start cannot both succeed. `FileStore` locks with `flock` (POSIX), `MariaDBStore` with `SELECT ... FOR UPDATE`. +- A run with several observers, each with its own store, queues, starts, cancels and ends holding + every store's record at once: a store that refuses leaves all of them unchanged. Saving is not + a two-phase commit, so a store failing to save can still leave them split. Two runs of the same + id whose observers list the same stores in different orders can wait on each other forever. +- Every store keeps the same record: an observer refuses a change JSON or PROV would not give back + unchanged, such as a tuple, NaN, an empty string, or one file used twice by the same activity. ### Creating a run diff --git a/rec/observer.py b/rec/observer.py index b072025..e61e0b7 100644 --- a/rec/observer.py +++ b/rec/observer.py @@ -1,6 +1,7 @@ """Records the events of runs in a store.""" import os +import threading from contextlib import contextmanager from datetime import datetime from pathlib import Path, PurePath @@ -8,8 +9,9 @@ from rdf_utils.models.prov import get_pkg_info -from rec import State, Verdict +from rec import State, Verdict, provenance from rec.record import ( + ORDER, Agent, Dependency, FileRef, @@ -19,6 +21,7 @@ Repository, Software, Usage, + from_json, to_json, ) from rec.stores import Store @@ -35,16 +38,44 @@ class Observer: def __init__(self, store: Store): self.store = store + # Per thread: a heartbeat must wait for the store, not join another thread's held record. + self._held = threading.local() + + @contextmanager + def _hold(self, run_id: str): + """Keep the run's record open: the calls made meanwhile are kept together when the block ends, or none is.""" + with self._record(run_id) as record: + outer = getattr(self._held, "record", None) + self._held.record = record + try: + yield + finally: + self._held.record = outer @contextmanager def _record(self, run_id: str): + held = getattr(self._held, "record", None) + if held is not None and held.run_id == run_id: + yield held + return with self.store.edit(run_id) as record: yield record - # Checked for every store, so none keeps a record another could not. + for name, key in ORDER.items(): + getattr(record, name).sort(key=key) + # Checked for every store, so none keeps a record another would change or could not keep. try: - to_json(record) - except TypeError as error: + kept = from_json(to_json(record)) + except (TypeError, ValueError) as error: raise ValueError(f"run '{run_id}' holds a value JSON cannot keep -- {error}") from error + if kept != record: + raise ValueError(f"run '{run_id}' holds a value JSON would change -- e.g. a non-string key or a tuple") + as_prov = provenance.record(provenance.graph(record), run_id) + changed = [name for name in vars(record) if getattr(as_prov, name) != getattr(record, name)] + if changed: + raise ValueError( + f"run '{run_id}' would read back from PROV with other {changed} -- " + "e.g. an empty string, or one file, agent, repository or dependency logged twice" + ) def log_queued_run(self, run_id: str, queued_time: datetime): with self._record(run_id) as record: @@ -63,6 +94,8 @@ def log_started_run(self, run_id: str, started_time: datetime, trigger=None, sta def log_run_heartbeat(self, run_id: str, beat_time: datetime, result=None): with self._record(run_id) as record: + if record.state is not State.IN_PROGRESS: + raise RuntimeError(f"run '{run_id}' is {record.state} -- only a run in progress beats") record.heartbeat_time = beat_time if result is not None: record.result = result @@ -109,6 +142,8 @@ def log_scalar(self, run_id: str, metric_name: str, value, step: int | None = No def add_agent(self, run_id: str, agent_id: str, agent_type: str, name: str | None = None): if agent_type not in AGENT_TYPES: raise ValueError(f"'{agent_type}' is not a PROV agent type -- use one of {list(AGENT_TYPES)}") + if agent_type == "SoftwareAgent" and not name: + raise ValueError(f"'{agent_id}' is a software agent without a name -- the prov-extension shapes require one") with self._record(run_id) as record: record.agents.append(Agent(agent_id, agent_type, name)) @@ -117,14 +152,20 @@ def add_resource(self, run_id: str, filename, usage_activity=None, usage_time=No record.resources.append(Usage(file_ref(filename, title, sha256, size_bytes), usage_activity, usage_time)) def add_artefact(self, run_id: str, filename, gen_activity=None, generated_time=None, title=None, sha256=None, size_bytes=None): + ref = file_ref(filename, title, sha256, size_bytes) with self._record(run_id) as record: - record.artefacts.append(Generation(file_ref(filename, title, sha256, size_bytes), gen_activity, generated_time)) + # PROV-Constraints, generation-uniqueness: an entity has at most one generation. + if any((row.file.path, row.file.root) == (ref.path, ref.root) for row in record.artefacts): + raise ValueError(f"'{ref.path}' is already an artefact of run '{run_id}' -- a file is generated once") + record.artefacts.append(Generation(ref, gen_activity, generated_time)) def close(self): self.store.close() def _end(self, run_id, end_time, verdict, result=None, fail_trace=None): with self._record(run_id) as record: + if record.state is not State.IN_PROGRESS: + raise RuntimeError(f"run '{run_id}' is {record.state} -- only a run in progress can end") record.state, record.verdict, record.end_time = State.COMPLETE, verdict, end_time if result is not None: record.result = result diff --git a/rec/provenance.py b/rec/provenance.py index f14f33d..8219b35 100644 --- a/rec/provenance.py +++ b/rec/provenance.py @@ -17,6 +17,7 @@ from rec import State, Verdict from rec.record import ( + ORDER, Agent, Dependency, FileRef, @@ -111,7 +112,7 @@ def graph(record: RunRecord, base: str = RUN_BASE) -> Graph: for usage in record.resources: entity = _file(g, run, usage.file) activity = URIRef(usage.activity or run) - node = URIRef(f"{run}/usage/{quote(str(activity), safe='')}/{quote(usage.file.path, safe='')}") + node = URIRef(f"{entity}/usage/{quote(str(activity), safe='')}") g.add((node, RDF.type, PROV.Usage)) g.add((node, PROV.entity, entity)) if usage.time: @@ -162,7 +163,7 @@ def graph(record: RunRecord, base: str = RUN_BASE) -> Graph: for generation in record.artefacts: entity = _file(g, run, generation.file) activity = URIRef(generation.activity or run) - node = URIRef(f"{run}/generation/{quote(str(activity), safe='')}/{quote(generation.file.path, safe='')}") + node = URIRef(f"{entity}/generation/{quote(str(activity), safe='')}") g.add((activity, RDF.type, PROV.Activity)) g.add((entity, PROV.wasGeneratedBy, activity)) g.add((entity, PROV.qualifiedGeneration, node)) @@ -195,6 +196,8 @@ def record(g: Graph, run_id: str, base: str = RUN_BASE) -> RunRecord: result = g.value(run, REC.result) run_usages = {g.value(usage, PROV.entity) for usage in g.objects(run, PROV.qualifiedUsage)} kinds = {SDO.SoftwareSourceCode, SDO.SoftwareApplication} + # Only what links to this run, or what graph() named under its IRI: the graph may hold other runs. + own = f"{run}/" return RunRecord( run_id=run_id, state=next(state for state, iri in STATES.items() if iri == g.value(run, OSLC_AUTO.state)), @@ -227,7 +230,7 @@ def record(g: Graph, run_id: str, base: str = RUN_BASE) -> RunRecord: for agent in g.objects(run, PROV.wasAssociatedWith) if agent != software ), - key=lambda agent: agent.id, + key=ORDER["agents"], ), sources=sorted( ( @@ -235,21 +238,23 @@ def record(g: Graph, run_id: str, base: str = RUN_BASE) -> RunRecord: for entity in g.objects(run, PROV.used) if entity != plan and entity not in run_usages and not set(g.objects(entity, RDF.type)) & kinds ), - key=lambda ref: ref.path, + key=ORDER["sources"], ), repositories=sorted( ( Repository(str(g.value(node, RDFS.label)), _python(g.value(node, SDO.codeRepository)), _python(g.value(node, SDO.identifier))) - for node in g.subjects(RDF.type, SDO.SoftwareSourceCode) + for node in g.objects(run, PROV.used) + if (node, RDF.type, SDO.SoftwareSourceCode) in g ), - key=lambda row: row.name, + key=ORDER["repositories"], ), dependencies=sorted( ( Dependency(str(g.value(node, RDFS.label)), _python(g.value(node, SDO.softwareVersion))) - for node in g.subjects(RDF.type, SDO.SoftwareApplication) + for node in g.objects(run, PROV.used) + if (node, RDF.type, SDO.SoftwareApplication) in g ), - key=lambda row: row.name, + key=ORDER["dependencies"], ), resources=sorted( ( @@ -259,8 +264,9 @@ def record(g: Graph, run_id: str, base: str = RUN_BASE) -> RunRecord: _python(g.value(usage, PROV.atTime)), ) for activity, usage in g.subject_objects(PROV.qualifiedUsage) + if usage.startswith(own) ), - key=lambda row: (row.activity or "", row.file.path), + key=ORDER["resources"], ), artefacts=sorted( ( @@ -270,8 +276,9 @@ def record(g: Graph, run_id: str, base: str = RUN_BASE) -> RunRecord: _python(g.value(node, PROV.atTime)), ) for entity, node in g.subject_objects(PROV.qualifiedGeneration) + if node.startswith(own) ), - key=lambda row: (row.activity or "", row.file.path), + key=ORDER["artefacts"], ), metrics=sorted( ( @@ -281,9 +288,10 @@ def record(g: Graph, run_id: str, base: str = RUN_BASE) -> RunRecord: g.value(node, QUDT.value).toPython(), _python(g.value(node, PROV.generatedAtTime)), ) - for node in g.subjects(RDF.type, REC.Metric) + for node in g.subjects(PROV.wasGeneratedBy, run) + if (node, RDF.type, REC.Metric) in g ), - key=lambda row: (row.name, row.step), + key=ORDER["metrics"], ), ) @@ -294,7 +302,11 @@ def document(g: Graph) -> dict: def _file(g: Graph, run: URIRef, ref: FileRef) -> URIRef: - entity = URIRef(f"{run}/file/{quote(ref.path, safe='')}") + # The root is part of the name: one relative path logged from two directories is two files. + if ref.root: + entity = URIRef(f"{run}/file/{quote(ref.root, safe='')}/{quote(ref.path, safe='')}") + else: + entity = URIRef(f"{run}/file/{quote(ref.path, safe='')}") if ref.root: location = URIRef(f"{entity}/location") add_relative_location(g, location, ref.path, ref.root) diff --git a/rec/record.py b/rec/record.py index 538c18b..bb2cd07 100644 --- a/rec/record.py +++ b/rec/record.py @@ -8,6 +8,16 @@ from rec import State, Verdict TIMES = ("queued_time", "start_time", "end_time", "heartbeat_time") +# The order a record keeps its lists in, the one a PROV graph, having none, reads them back in. +ORDER = { + "agents": lambda agent: agent.id, + "sources": lambda ref: (ref.path, ref.root or ""), + "repositories": lambda row: row.name, + "dependencies": lambda row: row.name, + "resources": lambda row: (row.activity or "", row.file.path, row.file.root or ""), + "artefacts": lambda row: (row.activity or "", row.file.path, row.file.root or ""), + "metrics": lambda row: (row.name, row.step), +} @dataclass @@ -111,8 +121,8 @@ class RunRecord: def to_json(record: RunRecord) -> str: - """The record as JSON, its times in ISO 8601.""" - return json.dumps(asdict(record), default=datetime.isoformat, indent=2) + """The record as JSON (RFC 8259, so no NaN or infinity), its times in ISO 8601.""" + return json.dumps(asdict(record), default=datetime.isoformat, allow_nan=False, indent=2) def from_json(text: str) -> RunRecord: diff --git a/rec/run.py b/rec/run.py index c2165f1..72b8807 100644 --- a/rec/run.py +++ b/rec/run.py @@ -6,6 +6,7 @@ import threading import traceback from collections.abc import Sequence +from contextlib import ExitStack, contextmanager from uuid import uuid4 from rec import State, Verdict @@ -22,7 +23,8 @@ def create(cls, func, interval=10): return stop_event, timer_thread def __init__(self, event, func, interval=10.0): - super().__init__() + # A daemon: a beat stuck on a store must not keep the process alive once the run is over. + super().__init__(daemon=True) self.stopped = event self.func = func self.interval = interval @@ -53,6 +55,9 @@ def __init__( ): self._id = run_id self.observers = list(observers) + # A start holds every store's record at once; a store held twice would wait on itself. + if len({id(observer.store) for observer in self.observers}) < len(self.observers): + raise ValueError("'observers' share a store -- give each its own store") self.start_time = None self.end_time = None self.state = None @@ -71,9 +76,13 @@ def id(self): self._id = str(uuid4()) return self._id - def _stop_time(self): - self.end_time = datetime.datetime.now(datetime.UTC) - return self.end_time + @contextmanager + def _held(self): + """Every store's record open at once: one refusal leaves them all unchanged; a failed save can still split them.""" + with ExitStack() as held: + for observer in self.observers: + held.enter_context(observer._hold(self.id)) + yield def _start_heartbeat(self): if self.beat_interval > 0: @@ -99,15 +108,17 @@ def _emit_heartbeat(self): def _emit_cancelled(self): cancelled_time = datetime.datetime.now(datetime.UTC) # The stores go first, as on start: one of them may refuse. - for observer in self.observers: - observer.log_cancelled_run(self.id, cancelled_time) + with self._held(): + for observer in self.observers: + observer.log_cancelled_run(self.id, cancelled_time) self.state, self.verdict, self.end_time = State.CANCELED, Verdict.UNAVAILABLE, cancelled_time logger.info("Cancelled run %s", self.id) def _emit_queued(self): queued_time = datetime.datetime.now(datetime.UTC) - for observer in self.observers: - observer.log_queued_run(self.id, queued_time) + with self._held(): + for observer in self.observers: + observer.log_queued_run(self.id, queued_time) self.state, self.verdict = State.QUEUED, Verdict.UNAVAILABLE logger.info("Queued run %s", self.id) @@ -127,39 +138,37 @@ def _emit_started(self, trigger=None, starter=None): # A class typed into an interpreter has no file to name. program = None # The stores go first: one of them may hold a cancellation this object never saw. - for observer in self.observers: - observer.log_started_run(self.id, start_time, trigger=trigger, starter=starter, program=program) + with self._held(): + for observer in self.observers: + observer.log_started_run(self.id, start_time, trigger=trigger, starter=starter, program=program) self.state, self.verdict = State.IN_PROGRESS, Verdict.UNAVAILABLE self.start_time = start_time self.log_host_info(host_info()) def _emit_completed(self): - self.state, self.verdict = State.COMPLETE, Verdict.PASSED - completed_time = self._stop_time() + completed_time = datetime.datetime.now(datetime.UTC) + with self._held(): + for observer in self.observers: + observer.log_completed_run(self.id, completed_time, self.result) + self.state, self.verdict, self.end_time = State.COMPLETE, Verdict.PASSED, completed_time logger.info("Completed run %s after %s", self.id, completed_time - self.start_time) - # Update info on observers - for observer in self.observers: - observer.log_completed_run(self.id, completed_time, self.result) - def _emit_interrupted(self, error=None): - self.state, self.verdict = State.COMPLETE, Verdict.ERROR - interrupted_time = self._stop_time() + interrupted_time = datetime.datetime.now(datetime.UTC) + with self._held(): + for observer in self.observers: + observer.log_interrupted_run(self.id, interrupted_time, _fail_trace(error)) + self.state, self.verdict, self.end_time = State.COMPLETE, Verdict.ERROR, interrupted_time logger.warning("Interrupted run %s after %s", self.id, interrupted_time - self.start_time) - # Update info on observers - for observer in self.observers: - observer.log_interrupted_run(self.id, interrupted_time, _fail_trace(error)) - def _emit_failed(self, error=None): - self.state, self.verdict = State.COMPLETE, Verdict.FAILED - failed_time = self._stop_time() + failed_time = datetime.datetime.now(datetime.UTC) + with self._held(): + for observer in self.observers: + observer.log_failed_run(self.id, failed_time, _fail_trace(error)) + self.state, self.verdict, self.end_time = State.COMPLETE, Verdict.FAILED, failed_time logger.error("Failed run %s after %s", self.id, failed_time - self.start_time, exc_info=error) - # Update info on observers - for observer in self.observers: - observer.log_failed_run(self.id, failed_time, _fail_trace(error)) - def _execute_hooks(self, hooks): for hook in hooks: hook() diff --git a/rec/stores/file_store.py b/rec/stores/file_store.py index 3543e4a..8a3a0e8 100644 --- a/rec/stores/file_store.py +++ b/rec/stores/file_store.py @@ -49,9 +49,9 @@ def edit(self, run_id: str): fcntl.flock(lock, fcntl.LOCK_EX) record = self.load(run_id) or RunRecord(run_id) yield record - self.save(record) + self._save(record) - def save(self, record: RunRecord) -> None: + def _save(self, record: RunRecord) -> None: if self.fmt == "json": text = to_json(record) else: From 16a470646e81d2eb6cc343cb72be2191c91ff688 Mon Sep 17 00:00:00 2001 From: Vamsi Kalagaturu Date: Mon, 12 Oct 2026 16:38:30 +0200 Subject: [PATCH 07/16] Type every run an execution and an OSLC Automation result - graph() types a run prov-ext:Execution and oslc_auto:AutomationResult whatever its state; a started run adds its start time and association - A queued or cancelled run conforms with no start time, association or usage - The shapes refuse a run without a verdict, a queued run with a start time, and a run that is not an execution or not an automation result - README describes the run's types --- README.md | 10 +++++----- rec/provenance.py | 7 ++++--- tests/test_run.py | 37 +++++++++++++++++++++++++++++++++++-- 3 files changed, 44 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index d89caea..5c3b398 100644 --- a/README.md +++ b/README.md @@ -53,11 +53,11 @@ python examples/decentral_run.py `rec.provenance.graph(record)` is the run in PROV on the [rec and prov-extension vocabularies](https://secorolab.github.io/metamodels/), built with the -rdf-utils PROV helpers, and `rec.provenance.record(graph, run_id)` reads it back. Its lifecycle is -an OSLC Automation state and verdict (`rec.State` and `rec.Verdict`: a run is `queued`, -`in-progress`, `canceled` or `complete`, and once complete `passed`, `failed` or `error`; a -verdict is `unavailable` before that). A run that has not started is a `prov:Activity`; once -started it is a `prov-ext:Execution` associated with rec, whose plan is the file defining the run. +rdf-utils PROV helpers, and `rec.provenance.record(graph, run_id)` reads it back. A run is a +`prov-ext:Execution` and an `oslc_auto:AutomationResult`, its lifecycle an OSLC Automation state and +verdict (`rec.State` and `rec.Verdict`: a run is `queued`, `in-progress`, `canceled` or `complete`, +and once complete `passed`, `failed` or `error`; a verdict is `unavailable` before that). Once +started it has a start time and is associated with rec, whose plan is the file defining the run. Its host is a `rec:Host`; sources, resources, repositories and dependencies are entities it `prov:used`; artefacts are what it generated, with checksum and size; scalars are `rec:Metric` quantities; a list or mapping result is an `rdf:JSON` literal. A relative file path is recorded diff --git a/rec/provenance.py b/rec/provenance.py index 8219b35..e43f795 100644 --- a/rec/provenance.py +++ b/rec/provenance.py @@ -70,13 +70,14 @@ def graph(record: RunRecord, base: str = RUN_BASE) -> Graph: - """The run as a `prov:Activity` with its OSLC state; once started, a `prov-ext:Execution` - of its program by the software that recorded it.""" + """The run as a `prov-ext:Execution` and an `oslc_auto:AutomationResult` with its state and verdict; + once started, of its program by the software that recorded it.""" g = Graph() for prefix, namespace in PREFIXES.items(): g.bind(prefix, namespace) run = URIRef(base + quote(record.run_id, safe="")) - g.add((run, RDF.type, PROV.Activity)) + g.add((run, RDF.type, PROV_EXT.Execution)) + g.add((run, RDF.type, OSLC_AUTO.AutomationResult)) g.add((run, OSLC_AUTO.state, STATES[record.state])) g.add((run, OSLC_AUTO.verdict, VERDICTS[record.verdict])) for value, predicate in ((record.queued_time, REC["queued-time"]), (record.heartbeat_time, REC["heartbeat-time"])): diff --git a/tests/test_run.py b/tests/test_run.py index dfbdd5f..a3c1afe 100644 --- a/tests/test_run.py +++ b/tests/test_run.py @@ -11,7 +11,7 @@ from rec import State, Verdict, provenance from rec.observer import Observer -from rec.provenance import PROV_EXT, REC +from rec.provenance import OSLC_AUTO, PROV_EXT, REC from rec.run import Run from rec.stores.file_store import FileStore @@ -97,10 +97,39 @@ def test_a_queued_run_has_not_executed_yet(store): ok, _, report = validate(g, shacl_graph=SHAPES, inference="rdfs") assert ok, report node = URIRef(provenance.RUN_BASE + "run-q") - assert (node, RDF.type, PROV.Activity) in g and (node, RDF.type, PROV_EXT.Execution) not in g + assert {PROV_EXT.Execution, OSLC_AUTO.AutomationResult} <= set(g.objects(node, RDF.type)) + assert g.value(node, PROV.startedAtTime) is None and g.value(node, PROV.wasAssociatedWith) is None assert g.value(node, PROV.used) is None and g.value(node, REC["queued-time"]) is not None +# Each starts from a completed run and breaks one rule of the run's shape. +@pytest.mark.parametrize( + ("removed", "added"), + [ + ([(OSLC_AUTO.verdict, None)], []), + ( + [(OSLC_AUTO.state, None), (OSLC_AUTO.verdict, None)], + [(OSLC_AUTO.state, OSLC_AUTO.queued), (OSLC_AUTO.verdict, OSLC_AUTO.unavailable)], + ), + ([(RDF.type, PROV_EXT.Execution)], []), + ([(RDF.type, OSLC_AUTO.AutomationResult)], []), + ], + ids=["without a verdict", "queued with a start time", "not an execution", "not an automation result"], +) +def test_the_shapes_refuse_a_run_that_contradicts_its_state(store, tmp_path, monkeypatch, removed, added): + monkeypatch.chdir(tmp_path) + run = CalibrationRun(observers=[Observer(store)], run_id="run-x") + run.beat_interval = 0 + run.run() + g = provenance.graph(store.load("run-x")) + node = URIRef(provenance.RUN_BASE + "run-x") + for predicate, value in removed: + g.remove((node, predicate, value)) + for predicate, value in added: + g.add((node, predicate, value)) + assert not validate(g, shacl_graph=SHAPES, inference="rdfs")[0] + + @pytest.mark.parametrize( ("cls", "verdict", "trace"), [(FailingRun, Verdict.FAILED, "ValueError: no gripper attached"), (InterruptedRun, Verdict.ERROR, "KeyboardInterrupt")], @@ -135,6 +164,10 @@ def test_only_a_queued_run_is_cancelled(store): with pytest.raises(RuntimeError, match="is canceled"): queued.run() assert (store.load("run-q").state, store.load("run-q").verdict) == (State.CANCELED, Verdict.UNAVAILABLE) + g = provenance.graph(store.load("run-q")) + ok, _, report = validate(g, shacl_graph=SHAPES, inference="rdfs") + assert ok, report + assert g.value(URIRef(provenance.RUN_BASE + "run-q"), PROV.startedAtTime) is None done = CalibrationRun(observers=[Observer(store)], run_id="run-d") done.beat_interval = 0 From 816d61ffe570fe4365dac486e692f30d6b9fb548 Mon Sep 17 00:00:00 2001 From: Vamsi Kalagaturu Date: Thu, 15 Oct 2026 16:57:53 +0200 Subject: [PATCH 08/16] Keep each run's state in its store and record its steps - MariaDBStore keeps a run as a row of _runs and a row per list item, from rec/stores/mariadb.sql, instead of a JSON blob - Run reads state and verdict from the store; a Run with a stored run_id goes on from there and the store decides each step - cancel() ends a queued run as canceled; a run in progress becomes canceling and ends as canceled once main returns - Keep what main returned as rec:result - Add run steps: add_activity records a prov-extension activity dcterms:isPartOf the run; a resource or artefact may only name a step of its run - Compare stores by PROV graph isomorphism and drop the sorting of record lists - Remove log_sources, info(), the pre/post run hooks, Scenario, Feature and the decentralized example - Build with hatchling and take the version from git tags - Fix reading agents back from MariaDB, whose id column was dropped - Add file, MariaDB and all-stores examples; rewrite the README around snippets - Test cancelling a run in progress, run steps, and files of unknown steps --- README.md | 203 ++++++++++++++++++++++++-------- examples/all_stores_run.py | 38 ++++++ examples/decentral_run.py | 19 --- examples/file_store_run.py | 32 +++++ examples/mariadb_store_run.py | 43 +++++++ pyproject.toml | 16 ++- rec/feature.py | 17 --- rec/observer.py | 205 +++++++++++++++++--------------- rec/provenance.py | 186 ++++++++++++++--------------- rec/record.py | 76 +++++++++--- rec/run.py | 213 +++++++++++++--------------------- rec/scenario.py | 18 --- rec/stores/__init__.py | 46 +++++++- rec/stores/file_store.py | 18 ++- rec/stores/mariadb.sql | 101 ++++++++++++++++ rec/stores/mariadb_store.py | 189 ++++++++++++++++++++++++------ tests/test_mariadb_store.py | 38 ++++-- tests/test_run.py | 120 +++++++++++++++---- 18 files changed, 1052 insertions(+), 526 deletions(-) create mode 100644 examples/all_stores_run.py delete mode 100644 examples/decentral_run.py create mode 100644 examples/file_store_run.py create mode 100644 examples/mariadb_store_run.py delete mode 100644 rec/feature.py delete mode 100644 rec/scenario.py create mode 100644 rec/stores/mariadb.sql diff --git a/README.md b/README.md index 5c3b398..16e37a8 100644 --- a/README.md +++ b/README.md @@ -1,73 +1,175 @@ # 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 provenance in [PROV](https://www.w3.org/TR/prov-o/), on the +[rec and prov-extension vocabularies](https://secorolab.github.io/metamodels/). ## 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 ``` -Add the MariaDB backend when runs are stored in a database: +## Recording a run -```shell -pip install -e ".[mariadb]" +A run is a `Run` subclass; `main` does the work and logs what it uses and generates. + +```python +from rec.observer import Observer +from rec.run import Run +from rec.stores.file_store import FileStore + + +class PickPlaceRun(Run): + def main(self): + self.add_agent("https://example.org/agent/arm", "Agent", name="arm") + self.log_repositories([{"name": "controller", "url": "https://example.org/lab/controller", "commit": "0123abcd"}]) + self.add_resource("config/robot.yaml") + self.add_artefact("results/trajectory.csv") + self.log_scalar("final-position-error", 0.004) + return "placed" + + +observer = Observer(FileStore("runs/prov")) +PickPlaceRun(observers=[observer], run_id="pick-place-1").run() +observer.close() ``` -## Examples +`run()` records the start, runs `main`, and ends the run as `passed`, `failed` (`main` raised) or +`error` (interrupted). What `main` returns is kept as the run's result. -### Observers and stores +### Steps of a run -An `Observer` records the events of any number of runs in a store; every call names the run it is -about, and whoever created the observer closes it once its runs are over. What it records is a -`rec.record.RunRecord`, the same whatever the store: +A step is an activity of a prov-extension kind (`Execution`, `Assurance`, `Transformation`, +`Generalization`, `Specification`) that is `dcterms:isPartOf` the run. Files name the step that +used or generated them: -- `FileStore(directory, fmt="rdf")` keeps each run as its PROV document, `.ld.json`; - `fmt="json"` keeps the record itself as `.json`. -- `MariaDBStore(db_name, table)` keeps one row per run: the record, with `state` and `verdict` - columns to query runs by. -- Any object with `load(run_id)`, `edit(run_id)`, `run_ids(state=None)` and `close()` is a store - (`rec.stores.Store`). `edit` is a context manager yielding the run's record and keeping it when - the block ends; no other edit of that run, from any process, may interleave, so a cancellation - and a start cannot both succeed. `FileStore` locks with `flock` (POSIX), `MariaDBStore` with - `SELECT ... FOR UPDATE`. -- A run with several observers, each with its own store, queues, starts, cancels and ends holding - every store's record at once: a store that refuses leaves all of them unchanged. Saving is not - a two-phase commit, so a store failing to save can still leave them split. Two runs of the same - id whose observers list the same stores in different orders can wait on each other forever. -- Every store keeps the same record: an observer refuses a change JSON or PROV would not give back - unchanged, such as a tuple, NaN, an empty string, or one file used twice by the same activity. +```python +calibration = "https://example.org/calibration/1" +self.add_activity(calibration, "Execution", "https://example.org/agent/arm", start, end) +self.add_resource("config/robot.yaml", usage_activity=calibration) +self.add_artefact("results/calibration.json", gen_activity=calibration) +``` -### Creating a run +### Queueing and cancelling -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: +State lives in the store, so any `Run` with the same id sees and changes the same run: -```shell -python examples/decentral_run.py +```python +DrawerRun(observers=[observer], run_id="drawer-2").queue() + +# elsewhere, e.g. a scheduler with its own connection +Run(observers=[Observer(MariaDBStore())], run_id="drawer-2").cancel() +``` + +| State when cancelled | Result | +|---|---| +| `queued` | `canceled` | +| `in-progress` | `canceling`; `main` sees `self.state is State.CANCELING`, returns, and the run ends `canceled` | +| anything else | `RuntimeError` | + +The store decides every step under a lock (`flock` for files, `SELECT ... FOR UPDATE` for +MariaDB): only a new run is queued, only a new or queued run starts. + +## Stores + +| Store | Keeps a run as | +|---|---| +| `FileStore(dir)` | its PROV document, `.ld.json` | +| `FileStore(dir, fmt="json")` | the `RunRecord` as `.json` | +| `MariaDBStore(db_name, prefix)` | a row of `_runs` and a row per list item, see [mariadb.sql](rec/stores/mariadb.sql) | + +All keep the same record. A run may have several observers, one store each: + +```python +stores = [FileStore("runs/prov"), FileStore("runs/json", fmt="json"), MariaDBStore()] +run = ScrewingRun(observers=[Observer(store) for store in stores], run_id="screw-1") +run.run() + +graphs = [provenance.graph(store.load("screw-1")) for store in stores] +assert all(isomorphic(graphs[0], graph) for graph in graphs) ``` -### What a run records +### One artefact in each store -`rec.provenance.graph(record)` is the run in PROV on the -[rec and prov-extension vocabularies](https://secorolab.github.io/metamodels/), built with the -rdf-utils PROV helpers, and `rec.provenance.record(graph, run_id)` reads it back. A run is a -`prov-ext:Execution` and an `oslc_auto:AutomationResult`, its lifecycle an OSLC Automation state and -verdict (`rec.State` and `rec.Verdict`: a run is `queued`, `in-progress`, `canceled` or `complete`, -and once complete `passed`, `failed` or `error`; a verdict is `unavailable` before that). Once -started it has a start time and is associated with rec, whose plan is the file defining the run. -Its host is a `rec:Host`; sources, resources, repositories and dependencies are entities it -`prov:used`; artefacts are what it generated, with checksum and size; scalars are `rec:Metric` -quantities; a list or mapping result is an `rdf:JSON` literal. A relative file path is recorded -relative to the directory it was logged from. The run node is -`https://secoro.uni-bremen.de/rec/run/`, the id percent-encoded, unless another `base` is -given. +```python +self.add_artefact("results/trajectory.csv", sha256="9f86d0...0a08", size_bytes=2048) # logged from /home/lab +``` + +`FileStore(dir)`, `.ld.json` (shown as Turtle; `run:` is `https://secoro.uni-bremen.de/rec/run/`): + +```turtle + + a prov:Entity ; + prov:atLocation [ a prov-ext:RelativeLocation ; + prov-ext:rel-path "results/trajectory.csv"^^xsd:anyURI ; + prov:atLocation ] ; + prov:wasGeneratedBy run:pick-place-1 ; + prov:qualifiedGeneration [ a prov:Generation ; + prov:activity run:pick-place-1 ; + prov:atTime "2026-10-15T09:30:00+00:00"^^xsd:dateTime ] ; + spdx:checksum [ a spdx:Checksum ; + spdx:algorithm spdx:checksumAlgorithm_sha256 ; + spdx:checksumValue "9f86d0...0a08"^^xsd:hexBinary ] ; + dcat:byteSize "2048"^^xsd:nonNegativeInteger . +``` + +`FileStore(dir, fmt="json")`, `.json`: + +```json +"artefacts": [ + { + "file": {"path": "results/trajectory.csv", "root": "/home/lab", "title": null, + "sha256": "9f86d0...0a08", "size_bytes": 2048}, + "activity": null, + "time": "2026-10-15T09:30:00+00:00" + } +] +``` + +`MariaDBStore()`, a row of `logs_artefacts` (`run` is the run's `id` in `logs_runs`; `activity` is +`''` for the run itself): + +| run | path | root | title | sha256 | size_bytes | activity | time | +|---|---|---|---|---|---|---|---| +| 1 | results/trajectory.csv | /home/lab | NULL | 9f86d0...0a08 | 2048 | | 2026-10-15 09:30:00.000000 | + +A value one store could not give back is refused when logged: a NaN or infinite metric, or an +item logged twice (`rec.record.KEYS`). Any object with `load`, `edit`, `run_ids` and `close` is a +store (`rec.stores.Store`). + +## The PROV graph + +```python +from rec import provenance -## Connecting to MariaDB +g = provenance.graph(store.load("pick-place-1")) # RunRecord -> rdflib Graph +record = provenance.record(g, "pick-place-1") # and back +``` + +```turtle + + a prov-ext:Execution, oslc_auto:AutomationResult ; + oslc_auto:state oslc_auto:complete ; + oslc_auto:verdict oslc_auto:passed ; + prov:used <.../repository/controller>, ... ; + prov:wasAssociatedWith ; + rec:result "placed" . +``` + +A run id is RFC 3986 unreserved characters (letters, digits, `-`, `.`, `_`, `~`); a run given none +gets a UUID. + +## Examples + +```shell +python examples/file_store_run.py # PROV and JSON files +python examples/mariadb_store_run.py # queue, cancel by id, run +python examples/all_stores_run.py # one run in all three stores +``` -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: +The MariaDB examples need the `mariadb` extra and an `.env` at the repository root: ```dotenv MARIADB_USER="user" @@ -83,11 +185,12 @@ pip install -e ".[dev]" pytest ``` -The conformance test validates a recorded run against the shapes in a +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/all_stores_run.py b/examples/all_stores_run.py new file mode 100644 index 0000000..cebde73 --- /dev/null +++ b/examples/all_stores_run.py @@ -0,0 +1,38 @@ +"""Record one run in all three stores at once -- PROV document, JSON record, MariaDB tables -- and check they give back the same graph. + +Needs the `mariadb` extra and the connection settings in `.env` (see the README). +""" + +from rdflib.compare import isomorphic + +from rec import provenance +from rec.observer import Observer +from rec.run import Run +from rec.stores.file_store import FileStore +from rec.stores.mariadb_store import MariaDBStore + + +class ScrewingRun(Run): + def main(self): + self.add_agent("https://example.org/agent/arm", "Agent", name="arm") + self.log_dependencies([{"name": "rdflib", "version": "7.6.0"}]) + self.add_resource("config/screw.yaml") + self.add_artefact("results/torque.csv") + # One count per screw: a step per attempt, not per sample. + for screw, attempts in enumerate([1, 2, 1]): + self.log_scalar("attempts", attempts, screw) + self.log_scalar("safety-stops", 0) + return 3 + + +if __name__ == "__main__": + stores = [FileStore("runs/prov"), FileStore("runs/json", fmt="json"), MariaDBStore(db_name="logbook", prefix="logs")] + observers = [Observer(store) for store in stores] + run = ScrewingRun(observers=observers, run_id="screw-1") + run.run() + + prov, records, tables = (provenance.graph(store.load(run.id)) for store in stores) + assert isomorphic(prov, records) and isomorphic(prov, tables) + print(prov.serialize(format="turtle")) + for observer in observers: + observer.close() diff --git a/examples/decentral_run.py b/examples/decentral_run.py deleted file mode 100644 index a5dc9d8..0000000 --- a/examples/decentral_run.py +++ /dev/null @@ -1,19 +0,0 @@ -from rec.observer import Observer -from rec.run import Run -from rec.stores.mariadb_store import MariaDBStore - - -def main(): - import time - - print("\tThis the main of the run") - time.sleep(15) - - -if __name__ == "__main__": - observer = Observer(MariaDBStore()) - run = Run(observers=[observer]) - run.main = main - - run.run() - observer.close() diff --git a/examples/file_store_run.py b/examples/file_store_run.py new file mode 100644 index 0000000..11c745e --- /dev/null +++ b/examples/file_store_run.py @@ -0,0 +1,32 @@ +"""Record a run as a PROV document and as a JSON record in directories, and read it back.""" + +from rec.observer import Observer +from rec.run import Run +from rec.stores.file_store import FileStore + + +class PickPlaceRun(Run): + def main(self): + self.add_agent("https://example.org/agent/arm", "Agent", name="arm") + self.log_repositories([{"name": "controller", "url": "https://example.org/lab/controller", "commit": "0123abcd"}]) + self.log_dependencies([{"name": "rdflib", "version": "7.6.0"}]) + self.add_resource("config/robot.yaml") + self.add_artefact("results/trajectory.csv") + # The value the verdict is judged on; the trajectory itself is the artefact. + self.log_scalar("final-position-error", 0.004) + return "placed" + + +if __name__ == "__main__": + prov = FileStore("runs/prov") + records = FileStore("runs/json", fmt="json") + observers = [Observer(prov), Observer(records)] + run = PickPlaceRun(observers=observers, run_id="pick-place-1") + run.run() + for observer in observers: + observer.close() + + print(f"PROV document: {prov.path(run.id)}") + record = records.load(run.id) + assert record is not None + print(record.state, record.verdict, [(metric.name, metric.step, metric.value) for metric in record.metrics]) diff --git a/examples/mariadb_store_run.py b/examples/mariadb_store_run.py new file mode 100644 index 0000000..e5e0071 --- /dev/null +++ b/examples/mariadb_store_run.py @@ -0,0 +1,43 @@ +"""Queue runs in MariaDB, cancel one by id as a scheduler would, run the other, and read it back. + +Needs the `mariadb` extra and the connection settings in `.env` (see the README). +""" + +from rec import State +from rec.observer import Observer +from rec.run import Run +from rec.stores.mariadb_store import MariaDBStore + + +class DrawerOpeningRun(Run): + def main(self): + self.add_agent("https://example.org/agent/dual-arm", "Agent", name="dual-arm") + self.add_resource("config/cabinet.yaml") + if self.state is State.CANCELING: + return "stopped" + self.add_artefact("results/drawer-opening.bag") + self.log_scalar("loop-overruns", 0) + self.log_scalar("retries", 1) + return "opened" + + +if __name__ == "__main__": + observer = Observer(MariaDBStore(db_name="logbook", prefix="logs")) + kept = DrawerOpeningRun(observers=[observer], run_id="drawer-1") + dropped = DrawerOpeningRun(observers=[observer], run_id="drawer-2") + kept.queue() + dropped.queue() + print("queued:", observer.store.run_ids(State.QUEUED)) + + # A scheduler holds only the id, and its own connection to the same tables. + scheduler = Observer(MariaDBStore(db_name="logbook", prefix="logs")) + Run(observers=[scheduler], run_id="drawer-2").cancel() + scheduler.close() + print("drawer-2:", dropped.state) + + kept.run() + record = observer.store.load(kept.id) + assert record is not None + print(record.state, record.verdict, [(metric.name, metric.step, metric.value) for metric in record.metrics]) + print("canceled:", observer.store.run_ids(State.CANCELED)) + observer.close() diff --git a/pyproject.toml b/pyproject.toml index 21f242a..9487734 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,9 @@ [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" @@ -18,7 +21,10 @@ maintainers = [ [project.optional-dependencies] mariadb = ["dotenv", "mariadb"] -dev = ["black>=24.4.2", "pytest", "pyshacl"] +dev = ["pytest", "pyshacl"] + +[tool.hatch.metadata] +allow-direct-references = true -[tool.setuptools.packages.find] -where = ["."] # list of folders that contain the packages (["."] by default) +[tool.hatch.build.targets.wheel] +packages = ["rec"] 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/observer.py b/rec/observer.py index e61e0b7..7f8388f 100644 --- a/rec/observer.py +++ b/rec/observer.py @@ -9,25 +9,23 @@ from rdf_utils.models.prov import get_pkg_info -from rec import State, Verdict, provenance +from rec import State, Verdict from rec.record import ( - ORDER, + Activity, Agent, Dependency, FileRef, Generation, Host, - Metric, Repository, Software, Usage, - from_json, - to_json, ) from rec.stores import Store # PROV-O's agent classes (PROV-O 4.1). AGENT_TYPES = ("Agent", "SoftwareAgent", "Person", "Organization") +ACTIVITY_KINDS = ("Specification", "Transformation", "Generalization", "Execution", "Assurance") class Observer: @@ -38,138 +36,161 @@ class Observer: def __init__(self, store: Store): self.store = store - # Per thread: a heartbeat must wait for the store, not join another thread's held record. + # Per thread: a heartbeat must wait for the store, not join another thread's held run. self._held = threading.local() @contextmanager def _hold(self, run_id: str): - """Keep the run's record open: the calls made meanwhile are kept together when the block ends, or none is.""" - with self._record(run_id) as record: - outer = getattr(self._held, "record", None) - self._held.record = record + """Keep the run open in the store: the calls made meanwhile are kept together when the block ends, or none is.""" + with self._run(run_id) as run: + outer = getattr(self._held, "run", None) + self._held.run = run try: yield finally: - self._held.record = outer + self._held.run = outer @contextmanager - def _record(self, run_id: str): - held = getattr(self._held, "record", None) + def _run(self, run_id: str): + held = getattr(self._held, "run", None) if held is not None and held.run_id == run_id: yield held return - with self.store.edit(run_id) as record: - yield record - for name, key in ORDER.items(): - getattr(record, name).sort(key=key) - # Checked for every store, so none keeps a record another would change or could not keep. - try: - kept = from_json(to_json(record)) - except (TypeError, ValueError) as error: - raise ValueError(f"run '{run_id}' holds a value JSON cannot keep -- {error}") from error - if kept != record: - raise ValueError(f"run '{run_id}' holds a value JSON would change -- e.g. a non-string key or a tuple") - as_prov = provenance.record(provenance.graph(record), run_id) - changed = [name for name in vars(record) if getattr(as_prov, name) != getattr(record, name)] - if changed: - raise ValueError( - f"run '{run_id}' would read back from PROV with other {changed} -- " - "e.g. an empty string, or one file, agent, repository or dependency logged twice" - ) + with self.store.edit(run_id) as run: + yield run def log_queued_run(self, run_id: str, queued_time: datetime): - with self._record(run_id) as record: - if record.state is not State.NEW: - raise RuntimeError(f"run '{run_id}' is {record.state} -- only a new run can be queued") - record.state, record.verdict, record.queued_time = State.QUEUED, Verdict.UNAVAILABLE, queued_time - - def log_started_run(self, run_id: str, started_time: datetime, trigger=None, starter=None, program=None): - with self._record(run_id) as record: - if record.state not in (State.NEW, State.QUEUED): - raise RuntimeError(f"run '{run_id}' is {record.state} -- only a run that has not started can start") - record.state, record.verdict, record.start_time = State.IN_PROGRESS, Verdict.UNAVAILABLE, started_time - record.trigger, record.starter = trigger, starter - record.program = file_ref(program) if program else None - record.recorder = Software(*get_pkg_info("rec")) - - def log_run_heartbeat(self, run_id: str, beat_time: datetime, result=None): - with self._record(run_id) as record: - if record.state is not State.IN_PROGRESS: - raise RuntimeError(f"run '{run_id}' is {record.state} -- only a run in progress beats") - record.heartbeat_time = beat_time - if result is not None: - record.result = result - - def log_completed_run(self, run_id: str, completed_time: datetime, result=None): + """Record a new run as queued; raises RuntimeError for a run that is not new.""" + with self._run(run_id) as run: + if run.state is not State.NEW: + raise RuntimeError(f"run '{run_id}' is {run.state} -- only a new run can be queued") + run.update(state=State.QUEUED, verdict=Verdict.UNAVAILABLE, queued_time=queued_time) + + def log_started_run(self, run_id: str, started_time: datetime, trigger_entity=None, trigger_generator=None, program=None): + """Record a new or queued run as in progress, with what started it and rec as its recorder. + + :param trigger_entity: An entity that triggers the run + :param trigger_generator: The activity that generated the trigger entity + :param program: The file defining the run + :raises RuntimeError: The run has already started, or was cancelled + """ + with self._run(run_id) as run: + if run.state not in (State.NEW, State.QUEUED): + raise RuntimeError(f"run '{run_id}' is {run.state} -- only a run that has not started can start") + run.update( + state=State.IN_PROGRESS, + verdict=Verdict.UNAVAILABLE, + start_time=started_time, + trigger_entity=trigger_entity, + trigger_generator=trigger_generator, + program=file_ref(program) if program else None, + recorder=Software(*get_pkg_info("rec")), + ) + + def log_run_heartbeat(self, run_id: str, beat_time: datetime): + """Record that a started run is still alive; raises RuntimeError for any other run.""" + with self._run(run_id) as run: + if run.state not in (State.IN_PROGRESS, State.CANCELING): + raise RuntimeError(f"run '{run_id}' is {run.state} -- only a started run beats") + run.update(heartbeat_time=beat_time) + + def log_completed_run(self, run_id: str, completed_time: datetime, result: str | None = None): + """End a run in progress as passed, or a canceling one as canceled, with what its ``main`` returned. + + :raises RuntimeError: The run has not started, or has ended + """ self._end(run_id, completed_time, Verdict.PASSED, result=result) def log_interrupted_run(self, run_id: str, interrupted_time: datetime, fail_trace: str | None = None): + """End a run in progress with an error verdict and the trace of what interrupted it.""" self._end(run_id, interrupted_time, Verdict.ERROR, fail_trace=fail_trace) def log_failed_run(self, run_id: str, failed_time: datetime, fail_trace: str | None = None): + """End a run in progress as failed, with the trace of the exception that ended it.""" self._end(run_id, failed_time, Verdict.FAILED, fail_trace=fail_trace) def log_cancelled_run(self, run_id: str, cancelled_time: datetime): - with self._record(run_id) as record: - if record.state is not State.QUEUED: - raise RuntimeError(f"run '{run_id}' is {record.state} -- only a queued run can be cancelled") - record.state, record.verdict, record.end_time = State.CANCELED, Verdict.UNAVAILABLE, cancelled_time + """Cancel a queued run, or ask a run in progress to stop; raises RuntimeError for any other run.""" + with self._run(run_id) as run: + if run.state is State.QUEUED: + run.update(state=State.CANCELED, verdict=Verdict.UNAVAILABLE, end_time=cancelled_time) + elif run.state is State.IN_PROGRESS: + run.update(state=State.CANCELING) + else: + raise RuntimeError(f"run '{run_id}' is {run.state} -- only a queued run or one in progress can be cancelled") def log_host_info(self, run_id: str, host_info: dict): - with self._record(run_id) as record: - record.host = Host(host_info.get("hostname"), host_info.get("os"), host_info.get("python"), host_info.get("cpu")) - - def log_sources(self, run_id: str, sources: list): - with self._record(run_id) as record: - record.sources += [file_ref(row["path"], row.get("title"), row.get("sha256"), row.get("size_bytes")) for row in sources] + """Record the machine executing the run, from ``hostname``, ``os``, ``python`` and ``cpu``.""" + with self._run(run_id) as run: + run.update(host=Host(host_info.get("hostname"), host_info.get("os"), host_info.get("python"), host_info.get("cpu"))) def log_repositories(self, run_id: str, repositories: list): - with self._record(run_id) as record: - record.repositories += [Repository(row["name"], row.get("url"), row.get("commit")) for row in repositories] + """Record repositories, rows with a ``name`` and optionally ``url``, ``commit``; refuses a name twice.""" + with self._run(run_id) as run: + for row in repositories: + run.add("repositories", Repository(row["name"], row.get("url"), row.get("commit"))) def log_dependencies(self, run_id: str, dependencies: list): - with self._record(run_id) as record: - record.dependencies += [Dependency(row["name"], row.get("version")) for row in dependencies] + """Record dependencies, rows with a ``name`` and optionally ``version``; refuses a name twice.""" + with self._run(run_id) as run: + for row in dependencies: + run.add("dependencies", Dependency(row["name"], row.get("version"))) def log_scalar(self, run_id: str, metric_name: str, value, step: int | None = None, time: datetime | None = None): - with self._record(run_id) as record: - if step is None: - step = sum(1 for metric in record.metrics if metric.name == metric_name) - # One value per step: logging a step again is a re-measurement, not a second one. - kept = [metric for metric in record.metrics if (metric.name, metric.step) != (metric_name, step)] - record.metrics = [*kept, Metric(metric_name, step, value, time)] + """Record a metric's value at ``step``, or at its next step; a step logged again gets the new value. + + :raises ValueError: The value is NaN or infinite + """ + with self._run(run_id) as run: + run.add_metric(metric_name, value, step, time) def add_agent(self, run_id: str, agent_id: str, agent_type: str, name: str | None = None): + """Associate an agent with the run. + + :param agent_type: A PROV-O agent class: ``Agent``, ``SoftwareAgent``, ``Person`` or ``Organization`` + :raises ValueError: The type is not one of those, a software agent has no name, or the agent is already associated + """ if agent_type not in AGENT_TYPES: raise ValueError(f"'{agent_type}' is not a PROV agent type -- use one of {list(AGENT_TYPES)}") if agent_type == "SoftwareAgent" and not name: raise ValueError(f"'{agent_id}' is a software agent without a name -- the prov-extension shapes require one") - with self._record(run_id) as record: - record.agents.append(Agent(agent_id, agent_type, name)) + with self._run(run_id) as run: + run.add("agents", Agent(agent_id, agent_type, name)) + + def add_activity(self, run_id: str, activity_id: str, kind: str, agent_id: str, start_time: datetime, end_time: datetime | None = None): + """Add a step of the run, done by ``agent_id``; a file it used or generated names it as its activity. + + :param kind: A prov-extension activity class: ``Specification``, ``Transformation``, ``Generalization``, + ``Execution`` or ``Assurance`` + :raises ValueError: The kind is not one of those, or the run already has the activity + """ + if kind not in ACTIVITY_KINDS: + raise ValueError(f"'{kind}' is not a prov-extension activity class -- use one of {list(ACTIVITY_KINDS)}") + with self._run(run_id) as run: + run.add("activities", Activity(activity_id, kind, agent_id, start_time, end_time)) def add_resource(self, run_id: str, filename, usage_activity=None, usage_time=None, title=None, sha256=None, size_bytes=None): - with self._record(run_id) as record: - record.resources.append(Usage(file_ref(filename, title, sha256, size_bytes), usage_activity, usage_time)) + """Record a file used by ``usage_activity``, or by the run; refuses one file used twice by one activity.""" + with self._run(run_id) as run: + run.add("resources", Usage(file_ref(filename, title, sha256, size_bytes), usage_activity, usage_time)) def add_artefact(self, run_id: str, filename, gen_activity=None, generated_time=None, title=None, sha256=None, size_bytes=None): - ref = file_ref(filename, title, sha256, size_bytes) - with self._record(run_id) as record: - # PROV-Constraints, generation-uniqueness: an entity has at most one generation. - if any((row.file.path, row.file.root) == (ref.path, ref.root) for row in record.artefacts): - raise ValueError(f"'{ref.path}' is already an artefact of run '{run_id}' -- a file is generated once") - record.artefacts.append(Generation(ref, gen_activity, generated_time)) + """Record a file generated by ``gen_activity``, or by the run; refuses a file generated twice.""" + with self._run(run_id) as run: + run.add("artefacts", Generation(file_ref(filename, title, sha256, size_bytes), gen_activity, generated_time)) def close(self): self.store.close() - def _end(self, run_id, end_time, verdict, result=None, fail_trace=None): - with self._record(run_id) as record: - if record.state is not State.IN_PROGRESS: - raise RuntimeError(f"run '{run_id}' is {record.state} -- only a run in progress can end") - record.state, record.verdict, record.end_time = State.COMPLETE, verdict, end_time - if result is not None: - record.result = result - record.fail_trace = fail_trace + def _end(self, run_id, end_time, verdict, fail_trace=None, result=None): + with self._run(run_id) as run: + if run.state is State.CANCELING: + # The shapes keep a fail trace for a failed or error verdict only. + run.update(state=State.CANCELED, verdict=Verdict.UNAVAILABLE, end_time=end_time, result=result) + elif run.state is State.IN_PROGRESS: + run.update(state=State.COMPLETE, verdict=verdict, end_time=end_time, fail_trace=fail_trace, result=result) + else: + raise RuntimeError(f"run '{run_id}' is {run.state} -- only a started run can end") def file_ref(path, title=None, sha256=None, size_bytes=None) -> FileRef: diff --git a/rec/provenance.py b/rec/provenance.py index e43f795..c64757b 100644 --- a/rec/provenance.py +++ b/rec/provenance.py @@ -1,10 +1,12 @@ """A run record as PROV on the prov-extension and rec vocabularies, and back.""" import json +from typing import Any from urllib.parse import quote, unquote from rdf_utils.models.prov import ( _path_from_file_url, + add_activity, add_agent, add_entity, add_file_entity, @@ -13,11 +15,12 @@ load_pkg_prov, ) from rdflib import XSD, Graph, Literal, Namespace, URIRef -from rdflib.namespace import DCAT, PROV, RDF, RDFS, SDO +from rdflib.namespace import DCAT, DCTERMS, PROV, RDF, RDFS, SDO +from rdflib.term import Node from rec import State, Verdict from rec.record import ( - ORDER, + Activity, Agent, Dependency, FileRef, @@ -62,6 +65,7 @@ "oslc_auto": OSLC_AUTO, "spdx": SPDX, "dcat": DCAT, + "dcterms": DCTERMS, "schema": SDO, "qudt": QUDT, "rdfs": RDFS, @@ -75,7 +79,7 @@ def graph(record: RunRecord, base: str = RUN_BASE) -> Graph: g = Graph() for prefix, namespace in PREFIXES.items(): g.bind(prefix, namespace) - run = URIRef(base + quote(record.run_id, safe="")) + run = URIRef(base + record.run_id) g.add((run, RDF.type, PROV_EXT.Execution)) g.add((run, RDF.type, OSLC_AUTO.AutomationResult)) g.add((run, OSLC_AUTO.state, STATES[record.state])) @@ -83,15 +87,12 @@ def graph(record: RunRecord, base: str = RUN_BASE) -> Graph: for value, predicate in ((record.queued_time, REC["queued-time"]), (record.heartbeat_time, REC["heartbeat-time"])): if value: g.add((run, predicate, Literal(value))) - # A structured result as a JSON literal (JSON-LD 1.1, 4.2.2); a scalar keeps its XSD type. - if isinstance(record.result, (dict, list, tuple)): - g.add((run, REC.result, Literal(json.dumps(record.result), datatype=RDF.JSON))) - elif record.result is not None: - g.add((run, REC.result, Literal(record.result))) if record.fail_trace: g.add((run, REC["fail-trace"], Literal(record.fail_trace, datatype=XSD.string))) + if record.result is not None: + g.add((run, REC.result, Literal(record.result, datatype=XSD.string))) - used = [_file(g, run, ref) for ref in record.sources] + used = [] for row in record.repositories: repository = URIRef(f"{run}/repository/{quote(row.name, safe='')}") add_entity(g, repository) @@ -122,7 +123,7 @@ def graph(record: RunRecord, base: str = RUN_BASE) -> Graph: g.add((activity, PROV.used, entity)) g.add((activity, PROV.qualifiedUsage, node)) - if record.start_time: + if record.start_time and record.recorder: software = URIRef(f"{run}/software") load_pkg_prov(g, software, record.recorder.name, record.recorder.version, record.recorder.commit, record.recorder.repository) association = URIRef(f"{run}/association") @@ -143,15 +144,19 @@ def graph(record: RunRecord, base: str = RUN_BASE) -> Graph: for agent in record.agents: add_agent(g, URIRef(agent.id), (PROV[agent.type],), agent.name) g.add((run, PROV.wasAssociatedWith, URIRef(agent.id))) + # PROV has no part-whole relation between activities. + for activity in record.activities: + add_activity(g, URIRef(activity.id), (PROV_EXT[activity.kind],), (), URIRef(activity.agent), activity.start_time, activity.end_time) + g.add((URIRef(activity.id), DCTERMS.isPartOf, run)) - if record.trigger: + if record.trigger_entity: start = URIRef(f"{run}/start") - g.add((run, PROV.wasStartedBy, URIRef(record.trigger))) + g.add((run, PROV.wasStartedBy, URIRef(record.trigger_entity))) g.add((run, PROV.qualifiedStart, start)) g.add((start, RDF.type, PROV.Start)) - g.add((start, PROV.entity, URIRef(record.trigger))) - if record.starter: - g.add((start, PROV.hadActivity, URIRef(record.starter))) + g.add((start, PROV.entity, URIRef(record.trigger_entity))) + if record.trigger_generator: + g.add((start, PROV.hadActivity, URIRef(record.trigger_generator))) if record.host: host = URIRef(f"{run}/host") g.add((host, RDF.type, REC.Host)) @@ -188,15 +193,12 @@ def graph(record: RunRecord, base: str = RUN_BASE) -> Graph: def record(g: Graph, run_id: str, base: str = RUN_BASE) -> RunRecord: - """The record ``graph`` wrote; its lists come back sorted, a graph having no order.""" - run = URIRef(base + quote(run_id, safe="")) + """The record ``graph`` wrote; its lists come back in no particular order, a graph having none.""" + run = URIRef(base + run_id) association = g.value(run, PROV.qualifiedAssociation) plan, software = g.value(association, PROV.hadPlan), g.value(association, PROV.agent) start = g.value(run, PROV.qualifiedStart) host = g.value(run, PROV.atLocation) - result = g.value(run, REC.result) - run_usages = {g.value(usage, PROV.entity) for usage in g.objects(run, PROV.qualifiedUsage)} - kinds = {SDO.SoftwareSourceCode, SDO.SoftwareApplication} # Only what links to this run, or what graph() named under its IRI: the graph may hold other runs. own = f"{run}/" return RunRecord( @@ -207,8 +209,8 @@ def record(g: Graph, run_id: str, base: str = RUN_BASE) -> RunRecord: start_time=_python(g.value(run, PROV.startedAtTime)), end_time=_python(g.value(run, PROV.endedAtTime)), heartbeat_time=_python(g.value(run, REC["heartbeat-time"])), - result=json.loads(result) if result is not None and result.datatype == RDF.JSON else _python(result), fail_trace=_python(g.value(run, REC["fail-trace"])), + result=_python(g.value(run, REC.result)), program=_file_ref(g, plan) if plan else None, recorder=Software( str(g.value(software, SDO.name)), @@ -218,82 +220,67 @@ def record(g: Graph, run_id: str, base: str = RUN_BASE) -> RunRecord: ) if software else None, - trigger=_python(g.value(start, PROV.entity)), - starter=_python(g.value(start, PROV.hadActivity)), + trigger_entity=_python(g.value(start, PROV.entity)), + trigger_generator=_python(g.value(start, PROV.hadActivity)), host=Host(**{key: _python(g.value(host, predicate)) for key, predicate in HOST_TERMS.items()}) if host else None, - agents=sorted( - ( - Agent( - str(agent), - next((str(kind).removeprefix(str(PROV)) for kind in g.objects(agent, RDF.type) if kind != PROV.Agent), "Agent"), - _python(g.value(agent, SDO.name)), - ) - for agent in g.objects(run, PROV.wasAssociatedWith) - if agent != software - ), - key=ORDER["agents"], - ), - sources=sorted( - ( - _file_ref(g, entity) - for entity in g.objects(run, PROV.used) - if entity != plan and entity not in run_usages and not set(g.objects(entity, RDF.type)) & kinds - ), - key=ORDER["sources"], - ), - repositories=sorted( - ( - Repository(str(g.value(node, RDFS.label)), _python(g.value(node, SDO.codeRepository)), _python(g.value(node, SDO.identifier))) - for node in g.objects(run, PROV.used) - if (node, RDF.type, SDO.SoftwareSourceCode) in g - ), - key=ORDER["repositories"], - ), - dependencies=sorted( - ( - Dependency(str(g.value(node, RDFS.label)), _python(g.value(node, SDO.softwareVersion))) - for node in g.objects(run, PROV.used) - if (node, RDF.type, SDO.SoftwareApplication) in g - ), - key=ORDER["dependencies"], - ), - resources=sorted( - ( - Usage( - _file_ref(g, g.value(usage, PROV.entity)), - None if activity == run else str(activity), - _python(g.value(usage, PROV.atTime)), - ) - for activity, usage in g.subject_objects(PROV.qualifiedUsage) - if usage.startswith(own) - ), - key=ORDER["resources"], - ), - artefacts=sorted( - ( - Generation( - _file_ref(g, entity), - None if g.value(node, PROV.activity) == run else str(g.value(node, PROV.activity)), - _python(g.value(node, PROV.atTime)), - ) - for entity, node in g.subject_objects(PROV.qualifiedGeneration) - if node.startswith(own) - ), - key=ORDER["artefacts"], - ), - metrics=sorted( - ( - Metric( - str(g.value(node, RDFS.label)), - g.value(node, REC.step).toPython(), - g.value(node, QUDT.value).toPython(), - _python(g.value(node, PROV.generatedAtTime)), - ) - for node in g.subjects(PROV.wasGeneratedBy, run) - if (node, RDF.type, REC.Metric) in g - ), - key=ORDER["metrics"], - ), + agents=[ + Agent( + str(agent), + next((str(kind).removeprefix(str(PROV)) for kind in g.objects(agent, RDF.type) if kind != PROV.Agent), "Agent"), + _python(g.value(agent, SDO.name)), + ) + for agent in g.objects(run, PROV.wasAssociatedWith) + if agent != software + ], + activities=[ + Activity( + str(activity), + next(str(kind).removeprefix(str(PROV_EXT)) for kind in g.objects(activity, RDF.type) if str(kind).startswith(str(PROV_EXT))), + str(g.value(activity, PROV.wasAssociatedWith)), + _python(g.value(activity, PROV.startedAtTime)), + _python(g.value(activity, PROV.endedAtTime)), + ) + for activity in g.subjects(DCTERMS.isPartOf, run) + ], + repositories=[ + Repository(str(g.value(node, RDFS.label)), _python(g.value(node, SDO.codeRepository)), _python(g.value(node, SDO.identifier))) + for node in g.objects(run, PROV.used) + if (node, RDF.type, SDO.SoftwareSourceCode) in g + ], + dependencies=[ + Dependency(str(g.value(node, RDFS.label)), _python(g.value(node, SDO.softwareVersion))) + for node in g.objects(run, PROV.used) + if (node, RDF.type, SDO.SoftwareApplication) in g + ], + resources=[ + Usage( + _file_ref(g, entity), + None if activity == run else str(activity), + _python(g.value(usage, PROV.atTime)), + ) + for activity, usage in g.subject_objects(PROV.qualifiedUsage) + if str(usage).startswith(own) + for entity in g.objects(usage, PROV.entity) + ], + artefacts=[ + Generation( + _file_ref(g, entity), + None if g.value(node, PROV.activity) == run else str(g.value(node, PROV.activity)), + _python(g.value(node, PROV.atTime)), + ) + for entity, node in g.subject_objects(PROV.qualifiedGeneration) + if str(node).startswith(own) + ], + metrics=[ + Metric( + str(g.value(node, RDFS.label)), + _python(g.value(node, REC.step)), + _python(g.value(node, QUDT.value)), + _python(g.value(node, PROV.generatedAtTime)), + ) + for node in g.subjects(PROV.wasGeneratedBy, run) + if (node, RDF.type, REC.Metric) in g + ], ) @@ -327,14 +314,13 @@ def _file(g: Graph, run: URIRef, ref: FileRef) -> URIRef: return entity -def _file_ref(g: Graph, entity: URIRef) -> FileRef: +def _file_ref(g: Graph, entity: Node) -> FileRef: location = g.value(entity, PROV.atLocation) rel_path = g.value(location, PROV_EXT["rel-path"]) if rel_path is not None: path, root = unquote(str(rel_path)), str(_path_from_file_url(str(g.value(location, PROV.atLocation)))) else: path, root = str(_path_from_file_url(str(location))) if str(location).startswith("file:") else str(location), None - size = g.value(entity, DCAT.byteSize) # An xsd:hexBinary's Python value is bytes; the record holds the hex text. checksum = g.value(g.value(entity, SPDX.checksum), SPDX.checksumValue) return FileRef( @@ -342,11 +328,11 @@ def _file_ref(g: Graph, entity: URIRef) -> FileRef: root, _python(g.value(entity, RDFS.label)), str(checksum) if checksum is not None else None, - size.toPython() if size is not None else None, + _python(g.value(entity, DCAT.byteSize)), ) -def _python(term): +def _python(term: Node | None) -> Any: """A term as the value the record holds: a literal's Python value, an IRI as its string.""" if term is None: return None diff --git a/rec/record.py b/rec/record.py index bb2cd07..c2eb809 100644 --- a/rec/record.py +++ b/rec/record.py @@ -1,21 +1,25 @@ """What rec records of a run, independent of where it is stored.""" import json +import math +import re from dataclasses import asdict, dataclass, field from datetime import datetime -from typing import Any from rec import State, Verdict +# 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._~-]+") TIMES = ("queued_time", "start_time", "end_time", "heartbeat_time") -# The order a record keeps its lists in, the one a PROV graph, having none, reads them back in. -ORDER = { +# What makes a row of each list one of a kind. +KEYS = { "agents": lambda agent: agent.id, - "sources": lambda ref: (ref.path, ref.root or ""), + "activities": lambda activity: activity.id, "repositories": lambda row: row.name, "dependencies": lambda row: row.name, - "resources": lambda row: (row.activity or "", row.file.path, row.file.root or ""), - "artefacts": lambda row: (row.activity or "", row.file.path, row.file.root or ""), + "resources": lambda row: (row.activity, row.file.path, row.file.root), + # PROV-Constraints, generation-uniqueness: an entity has at most one generation. + "artefacts": lambda row: (row.file.path, row.file.root), "metrics": lambda row: (row.name, row.step), } @@ -49,8 +53,21 @@ class Generation: time: datetime | None = None +@dataclass +class Activity: + """A step of the run, ``dcterms:isPartOf`` it; ``kind`` is its prov-extension class, e.g. ``Execution``.""" + + id: str + kind: str + agent: str + start_time: datetime + end_time: datetime | None = None + + @dataclass class Agent: + """A PROV agent associated with the run; ``type`` is its PROV-O class, e.g. ``Person``.""" + id: str type: str name: str | None = None @@ -71,11 +88,18 @@ class Dependency: @dataclass class Metric: + """A value of the metric ``name`` at ``step``; raises ValueError for a NaN or infinite value.""" + name: str step: int value: float | int time: datetime | None = None + def __post_init__(self): + # JSON (RFC 8259) and MariaDB's DOUBLE have no NaN or infinity. + if not math.isfinite(self.value): + raise ValueError(f"metric '{self.name}' is {self.value} -- a metric is finite") + @dataclass class Software: @@ -97,6 +121,8 @@ class Host: @dataclass class RunRecord: + """What rec knows of a run; also what FileStore.edit yields to change it (rec.stores.RunHandle).""" + run_id: str state: State = State.NEW verdict: Verdict = Verdict.UNAVAILABLE @@ -104,21 +130,44 @@ class RunRecord: start_time: datetime | None = None end_time: datetime | None = None heartbeat_time: datetime | None = None - result: Any = None fail_trace: str | None = None + result: str | None = None program: FileRef | None = None recorder: Software | None = None - trigger: str | None = None - starter: str | None = None + trigger_entity: str | None = None + trigger_generator: str | None = None host: Host | None = None agents: list[Agent] = field(default_factory=list) - sources: list[FileRef] = field(default_factory=list) + activities: list[Activity] = field(default_factory=list) repositories: list[Repository] = field(default_factory=list) dependencies: list[Dependency] = field(default_factory=list) resources: list[Usage] = field(default_factory=list) artefacts: list[Generation] = field(default_factory=list) metrics: list[Metric] = field(default_factory=list) + def __post_init__(self): + if not RUN_ID.fullmatch(self.run_id): + raise ValueError(f"'{self.run_id}' is not a run id -- use letters, digits, '-', '.', '_' or '~', not '.' or '..'") + + def update(self, **values): + for name, value in values.items(): + setattr(self, name, value) + + def add(self, kind: str, row, replace: bool = False): + rows = getattr(self, kind) + key = KEYS[kind](row) + activity = row.activity if isinstance(row, (Usage, Generation)) else None + if activity is not None and all(kept.id != activity for kept in self.activities): + raise ValueError(f"run '{self.run_id}' has no activity '{activity}' -- add it to the run first") + if not replace and any(KEYS[kind](kept) == key for kept in rows): + raise ValueError(f"run '{self.run_id}' already has {key} among its {kind} -- each is logged once") + rows[:] = [*(kept for kept in rows if KEYS[kind](kept) != key), row] + + def add_metric(self, name: str, value: float, step: int | None = None, time: datetime | None = None): + if step is None: + step = max((kept.step for kept in self.metrics if kept.name == name), default=-1) + 1 + self.add("metrics", Metric(name, step, value, time), replace=True) + def to_json(record: RunRecord) -> str: """The record as JSON (RFC 8259, so no NaN or infinity), its times in ISO 8601.""" @@ -128,19 +177,20 @@ def to_json(record: RunRecord) -> str: def from_json(text: str) -> RunRecord: """The record ``to_json`` wrote.""" data = json.loads(text) - for row in [data, *data["resources"], *data["artefacts"], *data["metrics"]]: + for row in [data, *data.get("activities", []), *data["resources"], *data["artefacts"], *data["metrics"]]: for key in (*TIMES, "time"): if row.get(key): row[key] = datetime.fromisoformat(row[key]) return RunRecord( - **{key: data[key] for key in ("run_id", "result", "fail_trace", "trigger", "starter", *TIMES)}, + **{key: data[key] for key in ("run_id", "fail_trace", "trigger_entity", "trigger_generator", *TIMES)}, + result=data.get("result"), state=State(data["state"]), verdict=Verdict(data["verdict"]), program=FileRef(**data["program"]) if data["program"] else None, recorder=Software(**data["recorder"]) if data["recorder"] else None, host=Host(**data["host"]) if data["host"] else None, agents=[Agent(**row) for row in data["agents"]], - sources=[FileRef(**row) for row in data["sources"]], + activities=[Activity(**row) for row in data.get("activities", [])], repositories=[Repository(**row) for row in data["repositories"]], dependencies=[Dependency(**row) for row in data["dependencies"]], resources=[Usage(FileRef(**row["file"]), row["activity"], row["time"]) for row in data["resources"]], diff --git a/rec/run.py b/rec/run.py index 72b8807..0a02996 100644 --- a/rec/run.py +++ b/rec/run.py @@ -16,12 +16,6 @@ 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): # A daemon: a beat stuck on a store must not keep the process alive once the run is over. super().__init__(daemon=True) @@ -50,22 +44,13 @@ def __init__( self, observers: Sequence[Observer] = (), run_id: str | None = None, - pre_run_hooks: list = (), - post_run_hooks: list = (), ): self._id = run_id self.observers = list(observers) # A start holds every store's record at once; a store held twice would wait on itself. if len({id(observer.store) for observer in self.observers}) < len(self.observers): raise ValueError("'observers' share a store -- give each its own store") - self.start_time = None - self.end_time = None - self.state = None - self.verdict = None self.result = None - self.pre_run_hooks = list(pre_run_hooks) - self.post_run_hooks = list(post_run_hooks) - self._heartbeat = None self.beat_interval = 10 @@ -76,6 +61,18 @@ def id(self): self._id = str(uuid4()) return self._id + @property + def state(self): + """The run's state as the first observer's store keeps it, ``new`` until it is stored""" + record = self.observers[0].store.load(self.id) if self.observers else None + return record.state if record else State.NEW + + @property + def verdict(self): + """The run's verdict as the first observer's store keeps it""" + record = self.observers[0].store.load(self.id) if self.observers else None + return record.verdict if record else Verdict.UNAVAILABLE + @contextmanager def _held(self): """Every store's record open at once: one refusal leaves them all unchanged; a failed save can still split them.""" @@ -86,48 +83,28 @@ def _held(self): def _start_heartbeat(self): if self.beat_interval > 0: - self._stop_heartbeat_event, self._heartbeat = IntervalTimer.create( - self._emit_heartbeat, self.beat_interval - ) + self._stop_heartbeat_event = threading.Event() + self._heartbeat = IntervalTimer(self._stop_heartbeat_event, 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) - logger.debug("Run %s still running, result so far: %s", self.id, self.result) + logger.debug("Run %s still running", self.id) # Update info on observers for observer in self.observers: - observer.log_run_heartbeat(self.id, beat_time, result=self.result) - - def _emit_cancelled(self): - cancelled_time = datetime.datetime.now(datetime.UTC) - # The stores go first, as on start: one of them may refuse. - with self._held(): - for observer in self.observers: - observer.log_cancelled_run(self.id, cancelled_time) - self.state, self.verdict, self.end_time = State.CANCELED, Verdict.UNAVAILABLE, cancelled_time - logger.info("Cancelled run %s", self.id) - - def _emit_queued(self): - queued_time = datetime.datetime.now(datetime.UTC) - with self._held(): - for observer in self.observers: - observer.log_queued_run(self.id, queued_time) - self.state, self.verdict = State.QUEUED, Verdict.UNAVAILABLE - logger.info("Queued run %s", self.id) + observer.log_run_heartbeat(self.id, beat_time) - def _emit_started(self, trigger=None, starter=None): + def _emit_started(self, trigger_entity=None, trigger_generator=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: + :param trigger_entity: An entity that triggers the run + :param trigger_generator: The activity that generated the trigger entity """ start_time = datetime.datetime.now(datetime.UTC) logger.info("Starting run %s", self.id) @@ -137,87 +114,69 @@ def _emit_started(self, trigger=None, starter=None): except (TypeError, OSError): # A class typed into an interpreter has no file to name. program = None - # The stores go first: one of them may hold a cancellation this object never saw. with self._held(): for observer in self.observers: - observer.log_started_run(self.id, start_time, trigger=trigger, starter=starter, program=program) - self.state, self.verdict = State.IN_PROGRESS, Verdict.UNAVAILABLE - self.start_time = start_time + observer.log_started_run( + self.id, start_time, trigger_entity=trigger_entity, trigger_generator=trigger_generator, program=program + ) self.log_host_info(host_info()) - def _emit_completed(self): - completed_time = datetime.datetime.now(datetime.UTC) - with self._held(): - for observer in self.observers: - observer.log_completed_run(self.id, completed_time, self.result) - self.state, self.verdict, self.end_time = State.COMPLETE, Verdict.PASSED, completed_time - logger.info("Completed run %s after %s", self.id, completed_time - self.start_time) - - def _emit_interrupted(self, error=None): - interrupted_time = datetime.datetime.now(datetime.UTC) - with self._held(): - for observer in self.observers: - observer.log_interrupted_run(self.id, interrupted_time, _fail_trace(error)) - self.state, self.verdict, self.end_time = State.COMPLETE, Verdict.ERROR, interrupted_time - logger.warning("Interrupted run %s after %s", self.id, interrupted_time - self.start_time) - - def _emit_failed(self, error=None): - failed_time = datetime.datetime.now(datetime.UTC) + def _emit_ended(self, error=None): + """End the run as passed, error or failed by ``error``, or as canceled if a cancel came while it ran""" + end_time = datetime.datetime.now(datetime.UTC) with self._held(): for observer in self.observers: - observer.log_failed_run(self.id, failed_time, _fail_trace(error)) - self.state, self.verdict, self.end_time = State.COMPLETE, Verdict.FAILED, failed_time - logger.error("Failed run %s after %s", self.id, failed_time - self.start_time, exc_info=error) - - def _execute_hooks(self, hooks): - for hook in hooks: - hook() - - def main(self): + if error is None: + observer.log_completed_run(self.id, end_time, None if self.result is None else str(self.result)) + elif isinstance(error, KeyboardInterrupt): + observer.log_interrupted_run(self.id, end_time, _fail_trace(error)) + else: + observer.log_failed_run(self.id, end_time, _fail_trace(error)) + logger.log(logging.INFO if error is None else logging.ERROR, "Ended run %s", self.id, exc_info=error) + + def main(self) -> object: pass def queue(self): - """Record the run as queued, before a runner starts it""" - if self.state is not None: - raise RuntimeError(f"cannot queue a run that is {self.state}") - self._emit_queued() + """Record the run as queued, before a runner starts it; the store refuses a run that is not new""" + queued_time = datetime.datetime.now(datetime.UTC) + with self._held(): + for observer in self.observers: + observer.log_queued_run(self.id, queued_time) + logger.info("Queued run %s", self.id) return self.id def cancel(self): - """Cancel a queued run before it starts""" - if self.state is not State.QUEUED: - raise RuntimeError(f"only a queued run can be cancelled, not one that is {self.state}") - self._emit_cancelled() + """Cancel a queued run, or ask one in progress to stop: it ends as canceled once ``main`` returns. - def run(self, trigger=None, starter=None): - """ - A centralized runner can start and complete a run. Decentralized runners should not use this method. - :param trigger: An entity that triggers the run - :param starter: The activity that generated the trigger - :return: + Any holder of the run's id can cancel it, through a ``Run`` with that ``run_id`` on the same stores. + ``main`` sees the request as ``self.state`` being ``State.CANCELING``. """ - if self.state not in (None, State.QUEUED): - raise RuntimeError(f"cannot start a run that is {self.state}") - self._emit_started(trigger, starter) + cancel_time = datetime.datetime.now(datetime.UTC) + with self._held(): + for observer in self.observers: + observer.log_cancelled_run(self.id, cancel_time) + logger.info("Cancelled run %s", self.id) + def run(self, trigger_entity=None, trigger_generator=None): + """ + Start the run, execute ``main`` and record how it ended + :param trigger_entity: An entity that triggers the run + :param trigger_generator: The activity that generated the trigger entity + :raises RuntimeError: The store holds the run as started or canceled + """ + self._emit_started(trigger_entity, trigger_generator) + failure = None try: - # Stopped before any outcome is recorded, and on SystemExit too: the thread is not a daemon. + # Stopped before the end is recorded: a late beat would find the run ended and raise. try: self._start_heartbeat() - self._execute_hooks(self.pre_run_hooks) self.result = self.main() finally: self._stop_heartbeat() - logger.info("Result of run %s: %s", self.id, self.result) - self._emit_completed() - except KeyboardInterrupt as interrupt: - self._emit_interrupted(interrupt) - return self.result - except Exception as error: - self._emit_failed(error) - return self.result - # After completion: a post-run hook that raises is the caller's error, not the run's. - self._execute_hooks(self.post_run_hooks) + except (KeyboardInterrupt, Exception) as error: + failure = error + self._emit_ended(failure) return self.result def log_scalar(self, metric_name, value, step: int | None = None): @@ -226,25 +185,15 @@ def log_scalar(self, metric_name, value, step: int | None = None): :param metric_name: Name of the metric being logged :param value: The measured value :param step: Optional. Integer value representing the iteration number - :return: """ now = datetime.datetime.now(datetime.UTC) for observer in self.observers: observer.log_scalar(self.id, metric_name, value, step, now) - def log_sources(self, sources: list): - """Log the source code files used to execute this run (e.g., file name/path, md5) - :param sources: rows with a ``path`` and optionally ``title``, ``sha256``, ``size_bytes`` - :return: - """ - for observer in self.observers: - observer.log_sources(self.id, sources) - def log_repositories(self, repositories: list): """ Log the git information of the sources used in this run (url, commit/tag, uncommited changes) :param repositories: rows with a ``name`` and optionally ``url``, ``commit`` - :return: """ for observer in self.observers: observer.log_repositories(self.id, repositories) @@ -253,7 +202,6 @@ def log_dependencies(self, dependencies: list): """ Log the dependencies of the sources used in this run (e.g., package name, version) :param dependencies: rows with a ``name`` and optionally ``version`` - :return: """ for observer in self.observers: observer.log_dependencies(self.id, dependencies) @@ -262,7 +210,6 @@ def log_host_info(self, host_info: dict): """ Log information about the machine executing this run (e.g., cpu, gpu, OS, user, hostname, python version and venv, env variables, etc.) :param host_info: ``hostname``, ``os``, ``python``, ``cpu``; see :func:`host_info` - :return: """ for observer in self.observers: observer.log_host_info(self.id, host_info) @@ -273,11 +220,29 @@ def add_agent(self, agent_id: str, agent_type: str, name: str | None = None): :param agent_id: A unique ID for this agent :param agent_type: A PROV agent class: Agent, SoftwareAgent, Person or Organization :param name: The agent's name; a software agent must have one - :return: """ for observer in self.observers: observer.add_agent(self.id, agent_id, agent_type, name) + def add_activity( + self, + activity_id: str, + kind: str, + agent_id: str, + start_time: datetime.datetime, + end_time: datetime.datetime | None = None, + ): + """ + Add a step of the run (e.g., a calibration) that resources and artefacts can name as their activity + :param activity_id: The activity's IRI + :param kind: A prov-extension activity class: Specification, Transformation, Generalization, Execution or Assurance + :param agent_id: The agent that did it + :param start_time: When it started + :param end_time: When it ended + """ + for observer in self.observers: + observer.add_activity(self.id, activity_id, kind, agent_id, start_time, end_time) + def add_resource( self, filename, @@ -291,7 +256,6 @@ def add_resource( 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 @@ -299,7 +263,6 @@ def add_resource( :param title: A short title for the resource. Default: The file name :param sha256: The file's SHA-256 checksum, as hex :param size_bytes: The file's size - :return: """ if usage_time is None: usage_time = datetime.datetime.now(datetime.UTC) @@ -319,7 +282,6 @@ def add_artefact( 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 @@ -327,27 +289,12 @@ def add_artefact( :param title: A short title for the generated artefact :param sha256: The file's SHA-256 checksum, as hex :param size_bytes: The file's size - :return: """ if generated_time is None: generated_time = datetime.datetime.now(datetime.UTC) for observer in self.observers: observer.add_artefact(self.id, filename, gen_activity, generated_time, title, sha256, size_bytes) - def info(self): - """A summary of the run data - - :return: - """ - return { - "id": self._id, - "state": self.state, - "verdict": self.verdict, - "start_time": self.start_time.isoformat() if self.start_time else None, - "end_time": self.end_time.isoformat() if self.end_time else None, - "result": self.result, - } - def _fail_trace(error): return "".join(traceback.format_exception(error)) if error is not None else None 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 index 300f56f..5faedc7 100644 --- a/rec/stores/__init__.py +++ b/rec/stores/__init__.py @@ -1,21 +1,57 @@ """Where run records are kept: any object with these methods is a store.""" from contextlib import AbstractContextManager +from datetime import datetime from typing import Protocol from rec import State from rec.record import RunRecord +class RunHandle(Protocol): + """A run held by ``Store.edit``: its state, and the changes made to it.""" + + run_id: str + state: State + + def update(self, **values) -> None: + """Set fields of the run that it has one of, e.g. ``state``, ``start_time`` or ``host``.""" + ... + + def add(self, kind: str, row, replace: bool = False) -> None: + """Add a row to one of the run's lists, e.g. ``artefacts``. + + Raises ValueError if the list already has a row with the same key + (``rec.record.KEYS``), unless ``replace`` is set. + """ + ... + + def add_metric(self, name: str, value: float, step: int | None = None, time: datetime | None = None) -> None: + """Add a metric's value at ``step``, or after its last step, replacing a value at that step. + + Raises ValueError for a NaN or infinite value. + """ + ... + + class Store(Protocol): def load(self, run_id: str) -> RunRecord | None: - """The run's record, None for a run the store does not hold.""" + """Return the stored record of a run, or None if the run is not stored.""" + ... + + def edit(self, run_id: str) -> AbstractContextManager[RunHandle]: + """Lock a run for changing and keep the changes when the with block exits. - def edit(self, run_id: str) -> AbstractContextManager[RunRecord]: - """The run's record, new if not held, kept when the block ends; no other edit of the run interleaves and an error keeps nothing.""" + Yields a new run if the run is not stored. Other edits of the same run, + also from other processes, wait until the block exits. If the block + raises, nothing is kept. + """ + ... def run_ids(self, state: State | None = None) -> list[str]: - """The runs the store holds, those in STATE only when given.""" + """Return the ids of all stored runs, or only of those in the given state.""" + ... def close(self) -> None: - """Release what the store holds open; whoever created it calls this once.""" + """Close the store's connections; the code that created the store calls it once.""" + ... diff --git a/rec/stores/file_store.py b/rec/stores/file_store.py index 8a3a0e8..44195c6 100644 --- a/rec/stores/file_store.py +++ b/rec/stores/file_store.py @@ -8,13 +8,14 @@ from rdflib import Graph from rec import State, provenance -from rec.record import RunRecord, from_json, to_json +from rec.record import RUN_ID, RunRecord, from_json, to_json +from rec.stores import Store # The file each format keeps a run in: its record, or its PROV document. SUFFIXES = {"json": ".json", "rdf": ".ld.json"} -class FileStore: +class FileStore(Store): def __init__(self, directory, fmt: str = "rdf", base: str = provenance.RUN_BASE): """ :param directory: Where the files go; created on first write @@ -28,8 +29,13 @@ def __init__(self, directory, fmt: str = "rdf", base: str = provenance.RUN_BASE) self.base = base def path(self, run_id: str) -> Path: - if not run_id or run_id in (".", "..") or Path(run_id).name != run_id: - raise ValueError(f"'{run_id}' is not a file name -- a run id names its file in the directory") + """Return the run's file, ``.ld.json`` or ``.json`` in the directory. + + :raises ValueError: ``run_id`` is not a run id (``rec.record.RUN_ID``) + """ + # A load comes before any record, and an id like '../x' must not read outside the directory. + if not RUN_ID.fullmatch(run_id): + raise ValueError(f"'{run_id}' is not a run id -- use letters, digits, '-', '.', '_' or '~', not '.' or '..'") return self.directory / f"{run_id}{SUFFIXES[self.fmt]}" def load(self, run_id: str) -> RunRecord | None: @@ -42,6 +48,10 @@ def load(self, run_id: str) -> RunRecord | None: @contextmanager def edit(self, run_id: str): + """Yield the run's ``RunRecord`` under an ``flock`` on ``.lock``, 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. diff --git a/rec/stores/mariadb.sql b/rec/stores/mariadb.sql new file mode 100644 index 0000000..f7bd93b --- /dev/null +++ b/rec/stores/mariadb.sql @@ -0,0 +1,101 @@ +CREATE TABLE IF NOT EXISTS {prefix}_runs ( + id INT AUTO_INCREMENT PRIMARY KEY, + run_id VARCHAR(255) NOT NULL UNIQUE, + state VARCHAR(20) NOT NULL, + verdict VARCHAR(20) NOT NULL, + queued_time DATETIME(6), + start_time DATETIME(6), + end_time DATETIME(6), + heartbeat_time DATETIME(6), + fail_trace TEXT, + result TEXT, + trigger_entity TEXT, + trigger_generator TEXT, + program_path TEXT, + program_root TEXT, + program_title TEXT, + program_sha256 CHAR(64), + program_size_bytes BIGINT, + recorder_name TEXT, + recorder_version TEXT, + recorder_commit TEXT, + recorder_repository TEXT, + host_hostname TEXT, + host_os TEXT, + host_python TEXT, + host_cpu TEXT +); + +CREATE TABLE IF NOT EXISTS {prefix}_agents ( + run INT NOT NULL, + id TEXT NOT NULL, + type VARCHAR(20) NOT NULL, + name TEXT, + UNIQUE (run, id), + FOREIGN KEY (run) REFERENCES {prefix}_runs (id) +); + +CREATE TABLE IF NOT EXISTS {prefix}_activities ( + run INT NOT NULL, + id TEXT NOT NULL, + kind VARCHAR(20) NOT NULL, + agent TEXT NOT NULL, + start_time DATETIME(6) NOT NULL, + end_time DATETIME(6), + UNIQUE (run, id), + FOREIGN KEY (run) REFERENCES {prefix}_runs (id) +); + +CREATE TABLE IF NOT EXISTS {prefix}_repositories ( + run INT NOT NULL, + name VARCHAR(255) NOT NULL, + url TEXT, + `commit` TEXT, + UNIQUE (run, name), + FOREIGN KEY (run) REFERENCES {prefix}_runs (id) +); + +CREATE TABLE IF NOT EXISTS {prefix}_dependencies ( + run INT NOT NULL, + name VARCHAR(255) NOT NULL, + version TEXT, + UNIQUE (run, name), + FOREIGN KEY (run) REFERENCES {prefix}_runs (id) +); + +CREATE TABLE IF NOT EXISTS {prefix}_resources ( + run INT NOT NULL, + path TEXT NOT NULL, + root TEXT NOT NULL, + title TEXT, + sha256 CHAR(64), + size_bytes BIGINT, + activity TEXT NOT NULL, + time DATETIME(6), + UNIQUE (run, activity, path, root), + FOREIGN KEY (run) REFERENCES {prefix}_runs (id) +); + +CREATE TABLE IF NOT EXISTS {prefix}_artefacts ( + run INT NOT NULL, + path TEXT NOT NULL, + root TEXT NOT NULL, + title TEXT, + sha256 CHAR(64), + size_bytes BIGINT, + activity TEXT NOT NULL, + time DATETIME(6), + UNIQUE (run, path, root), + FOREIGN KEY (run) REFERENCES {prefix}_runs (id) +); + +CREATE TABLE IF NOT EXISTS {prefix}_metrics ( + run INT NOT NULL, + name VARCHAR(255) NOT NULL, + step INT NOT NULL, + value DOUBLE NOT NULL, + is_integer BOOL NOT NULL, + time DATETIME(6), + UNIQUE (run, name, step), + FOREIGN KEY (run) REFERENCES {prefix}_runs (id) +); diff --git a/rec/stores/mariadb_store.py b/rec/stores/mariadb_store.py index 5a70fb2..a346a3e 100644 --- a/rec/stores/mariadb_store.py +++ b/rec/stores/mariadb_store.py @@ -1,29 +1,48 @@ -"""A store keeping each run as one row of a MariaDB table.""" +"""A store keeping runs in MariaDB tables: a row per run, and a row per item of each of its lists.""" import os import threading from contextlib import contextmanager +from dataclasses import asdict, fields, is_dataclass +from datetime import UTC, datetime +from enum import Enum +from importlib.resources import files +from types import UnionType +from typing import Any, get_args, get_origin, get_type_hints import mariadb from dotenv import load_dotenv -from rec import State -from rec.record import RunRecord, from_json, to_json +from rec import State, Verdict +from rec.record import KEYS, FileRef, Generation, Metric, RunRecord, Usage +from rec.stores import RunHandle, Store +# mariadb.sql follows RunRecord: a list field is a table, a dataclass field `_` run columns. +RECORD_FIELDS = get_type_hints(RunRecord) +TABLES = {name: get_args(hint)[0] for name, hint in RECORD_FIELDS.items() if get_origin(hint) is list} +PARTS = { + name: get_args(hint)[0] + for name, hint in RECORD_FIELDS.items() + if get_origin(hint) is UnionType and is_dataclass(get_args(hint)[0]) +} +# Optional columns of a unique key, kept as "" for None: MariaDB's UNIQUE treats NULLs as distinct. +KEY_TEXT = ("root", "activity") -class MariaDBStore: - def __init__(self, db_name: str = "logbook", table: str = "logs"): + +class MariaDBStore(Store): + def __init__(self, db_name: str = "logbook", prefix: str = "logs"): """ - Store in a MariaDB table, connecting with ``MARIADB_USER``, ``MARIADB_PASSWORD``, + 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 table: Name of the table, one row per run: ``id`` in the order runs were added, - ``run_id``, ``state`` and ``verdict`` to query by, and ``record`` + :param prefix: Prefix of the table names: ``_runs`` has a row per run, ``id`` in the + order runs were added; ``_metrics``, ``_artefacts`` and the other lists + have a row per item, ``run`` naming its run's ``id`` """ load_dotenv() self.db_name = db_name - self.table = table + self.prefix = prefix self.conn = mariadb.connect( user=os.getenv("MARIADB_USER"), password=os.getenv("MARIADB_PASSWORD"), @@ -35,39 +54,42 @@ def __init__(self, db_name: str = "logbook", table: str = "logs"): 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() - self.cursor.execute( - f""" - CREATE TABLE IF NOT EXISTS {table} ( - id INT AUTO_INCREMENT PRIMARY KEY, - run_id VARCHAR(255) NOT NULL UNIQUE, - state VARCHAR(20) NOT NULL, - verdict VARCHAR(20) NOT NULL, - record LONGTEXT NOT NULL - ) - """ - ) + schema = files("rec.stores").joinpath("mariadb.sql").read_text().format(prefix=prefix) + for statement in schema.split(";"): + if statement.strip(): + self.cursor.execute(statement) def load(self, run_id: str) -> RunRecord | None: - with self._lock: - self.cursor.execute(f"SELECT record FROM {self.table} WHERE run_id = ?", (run_id,)) - row = self.cursor.fetchone() - return from_json(row[0]) if row else None + with self._lock, self.conn.cursor(dictionary=True) as cursor: + cursor.execute(f"SELECT * FROM {self.prefix}_runs WHERE run_id = ?", (run_id,)) + columns = cursor.fetchone() + if columns is None: + return None + record = _row(RunRecord, columns) + for kind, cls in TABLES.items(): + cursor.execute(f"SELECT * FROM {self.prefix}_{kind} WHERE run = ?", (columns["id"],)) + setattr(record, kind, [_row(cls, row) for row in cursor.fetchall()]) + return record @contextmanager def edit(self, run_id: str): + """Yield a ``MariaDBRun`` in one transaction, committed when the block exits, rolled back if it raises. + + The run's row is locked with ``SELECT ... FOR UPDATE``, and inserted first if the run is new. + """ with self._lock: self.conn.begin() try: - self.cursor.execute(f"SELECT record FROM {self.table} WHERE run_id = ? FOR UPDATE", (run_id,)) + self.cursor.execute(f"SELECT id, state FROM {self.prefix}_runs WHERE run_id = ? FOR UPDATE", (run_id,)) row = self.cursor.fetchone() - record = from_json(row[0]) if row else RunRecord(run_id) - yield record - values = (str(record.state), str(record.verdict), to_json(record), run_id) - # Not INSERT ... ON DUPLICATE KEY UPDATE: InnoDB spends an `id` on every such update. - if row: - self.cursor.execute(f"UPDATE {self.table} SET state = ?, verdict = ?, record = ? WHERE run_id = ?", values) - else: - self.cursor.execute(f"INSERT INTO {self.table} (state, verdict, record, run_id) VALUES (?, ?, ?, ?)", values) + if row is None: + new = RunRecord(run_id) + self.cursor.execute( + f"INSERT INTO {self.prefix}_runs (run_id, state, verdict) VALUES (?, ?, ?) RETURNING id, state", + (new.run_id, str(new.state), str(new.verdict)), + ) + row = self.cursor.fetchone() + yield MariaDBRun(self, run_id, row[0], State(row[1])) except BaseException: self.conn.rollback() raise @@ -76,11 +98,108 @@ def edit(self, run_id: str): def run_ids(self, state: State | None = None) -> list[str]: with self._lock: if state is None: - self.cursor.execute(f"SELECT run_id FROM {self.table} ORDER BY id") + self.cursor.execute(f"SELECT run_id FROM {self.prefix}_runs ORDER BY id") else: - self.cursor.execute(f"SELECT run_id FROM {self.table} WHERE state = ? ORDER BY id", (str(state),)) + self.cursor.execute(f"SELECT run_id FROM {self.prefix}_runs WHERE state = ? ORDER BY id", (str(state),)) return [row[0] for row in self.cursor.fetchall()] def close(self) -> None: self.cursor.close() self.conn.close() + + +class MariaDBRun(RunHandle): + """A run's rows, locked by the transaction of the edit that yields it; each change is one statement.""" + + def __init__(self, store: MariaDBStore, run_id: str, id: int, state: State): + """ + :param store: The store whose transaction holds the run + :param run_id: The run's id + :param id: The run's ``id`` in ``_runs``, which its list rows name as ``run`` + :param state: The run's state when the edit began + """ + self.store = store + self.run_id = run_id + self.id = id + self.state = state + + def update(self, **values): + columns = {} + for name, value in values.items(): + if name in PARTS: + columns |= {f"{name}_{item.name}": getattr(value, item.name) if value else None for item in fields(PARTS[name])} + else: + columns[name] = value + columns = _columns(columns) + self.store.cursor.execute( + f"UPDATE {self.store.prefix}_runs SET {', '.join(f'`{name}` = ?' for name in columns)} WHERE id = ?", + (*columns.values(), self.id), + ) + self.state = values.get("state", self.state) + + def add(self, kind: str, row, replace: bool = False): + activity = row.activity if isinstance(row, (Usage, Generation)) else None + if activity is not None: + self.store.cursor.execute(f"SELECT 1 FROM {self.store.prefix}_activities WHERE run = ? AND id = ?", (self.id, activity)) + if self.store.cursor.fetchone() is None: + raise ValueError(f"run '{self.run_id}' has no activity '{activity}' -- add it to the run first") + values = asdict(row) + values = _columns({**values.pop("file", {}), **values}) + if kind == "metrics": + values["is_integer"] = isinstance(values["value"], int) + names = ", ".join(f"`{name}`" for name in values) + statement = f"INSERT INTO {self.store.prefix}_{kind} (run, {names}) VALUES (?{', ?' * len(values)})" + if replace: + statement += " ON DUPLICATE KEY UPDATE " + ", ".join(f"`{name}` = VALUE(`{name}`)" for name in values) + try: + self.store.cursor.execute(statement, (self.id, *values.values())) + except mariadb.IntegrityError as error: + raise ValueError(f"run '{self.run_id}' already has {KEYS[kind](row)} among its {kind} -- each is logged once") from error + + def add_metric(self, name: str, value: float, step: int | None = None, time: datetime | None = None): + if step is None: + self.store.cursor.execute( + f"SELECT COALESCE(MAX(step) + 1, 0) FROM {self.store.prefix}_metrics WHERE run = ? AND name = ?", + (self.id, name), + ) + step = int(self.store.cursor.fetchone()[0]) + self.add("metrics", Metric(name, step, value, time), replace=True) + + +def _columns(values: dict) -> dict: + """Values as columns hold them: times in UTC without a zone, enums as text, no NULL in a unique key.""" + columns = {} + for name, value in values.items(): + if isinstance(value, datetime): + value = value.astimezone(UTC).replace(tzinfo=None) + elif isinstance(value, Enum): + value = str(value) + elif value is None and name in KEY_TEXT: + value = "" + columns[name] = value + return columns + + +def _row[T](cls: type[T], columns: dict) -> T: + """A row of the record, from the columns ``_columns`` wrote.""" + values: dict[str, Any] = {} + for name, value in columns.items(): + if isinstance(value, datetime): + value = value.replace(tzinfo=UTC) + elif value == "" and name in KEY_TEXT: + value = None + if name != "run": + values[name] = value + if cls is RunRecord: + # The table key; a list row's ``id`` is data, e.g. an agent's IRI. + values.pop("id") + for name, part in PARTS.items(): + kept = {item.name: values.pop(f"{name}_{item.name}") for item in fields(part)} + values[name] = part(**kept) if any(value is not None for value in kept.values()) else None + values["state"], values["verdict"] = State(values["state"]), Verdict(values["verdict"]) + if cls in (Usage, Generation): + values["file"] = FileRef(**{item.name: values.pop(item.name) for item in fields(FileRef)}) + if cls is Metric: + is_integer = values.pop("is_integer") + values["value"] = int(values["value"]) if is_integer else values["value"] + return cls(**values) diff --git a/tests/test_mariadb_store.py b/tests/test_mariadb_store.py index 5d0beb8..a2ba126 100644 --- a/tests/test_mariadb_store.py +++ b/tests/test_mariadb_store.py @@ -3,13 +3,14 @@ from uuid import uuid4 import pytest +from rdflib.compare import isomorphic pytest.importorskip("mariadb", reason="the MariaDB driver is an optional extra") -from rec import State, Verdict # noqa: E402 +from rec import State, Verdict, provenance # noqa: E402 from rec.observer import Observer # noqa: E402 from rec.run import Run # noqa: E402 from rec.stores.file_store import FileStore # noqa: E402 -from rec.stores.mariadb_store import MariaDBStore # noqa: E402 +from rec.stores.mariadb_store import TABLES, MariaDBStore # noqa: E402 TEST_DATABASE = os.getenv("REC_TEST_MARIADB_DATABASE") pytestmark = pytest.mark.skipif( @@ -20,10 +21,10 @@ @pytest.fixture def store(): - table = f"rec_test_{uuid4().hex}" - db = MariaDBStore(db_name=TEST_DATABASE, table=table) + prefix = f"rec_test_{uuid4().hex}" + db = MariaDBStore(db_name=TEST_DATABASE, prefix=prefix) yield db - db.cursor.execute(f"DROP TABLE IF EXISTS {table}") + db.cursor.execute(f"DROP TABLE IF EXISTS {', '.join(f'{prefix}_{kind}' for kind in TABLES)}, {prefix}_runs") db.close() @@ -34,22 +35,39 @@ def main(self): return "ok" -def test_a_row_keeps_the_whole_record(store, tmp_path): +def test_the_tables_keep_the_whole_record(store, tmp_path): files = FileStore(tmp_path, fmt="json") runs = [QuickRun(observers=[Observer(store), Observer(files)], run_id=f"run-{i}") for i in range(3)] for run in runs: run.beat_interval = 0 run.run() for run in runs: - assert store.load(run.id) == files.load(run.id) - # The state and verdict columns are the record's, to query runs by. - store.cursor.execute(f"SELECT state, verdict FROM {store.table} WHERE run_id = 'run-0'") + from_tables, from_json = store.load(run.id), files.load(run.id) + assert from_tables is not None and from_json is not None + assert isomorphic(provenance.graph(from_tables), provenance.graph(from_json)) + store.cursor.execute(f"SELECT state, verdict FROM {store.prefix}_runs WHERE run_id = 'run-0'") assert store.cursor.fetchone() == ("complete", "passed") + # A metric is a row of its own, its int kept an int. + store.cursor.execute(f"SELECT name, step, value, is_integer FROM {store.prefix}_metrics") + assert store.cursor.fetchall() == [("frames", 0, 1.0, 1)] * 3 + assert store.load("run-0").metrics[0].value == 1 and isinstance(store.load("run-0").metrics[0].value, int) assert store.run_ids(State.COMPLETE) == ["run-0", "run-1", "run-2"] +def test_the_tables_refuse_a_file_of_an_unknown_step(store): + observer = Observer(store) + observer.add_activity("run-a", "https://example.org/step", "Execution", "https://example.org/agent", datetime.now(UTC)) + observer.add_resource("run-a", "config.yaml", usage_activity="https://example.org/step") + with pytest.raises(ValueError, match="has no activity"): + observer.add_artefact("run-a", "out.csv", gen_activity="https://example.org/missing") + record = store.load("run-a") + assert [activity.id for activity in record.activities] == ["https://example.org/step"] + assert [usage.activity for usage in record.resources] == ["https://example.org/step"] + assert record.artefacts == [] + + def test_a_queued_run_is_cancelled_by_id(store): QuickRun(observers=[Observer(store)], run_id="queued").queue() assert store.run_ids(State.IN_PROGRESS) == [] - Observer(MariaDBStore(db_name=TEST_DATABASE, table=store.table)).log_cancelled_run("queued", datetime.now(UTC)) + Run(observers=[Observer(MariaDBStore(db_name=TEST_DATABASE, prefix=store.prefix))], run_id="queued").cancel() assert (store.load("queued").state, store.load("queued").verdict) == (State.CANCELED, Verdict.UNAVAILABLE) diff --git a/tests/test_run.py b/tests/test_run.py index a3c1afe..e861d28 100644 --- a/tests/test_run.py +++ b/tests/test_run.py @@ -7,11 +7,13 @@ from pyshacl import validate from rdf_utils.models.prov import _path_from_file_url, resolve_location from rdflib import Graph, Literal, URIRef -from rdflib.namespace import PROV, RDF, RDFS, SDO +from rdflib.compare import isomorphic +from rdflib.namespace import DCTERMS, PROV, RDF, RDFS, SDO from rec import State, Verdict, provenance from rec.observer import Observer from rec.provenance import OSLC_AUTO, PROV_EXT, REC +from rec.record import RunRecord from rec.run import Run from rec.stores.file_store import FileStore @@ -24,16 +26,19 @@ class CalibrationRun(Run): def main(self): self.add_agent("https://example.org/agent/calibrator", "SoftwareAgent", name="calibrator") - self.log_sources([{"path": "model.ld.json", "sha256": "deadbeef", "size_bytes": 4}]) self.log_repositories([{"name": "controller", "url": "https://example.org/lab/controller", "commit": "0123abcd"}]) self.log_dependencies([{"name": "rdflib", "version": "7.7.0"}]) + calibration, verification = "https://example.org/calibration/1", "https://example.org/verification/1" + now = datetime.now(UTC) + self.add_activity(calibration, "Execution", "https://example.org/agent/calibrator", now, now) + self.add_activity(verification, "Assurance", "https://example.org/agent/calibrator", now, now) # One file used by two activities whose IRIs end in the same segment. - self.add_resource("config/robot.yaml", usage_activity="https://example.org/calibration/1") - self.add_resource("config/robot.yaml", usage_activity="https://example.org/verification/1") + self.add_resource("config/robot.yaml", usage_activity=calibration) + self.add_resource("config/robot.yaml", usage_activity=verification) # A path with spaces and '%', an IRI, and a path relative to where it is logged. self.add_artefact("/tmp/rec data/50% done.json") self.add_artefact("https://example.org/data/scan.bag") - self.add_artefact("results/calibration.json", sha256="deadbeef", size_bytes=4) + self.add_artefact("results/calibration.json", gen_activity=verification, sha256="deadbeef", size_bytes=4) self.log_scalar("position-error", 0.5) self.log_scalar("position-error", 0.3) return "calibrated" @@ -49,6 +54,15 @@ def main(self): raise KeyboardInterrupt +class StoppedRun(Run): + def main(self): + # A scheduler holding only the id asks the run to stop while it is in progress. + Run(observers=[Observer(self.observers[0].store)], run_id=self.id).cancel() + if self.state is State.CANCELING: + return "stopped" + return "finished" + + @pytest.fixture(params=["json", "rdf"]) def store(request, tmp_path): return FileStore(tmp_path / request.param, fmt=request.param) @@ -87,8 +101,9 @@ def test_a_record_is_the_same_in_every_store(tmp_path, monkeypatch): run = CalibrationRun(observers=[Observer(as_json), Observer(as_rdf)], run_id="run-1") run.beat_interval = 0 run.run() - # The run logged its lists in the order a graph reads them back. - assert as_rdf.load("run-1") == as_json.load("run-1") + from_rdf, from_json = as_rdf.load("run-1"), as_json.load("run-1") + assert from_rdf is not None and from_json is not None + assert isomorphic(provenance.graph(from_rdf), provenance.graph(from_json)) def test_a_queued_run_has_not_executed_yet(store): @@ -145,22 +160,12 @@ def test_a_run_that_stops_early_records_how(store, cls, verdict, trace): assert ok, report -def test_a_post_run_hook_that_raises_leaves_the_run_passed(store): - def broken_hook(): - raise RuntimeError("hook") - - run = CalibrationRun(observers=[Observer(store)], run_id="run-h", post_run_hooks=[broken_hook]) - run.beat_interval = 0 - with pytest.raises(RuntimeError, match="hook"): - run.run() - assert (store.load("run-h").state, store.load("run-h").verdict) == (State.COMPLETE, Verdict.PASSED) - - def test_only_a_queued_run_is_cancelled(store): queued = CalibrationRun(observers=[Observer(store)], run_id="run-q") queued.queue() - # A scheduler holding only the store cancels a run it did not create, and the store decides. - Observer(store).log_cancelled_run("run-q", datetime.now(UTC)) + # A scheduler holding only the id cancels a run it did not create, and the store decides. + Run(observers=[Observer(store)], run_id="run-q").cancel() + assert queued.state is State.CANCELED with pytest.raises(RuntimeError, match="is canceled"): queued.run() assert (store.load("run-q").state, store.load("run-q").verdict) == (State.CANCELED, Verdict.UNAVAILABLE) @@ -172,12 +177,60 @@ def test_only_a_queued_run_is_cancelled(store): done = CalibrationRun(observers=[Observer(store)], run_id="run-d") done.beat_interval = 0 done.run() - with pytest.raises(RuntimeError, match="only a queued run"): - Observer(store).log_cancelled_run("run-d", datetime.now(UTC)) + with pytest.raises(RuntimeError, match="only a queued run or one in progress"): + Run(observers=[Observer(store)], run_id="run-d").cancel() assert store.load("run-d").verdict is Verdict.PASSED assert store.run_ids(State.CANCELED) == ["run-q"] +def test_a_run_in_progress_stops_when_cancelled(store): + run = StoppedRun(observers=[Observer(store)], run_id="run-s") + run.beat_interval = 0 + assert run.run() == "stopped" + record = store.load("run-s") + assert (record.state, record.verdict, record.result) == (State.CANCELED, Verdict.UNAVAILABLE, "stopped") + assert record.start_time is not None and record.end_time is not None + ok, _, report = validate(provenance.graph(record), shacl_graph=SHAPES, inference="rdfs") + assert ok, report + with pytest.raises(RuntimeError, match="only a queued run or one in progress"): + run.cancel() + + +def test_a_step_is_part_of_its_run(store, tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + run = CalibrationRun(observers=[Observer(store)], run_id="run-a") + run.beat_interval = 0 + run.run() + record = store.load("run-a") + assert {(activity.id, activity.kind) for activity in record.activities} == { + ("https://example.org/calibration/1", "Execution"), + ("https://example.org/verification/1", "Assurance"), + } + g = provenance.graph(record) + node = URIRef(provenance.RUN_BASE + "run-a") + verification = URIRef("https://example.org/verification/1") + assert set(g.subjects(DCTERMS.isPartOf, node)) == {URIRef("https://example.org/calibration/1"), verification} + assert (verification, RDF.type, PROV_EXT.Assurance) in g + assert g.value(verification, PROV.wasAssociatedWith) == URIRef("https://example.org/agent/calibrator") + assert (g.value(verification, PROV.used), RDF.type, PROV.Entity) in g + assert (None, PROV.wasGeneratedBy, verification) in g + + +@pytest.mark.parametrize( + ("method", "args", "message"), + [ + ("add_activity", ("https://example.org/step", "Calibration", "https://example.org/agent", datetime.now(UTC)), "not a prov-extension activity class"), + ("add_resource", ("config.yaml", "https://example.org/missing"), "has no activity"), + ("add_artefact", ("out.csv", "https://example.org/missing"), "has no activity"), + ], + ids=["unknown kind", "resource of an unknown step", "artefact of an unknown step"], +) +def test_a_step_must_be_known_to_its_run(store, method, args, message): + with pytest.raises(ValueError, match=message): + getattr(Observer(store), method)("run-u", *args) + assert store.load("run-u") is None + + def test_logging_a_step_again_replaces_its_value(store): observer = Observer(store) observer.log_scalar("run-m", "error", 0.5, step=1) @@ -185,6 +238,21 @@ def test_logging_a_step_again_replaces_its_value(store): assert [(metric.step, metric.value) for metric in store.load("run-m").metrics] == [(1, 0.1)] +@pytest.mark.parametrize( + ("method", "args"), + [ + ("log_scalar", ("error", float("nan"))), + ("log_scalar", ("error", float("inf"))), + ("log_dependencies", ([{"name": "rdflib"}, {"name": "rdflib"}],)), + ], + ids=["nan metric", "infinite metric", "logged twice"], +) +def test_a_value_every_store_cannot_keep_is_refused_and_nothing_kept(store, method, args): + with pytest.raises(ValueError): + getattr(Observer(store), method)("run-v", *args) + assert store.load("run-v") is None + + def test_one_observer_records_many_runs_at_once(store): """Every run is addressed by its id, and none closes the observer.""" observer = Observer(store) @@ -200,7 +268,9 @@ def test_one_observer_records_many_runs_at_once(store): assert all(len(store.load(run.id).metrics) == 2 for run in runs) -@pytest.mark.parametrize("run_id", ["../escape", "/tmp/escape", "nested/run", "", ".", ".."]) -def test_a_run_id_names_a_file_inside_the_directory(store, run_id): - with pytest.raises(ValueError, match="not a file name"): +@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"): + RunRecord(run_id) + with pytest.raises(ValueError, match="is not a run id"): store.path(run_id) From 09ec234f2fd57a7008be489f9b1099e7a1df710b Mon Sep 17 00:00:00 2001 From: Vamsi Kalagaturu Date: Thu, 12 Nov 2026 14:27:31 +0100 Subject: [PATCH 09/16] Reduce rec to the run lifecycle as a provenance bundle - Write a run as a prov:Bundle attributed to rec's purl, with rdf-utils load_pkg_prov, load_execution_prov and add_wall_instant - Keep the bundle id in the record, minted on the run's first edit - Record the packages a run used as rdf-utils PackageInfo (log_packages), replacing repositories and dependencies - Drop agents, activities, resources, artefacts, metrics, program, trigger and result: tools record their files and steps in their own bundles - FileStore writes any rdf-utils DatasetFormat; drop the JSON record format - MariaDB keeps runs and packages tables, the recorder flagged - Keep queue, cancel and heartbeat --- README.md | 140 +++++---------- examples/all_stores_run.py | 23 ++- examples/file_store_run.py | 25 ++- examples/mariadb_store_run.py | 10 +- rec/observer.py | 123 +++---------- rec/provenance.py | 322 ++++++++-------------------------- rec/record.py | 175 ++---------------- rec/run.py | 140 ++------------- rec/stores/__init__.py | 22 +-- rec/stores/file_store.py | 44 ++--- rec/stores/mariadb.sql | 90 +--------- rec/stores/mariadb_store.py | 157 +++++++---------- tests/test_mariadb_store.py | 47 +++-- tests/test_run.py | 164 +++++------------ 14 files changed, 346 insertions(+), 1136 deletions(-) diff --git a/README.md b/README.md index 16e37a8..cacfbe2 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,9 @@ # Robot Execution Catalog (REC) REC makes the data of robot executions [FAIR](https://www.go-fair.org/fair-principles/): it records -each run's provenance in [PROV](https://www.w3.org/TR/prov-o/), on the -[rec and prov-extension vocabularies](https://secorolab.github.io/metamodels/). +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 @@ -13,9 +14,11 @@ pip install -e ".[mariadb]" # and the MariaDB store ## Recording a run -A run is a `Run` subclass; `main` does the work and logs what it uses and generates. +A run is a `Run` subclass; `main` does the work and logs the software packages it uses. ```python +from rdf_utils.models.prov import get_py_pkg_info + from rec.observer import Observer from rec.run import Run from rec.stores.file_store import FileStore @@ -23,11 +26,7 @@ from rec.stores.file_store import FileStore class PickPlaceRun(Run): def main(self): - self.add_agent("https://example.org/agent/arm", "Agent", name="arm") - self.log_repositories([{"name": "controller", "url": "https://example.org/lab/controller", "commit": "0123abcd"}]) - self.add_resource("config/robot.yaml") - self.add_artefact("results/trajectory.csv") - self.log_scalar("final-position-error", 0.004) + self.log_packages([get_py_pkg_info("controller")]) return "placed" @@ -36,21 +35,12 @@ PickPlaceRun(observers=[observer], run_id="pick-place-1").run() observer.close() ``` -`run()` records the start, runs `main`, and ends the run as `passed`, `failed` (`main` raised) or -`error` (interrupted). What `main` returns is kept as the run's result. - -### Steps of a run - -A step is an activity of a prov-extension kind (`Execution`, `Assurance`, `Transformation`, -`Generalization`, `Specification`) that is `dcterms:isPartOf` the run. Files name the step that -used or generated them: +`run()` records the start and the host, runs `main`, and ends the run as `passed`, `failed` +(`main` raised) or `error` (interrupted). It returns what `main` returned; rec does not record it. -```python -calibration = "https://example.org/calibration/1" -self.add_activity(calibration, "Execution", "https://example.org/agent/arm", start, end) -self.add_resource("config/robot.yaml", usage_activity=calibration) -self.add_artefact("results/calibration.json", gen_activity=calibration) -``` +Files a run 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 @@ -70,103 +60,55 @@ Run(observers=[Observer(MariaDBStore())], run_id="drawer-2").cancel() | anything else | `RuntimeError` | The store decides every step under a lock (`flock` for files, `SELECT ... FOR UPDATE` for -MariaDB): only a new run is queued, only a new or queued run starts. +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`. ## Stores | Store | Keeps a run as | |---|---| -| `FileStore(dir)` | its PROV document, `.ld.json` | -| `FileStore(dir, fmt="json")` | the `RunRecord` as `.json` | -| `MariaDBStore(db_name, prefix)` | a row of `_runs` and a row per list item, see [mariadb.sql](rec/stores/mariadb.sql) | - -All keep the same record. A run may have several observers, one store each: - -```python -stores = [FileStore("runs/prov"), FileStore("runs/json", fmt="json"), MariaDBStore()] -run = ScrewingRun(observers=[Observer(store) for store in stores], run_id="screw-1") -run.run() - -graphs = [provenance.graph(store.load("screw-1")) for store in stores] -assert all(isomorphic(graphs[0], graph) for graph in graphs) -``` - -### One artefact in each store - -```python -self.add_artefact("results/trajectory.csv", sha256="9f86d0...0a08", size_bytes=2048) # logged from /home/lab -``` - -`FileStore(dir)`, `.ld.json` (shown as Turtle; `run:` is `https://secoro.uni-bremen.de/rec/run/`): - -```turtle - - a prov:Entity ; - prov:atLocation [ a prov-ext:RelativeLocation ; - prov-ext:rel-path "results/trajectory.csv"^^xsd:anyURI ; - prov:atLocation ] ; - prov:wasGeneratedBy run:pick-place-1 ; - prov:qualifiedGeneration [ a prov:Generation ; - prov:activity run:pick-place-1 ; - prov:atTime "2026-10-15T09:30:00+00:00"^^xsd:dateTime ] ; - spdx:checksum [ a spdx:Checksum ; - spdx:algorithm spdx:checksumAlgorithm_sha256 ; - spdx:checksumValue "9f86d0...0a08"^^xsd:hexBinary ] ; - dcat:byteSize "2048"^^xsd:nonNegativeInteger . -``` - -`FileStore(dir, fmt="json")`, `.json`: - -```json -"artefacts": [ - { - "file": {"path": "results/trajectory.csv", "root": "/home/lab", "title": null, - "sha256": "9f86d0...0a08", "size_bytes": 2048}, - "activity": null, - "time": "2026-10-15T09:30:00+00:00" - } -] -``` - -`MariaDBStore()`, a row of `logs_artefacts` (`run` is the run's `id` in `logs_runs`; `activity` is -`''` for the run itself): - -| run | path | root | title | sha256 | size_bytes | activity | time | -|---|---|---|---|---|---|---|---| -| 1 | results/trajectory.csv | /home/lab | NULL | 9f86d0...0a08 | 2048 | | 2026-10-15 09:30:00.000000 | +| `FileStore(dir)` | its bundle, `.ld.json`; `fmt=DatasetFormat.TRIG` or `NQUADS` for `.trig`, `.nq` | +| `MariaDBStore(db_name, prefix)` | a row of `_runs` and a row per package in `_packages`, see [mariadb.sql](rec/stores/mariadb.sql) | -A value one store could not give back is refused when logged: a NaN or infinite metric, or an -item logged twice (`rec.record.KEYS`). Any object with `load`, `edit`, `run_ids` and `close` is a -store (`rec.stores.Store`). +A run may have several observers, one store each. Each store names the run's bundle on its first +edit, so two stores hold the same run in differently named bundles. Any object with `load`, +`edit`, `run_ids` and `close` is a store (`rec.stores.Store`). -## The PROV graph +## The PROV bundle ```python from rec import provenance -g = provenance.graph(store.load("pick-place-1")) # RunRecord -> rdflib Graph -record = provenance.record(g, "pick-place-1") # and back +ds = provenance.dataset(store.load("pick-place-1")) # RunRecord -> rdflib Dataset +record = provenance.record(ds, "pick-place-1") # and back ``` -```turtle - - a prov-ext:Execution, oslc_auto:AutomationResult ; - oslc_auto:state oslc_auto:complete ; - oslc_auto:verdict oslc_auto:passed ; - prov:used <.../repository/controller>, ... ; - prov:wasAssociatedWith ; - rec:result "placed" . +```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 ; + prov:used ; + time:hasBeginning ; + time:hasEnd ; + prov:atLocation . +} ``` -A run id is RFC 3986 unreserved characters (letters, digits, `-`, `.`, `_`, `~`); a run given none -gets a UUID. +A package is recorded by rdf-utils' `load_pkg_prov`, named by its purl. A run id is RFC 3986 +unreserved characters (letters, digits, `-`, `.`, `_`, `~`); a run given none gets a UUID. ## Examples ```shell -python examples/file_store_run.py # PROV and JSON files +python examples/file_store_run.py # JSON-LD and TriG files python examples/mariadb_store_run.py # queue, cancel by id, run -python examples/all_stores_run.py # one run in all three stores +python examples/all_stores_run.py # one run in a file and in MariaDB ``` The MariaDB examples need the `mariadb` extra and an `.env` at the repository root: diff --git a/examples/all_stores_run.py b/examples/all_stores_run.py index cebde73..33df299 100644 --- a/examples/all_stores_run.py +++ b/examples/all_stores_run.py @@ -1,8 +1,9 @@ -"""Record one run in all three stores at once -- PROV document, JSON record, MariaDB tables -- and check they give back the same graph. +"""Record one run in a PROV bundle file and in MariaDB tables at once, and check they give back the same run. Needs the `mariadb` extra and the connection settings in `.env` (see the README). """ +from rdf_utils.models.prov import get_py_pkg_info from rdflib.compare import isomorphic from rec import provenance @@ -14,25 +15,21 @@ class ScrewingRun(Run): def main(self): - self.add_agent("https://example.org/agent/arm", "Agent", name="arm") - self.log_dependencies([{"name": "rdflib", "version": "7.6.0"}]) - self.add_resource("config/screw.yaml") - self.add_artefact("results/torque.csv") - # One count per screw: a step per attempt, not per sample. - for screw, attempts in enumerate([1, 2, 1]): - self.log_scalar("attempts", attempts, screw) - self.log_scalar("safety-stops", 0) + self.log_packages([get_py_pkg_info("rdflib")]) return 3 if __name__ == "__main__": - stores = [FileStore("runs/prov"), FileStore("runs/json", fmt="json"), MariaDBStore(db_name="logbook", prefix="logs")] + stores = [FileStore("runs/prov"), MariaDBStore(db_name="logbook", prefix="logs")] observers = [Observer(store) for store in stores] run = ScrewingRun(observers=observers, run_id="screw-1") run.run() - prov, records, tables = (provenance.graph(store.load(run.id)) for store in stores) - assert isomorphic(prov, records) and isomorphic(prov, tables) - print(prov.serialize(format="turtle")) + from_file, from_tables = (store.load(run.id) for store in stores) + # Each store minted its own bundle on the run's first edit. + from_tables.bundle = from_file.bundle + bundle, tables = (provenance.dataset(record).graph(record.bundle) for record in (from_file, from_tables)) + assert isomorphic(bundle, tables) + print(bundle.serialize(format="turtle")) for observer in observers: observer.close() diff --git a/examples/file_store_run.py b/examples/file_store_run.py index 11c745e..00780dc 100644 --- a/examples/file_store_run.py +++ b/examples/file_store_run.py @@ -1,4 +1,7 @@ -"""Record a run as a PROV document and as a JSON record in directories, and read it back.""" +"""Record a run as a PROV bundle in JSON-LD and in TriG, and read it back.""" + +from rdf_utils import DatasetFormat +from rdf_utils.models.prov import get_py_pkg_info from rec.observer import Observer from rec.run import Run @@ -7,26 +10,20 @@ class PickPlaceRun(Run): def main(self): - self.add_agent("https://example.org/agent/arm", "Agent", name="arm") - self.log_repositories([{"name": "controller", "url": "https://example.org/lab/controller", "commit": "0123abcd"}]) - self.log_dependencies([{"name": "rdflib", "version": "7.6.0"}]) - self.add_resource("config/robot.yaml") - self.add_artefact("results/trajectory.csv") - # The value the verdict is judged on; the trajectory itself is the artefact. - self.log_scalar("final-position-error", 0.004) + self.log_packages([get_py_pkg_info("rdflib")]) return "placed" if __name__ == "__main__": - prov = FileStore("runs/prov") - records = FileStore("runs/json", fmt="json") - observers = [Observer(prov), Observer(records)] + as_json_ld = FileStore("runs/prov") + as_trig = FileStore("runs/prov", fmt=DatasetFormat.TRIG) + observers = [Observer(as_json_ld), Observer(as_trig)] run = PickPlaceRun(observers=observers, run_id="pick-place-1") run.run() for observer in observers: observer.close() - print(f"PROV document: {prov.path(run.id)}") - record = records.load(run.id) + print(f"PROV bundle: {as_json_ld.path(run.id)}, {as_trig.path(run.id)}") + record = as_trig.load(run.id) assert record is not None - print(record.state, record.verdict, [(metric.name, metric.step, metric.value) for metric in record.metrics]) + print(record.state, record.verdict, [package.purl for package in record.packages]) diff --git a/examples/mariadb_store_run.py b/examples/mariadb_store_run.py index e5e0071..707ef0f 100644 --- a/examples/mariadb_store_run.py +++ b/examples/mariadb_store_run.py @@ -3,6 +3,8 @@ Needs the `mariadb` extra and the connection settings in `.env` (see the README). """ +from rdf_utils.models.prov import get_py_pkg_info + from rec import State from rec.observer import Observer from rec.run import Run @@ -11,13 +13,9 @@ class DrawerOpeningRun(Run): def main(self): - self.add_agent("https://example.org/agent/dual-arm", "Agent", name="dual-arm") - self.add_resource("config/cabinet.yaml") + self.log_packages([get_py_pkg_info("rdflib")]) if self.state is State.CANCELING: return "stopped" - self.add_artefact("results/drawer-opening.bag") - self.log_scalar("loop-overruns", 0) - self.log_scalar("retries", 1) return "opened" @@ -38,6 +36,6 @@ def main(self): kept.run() record = observer.store.load(kept.id) assert record is not None - print(record.state, record.verdict, [(metric.name, metric.step, metric.value) for metric in record.metrics]) + print(record.state, record.verdict, [package.purl for package in record.packages]) print("canceled:", observer.store.run_ids(State.CANCELED)) observer.close() diff --git a/rec/observer.py b/rec/observer.py index 7f8388f..0986a7d 100644 --- a/rec/observer.py +++ b/rec/observer.py @@ -1,32 +1,17 @@ """Records the events of runs in a store.""" -import os import threading from contextlib import contextmanager from datetime import datetime -from pathlib import Path, PurePath -from urllib.parse import urlsplit +from uuid import uuid4 -from rdf_utils.models.prov import get_pkg_info +from rdf_utils.models.prov import PackageInfo, get_py_pkg_info +from rdflib import URIRef from rec import State, Verdict -from rec.record import ( - Activity, - Agent, - Dependency, - FileRef, - Generation, - Host, - Repository, - Software, - Usage, -) +from rec.record import Host from rec.stores import Store -# PROV-O's agent classes (PROV-O 4.1). -AGENT_TYPES = ("Agent", "SoftwareAgent", "Person", "Organization") -ACTIVITY_KINDS = ("Specification", "Transformation", "Generalization", "Execution", "Assurance") - class Observer: """Records the events of any number of runs in one store; every call names its run. @@ -57,6 +42,9 @@ def _run(self, run_id: str): yield held return with self.store.edit(run_id) as run: + # A run's bundle is named once and attributed to the rec that first recorded it. + if run.bundle is None: + run.update(bundle=URIRef(uuid4().urn), recorder=get_py_pkg_info("rec")) yield run def log_queued_run(self, run_id: str, queued_time: datetime): @@ -66,26 +54,15 @@ def log_queued_run(self, run_id: str, queued_time: datetime): raise RuntimeError(f"run '{run_id}' is {run.state} -- only a new run can be queued") run.update(state=State.QUEUED, verdict=Verdict.UNAVAILABLE, queued_time=queued_time) - def log_started_run(self, run_id: str, started_time: datetime, trigger_entity=None, trigger_generator=None, program=None): - """Record a new or queued run as in progress, with what started it and rec as its recorder. + def log_started_run(self, run_id: str, started_time: datetime): + """Record a new or queued run as in progress. - :param trigger_entity: An entity that triggers the run - :param trigger_generator: The activity that generated the trigger entity - :param program: The file defining the run :raises RuntimeError: The run has already started, or was cancelled """ with self._run(run_id) as run: if run.state not in (State.NEW, State.QUEUED): raise RuntimeError(f"run '{run_id}' is {run.state} -- only a run that has not started can start") - run.update( - state=State.IN_PROGRESS, - verdict=Verdict.UNAVAILABLE, - start_time=started_time, - trigger_entity=trigger_entity, - trigger_generator=trigger_generator, - program=file_ref(program) if program else None, - recorder=Software(*get_pkg_info("rec")), - ) + run.update(state=State.IN_PROGRESS, verdict=Verdict.UNAVAILABLE, start_time=started_time) def log_run_heartbeat(self, run_id: str, beat_time: datetime): """Record that a started run is still alive; raises RuntimeError for any other run.""" @@ -94,12 +71,12 @@ def log_run_heartbeat(self, run_id: str, beat_time: datetime): raise RuntimeError(f"run '{run_id}' is {run.state} -- only a started run beats") run.update(heartbeat_time=beat_time) - def log_completed_run(self, run_id: str, completed_time: datetime, result: str | None = None): - """End a run in progress as passed, or a canceling one as canceled, with what its ``main`` returned. + def log_completed_run(self, run_id: str, completed_time: datetime): + """End a run in progress as passed, or a canceling one as canceled. :raises RuntimeError: The run has not started, or has ended """ - self._end(run_id, completed_time, Verdict.PASSED, result=result) + self._end(run_id, completed_time, Verdict.PASSED) def log_interrupted_run(self, run_id: str, interrupted_time: datetime, fail_trace: str | None = None): """End a run in progress with an error verdict and the trace of what interrupted it.""" @@ -124,81 +101,21 @@ def log_host_info(self, run_id: str, host_info: dict): with self._run(run_id) as run: run.update(host=Host(host_info.get("hostname"), host_info.get("os"), host_info.get("python"), host_info.get("cpu"))) - def log_repositories(self, run_id: str, repositories: list): - """Record repositories, rows with a ``name`` and optionally ``url``, ``commit``; refuses a name twice.""" - with self._run(run_id) as run: - for row in repositories: - run.add("repositories", Repository(row["name"], row.get("url"), row.get("commit"))) - - def log_dependencies(self, run_id: str, dependencies: list): - """Record dependencies, rows with a ``name`` and optionally ``version``; refuses a name twice.""" - with self._run(run_id) as run: - for row in dependencies: - run.add("dependencies", Dependency(row["name"], row.get("version"))) - - def log_scalar(self, run_id: str, metric_name: str, value, step: int | None = None, time: datetime | None = None): - """Record a metric's value at ``step``, or at its next step; a step logged again gets the new value. - - :raises ValueError: The value is NaN or infinite - """ - with self._run(run_id) as run: - run.add_metric(metric_name, value, step, time) - - def add_agent(self, run_id: str, agent_id: str, agent_type: str, name: str | None = None): - """Associate an agent with the run. - - :param agent_type: A PROV-O agent class: ``Agent``, ``SoftwareAgent``, ``Person`` or ``Organization`` - :raises ValueError: The type is not one of those, a software agent has no name, or the agent is already associated - """ - if agent_type not in AGENT_TYPES: - raise ValueError(f"'{agent_type}' is not a PROV agent type -- use one of {list(AGENT_TYPES)}") - if agent_type == "SoftwareAgent" and not name: - raise ValueError(f"'{agent_id}' is a software agent without a name -- the prov-extension shapes require one") + def log_packages(self, run_id: str, packages: list[PackageInfo]): + """Record the software packages the run used, e.g. from rdf-utils `get_py_pkg_info`; refuses a purl twice.""" with self._run(run_id) as run: - run.add("agents", Agent(agent_id, agent_type, name)) - - def add_activity(self, run_id: str, activity_id: str, kind: str, agent_id: str, start_time: datetime, end_time: datetime | None = None): - """Add a step of the run, done by ``agent_id``; a file it used or generated names it as its activity. - - :param kind: A prov-extension activity class: ``Specification``, ``Transformation``, ``Generalization``, - ``Execution`` or ``Assurance`` - :raises ValueError: The kind is not one of those, or the run already has the activity - """ - if kind not in ACTIVITY_KINDS: - raise ValueError(f"'{kind}' is not a prov-extension activity class -- use one of {list(ACTIVITY_KINDS)}") - with self._run(run_id) as run: - run.add("activities", Activity(activity_id, kind, agent_id, start_time, end_time)) - - def add_resource(self, run_id: str, filename, usage_activity=None, usage_time=None, title=None, sha256=None, size_bytes=None): - """Record a file used by ``usage_activity``, or by the run; refuses one file used twice by one activity.""" - with self._run(run_id) as run: - run.add("resources", Usage(file_ref(filename, title, sha256, size_bytes), usage_activity, usage_time)) - - def add_artefact(self, run_id: str, filename, gen_activity=None, generated_time=None, title=None, sha256=None, size_bytes=None): - """Record a file generated by ``gen_activity``, or by the run; refuses a file generated twice.""" - with self._run(run_id) as run: - run.add("artefacts", Generation(file_ref(filename, title, sha256, size_bytes), gen_activity, generated_time)) + for package in packages: + run.add_package(package) def close(self): self.store.close() - def _end(self, run_id, end_time, verdict, fail_trace=None, result=None): + def _end(self, run_id, end_time, verdict, fail_trace=None): with self._run(run_id) as run: if run.state is State.CANCELING: # The shapes keep a fail trace for a failed or error verdict only. - run.update(state=State.CANCELED, verdict=Verdict.UNAVAILABLE, end_time=end_time, result=result) + run.update(state=State.CANCELED, verdict=Verdict.UNAVAILABLE, end_time=end_time) elif run.state is State.IN_PROGRESS: - run.update(state=State.COMPLETE, verdict=verdict, end_time=end_time, fail_trace=fail_trace, result=result) + run.update(state=State.COMPLETE, verdict=verdict, end_time=end_time, fail_trace=fail_trace) else: raise RuntimeError(f"run '{run_id}' is {run.state} -- only a started run can end") - - -def file_ref(path, title=None, sha256=None, size_bytes=None) -> FileRef: - """A file as logged: an IRI as given, an absolute path resolved, a relative path from the working directory.""" - path = str(path) - # An IRI's scheme is longer than a drive letter. - if len(urlsplit(path).scheme) > 1: - return FileRef(path, None, title, sha256, size_bytes) - if Path(path).is_absolute(): - return FileRef(str(Path(path).resolve()), None, title, sha256, size_bytes) - return FileRef(PurePath(path).as_posix(), os.getcwd(), title, sha256, size_bytes) diff --git a/rec/provenance.py b/rec/provenance.py index c64757b..cabe41d 100644 --- a/rec/provenance.py +++ b/rec/provenance.py @@ -1,46 +1,23 @@ -"""A run record as PROV on the prov-extension and rec vocabularies, and back.""" +"""A run record as a PROV bundle on the prov-extension and rec vocabularies, and back.""" -import json +from datetime import datetime from typing import Any -from urllib.parse import quote, unquote -from rdf_utils.models.prov import ( - _path_from_file_url, - add_activity, - add_agent, - add_entity, - add_file_entity, - add_relative_location, - load_execution_prov, - load_pkg_prov, -) -from rdflib import XSD, Graph, Literal, Namespace, URIRef -from rdflib.namespace import DCAT, DCTERMS, PROV, RDF, RDFS, SDO +from rdf_utils import DatasetFormat +from rdf_utils.models.prov import PackageInfo, load_execution_prov, load_pkg_prov +from rdf_utils.models.time import add_wall_instant +from rdf_utils.models.vocab import URI_SPDX_SW_TYPE_PACKAGE +from rdflib import XSD, Dataset, Graph, Literal, Namespace, URIRef +from rdflib.namespace import PROV, RDF, SDO, TIME from rdflib.term import Node from rec import State, Verdict -from rec.record import ( - Activity, - Agent, - Dependency, - FileRef, - Generation, - Host, - Metric, - Repository, - RunRecord, - Software, - Usage, -) +from rec.record import Host, RunRecord RUN_BASE = "https://secoro.uni-bremen.de/rec/run/" 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#") -SPDX = Namespace("http://spdx.org/rdf/terms#") -QUDT = Namespace("http://qudt.org/schema/qudt/") -DIMENSIONLESS = URIRef("http://qudt.org/vocab/quantitykind/Dimensionless") -UNITLESS = URIRef("http://qudt.org/vocab/unit/UNITLESS") STATES = { State.NEW: OSLC_AUTO.new, @@ -63,22 +40,26 @@ "prov-ext": PROV_EXT, "rec": REC, "oslc_auto": OSLC_AUTO, - "spdx": SPDX, - "dcat": DCAT, - "dcterms": DCTERMS, "schema": SDO, - "qudt": QUDT, - "rdfs": RDFS, + "time": TIME, "xsd": XSD, } -def graph(record: RunRecord, base: str = RUN_BASE) -> Graph: - """The run as a `prov-ext:Execution` and an `oslc_auto:AutomationResult` with its state and verdict; - once started, of its program by the software that recorded it.""" - g = Graph() +def dataset(record: RunRecord, base: str = RUN_BASE) -> Dataset: + """The run in its bundle, attributed to its recorder: a `prov-ext:Execution` and an + `oslc_auto:AutomationResult` with its state and verdict; once started, of the packages it used + by its recorder.""" + ds = Dataset() for prefix, namespace in PREFIXES.items(): - g.bind(prefix, namespace) + ds.bind(prefix, namespace) + g = ds.graph(record.bundle) + # The bundle's id is kept in the record, so these are rdf-utils `create_bundle`'s triples + # under an id minted once rather than on every write. + g.add((record.bundle, RDF.type, PROV.Bundle)) + g.add((record.bundle, PROV.wasAttributedTo, record.recorder.purl)) + load_pkg_prov(g, record.recorder) + run = URIRef(base + record.run_id) g.add((run, RDF.type, PROV_EXT.Execution)) g.add((run, RDF.type, OSLC_AUTO.AutomationResult)) @@ -89,74 +70,25 @@ def graph(record: RunRecord, base: str = RUN_BASE) -> Graph: g.add((run, predicate, Literal(value))) if record.fail_trace: g.add((run, REC["fail-trace"], Literal(record.fail_trace, datatype=XSD.string))) - if record.result is not None: - g.add((run, REC.result, Literal(record.result, datatype=XSD.string))) - - used = [] - for row in record.repositories: - repository = URIRef(f"{run}/repository/{quote(row.name, safe='')}") - add_entity(g, repository) - g.add((repository, RDF.type, SDO.SoftwareSourceCode)) - g.add((repository, RDFS.label, Literal(row.name))) - if row.commit: - g.add((repository, SDO.identifier, Literal(row.commit))) - if row.url: - g.add((repository, SDO.codeRepository, URIRef(row.url))) - used.append(repository) - for row in record.dependencies: - dependency = URIRef(f"{run}/dependency/{quote(row.name, safe='')}") - add_entity(g, dependency) - g.add((dependency, RDF.type, SDO.SoftwareApplication)) - g.add((dependency, RDFS.label, Literal(row.name))) - if row.version: - g.add((dependency, SDO.softwareVersion, Literal(row.version))) - used.append(dependency) - for usage in record.resources: - entity = _file(g, run, usage.file) - activity = URIRef(usage.activity or run) - node = URIRef(f"{entity}/usage/{quote(str(activity), safe='')}") - g.add((node, RDF.type, PROV.Usage)) - g.add((node, PROV.entity, entity)) - if usage.time: - g.add((node, PROV.atTime, Literal(usage.time))) - g.add((activity, RDF.type, PROV.Activity)) - g.add((activity, PROV.used, entity)) - g.add((activity, PROV.qualifiedUsage, node)) - if record.start_time and record.recorder: - software = URIRef(f"{run}/software") - load_pkg_prov(g, software, record.recorder.name, record.recorder.version, record.recorder.commit, record.recorder.repository) - association = URIRef(f"{run}/association") - g.add((run, PROV.qualifiedAssociation, association)) - g.add((association, RDF.type, PROV.Association)) - g.add((association, PROV.agent, software)) - if record.program: - plan = _file(g, run, record.program) - g.add((plan, RDF.type, PROV.Plan)) - g.add((association, PROV.hadPlan, plan)) - used.append(plan) - load_execution_prov(g, run, used, software, record.start_time, record.end_time) + for package in record.packages: + load_pkg_prov(g, package) + used = [package.purl for package in record.packages] + ended = None + if record.end_time: + ended = URIRef(f"{run}/end") + add_wall_instant(g, ended, record.end_time) + if record.start_time: + started = URIRef(f"{run}/beginning") + add_wall_instant(g, started, record.start_time) + load_execution_prov(g, run, used, record.recorder.purl, started, ended) else: - for entity in used: - g.add((run, PROV.used, entity)) - if record.end_time: - g.add((run, PROV.endedAtTime, Literal(record.end_time))) - for agent in record.agents: - add_agent(g, URIRef(agent.id), (PROV[agent.type],), agent.name) - g.add((run, PROV.wasAssociatedWith, URIRef(agent.id))) - # PROV has no part-whole relation between activities. - for activity in record.activities: - add_activity(g, URIRef(activity.id), (PROV_EXT[activity.kind],), (), URIRef(activity.agent), activity.start_time, activity.end_time) - g.add((URIRef(activity.id), DCTERMS.isPartOf, run)) + # A queued run cancelled before it started: it has an end, but no beginning or recorder. + for purl in used: + g.add((run, PROV.used, purl)) + if ended is not None: + g.add((run, TIME.hasEnd, ended)) - if record.trigger_entity: - start = URIRef(f"{run}/start") - g.add((run, PROV.wasStartedBy, URIRef(record.trigger_entity))) - g.add((run, PROV.qualifiedStart, start)) - g.add((start, RDF.type, PROV.Start)) - g.add((start, PROV.entity, URIRef(record.trigger_entity))) - if record.trigger_generator: - g.add((start, PROV.hadActivity, URIRef(record.trigger_generator))) if record.host: host = URIRef(f"{run}/host") g.add((host, RDF.type, REC.Host)) @@ -165,170 +97,51 @@ def graph(record: RunRecord, base: str = RUN_BASE) -> Graph: if getattr(record.host, key): g.add((host, predicate, Literal(getattr(record.host, key)))) g.add((run, PROV.atLocation, host)) + return ds - for generation in record.artefacts: - entity = _file(g, run, generation.file) - activity = URIRef(generation.activity or run) - node = URIRef(f"{entity}/generation/{quote(str(activity), safe='')}") - g.add((activity, RDF.type, PROV.Activity)) - g.add((entity, PROV.wasGeneratedBy, activity)) - g.add((entity, PROV.qualifiedGeneration, node)) - g.add((node, RDF.type, PROV.Generation)) - g.add((node, PROV.activity, activity)) - if generation.time: - g.add((node, PROV.atTime, Literal(generation.time))) - for metric in record.metrics: - node = URIRef(f"{run}/metric/{quote(metric.name, safe='')}/{metric.step}") - add_entity(g, node) - g.add((node, RDF.type, REC.Metric)) - g.add((node, PROV.wasGeneratedBy, run)) - g.add((node, RDFS.label, Literal(metric.name))) - g.add((node, QUDT.hasQuantityKind, DIMENSIONLESS)) - g.add((node, QUDT.value, Literal(metric.value))) - g.add((node, QUDT.unit, UNITLESS)) - g.add((node, REC.step, Literal(metric.step))) - if metric.time: - g.add((node, PROV.generatedAtTime, Literal(metric.time))) - return g - -def record(g: Graph, run_id: str, base: str = RUN_BASE) -> RunRecord: - """The record ``graph`` wrote; its lists come back in no particular order, a graph having none.""" +def record(ds: Dataset, run_id: str, base: str = RUN_BASE) -> RunRecord: + """The record ``dataset`` wrote; its packages come back in no particular order, a graph having none.""" run = URIRef(base + run_id) - association = g.value(run, PROV.qualifiedAssociation) - plan, software = g.value(association, PROV.hadPlan), g.value(association, PROV.agent) - start = g.value(run, PROV.qualifiedStart) + g = next(graph for graph in ds.graphs() if (run, OSLC_AUTO.state, None) in graph) host = g.value(run, PROV.atLocation) - # Only what links to this run, or what graph() named under its IRI: the graph may hold other runs. - own = f"{run}/" return RunRecord( run_id=run_id, + bundle=g.identifier, state=next(state for state, iri in STATES.items() if iri == g.value(run, OSLC_AUTO.state)), verdict=next(verdict for verdict, iri in VERDICTS.items() if iri == g.value(run, OSLC_AUTO.verdict)), queued_time=_python(g.value(run, REC["queued-time"])), - start_time=_python(g.value(run, PROV.startedAtTime)), - end_time=_python(g.value(run, PROV.endedAtTime)), + start_time=_python(g.value(run, TIME.hasBeginning / TIME.inXSDDateTimeStamp)), + end_time=_python(g.value(run, TIME.hasEnd / TIME.inXSDDateTimeStamp)), heartbeat_time=_python(g.value(run, REC["heartbeat-time"])), fail_trace=_python(g.value(run, REC["fail-trace"])), - result=_python(g.value(run, REC.result)), - program=_file_ref(g, plan) if plan else None, - recorder=Software( - str(g.value(software, SDO.name)), - _python(g.value(software, SDO.softwareVersion)), - _python(g.value(software, SDO.identifier)), - _python(g.value(software, SDO.codeRepository)), - ) - if software - else None, - trigger_entity=_python(g.value(start, PROV.entity)), - trigger_generator=_python(g.value(start, PROV.hadActivity)), + recorder=_package(g, g.value(g.identifier, PROV.wasAttributedTo)), host=Host(**{key: _python(g.value(host, predicate)) for key, predicate in HOST_TERMS.items()}) if host else None, - agents=[ - Agent( - str(agent), - next((str(kind).removeprefix(str(PROV)) for kind in g.objects(agent, RDF.type) if kind != PROV.Agent), "Agent"), - _python(g.value(agent, SDO.name)), - ) - for agent in g.objects(run, PROV.wasAssociatedWith) - if agent != software - ], - activities=[ - Activity( - str(activity), - next(str(kind).removeprefix(str(PROV_EXT)) for kind in g.objects(activity, RDF.type) if str(kind).startswith(str(PROV_EXT))), - str(g.value(activity, PROV.wasAssociatedWith)), - _python(g.value(activity, PROV.startedAtTime)), - _python(g.value(activity, PROV.endedAtTime)), - ) - for activity in g.subjects(DCTERMS.isPartOf, run) - ], - repositories=[ - Repository(str(g.value(node, RDFS.label)), _python(g.value(node, SDO.codeRepository)), _python(g.value(node, SDO.identifier))) - for node in g.objects(run, PROV.used) - if (node, RDF.type, SDO.SoftwareSourceCode) in g - ], - dependencies=[ - Dependency(str(g.value(node, RDFS.label)), _python(g.value(node, SDO.softwareVersion))) - for node in g.objects(run, PROV.used) - if (node, RDF.type, SDO.SoftwareApplication) in g - ], - resources=[ - Usage( - _file_ref(g, entity), - None if activity == run else str(activity), - _python(g.value(usage, PROV.atTime)), - ) - for activity, usage in g.subject_objects(PROV.qualifiedUsage) - if str(usage).startswith(own) - for entity in g.objects(usage, PROV.entity) - ], - artefacts=[ - Generation( - _file_ref(g, entity), - None if g.value(node, PROV.activity) == run else str(g.value(node, PROV.activity)), - _python(g.value(node, PROV.atTime)), - ) - for entity, node in g.subject_objects(PROV.qualifiedGeneration) - if str(node).startswith(own) - ], - metrics=[ - Metric( - str(g.value(node, RDFS.label)), - _python(g.value(node, REC.step)), - _python(g.value(node, QUDT.value)), - _python(g.value(node, PROV.generatedAtTime)), - ) - for node in g.subjects(PROV.wasGeneratedBy, run) - if (node, RDF.type, REC.Metric) in g + packages=[ + _package(g, purl) + for purl in g.objects(run, PROV.used) + if (purl, RDF.type, URI_SPDX_SW_TYPE_PACKAGE) in g ], ) -def document(g: Graph) -> dict: - """The graph as JSON-LD, compacted on the vocabularies' prefixes.""" - return json.loads(g.serialize(format="json-ld", context={prefix: str(ns) for prefix, ns in PREFIXES.items()})) +def serialize(ds: Dataset, fmt: DatasetFormat) -> str: + """The dataset in FMT; JSON-LD compacted on the vocabularies' prefixes.""" + if fmt is DatasetFormat.JSON_LD: + return ds.serialize(format=fmt, context={prefix: str(ns) for prefix, ns in PREFIXES.items()}, indent=2) + return ds.serialize(format=fmt) -def _file(g: Graph, run: URIRef, ref: FileRef) -> URIRef: - # The root is part of the name: one relative path logged from two directories is two files. - if ref.root: - entity = URIRef(f"{run}/file/{quote(ref.root, safe='')}/{quote(ref.path, safe='')}") - else: - entity = URIRef(f"{run}/file/{quote(ref.path, safe='')}") - if ref.root: - location = URIRef(f"{entity}/location") - add_relative_location(g, location, ref.path, ref.root) - else: - location = ref.path - add_file_entity(g, entity, location) - if ref.title: - g.set((entity, RDFS.label, Literal(ref.title))) - if ref.sha256: - checksum = URIRef(f"{entity}/checksum") - g.add((entity, SPDX.checksum, checksum)) - g.add((checksum, RDF.type, SPDX.Checksum)) - g.set((checksum, SPDX.algorithm, SPDX.checksumAlgorithm_sha256)) - g.set((checksum, SPDX.checksumValue, Literal(ref.sha256, datatype=XSD.hexBinary))) - if ref.size_bytes is not None: - g.set((entity, DCAT.byteSize, Literal(ref.size_bytes, datatype=XSD.nonNegativeInteger))) - return entity - - -def _file_ref(g: Graph, entity: Node) -> FileRef: - location = g.value(entity, PROV.atLocation) - rel_path = g.value(location, PROV_EXT["rel-path"]) - if rel_path is not None: - path, root = unquote(str(rel_path)), str(_path_from_file_url(str(g.value(location, PROV.atLocation)))) - else: - path, root = str(_path_from_file_url(str(location))) if str(location).startswith("file:") else str(location), None - # An xsd:hexBinary's Python value is bytes; the record holds the hex text. - checksum = g.value(g.value(entity, SPDX.checksum), SPDX.checksumValue) - return FileRef( - path, - root, - _python(g.value(entity, RDFS.label)), - str(checksum) if checksum is not None else None, - _python(g.value(entity, DCAT.byteSize)), +def _package(g: Graph, purl: Node) -> PackageInfo: + """The package `load_pkg_prov` wrote at PURL; it writes no distribution name or directory.""" + revision = _python(g.value(purl, SDO.identifier)) + return PackageInfo( + name=str(g.value(purl, SDO.name)), + purl=URIRef(purl), + version=_python(g.value(purl, SDO.softwareVersion)), + revision=revision.removesuffix("-dirty") if revision else None, + repository=_python(g.value(purl, SDO.codeRepository)), + dirty=bool(revision and revision.endswith("-dirty")), ) @@ -336,4 +149,7 @@ def _python(term: Node | None) -> Any: """A term as the value the record holds: a literal's Python value, an IRI as its string.""" if term is None: return None + # rdflib maps no Python type to xsd:dateTimeStamp. + if isinstance(term, Literal) and term.datatype == XSD.dateTimeStamp: + return datetime.fromisoformat(str(term)) return term.toPython() if isinstance(term, Literal) else str(term) diff --git a/rec/record.py b/rec/record.py index c2eb809..a1fe79f 100644 --- a/rec/record.py +++ b/rec/record.py @@ -1,114 +1,16 @@ """What rec records of a run, independent of where it is stored.""" -import json -import math import re -from dataclasses import asdict, dataclass, field +from dataclasses import dataclass, field from datetime import datetime +from rdf_utils.models.prov import PackageInfo +from rdflib import URIRef + from rec import State, Verdict # 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._~-]+") -TIMES = ("queued_time", "start_time", "end_time", "heartbeat_time") -# What makes a row of each list one of a kind. -KEYS = { - "agents": lambda agent: agent.id, - "activities": lambda activity: activity.id, - "repositories": lambda row: row.name, - "dependencies": lambda row: row.name, - "resources": lambda row: (row.activity, row.file.path, row.file.root), - # PROV-Constraints, generation-uniqueness: an entity has at most one generation. - "artefacts": lambda row: (row.file.path, row.file.root), - "metrics": lambda row: (row.name, row.step), -} - - -@dataclass -class FileRef: - """A file as logged: an absolute path, an IRI, or a path relative to ``root``.""" - - path: str - root: str | None = None - title: str | None = None - sha256: str | None = None - size_bytes: int | None = None - - -@dataclass -class Usage: - """A file an activity used; the activity is the run itself when None.""" - - file: FileRef - activity: str | None = None - time: datetime | None = None - - -@dataclass -class Generation: - """A file an activity generated; the activity is the run itself when None.""" - - file: FileRef - activity: str | None = None - time: datetime | None = None - - -@dataclass -class Activity: - """A step of the run, ``dcterms:isPartOf`` it; ``kind`` is its prov-extension class, e.g. ``Execution``.""" - - id: str - kind: str - agent: str - start_time: datetime - end_time: datetime | None = None - - -@dataclass -class Agent: - """A PROV agent associated with the run; ``type`` is its PROV-O class, e.g. ``Person``.""" - - id: str - type: str - name: str | None = None - - -@dataclass -class Repository: - name: str - url: str | None = None - commit: str | None = None - - -@dataclass -class Dependency: - name: str - version: str | None = None - - -@dataclass -class Metric: - """A value of the metric ``name`` at ``step``; raises ValueError for a NaN or infinite value.""" - - name: str - step: int - value: float | int - time: datetime | None = None - - def __post_init__(self): - # JSON (RFC 8259) and MariaDB's DOUBLE have no NaN or infinity. - if not math.isfinite(self.value): - raise ValueError(f"metric '{self.name}' is {self.value} -- a metric is finite") - - -@dataclass -class Software: - """The package that recorded the run, as it was when the run started.""" - - name: str - version: str | None = None - commit: str | None = None - repository: str | None = None @dataclass @@ -121,9 +23,14 @@ class Host: @dataclass class RunRecord: - """What rec knows of a run; also what FileStore.edit yields to change it (rec.stores.RunHandle).""" + """What rec knows of a run; also what FileStore.edit yields to change it (rec.stores.RunHandle). + + ``bundle`` names the run's provenance bundle and ``recorder`` is the rec that writes it, both + set on the run's first edit. ``packages`` is the software the run used. + """ run_id: str + bundle: URIRef | None = None state: State = State.NEW verdict: Verdict = Verdict.UNAVAILABLE queued_time: datetime | None = None @@ -131,19 +38,9 @@ class RunRecord: end_time: datetime | None = None heartbeat_time: datetime | None = None fail_trace: str | None = None - result: str | None = None - program: FileRef | None = None - recorder: Software | None = None - trigger_entity: str | None = None - trigger_generator: str | None = None + recorder: PackageInfo | None = None host: Host | None = None - agents: list[Agent] = field(default_factory=list) - activities: list[Activity] = field(default_factory=list) - repositories: list[Repository] = field(default_factory=list) - dependencies: list[Dependency] = field(default_factory=list) - resources: list[Usage] = field(default_factory=list) - artefacts: list[Generation] = field(default_factory=list) - metrics: list[Metric] = field(default_factory=list) + packages: list[PackageInfo] = field(default_factory=list) def __post_init__(self): if not RUN_ID.fullmatch(self.run_id): @@ -153,47 +50,7 @@ def update(self, **values): for name, value in values.items(): setattr(self, name, value) - def add(self, kind: str, row, replace: bool = False): - rows = getattr(self, kind) - key = KEYS[kind](row) - activity = row.activity if isinstance(row, (Usage, Generation)) else None - if activity is not None and all(kept.id != activity for kept in self.activities): - raise ValueError(f"run '{self.run_id}' has no activity '{activity}' -- add it to the run first") - if not replace and any(KEYS[kind](kept) == key for kept in rows): - raise ValueError(f"run '{self.run_id}' already has {key} among its {kind} -- each is logged once") - rows[:] = [*(kept for kept in rows if KEYS[kind](kept) != key), row] - - def add_metric(self, name: str, value: float, step: int | None = None, time: datetime | None = None): - if step is None: - step = max((kept.step for kept in self.metrics if kept.name == name), default=-1) + 1 - self.add("metrics", Metric(name, step, value, time), replace=True) - - -def to_json(record: RunRecord) -> str: - """The record as JSON (RFC 8259, so no NaN or infinity), its times in ISO 8601.""" - return json.dumps(asdict(record), default=datetime.isoformat, allow_nan=False, indent=2) - - -def from_json(text: str) -> RunRecord: - """The record ``to_json`` wrote.""" - data = json.loads(text) - for row in [data, *data.get("activities", []), *data["resources"], *data["artefacts"], *data["metrics"]]: - for key in (*TIMES, "time"): - if row.get(key): - row[key] = datetime.fromisoformat(row[key]) - return RunRecord( - **{key: data[key] for key in ("run_id", "fail_trace", "trigger_entity", "trigger_generator", *TIMES)}, - result=data.get("result"), - state=State(data["state"]), - verdict=Verdict(data["verdict"]), - program=FileRef(**data["program"]) if data["program"] else None, - recorder=Software(**data["recorder"]) if data["recorder"] else None, - host=Host(**data["host"]) if data["host"] else None, - agents=[Agent(**row) for row in data["agents"]], - activities=[Activity(**row) for row in data.get("activities", [])], - repositories=[Repository(**row) for row in data["repositories"]], - dependencies=[Dependency(**row) for row in data["dependencies"]], - resources=[Usage(FileRef(**row["file"]), row["activity"], row["time"]) for row in data["resources"]], - artefacts=[Generation(FileRef(**row["file"]), row["activity"], row["time"]) for row in data["artefacts"]], - metrics=[Metric(**row) for row in data["metrics"]], - ) + def add_package(self, package: PackageInfo): + if any(kept.purl == package.purl for kept in self.packages): + raise ValueError(f"run '{self.run_id}' already has package '{package.purl}' -- each is logged once") + self.packages.append(package) diff --git a/rec/run.py b/rec/run.py index 0a02996..27ac26e 100644 --- a/rec/run.py +++ b/rec/run.py @@ -1,5 +1,4 @@ import datetime -import inspect import logging import platform import socket @@ -9,6 +8,8 @@ from contextlib import ExitStack, contextmanager from uuid import uuid4 +from rdf_utils.models.prov import PackageInfo + from rec import State, Verdict from rec.observer import Observer @@ -100,25 +101,13 @@ def _emit_heartbeat(self): for observer in self.observers: observer.log_run_heartbeat(self.id, beat_time) - def _emit_started(self, trigger_entity=None, trigger_generator=None): - """ - Records the metadata of the starting run - :param trigger_entity: An entity that triggers the run - :param trigger_generator: The activity that generated the trigger entity - """ + def _emit_started(self): + """Record the run as started, on the machine executing it""" start_time = datetime.datetime.now(datetime.UTC) logger.info("Starting run %s", self.id) - - try: - program = inspect.getfile(type(self)) - except (TypeError, OSError): - # A class typed into an interpreter has no file to name. - program = None with self._held(): for observer in self.observers: - observer.log_started_run( - self.id, start_time, trigger_entity=trigger_entity, trigger_generator=trigger_generator, program=program - ) + observer.log_started_run(self.id, start_time) self.log_host_info(host_info()) def _emit_ended(self, error=None): @@ -127,7 +116,7 @@ def _emit_ended(self, error=None): with self._held(): for observer in self.observers: if error is None: - observer.log_completed_run(self.id, end_time, None if self.result is None else str(self.result)) + observer.log_completed_run(self.id, end_time) elif isinstance(error, KeyboardInterrupt): observer.log_interrupted_run(self.id, end_time, _fail_trace(error)) else: @@ -158,14 +147,13 @@ def cancel(self): observer.log_cancelled_run(self.id, cancel_time) logger.info("Cancelled run %s", self.id) - def run(self, trigger_entity=None, trigger_generator=None): + def run(self): """ Start the run, execute ``main`` and record how it ended - :param trigger_entity: An entity that triggers the run - :param trigger_generator: The activity that generated the trigger entity + :returns: What ``main`` returned; rec does not record it :raises RuntimeError: The store holds the run as started or canceled """ - self._emit_started(trigger_entity, trigger_generator) + self._emit_started() failure = None try: # Stopped before the end is recorded: a late beat would find the run ended and raise. @@ -179,121 +167,21 @@ def run(self, trigger_entity=None, trigger_generator=None): self._emit_ended(failure) return self.result - def log_scalar(self, metric_name, value, step: int | None = 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 - """ - now = datetime.datetime.now(datetime.UTC) - for observer in self.observers: - observer.log_scalar(self.id, metric_name, value, step, now) - - def log_repositories(self, repositories: list): - """ - Log the git information of the sources used in this run (url, commit/tag, uncommited changes) - :param repositories: rows with a ``name`` and optionally ``url``, ``commit`` - """ - for observer in self.observers: - observer.log_repositories(self.id, repositories) - - def log_dependencies(self, dependencies: list): - """ - Log the dependencies of the sources used in this run (e.g., package name, version) - :param dependencies: rows with a ``name`` and optionally ``version`` - """ - for observer in self.observers: - observer.log_dependencies(self.id, dependencies) - def log_host_info(self, host_info: dict): """ - Log information about the machine executing this run (e.g., cpu, gpu, OS, user, hostname, python version and venv, env variables, etc.) + Log information about the machine executing this run :param host_info: ``hostname``, ``os``, ``python``, ``cpu``; see :func:`host_info` """ for observer in self.observers: observer.log_host_info(self.id, host_info) - def add_agent(self, agent_id: str, agent_type: str, name: str | None = None): - """ - Add an agent (e.g., a robot) to the run - :param agent_id: A unique ID for this agent - :param agent_type: A PROV agent class: Agent, SoftwareAgent, Person or Organization - :param name: The agent's name; a software agent must have one - """ - for observer in self.observers: - observer.add_agent(self.id, agent_id, agent_type, name) - - def add_activity( - self, - activity_id: str, - kind: str, - agent_id: str, - start_time: datetime.datetime, - end_time: datetime.datetime | None = None, - ): - """ - Add a step of the run (e.g., a calibration) that resources and artefacts can name as their activity - :param activity_id: The activity's IRI - :param kind: A prov-extension activity class: Specification, Transformation, Generalization, Execution or Assurance - :param agent_id: The agent that did it - :param start_time: When it started - :param end_time: When it ended - """ - for observer in self.observers: - observer.add_activity(self.id, activity_id, kind, agent_id, start_time, end_time) - - def add_resource( - self, - filename, - usage_activity=None, - usage_time=None, - title=None, - sha256=None, - size_bytes=None, - ): - """ - Add a resource to the run - - This method only records the filename and minimal metadata. - - :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 sha256: The file's SHA-256 checksum, as hex - :param size_bytes: The file's size - """ - if usage_time is None: - usage_time = datetime.datetime.now(datetime.UTC) - for observer in self.observers: - observer.add_resource(self.id, filename, usage_activity, usage_time, title, sha256, size_bytes) - - def add_artefact( - self, - filename, - gen_activity=None, - generated_time=None, - title=None, - sha256=None, - size_bytes=None, - ): + def log_packages(self, packages: list[PackageInfo]): """ - Add an artefact to the run - - This method only records the filename and minimal metadata. - - :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 sha256: The file's SHA-256 checksum, as hex - :param size_bytes: The file's size + Log the software packages this run used + :param packages: e.g. from rdf-utils ``get_py_pkg_info`` or ``get_ros_pkg_info`` """ - if generated_time is None: - generated_time = datetime.datetime.now(datetime.UTC) for observer in self.observers: - observer.add_artefact(self.id, filename, gen_activity, generated_time, title, sha256, size_bytes) + observer.log_packages(self.id, packages) def _fail_trace(error): diff --git a/rec/stores/__init__.py b/rec/stores/__init__.py index 5faedc7..eb5d1e6 100644 --- a/rec/stores/__init__.py +++ b/rec/stores/__init__.py @@ -1,36 +1,28 @@ """Where run records are kept: any object with these methods is a store.""" from contextlib import AbstractContextManager -from datetime import datetime from typing import Protocol +from rdf_utils.models.prov import PackageInfo +from rdflib import URIRef + from rec import State from rec.record import RunRecord class RunHandle(Protocol): - """A run held by ``Store.edit``: its state, and the changes made to it.""" + """A run held by ``Store.edit``: its state and bundle, and the changes made to it.""" run_id: str state: State + bundle: URIRef | None def update(self, **values) -> None: """Set fields of the run that it has one of, e.g. ``state``, ``start_time`` or ``host``.""" ... - def add(self, kind: str, row, replace: bool = False) -> None: - """Add a row to one of the run's lists, e.g. ``artefacts``. - - Raises ValueError if the list already has a row with the same key - (``rec.record.KEYS``), unless ``replace`` is set. - """ - ... - - def add_metric(self, name: str, value: float, step: int | None = None, time: datetime | None = None) -> None: - """Add a metric's value at ``step``, or after its last step, replacing a value at that step. - - Raises ValueError for a NaN or infinite value. - """ + def add_package(self, package: PackageInfo) -> None: + """Add a package the run used; raises ValueError if the run already has its purl.""" ... diff --git a/rec/stores/file_store.py b/rec/stores/file_store.py index 44195c6..4d460ad 100644 --- a/rec/stores/file_store.py +++ b/rec/stores/file_store.py @@ -1,50 +1,43 @@ """A store keeping each run as one file in a directory.""" import fcntl -import json from contextlib import contextmanager from pathlib import Path -from rdflib import Graph +from rdf_utils import DatasetFormat +from rdflib import Dataset from rec import State, provenance -from rec.record import RUN_ID, RunRecord, from_json, to_json +from rec.record import RUN_ID, RunRecord from rec.stores import Store -# The file each format keeps a run in: its record, or its PROV document. -SUFFIXES = {"json": ".json", "rdf": ".ld.json"} - class FileStore(Store): - def __init__(self, directory, fmt: str = "rdf", base: str = provenance.RUN_BASE): + def __init__(self, directory, fmt: DatasetFormat = DatasetFormat.JSON_LD, base: str = provenance.RUN_BASE): """ :param directory: Where the files go; created on first write - :param fmt: ``rdf`` for the run's PROV document, ``json`` for its record as JSON - :param base: IRI base of the run nodes in a PROV document + :param fmt: The format of the run's provenance bundle, kept as ``.`` + :param base: IRI base of the run nodes """ - if fmt not in SUFFIXES: - raise ValueError(f"'{fmt}' is not a file format -- use one of {list(SUFFIXES)}") self.directory = Path(directory) - self.fmt = fmt + self.fmt = DatasetFormat(fmt) self.base = base def path(self, run_id: str) -> Path: - """Return the run's file, ``.ld.json`` or ``.json`` in the directory. + """Return the run's file, ``.`` in the directory. :raises ValueError: ``run_id`` is not a run id (``rec.record.RUN_ID``) """ # A load comes before any record, and an id like '../x' must not read outside the directory. if not RUN_ID.fullmatch(run_id): raise ValueError(f"'{run_id}' is not a run id -- use letters, digits, '-', '.', '_' or '~', not '.' or '..'") - return self.directory / f"{run_id}{SUFFIXES[self.fmt]}" + return self.directory / f"{run_id}.{self.fmt.extension}" def load(self, run_id: str) -> RunRecord | None: path = self.path(run_id) if not path.exists(): return None - if self.fmt == "json": - return from_json(path.read_text()) - return provenance.record(Graph().parse(path, format="json-ld"), run_id, self.base) + return provenance.record(Dataset().parse(path, format=self.fmt), run_id, self.base) @contextmanager def edit(self, run_id: str): @@ -59,21 +52,12 @@ def edit(self, run_id: str): fcntl.flock(lock, fcntl.LOCK_EX) record = self.load(run_id) or RunRecord(run_id) yield record - self._save(record) - - def _save(self, record: RunRecord) -> None: - if self.fmt == "json": - text = to_json(record) - else: - text = json.dumps(provenance.document(provenance.graph(record, self.base)), indent=2) - self.directory.mkdir(parents=True, exist_ok=True) - path = self.path(record.run_id) - temporary = path.with_name(f"{path.name}.tmp") - temporary.write_text(text + "\n") - temporary.replace(path) + temporary = path.with_name(f"{path.name}.tmp") + temporary.write_text(provenance.serialize(provenance.dataset(record, self.base), self.fmt)) + temporary.replace(path) def run_ids(self, state: State | None = None) -> list[str]: - suffix = SUFFIXES[self.fmt] + suffix = f".{self.fmt.extension}" run_ids = sorted(path.name.removesuffix(suffix) for path in self.directory.glob(f"*{suffix}")) return [run_id for run_id in run_ids if state is None or self.load(run_id).state is state] diff --git a/rec/stores/mariadb.sql b/rec/stores/mariadb.sql index f7bd93b..f147c88 100644 --- a/rec/stores/mariadb.sql +++ b/rec/stores/mariadb.sql @@ -1,6 +1,7 @@ CREATE TABLE IF NOT EXISTS {prefix}_runs ( id INT AUTO_INCREMENT PRIMARY KEY, run_id VARCHAR(255) NOT NULL UNIQUE, + bundle VARCHAR(45), state VARCHAR(20) NOT NULL, verdict VARCHAR(20) NOT NULL, queued_time DATETIME(6), @@ -8,94 +9,21 @@ CREATE TABLE IF NOT EXISTS {prefix}_runs ( end_time DATETIME(6), heartbeat_time DATETIME(6), fail_trace TEXT, - result TEXT, - trigger_entity TEXT, - trigger_generator TEXT, - program_path TEXT, - program_root TEXT, - program_title TEXT, - program_sha256 CHAR(64), - program_size_bytes BIGINT, - recorder_name TEXT, - recorder_version TEXT, - recorder_commit TEXT, - recorder_repository TEXT, host_hostname TEXT, host_os TEXT, host_python TEXT, host_cpu TEXT ); -CREATE TABLE IF NOT EXISTS {prefix}_agents ( +CREATE TABLE IF NOT EXISTS {prefix}_packages ( run INT NOT NULL, - id TEXT NOT NULL, - type VARCHAR(20) NOT NULL, - name TEXT, - UNIQUE (run, id), - FOREIGN KEY (run) REFERENCES {prefix}_runs (id) -); - -CREATE TABLE IF NOT EXISTS {prefix}_activities ( - run INT NOT NULL, - id TEXT NOT NULL, - kind VARCHAR(20) NOT NULL, - agent TEXT NOT NULL, - start_time DATETIME(6) NOT NULL, - end_time DATETIME(6), - UNIQUE (run, id), - FOREIGN KEY (run) REFERENCES {prefix}_runs (id) -); - -CREATE TABLE IF NOT EXISTS {prefix}_repositories ( - run INT NOT NULL, - name VARCHAR(255) NOT NULL, - url TEXT, - `commit` TEXT, - UNIQUE (run, name), - FOREIGN KEY (run) REFERENCES {prefix}_runs (id) -); - -CREATE TABLE IF NOT EXISTS {prefix}_dependencies ( - run INT NOT NULL, - name VARCHAR(255) NOT NULL, + purl VARCHAR(512) NOT NULL, + name TEXT NOT NULL, version TEXT, - UNIQUE (run, name), - FOREIGN KEY (run) REFERENCES {prefix}_runs (id) -); - -CREATE TABLE IF NOT EXISTS {prefix}_resources ( - run INT NOT NULL, - path TEXT NOT NULL, - root TEXT NOT NULL, - title TEXT, - sha256 CHAR(64), - size_bytes BIGINT, - activity TEXT NOT NULL, - time DATETIME(6), - UNIQUE (run, activity, path, root), - FOREIGN KEY (run) REFERENCES {prefix}_runs (id) -); - -CREATE TABLE IF NOT EXISTS {prefix}_artefacts ( - run INT NOT NULL, - path TEXT NOT NULL, - root TEXT NOT NULL, - title TEXT, - sha256 CHAR(64), - size_bytes BIGINT, - activity TEXT NOT NULL, - time DATETIME(6), - UNIQUE (run, path, root), - FOREIGN KEY (run) REFERENCES {prefix}_runs (id) -); - -CREATE TABLE IF NOT EXISTS {prefix}_metrics ( - run INT NOT NULL, - name VARCHAR(255) NOT NULL, - step INT NOT NULL, - value DOUBLE NOT NULL, - is_integer BOOL NOT NULL, - time DATETIME(6), - UNIQUE (run, name, step), + revision TEXT, + repository TEXT, + dirty BOOL NOT NULL, + recorder BOOL NOT NULL, + UNIQUE (run, purl, recorder), FOREIGN KEY (run) REFERENCES {prefix}_runs (id) ); diff --git a/rec/stores/mariadb_store.py b/rec/stores/mariadb_store.py index a346a3e..58000fe 100644 --- a/rec/stores/mariadb_store.py +++ b/rec/stores/mariadb_store.py @@ -1,32 +1,25 @@ -"""A store keeping runs in MariaDB tables: a row per run, and a row per item of each of its lists.""" +"""A store keeping runs in MariaDB tables: a row per run, and a row per package it used or was recorded by.""" import os import threading from contextlib import contextmanager -from dataclasses import asdict, fields, is_dataclass +from dataclasses import fields from datetime import UTC, datetime from enum import Enum from importlib.resources import files -from types import UnionType -from typing import Any, get_args, get_origin, get_type_hints import mariadb from dotenv import load_dotenv +from rdf_utils.models.prov import PackageInfo +from rdflib import URIRef from rec import State, Verdict -from rec.record import KEYS, FileRef, Generation, Metric, RunRecord, Usage +from rec.record import Host, RunRecord from rec.stores import RunHandle, Store -# mariadb.sql follows RunRecord: a list field is a table, a dataclass field `_` run columns. -RECORD_FIELDS = get_type_hints(RunRecord) -TABLES = {name: get_args(hint)[0] for name, hint in RECORD_FIELDS.items() if get_origin(hint) is list} -PARTS = { - name: get_args(hint)[0] - for name, hint in RECORD_FIELDS.items() - if get_origin(hint) is UnionType and is_dataclass(get_args(hint)[0]) -} -# Optional columns of a unique key, kept as "" for None: MariaDB's UNIQUE treats NULLs as distinct. -KEY_TEXT = ("root", "activity") +# The columns of `_packages` besides `run` and `recorder`: what `load_pkg_prov` records. +PACKAGE_COLUMNS = ("purl", "name", "version", "revision", "repository", "dirty") +TABLES = ("packages", "runs") class MariaDBStore(Store): @@ -37,8 +30,8 @@ def __init__(self, db_name: str = "logbook", prefix: str = "logs"): :param db_name: Name of the database :param prefix: Prefix of the table names: ``_runs`` has a row per run, ``id`` in the - order runs were added; ``_metrics``, ``_artefacts`` and the other lists - have a row per item, ``run`` naming its run's ``id`` + order runs were added; ``_packages`` has a row per package, ``run`` naming its + run's ``id`` and ``recorder`` set for the rec that recorded it """ load_dotenv() self.db_name = db_name @@ -65,11 +58,25 @@ def load(self, run_id: str) -> RunRecord | None: columns = cursor.fetchone() if columns is None: return None - record = _row(RunRecord, columns) - for kind, cls in TABLES.items(): - cursor.execute(f"SELECT * FROM {self.prefix}_{kind} WHERE run = ?", (columns["id"],)) - setattr(record, kind, [_row(cls, row) for row in cursor.fetchall()]) - return record + cursor.execute(f"SELECT * FROM {self.prefix}_packages WHERE run = ?", (columns["id"],)) + packages = cursor.fetchall() + host = {item.name: columns.pop(f"host_{item.name}") for item in fields(Host)} + times = {name: columns[name].replace(tzinfo=UTC) for name in ("queued_time", "start_time", "end_time", "heartbeat_time") if columns[name]} + by_role = {True: [], False: []} + for row in packages: + values = {name: row[name] for name in PACKAGE_COLUMNS} + by_role[bool(row["recorder"])].append(PackageInfo(**values | {"purl": URIRef(values["purl"]), "dirty": bool(values["dirty"])})) + return RunRecord( + run_id=run_id, + bundle=URIRef(columns["bundle"]) if columns["bundle"] else None, + state=State(columns["state"]), + verdict=Verdict(columns["verdict"]), + fail_trace=columns["fail_trace"], + recorder=next(iter(by_role[True]), None), + host=Host(**host) if any(value is not None for value in host.values()) else None, + packages=by_role[False], + **times, + ) @contextmanager def edit(self, run_id: str): @@ -80,16 +87,16 @@ def edit(self, run_id: str): with self._lock: self.conn.begin() try: - self.cursor.execute(f"SELECT id, state FROM {self.prefix}_runs WHERE run_id = ? FOR UPDATE", (run_id,)) + self.cursor.execute(f"SELECT id, state, bundle FROM {self.prefix}_runs WHERE run_id = ? FOR UPDATE", (run_id,)) row = self.cursor.fetchone() if row is None: new = RunRecord(run_id) self.cursor.execute( - f"INSERT INTO {self.prefix}_runs (run_id, state, verdict) VALUES (?, ?, ?) RETURNING id, state", + f"INSERT INTO {self.prefix}_runs (run_id, state, verdict) VALUES (?, ?, ?) RETURNING id, state, bundle", (new.run_id, str(new.state), str(new.verdict)), ) row = self.cursor.fetchone() - yield MariaDBRun(self, run_id, row[0], State(row[1])) + yield MariaDBRun(self, run_id, row[0], State(row[1]), URIRef(row[2]) if row[2] else None) except BaseException: self.conn.rollback() raise @@ -111,95 +118,51 @@ def close(self) -> None: class MariaDBRun(RunHandle): """A run's rows, locked by the transaction of the edit that yields it; each change is one statement.""" - def __init__(self, store: MariaDBStore, run_id: str, id: int, state: State): + def __init__(self, store: MariaDBStore, run_id: str, id: int, state: State, bundle: URIRef | None): """ :param store: The store whose transaction holds the run :param run_id: The run's id - :param id: The run's ``id`` in ``_runs``, which its list rows name as ``run`` + :param id: The run's ``id`` in ``_runs``, which its package rows name as ``run`` :param state: The run's state when the edit began + :param bundle: The run's bundle when the edit began """ self.store = store self.run_id = run_id self.id = id self.state = state + self.bundle = bundle def update(self, **values): + if "recorder" in values: + self._insert_package(values.pop("recorder"), recorder=True) columns = {} for name, value in values.items(): - if name in PARTS: - columns |= {f"{name}_{item.name}": getattr(value, item.name) if value else None for item in fields(PARTS[name])} + if name == "host": + columns |= {f"host_{item.name}": getattr(value, item.name) if value else None for item in fields(Host)} + elif isinstance(value, datetime): + columns[name] = value.astimezone(UTC).replace(tzinfo=None) + elif isinstance(value, (Enum, URIRef)): + columns[name] = str(value) else: columns[name] = value - columns = _columns(columns) - self.store.cursor.execute( - f"UPDATE {self.store.prefix}_runs SET {', '.join(f'`{name}` = ?' for name in columns)} WHERE id = ?", - (*columns.values(), self.id), - ) + if columns: + self.store.cursor.execute( + f"UPDATE {self.store.prefix}_runs SET {', '.join(f'`{name}` = ?' for name in columns)} WHERE id = ?", + (*columns.values(), self.id), + ) self.state = values.get("state", self.state) + self.bundle = values.get("bundle", self.bundle) - def add(self, kind: str, row, replace: bool = False): - activity = row.activity if isinstance(row, (Usage, Generation)) else None - if activity is not None: - self.store.cursor.execute(f"SELECT 1 FROM {self.store.prefix}_activities WHERE run = ? AND id = ?", (self.id, activity)) - if self.store.cursor.fetchone() is None: - raise ValueError(f"run '{self.run_id}' has no activity '{activity}' -- add it to the run first") - values = asdict(row) - values = _columns({**values.pop("file", {}), **values}) - if kind == "metrics": - values["is_integer"] = isinstance(values["value"], int) - names = ", ".join(f"`{name}`" for name in values) - statement = f"INSERT INTO {self.store.prefix}_{kind} (run, {names}) VALUES (?{', ?' * len(values)})" - if replace: - statement += " ON DUPLICATE KEY UPDATE " + ", ".join(f"`{name}` = VALUE(`{name}`)" for name in values) + def add_package(self, package: PackageInfo): try: - self.store.cursor.execute(statement, (self.id, *values.values())) + self._insert_package(package, recorder=False) except mariadb.IntegrityError as error: - raise ValueError(f"run '{self.run_id}' already has {KEYS[kind](row)} among its {kind} -- each is logged once") from error + raise ValueError(f"run '{self.run_id}' already has package '{package.purl}' -- each is logged once") from error - def add_metric(self, name: str, value: float, step: int | None = None, time: datetime | None = None): - if step is None: - self.store.cursor.execute( - f"SELECT COALESCE(MAX(step) + 1, 0) FROM {self.store.prefix}_metrics WHERE run = ? AND name = ?", - (self.id, name), - ) - step = int(self.store.cursor.fetchone()[0]) - self.add("metrics", Metric(name, step, value, time), replace=True) - - -def _columns(values: dict) -> dict: - """Values as columns hold them: times in UTC without a zone, enums as text, no NULL in a unique key.""" - columns = {} - for name, value in values.items(): - if isinstance(value, datetime): - value = value.astimezone(UTC).replace(tzinfo=None) - elif isinstance(value, Enum): - value = str(value) - elif value is None and name in KEY_TEXT: - value = "" - columns[name] = value - return columns - - -def _row[T](cls: type[T], columns: dict) -> T: - """A row of the record, from the columns ``_columns`` wrote.""" - values: dict[str, Any] = {} - for name, value in columns.items(): - if isinstance(value, datetime): - value = value.replace(tzinfo=UTC) - elif value == "" and name in KEY_TEXT: - value = None - if name != "run": - values[name] = value - if cls is RunRecord: - # The table key; a list row's ``id`` is data, e.g. an agent's IRI. - values.pop("id") - for name, part in PARTS.items(): - kept = {item.name: values.pop(f"{name}_{item.name}") for item in fields(part)} - values[name] = part(**kept) if any(value is not None for value in kept.values()) else None - values["state"], values["verdict"] = State(values["state"]), Verdict(values["verdict"]) - if cls in (Usage, Generation): - values["file"] = FileRef(**{item.name: values.pop(item.name) for item in fields(FileRef)}) - if cls is Metric: - is_integer = values.pop("is_integer") - values["value"] = int(values["value"]) if is_integer else values["value"] - return cls(**values) + def _insert_package(self, package: PackageInfo, recorder: bool): + values = [str(getattr(package, name)) if name == "purl" else getattr(package, name) for name in PACKAGE_COLUMNS] + self.store.cursor.execute( + f"INSERT INTO {self.store.prefix}_packages (run, {', '.join(f'`{name}`' for name in PACKAGE_COLUMNS)}, recorder)" + f" VALUES (?{', ?' * len(PACKAGE_COLUMNS)}, ?)", + (self.id, *values, recorder), + ) diff --git a/tests/test_mariadb_store.py b/tests/test_mariadb_store.py index a2ba126..c3f7774 100644 --- a/tests/test_mariadb_store.py +++ b/tests/test_mariadb_store.py @@ -1,8 +1,9 @@ import os -from datetime import UTC, datetime from uuid import uuid4 import pytest +from rdf_utils.models.prov import PackageInfo +from rdflib import URIRef from rdflib.compare import isomorphic pytest.importorskip("mariadb", reason="the MariaDB driver is an optional extra") @@ -17,6 +18,14 @@ not TEST_DATABASE, reason="set REC_TEST_MARIADB_DATABASE to run MariaDB integration tests", ) +CONTROLLER = PackageInfo( + name="controller", + purl=URIRef("pkg:git/example.org/lab/controller@0123abcd"), + version="1.2.0", + revision="0123abcd", + repository="https://example.org/lab/controller", + dirty=True, +) @pytest.fixture @@ -24,48 +33,38 @@ 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 {', '.join(f'{prefix}_{kind}' for kind in TABLES)}, {prefix}_runs") + db.cursor.execute(f"DROP TABLE IF EXISTS {', '.join(f'{prefix}_{table}' for table in TABLES)}") db.close() class QuickRun(Run): def main(self): - self.add_artefact("/tmp/rec data/50% done.json") - self.log_scalar("frames", 1) + self.log_packages([CONTROLLER]) return "ok" def test_the_tables_keep_the_whole_record(store, tmp_path): - files = FileStore(tmp_path, fmt="json") + files = FileStore(tmp_path) runs = [QuickRun(observers=[Observer(store), Observer(files)], run_id=f"run-{i}") for i in range(3)] for run in runs: run.beat_interval = 0 run.run() for run in runs: - from_tables, from_json = store.load(run.id), files.load(run.id) - assert from_tables is not None and from_json is not None - assert isomorphic(provenance.graph(from_tables), provenance.graph(from_json)) + from_tables, from_file = store.load(run.id), files.load(run.id) + assert from_tables is not None and from_file is not None + # Each store mints its own bundle on the run's first edit; the run inside it is the same. + from_tables.bundle = from_file.bundle + assert isomorphic( + provenance.dataset(from_tables).graph(from_tables.bundle), + provenance.dataset(from_file).graph(from_file.bundle), + ) store.cursor.execute(f"SELECT state, verdict FROM {store.prefix}_runs WHERE run_id = 'run-0'") assert store.cursor.fetchone() == ("complete", "passed") - # A metric is a row of its own, its int kept an int. - store.cursor.execute(f"SELECT name, step, value, is_integer FROM {store.prefix}_metrics") - assert store.cursor.fetchall() == [("frames", 0, 1.0, 1)] * 3 - assert store.load("run-0").metrics[0].value == 1 and isinstance(store.load("run-0").metrics[0].value, int) + store.cursor.execute(f"SELECT name, recorder FROM {store.prefix}_packages ORDER BY run, recorder") + assert store.cursor.fetchall() == [("controller", 0), ("rec", 1)] * 3 assert store.run_ids(State.COMPLETE) == ["run-0", "run-1", "run-2"] -def test_the_tables_refuse_a_file_of_an_unknown_step(store): - observer = Observer(store) - observer.add_activity("run-a", "https://example.org/step", "Execution", "https://example.org/agent", datetime.now(UTC)) - observer.add_resource("run-a", "config.yaml", usage_activity="https://example.org/step") - with pytest.raises(ValueError, match="has no activity"): - observer.add_artefact("run-a", "out.csv", gen_activity="https://example.org/missing") - record = store.load("run-a") - assert [activity.id for activity in record.activities] == ["https://example.org/step"] - assert [usage.activity for usage in record.resources] == ["https://example.org/step"] - assert record.artefacts == [] - - def test_a_queued_run_is_cancelled_by_id(store): QuickRun(observers=[Observer(store)], run_id="queued").queue() assert store.run_ids(State.IN_PROGRESS) == [] diff --git a/tests/test_run.py b/tests/test_run.py index e861d28..3f4f5dc 100644 --- a/tests/test_run.py +++ b/tests/test_run.py @@ -1,14 +1,13 @@ import os import threading -from datetime import UTC, datetime from pathlib import Path import pytest from pyshacl import validate -from rdf_utils.models.prov import _path_from_file_url, resolve_location -from rdflib import Graph, Literal, URIRef -from rdflib.compare import isomorphic -from rdflib.namespace import DCTERMS, PROV, RDF, RDFS, SDO +from rdf_utils import DatasetFormat +from rdf_utils.models.prov import PackageInfo +from rdflib import Graph, URIRef +from rdflib.namespace import PROV, RDF, TIME from rec import State, Verdict, provenance from rec.observer import Observer @@ -21,26 +20,19 @@ SHAPES = Graph() for name in ("prov.shacl.ttl", "prov-extension.shacl.ttl", "rec/rec.shacl.ttl"): SHAPES.parse(METAMODELS / name, format="turtle") +CONTROLLER = PackageInfo( + name="controller", + purl=URIRef("pkg:git/example.org/lab/controller@0123abcd"), + version="1.2.0", + revision="0123abcd", + repository="https://example.org/lab/controller", + dirty=True, +) class CalibrationRun(Run): def main(self): - self.add_agent("https://example.org/agent/calibrator", "SoftwareAgent", name="calibrator") - self.log_repositories([{"name": "controller", "url": "https://example.org/lab/controller", "commit": "0123abcd"}]) - self.log_dependencies([{"name": "rdflib", "version": "7.7.0"}]) - calibration, verification = "https://example.org/calibration/1", "https://example.org/verification/1" - now = datetime.now(UTC) - self.add_activity(calibration, "Execution", "https://example.org/agent/calibrator", now, now) - self.add_activity(verification, "Assurance", "https://example.org/agent/calibrator", now, now) - # One file used by two activities whose IRIs end in the same segment. - self.add_resource("config/robot.yaml", usage_activity=calibration) - self.add_resource("config/robot.yaml", usage_activity=verification) - # A path with spaces and '%', an IRI, and a path relative to where it is logged. - self.add_artefact("/tmp/rec data/50% done.json") - self.add_artefact("https://example.org/data/scan.bag") - self.add_artefact("results/calibration.json", gen_activity=verification, sha256="deadbeef", size_bytes=4) - self.log_scalar("position-error", 0.5) - self.log_scalar("position-error", 0.3) + self.log_packages([CONTROLLER]) return "calibrated" @@ -63,58 +55,48 @@ def main(self): return "finished" -@pytest.fixture(params=["json", "rdf"]) +@pytest.fixture(params=list(DatasetFormat)) def store(request, tmp_path): - return FileStore(tmp_path / request.param, fmt=request.param) + return FileStore(tmp_path, fmt=request.param) -def test_a_completed_run_is_an_execution_of_its_program(store, tmp_path, monkeypatch): - monkeypatch.chdir(tmp_path) +def test_a_completed_run_is_an_execution_by_rec_of_the_packages_it_used(store): run = CalibrationRun(observers=[Observer(store)], run_id="run-1") run.beat_interval = 0 assert run.run() == "calibrated" - g = provenance.graph(store.load("run-1")) + record = store.load("run-1") + g = provenance.dataset(record).graph(record.bundle) ok, _, report = validate(g, shacl_graph=SHAPES, inference="rdfs") assert ok, report node = URIRef(provenance.RUN_BASE + "run-1") assert (node, RDF.type, PROV_EXT.Execution) in g - plan = g.value(g.value(node, PROV.qualifiedAssociation), PROV.hadPlan) - assert _path_from_file_url(str(resolve_location(g, plan))) == Path(__file__).resolve() - assert {str(g.value(agent, SDO.name)) for agent in g.objects(node, PROV.wasAssociatedWith)} == {"rec", "calibrator"} - # A dependency is software the run used, not an agent that ran it. - [dependency] = g.subjects(RDFS.label, Literal("rdflib")) - assert (node, PROV.used, dependency) in g and (dependency, RDF.type, PROV.SoftwareAgent) not in g - artefacts = {str(resolve_location(g, entity)) for entity in g.subjects(PROV.qualifiedGeneration, None)} - assert artefacts == { - "file:///tmp/rec%20data/50%25%20done.json", - "https://example.org/data/scan.bag", - (tmp_path.resolve() / "results/calibration.json").as_uri(), - } - assert len(list(g.subjects(RDF.type, PROV.Usage))) == 2 - assert len(list(g.subjects(RDF.type, REC.Metric))) == 2 - - -def test_a_record_is_the_same_in_every_store(tmp_path, monkeypatch): - monkeypatch.chdir(tmp_path) - as_json, as_rdf = FileStore(tmp_path / "json", fmt="json"), FileStore(tmp_path / "rdf", fmt="rdf") - run = CalibrationRun(observers=[Observer(as_json), Observer(as_rdf)], run_id="run-1") + assert (record.bundle, RDF.type, PROV.Bundle) in g + assert g.value(record.bundle, PROV.wasAttributedTo) == record.recorder.purl == g.value(node, PROV.wasAssociatedWith) + assert record.recorder.name == "rec" + assert record.packages == [CONTROLLER] + assert (node, PROV.used, CONTROLLER.purl) in g + + +def test_a_run_keeps_one_bundle_through_its_lifecycle(store): + run = CalibrationRun(observers=[Observer(store)], run_id="run-b") run.beat_interval = 0 + run.queue() + queued = store.load("run-b").bundle run.run() - from_rdf, from_json = as_rdf.load("run-1"), as_json.load("run-1") - assert from_rdf is not None and from_json is not None - assert isomorphic(provenance.graph(from_rdf), provenance.graph(from_json)) + assert queued is not None and store.load("run-b").bundle == queued def test_a_queued_run_has_not_executed_yet(store): CalibrationRun(observers=[Observer(store)], run_id="run-q").queue() - g = provenance.graph(store.load("run-q")) + record = store.load("run-q") + g = provenance.dataset(record).graph(record.bundle) ok, _, report = validate(g, shacl_graph=SHAPES, inference="rdfs") assert ok, report node = URIRef(provenance.RUN_BASE + "run-q") assert {PROV_EXT.Execution, OSLC_AUTO.AutomationResult} <= set(g.objects(node, RDF.type)) - assert g.value(node, PROV.startedAtTime) is None and g.value(node, PROV.wasAssociatedWith) is None - assert g.value(node, PROV.used) is None and g.value(node, REC["queued-time"]) is not None + assert g.value(node, TIME.hasBeginning) is None and g.value(node, PROV.wasAssociatedWith) is None + assert g.value(node, REC["queued-time"]) is not None # Each starts from a completed run and breaks one rule of the run's shape. @@ -131,12 +113,12 @@ def test_a_queued_run_has_not_executed_yet(store): ], ids=["without a verdict", "queued with a start time", "not an execution", "not an automation result"], ) -def test_the_shapes_refuse_a_run_that_contradicts_its_state(store, tmp_path, monkeypatch, removed, added): - monkeypatch.chdir(tmp_path) +def test_the_shapes_refuse_a_run_that_contradicts_its_state(store, removed, added): run = CalibrationRun(observers=[Observer(store)], run_id="run-x") run.beat_interval = 0 run.run() - g = provenance.graph(store.load("run-x")) + record = store.load("run-x") + g = provenance.dataset(record).graph(record.bundle) node = URIRef(provenance.RUN_BASE + "run-x") for predicate, value in removed: g.remove((node, predicate, value)) @@ -156,7 +138,7 @@ def test_a_run_that_stops_early_records_how(store, cls, verdict, trace): record = store.load("run-3") assert (record.state, record.verdict) == (State.COMPLETE, verdict) assert trace in record.fail_trace - ok, _, report = validate(provenance.graph(record), shacl_graph=SHAPES, inference="rdfs") + ok, _, report = validate(provenance.dataset(record).graph(record.bundle), shacl_graph=SHAPES, inference="rdfs") assert ok, report @@ -168,11 +150,12 @@ def test_only_a_queued_run_is_cancelled(store): assert queued.state is State.CANCELED with pytest.raises(RuntimeError, match="is canceled"): queued.run() - assert (store.load("run-q").state, store.load("run-q").verdict) == (State.CANCELED, Verdict.UNAVAILABLE) - g = provenance.graph(store.load("run-q")) + record = store.load("run-q") + assert (record.state, record.verdict) == (State.CANCELED, Verdict.UNAVAILABLE) + g = provenance.dataset(record).graph(record.bundle) ok, _, report = validate(g, shacl_graph=SHAPES, inference="rdfs") assert ok, report - assert g.value(URIRef(provenance.RUN_BASE + "run-q"), PROV.startedAtTime) is None + assert g.value(URIRef(provenance.RUN_BASE + "run-q"), TIME.hasBeginning) is None done = CalibrationRun(observers=[Observer(store)], run_id="run-d") done.beat_interval = 0 @@ -188,68 +171,17 @@ def test_a_run_in_progress_stops_when_cancelled(store): run.beat_interval = 0 assert run.run() == "stopped" record = store.load("run-s") - assert (record.state, record.verdict, record.result) == (State.CANCELED, Verdict.UNAVAILABLE, "stopped") + assert (record.state, record.verdict) == (State.CANCELED, Verdict.UNAVAILABLE) assert record.start_time is not None and record.end_time is not None - ok, _, report = validate(provenance.graph(record), shacl_graph=SHAPES, inference="rdfs") + ok, _, report = validate(provenance.dataset(record).graph(record.bundle), shacl_graph=SHAPES, inference="rdfs") assert ok, report with pytest.raises(RuntimeError, match="only a queued run or one in progress"): run.cancel() -def test_a_step_is_part_of_its_run(store, tmp_path, monkeypatch): - monkeypatch.chdir(tmp_path) - run = CalibrationRun(observers=[Observer(store)], run_id="run-a") - run.beat_interval = 0 - run.run() - record = store.load("run-a") - assert {(activity.id, activity.kind) for activity in record.activities} == { - ("https://example.org/calibration/1", "Execution"), - ("https://example.org/verification/1", "Assurance"), - } - g = provenance.graph(record) - node = URIRef(provenance.RUN_BASE + "run-a") - verification = URIRef("https://example.org/verification/1") - assert set(g.subjects(DCTERMS.isPartOf, node)) == {URIRef("https://example.org/calibration/1"), verification} - assert (verification, RDF.type, PROV_EXT.Assurance) in g - assert g.value(verification, PROV.wasAssociatedWith) == URIRef("https://example.org/agent/calibrator") - assert (g.value(verification, PROV.used), RDF.type, PROV.Entity) in g - assert (None, PROV.wasGeneratedBy, verification) in g - - -@pytest.mark.parametrize( - ("method", "args", "message"), - [ - ("add_activity", ("https://example.org/step", "Calibration", "https://example.org/agent", datetime.now(UTC)), "not a prov-extension activity class"), - ("add_resource", ("config.yaml", "https://example.org/missing"), "has no activity"), - ("add_artefact", ("out.csv", "https://example.org/missing"), "has no activity"), - ], - ids=["unknown kind", "resource of an unknown step", "artefact of an unknown step"], -) -def test_a_step_must_be_known_to_its_run(store, method, args, message): - with pytest.raises(ValueError, match=message): - getattr(Observer(store), method)("run-u", *args) - assert store.load("run-u") is None - - -def test_logging_a_step_again_replaces_its_value(store): - observer = Observer(store) - observer.log_scalar("run-m", "error", 0.5, step=1) - observer.log_scalar("run-m", "error", 0.1, step=1) - assert [(metric.step, metric.value) for metric in store.load("run-m").metrics] == [(1, 0.1)] - - -@pytest.mark.parametrize( - ("method", "args"), - [ - ("log_scalar", ("error", float("nan"))), - ("log_scalar", ("error", float("inf"))), - ("log_dependencies", ([{"name": "rdflib"}, {"name": "rdflib"}],)), - ], - ids=["nan metric", "infinite metric", "logged twice"], -) -def test_a_value_every_store_cannot_keep_is_refused_and_nothing_kept(store, method, args): - with pytest.raises(ValueError): - getattr(Observer(store), method)("run-v", *args) +def test_a_package_logged_twice_is_refused_and_nothing_kept(store): + with pytest.raises(ValueError, match="each is logged once"): + Observer(store).log_packages("run-v", [CONTROLLER, CONTROLLER]) assert store.load("run-v") is None @@ -265,7 +197,7 @@ def test_one_observer_records_many_runs_at_once(store): for thread in threads: thread.join() assert store.run_ids(State.COMPLETE) == sorted(run.id for run in runs) - assert all(len(store.load(run.id).metrics) == 2 for run in runs) + assert all(store.load(run.id).packages == [CONTROLLER] for run in runs) @pytest.mark.parametrize("run_id", ["../escape", "/tmp/escape", "nested/run", "a run", "läuft", "", ".", ".."]) From 51849aa69d7494d17b0a2383c56e2e332948420d Mon Sep 17 00:00:00 2001 From: Vamsi Kalagaturu Date: Thu, 12 Nov 2026 14:38:57 +0100 Subject: [PATCH 10/16] Type the packages a run used as entities - prov:used takes a prov:Entity; load_pkg_prov types a package as a software agent, spdx package and location only --- rec/provenance.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/rec/provenance.py b/rec/provenance.py index cabe41d..881ddcc 100644 --- a/rec/provenance.py +++ b/rec/provenance.py @@ -4,7 +4,7 @@ from typing import Any from rdf_utils import DatasetFormat -from rdf_utils.models.prov import PackageInfo, load_execution_prov, load_pkg_prov +from rdf_utils.models.prov import PackageInfo, add_entity, load_execution_prov, load_pkg_prov from rdf_utils.models.time import add_wall_instant from rdf_utils.models.vocab import URI_SPDX_SW_TYPE_PACKAGE from rdflib import XSD, Dataset, Graph, Literal, Namespace, URIRef @@ -73,6 +73,8 @@ def dataset(record: RunRecord, base: str = RUN_BASE) -> Dataset: for package in record.packages: load_pkg_prov(g, package) + # A software agent the run used is also an entity (PROV-DM 5.3), as prov:used requires. + add_entity(g, package.purl) used = [package.purl for package in record.packages] ended = None if record.end_time: From ad15a84d7f41bd506961c580a2836e5e70376536 Mon Sep 17 00:00:00 2001 From: Vamsi Kalagaturu Date: Thu, 12 Nov 2026 15:07:04 +0100 Subject: [PATCH 11/16] Leave what a run used to the tool that ran it - Drop packages, log_packages and add_package: the calling tool records the software it ran in its own bundle - Keep rec as the run's recorder; MariaDB keeps it in recorder_* columns of the runs table and drops the packages table - Remove the all-stores example --- README.md | 19 ++++----- examples/all_stores_run.py | 35 ---------------- examples/file_store_run.py | 4 +- examples/mariadb_store_run.py | 5 +-- rec/observer.py | 8 +--- rec/provenance.py | 28 ++++--------- rec/record.py | 10 +---- rec/run.py | 10 ----- rec/stores/__init__.py | 5 --- rec/stores/mariadb.sql | 19 +++------ rec/stores/mariadb_store.py | 77 ++++++++++++++--------------------- tests/test_mariadb_store.py | 15 +------ tests/test_run.py | 21 +--------- 13 files changed, 58 insertions(+), 198 deletions(-) delete mode 100644 examples/all_stores_run.py diff --git a/README.md b/README.md index cacfbe2..e48b920 100644 --- a/README.md +++ b/README.md @@ -14,11 +14,9 @@ pip install -e ".[mariadb]" # and the MariaDB store ## Recording a run -A run is a `Run` subclass; `main` does the work and logs the software packages it uses. +A run is a `Run` subclass; `main` does the work. ```python -from rdf_utils.models.prov import get_py_pkg_info - from rec.observer import Observer from rec.run import Run from rec.stores.file_store import FileStore @@ -26,7 +24,6 @@ from rec.stores.file_store import FileStore class PickPlaceRun(Run): def main(self): - self.log_packages([get_py_pkg_info("controller")]) return "placed" @@ -38,9 +35,9 @@ observer.close() `run()` records the start and the host, runs `main`, and ends the run as `passed`, `failed` (`main` raised) or `error` (interrupted). It returns what `main` returned; rec does not record it. -Files a run 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. +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 @@ -68,7 +65,7 @@ MariaDB): only a new run is queued, only a new or queued run starts. A started r | Store | Keeps a run as | |---|---| | `FileStore(dir)` | its bundle, `.ld.json`; `fmt=DatasetFormat.TRIG` or `NQUADS` for `.trig`, `.nq` | -| `MariaDBStore(db_name, prefix)` | a row of `_runs` and a row per package in `_packages`, see [mariadb.sql](rec/stores/mariadb.sql) | +| `MariaDBStore(db_name, prefix)` | a row of `_runs`, see [mariadb.sql](rec/stores/mariadb.sql) | A run may have several observers, one store each. Each store names the run's bundle on its first edit, so two stores hold the same run in differently named bundles. Any object with `load`, @@ -93,14 +90,13 @@ record = provenance.record(ds, "pick-place-1") # and back oslc_auto:state oslc_auto:complete ; oslc_auto:verdict oslc_auto:passed ; prov:wasAssociatedWith ; - prov:used ; time:hasBeginning ; time:hasEnd ; prov:atLocation . } ``` -A package is recorded by rdf-utils' `load_pkg_prov`, named by its purl. A run id is RFC 3986 +rec is recorded by rdf-utils' `load_pkg_prov`, named by its purl. A run id is RFC 3986 unreserved characters (letters, digits, `-`, `.`, `_`, `~`); a run given none gets a UUID. ## Examples @@ -108,10 +104,9 @@ unreserved characters (letters, digits, `-`, `.`, `_`, `~`); a run given none ge ```shell python examples/file_store_run.py # JSON-LD and TriG files python examples/mariadb_store_run.py # queue, cancel by id, run -python examples/all_stores_run.py # one run in a file and in MariaDB ``` -The MariaDB examples need the `mariadb` extra and an `.env` at the repository root: +The MariaDB example needs the `mariadb` extra and an `.env` at the repository root: ```dotenv MARIADB_USER="user" diff --git a/examples/all_stores_run.py b/examples/all_stores_run.py deleted file mode 100644 index 33df299..0000000 --- a/examples/all_stores_run.py +++ /dev/null @@ -1,35 +0,0 @@ -"""Record one run in a PROV bundle file and in MariaDB tables at once, and check they give back the same run. - -Needs the `mariadb` extra and the connection settings in `.env` (see the README). -""" - -from rdf_utils.models.prov import get_py_pkg_info -from rdflib.compare import isomorphic - -from rec import provenance -from rec.observer import Observer -from rec.run import Run -from rec.stores.file_store import FileStore -from rec.stores.mariadb_store import MariaDBStore - - -class ScrewingRun(Run): - def main(self): - self.log_packages([get_py_pkg_info("rdflib")]) - return 3 - - -if __name__ == "__main__": - stores = [FileStore("runs/prov"), MariaDBStore(db_name="logbook", prefix="logs")] - observers = [Observer(store) for store in stores] - run = ScrewingRun(observers=observers, run_id="screw-1") - run.run() - - from_file, from_tables = (store.load(run.id) for store in stores) - # Each store minted its own bundle on the run's first edit. - from_tables.bundle = from_file.bundle - bundle, tables = (provenance.dataset(record).graph(record.bundle) for record in (from_file, from_tables)) - assert isomorphic(bundle, tables) - print(bundle.serialize(format="turtle")) - for observer in observers: - observer.close() diff --git a/examples/file_store_run.py b/examples/file_store_run.py index 00780dc..3aeebf4 100644 --- a/examples/file_store_run.py +++ b/examples/file_store_run.py @@ -1,7 +1,6 @@ """Record a run as a PROV bundle in JSON-LD and in TriG, and read it back.""" from rdf_utils import DatasetFormat -from rdf_utils.models.prov import get_py_pkg_info from rec.observer import Observer from rec.run import Run @@ -10,7 +9,6 @@ class PickPlaceRun(Run): def main(self): - self.log_packages([get_py_pkg_info("rdflib")]) return "placed" @@ -26,4 +24,4 @@ def main(self): print(f"PROV bundle: {as_json_ld.path(run.id)}, {as_trig.path(run.id)}") record = as_trig.load(run.id) assert record is not None - print(record.state, record.verdict, [package.purl for package in record.packages]) + print(record.state, record.verdict, record.recorder.purl) diff --git a/examples/mariadb_store_run.py b/examples/mariadb_store_run.py index 707ef0f..2092b59 100644 --- a/examples/mariadb_store_run.py +++ b/examples/mariadb_store_run.py @@ -3,8 +3,6 @@ Needs the `mariadb` extra and the connection settings in `.env` (see the README). """ -from rdf_utils.models.prov import get_py_pkg_info - from rec import State from rec.observer import Observer from rec.run import Run @@ -13,7 +11,6 @@ class DrawerOpeningRun(Run): def main(self): - self.log_packages([get_py_pkg_info("rdflib")]) if self.state is State.CANCELING: return "stopped" return "opened" @@ -36,6 +33,6 @@ def main(self): kept.run() record = observer.store.load(kept.id) assert record is not None - print(record.state, record.verdict, [package.purl for package in record.packages]) + print(record.state, record.verdict, record.recorder.purl) print("canceled:", observer.store.run_ids(State.CANCELED)) observer.close() diff --git a/rec/observer.py b/rec/observer.py index 0986a7d..e2cd60a 100644 --- a/rec/observer.py +++ b/rec/observer.py @@ -5,7 +5,7 @@ from datetime import datetime from uuid import uuid4 -from rdf_utils.models.prov import PackageInfo, get_py_pkg_info +from rdf_utils.models.prov import get_py_pkg_info from rdflib import URIRef from rec import State, Verdict @@ -101,12 +101,6 @@ def log_host_info(self, run_id: str, host_info: dict): with self._run(run_id) as run: run.update(host=Host(host_info.get("hostname"), host_info.get("os"), host_info.get("python"), host_info.get("cpu"))) - def log_packages(self, run_id: str, packages: list[PackageInfo]): - """Record the software packages the run used, e.g. from rdf-utils `get_py_pkg_info`; refuses a purl twice.""" - with self._run(run_id) as run: - for package in packages: - run.add_package(package) - def close(self): self.store.close() diff --git a/rec/provenance.py b/rec/provenance.py index 881ddcc..da658fa 100644 --- a/rec/provenance.py +++ b/rec/provenance.py @@ -4,9 +4,8 @@ from typing import Any from rdf_utils import DatasetFormat -from rdf_utils.models.prov import PackageInfo, add_entity, load_execution_prov, load_pkg_prov +from rdf_utils.models.prov import PackageInfo, load_execution_prov, load_pkg_prov from rdf_utils.models.time import add_wall_instant -from rdf_utils.models.vocab import URI_SPDX_SW_TYPE_PACKAGE from rdflib import XSD, Dataset, Graph, Literal, Namespace, URIRef from rdflib.namespace import PROV, RDF, SDO, TIME from rdflib.term import Node @@ -48,8 +47,7 @@ def dataset(record: RunRecord, base: str = RUN_BASE) -> Dataset: """The run in its bundle, attributed to its recorder: a `prov-ext:Execution` and an - `oslc_auto:AutomationResult` with its state and verdict; once started, of the packages it used - by its recorder.""" + `oslc_auto:AutomationResult` with its state and verdict; once started, run by its recorder.""" ds = Dataset() for prefix, namespace in PREFIXES.items(): ds.bind(prefix, namespace) @@ -71,11 +69,6 @@ def dataset(record: RunRecord, base: str = RUN_BASE) -> Dataset: if record.fail_trace: g.add((run, REC["fail-trace"], Literal(record.fail_trace, datatype=XSD.string))) - for package in record.packages: - load_pkg_prov(g, package) - # A software agent the run used is also an entity (PROV-DM 5.3), as prov:used requires. - add_entity(g, package.purl) - used = [package.purl for package in record.packages] ended = None if record.end_time: ended = URIRef(f"{run}/end") @@ -83,13 +76,11 @@ def dataset(record: RunRecord, base: str = RUN_BASE) -> Dataset: if record.start_time: started = URIRef(f"{run}/beginning") add_wall_instant(g, started, record.start_time) - load_execution_prov(g, run, used, record.recorder.purl, started, ended) - else: + # What the run executed is recorded by the tool that knows it, in its own bundle. + load_execution_prov(g, run, (), record.recorder.purl, started, ended) + elif ended is not None: # A queued run cancelled before it started: it has an end, but no beginning or recorder. - for purl in used: - g.add((run, PROV.used, purl)) - if ended is not None: - g.add((run, TIME.hasEnd, ended)) + g.add((run, TIME.hasEnd, ended)) if record.host: host = URIRef(f"{run}/host") @@ -103,7 +94,7 @@ def dataset(record: RunRecord, base: str = RUN_BASE) -> Dataset: def record(ds: Dataset, run_id: str, base: str = RUN_BASE) -> RunRecord: - """The record ``dataset`` wrote; its packages come back in no particular order, a graph having none.""" + """The record ``dataset`` wrote.""" run = URIRef(base + run_id) g = next(graph for graph in ds.graphs() if (run, OSLC_AUTO.state, None) in graph) host = g.value(run, PROV.atLocation) @@ -119,11 +110,6 @@ def record(ds: Dataset, run_id: str, base: str = RUN_BASE) -> RunRecord: fail_trace=_python(g.value(run, REC["fail-trace"])), recorder=_package(g, g.value(g.identifier, PROV.wasAttributedTo)), host=Host(**{key: _python(g.value(host, predicate)) for key, predicate in HOST_TERMS.items()}) if host else None, - packages=[ - _package(g, purl) - for purl in g.objects(run, PROV.used) - if (purl, RDF.type, URI_SPDX_SW_TYPE_PACKAGE) in g - ], ) diff --git a/rec/record.py b/rec/record.py index a1fe79f..822e815 100644 --- a/rec/record.py +++ b/rec/record.py @@ -1,7 +1,7 @@ """What rec records of a run, independent of where it is stored.""" import re -from dataclasses import dataclass, field +from dataclasses import dataclass from datetime import datetime from rdf_utils.models.prov import PackageInfo @@ -26,7 +26,7 @@ class RunRecord: """What rec knows of a run; also what FileStore.edit yields to change it (rec.stores.RunHandle). ``bundle`` names the run's provenance bundle and ``recorder`` is the rec that writes it, both - set on the run's first edit. ``packages`` is the software the run used. + set on the run's first edit. """ run_id: str @@ -40,7 +40,6 @@ class RunRecord: fail_trace: str | None = None recorder: PackageInfo | None = None host: Host | None = None - packages: list[PackageInfo] = field(default_factory=list) def __post_init__(self): if not RUN_ID.fullmatch(self.run_id): @@ -49,8 +48,3 @@ def __post_init__(self): def update(self, **values): for name, value in values.items(): setattr(self, name, value) - - def add_package(self, package: PackageInfo): - if any(kept.purl == package.purl for kept in self.packages): - raise ValueError(f"run '{self.run_id}' already has package '{package.purl}' -- each is logged once") - self.packages.append(package) diff --git a/rec/run.py b/rec/run.py index 27ac26e..27d7ded 100644 --- a/rec/run.py +++ b/rec/run.py @@ -8,8 +8,6 @@ from contextlib import ExitStack, contextmanager from uuid import uuid4 -from rdf_utils.models.prov import PackageInfo - from rec import State, Verdict from rec.observer import Observer @@ -175,14 +173,6 @@ def log_host_info(self, host_info: dict): for observer in self.observers: observer.log_host_info(self.id, host_info) - def log_packages(self, packages: list[PackageInfo]): - """ - Log the software packages this run used - :param packages: e.g. from rdf-utils ``get_py_pkg_info`` or ``get_ros_pkg_info`` - """ - for observer in self.observers: - observer.log_packages(self.id, packages) - def _fail_trace(error): return "".join(traceback.format_exception(error)) if error is not None else None diff --git a/rec/stores/__init__.py b/rec/stores/__init__.py index eb5d1e6..76f2252 100644 --- a/rec/stores/__init__.py +++ b/rec/stores/__init__.py @@ -3,7 +3,6 @@ from contextlib import AbstractContextManager from typing import Protocol -from rdf_utils.models.prov import PackageInfo from rdflib import URIRef from rec import State @@ -21,10 +20,6 @@ def update(self, **values) -> None: """Set fields of the run that it has one of, e.g. ``state``, ``start_time`` or ``host``.""" ... - def add_package(self, package: PackageInfo) -> None: - """Add a package the run used; raises ValueError if the run already has its purl.""" - ... - class Store(Protocol): def load(self, run_id: str) -> RunRecord | None: diff --git a/rec/stores/mariadb.sql b/rec/stores/mariadb.sql index f147c88..44f7403 100644 --- a/rec/stores/mariadb.sql +++ b/rec/stores/mariadb.sql @@ -9,21 +9,14 @@ CREATE TABLE IF NOT EXISTS {prefix}_runs ( end_time DATETIME(6), heartbeat_time DATETIME(6), fail_trace TEXT, + recorder_purl TEXT, + recorder_name TEXT, + recorder_version TEXT, + recorder_revision TEXT, + recorder_repository TEXT, + recorder_dirty BOOL, host_hostname TEXT, host_os TEXT, host_python TEXT, host_cpu TEXT ); - -CREATE TABLE IF NOT EXISTS {prefix}_packages ( - run INT NOT NULL, - purl VARCHAR(512) NOT NULL, - name TEXT NOT NULL, - version TEXT, - revision TEXT, - repository TEXT, - dirty BOOL NOT NULL, - recorder BOOL NOT NULL, - UNIQUE (run, purl, recorder), - FOREIGN KEY (run) REFERENCES {prefix}_runs (id) -); diff --git a/rec/stores/mariadb_store.py b/rec/stores/mariadb_store.py index 58000fe..70a24cd 100644 --- a/rec/stores/mariadb_store.py +++ b/rec/stores/mariadb_store.py @@ -1,4 +1,4 @@ -"""A store keeping runs in MariaDB tables: a row per run, and a row per package it used or was recorded by.""" +"""A store keeping runs in MariaDB tables: a row per run.""" import os import threading @@ -17,9 +17,14 @@ from rec.record import Host, RunRecord from rec.stores import RunHandle, Store -# The columns of `_packages` besides `run` and `recorder`: what `load_pkg_prov` records. -PACKAGE_COLUMNS = ("purl", "name", "version", "revision", "repository", "dirty") -TABLES = ("packages", "runs") +# The fields of a run kept as `_` columns: what `load_pkg_prov` records of the +# recorder, and the host. +PARTS = { + "recorder": ("purl", "name", "version", "revision", "repository", "dirty"), + "host": tuple(item.name for item in fields(Host)), +} +TIMES = ("queued_time", "start_time", "end_time", "heartbeat_time") +TABLES = ("runs",) class MariaDBStore(Store): @@ -30,8 +35,7 @@ def __init__(self, db_name: str = "logbook", prefix: str = "logs"): :param db_name: Name of the database :param prefix: Prefix of the table names: ``_runs`` has a row per run, ``id`` in the - order runs were added; ``_packages`` has a row per package, ``run`` naming its - run's ``id`` and ``recorder`` set for the rec that recorded it + order runs were added """ load_dotenv() self.db_name = db_name @@ -56,26 +60,21 @@ def load(self, run_id: str) -> RunRecord | None: with self._lock, self.conn.cursor(dictionary=True) as cursor: cursor.execute(f"SELECT * FROM {self.prefix}_runs WHERE run_id = ?", (run_id,)) columns = cursor.fetchone() - if columns is None: - return None - cursor.execute(f"SELECT * FROM {self.prefix}_packages WHERE run = ?", (columns["id"],)) - packages = cursor.fetchall() - host = {item.name: columns.pop(f"host_{item.name}") for item in fields(Host)} - times = {name: columns[name].replace(tzinfo=UTC) for name in ("queued_time", "start_time", "end_time", "heartbeat_time") if columns[name]} - by_role = {True: [], False: []} - for row in packages: - values = {name: row[name] for name in PACKAGE_COLUMNS} - by_role[bool(row["recorder"])].append(PackageInfo(**values | {"purl": URIRef(values["purl"]), "dirty": bool(values["dirty"])})) + if columns is None: + return None + host = {item: columns[f"host_{item}"] for item in PARTS["host"]} + recorder = {item: columns[f"recorder_{item}"] for item in PARTS["recorder"]} return RunRecord( run_id=run_id, bundle=URIRef(columns["bundle"]) if columns["bundle"] else None, state=State(columns["state"]), verdict=Verdict(columns["verdict"]), fail_trace=columns["fail_trace"], - recorder=next(iter(by_role[True]), None), + recorder=PackageInfo(**recorder | {"purl": URIRef(recorder["purl"]), "dirty": bool(recorder["dirty"])}) + if recorder["purl"] + else None, host=Host(**host) if any(value is not None for value in host.values()) else None, - packages=by_role[False], - **times, + **{name: columns[name].replace(tzinfo=UTC) for name in TIMES if columns[name]}, ) @contextmanager @@ -116,13 +115,13 @@ def close(self) -> None: class MariaDBRun(RunHandle): - """A run's rows, locked by the transaction of the edit that yields it; each change is one statement.""" + """A run's row, locked by the transaction of the edit that yields it; each change is one statement.""" def __init__(self, store: MariaDBStore, run_id: str, id: int, state: State, bundle: URIRef | None): """ :param store: The store whose transaction holds the run :param run_id: The run's id - :param id: The run's ``id`` in ``_runs``, which its package rows name as ``run`` + :param id: The run's ``id`` in ``_runs`` :param state: The run's state when the edit began :param bundle: The run's bundle when the edit began """ @@ -133,36 +132,20 @@ def __init__(self, store: MariaDBStore, run_id: str, id: int, state: State, bund self.bundle = bundle def update(self, **values): - if "recorder" in values: - self._insert_package(values.pop("recorder"), recorder=True) columns = {} for name, value in values.items(): - if name == "host": - columns |= {f"host_{item.name}": getattr(value, item.name) if value else None for item in fields(Host)} - elif isinstance(value, datetime): + if name in PARTS: + columns |= {f"{name}_{item}": getattr(value, item) if value else None for item in PARTS[name]} + else: + columns[name] = value + for name, value in columns.items(): + if isinstance(value, datetime): columns[name] = value.astimezone(UTC).replace(tzinfo=None) elif isinstance(value, (Enum, URIRef)): columns[name] = str(value) - else: - columns[name] = value - if columns: - self.store.cursor.execute( - f"UPDATE {self.store.prefix}_runs SET {', '.join(f'`{name}` = ?' for name in columns)} WHERE id = ?", - (*columns.values(), self.id), - ) - self.state = values.get("state", self.state) - self.bundle = values.get("bundle", self.bundle) - - def add_package(self, package: PackageInfo): - try: - self._insert_package(package, recorder=False) - except mariadb.IntegrityError as error: - raise ValueError(f"run '{self.run_id}' already has package '{package.purl}' -- each is logged once") from error - - def _insert_package(self, package: PackageInfo, recorder: bool): - values = [str(getattr(package, name)) if name == "purl" else getattr(package, name) for name in PACKAGE_COLUMNS] self.store.cursor.execute( - f"INSERT INTO {self.store.prefix}_packages (run, {', '.join(f'`{name}`' for name in PACKAGE_COLUMNS)}, recorder)" - f" VALUES (?{', ?' * len(PACKAGE_COLUMNS)}, ?)", - (self.id, *values, recorder), + f"UPDATE {self.store.prefix}_runs SET {', '.join(f'`{name}` = ?' for name in columns)} WHERE id = ?", + (*columns.values(), self.id), ) + self.state = values.get("state", self.state) + self.bundle = values.get("bundle", self.bundle) diff --git a/tests/test_mariadb_store.py b/tests/test_mariadb_store.py index c3f7774..17e5e67 100644 --- a/tests/test_mariadb_store.py +++ b/tests/test_mariadb_store.py @@ -2,8 +2,6 @@ from uuid import uuid4 import pytest -from rdf_utils.models.prov import PackageInfo -from rdflib import URIRef from rdflib.compare import isomorphic pytest.importorskip("mariadb", reason="the MariaDB driver is an optional extra") @@ -18,14 +16,6 @@ not TEST_DATABASE, reason="set REC_TEST_MARIADB_DATABASE to run MariaDB integration tests", ) -CONTROLLER = PackageInfo( - name="controller", - purl=URIRef("pkg:git/example.org/lab/controller@0123abcd"), - version="1.2.0", - revision="0123abcd", - repository="https://example.org/lab/controller", - dirty=True, -) @pytest.fixture @@ -39,7 +29,6 @@ def store(): class QuickRun(Run): def main(self): - self.log_packages([CONTROLLER]) return "ok" @@ -60,8 +49,8 @@ def test_the_tables_keep_the_whole_record(store, tmp_path): ) store.cursor.execute(f"SELECT state, verdict FROM {store.prefix}_runs WHERE run_id = 'run-0'") assert store.cursor.fetchone() == ("complete", "passed") - store.cursor.execute(f"SELECT name, recorder FROM {store.prefix}_packages ORDER BY run, recorder") - assert store.cursor.fetchall() == [("controller", 0), ("rec", 1)] * 3 + store.cursor.execute(f"SELECT recorder_name FROM {store.prefix}_runs") + assert store.cursor.fetchall() == [("rec",)] * 3 assert store.run_ids(State.COMPLETE) == ["run-0", "run-1", "run-2"] diff --git a/tests/test_run.py b/tests/test_run.py index 3f4f5dc..c43d934 100644 --- a/tests/test_run.py +++ b/tests/test_run.py @@ -5,7 +5,6 @@ import pytest from pyshacl import validate from rdf_utils import DatasetFormat -from rdf_utils.models.prov import PackageInfo from rdflib import Graph, URIRef from rdflib.namespace import PROV, RDF, TIME @@ -20,19 +19,10 @@ SHAPES = Graph() for name in ("prov.shacl.ttl", "prov-extension.shacl.ttl", "rec/rec.shacl.ttl"): SHAPES.parse(METAMODELS / name, format="turtle") -CONTROLLER = PackageInfo( - name="controller", - purl=URIRef("pkg:git/example.org/lab/controller@0123abcd"), - version="1.2.0", - revision="0123abcd", - repository="https://example.org/lab/controller", - dirty=True, -) class CalibrationRun(Run): def main(self): - self.log_packages([CONTROLLER]) return "calibrated" @@ -60,7 +50,7 @@ def store(request, tmp_path): return FileStore(tmp_path, fmt=request.param) -def test_a_completed_run_is_an_execution_by_rec_of_the_packages_it_used(store): +def test_a_completed_run_is_an_execution_by_rec(store): run = CalibrationRun(observers=[Observer(store)], run_id="run-1") run.beat_interval = 0 assert run.run() == "calibrated" @@ -74,8 +64,6 @@ def test_a_completed_run_is_an_execution_by_rec_of_the_packages_it_used(store): assert (record.bundle, RDF.type, PROV.Bundle) in g assert g.value(record.bundle, PROV.wasAttributedTo) == record.recorder.purl == g.value(node, PROV.wasAssociatedWith) assert record.recorder.name == "rec" - assert record.packages == [CONTROLLER] - assert (node, PROV.used, CONTROLLER.purl) in g def test_a_run_keeps_one_bundle_through_its_lifecycle(store): @@ -179,12 +167,6 @@ def test_a_run_in_progress_stops_when_cancelled(store): run.cancel() -def test_a_package_logged_twice_is_refused_and_nothing_kept(store): - with pytest.raises(ValueError, match="each is logged once"): - Observer(store).log_packages("run-v", [CONTROLLER, CONTROLLER]) - assert store.load("run-v") is None - - def test_one_observer_records_many_runs_at_once(store): """Every run is addressed by its id, and none closes the observer.""" observer = Observer(store) @@ -197,7 +179,6 @@ def test_one_observer_records_many_runs_at_once(store): for thread in threads: thread.join() assert store.run_ids(State.COMPLETE) == sorted(run.id for run in runs) - assert all(store.load(run.id).packages == [CONTROLLER] for run in runs) @pytest.mark.parametrize("run_id", ["../escape", "/tmp/escape", "nested/run", "a run", "läuft", "", ".", ".."]) From e7f53dabf7787f9bab55e5bd432ab0847a316da4 Mon Sep 17 00:00:00 2001 From: Vamsi Kalagaturu Date: Thu, 12 Nov 2026 15:09:52 +0100 Subject: [PATCH 12/16] Merge the examples into one set of robot runs - One example records runs in a bundle file and in MariaDB: passed, failed, cancelled while queued, stopped while running - PickPlaceRun checks for a stop request between motions; DrawerOpeningRun fails on an unreachable handle --- README.md | 5 +-- examples/file_store_run.py | 27 ------------ examples/mariadb_store_run.py | 38 ----------------- examples/robot_runs.py | 78 +++++++++++++++++++++++++++++++++++ 4 files changed, 80 insertions(+), 68 deletions(-) delete mode 100644 examples/file_store_run.py delete mode 100644 examples/mariadb_store_run.py create mode 100644 examples/robot_runs.py diff --git a/README.md b/README.md index e48b920..ff6f5b6 100644 --- a/README.md +++ b/README.md @@ -102,11 +102,10 @@ unreserved characters (letters, digits, `-`, `.`, `_`, `~`); a run given none ge ## Examples ```shell -python examples/file_store_run.py # JSON-LD and TriG files -python examples/mariadb_store_run.py # queue, cancel by id, run +python examples/robot_runs.py # passed, failed, cancelled while queued, stopped while running ``` -The MariaDB example needs the `mariadb` extra and an `.env` at the repository root: +It records every run in a bundle file under `runs/prov` and in MariaDB, so it needs the `mariadb` extra and an `.env` at the repository root: ```dotenv MARIADB_USER="user" diff --git a/examples/file_store_run.py b/examples/file_store_run.py deleted file mode 100644 index 3aeebf4..0000000 --- a/examples/file_store_run.py +++ /dev/null @@ -1,27 +0,0 @@ -"""Record a run as a PROV bundle in JSON-LD and in TriG, and read it back.""" - -from rdf_utils import DatasetFormat - -from rec.observer import Observer -from rec.run import Run -from rec.stores.file_store import FileStore - - -class PickPlaceRun(Run): - def main(self): - return "placed" - - -if __name__ == "__main__": - as_json_ld = FileStore("runs/prov") - as_trig = FileStore("runs/prov", fmt=DatasetFormat.TRIG) - observers = [Observer(as_json_ld), Observer(as_trig)] - run = PickPlaceRun(observers=observers, run_id="pick-place-1") - run.run() - for observer in observers: - observer.close() - - print(f"PROV bundle: {as_json_ld.path(run.id)}, {as_trig.path(run.id)}") - record = as_trig.load(run.id) - assert record is not None - print(record.state, record.verdict, record.recorder.purl) diff --git a/examples/mariadb_store_run.py b/examples/mariadb_store_run.py deleted file mode 100644 index 2092b59..0000000 --- a/examples/mariadb_store_run.py +++ /dev/null @@ -1,38 +0,0 @@ -"""Queue runs in MariaDB, cancel one by id as a scheduler would, run the other, and read it back. - -Needs the `mariadb` extra and the connection settings in `.env` (see the README). -""" - -from rec import State -from rec.observer import Observer -from rec.run import Run -from rec.stores.mariadb_store import MariaDBStore - - -class DrawerOpeningRun(Run): - def main(self): - if self.state is State.CANCELING: - return "stopped" - return "opened" - - -if __name__ == "__main__": - observer = Observer(MariaDBStore(db_name="logbook", prefix="logs")) - kept = DrawerOpeningRun(observers=[observer], run_id="drawer-1") - dropped = DrawerOpeningRun(observers=[observer], run_id="drawer-2") - kept.queue() - dropped.queue() - print("queued:", observer.store.run_ids(State.QUEUED)) - - # A scheduler holds only the id, and its own connection to the same tables. - scheduler = Observer(MariaDBStore(db_name="logbook", prefix="logs")) - Run(observers=[scheduler], run_id="drawer-2").cancel() - scheduler.close() - print("drawer-2:", dropped.state) - - kept.run() - record = observer.store.load(kept.id) - assert record is not None - print(record.state, record.verdict, record.recorder.purl) - print("canceled:", observer.store.run_ids(State.CANCELED)) - observer.close() diff --git a/examples/robot_runs.py b/examples/robot_runs.py new file mode 100644 index 0000000..1fef357 --- /dev/null +++ b/examples/robot_runs.py @@ -0,0 +1,78 @@ +"""Record robot runs in a PROV bundle file and in MariaDB: one passes, one fails, one is +cancelled while queued and one is stopped while it runs. + +Needs the `mariadb` extra and the connection settings in `.env` (see the README). +""" + +import logging +import threading +import time + +from rec import State +from rec.observer import Observer +from rec.run import Run +from rec.stores.file_store import FileStore +from rec.stores.mariadb_store import MariaDBStore + +logger = logging.getLogger("robot_runs") + + +class PickPlaceRun(Run): + """Picks an object and places it, checking between motions whether it was asked to stop.""" + + motions = ("approach", "grasp", "lift", "transport", "place", "retreat") + + def main(self): + for done, motion in enumerate(self.motions): + if self.state is State.CANCELING: + logger.info("%s: stopped before %s", self.id, motion) + return f"stopped after {done} of {len(self.motions)} motions" + logger.info("%s: %s", self.id, motion) + time.sleep(0.5) + return "placed" + + +class DrawerOpeningRun(Run): + """Opens a drawer, and fails when the handle is further from its modelled pose than the gripper reaches.""" + + handle_offset = 0.04 + reach = 0.02 + + def main(self): + logger.info("%s: looking for the handle", self.id) + time.sleep(0.5) + if self.handle_offset > self.reach: + raise RuntimeError(f"handle is {self.handle_offset} m from its modelled pose -- the gripper reaches {self.reach} m") + return "opened" + + +if __name__ == "__main__": + logging.basicConfig(level=logging.INFO, format="%(message)s") + files, tables = FileStore("runs/prov"), MariaDBStore(db_name="logbook", prefix="logs") + observers = [Observer(files), Observer(tables)] + + passed = PickPlaceRun(observers=observers, run_id="pick-place-1") + # A short beat, so the run records a few heartbeats while it moves. + passed.beat_interval = 1 + passed.run() + + DrawerOpeningRun(observers=observers, run_id="drawer-1").run() + + # A scheduler holds only the ids, and its own connection to the same stores. + scheduler = [Observer(FileStore("runs/prov")), Observer(MariaDBStore(db_name="logbook", prefix="logs"))] + queued = PickPlaceRun(observers=observers, run_id="pick-place-2") + queued.queue() + Run(observers=scheduler, run_id="pick-place-2").cancel() + + stopped = PickPlaceRun(observers=observers, run_id="pick-place-3") + running = threading.Thread(target=stopped.run) + running.start() + time.sleep(1.2) + Run(observers=scheduler, run_id="pick-place-3").cancel() + running.join() + + for run_id in ("pick-place-1", "drawer-1", "pick-place-2", "pick-place-3"): + record = tables.load(run_id) + print(f"{run_id}: {record.state} {record.verdict} heartbeat={record.heartbeat_time} -> {files.path(run_id)}") + for observer in [*observers, *scheduler]: + observer.close() From 51c91b8610922b13b39ee97c11319130f15233a0 Mon Sep 17 00:00:00 2001 From: Vamsi Kalagaturu Date: Thu, 12 Nov 2026 15:52:24 +0100 Subject: [PATCH 13/16] Keep a run's bundle in its MariaDB row - The runs table holds a run's id and its bundle as JSON-LD; edit and load go through the same provenance functions as FileStore - Drop the per-field columns, the column mapping and MariaDBRun; run_ids filters by state from the bundles - Both stores yield a RunRecord, so the RunHandle protocol goes --- README.md | 2 +- rec/record.py | 2 +- rec/stores/__init__.py | 20 +------ rec/stores/mariadb.sql | 19 +----- rec/stores/mariadb_store.py | 116 +++++++++--------------------------- tests/test_mariadb_store.py | 10 +--- 6 files changed, 37 insertions(+), 132 deletions(-) diff --git a/README.md b/README.md index ff6f5b6..12a42af 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,7 @@ MariaDB): only a new run is queued, only a new or queued run starts. A started r | Store | Keeps a run as | |---|---| | `FileStore(dir)` | its bundle, `.ld.json`; `fmt=DatasetFormat.TRIG` or `NQUADS` for `.trig`, `.nq` | -| `MariaDBStore(db_name, prefix)` | a row of `_runs`, see [mariadb.sql](rec/stores/mariadb.sql) | +| `MariaDBStore(db_name, prefix)` | its bundle as JSON-LD in a row of `_runs`, see [mariadb.sql](rec/stores/mariadb.sql) | A run may have several observers, one store each. Each store names the run's bundle on its first edit, so two stores hold the same run in differently named bundles. Any object with `load`, diff --git a/rec/record.py b/rec/record.py index 822e815..8763f65 100644 --- a/rec/record.py +++ b/rec/record.py @@ -23,7 +23,7 @@ class Host: @dataclass class RunRecord: - """What rec knows of a run; also what FileStore.edit yields to change it (rec.stores.RunHandle). + """What rec knows of a run; also what a store's ``edit`` yields to change it. ``bundle`` names the run's provenance bundle and ``recorder`` is the rec that writes it, both set on the run's first edit. diff --git a/rec/stores/__init__.py b/rec/stores/__init__.py index 76f2252..b5d4fb3 100644 --- a/rec/stores/__init__.py +++ b/rec/stores/__init__.py @@ -3,33 +3,19 @@ from contextlib import AbstractContextManager from typing import Protocol -from rdflib import URIRef - from rec import State from rec.record import RunRecord -class RunHandle(Protocol): - """A run held by ``Store.edit``: its state and bundle, and the changes made to it.""" - - run_id: str - state: State - bundle: URIRef | None - - def update(self, **values) -> None: - """Set fields of the run that it has one of, e.g. ``state``, ``start_time`` or ``host``.""" - ... - - class Store(Protocol): def load(self, run_id: str) -> RunRecord | None: """Return the stored record of a run, or None if the run is not stored.""" ... - def edit(self, run_id: str) -> AbstractContextManager[RunHandle]: - """Lock a run for changing and keep the changes when the with block exits. + def edit(self, run_id: str) -> AbstractContextManager[RunRecord]: + """Lock a run for changing and keep the changes to its record when the with block exits. - Yields a new run if the run is not stored. Other edits of the same run, + Yields a new record if the run is not stored. Other edits of the same run, also from other processes, wait until the block exits. If the block raises, nothing is kept. """ diff --git a/rec/stores/mariadb.sql b/rec/stores/mariadb.sql index 44f7403..985e8c7 100644 --- a/rec/stores/mariadb.sql +++ b/rec/stores/mariadb.sql @@ -1,22 +1,5 @@ CREATE TABLE IF NOT EXISTS {prefix}_runs ( id INT AUTO_INCREMENT PRIMARY KEY, run_id VARCHAR(255) NOT NULL UNIQUE, - bundle VARCHAR(45), - state VARCHAR(20) NOT NULL, - verdict VARCHAR(20) NOT NULL, - queued_time DATETIME(6), - start_time DATETIME(6), - end_time DATETIME(6), - heartbeat_time DATETIME(6), - fail_trace TEXT, - recorder_purl TEXT, - recorder_name TEXT, - recorder_version TEXT, - recorder_revision TEXT, - recorder_repository TEXT, - recorder_dirty BOOL, - host_hostname TEXT, - host_os TEXT, - host_python TEXT, - host_cpu TEXT + bundle LONGTEXT ); diff --git a/rec/stores/mariadb_store.py b/rec/stores/mariadb_store.py index 70a24cd..c7af0c3 100644 --- a/rec/stores/mariadb_store.py +++ b/rec/stores/mariadb_store.py @@ -1,30 +1,18 @@ -"""A store keeping runs in MariaDB tables: a row per run.""" +"""A store keeping runs in MariaDB: a row per run, holding its provenance bundle.""" import os import threading from contextlib import contextmanager -from dataclasses import fields -from datetime import UTC, datetime -from enum import Enum from importlib.resources import files import mariadb from dotenv import load_dotenv -from rdf_utils.models.prov import PackageInfo -from rdflib import URIRef +from rdf_utils import DatasetFormat +from rdflib import Dataset -from rec import State, Verdict -from rec.record import Host, RunRecord -from rec.stores import RunHandle, Store - -# The fields of a run kept as `_` columns: what `load_pkg_prov` records of the -# recorder, and the host. -PARTS = { - "recorder": ("purl", "name", "version", "revision", "repository", "dirty"), - "host": tuple(item.name for item in fields(Host)), -} -TIMES = ("queued_time", "start_time", "end_time", "heartbeat_time") -TABLES = ("runs",) +from rec import State, provenance +from rec.record import RunRecord +from rec.stores import Store class MariaDBStore(Store): @@ -34,8 +22,8 @@ def __init__(self, db_name: str = "logbook", prefix: str = "logs"): ``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 names: ``_runs`` has a row per run, ``id`` in the - order runs were added + :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 """ load_dotenv() self.db_name = db_name @@ -57,45 +45,36 @@ def __init__(self, db_name: str = "logbook", prefix: str = "logs"): self.cursor.execute(statement) def load(self, run_id: str) -> RunRecord | None: - with self._lock, self.conn.cursor(dictionary=True) as cursor: - cursor.execute(f"SELECT * FROM {self.prefix}_runs WHERE run_id = ?", (run_id,)) - columns = cursor.fetchone() - if columns is None: + 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 - host = {item: columns[f"host_{item}"] for item in PARTS["host"]} - recorder = {item: columns[f"recorder_{item}"] for item in PARTS["recorder"]} - return RunRecord( - run_id=run_id, - bundle=URIRef(columns["bundle"]) if columns["bundle"] else None, - state=State(columns["state"]), - verdict=Verdict(columns["verdict"]), - fail_trace=columns["fail_trace"], - recorder=PackageInfo(**recorder | {"purl": URIRef(recorder["purl"]), "dirty": bool(recorder["dirty"])}) - if recorder["purl"] - else None, - host=Host(**host) if any(value is not None for value in host.values()) else None, - **{name: columns[name].replace(tzinfo=UTC) for name in TIMES if columns[name]}, - ) + return provenance.record(Dataset().parse(data=row[0], format=DatasetFormat.JSON_LD), run_id) @contextmanager def edit(self, run_id: str): - """Yield a ``MariaDBRun`` in one transaction, committed when the block exits, rolled back if it raises. + """Yield the run's ``RunRecord`` in one transaction, and save it when the block exits; roll back if it raises. The run's row is locked with ``SELECT ... FOR UPDATE``, and inserted first if the run is new. """ with self._lock: self.conn.begin() try: - self.cursor.execute(f"SELECT id, state, bundle FROM {self.prefix}_runs WHERE run_id = ? FOR UPDATE", (run_id,)) + self.cursor.execute(f"SELECT id, bundle FROM {self.prefix}_runs WHERE run_id = ? FOR UPDATE", (run_id,)) row = self.cursor.fetchone() if row is None: - new = RunRecord(run_id) - self.cursor.execute( - f"INSERT INTO {self.prefix}_runs (run_id, state, verdict) VALUES (?, ?, ?) RETURNING id, state, bundle", - (new.run_id, str(new.state), str(new.verdict)), - ) + record = RunRecord(run_id) + # Inserted before the block runs, so a concurrent edit of the same new run waits on its lock. + self.cursor.execute(f"INSERT INTO {self.prefix}_runs (run_id) VALUES (?) RETURNING id, bundle", (run_id,)) row = self.cursor.fetchone() - yield MariaDBRun(self, run_id, row[0], State(row[1]), URIRef(row[2]) if row[2] else None) + else: + record = provenance.record(Dataset().parse(data=row[1], format=DatasetFormat.JSON_LD), run_id) + yield record + self.cursor.execute( + f"UPDATE {self.prefix}_runs SET bundle = ? WHERE id = ?", + (provenance.serialize(provenance.dataset(record), DatasetFormat.JSON_LD), row[0]), + ) except BaseException: self.conn.rollback() raise @@ -103,49 +82,10 @@ def edit(self, run_id: str): def run_ids(self, state: State | None = None) -> list[str]: with self._lock: - if state is None: - self.cursor.execute(f"SELECT run_id FROM {self.prefix}_runs ORDER BY id") - else: - self.cursor.execute(f"SELECT run_id FROM {self.prefix}_runs WHERE state = ? ORDER BY id", (str(state),)) - return [row[0] for row in self.cursor.fetchall()] + self.cursor.execute(f"SELECT run_id FROM {self.prefix}_runs ORDER BY id") + run_ids = [row[0] for row in self.cursor.fetchall()] + return [run_id for run_id in run_ids if state is None or self.load(run_id).state is state] def close(self) -> None: self.cursor.close() self.conn.close() - - -class MariaDBRun(RunHandle): - """A run's row, locked by the transaction of the edit that yields it; each change is one statement.""" - - def __init__(self, store: MariaDBStore, run_id: str, id: int, state: State, bundle: URIRef | None): - """ - :param store: The store whose transaction holds the run - :param run_id: The run's id - :param id: The run's ``id`` in ``_runs`` - :param state: The run's state when the edit began - :param bundle: The run's bundle when the edit began - """ - self.store = store - self.run_id = run_id - self.id = id - self.state = state - self.bundle = bundle - - def update(self, **values): - columns = {} - for name, value in values.items(): - if name in PARTS: - columns |= {f"{name}_{item}": getattr(value, item) if value else None for item in PARTS[name]} - else: - columns[name] = value - for name, value in columns.items(): - if isinstance(value, datetime): - columns[name] = value.astimezone(UTC).replace(tzinfo=None) - elif isinstance(value, (Enum, URIRef)): - columns[name] = str(value) - self.store.cursor.execute( - f"UPDATE {self.store.prefix}_runs SET {', '.join(f'`{name}` = ?' for name in columns)} WHERE id = ?", - (*columns.values(), self.id), - ) - self.state = values.get("state", self.state) - self.bundle = values.get("bundle", self.bundle) diff --git a/tests/test_mariadb_store.py b/tests/test_mariadb_store.py index 17e5e67..066d858 100644 --- a/tests/test_mariadb_store.py +++ b/tests/test_mariadb_store.py @@ -9,7 +9,7 @@ from rec.observer import Observer # noqa: E402 from rec.run import Run # noqa: E402 from rec.stores.file_store import FileStore # noqa: E402 -from rec.stores.mariadb_store import TABLES, MariaDBStore # noqa: E402 +from rec.stores.mariadb_store import MariaDBStore # noqa: E402 TEST_DATABASE = os.getenv("REC_TEST_MARIADB_DATABASE") pytestmark = pytest.mark.skipif( @@ -23,7 +23,7 @@ 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 {', '.join(f'{prefix}_{table}' for table in TABLES)}") + db.cursor.execute(f"DROP TABLE IF EXISTS {prefix}_runs") db.close() @@ -32,7 +32,7 @@ def main(self): return "ok" -def test_the_tables_keep_the_whole_record(store, tmp_path): +def test_a_row_keeps_the_same_bundle_as_a_file(store, tmp_path): files = FileStore(tmp_path) runs = [QuickRun(observers=[Observer(store), Observer(files)], run_id=f"run-{i}") for i in range(3)] for run in runs: @@ -47,10 +47,6 @@ def test_the_tables_keep_the_whole_record(store, tmp_path): provenance.dataset(from_tables).graph(from_tables.bundle), provenance.dataset(from_file).graph(from_file.bundle), ) - store.cursor.execute(f"SELECT state, verdict FROM {store.prefix}_runs WHERE run_id = 'run-0'") - assert store.cursor.fetchone() == ("complete", "passed") - store.cursor.execute(f"SELECT recorder_name FROM {store.prefix}_runs") - assert store.cursor.fetchall() == [("rec",)] * 3 assert store.run_ids(State.COMPLETE) == ["run-0", "run-1", "run-2"] From a10bbc86022192fdccb2fcd670e99a821971a60a Mon Sep 17 00:00:00 2001 From: Vamsi Kalagaturu Date: Thu, 12 Nov 2026 16:39:35 +0100 Subject: [PATCH 14/16] Record each event in the run's bundle in place - A store's edit yields the run's parsed Dataset under its lock and writes it back; the Observer checks the state and sets only the event's triples - rdf-utils writes the bundle, rec as software agent, the execution and its instants once each; RunRecord and the record-bundle round trip go - A run has one observer and store; the run is associated with the rec that started it, the bundle attributed to the rec that first recorded it - MariaDB locks a new run's row by inserting it and keeps run ids case-sensitive; the table is created in code - An interrupt ends the run as error and is raised again; a failed heartbeat is logged and the next tried; a run that fails while canceling keeps its verdict - A run cancelled while queued has no beginning or end; times without a zone and files outside the store's directory are refused - Drop TriG and N-Quads files, run_ids, the warning verdict, the store protocols and the close forwarders; base moves to the Observer --- README.md | 53 +++++---- examples/robot_runs.py | 58 ++++----- rec/__init__.py | 1 - rec/observer.py | 212 ++++++++++++++++++++------------- rec/provenance.py | 117 ++---------------- rec/record.py | 50 -------- rec/run.py | 166 +++++++++----------------- rec/stores/__init__.py | 31 +---- rec/stores/file_store.py | 49 +++----- rec/stores/mariadb.sql | 5 - rec/stores/mariadb_store.py | 60 ++++------ tests/test_mariadb_store.py | 54 +++++---- tests/test_run.py | 228 +++++++++++++++++++++++------------- 13 files changed, 469 insertions(+), 615 deletions(-) delete mode 100644 rec/record.py delete mode 100644 rec/stores/mariadb.sql diff --git a/README.md b/README.md index 12a42af..db14904 100644 --- a/README.md +++ b/README.md @@ -27,13 +27,17 @@ class PickPlaceRun(Run): return "placed" -observer = Observer(FileStore("runs/prov")) -PickPlaceRun(observers=[observer], run_id="pick-place-1").run() -observer.close() +PickPlaceRun(Observer(FileStore("runs/prov")), run_id="pick-place-1").run() ``` `run()` records the start and the host, runs `main`, and ends the run as `passed`, `failed` -(`main` raised) or `error` (interrupted). It returns what `main` returned; rec does not record it. +(`main` raised) or `error` (interrupted, e.g. `KeyboardInterrupt` or `SystemExit`, which `run()` +raises again once recorded). It returns what `main` returned; rec does not record it. + +Each event changes only its own triples in the run's bundle: the store parses the bundle under its +lock, the `Observer` checks the run's state and sets what the event 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. 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` @@ -44,42 +48,34 @@ helpers, in that tool's own bundle. State lives in the store, so any `Run` with the same id sees and changes the same run: ```python -DrawerRun(observers=[observer], run_id="drawer-2").queue() +DrawerRun(Observer(MariaDBStore()), run_id="drawer-2").queue() # elsewhere, e.g. a scheduler with its own connection -Run(observers=[Observer(MariaDBStore())], run_id="drawer-2").cancel() +Run(Observer(MariaDBStore()), run_id="drawer-2").cancel() ``` | State when cancelled | Result | |---|---| -| `queued` | `canceled` | -| `in-progress` | `canceling`; `main` sees `self.state is State.CANCELING`, returns, and the run ends `canceled` | +| `queued` | `canceled`; it never started, so it has no beginning or end | +| `in-progress` | `canceling`; `main` sees `self.state is State.CANCELING`, returns, and the run ends `canceled`; a `main` that raises instead ends `complete` with its verdict | | anything else | `RuntimeError` | -The store decides every step under a lock (`flock` for files, `SELECT ... FOR UPDATE` 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`. +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`; `fmt=DatasetFormat.TRIG` or `NQUADS` for `.trig`, `.nq` | -| `MariaDBStore(db_name, prefix)` | its bundle as JSON-LD in a row of `_runs`, see [mariadb.sql](rec/stores/mariadb.sql) | +| `FileStore(dir)` | its bundle, `.ld.json` | +| `MariaDBStore(db_name, prefix)` | its bundle as JSON-LD in a row of `_runs` (`id`, `run_id`, `bundle`) | -A run may have several observers, one store each. Each store names the run's bundle on its first -edit, so two stores hold the same run in differently named bundles. Any object with `load`, -`edit`, `run_ids` and `close` is a store (`rec.stores.Store`). +`load(run_id)` returns the run's bundle as an rdflib `Dataset`; `Observer.lifecycle(run_id)` gives +its state and verdict. A run is recorded in one store. ## The PROV bundle -```python -from rec import provenance - -ds = provenance.dataset(store.load("pick-place-1")) # RunRecord -> rdflib Dataset -record = provenance.record(ds, "pick-place-1") # and back -``` - ```trig { a prov:Bundle ; @@ -96,8 +92,13 @@ record = provenance.record(ds, "pick-place-1") # and back } ``` -rec is recorded by rdf-utils' `load_pkg_prov`, named by its purl. A run id is RFC 3986 -unreserved characters (letters, digits, `-`, `.`, `_`, `~`); a run given none gets a UUID. +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 `Observer`. ## Examples @@ -105,7 +106,7 @@ unreserved characters (letters, digits, `-`, `.`, `_`, `~`); a run given none ge python examples/robot_runs.py # passed, failed, cancelled while queued, stopped while running ``` -It records every run in a bundle file under `runs/prov` and in MariaDB, so it needs the `mariadb` extra and an `.env` at the repository root: +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" diff --git a/examples/robot_runs.py b/examples/robot_runs.py index 1fef357..50b1d92 100644 --- a/examples/robot_runs.py +++ b/examples/robot_runs.py @@ -1,4 +1,4 @@ -"""Record robot runs in a PROV bundle file and in MariaDB: one passes, one fails, one is +"""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. Needs the `mariadb` extra and the connection settings in `.env` (see the README). @@ -48,31 +48,31 @@ def main(self): if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(message)s") - files, tables = FileStore("runs/prov"), MariaDBStore(db_name="logbook", prefix="logs") - observers = [Observer(files), Observer(tables)] - - passed = PickPlaceRun(observers=observers, run_id="pick-place-1") - # A short beat, so the run records a few heartbeats while it moves. - passed.beat_interval = 1 - passed.run() - - DrawerOpeningRun(observers=observers, run_id="drawer-1").run() - - # A scheduler holds only the ids, and its own connection to the same stores. - scheduler = [Observer(FileStore("runs/prov")), Observer(MariaDBStore(db_name="logbook", prefix="logs"))] - queued = PickPlaceRun(observers=observers, run_id="pick-place-2") - queued.queue() - Run(observers=scheduler, run_id="pick-place-2").cancel() - - stopped = PickPlaceRun(observers=observers, run_id="pick-place-3") - running = threading.Thread(target=stopped.run) - running.start() - time.sleep(1.2) - Run(observers=scheduler, run_id="pick-place-3").cancel() - running.join() - - for run_id in ("pick-place-1", "drawer-1", "pick-place-2", "pick-place-3"): - record = tables.load(run_id) - print(f"{run_id}: {record.state} {record.verdict} heartbeat={record.heartbeat_time} -> {files.path(run_id)}") - for observer in [*observers, *scheduler]: - observer.close() + # A scheduler holds only the run ids, and its own store on the same files or tables. + for store, scheduler_store in ( + (FileStore("runs/prov"), FileStore("runs/prov")), + (MariaDBStore(db_name="logbook", prefix="logs"), MariaDBStore(db_name="logbook", prefix="logs")), + ): + observer, scheduler = Observer(store), Observer(scheduler_store) + + passed = PickPlaceRun(observer, run_id="pick-place-1") + # A short beat, so the run records a few heartbeats while it moves. + passed.beat_interval = 1 + passed.run() + + DrawerOpeningRun(observer, run_id="drawer-1").run() + + PickPlaceRun(observer, run_id="pick-place-2").queue() + Run(scheduler, run_id="pick-place-2").cancel() + + stopped = PickPlaceRun(observer, run_id="pick-place-3") + running = threading.Thread(target=stopped.run) + running.start() + time.sleep(1.2) + Run(scheduler, run_id="pick-place-3").cancel() + running.join() + + for run_id in ("pick-place-1", "drawer-1", "pick-place-2", "pick-place-3"): + print(type(store).__name__, run_id, *observer.lifecycle(run_id)) + store.close() + scheduler_store.close() diff --git a/rec/__init__.py b/rec/__init__.py index 567d075..b307ca3 100644 --- a/rec/__init__.py +++ b/rec/__init__.py @@ -15,6 +15,5 @@ class State(StrEnum): class Verdict(StrEnum): UNAVAILABLE = "unavailable" PASSED = "passed" - WARNING = "warning" FAILED = "failed" ERROR = "error" diff --git a/rec/observer.py b/rec/observer.py index e2cd60a..4cc70ee 100644 --- a/rec/observer.py +++ b/rec/observer.py @@ -1,115 +1,163 @@ -"""Records the events of runs in a store.""" +"""Records the events of runs in a store, each run as its provenance bundle.""" + +from __future__ import annotations -import threading from contextlib import contextmanager from datetime import datetime -from uuid import uuid4 +from typing import TYPE_CHECKING -from rdf_utils.models.prov import get_py_pkg_info -from rdflib import URIRef +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.record import Host -from rec.stores import Store +from rec.provenance import HOST_TERMS, OSLC_AUTO, PROV_EXT, REC, RUN_BASE, RUN_ID, STATES, VERDICTS + +if TYPE_CHECKING: + # The MariaDB driver is an optional extra. + from rec.stores.file_store import FileStore + from rec.stores.mariadb_store import MariaDBStore class Observer: """Records the events of any number of runs in one store; every call names its run. - Whoever creates the observer closes it, once every run it records is over. + A run is a `prov-ext:Execution` and an `oslc_auto:AutomationResult` in a `prov:Bundle` attributed + to the rec that first recorded it. Each event changes only its own triples, in the bundle the + store parsed under its lock. """ - def __init__(self, store: Store): + def __init__(self, store: FileStore | MariaDBStore, base: str = RUN_BASE): + """ + :param store: Where the runs' bundles are kept + :param base: IRI base of the run nodes; a run is ```` + """ self.store = store - # Per thread: a heartbeat must wait for the store, not join another thread's held run. - self._held = threading.local() - - @contextmanager - def _hold(self, run_id: str): - """Keep the run open in the store: the calls made meanwhile are kept together when the block ends, or none is.""" - with self._run(run_id) as run: - outer = getattr(self._held, "run", None) - self._held.run = run - try: - yield - finally: - self._held.run = outer + self.base = base + # Read once: it inspects rec's checkout, and every edit of a run holds the store's lock. + self.recorder = get_py_pkg_info("rec") @contextmanager def _run(self, run_id: str): - held = getattr(self._held, "run", None) - if held is not None and held.run_id == run_id: - yield held - return - with self.store.edit(run_id) as run: - # A run's bundle is named once and attributed to the rec that first recorded it. - if run.bundle is None: - run.update(bundle=URIRef(uuid4().urn), recorder=get_py_pkg_info("rec")) - yield run + """Yield the run's bundle and node under the store's lock, the bundle created on the run's first edit. + + :raises ValueError: ``run_id`` is not a run id (``rec.provenance.RUN_ID``) + """ + if not RUN_ID.fullmatch(run_id): + raise ValueError(f"'{run_id}' is not a run id -- use letters, digits, '-', '.', '_' or '~', not '.' or '..'") + run = URIRef(self.base + run_id) + with self.store.edit(run_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((run, RDF.type, PROV_EXT.Execution)) + bundle.add((run, RDF.type, OSLC_AUTO.AutomationResult)) + bundle.add((run, OSLC_AUTO.state, OSLC_AUTO.new)) + bundle.add((run, OSLC_AUTO.verdict, OSLC_AUTO.unavailable)) + yield bundle, run + + def lifecycle(self, run_id: str) -> tuple[State, Verdict]: + """The run's state and verdict as the store keeps them; a run not stored is new. + + :raises ValueError: The stored bundle holds no run of this id under the observer's base + """ + ds = self.store.load(run_id) + if ds is None: + return State.NEW, Verdict.UNAVAILABLE + run = URIRef(self.base + run_id) + bundle = next((graph for graph in ds.graphs() if (run, OSLC_AUTO.state, None) in graph), None) + if bundle is None: + raise ValueError(f"the bundle of run '{run_id}' has no '{run}' -- it was recorded under another base") + state, verdict = bundle.value(run, OSLC_AUTO.state), bundle.value(run, 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), + ) def log_queued_run(self, run_id: str, queued_time: datetime): """Record a new run as queued; raises RuntimeError for a run that is not new.""" - with self._run(run_id) as run: - if run.state is not State.NEW: - raise RuntimeError(f"run '{run_id}' is {run.state} -- only a new run can be queued") - run.update(state=State.QUEUED, verdict=Verdict.UNAVAILABLE, queued_time=queued_time) + if queued_time.utcoffset() is None: + raise ValueError(f"queued time {queued_time} of run '{run_id}' has no time zone -- a run's times are wall-clock instants") + with self._run(run_id) as (bundle, run): + state = bundle.value(run, OSLC_AUTO.state) + if state != OSLC_AUTO.new: + raise RuntimeError(f"run '{run_id}' is {state.fragment} -- only a new run can be queued") + bundle.set((run, OSLC_AUTO.state, OSLC_AUTO.queued)) + bundle.add((run, REC["queued-time"], Literal(queued_time))) def log_started_run(self, run_id: str, started_time: datetime): - """Record a new or queued run as in progress. + """Record a new or queued run as in progress, executed by this observer's rec. :raises RuntimeError: The run has already started, or was cancelled """ - with self._run(run_id) as run: - if run.state not in (State.NEW, State.QUEUED): - raise RuntimeError(f"run '{run_id}' is {run.state} -- only a run that has not started can start") - run.update(state=State.IN_PROGRESS, verdict=Verdict.UNAVAILABLE, start_time=started_time) + with self._run(run_id) as (bundle, run): + state = bundle.value(run, OSLC_AUTO.state) + if state not in (OSLC_AUTO.new, OSLC_AUTO.queued): + raise RuntimeError(f"run '{run_id}' is {state.fragment} -- only a run that has not started can start") + # 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 = URIRef(f"{run}/beginning") + add_wall_instant(bundle, started, started_time) + load_execution_prov(bundle, run, (), self.recorder.purl, started) + bundle.set((run, OSLC_AUTO.state, OSLC_AUTO.inProgress)) def log_run_heartbeat(self, run_id: str, beat_time: datetime): """Record that a started run is still alive; raises RuntimeError for any other run.""" - with self._run(run_id) as run: - if run.state not in (State.IN_PROGRESS, State.CANCELING): - raise RuntimeError(f"run '{run_id}' is {run.state} -- only a started run beats") - run.update(heartbeat_time=beat_time) - - def log_completed_run(self, run_id: str, completed_time: datetime): - """End a run in progress as passed, or a canceling one as canceled. - + if beat_time.utcoffset() is None: + raise ValueError(f"heartbeat time {beat_time} of run '{run_id}' has no time zone -- a run's times are wall-clock instants") + with self._run(run_id) as (bundle, run): + state = bundle.value(run, OSLC_AUTO.state) + if state not in (OSLC_AUTO.inProgress, OSLC_AUTO.canceling): + raise RuntimeError(f"run '{run_id}' is {state.fragment} -- only a started run beats") + bundle.set((run, REC["heartbeat-time"], Literal(beat_time))) + + def log_ended_run(self, run_id: str, ended_time: datetime, verdict: Verdict, fail_trace: str | None = None): + """End a started run with its verdict: a canceling run that passed ends canceled, any other ends complete. + + :param verdict: ``passed``, ``failed`` (its main raised) or ``error`` (it was interrupted) + :param fail_trace: The trace of what ended a failed or error run :raises RuntimeError: The run has not started, or has ended """ - self._end(run_id, completed_time, Verdict.PASSED) - - def log_interrupted_run(self, run_id: str, interrupted_time: datetime, fail_trace: str | None = None): - """End a run in progress with an error verdict and the trace of what interrupted it.""" - self._end(run_id, interrupted_time, Verdict.ERROR, fail_trace=fail_trace) - - def log_failed_run(self, run_id: str, failed_time: datetime, fail_trace: str | None = None): - """End a run in progress as failed, with the trace of the exception that ended it.""" - self._end(run_id, failed_time, Verdict.FAILED, fail_trace=fail_trace) - - def log_cancelled_run(self, run_id: str, cancelled_time: datetime): - """Cancel a queued run, or ask a run in progress to stop; raises RuntimeError for any other run.""" - with self._run(run_id) as run: - if run.state is State.QUEUED: - run.update(state=State.CANCELED, verdict=Verdict.UNAVAILABLE, end_time=cancelled_time) - elif run.state is State.IN_PROGRESS: - run.update(state=State.CANCELING) + with self._run(run_id) as (bundle, run): + state = bundle.value(run, OSLC_AUTO.state) + if state not in (OSLC_AUTO.inProgress, OSLC_AUTO.canceling): + raise RuntimeError(f"run '{run_id}' is {state.fragment} -- only a started run can end") + ended = URIRef(f"{run}/end") + add_wall_instant(bundle, ended, ended_time) + bundle.add((run, 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((run, OSLC_AUTO.state, OSLC_AUTO.canceled)) + return + bundle.set((run, OSLC_AUTO.state, OSLC_AUTO.complete)) + bundle.set((run, OSLC_AUTO.verdict, VERDICTS[verdict])) + if fail_trace: + bundle.add((run, REC["fail-trace"], Literal(fail_trace, datatype=XSD.string))) + + def log_cancelled_run(self, run_id: str): + """Cancel a queued run, or ask a run in progress to stop; raises RuntimeError for any other run. + + A queued run that is cancelled never started, so it has neither a beginning nor an end. + """ + with self._run(run_id) as (bundle, run): + state = bundle.value(run, OSLC_AUTO.state) + if state == OSLC_AUTO.queued: + bundle.set((run, OSLC_AUTO.state, OSLC_AUTO.canceled)) + elif state == OSLC_AUTO.inProgress: + bundle.set((run, OSLC_AUTO.state, OSLC_AUTO.canceling)) else: - raise RuntimeError(f"run '{run_id}' is {run.state} -- only a queued run or one in progress can be cancelled") + raise RuntimeError(f"run '{run_id}' is {state.fragment} -- only a queued run or one in progress can be cancelled") def log_host_info(self, run_id: str, host_info: dict): - """Record the machine executing the run, from ``hostname``, ``os``, ``python`` and ``cpu``.""" - with self._run(run_id) as run: - run.update(host=Host(host_info.get("hostname"), host_info.get("os"), host_info.get("python"), host_info.get("cpu"))) - - def close(self): - self.store.close() - - def _end(self, run_id, end_time, verdict, fail_trace=None): - with self._run(run_id) as run: - if run.state is State.CANCELING: - # The shapes keep a fail trace for a failed or error verdict only. - run.update(state=State.CANCELED, verdict=Verdict.UNAVAILABLE, end_time=end_time) - elif run.state is State.IN_PROGRESS: - run.update(state=State.COMPLETE, verdict=verdict, end_time=end_time, fail_trace=fail_trace) - else: - raise RuntimeError(f"run '{run_id}' is {run.state} -- only a started run can end") + """Record the machine executing the run from ``hostname``, ``os``, ``python`` and ``cpu``; other keys are not recorded.""" + with self._run(run_id) as (bundle, run): + host = URIRef(f"{run}/host") + bundle.add((host, RDF.type, REC.Host)) + bundle.add((host, RDF.type, PROV.Location)) + for key, predicate in HOST_TERMS.items(): + if host_info.get(key): + bundle.set((host, predicate, Literal(host_info[key]))) + bundle.set((run, PROV.atLocation, host)) diff --git a/rec/provenance.py b/rec/provenance.py index da658fa..b8c4efb 100644 --- a/rec/provenance.py +++ b/rec/provenance.py @@ -1,19 +1,15 @@ -"""A run record as a PROV bundle on the prov-extension and rec vocabularies, and back.""" +"""The vocabulary of a run's provenance bundle: prov-extension, rec, and OSLC Automation state and verdict.""" -from datetime import datetime -from typing import Any +import re -from rdf_utils import DatasetFormat -from rdf_utils.models.prov import PackageInfo, load_execution_prov, load_pkg_prov -from rdf_utils.models.time import add_wall_instant -from rdflib import XSD, Dataset, Graph, Literal, Namespace, URIRef -from rdflib.namespace import PROV, RDF, SDO, TIME -from rdflib.term import Node +from rdflib import XSD, Namespace +from rdflib.namespace import PROV, SDO, TIME from rec import State, Verdict -from rec.record import Host, RunRecord 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#") @@ -29,7 +25,6 @@ VERDICTS = { Verdict.UNAVAILABLE: OSLC_AUTO.unavailable, Verdict.PASSED: OSLC_AUTO.passed, - Verdict.WARNING: OSLC_AUTO.warning, Verdict.FAILED: OSLC_AUTO.failed, Verdict.ERROR: OSLC_AUTO.error, } @@ -43,101 +38,5 @@ "time": TIME, "xsd": XSD, } - - -def dataset(record: RunRecord, base: str = RUN_BASE) -> Dataset: - """The run in its bundle, attributed to its recorder: a `prov-ext:Execution` and an - `oslc_auto:AutomationResult` with its state and verdict; once started, run by its recorder.""" - ds = Dataset() - for prefix, namespace in PREFIXES.items(): - ds.bind(prefix, namespace) - g = ds.graph(record.bundle) - # The bundle's id is kept in the record, so these are rdf-utils `create_bundle`'s triples - # under an id minted once rather than on every write. - g.add((record.bundle, RDF.type, PROV.Bundle)) - g.add((record.bundle, PROV.wasAttributedTo, record.recorder.purl)) - load_pkg_prov(g, record.recorder) - - run = URIRef(base + record.run_id) - g.add((run, RDF.type, PROV_EXT.Execution)) - g.add((run, RDF.type, OSLC_AUTO.AutomationResult)) - g.add((run, OSLC_AUTO.state, STATES[record.state])) - g.add((run, OSLC_AUTO.verdict, VERDICTS[record.verdict])) - for value, predicate in ((record.queued_time, REC["queued-time"]), (record.heartbeat_time, REC["heartbeat-time"])): - if value: - g.add((run, predicate, Literal(value))) - if record.fail_trace: - g.add((run, REC["fail-trace"], Literal(record.fail_trace, datatype=XSD.string))) - - ended = None - if record.end_time: - ended = URIRef(f"{run}/end") - add_wall_instant(g, ended, record.end_time) - if record.start_time: - started = URIRef(f"{run}/beginning") - add_wall_instant(g, started, record.start_time) - # What the run executed is recorded by the tool that knows it, in its own bundle. - load_execution_prov(g, run, (), record.recorder.purl, started, ended) - elif ended is not None: - # A queued run cancelled before it started: it has an end, but no beginning or recorder. - g.add((run, TIME.hasEnd, ended)) - - if record.host: - host = URIRef(f"{run}/host") - g.add((host, RDF.type, REC.Host)) - g.add((host, RDF.type, PROV.Location)) - for key, predicate in HOST_TERMS.items(): - if getattr(record.host, key): - g.add((host, predicate, Literal(getattr(record.host, key)))) - g.add((run, PROV.atLocation, host)) - return ds - - -def record(ds: Dataset, run_id: str, base: str = RUN_BASE) -> RunRecord: - """The record ``dataset`` wrote.""" - run = URIRef(base + run_id) - g = next(graph for graph in ds.graphs() if (run, OSLC_AUTO.state, None) in graph) - host = g.value(run, PROV.atLocation) - return RunRecord( - run_id=run_id, - bundle=g.identifier, - state=next(state for state, iri in STATES.items() if iri == g.value(run, OSLC_AUTO.state)), - verdict=next(verdict for verdict, iri in VERDICTS.items() if iri == g.value(run, OSLC_AUTO.verdict)), - queued_time=_python(g.value(run, REC["queued-time"])), - start_time=_python(g.value(run, TIME.hasBeginning / TIME.inXSDDateTimeStamp)), - end_time=_python(g.value(run, TIME.hasEnd / TIME.inXSDDateTimeStamp)), - heartbeat_time=_python(g.value(run, REC["heartbeat-time"])), - fail_trace=_python(g.value(run, REC["fail-trace"])), - recorder=_package(g, g.value(g.identifier, PROV.wasAttributedTo)), - host=Host(**{key: _python(g.value(host, predicate)) for key, predicate in HOST_TERMS.items()}) if host else None, - ) - - -def serialize(ds: Dataset, fmt: DatasetFormat) -> str: - """The dataset in FMT; JSON-LD compacted on the vocabularies' prefixes.""" - if fmt is DatasetFormat.JSON_LD: - return ds.serialize(format=fmt, context={prefix: str(ns) for prefix, ns in PREFIXES.items()}, indent=2) - return ds.serialize(format=fmt) - - -def _package(g: Graph, purl: Node) -> PackageInfo: - """The package `load_pkg_prov` wrote at PURL; it writes no distribution name or directory.""" - revision = _python(g.value(purl, SDO.identifier)) - return PackageInfo( - name=str(g.value(purl, SDO.name)), - purl=URIRef(purl), - version=_python(g.value(purl, SDO.softwareVersion)), - revision=revision.removesuffix("-dirty") if revision else None, - repository=_python(g.value(purl, SDO.codeRepository)), - dirty=bool(revision and revision.endswith("-dirty")), - ) - - -def _python(term: Node | None) -> Any: - """A term as the value the record holds: a literal's Python value, an IRI as its string.""" - if term is None: - return None - # rdflib maps no Python type to xsd:dateTimeStamp. - if isinstance(term, Literal) and term.datatype == XSD.dateTimeStamp: - return datetime.fromisoformat(str(term)) - return term.toPython() if isinstance(term, Literal) else str(term) +# 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/record.py b/rec/record.py deleted file mode 100644 index 8763f65..0000000 --- a/rec/record.py +++ /dev/null @@ -1,50 +0,0 @@ -"""What rec records of a run, independent of where it is stored.""" - -import re -from dataclasses import dataclass -from datetime import datetime - -from rdf_utils.models.prov import PackageInfo -from rdflib import URIRef - -from rec import State, Verdict - -# 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._~-]+") - - -@dataclass -class Host: - hostname: str | None = None - os: str | None = None - python: str | None = None - cpu: str | None = None - - -@dataclass -class RunRecord: - """What rec knows of a run; also what a store's ``edit`` yields to change it. - - ``bundle`` names the run's provenance bundle and ``recorder`` is the rec that writes it, both - set on the run's first edit. - """ - - run_id: str - bundle: URIRef | None = None - state: State = State.NEW - verdict: Verdict = Verdict.UNAVAILABLE - queued_time: datetime | None = None - start_time: datetime | None = None - end_time: datetime | None = None - heartbeat_time: datetime | None = None - fail_trace: str | None = None - recorder: PackageInfo | None = None - host: Host | None = None - - def __post_init__(self): - if not RUN_ID.fullmatch(self.run_id): - raise ValueError(f"'{self.run_id}' is not a run id -- use letters, digits, '-', '.', '_' or '~', not '.' or '..'") - - def update(self, **values): - for name, value in values.items(): - setattr(self, name, value) diff --git a/rec/run.py b/rec/run.py index 27d7ded..0254d25 100644 --- a/rec/run.py +++ b/rec/run.py @@ -4,8 +4,6 @@ import socket import threading import traceback -from collections.abc import Sequence -from contextlib import ExitStack, contextmanager from uuid import uuid4 from rec import State, Verdict @@ -14,20 +12,6 @@ logger = logging.getLogger(__name__) -class IntervalTimer(threading.Thread): - def __init__(self, event, func, interval=10.0): - # A daemon: a beat stuck on a store must not keep the process alive once the run is over. - super().__init__(daemon=True) - self.stopped = event - self.func = func - self.interval = interval - - def run(self): - while not self.stopped.wait(self.interval): - self.func() - self.func() - - def host_info(): """Information about the machine executing a run""" return { @@ -39,110 +23,58 @@ def host_info(): class Run: - def __init__( - self, - observers: Sequence[Observer] = (), - run_id: str | None = None, - ): + def __init__(self, observer: Observer, run_id: str | None = None): + """ + :param observer: Records the run in its store + :param run_id: The run's id in the store; a UUID is minted when none is given + """ + self.observer = observer self._id = run_id - self.observers = list(observers) - # A start holds every store's record at once; a store held twice would wait on itself. - if len({id(observer.store) for observer in self.observers}) < len(self.observers): - raise ValueError("'observers' share a store -- give each its own store") self.result = None - self._heartbeat = None self.beat_interval = 10 + self._stop_beating = threading.Event() @property def id(self): - """The run's identity, the same in every observer; minted here when the caller gave none""" + """The run's identity in the store; minted here when the caller gave none""" if self._id is None: self._id = str(uuid4()) return self._id @property - def state(self): - """The run's state as the first observer's store keeps it, ``new`` until it is stored""" - record = self.observers[0].store.load(self.id) if self.observers else None - return record.state if record else State.NEW + def state(self) -> State: + """The run's state as the store keeps it, ``new`` until it is stored""" + return self.observer.lifecycle(self.id)[0] @property - def verdict(self): - """The run's verdict as the first observer's store keeps it""" - record = self.observers[0].store.load(self.id) if self.observers else None - return record.verdict if record else Verdict.UNAVAILABLE - - @contextmanager - def _held(self): - """Every store's record open at once: one refusal leaves them all unchanged; a failed save can still split them.""" - with ExitStack() as held: - for observer in self.observers: - held.enter_context(observer._hold(self.id)) - yield - - def _start_heartbeat(self): - if self.beat_interval > 0: - self._stop_heartbeat_event = threading.Event() - self._heartbeat = IntervalTimer(self._stop_heartbeat_event, self._emit_heartbeat, self.beat_interval) - self._heartbeat.start() - - def _stop_heartbeat(self): - 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) - logger.debug("Run %s still running", self.id) - - # Update info on observers - for observer in self.observers: - observer.log_run_heartbeat(self.id, beat_time) - - def _emit_started(self): - """Record the run as started, on the machine executing it""" - start_time = datetime.datetime.now(datetime.UTC) - logger.info("Starting run %s", self.id) - with self._held(): - for observer in self.observers: - observer.log_started_run(self.id, start_time) - self.log_host_info(host_info()) + def verdict(self) -> Verdict: + """The run's verdict as the store keeps it""" + return self.observer.lifecycle(self.id)[1] - def _emit_ended(self, error=None): - """End the run as passed, error or failed by ``error``, or as canceled if a cancel came while it ran""" - end_time = datetime.datetime.now(datetime.UTC) - with self._held(): - for observer in self.observers: - if error is None: - observer.log_completed_run(self.id, end_time) - elif isinstance(error, KeyboardInterrupt): - observer.log_interrupted_run(self.id, end_time, _fail_trace(error)) - else: - observer.log_failed_run(self.id, end_time, _fail_trace(error)) - logger.log(logging.INFO if error is None else logging.ERROR, "Ended run %s", self.id, exc_info=error) + def _beat(self): + while not self._stop_beating.wait(self.beat_interval): + # A store briefly out of reach must not stop the beats that follow. + try: + self.observer.log_run_heartbeat(self.id, datetime.datetime.now(datetime.UTC)) + except Exception: + logger.exception("Run %s could not record its heartbeat", self.id) def main(self) -> object: pass def queue(self): """Record the run as queued, before a runner starts it; the store refuses a run that is not new""" - queued_time = datetime.datetime.now(datetime.UTC) - with self._held(): - for observer in self.observers: - observer.log_queued_run(self.id, queued_time) + self.observer.log_queued_run(self.id, datetime.datetime.now(datetime.UTC)) logger.info("Queued run %s", self.id) return self.id def cancel(self): """Cancel a queued run, or ask one in progress to stop: it ends as canceled once ``main`` returns. - Any holder of the run's id can cancel it, through a ``Run`` with that ``run_id`` on the same stores. + Any holder of the run's id can cancel it, through a ``Run`` with that ``run_id`` on the same store. ``main`` sees the request as ``self.state`` being ``State.CANCELING``. """ - cancel_time = datetime.datetime.now(datetime.UTC) - with self._held(): - for observer in self.observers: - observer.log_cancelled_run(self.id, cancel_time) + self.observer.log_cancelled_run(self.id) logger.info("Cancelled run %s", self.id) def run(self): @@ -150,19 +82,40 @@ def run(self): Start the run, execute ``main`` and record how it ended :returns: What ``main`` returned; rec does not record it :raises RuntimeError: The store holds the run as started or canceled + :raises BaseException: What interrupted ``main``, e.g. ``KeyboardInterrupt`` or ``SystemExit``, once the run is ended as error """ - self._emit_started() - failure = None + self.observer.log_started_run(self.id, datetime.datetime.now(datetime.UTC)) + logger.info("Started run %s", self.id) + self.log_host_info(host_info()) + beating = threading.Thread(target=self._beat, daemon=True) if self.beat_interval > 0 else None + error = None try: - # Stopped before the end is recorded: a late beat would find the run ended and raise. - try: - self._start_heartbeat() - self.result = self.main() - finally: - self._stop_heartbeat() - except (KeyboardInterrupt, Exception) as error: - failure = error - self._emit_ended(failure) + if beating is not None: + beating.start() + self.result = self.main() + except BaseException as caught: + error = caught + finally: + # Stopped before the end is recorded: a late beat would find the run ended. + self._stop_beating.set() + if beating is not None: + beating.join() + if error is None: + verdict = Verdict.PASSED + elif isinstance(error, Exception): + verdict = Verdict.FAILED + else: + verdict = Verdict.ERROR + self.observer.log_ended_run( + self.id, + datetime.datetime.now(datetime.UTC), + verdict, + "".join(traceback.format_exception(error)) if error is not None else None, + ) + logger.log(logging.INFO if error is None else logging.ERROR, "Ended run %s", self.id, exc_info=error) + # An interrupt is the process being asked to stop: recorded, then passed on. + if error is not None and not isinstance(error, Exception): + raise error return self.result def log_host_info(self, host_info: dict): @@ -170,9 +123,4 @@ def log_host_info(self, host_info: dict): Log information about the machine executing this run :param host_info: ``hostname``, ``os``, ``python``, ``cpu``; see :func:`host_info` """ - for observer in self.observers: - observer.log_host_info(self.id, host_info) - - -def _fail_trace(error): - return "".join(traceback.format_exception(error)) if error is not None else None + self.observer.log_host_info(self.id, host_info) diff --git a/rec/stores/__init__.py b/rec/stores/__init__.py index b5d4fb3..2b9d5b7 100644 --- a/rec/stores/__init__.py +++ b/rec/stores/__init__.py @@ -1,30 +1 @@ -"""Where run records are kept: any object with these methods is a store.""" - -from contextlib import AbstractContextManager -from typing import Protocol - -from rec import State -from rec.record import RunRecord - - -class Store(Protocol): - def load(self, run_id: str) -> RunRecord | None: - """Return the stored record of a run, or None if the run is not stored.""" - ... - - def edit(self, run_id: str) -> AbstractContextManager[RunRecord]: - """Lock a run for changing and keep the changes to its record when the with block exits. - - Yields a new record if the run is not stored. Other edits of the same run, - also from other processes, wait until the block exits. If the block - raises, nothing is kept. - """ - ... - - def run_ids(self, state: State | None = None) -> list[str]: - """Return the ids of all stored runs, or only of those in the given state.""" - ... - - def close(self) -> None: - """Close the store's connections; the code that created the store calls it once.""" - ... +"""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 index 4d460ad..ca13689 100644 --- a/rec/stores/file_store.py +++ b/rec/stores/file_store.py @@ -1,4 +1,4 @@ -"""A store keeping each run as one file in a directory.""" +"""A store keeping each run's provenance bundle as a JSON-LD file in a directory.""" import fcntl from contextlib import contextmanager @@ -7,41 +7,36 @@ from rdf_utils import DatasetFormat from rdflib import Dataset -from rec import State, provenance -from rec.record import RUN_ID, RunRecord -from rec.stores import Store +from rec.provenance import CONTEXT -class FileStore(Store): - def __init__(self, directory, fmt: DatasetFormat = DatasetFormat.JSON_LD, base: str = provenance.RUN_BASE): +class FileStore: + def __init__(self, directory): """ - :param directory: Where the files go; created on first write - :param fmt: The format of the run's provenance bundle, kept as ``.`` - :param base: IRI base of the run nodes + :param directory: Where the files go, ``.ld.json`` each; created on first write """ self.directory = Path(directory) - self.fmt = DatasetFormat(fmt) - self.base = base def path(self, run_id: str) -> Path: - """Return the run's file, ``.`` in the directory. + """Return the run's file, ``.ld.json`` in the directory. - :raises ValueError: ``run_id`` is not a run id (``rec.record.RUN_ID``) + :raises ValueError: ``run_id`` would name a file outside the directory, e.g. ``../x`` """ - # A load comes before any record, and an id like '../x' must not read outside the directory. - if not RUN_ID.fullmatch(run_id): - raise ValueError(f"'{run_id}' is not a run id -- use letters, digits, '-', '.', '_' or '~', not '.' or '..'") - return self.directory / f"{run_id}.{self.fmt.extension}" + 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) -> RunRecord | None: + 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 provenance.record(Dataset().parse(path, format=self.fmt), run_id, self.base) + return Dataset().parse(path, format=DatasetFormat.JSON_LD) @contextmanager def edit(self, run_id: str): - """Yield the run's ``RunRecord`` under an ``flock`` on ``.lock``, and save it when the block exits. + """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. """ @@ -50,16 +45,8 @@ def edit(self, run_id: str): # 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) - record = self.load(run_id) or RunRecord(run_id) - yield record + 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(provenance.serialize(provenance.dataset(record, self.base), self.fmt)) + temporary.write_text(ds.serialize(format=DatasetFormat.JSON_LD, context=CONTEXT, indent=2)) temporary.replace(path) - - def run_ids(self, state: State | None = None) -> list[str]: - suffix = f".{self.fmt.extension}" - run_ids = sorted(path.name.removesuffix(suffix) for path in self.directory.glob(f"*{suffix}")) - return [run_id for run_id in run_ids if state is None or self.load(run_id).state is state] - - def close(self) -> None: - """Nothing stays open between writes.""" diff --git a/rec/stores/mariadb.sql b/rec/stores/mariadb.sql deleted file mode 100644 index 985e8c7..0000000 --- a/rec/stores/mariadb.sql +++ /dev/null @@ -1,5 +0,0 @@ -CREATE TABLE IF NOT EXISTS {prefix}_runs ( - id INT AUTO_INCREMENT PRIMARY KEY, - run_id VARCHAR(255) NOT NULL UNIQUE, - bundle LONGTEXT -); diff --git a/rec/stores/mariadb_store.py b/rec/stores/mariadb_store.py index c7af0c3..4f4ff02 100644 --- a/rec/stores/mariadb_store.py +++ b/rec/stores/mariadb_store.py @@ -1,21 +1,18 @@ -"""A store keeping runs in MariaDB: a row per run, holding its provenance bundle.""" +"""A store keeping runs in MariaDB: a row per run, holding its provenance bundle as JSON-LD.""" import os import threading from contextlib import contextmanager -from importlib.resources import files import mariadb from dotenv import load_dotenv from rdf_utils import DatasetFormat from rdflib import Dataset -from rec import State, provenance -from rec.record import RunRecord -from rec.stores import Store +from rec.provenance import CONTEXT -class MariaDBStore(Store): +class MariaDBStore: def __init__(self, db_name: str = "logbook", prefix: str = "logs"): """ Store in MariaDB tables, connecting with ``MARIADB_USER``, ``MARIADB_PASSWORD``, @@ -26,7 +23,6 @@ def __init__(self, db_name: str = "logbook", prefix: str = "logs"): order runs were added and ``bundle`` its provenance bundle as JSON-LD """ load_dotenv() - self.db_name = db_name self.prefix = prefix self.conn = mariadb.connect( user=os.getenv("MARIADB_USER"), @@ -39,53 +35,47 @@ def __init__(self, db_name: str = "logbook", prefix: str = "logs"): 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() - schema = files("rec.stores").joinpath("mariadb.sql").read_text().format(prefix=prefix) - for statement in schema.split(";"): - if statement.strip(): - self.cursor.execute(statement) + # 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) -> RunRecord | None: + 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 provenance.record(Dataset().parse(data=row[0], format=DatasetFormat.JSON_LD), run_id) + return Dataset().parse(data=row[0], format=DatasetFormat.JSON_LD) @contextmanager def edit(self, run_id: str): - """Yield the run's ``RunRecord`` in one transaction, and save it when the block exits; roll back if it raises. - - The run's row is locked with ``SELECT ... FOR UPDATE``, and inserted first if the run is new. - """ + """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: - self.cursor.execute(f"SELECT id, bundle FROM {self.prefix}_runs WHERE run_id = ? FOR UPDATE", (run_id,)) - row = self.cursor.fetchone() - if row is None: - record = RunRecord(run_id) - # Inserted before the block runs, so a concurrent edit of the same new run waits on its lock. - self.cursor.execute(f"INSERT INTO {self.prefix}_runs (run_id) VALUES (?) RETURNING id, bundle", (run_id,)) - row = self.cursor.fetchone() - else: - record = provenance.record(Dataset().parse(data=row[1], format=DatasetFormat.JSON_LD), run_id) - yield record + # 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"UPDATE {self.prefix}_runs SET bundle = ? WHERE id = ?", - (provenance.serialize(provenance.dataset(record), DatasetFormat.JSON_LD), row[0]), + 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 run_ids(self, state: State | None = None) -> list[str]: - with self._lock: - self.cursor.execute(f"SELECT run_id FROM {self.prefix}_runs ORDER BY id") - run_ids = [row[0] for row in self.cursor.fetchall()] - return [run_id for run_id in run_ids if state is None or self.load(run_id).state is state] - def close(self) -> None: self.cursor.close() self.conn.close() diff --git a/tests/test_mariadb_store.py b/tests/test_mariadb_store.py index 066d858..216c30d 100644 --- a/tests/test_mariadb_store.py +++ b/tests/test_mariadb_store.py @@ -1,16 +1,21 @@ import os +from pathlib import Path from uuid import uuid4 import pytest -from rdflib.compare import isomorphic +from pyshacl import validate +from rdflib import Graph pytest.importorskip("mariadb", reason="the MariaDB driver is an optional extra") -from rec import State, Verdict, provenance # noqa: E402 +from rec import State, Verdict # noqa: E402 from rec.observer import Observer # noqa: E402 from rec.run import Run # noqa: E402 -from rec.stores.file_store import FileStore # 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, @@ -32,26 +37,23 @@ def main(self): return "ok" -def test_a_row_keeps_the_same_bundle_as_a_file(store, tmp_path): - files = FileStore(tmp_path) - runs = [QuickRun(observers=[Observer(store), Observer(files)], run_id=f"run-{i}") for i in range(3)] - for run in runs: - run.beat_interval = 0 - run.run() - for run in runs: - from_tables, from_file = store.load(run.id), files.load(run.id) - assert from_tables is not None and from_file is not None - # Each store mints its own bundle on the run's first edit; the run inside it is the same. - from_tables.bundle = from_file.bundle - assert isomorphic( - provenance.dataset(from_tables).graph(from_tables.bundle), - provenance.dataset(from_file).graph(from_file.bundle), - ) - assert store.run_ids(State.COMPLETE) == ["run-0", "run-1", "run-2"] - - -def test_a_queued_run_is_cancelled_by_id(store): - QuickRun(observers=[Observer(store)], run_id="queued").queue() - assert store.run_ids(State.IN_PROGRESS) == [] - Run(observers=[Observer(MariaDBStore(db_name=TEST_DATABASE, prefix=store.prefix))], run_id="queued").cancel() - assert (store.load("queued").state, store.load("queued").verdict) == (State.CANCELED, Verdict.UNAVAILABLE) +def test_a_row_keeps_the_run_as_a_valid_bundle(store): + QuickRun(Observer(store), run_id="run-0").run() + assert Observer(store).lifecycle("run-0") == (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): + QuickRun(Observer(store), run_id="queued").queue() + scheduler = MariaDBStore(db_name=TEST_DATABASE, prefix=store.prefix) + Run(Observer(scheduler), run_id="queued").cancel() + scheduler.close() + assert Observer(store).lifecycle("queued") == (State.CANCELED, Verdict.UNAVAILABLE) + + +def test_run_ids_differing_in_case_are_two_runs(store): + QuickRun(Observer(store), run_id="Pick-1").run() + QuickRun(Observer(store), run_id="pick-1").queue() + assert Observer(store).lifecycle("Pick-1") == (State.COMPLETE, Verdict.PASSED) + assert Observer(store).lifecycle("pick-1") == (State.QUEUED, Verdict.UNAVAILABLE) diff --git a/tests/test_run.py b/tests/test_run.py index c43d934..b6c639d 100644 --- a/tests/test_run.py +++ b/tests/test_run.py @@ -1,17 +1,16 @@ import os import threading +from datetime import datetime from pathlib import Path import pytest from pyshacl import validate -from rdf_utils import DatasetFormat from rdflib import Graph, URIRef from rdflib.namespace import PROV, RDF, TIME -from rec import State, Verdict, provenance +from rec import State, Verdict from rec.observer import Observer -from rec.provenance import OSLC_AUTO, PROV_EXT, REC -from rec.record import RunRecord +from rec.provenance import OSLC_AUTO, PROV_EXT, REC, RUN_BASE from rec.run import Run from rec.stores.file_store import FileStore @@ -36,55 +35,82 @@ def main(self): raise KeyboardInterrupt +class ExitingRun(Run): + def main(self): + raise SystemExit(3) + + class StoppedRun(Run): def main(self): # A scheduler holding only the id asks the run to stop while it is in progress. - Run(observers=[Observer(self.observers[0].store)], run_id=self.id).cancel() + Run(Observer(self.observer.store), run_id=self.id).cancel() if self.state is State.CANCELING: return "stopped" return "finished" -@pytest.fixture(params=list(DatasetFormat)) -def store(request, tmp_path): - return FileStore(tmp_path, fmt=request.param) +class CrashedWhileStoppingRun(Run): + def main(self): + Run(Observer(self.observer.store), run_id=self.id).cancel() + raise ValueError("gripper jammed while releasing") + + +class SlowRun(Run): + def main(self): + threading.Event().wait(0.05) + +@pytest.fixture +def store(tmp_path): + return FileStore(tmp_path) -def test_a_completed_run_is_an_execution_by_rec(store): - run = CalibrationRun(observers=[Observer(store)], run_id="run-1") - run.beat_interval = 0 - assert run.run() == "calibrated" - record = store.load("run-1") - g = provenance.dataset(record).graph(record.bundle) - ok, _, report = validate(g, shacl_graph=SHAPES, inference="rdfs") +def test_a_completed_run_is_an_execution_by_rec_in_a_bundle_attributed_to_rec(store): + observer = Observer(store) + assert CalibrationRun(observer, run_id="run-1").run() == "calibrated" + + ds = store.load("run-1") + ok, _, report = validate(ds, shacl_graph=SHAPES, inference="rdfs") assert ok, report - node = URIRef(provenance.RUN_BASE + "run-1") - assert (node, RDF.type, PROV_EXT.Execution) in g - assert (record.bundle, RDF.type, PROV.Bundle) in g - assert g.value(record.bundle, PROV.wasAttributedTo) == record.recorder.purl == g.value(node, PROV.wasAssociatedWith) - assert record.recorder.name == "rec" + [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) == observer.recorder.purl == bundle.value(node, PROV.wasAssociatedWith) + assert observer.lifecycle("run-1") == (State.COMPLETE, Verdict.PASSED) def test_a_run_keeps_one_bundle_through_its_lifecycle(store): - run = CalibrationRun(observers=[Observer(store)], run_id="run-b") - run.beat_interval = 0 + run = CalibrationRun(Observer(store), run_id="run-b") run.queue() - queued = store.load("run-b").bundle + queued = {graph.identifier for graph in store.load("run-b").graphs() if (graph.identifier, RDF.type, PROV.Bundle) in graph} run.run() - assert queued is not None and store.load("run-b").bundle == queued + 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_an_event_changes_only_its_own_triples(store): + """A triple another tool put in the run's bundle survives rec's later events.""" + observer = Observer(store) + CalibrationRun(observer, run_id="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"))) + CalibrationRun(observer, run_id="run-k").run() + 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): - CalibrationRun(observers=[Observer(store)], run_id="run-q").queue() - record = store.load("run-q") - g = provenance.dataset(record).graph(record.bundle) - ok, _, report = validate(g, shacl_graph=SHAPES, inference="rdfs") + CalibrationRun(Observer(store), run_id="run-q").queue() + ds = store.load("run-q") + ok, _, report = validate(ds, shacl_graph=SHAPES, inference="rdfs") assert ok, report - node = URIRef(provenance.RUN_BASE + "run-q") - assert {PROV_EXT.Execution, OSLC_AUTO.AutomationResult} <= set(g.objects(node, RDF.type)) - assert g.value(node, TIME.hasBeginning) is None and g.value(node, PROV.wasAssociatedWith) is None - assert g.value(node, REC["queued-time"]) is not None + 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 # Each starts from a completed run and breaks one rule of the run's shape. @@ -102,75 +128,97 @@ def test_a_queued_run_has_not_executed_yet(store): ids=["without a verdict", "queued with a start time", "not an execution", "not an automation result"], ) def test_the_shapes_refuse_a_run_that_contradicts_its_state(store, removed, added): - run = CalibrationRun(observers=[Observer(store)], run_id="run-x") - run.beat_interval = 0 - run.run() - record = store.load("run-x") - g = provenance.dataset(record).graph(record.bundle) - node = URIRef(provenance.RUN_BASE + "run-x") + CalibrationRun(Observer(store), run_id="run-x").run() + ds = store.load("run-x") + [bundle] = [graph for graph in ds.graphs() if (graph.identifier, RDF.type, PROV.Bundle) in graph] + node = URIRef(RUN_BASE + "run-x") for predicate, value in removed: - g.remove((node, predicate, value)) + bundle.remove((node, predicate, value)) for predicate, value in added: - g.add((node, predicate, value)) - assert not validate(g, shacl_graph=SHAPES, inference="rdfs")[0] + bundle.add((node, predicate, value)) + assert not validate(ds, shacl_graph=SHAPES, inference="rdfs")[0] -@pytest.mark.parametrize( - ("cls", "verdict", "trace"), - [(FailingRun, Verdict.FAILED, "ValueError: no gripper attached"), (InterruptedRun, Verdict.ERROR, "KeyboardInterrupt")], -) -def test_a_run_that_stops_early_records_how(store, cls, verdict, trace): - run = cls(observers=[Observer(store)], run_id="run-3") - run.beat_interval = 0 - run.run() - record = store.load("run-3") - assert (record.state, record.verdict) == (State.COMPLETE, verdict) - assert trace in record.fail_trace - ok, _, report = validate(provenance.dataset(record).graph(record.bundle), shacl_graph=SHAPES, inference="rdfs") +def test_a_run_whose_main_raises_fails_with_its_trace(store): + observer = Observer(store) + FailingRun(observer, run_id="run-f").run() + assert observer.lifecycle("run-f") == (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(("cls", "interrupt"), [(InterruptedRun, KeyboardInterrupt), (ExitingRun, SystemExit)]) +def test_an_interrupted_run_ends_as_error_and_the_interrupt_goes_on(store, cls, interrupt): + observer = Observer(store) + with pytest.raises(interrupt): + cls(observer, run_id="run-i").run() + assert observer.lifecycle("run-i") == (State.COMPLETE, Verdict.ERROR) + ok, _, report = validate(store.load("run-i"), shacl_graph=SHAPES, inference="rdfs") assert ok, report -def test_only_a_queued_run_is_cancelled(store): - queued = CalibrationRun(observers=[Observer(store)], run_id="run-q") +def test_only_a_queued_run_or_one_in_progress_is_cancelled(store): + observer = Observer(store) + queued = CalibrationRun(observer, run_id="run-q") queued.queue() # A scheduler holding only the id cancels a run it did not create, and the store decides. - Run(observers=[Observer(store)], run_id="run-q").cancel() - assert queued.state is State.CANCELED + Run(Observer(store), run_id="run-q").cancel() + assert (queued.state, queued.verdict) == (State.CANCELED, Verdict.UNAVAILABLE) with pytest.raises(RuntimeError, match="is canceled"): queued.run() - record = store.load("run-q") - assert (record.state, record.verdict) == (State.CANCELED, Verdict.UNAVAILABLE) - g = provenance.dataset(record).graph(record.bundle) - ok, _, report = validate(g, shacl_graph=SHAPES, inference="rdfs") + ds = store.load("run-q") + ok, _, report = validate(ds, shacl_graph=SHAPES, inference="rdfs") assert ok, report - assert g.value(URIRef(provenance.RUN_BASE + "run-q"), TIME.hasBeginning) is None + 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 = CalibrationRun(observers=[Observer(store)], run_id="run-d") - done.beat_interval = 0 - done.run() + CalibrationRun(observer, run_id="run-d").run() with pytest.raises(RuntimeError, match="only a queued run or one in progress"): - Run(observers=[Observer(store)], run_id="run-d").cancel() - assert store.load("run-d").verdict is Verdict.PASSED - assert store.run_ids(State.CANCELED) == ["run-q"] + Run(Observer(store), run_id="run-d").cancel() + assert observer.lifecycle("run-d") == (State.COMPLETE, Verdict.PASSED) def test_a_run_in_progress_stops_when_cancelled(store): - run = StoppedRun(observers=[Observer(store)], run_id="run-s") - run.beat_interval = 0 + observer = Observer(store) + run = StoppedRun(observer, run_id="run-s") assert run.run() == "stopped" - record = store.load("run-s") - assert (record.state, record.verdict) == (State.CANCELED, Verdict.UNAVAILABLE) - assert record.start_time is not None and record.end_time is not None - ok, _, report = validate(provenance.dataset(record).graph(record.bundle), shacl_graph=SHAPES, inference="rdfs") + assert observer.lifecycle("run-s") == (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): + observer = Observer(store) + CrashedWhileStoppingRun(observer, run_id="run-c").run() + assert observer.lifecycle("run-c") == (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 = SlowRun(Observer(store), run_id="run-h") + run.beat_interval = 0.01 + run.run() + 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 - with pytest.raises(RuntimeError, match="only a queued run or one in progress"): - run.cancel() def test_one_observer_records_many_runs_at_once(store): - """Every run is addressed by its id, and none closes the observer.""" + """Every run is addressed by its id, each locked on its own.""" observer = Observer(store) - runs = [CalibrationRun(observers=[observer], run_id=f"run-{i}") for i in range(6)] + runs = [SlowRun(observer, run_id=f"run-{i}") for i in range(6)] for run in runs: run.beat_interval = 0.01 threads = [threading.Thread(target=run.run) for run in runs] @@ -178,12 +226,28 @@ def test_one_observer_records_many_runs_at_once(store): thread.start() for thread in threads: thread.join() - assert store.run_ids(State.COMPLETE) == sorted(run.id for run in runs) + assert all(observer.lifecycle(run.id) == (State.COMPLETE, Verdict.PASSED) for run in runs) + + +def test_a_time_without_a_zone_is_refused_and_nothing_kept(store): + with pytest.raises(ValueError, match="has no time zone"): + Observer(store).log_queued_run("run-z", datetime(2026, 11, 12, 9, 30)) + assert store.load("run-z") is None + + +def test_a_run_recorded_under_another_base_is_not_read_as_this_one(store): + CalibrationRun(Observer(store), run_id="run-o").queue() + with pytest.raises(ValueError, match="recorded under another base"): + Observer(store, base="https://example.org/runs/").lifecycle("run-o") @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"): - RunRecord(run_id) - with pytest.raises(ValueError, match="is not a run id"): - store.path(run_id) + Observer(store).log_queued_run(run_id, datetime.now().astimezone()) + + +@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) From 4ae41f0e3ba0cc0731c2cdef7ba3086bfbf1ece6 Mon Sep 17 00:00:00 2001 From: Vamsi Kalagaturu Date: Thu, 12 Nov 2026 17:01:26 +0100 Subject: [PATCH 15/16] End a run whose start fails after it is recorded, and edit only the run's own bundle - run() records the host inside the guarded block, so a failure there ends the started run as failed; the heartbeat is joined only if it started - The Observer finds the run's bundle by the run's state, not the first prov:Bundle, and refuses a dataset holding a run under another base --- rec/observer.py | 5 ++++- rec/run.py | 5 +++-- tests/test_run.py | 34 +++++++++++++++++++++++++++++++++- 3 files changed, 40 insertions(+), 4 deletions(-) diff --git a/rec/observer.py b/rec/observer.py index 4cc70ee..67b5cdd 100644 --- a/rec/observer.py +++ b/rec/observer.py @@ -48,8 +48,11 @@ def _run(self, run_id: str): raise ValueError(f"'{run_id}' is not a run id -- use letters, digits, '-', '.', '_' or '~', not '.' or '..'") run = URIRef(self.base + run_id) with self.store.edit(run_id) as ds: - bundle = next((graph for graph in ds.graphs() if (graph.identifier, RDF.type, PROV.Bundle) in graph), None) + # The run's own bundle: another tool may keep its bundles in the same dataset. + bundle = next((graph for graph in ds.graphs() if (run, OSLC_AUTO.state, None) in graph), None) if bundle is None: + if any((None, OSLC_AUTO.state, None) in graph for graph in ds.graphs()): + raise ValueError(f"the bundle of run '{run_id}' has no '{run}' -- it was recorded under another base") bundle = ds.graph(create_bundle(ds, self.recorder.purl)) load_pkg_prov(bundle, self.recorder) bundle.add((run, RDF.type, PROV_EXT.Execution)) diff --git a/rec/run.py b/rec/run.py index 0254d25..eb925f4 100644 --- a/rec/run.py +++ b/rec/run.py @@ -86,10 +86,11 @@ def run(self): """ self.observer.log_started_run(self.id, datetime.datetime.now(datetime.UTC)) logger.info("Started run %s", self.id) - self.log_host_info(host_info()) beating = threading.Thread(target=self._beat, daemon=True) if self.beat_interval > 0 else None error = None + # Everything after the start is inside: whatever fails, the started run gets its end. try: + self.log_host_info(host_info()) if beating is not None: beating.start() self.result = self.main() @@ -98,7 +99,7 @@ def run(self): finally: # Stopped before the end is recorded: a late beat would find the run ended. self._stop_beating.set() - if beating is not None: + if beating is not None and beating.is_alive(): beating.join() if error is None: verdict = Verdict.PASSED diff --git a/tests/test_run.py b/tests/test_run.py index b6c639d..99bb864 100644 --- a/tests/test_run.py +++ b/tests/test_run.py @@ -5,6 +5,7 @@ import pytest from pyshacl import validate +from rdf_utils.models.prov import create_bundle from rdflib import Graph, URIRef from rdflib.namespace import PROV, RDF, TIME @@ -60,6 +61,14 @@ def main(self): threading.Event().wait(0.05) +class HostlessRun(Run): + def log_host_info(self, host_info): + raise OSError("no hostname") + + def main(self): + raise AssertionError("main must not run when the start cannot be completed") + + @pytest.fixture def store(tmp_path): return FileStore(tmp_path) @@ -101,6 +110,26 @@ def test_an_event_changes_only_its_own_triples(store): assert (URIRef(RUN_BASE + "run-k"), PROV.wasInfluencedBy, URIRef("https://example.org/schedule/1")) in ds +def test_another_tools_bundle_in_the_dataset_is_left_alone(store): + tool = URIRef("https://example.org/agent/scheduler") + with store.edit("run-t") as ds: + foreign = create_bundle(ds, tool) + observer = Observer(store) + CalibrationRun(observer, run_id="run-t").run() + assert observer.lifecycle("run-t") == (State.COMPLETE, Verdict.PASSED) + ds = store.load("run-t") + assert set(ds.graph(foreign)) == {(foreign, RDF.type, PROV.Bundle), (foreign, PROV.wasAttributedTo, tool)} + + +def test_a_run_that_cannot_finish_starting_still_ends(store): + observer = Observer(store) + HostlessRun(observer, run_id="run-n").run() + assert observer.lifecycle("run-n") == (State.COMPLETE, Verdict.FAILED) + ds = store.load("run-n") + ds.default_union = True + assert "OSError: no hostname" in str(ds.value(URIRef(RUN_BASE + "run-n"), REC["fail-trace"])) + + def test_a_queued_run_has_not_executed_yet(store): CalibrationRun(Observer(store), run_id="run-q").queue() ds = store.load("run-q") @@ -237,8 +266,11 @@ def test_a_time_without_a_zone_is_refused_and_nothing_kept(store): def test_a_run_recorded_under_another_base_is_not_read_as_this_one(store): CalibrationRun(Observer(store), run_id="run-o").queue() + elsewhere = Observer(store, base="https://example.org/runs/") + with pytest.raises(ValueError, match="recorded under another base"): + elsewhere.lifecycle("run-o") with pytest.raises(ValueError, match="recorded under another base"): - Observer(store, base="https://example.org/runs/").lifecycle("run-o") + elsewhere.log_cancelled_run("run-o") @pytest.mark.parametrize("run_id", ["../escape", "/tmp/escape", "nested/run", "a run", "läuft", "", ".", ".."]) From 19edcdec4f6dc696dad9e7ed653cb494c81473d2 Mon Sep 17 00:00:00 2001 From: Vamsi Kalagaturu Date: Thu, 12 Nov 2026 17:34:11 +0100 Subject: [PATCH 16/16] Make a run one handle over its bundle, and pin rdf-utils - Run(store, run_id, base) queues, starts, beats, ends, cancels and reads its lifecycle; run(work) does the steps around a plain function, replacing the Observer and subclassed main - Each step checks the state once in _step, stamps its time under the store's lock and changes only its triples; the host is recorded with the start - end refuses an unavailable verdict and a trace on a passed run; an interrupt is raised again even when the end cannot be recorded; the heartbeat join is bounded - MariaDB refuses a prefix that is not a table name; a stored run holds only rec's bundle - Follow rdf-utils add_wall_instant(graph, stamp, instant_id=) and pin rdf-utils to bad7c02, which no release tag includes yet - The example records fresh runs on every invocation --- README.md | 39 +++--- examples/robot_runs.py | 89 ++++++------ pyproject.toml | 2 +- rec/observer.py | 166 ---------------------- rec/run.py | 266 +++++++++++++++++++++++------------- rec/stores/mariadb_store.py | 4 + tests/test_mariadb_store.py | 32 +++-- tests/test_run.py | 230 +++++++++++-------------------- 8 files changed, 334 insertions(+), 494 deletions(-) delete mode 100644 rec/observer.py diff --git a/README.md b/README.md index db14904..6bc5fed 100644 --- a/README.md +++ b/README.md @@ -14,30 +14,30 @@ pip install -e ".[mariadb]" # and the MariaDB store ## Recording a run -A run is a `Run` subclass; `main` does the work. +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)`: ```python -from rec.observer import Observer from rec.run import Run from rec.stores.file_store import FileStore -class PickPlaceRun(Run): - def main(self): - return "placed" +def pick_and_place(run): + return "placed" -PickPlaceRun(Observer(FileStore("runs/prov")), run_id="pick-place-1").run() +Run(FileStore("runs/prov"), "pick-place-1").run(pick_and_place) ``` -`run()` records the start and the host, runs `main`, and ends the run as `passed`, `failed` -(`main` raised) or `error` (interrupted, e.g. `KeyboardInterrupt` or `SystemExit`, which `run()` -raises again once recorded). It returns what `main` returned; rec does not record it. +`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. -Each event changes only its own triples in the run's bundle: the store parses the bundle under its -lock, the `Observer` checks the run's state and sets what the event 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. +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. 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` @@ -48,16 +48,16 @@ helpers, in that tool's own bundle. State lives in the store, so any `Run` with the same id sees and changes the same run: ```python -DrawerRun(Observer(MariaDBStore()), run_id="drawer-2").queue() +Run(MariaDBStore(), "drawer-2").queue() # elsewhere, e.g. a scheduler with its own connection -Run(Observer(MariaDBStore()), run_id="drawer-2").cancel() +Run(MariaDBStore(), "drawer-2").cancel() ``` | State when cancelled | Result | |---|---| | `queued` | `canceled`; it never started, so it has no beginning or end | -| `in-progress` | `canceling`; `main` sees `self.state is State.CANCELING`, returns, and the run ends `canceled`; a `main` that raises instead ends `complete` with its verdict | +| `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 @@ -71,8 +71,9 @@ seconds, recorded as `rec:heartbeat-time`; a beat that fails is logged and the n | `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`; `Observer.lifecycle(run_id)` gives -its state and verdict. A run is recorded in one store. +`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 @@ -98,7 +99,7 @@ OSLC Automation 2.1; it is not a conformant `oslc_auto:AutomationResult`, which 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 `Observer`. +gets a UUID. The run's node is ``, `base` given to the `Run`. ## Examples diff --git a/examples/robot_runs.py b/examples/robot_runs.py index 50b1d92..5bb5def 100644 --- a/examples/robot_runs.py +++ b/examples/robot_runs.py @@ -1,5 +1,5 @@ """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. +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). """ @@ -7,72 +7,67 @@ import logging import threading import time +from uuid import uuid4 from rec import State -from rec.observer import Observer 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" -class PickPlaceRun(Run): - """Picks an object and places it, checking between motions whether it was asked to stop.""" - - motions = ("approach", "grasp", "lift", "transport", "place", "retreat") - - def main(self): - for done, motion in enumerate(self.motions): - if self.state is State.CANCELING: - logger.info("%s: stopped before %s", self.id, motion) - return f"stopped after {done} of {len(self.motions)} motions" - logger.info("%s: %s", self.id, motion) - time.sleep(0.5) - return "placed" - - -class DrawerOpeningRun(Run): - """Opens a drawer, and fails when the handle is further from its modelled pose than the gripper reaches.""" - - handle_offset = 0.04 - reach = 0.02 - - def main(self): - logger.info("%s: looking for the handle", self.id) - time.sleep(0.5) - if self.handle_offset > self.reach: - raise RuntimeError(f"handle is {self.handle_offset} m from its modelled pose -- the gripper reaches {self.reach} m") - return "opened" +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") - # A scheduler holds only the run ids, and its own store on the same files or tables. - for store, scheduler_store in ( - (FileStore("runs/prov"), FileStore("runs/prov")), - (MariaDBStore(db_name="logbook", prefix="logs"), MariaDBStore(db_name="logbook", prefix="logs")), - ): - observer, scheduler = Observer(store), Observer(scheduler_store) + 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 = PickPlaceRun(observer, run_id="pick-place-1") + 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() + passed.run(pick_and_place) - DrawerOpeningRun(observer, run_id="drawer-1").run() + failed = Run(store, f"drawer-{session}-1") + failed.run(open_drawer) - PickPlaceRun(observer, run_id="pick-place-2").queue() - Run(scheduler, run_id="pick-place-2").cancel() + queued = Run(store, f"pick-place-{session}-2") + queued.queue() + Run(scheduler, queued.id).cancel() - stopped = PickPlaceRun(observer, run_id="pick-place-3") - running = threading.Thread(target=stopped.run) + 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, run_id="pick-place-3").cancel() + Run(scheduler, stopped.id).cancel() running.join() - for run_id in ("pick-place-1", "drawer-1", "pick-place-2", "pick-place-3"): - print(type(store).__name__, run_id, *observer.lifecycle(run_id)) - store.close() - scheduler_store.close() + 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 9487734..34cd12c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -11,7 +11,7 @@ description = "Robot Execution Catalog (REC) is a python library to manage data dynamic = ["version"] dependencies = [ "rdflib>=7.6.0", - "rdf-utils @ git+https://github.com/minhnh/rdf-utils@main", + "rdf-utils @ git+https://github.com/minhnh/rdf-utils@bad7c02ca44de57c2461a354e3543e6d5a09341b", ] requires-python = ">= 3.12" readme = "README.md" diff --git a/rec/observer.py b/rec/observer.py deleted file mode 100644 index 67b5cdd..0000000 --- a/rec/observer.py +++ /dev/null @@ -1,166 +0,0 @@ -"""Records the events of runs in a store, each run as its provenance bundle.""" - -from __future__ import annotations - -from contextlib import contextmanager -from datetime import datetime -from typing import TYPE_CHECKING - -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 - -if TYPE_CHECKING: - # The MariaDB driver is an optional extra. - from rec.stores.file_store import FileStore - from rec.stores.mariadb_store import MariaDBStore - - -class Observer: - """Records the events of any number of runs in one store; every call names its run. - - A run is a `prov-ext:Execution` and an `oslc_auto:AutomationResult` in a `prov:Bundle` attributed - to the rec that first recorded it. Each event changes only its own triples, in the bundle the - store parsed under its lock. - """ - - def __init__(self, store: FileStore | MariaDBStore, base: str = RUN_BASE): - """ - :param store: Where the runs' bundles are kept - :param base: IRI base of the run nodes; a run is ```` - """ - self.store = store - self.base = base - # Read once: it inspects rec's checkout, and every edit of a run holds the store's lock. - self.recorder = get_py_pkg_info("rec") - - @contextmanager - def _run(self, run_id: str): - """Yield the run's bundle and node under the store's lock, the bundle created on the run's first edit. - - :raises ValueError: ``run_id`` is not a run id (``rec.provenance.RUN_ID``) - """ - if not RUN_ID.fullmatch(run_id): - raise ValueError(f"'{run_id}' is not a run id -- use letters, digits, '-', '.', '_' or '~', not '.' or '..'") - run = URIRef(self.base + run_id) - with self.store.edit(run_id) as ds: - # The run's own bundle: another tool may keep its bundles in the same dataset. - bundle = next((graph for graph in ds.graphs() if (run, OSLC_AUTO.state, None) in graph), None) - if bundle is None: - if any((None, OSLC_AUTO.state, None) in graph for graph in ds.graphs()): - raise ValueError(f"the bundle of run '{run_id}' has no '{run}' -- it was recorded under another base") - bundle = ds.graph(create_bundle(ds, self.recorder.purl)) - load_pkg_prov(bundle, self.recorder) - bundle.add((run, RDF.type, PROV_EXT.Execution)) - bundle.add((run, RDF.type, OSLC_AUTO.AutomationResult)) - bundle.add((run, OSLC_AUTO.state, OSLC_AUTO.new)) - bundle.add((run, OSLC_AUTO.verdict, OSLC_AUTO.unavailable)) - yield bundle, run - - def lifecycle(self, run_id: str) -> tuple[State, Verdict]: - """The run's state and verdict as the store keeps them; a run not stored is new. - - :raises ValueError: The stored bundle holds no run of this id under the observer's base - """ - ds = self.store.load(run_id) - if ds is None: - return State.NEW, Verdict.UNAVAILABLE - run = URIRef(self.base + run_id) - bundle = next((graph for graph in ds.graphs() if (run, OSLC_AUTO.state, None) in graph), None) - if bundle is None: - raise ValueError(f"the bundle of run '{run_id}' has no '{run}' -- it was recorded under another base") - state, verdict = bundle.value(run, OSLC_AUTO.state), bundle.value(run, 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), - ) - - def log_queued_run(self, run_id: str, queued_time: datetime): - """Record a new run as queued; raises RuntimeError for a run that is not new.""" - if queued_time.utcoffset() is None: - raise ValueError(f"queued time {queued_time} of run '{run_id}' has no time zone -- a run's times are wall-clock instants") - with self._run(run_id) as (bundle, run): - state = bundle.value(run, OSLC_AUTO.state) - if state != OSLC_AUTO.new: - raise RuntimeError(f"run '{run_id}' is {state.fragment} -- only a new run can be queued") - bundle.set((run, OSLC_AUTO.state, OSLC_AUTO.queued)) - bundle.add((run, REC["queued-time"], Literal(queued_time))) - - def log_started_run(self, run_id: str, started_time: datetime): - """Record a new or queued run as in progress, executed by this observer's rec. - - :raises RuntimeError: The run has already started, or was cancelled - """ - with self._run(run_id) as (bundle, run): - state = bundle.value(run, OSLC_AUTO.state) - if state not in (OSLC_AUTO.new, OSLC_AUTO.queued): - raise RuntimeError(f"run '{run_id}' is {state.fragment} -- only a run that has not started can start") - # 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 = URIRef(f"{run}/beginning") - add_wall_instant(bundle, started, started_time) - load_execution_prov(bundle, run, (), self.recorder.purl, started) - bundle.set((run, OSLC_AUTO.state, OSLC_AUTO.inProgress)) - - def log_run_heartbeat(self, run_id: str, beat_time: datetime): - """Record that a started run is still alive; raises RuntimeError for any other run.""" - if beat_time.utcoffset() is None: - raise ValueError(f"heartbeat time {beat_time} of run '{run_id}' has no time zone -- a run's times are wall-clock instants") - with self._run(run_id) as (bundle, run): - state = bundle.value(run, OSLC_AUTO.state) - if state not in (OSLC_AUTO.inProgress, OSLC_AUTO.canceling): - raise RuntimeError(f"run '{run_id}' is {state.fragment} -- only a started run beats") - bundle.set((run, REC["heartbeat-time"], Literal(beat_time))) - - def log_ended_run(self, run_id: str, ended_time: datetime, verdict: Verdict, fail_trace: str | None = None): - """End a started run with its verdict: a canceling run that passed ends canceled, any other ends complete. - - :param verdict: ``passed``, ``failed`` (its main raised) or ``error`` (it was interrupted) - :param fail_trace: The trace of what ended a failed or error run - :raises RuntimeError: The run has not started, or has ended - """ - with self._run(run_id) as (bundle, run): - state = bundle.value(run, OSLC_AUTO.state) - if state not in (OSLC_AUTO.inProgress, OSLC_AUTO.canceling): - raise RuntimeError(f"run '{run_id}' is {state.fragment} -- only a started run can end") - ended = URIRef(f"{run}/end") - add_wall_instant(bundle, ended, ended_time) - bundle.add((run, 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((run, OSLC_AUTO.state, OSLC_AUTO.canceled)) - return - bundle.set((run, OSLC_AUTO.state, OSLC_AUTO.complete)) - bundle.set((run, OSLC_AUTO.verdict, VERDICTS[verdict])) - if fail_trace: - bundle.add((run, REC["fail-trace"], Literal(fail_trace, datatype=XSD.string))) - - def log_cancelled_run(self, run_id: str): - """Cancel a queued run, or ask a run in progress to stop; raises RuntimeError for any other run. - - A queued run that is cancelled never started, so it has neither a beginning nor an end. - """ - with self._run(run_id) as (bundle, run): - state = bundle.value(run, OSLC_AUTO.state) - if state == OSLC_AUTO.queued: - bundle.set((run, OSLC_AUTO.state, OSLC_AUTO.canceled)) - elif state == OSLC_AUTO.inProgress: - bundle.set((run, OSLC_AUTO.state, OSLC_AUTO.canceling)) - else: - raise RuntimeError(f"run '{run_id}' is {state.fragment} -- only a queued run or one in progress can be cancelled") - - def log_host_info(self, run_id: str, host_info: dict): - """Record the machine executing the run from ``hostname``, ``os``, ``python`` and ``cpu``; other keys are not recorded.""" - with self._run(run_id) as (bundle, run): - host = URIRef(f"{run}/host") - bundle.add((host, RDF.type, REC.Host)) - bundle.add((host, RDF.type, PROV.Location)) - for key, predicate in HOST_TERMS.items(): - if host_info.get(key): - bundle.set((host, predicate, Literal(host_info[key]))) - bundle.set((run, PROV.atLocation, host)) diff --git a/rec/run.py b/rec/run.py index eb925f4..31b03d6 100644 --- a/rec/run.py +++ b/rec/run.py @@ -1,127 +1,199 @@ -import datetime +"""A run and its lifecycle, recorded in a store as the run's provenance bundle.""" + +from __future__ import annotations + 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 +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.observer import Observer +from rec.provenance import HOST_TERMS, OSLC_AUTO, PROV_EXT, REC, RUN_BASE, RUN_ID, STATES, VERDICTS + +if TYPE_CHECKING: + # The MariaDB driver is an optional extra. + from rec.stores.file_store import FileStore + from rec.stores.mariadb_store import MariaDBStore logger = logging.getLogger(__name__) -def host_info(): - """Information about the machine executing a run""" - return { - "hostname": socket.gethostname(), - "os": platform.platform(), - "python": platform.python_version(), - "cpu": platform.processor() or None, - } +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. + """ -class Run: - def __init__(self, observer: Observer, run_id: str | None = None): + def __init__(self, store: FileStore | MariaDBStore, run_id: str | None = None, base: str = RUN_BASE): """ - :param observer: Records the run in its store - :param run_id: The run's id in the store; a UUID is minted when none is given + :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.observer = observer - self._id = run_id - self.result = None - self.beat_interval = 10 - self._stop_beating = threading.Event() - - @property - def id(self): - """The run's identity in the store; minted here when the caller gave none""" - if self._id is None: - self._id = str(uuid4()) - return self._id - - @property - def state(self) -> State: - """The run's state as the store keeps it, ``new`` until it is stored""" - return self.observer.lifecycle(self.id)[0] - - @property - def verdict(self) -> Verdict: - """The run's verdict as the store keeps it""" - return self.observer.lifecycle(self.id)[1] - - def _beat(self): - while not self._stop_beating.wait(self.beat_interval): - # A store briefly out of reach must not stop the beats that follow. - try: - self.observer.log_run_heartbeat(self.id, datetime.datetime.now(datetime.UTC)) - except Exception: - logger.exception("Run %s could not record its heartbeat", self.id) - - def main(self) -> object: - pass + 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), + ) def queue(self): - """Record the run as queued, before a runner starts it; the store refuses a run that is not new""" - self.observer.log_queued_run(self.id, datetime.datetime.now(datetime.UTC)) + """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) - return 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 as canceled once ``main`` returns. + """Cancel a queued run, or ask one in progress to stop: it ends canceled once its work returns. - Any holder of the run's id can cancel it, through a ``Run`` with that ``run_id`` on the same store. - ``main`` sees the request as ``self.state`` being ``State.CANCELING``. + A queued run that is cancelled never started, so it has neither a beginning nor an end. """ - self.observer.log_cancelled_run(self.id) + 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): - """ - Start the run, execute ``main`` and record how it ended - :returns: What ``main`` returned; rec does not record it - :raises RuntimeError: The store holds the run as started or canceled - :raises BaseException: What interrupted ``main``, e.g. ``KeyboardInterrupt`` or ``SystemExit``, once the run is ended as error + 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.observer.log_started_run(self.id, datetime.datetime.now(datetime.UTC)) - logger.info("Started run %s", self.id) - beating = threading.Thread(target=self._beat, daemon=True) if self.beat_interval > 0 else None - error = None - # Everything after the start is inside: whatever fails, the started run gets its end. + 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.log_host_info(host_info()) - if beating is not None: - beating.start() - self.result = self.main() + beating.start() + result = work(self) except BaseException as caught: error = caught finally: - # Stopped before the end is recorded: a late beat would find the run ended. - self._stop_beating.set() - if beating is not None and beating.is_alive(): - beating.join() - if error is None: - verdict = Verdict.PASSED - elif isinstance(error, Exception): - verdict = Verdict.FAILED - else: - verdict = Verdict.ERROR - self.observer.log_ended_run( - self.id, - datetime.datetime.now(datetime.UTC), - verdict, - "".join(traceback.format_exception(error)) if error is not None else None, - ) - logger.log(logging.INFO if error is None else logging.ERROR, "Ended run %s", self.id, exc_info=error) - # An interrupt is the process being asked to stop: recorded, then passed on. - if error is not None and not isinstance(error, Exception): - raise error - return self.result - - def log_host_info(self, host_info: dict): - """ - Log information about the machine executing this run - :param host_info: ``hostname``, ``os``, ``python``, ``cpu``; see :func:`host_info` - """ - self.observer.log_host_info(self.id, host_info) + 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/stores/mariadb_store.py b/rec/stores/mariadb_store.py index 4f4ff02..4d7760e 100644 --- a/rec/stores/mariadb_store.py +++ b/rec/stores/mariadb_store.py @@ -1,6 +1,7 @@ """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 @@ -22,6 +23,9 @@ def __init__(self, db_name: str = "logbook", prefix: str = "logs"): :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( diff --git a/tests/test_mariadb_store.py b/tests/test_mariadb_store.py index 216c30d..053765d 100644 --- a/tests/test_mariadb_store.py +++ b/tests/test_mariadb_store.py @@ -8,7 +8,6 @@ pytest.importorskip("mariadb", reason="the MariaDB driver is an optional extra") from rec import State, Verdict # noqa: E402 -from rec.observer import Observer # noqa: E402 from rec.run import Run # noqa: E402 from rec.stores.mariadb_store import MariaDBStore # noqa: E402 @@ -32,28 +31,35 @@ def store(): db.close() -class QuickRun(Run): - def main(self): - return "ok" +def succeed(run): + return "ok" def test_a_row_keeps_the_run_as_a_valid_bundle(store): - QuickRun(Observer(store), run_id="run-0").run() - assert Observer(store).lifecycle("run-0") == (State.COMPLETE, Verdict.PASSED) + 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): - QuickRun(Observer(store), run_id="queued").queue() + run = Run(store, "queued") + run.queue() scheduler = MariaDBStore(db_name=TEST_DATABASE, prefix=store.prefix) - Run(Observer(scheduler), run_id="queued").cancel() + Run(scheduler, "queued").cancel() scheduler.close() - assert Observer(store).lifecycle("queued") == (State.CANCELED, Verdict.UNAVAILABLE) + assert run.lifecycle() == (State.CANCELED, Verdict.UNAVAILABLE) def test_run_ids_differing_in_case_are_two_runs(store): - QuickRun(Observer(store), run_id="Pick-1").run() - QuickRun(Observer(store), run_id="pick-1").queue() - assert Observer(store).lifecycle("Pick-1") == (State.COMPLETE, Verdict.PASSED) - assert Observer(store).lifecycle("pick-1") == (State.QUEUED, Verdict.UNAVAILABLE) + 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 index 99bb864..33e4038 100644 --- a/tests/test_run.py +++ b/tests/test_run.py @@ -1,16 +1,13 @@ import os import threading -from datetime import datetime from pathlib import Path import pytest from pyshacl import validate -from rdf_utils.models.prov import create_bundle from rdflib import Graph, URIRef from rdflib.namespace import PROV, RDF, TIME from rec import State, Verdict -from rec.observer import Observer from rec.provenance import OSLC_AUTO, PROV_EXT, REC, RUN_BASE from rec.run import Run from rec.stores.file_store import FileStore @@ -21,52 +18,41 @@ SHAPES.parse(METAMODELS / name, format="turtle") -class CalibrationRun(Run): - def main(self): - return "calibrated" +def calibrate(run): + return "calibrated" -class FailingRun(Run): - def main(self): - raise ValueError("no gripper attached") +def drop_gripper(run): + raise ValueError("no gripper attached") -class InterruptedRun(Run): - def main(self): - raise KeyboardInterrupt +def interrupt(run): + raise KeyboardInterrupt -class ExitingRun(Run): - def main(self): - raise SystemExit(3) +def exit_process(run): + raise SystemExit(3) -class StoppedRun(Run): - def main(self): - # A scheduler holding only the id asks the run to stop while it is in progress. - Run(Observer(self.observer.store), run_id=self.id).cancel() - if self.state is State.CANCELING: - return "stopped" - return "finished" +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" -class CrashedWhileStoppingRun(Run): - def main(self): - Run(Observer(self.observer.store), run_id=self.id).cancel() - raise ValueError("gripper jammed while releasing") +def jam_while_stopping(run): + Run(run.store, run.id).cancel() + raise ValueError("gripper jammed while releasing") -class SlowRun(Run): - def main(self): - threading.Event().wait(0.05) +def wait_a_little(run): + threading.Event().wait(0.05) -class HostlessRun(Run): - def log_host_info(self, host_info): - raise OSError("no hostname") - - def main(self): - raise AssertionError("main must not run when the start cannot be completed") +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 @@ -75,8 +61,8 @@ def store(tmp_path): def test_a_completed_run_is_an_execution_by_rec_in_a_bundle_attributed_to_rec(store): - observer = Observer(store) - assert CalibrationRun(observer, run_id="run-1").run() == "calibrated" + run = Run(store, "run-1") + assert run.run(calibrate) == "calibrated" ds = store.load("run-1") ok, _, report = validate(ds, shacl_graph=SHAPES, inference="rdfs") @@ -84,54 +70,34 @@ def test_a_completed_run_is_an_execution_by_rec_in_a_bundle_attributed_to_rec(st [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) == observer.recorder.purl == bundle.value(node, PROV.wasAssociatedWith) - assert observer.lifecycle("run-1") == (State.COMPLETE, Verdict.PASSED) + 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 = CalibrationRun(Observer(store), run_id="run-b") + 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() + 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_an_event_changes_only_its_own_triples(store): - """A triple another tool put in the run's bundle survives rec's later events.""" - observer = Observer(store) - CalibrationRun(observer, run_id="run-k").queue() +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"))) - CalibrationRun(observer, run_id="run-k").run() + 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_another_tools_bundle_in_the_dataset_is_left_alone(store): - tool = URIRef("https://example.org/agent/scheduler") - with store.edit("run-t") as ds: - foreign = create_bundle(ds, tool) - observer = Observer(store) - CalibrationRun(observer, run_id="run-t").run() - assert observer.lifecycle("run-t") == (State.COMPLETE, Verdict.PASSED) - ds = store.load("run-t") - assert set(ds.graph(foreign)) == {(foreign, RDF.type, PROV.Bundle), (foreign, PROV.wasAttributedTo, tool)} - - -def test_a_run_that_cannot_finish_starting_still_ends(store): - observer = Observer(store) - HostlessRun(observer, run_id="run-n").run() - assert observer.lifecycle("run-n") == (State.COMPLETE, Verdict.FAILED) - ds = store.load("run-n") - ds.default_union = True - assert "OSError: no hostname" in str(ds.value(URIRef(RUN_BASE + "run-n"), REC["fail-trace"])) - - def test_a_queued_run_has_not_executed_yet(store): - CalibrationRun(Observer(store), run_id="run-q").queue() + Run(store, "run-q").queue() ds = store.load("run-q") ok, _, report = validate(ds, shacl_graph=SHAPES, inference="rdfs") assert ok, report @@ -142,36 +108,10 @@ def test_a_queued_run_has_not_executed_yet(store): assert ds.value(node, REC["queued-time"]) is not None -# Each starts from a completed run and breaks one rule of the run's shape. -@pytest.mark.parametrize( - ("removed", "added"), - [ - ([(OSLC_AUTO.verdict, None)], []), - ( - [(OSLC_AUTO.state, None), (OSLC_AUTO.verdict, None)], - [(OSLC_AUTO.state, OSLC_AUTO.queued), (OSLC_AUTO.verdict, OSLC_AUTO.unavailable)], - ), - ([(RDF.type, PROV_EXT.Execution)], []), - ([(RDF.type, OSLC_AUTO.AutomationResult)], []), - ], - ids=["without a verdict", "queued with a start time", "not an execution", "not an automation result"], -) -def test_the_shapes_refuse_a_run_that_contradicts_its_state(store, removed, added): - CalibrationRun(Observer(store), run_id="run-x").run() - ds = store.load("run-x") - [bundle] = [graph for graph in ds.graphs() if (graph.identifier, RDF.type, PROV.Bundle) in graph] - node = URIRef(RUN_BASE + "run-x") - for predicate, value in removed: - bundle.remove((node, predicate, value)) - for predicate, value in added: - bundle.add((node, predicate, value)) - assert not validate(ds, shacl_graph=SHAPES, inference="rdfs")[0] - - -def test_a_run_whose_main_raises_fails_with_its_trace(store): - observer = Observer(store) - FailingRun(observer, run_id="run-f").run() - assert observer.lifecycle("run-f") == (State.COMPLETE, Verdict.FAILED) +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 @@ -179,25 +119,42 @@ def test_a_run_whose_main_raises_fails_with_its_trace(store): assert "ValueError: no gripper attached" in str(ds.value(URIRef(RUN_BASE + "run-f"), REC["fail-trace"])) -@pytest.mark.parametrize(("cls", "interrupt"), [(InterruptedRun, KeyboardInterrupt), (ExitingRun, SystemExit)]) -def test_an_interrupted_run_ends_as_error_and_the_interrupt_goes_on(store, cls, interrupt): - observer = Observer(store) - with pytest.raises(interrupt): - cls(observer, run_id="run-i").run() - assert observer.lifecycle("run-i") == (State.COMPLETE, Verdict.ERROR) +@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): - observer = Observer(store) - queued = CalibrationRun(observer, run_id="run-q") + 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(Observer(store), run_id="run-q").cancel() - assert (queued.state, queued.verdict) == (State.CANCELED, Verdict.UNAVAILABLE) + Run(store, "run-q").cancel() + assert queued.lifecycle() == (State.CANCELED, Verdict.UNAVAILABLE) with pytest.raises(RuntimeError, match="is canceled"): - queued.run() + queued.run(calibrate) ds = store.load("run-q") ok, _, report = validate(ds, shacl_graph=SHAPES, inference="rdfs") assert ok, report @@ -206,17 +163,17 @@ def test_only_a_queued_run_or_one_in_progress_is_cancelled(store): assert ds.value(URIRef(RUN_BASE + "run-q"), TIME.hasBeginning) is None assert ds.value(URIRef(RUN_BASE + "run-q"), TIME.hasEnd) is None - CalibrationRun(observer, run_id="run-d").run() + done = Run(store, "run-d") + done.run(calibrate) with pytest.raises(RuntimeError, match="only a queued run or one in progress"): - Run(Observer(store), run_id="run-d").cancel() - assert observer.lifecycle("run-d") == (State.COMPLETE, Verdict.PASSED) + Run(store, "run-d").cancel() + assert done.lifecycle() == (State.COMPLETE, Verdict.PASSED) def test_a_run_in_progress_stops_when_cancelled(store): - observer = Observer(store) - run = StoppedRun(observer, run_id="run-s") - assert run.run() == "stopped" - assert observer.lifecycle("run-s") == (State.CANCELED, Verdict.UNAVAILABLE) + 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 @@ -226,17 +183,17 @@ def test_a_run_in_progress_stops_when_cancelled(store): def test_a_run_that_fails_while_stopping_keeps_its_verdict(store): - observer = Observer(store) - CrashedWhileStoppingRun(observer, run_id="run-c").run() - assert observer.lifecycle("run-c") == (State.COMPLETE, Verdict.FAILED) + 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 = SlowRun(Observer(store), run_id="run-h") + run = Run(store, "run-h") run.beat_interval = 0.01 - run.run() + 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 @@ -244,39 +201,10 @@ def test_a_running_run_beats(store): assert ok, report -def test_one_observer_records_many_runs_at_once(store): - """Every run is addressed by its id, each locked on its own.""" - observer = Observer(store) - runs = [SlowRun(observer, run_id=f"run-{i}") for i in range(6)] - for run in runs: - run.beat_interval = 0.01 - threads = [threading.Thread(target=run.run) for run in runs] - for thread in threads: - thread.start() - for thread in threads: - thread.join() - assert all(observer.lifecycle(run.id) == (State.COMPLETE, Verdict.PASSED) for run in runs) - - -def test_a_time_without_a_zone_is_refused_and_nothing_kept(store): - with pytest.raises(ValueError, match="has no time zone"): - Observer(store).log_queued_run("run-z", datetime(2026, 11, 12, 9, 30)) - assert store.load("run-z") is None - - -def test_a_run_recorded_under_another_base_is_not_read_as_this_one(store): - CalibrationRun(Observer(store), run_id="run-o").queue() - elsewhere = Observer(store, base="https://example.org/runs/") - with pytest.raises(ValueError, match="recorded under another base"): - elsewhere.lifecycle("run-o") - with pytest.raises(ValueError, match="recorded under another base"): - elsewhere.log_cancelled_run("run-o") - - -@pytest.mark.parametrize("run_id", ["../escape", "/tmp/escape", "nested/run", "a run", "läuft", "", ".", ".."]) +@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"): - Observer(store).log_queued_run(run_id, datetime.now().astimezone()) + Run(store, run_id) @pytest.mark.parametrize("run_id", ["../escape", "/tmp/escape", "nested/run"])