# Concepts MetaRelay moves **records** to **destinations**. The ideas below are the same for every backend. ## The pieces | Concept | What it is | | --- | --- | | **Record** | A JSON document: `schema_id`, `schema_version`, `record_id`, `context` and `payload`. The payload is checked against its schema when the record is created. | | **Schema** | A Pydantic model registered under an ID and version, for example `fiber_photometry.implant` v1. It must set `extra="forbid"` or `"allow"`, so unknown keys are never dropped silently. | | **Destination** | A URI that picks the backend: `file:///…`, `labarchives://…`, `elabftw://…`, `github://…`. | | **Session** | An open connection to one destination. `connect(uri)` returns one. | | **Container** | Where records live, named by a **LogicalPath** such as `("Fiber study", "Cohort A")`. Each backend maps it to what it has: folders, notebook pages, eLabFTW categories and entries. Only `ensure_container` creates one; listing, reading or writing a missing container raises `NotFoundError`, so a typo isn't mistaken for an empty container. `ensure_container(path, holds_records=True)` asks for a container that holds only records (a notebook page where the backend has one). | | **Receipt** | What MetaRelay knows about a record after writing or reading it, including its checksum. Keep receipts (in a `SyncIndex`) to detect conflicts next time. | | **Preview** | A readable table of the record, stored next to it, so people never have to read raw JSON. | ## Writing a record ``` ┌────────────── your receipt from last time ▼ record ──► write_record ──► compare with what's at the destination now │ ┌────────────────────────┼─────────────────────────┐ ▼ ▼ ▼ nothing there, same as your record, changed by someone or only your own nothing to do else since your earlier version receipt │ │ │ WRITE SKIP ConflictError ``` ## Write modes | Mode | If the record already exists | | --- | --- | | `upsert` (default) | Update it, unless it changed at the destination since your receipt. Without a receipt, only an identical record is accepted. | | `create` | Always `ConflictError`. | | `force` | Overwrite it. Use only after the user chose to. | Edits made directly to the preview (a notebook entry, or the `.md` file) also count as a change at the destination, so they are not overwritten silently. That holds even if you read the record after the edit: a read returns the JSON, not the preview, so its receipt still describes the preview MetaRelay last wrote. ## Handling a conflict `ConflictError` means someone changed the record at the destination since your receipt. MetaRelay never picks a winner. Show the person both versions (`read_record` returns theirs), and let them choose: - **Keep their change:** copy it into your record, then write it with `mode=WriteMode.FORCE`. Your record now holds both. - **Keep yours:** write it with `mode=WriteMode.FORCE`. The [`save_metadata` example](../examples/save_metadata/README.md) writes every record this way. It stops on a conflict unless the person already chose to replace the change: ```python def write( session: Session, where: LogicalPath, record: Record, receipts: SyncIndex, *, force: bool = False, ) -> Receipt: """Write ``record`` with the receipt from the last write, and keep the new one. Raises: ConflictError: If the record changed at the destination since then, unless ``force`` is set. """ prior = receipts.get(session.destination, where, record.record_id) try: receipt = session.write_record(where, record, prior_receipt=prior) except ConflictError: # Someone changed the record at the destination since `prior`. # Stop, unless the person already chose to replace their change. if not force: raise receipt = session.write_record(where, record, mode=WriteMode.FORCE) receipts.put(receipt) return receipt ``` ### When someone edited the preview The `ConflictError` for an edit to the preview says what changed. Its `preview_diff` lists each table row whose value differs from what MetaRelay wrote, and whether that list is complete. To keep the edits, `accept_edits` copies them into the record and writes it, so the JSON and the preview agree again: ```python from metarelay import ConflictError, accept_edits try: session.write_record(path, record, prior_receipt=receipt) except ConflictError as error: diff = error.preview_diff if diff is None or not diff.complete: raise # another kind of conflict, or changes MetaRelay can't list for edit in diff.edits: print(edit.describe()) # Metadata · fiber.core_um: '400' → '200' if person_accepts(): written = accept_edits(session, path, record, diff) record = written[record.record_id].record # now holds the edits ``` The JSON stays the source of truth: MetaRelay never takes a value from the preview by itself, only when your code calls `accept_edits`. Keep the returned record: writing your old copy again would undo the edits. Each value goes back where the generic preview showed it (`Context` rows into `context`, `Metadata` rows such as `fiber.core_um` into `payload`), converted to the type it replaces, and the result is validated. If any edit can't be applied, nothing is written and `ValidationError` says why: an edit to a value your record also changed, an added or removed row, a value that isn't a number where one was, or a schema with its own renderer. `apply_edits(record, edits)` does the copying without writing. On eLabFTW one entry holds several records, and the diff lists edits to all of them. `accept_edits` reads the other records, applies their edits, and writes them too, because a forced write rebuilds the whole entry. Like any forced write, it overwrites a change someone makes at the same moment. `complete` is `False` when someone also changed something MetaRelay can't list, such as text added between the tables: look at the entry and copy what you want by hand. The written values come from rendering the stored record again, so if a MetaRelay upgrade or a schema's renderer changed how a value reads since the last write, that row shows up as an edit too. On a local folder or GitHub the diff lists no edits instead, as it does when someone edited the `.json` but not the preview: MetaRelay can't tell old values from a person's edits. The `metarelay` command does the same: `metarelay write` lists the edits, and `metarelay write --accept-edits` accepts them and updates your JSON file. ## Errors Every backend raises the same errors, all subclasses of `MetaRelayError`: | Error | Means | | --- | --- | | `ConfigurationError` | Bad URI or config, or the backend's extra isn't installed | | `AuthenticationError` | Login failed | | `PermissionDeniedError` | Logged in, but not allowed | | `BackendUnavailableError` | Couldn't reach the destination | | `NotFoundError` | No such container or record | | `ConflictError` | The write would overwrite someone else's change | | `ValidationError` | A record, payload or name is invalid | ## Backends and the conformance suite A backend is done when it passes the conformance suite. It ships in `metarelay[testing]`, so a backend in another package can run the same checks: ```python import pytest from metarelay import connect from metarelay.testing import BackendConformance class TestMyBackend(BackendConformance): @pytest.fixture def session(self): session = connect("mybackend://test-server") yield session session.close() ``` `metarelay.testing.MemorySession` is an in-memory backend for testing code that uses MetaRelay without touching disk. ## The local backend `file:///path/to/folder` stores each container as a folder. The folder must already exist. - `{id}.json` is the record and the source of truth; `{id}.md` is its preview. - `.metarelay/index.json` lists which files are records. Delete it, and it is rebuilt from the `.json` files. - `.metarelay/history.jsonl` gets one line per write. - Names that are unsafe on any common filesystem are rejected everywhere (`\ : * ? " < > |`, a trailing dot or space, `CON`, `NUL`, …). Names starting with `.` are reserved. - Names are compared ignoring case and Unicode spelling, on every OS. A name that matches an existing one only that way (`study` next to `Study`, or record `Implant-M1` next to `implant-M1`) is refused, so a folder behaves the same on macOS, Windows and Linux. - Every `.json` in a container is a record, except files written with `write_file`. A `.json` that isn't a valid record makes listing fail with an error naming the file, rather than the record silently disappearing. So give MetaRelay its own folder, not one where an app keeps other `.json` files. - The same folder always gets the same destination URI (`lab data` and `lab%20data`, or a symlinked path, are one destination), so receipts match. - `create` is enforced even with two writers. Other modes assume one writer per folder at a time.