Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -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
122 changes: 104 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,40 +1,113 @@
# Robot Execution Catalog (REC)

REC is a tool that aims to make data in robot executions [FAIR](https://www.go-fair.org/fair-principles/).
It is designed to configure, manage, organize and consolidate (meta)data used or generated by robots executing tasks or tests.
REC makes the data of robot executions [FAIR](https://www.go-fair.org/fair-principles/): it records
each run's lifecycle in [PROV](https://www.w3.org/TR/prov-o/), on the
[rec and prov-extension vocabularies](https://secorolab.github.io/metamodels/), as a provenance
bundle written with [rdf-utils](https://github.com/minhnh/rdf-utils).

## Installation

In your terminal, go to where you have cloned this repository and install it in editable mode:

```shell
pip install -e .
pip install -e . # file stores
pip install -e ".[mariadb]" # and the MariaDB store
```

## Examples
## Recording a run

The current skeleton of the code allows you to run two examples: The `MariaDBObserver` and a `Run`.
A `Run` is a handle on one run in one store: `queue()`, `start()`, `beat()`, `end(verdict)`,
`cancel()` and `lifecycle()`. `run(work)` does the steps for you around `work(run)`:

### Observers
```python
from rec.run import Run
from rec.stores.file_store import FileStore

An Observer is an interface to a type of data storage. For now, we have added a `MariaDBObserver` with some basic functionality. To test it you can run the following in your terminal:

```shell
python rec/observers/mariadb_observer.py
def pick_and_place(run):
return "placed"


Run(FileStore("runs/prov"), "pick-place-1").run(pick_and_place)
```

### Creating a run
`run(work)` starts the run (recording the machine it runs on), beats every `beat_interval`
seconds while `work` runs, and ends the run as `passed`, `failed` (`work` raised) or `error`
(interrupted, e.g. `KeyboardInterrupt` or `SystemExit`, which `run` raises again once recorded).
It returns what `work` returned; rec does not record it.

The [example](examples/decentral_run.py) shows how to create a run object, attach an observer, and define the `main` function of your tests. You can test its basic functionality by running the script:
Each step changes only its own triples in the run's bundle: the store parses the bundle under its
lock, the step checks the run's state and sets what it changes, and the store writes it back.
rdf-utils writes the bundle (`create_bundle`), rec as its software agent (`load_pkg_prov`), the
execution (`load_execution_prov`) and its instants (`add_wall_instant`), each once.

```shell
python examples/decentral_run.py
What a run executes, the software and files it uses or generates, and its steps, are recorded by
the tool that knows them, with rdf-utils' `add_file_entity`, `add_activity` and the `load_*_prov`
helpers, in that tool's own bundle.

### Queueing and cancelling

State lives in the store, so any `Run` with the same id sees and changes the same run:

```python
Run(MariaDBStore(), "drawer-2").queue()

# elsewhere, e.g. a scheduler with its own connection
Run(MariaDBStore(), "drawer-2").cancel()
```

| State when cancelled | Result |
|---|---|
| `queued` | `canceled`; it never started, so it has no beginning or end |
| `in-progress` | `canceling`; `work` sees `run.lifecycle()[0] is State.CANCELING`, returns, and the run ends `canceled`; `work` that raises instead ends `complete` with its verdict |
| anything else | `RuntimeError` |

The store decides every step under a lock (`flock` for files, the run's row for MariaDB): only a
new run is queued, only a new or queued run starts. A started run beats every `beat_interval`
seconds, recorded as `rec:heartbeat-time`; a beat that fails is logged and the next one tried.

## Stores

| Store | Keeps a run as |
|---|---|
| `FileStore(dir)` | its bundle, `<run_id>.ld.json` |
| `MariaDBStore(db_name, prefix)` | its bundle as JSON-LD in a row of `<prefix>_runs` (`id`, `run_id`, `bundle`) |

`load(run_id)` returns the run's bundle as an rdflib `Dataset`; `Run.lifecycle()` gives its state
and verdict. A run is recorded in one store, and a stored run holds only rec's bundle.
`MariaDBStore` takes a prefix of letters, digits and `_`, as it becomes part of a table name.

## The PROV bundle

```trig
<urn:uuid:7f1c…> {
<urn:uuid:7f1c…> a prov:Bundle ;
prov:wasAttributedTo <pkg:git/github.com/secorolab/rec@816d61f> .

<https://secoro.uni-bremen.de/rec/run/pick-place-1>
a prov-ext:Execution, oslc_auto:AutomationResult ;
oslc_auto:state oslc_auto:complete ;
oslc_auto:verdict oslc_auto:passed ;
prov:wasAssociatedWith <pkg:git/github.com/secorolab/rec@816d61f> ;
time:hasBeginning <https://secoro.uni-bremen.de/rec/run/pick-place-1/beginning> ;
time:hasEnd <https://secoro.uni-bremen.de/rec/run/pick-place-1/end> ;
prov:atLocation <https://secoro.uni-bremen.de/rec/run/pick-place-1/host> .
}
```

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><run_id>`, `base` given to the `Run`.

## Examples

## Connecting to MariaDB
```shell
python examples/robot_runs.py # passed, failed, cancelled while queued, stopped while running
```

Create an `.env` file at the root of this repository and update the contents with your credentials and the IP of the server where its deployed:
It records the runs as bundle files under `runs/prov`, then in MariaDB, so it needs the `mariadb` extra and an `.env` at the repository root:

```dotenv
MARIADB_USER="user"
Expand All @@ -43,6 +116,19 @@ MARIADB_HOST="localhost"
MARIADB_PORT=3306
```

## Tests

```shell
pip install -e ".[dev]"
pytest
```

The conformance tests validate runs against the shapes of a
[metamodels](https://github.com/secorolab/metamodels) checkout beside this repository or at
`REC_METAMODELS_DIR`. MariaDB tests need the `mariadb` extra and a disposable database named by
`REC_TEST_MARIADB_DATABASE`.

## Acknowledgments

This tool is inspired by [sacred](https://github.com/IDSIA/sacred/tree/master), a tool to organize experiments for Machine Learning. We borrow small pieces of code under the [MIT License](https://opensource.org/license/MIT), but have rewritten and simplified the framework for robotics.
Inspired by [sacred](https://github.com/IDSIA/sacred/tree/master); small pieces of its code are
used under the [MIT License](https://opensource.org/license/MIT).
17 changes: 0 additions & 17 deletions examples/decentral_run.py

This file was deleted.

73 changes: 73 additions & 0 deletions examples/robot_runs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
"""Record robot runs, first as bundle files and then in MariaDB: one passes, one fails, one is
cancelled while queued and one is stopped while it runs. Every invocation records new runs.

Needs the `mariadb` extra and the connection settings in `.env` (see the README).
"""

import logging
import threading
import time
from uuid import uuid4

from rec import State
from rec.run import Run
from rec.stores.file_store import FileStore
from rec.stores.mariadb_store import MariaDBStore

logger = logging.getLogger("robot_runs")
MOTIONS = ("approach", "grasp", "lift", "transport", "place", "retreat")
# How far the drawer handle is from its modelled pose, and how far the gripper reaches, in metres.
HANDLE_OFFSET, REACH = 0.04, 0.02


def pick_and_place(run):
"""Pick an object and place it, checking between motions whether the run was asked to stop."""
for done, motion in enumerate(MOTIONS):
if run.lifecycle()[0] is State.CANCELING:
logger.info("%s: stopped before %s", run.id, motion)
return f"stopped after {done} of {len(MOTIONS)} motions"
logger.info("%s: %s", run.id, motion)
time.sleep(0.5)
return "placed"


def open_drawer(run):
"""Open a drawer, failing when the handle is further from its modelled pose than the gripper reaches."""
logger.info("%s: looking for the handle", run.id)
time.sleep(0.5)
if HANDLE_OFFSET > REACH:
raise RuntimeError(f"handle is {HANDLE_OFFSET} m from its modelled pose -- the gripper reaches {REACH} m")
return "opened"


if __name__ == "__main__":
logging.basicConfig(level=logging.INFO, format="%(message)s")
session = uuid4().hex[:8]
for make_store in (lambda: FileStore("runs/prov"), lambda: MariaDBStore(db_name="logbook", prefix="logs")):
# A scheduler holds only the run ids, and its own store on the same files or tables.
store, scheduler = make_store(), make_store()

passed = Run(store, f"pick-place-{session}-1")
# A short beat, so the run records a few heartbeats while it moves.
passed.beat_interval = 1
passed.run(pick_and_place)

failed = Run(store, f"drawer-{session}-1")
failed.run(open_drawer)

queued = Run(store, f"pick-place-{session}-2")
queued.queue()
Run(scheduler, queued.id).cancel()

stopped = Run(store, f"pick-place-{session}-3")
running = threading.Thread(target=stopped.run, args=(pick_and_place,))
running.start()
time.sleep(1.2)
Run(scheduler, stopped.id).cancel()
running.join()

for run in (passed, failed, queued, stopped):
print(type(store).__name__, run.id, *run.lifecycle())
if isinstance(store, MariaDBStore):
store.close()
scheduler.close()
21 changes: 13 additions & 8 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
[build-system]
requires = ["setuptools >= 61.0"]
build-backend = "setuptools.build_meta"
requires = ["hatchling", "hatch-vcs"]
build-backend = "hatchling.build"

[tool.hatch.version]
source = "vcs"

[project]
name = "rec"
description = "Robot Execution Catalog (REC) is a python library to manage data from robot runs"
dynamic = ["version"]
dependencies = [
"click>=8.1.7",
"dotenv",
"mariadb"
"rdflib>=7.6.0",
"rdf-utils @ git+https://github.com/minhnh/rdf-utils@bad7c02ca44de57c2461a354e3543e6d5a09341b",
]
requires-python = ">= 3.12"
readme = "README.md"
Expand All @@ -18,8 +20,11 @@ maintainers = [
]

[project.optional-dependencies]
dev = ["black>=24.4.2"]
mariadb = ["dotenv", "mariadb"]
dev = ["pytest", "pyshacl"]

[tool.setuptools.packages.find]
where = ["."] # list of folders that contain the packages (["."] by default)
[tool.hatch.metadata]
allow-direct-references = true

[tool.hatch.build.targets.wheel]
packages = ["rec"]
19 changes: 19 additions & 0 deletions rec/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
"""Where a run is and how it turned out: OSLC Automation state and verdict, by their rec.json terms."""

from enum import StrEnum


class State(StrEnum):
NEW = "new"
QUEUED = "queued"
IN_PROGRESS = "in-progress"
CANCELING = "canceling"
CANCELED = "canceled"
COMPLETE = "complete"


class Verdict(StrEnum):
UNAVAILABLE = "unavailable"
PASSED = "passed"
FAILED = "failed"
ERROR = "error"
17 changes: 0 additions & 17 deletions rec/feature.py

This file was deleted.

Empty file removed rec/observers/__init__.py
Empty file.
Loading
Loading