diff --git a/RELEASING.md b/RELEASING.md index 72aa1fd26..c66d0de9d 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -358,12 +358,12 @@ uv run --no-project --isolated --python 3.12 \ uv run --no-project --isolated --python 3.12 \ --with "orcapod[spiraldb] @ git+https://github.com/metamorphic-labs/orcapod-python@" \ - --with spiral-sdk==0.16.74 scripts/migrate_spiral_schemas.py \ + --with spiral-sdk==0.16.78 scripts/migrate_spiral_schemas.py \ write --project --dataset --plan plan.json --digest uv run --no-project --isolated --python 3.12 \ --with "orcapod[spiraldb] @ git+https://github.com/metamorphic-labs/orcapod-python@" \ - --with spiral-sdk==0.16.74 scripts/migrate_spiral_schemas.py \ + --with spiral-sdk==0.16.78 scripts/migrate_spiral_schemas.py \ verify --project --dataset --plan plan.json ``` diff --git a/changelog.d/ITL-1495.md b/changelog.d/ITL-1495.md new file mode 100644 index 000000000..d78b72627 --- /dev/null +++ b/changelog.d/ITL-1495.md @@ -0,0 +1,3 @@ +### Changed + +- The `spiraldb` extra pins `spiral-sdk==0.16.78` (was `0.16.74`), the release that reads and writes a SpiralDB table's metadata. Orcapod still only reads SpiralDB; the conformance tests pass on the service with it. diff --git a/changelog.d/ITL-1498.md b/changelog.d/ITL-1498.md new file mode 100644 index 000000000..9d272b4a3 --- /dev/null +++ b/changelog.d/ITL-1498.md @@ -0,0 +1,4 @@ +### Breaking changes and migration + +- `DBConnectorProtocol` has three more required methods: `table_name(path)`, `has_table(table_name)` and `table_paths(prefix, pending)`. `ConnectorArrowDatabase` now asks the connector to name its tables, test their existence and list their paths. SQLite, PostgreSQL and SpiralDB keep the names and listings they had. A connector of your own implements the three methods; `orcapod.databases.table_names` has the rule the built-in connectors use. +- `DBConnectorProtocol.validate_records` takes a required keyword argument, `table_name` (the name `table_name(path)` gave, or `None` for rows checked for no table in particular). `ConnectorArrowDatabase` passes it, so a connector that records something per table checks the rows against that table before they are buffered: a SpiralDB store refuses rows of another data context than the table records. SQLite and PostgreSQL ignore it. A connector of your own adds the argument. diff --git a/docs/dev/plans/2026-11-26-itl-1495-spiral-store-names.md b/docs/dev/plans/2026-11-26-itl-1495-spiral-store-names.md new file mode 100644 index 000000000..8ac9dc1d3 --- /dev/null +++ b/docs/dev/plans/2026-11-26-itl-1495-spiral-store-names.md @@ -0,0 +1,36 @@ +# ITL-1495: SpiralDB store, stages 0 and 1 + +Stages 0 and 1 of `docs/dev/specs/itl-1446-round2-spiral-sdk.md` (PR 588), approved by the +coordinator on the developer's behalf (decisions 1, 2, 3, 4 and 6). One pull request. + +## Stage 0: spiral-sdk 0.16.78 + +1. `pyproject.toml`: `spiral-sdk==0.16.78`; `uv lock --upgrade-package spiral-sdk`. The version + in `RELEASING.md`'s migration commands follows. +2. `tests/test_databases/fake_spiral_sdk.py`: `get_metadata` / `set_metadata` on the fake keyed + table, as measured live with 0.16.78 (rule `table-metadata`): an upsert, never a deletion, + not versioned, readable before any row, a key over 255 UTF-8 bytes, or an entry whose key + and value together are over 8,192 bytes, refused with `status 400` and nothing written. +3. Tests first: a conformance test of table metadata in + `tests/test_databases/test_spiraldb_connector_integration.py`, run on the fake always and + live opt-in, with fixed keys so a live table does not grow. The live conformance suite is + rerun with 0.16.78 (`itl-1186-switch.md` section 7: a bump reruns it). + +## Stage 1: store table names + +`src/orcapod/databases/spiral_store_names.py`, pure, imports no client: + +- `SPIRAL_TABLE_NAME_LABEL = "spiral_table_name_v1"`, beside `store_table_digest(path)`: SHA-256 + of the canonical JSON array of the full path components, bare hex (a hash in a name). +- `table_name_hint(path)`, `store_table_name(path)` (`o1__`), and + `store_table_name_prefix(prefix)`, the name prefix every table under a path prefix has. +- `store_table_metadata(path, data_context_key)`: the four entries of spec 2.2. +- `classify_store_table(metadata, path)`: this path's table, or an unmarked one (2.5); any other + path, format or a partial record raises `SpiralStoreTableCollisionError`. + +Then: the hash site inventory row in `docs/reference/hashing.md` ("in a name"); a golden group +`spiral_table_name` in `tests/test_hashing/golden/cases.py`, written by the generator into a new +file (the diff adds only that file and its history entry). Tests: determinism, the length bound, +the alphabet, prefix property of the hint, injectivity on adversarial paths, refusals. + +Nothing calls the module yet; no other hash, stored path or golden value moves. diff --git a/docs/dev/plans/2026-11-26-itl-1497-spiral-store-codec.md b/docs/dev/plans/2026-11-26-itl-1497-spiral-store-codec.md new file mode 100644 index 000000000..70e3e89cf --- /dev/null +++ b/docs/dev/plans/2026-11-26-itl-1497-spiral-store-codec.md @@ -0,0 +1,51 @@ +# ITL-1497: the codec of a SpiralDB store table, on spiral-sdk + +Stage 2 of `docs/dev/specs/itl-1446-round2-spiral-sdk.md` (PR 588), approved by the +coordinator on the developer's behalf (decision 4). It stacks on PR 589 (ITL-1495: spiral-sdk +0.16.78 and its fake). + +## What is carried over from PR 545 + +`src/orcapod/databases/spiral_store.py` and `tests/test_databases/test_spiral_store.py`, from +PR 545's branch, with these changes: + +- **The manifest is one payload**: `manifest_bytes` gives its bytes and `read_manifest_bytes` + reads them back. Kept in a table's metadata, it is `manifest_entries` (the chunks and their + header), read back by `read_manifest`, which takes the table's whole metadata mapping, never + raw payload bytes. Where it is kept is + stage 3's: decision 4 was revised on 2026-11-26 (ITL-1498), and stage 3 keeps it in the + table's own metadata, in chunks of at most 8 KiB (a key and its value together), beside the + identity record (`spiral_store_names`, PR 589). It is not kept in the dataset's schema table, + which is all or nothing under one completion marker. The format stays a draft + (`orcapod.spiral_store.draft`, version 0) while store mode is private: the format and + version are fixed when the store is switched on (stage 5), with a decision then on reading + draft tables (N57). +- **Timestamps are written as they are**, not as integers. +- **A null fixed-size list of structs is kept**, no longer refused. +- Everything else is unchanged: names, types, nullability, refusals before anything is written, + reading by the manifest's stored names, no row order. + +## Measured live with spiral-sdk 0.16.78 (2026-11-26, throwaway tables) + +| What | Result | +|---|---| +| booleans, integers (`uint64` max), floats (signed zeros and NaN payloads, `float16` too), `decimal128/256`, `date32`, `date64` off midnight, `null` | kept bit for bit | +| timestamps of every unit, with and without a zone, every `int64` value (`datetime.max` and `.min` included) | kept bit for bit: **written as they are** (pyspiral's service refused instants after 9999-12-30) | +| `time32` / `time64` within a day | kept; **outside one day: the whole write refused**, so times stay integers | +| `decimal32/64` | come back as `decimal128`: written as such, restored | +| strings, binaries, lists | come back in their small variants: normalized on read | +| struct fields | sorted by name at the top level (not inside a list): restored by name | +| map `keys_sorted` | dropped: restored from the manifest | +| a null fixed-size list of structs | **kept** (the refusal is lifted) | +| a null struct item inside a list | kept by the service; still refused by the codec, which does not yet carry a struct's validity (a later lift) | +| a null struct at the top level, an empty struct, `fixed_size_binary`, `duration`, `interval` | refused | +| column and struct field names | refused: a `__` or `$` prefix, any `.`, exactly `*`, the empty name. Kept: `$`, `*` and `;` inside a name, control characters, case and Unicode normal forms apart, 1,024 characters. NUL is cut silently. The codec's escape rule covers every refusal and NUL, so it is unchanged | +| a write of no rows | publishes nothing; a key-only write is refused | + +The fake (`tests/test_databases/fake_spiral_sdk.py`) now refuses the empty name, `*` and times +outside a day as the service does. The conformance tests (`test_spiraldb_connector_integration.py`) +run the codec through spiral-sdk on the fake and live: the rows written are the rows read. They +also check that the service refuses each name and value listed in the refusal test +(`test_what_the_store_codec_avoids_is_refused`). Not every value the codec avoids is refused by +the service: the codec also refuses what the service keeps but the codec cannot yet carry back +(a null struct item inside a list). diff --git a/docs/dev/plans/2026-11-26-itl-1498-spiral-store-mode.md b/docs/dev/plans/2026-11-26-itl-1498-spiral-store-mode.md new file mode 100644 index 000000000..edfe73dfc --- /dev/null +++ b/docs/dev/plans/2026-11-26-itl-1498-spiral-store-mode.md @@ -0,0 +1,89 @@ +# ITL-1498: the SpiralDB connector's store mode (stage 3) + +Stage 3 of `docs/dev/specs/itl-1446-round2-spiral-sdk.md` (PR 588), stacked on PR 590 +(ITL-1497, the codec) and PR 589 (ITL-1495, names and metadata). Q1 to Q4 approved as +recommended by the coordinator on the developer's behalf (2026-11-26); Q2 revises decision 4. +Implemented in `databases/table_names.py`, `databases/spiraldb_store_tables.py`, the +connector's `_store` flag, and the chunked manifest of `spiral_store.manifest_entries`. + +## What the code does today + +- `ConnectorArrowDatabase` owns the path-to-name rule (`_path_to_table_name`: sanitize, join + with `__`), tests existence with `name in connector.get_table_names()`, and lists paths by + splitting names back (`list_table_paths`). A connector sees table names only, never a path. +- Every read is a whole-table read (`SELECT * FROM ""`, then filtered in Arrow); there + is no keyed read. +- `SpiralDBConnector` reads only; every write raises `SpiralDBWriteNotSupportedError`. + +## Proposal + +**Q1. Naming moves into the connector.** `DBConnectorProtocol` gains three required methods +(protocols are internal, so no optional capability): + +- `table_name(path) -> str`: the stored name of the table at a full path; +- `has_table(table_name) -> bool`: whether it exists; +- `table_paths(prefix, pending_names) -> list[path]`: the paths of the stored tables under + `prefix`. + +`ConnectorArrowDatabase` calls these instead of its own rule. SQLite, PostgreSQL and a plain +SpiralDB connector implement them with today's rule, moved unchanged into one shared helper, +so nothing they do changes. The other shape, a separate database class for SpiralDB that +copies `ConnectorArrowDatabase`'s pending, flush and guard machinery, is not recommended: two +copies of that machinery can drift. + +**Store mode** (`SpiralDBConnector(project, dataset, _store=True)`): + +- `table_name(path)`: `spiral_store_names.store_table_name`. The connector remembers each + name's path. A name it has not computed is not resolved from the table's metadata: the + calls that look a table up by name (`has_table`, the column info and schema, reads, + `create_table_if_not_exists`, `upsert_records`) raise `KeyError` for a name this + connector's `table_name(path)` has not computed. `ConnectorArrowDatabase` always computes + the name first. `get_pk_columns` needs no lookup and answers the store's key for any name. +- `has_table(name)`: opens the table by name, with no listing. Its record is read and checked: + another path or format raises `SpiralStoreTableCollisionError`. +- `table_paths(prefix)`: one listing, then the names starting with + `store_table_name_prefix(prefix)`, then each candidate's metadata (cached by table id), then + the recorded paths under `prefix`. Stale-layout checks use this unchanged (ITL-954). +- `create_table_if_not_exists`: checks the key column and that the name is one this connector + computed; it creates no table (as built, after the review of fe4145c7: every check runs + before a table is created). +- First non-empty `upsert_records` on a table: after every check of the rows, create the table + (`create_keyed_table` with the key column; a 409 means it was made meanwhile and is judged + again), or adopt the empty one found; write the identity record and the manifest together, + in one metadata upsert; then append the rows. If that write stops part way, what can remain + is an empty table with no record, or a recorded table with no rows: a later first writer + adopts either one, since a table with no rows is new (N42). **Q4**: the data context recorded is the one of the rows' `__data_context`, which must + be a single value. A table found without a record, and with no rows and the expected key, is + adopted; otherwise it is refused (decision 3). +- `upsert_records`: rows through `spiral_store.encode_rows`; `skip_existing` reads the key + column once. A write of no rows is never sent. +- `get_column_info` and `iter_batches`: the logical columns, rows through + `spiral_store.decode_rows` against the manifest. +- Plain tables are not store tables: a store-mode connector sees only `o1_` tables. + +**Q2. Where the manifest lives (revisits decision 4).** On main, the dataset's schema table +(`__orcapod_schemas__`) is all or nothing: one completion marker holds a digest of every +row, and a dataset whose marker does not fit its rows is refused for every read. Adding a +store table would mean reading the whole schema table and writing its row plus a new marker +(one append, so atomic), and every plain reader would parse store rows too. Recommended: keep +the manifest in the table's own metadata, in chunks of at most 8 KiB (PR 545's chunked format, +which PR 590 replaced with one record), beside the identity keys. Store tables then stay +independent of each other and of the schema table. Measured: there is no total metadata limit +in sight; reads slow down only past a megabyte. + +**Q3. Store mode stays private until stage 5.** The flag is underscored, `to_config` refuses a +store-mode connector, and there is no lease yet (stage 4). Writes happen only in tests on the +fake and in the live conformance dataset. + +## Measured (live, spiral-sdk 0.16.78) + +- A key-range scan returns no row for an absent key, and rows in the order of the ranges + asked: no null rows (ITL-1476's second finding does not apply to spiral-sdk). +- Table names: the store's names are at most 164 characters in `[a-z0-9_]`, within the + service's 255 (ITL-1476's first finding). +- A write of no rows publishes nothing (ITL-1476's third finding); the store sends none. + +## Not in this stage + +The lease (stage 4), keyed reads in place of whole-table reads (a later performance stage), +and job integration with switch-on (stage 5). diff --git a/docs/dev/scripts/itl_1446_store_evaluation.py b/docs/dev/scripts/itl_1446_store_evaluation.py new file mode 100644 index 000000000..421be7c0e --- /dev/null +++ b/docs/dev/scripts/itl_1446_store_evaluation.py @@ -0,0 +1,703 @@ +"""End-to-end evaluation of the SpiralDB store as of ITL-1498 (no lease, one process). + +One job (a function pod, a join, a filter, a group by, a second function, a side effect) +through every scenario of ITL-1446's goals, on Delta and on a SpiralDB store (the fake, or +live), compared value for value; every SpiralDB call is counted per table. + + uv run python docs/dev/scripts/itl_1446_store_evaluation.py fake + SPIRAL_PROJECT_ID=... uv run python docs/dev/scripts/itl_1446_store_evaluation.py live + +Live runs need a sign-in spiral-sdk finds (``SPIRAL_CLIENT_ID``, ``SPIRAL_PRIVATE_KEY``) and +write fixed-name tables of a fresh job name into ``ORCAPOD_SPIRAL_CONFORMANCE_DATASET`` +(default ``orcapod_conformance``). Prints a JSON report; numbers measured live are not +kept in the repository. +""" + +from __future__ import annotations + +import asyncio +import json +import os +import re +import sys +import tempfile +import time +import uuid +import warnings +from collections import Counter, defaultdict +from contextlib import ExitStack +from pathlib import Path +from typing import Any, cast + +import pyarrow as pa + +from orcapod.utils.arrow_utils import normalize_to_large_types + +from orcapod import PipelineJob, function_pod +from orcapod.databases import ( + ConnectorArrowDatabase, + DeltaTableDatabase, + SpiralDBConnector, +) +from orcapod.side_effects import SideEffectPod +from orcapod.sources import ArrowTableSource + +warnings.filterwarnings("ignore") +REPO = Path(__file__).resolve().parents[3] +sys.path.insert(0, str(REPO)) + +CALLS: Counter[str] = Counter() +SENT: list[float] = [] + + +def make_rate(version: str) -> Any: + """The firing-rate function pod, at a version.""" + + @function_pod(output_keys="rate_hz", version=version) + def firing_rate(n_spikes: int, duration_s: float) -> float: + """Spikes per second of one unit (counted).""" + CALLS["firing_rate"] += 1 + return n_spikes / duration_s + + return firing_rate + + +@function_pod(output_keys="mean_rate_hz") +def mean_rate(rate_hz: list[float]) -> float: + """The mean of a subject's rates.""" + CALLS["mean_rate"] += 1 + return sum(rate_hz) / len(rate_hz) + + +def notify(ctx: Any, mean_rate_hz: float) -> None: + """The side effect: records each delivered payload in ``SENT``.""" + SENT.append(mean_rate_hz) + + +def units_table(extra: bool = False) -> pa.Table: + """The units source's rows; ``extra`` adds two.""" + rows = [ + (s, u, 100 + 7 * i, 10.0 + (i % 3)) + for i, (s, u) in enumerate( + (s, u) for s in ("m1", "m2", "m3", "m4") for u in ("u1", "u2", "u3") + ) + ] + if extra: + rows += [("m1", "u4", 999, 9.0), ("m2", "u4", 555, 11.0)] + schema = pa.schema( + [ + pa.field("subject_id", pa.large_string(), nullable=False), + pa.field("unit", pa.large_string(), nullable=False), + pa.field("n_spikes", pa.int64(), nullable=False), + pa.field("duration_s", pa.float64(), nullable=False), + ] + ) + return pa.Table.from_pylist( + [dict(zip(schema.names, r)) for r in rows], schema=schema + ) + + +SUBJECTS = pa.Table.from_pylist( + [ + {"subject_id": s, "genotype": g} + for s, g in (("m1", "ko"), ("m2", "ko"), ("m3", "wt"), ("m4", "ko")) + ], + schema=pa.schema( + [ + pa.field("subject_id", pa.large_string(), nullable=False), + pa.field("genotype", pa.large_string(), nullable=False), + ] + ), +) + + +def sources(extra: bool = False) -> dict[str, Any]: + """The job's two sources, by name.""" + return { + "units": ArrowTableSource( + units_table(extra), + tag_columns=["subject_id", "unit"], + tag_only_columns=True, + source_id="units", + record_id_columns=["subject_id", "unit"], + ), + "subjects": ArrowTableSource( + SUBJECTS, + tag_columns=["subject_id"], + source_id="subjects", + record_id_columns=["subject_id"], + ), + } + + +def build(job: PipelineJob, *, extra: bool = False, version: str = "v1.0") -> None: + """Build the evaluated pipeline in ``job``.""" + given = sources(extra) + units, subjects = given["units"], given["subjects"] + with job: + rates = make_rate(version).pod(units, label="rates") + kept = rates.join(subjects).filter(genotype="ko") + grouped = kept.group_by(["subject_id"]).select_data_columns(["rate_hz"]) + means = mean_rate.pod(grouped, label="means") + SideEffectPod(notify)(means, label="notify") + + +# ----------------------------------------------------------------- what is compared +# +# Two runs on Delta differ only in generated values: the run ids and times (the +# ``GENERATED`` columns, masked), and the function result ids, random per result, which +# also appear in the result tables' ``__record_id``, the pipeline tables' ``__data_id`` +# and inside the source-info tokens. Result ids are matched by the result's input hash +# (``__input_data_hash``) and replaced by the reference run's, at every place they +# appear (``IdMap``). Everything else is compared exactly: the schema (names, large +# types, nullability) apart from the rows, and the rows, in order where the run's +# order is deterministic (sync), as sets otherwise (async). No difference is ever +# dropped because the control shows one of the same kind: the control (a second Delta +# run) is itself compared, and a difference it shows means the normalization is +# incomplete, which fails the evaluation too. + + +GENERATED = { + "__pod_ts", + "__recorded_at", + "executed_at", + "__run_id", + "__pipeline_run_id", + "pipeline_run_id", + "__executor_info", +} +"""Columns whose values a run generates (times, run ids): masked before comparing.""" + + +def node_rows(job: PipelineJob) -> dict[str, pa.Table]: + """Every node's rows, with system tags, source info and content hashes.""" + columns = {"system_tags": True, "source": True, "content_hash": True} + return {n: job.nodes[n].as_table(columns=columns) for n in sorted(job.nodes)} + + +def node_hashes(job: PipelineJob) -> dict[str, tuple[str, str]]: + """Every node's content hash and pipeline hash.""" + out = {} + for name in sorted(job.nodes): + node = job.nodes[name] + out[name] = (node.content_hash().to_string(), node.pipeline_hash().to_string()) + return out + + +def stored(db: Any, job_name: str) -> dict[tuple[str, ...], pa.Table]: + """Every stored table this evaluation wrote, by path. + + Only paths under this evaluation's jobs (``job_name`` and its suffixed forms) and + under this evaluation's separate result database (``results/``, the run being + ``job_name`` without its ``eval_`` mark) are kept: a live dataset also holds the + tables of earlier evaluations. + """ + run = job_name.removeprefix("eval_") + out = {} + for path in db.list_table_paths(): + if not path or not ( + path[0].startswith(job_name) or tuple(path[:2]) == ("results", run) + ): + continue + table = db.get_all_records(path, record_id_column="__record_id") + if table is not None: + out[path] = table.sort_by("__record_id") + return out + + +def _binary(table: pa.Table, column: str) -> list[bytes]: + """A binary column's values (never null in a result table).""" + return cast("list[bytes]", table[column].to_pylist()) + + +class IdMap: + """Replaces another run's function result ids by the reference run's. + + Built from the result tables of the two stores: a result is the same result when + its input hash is the same. + """ + + def __init__( + self, + reference: dict[tuple[str, ...], pa.Table], + other: dict[tuple[str, ...], pa.Table], + ) -> None: + """Match ``other``'s result ids to ``reference``'s by input hash.""" + self.ids: dict[bytes, bytes] = {} + for path in set(reference) & set(other): + if not path[-1].startswith("rdb_"): + continue # not a function result table + ref, oth = reference[path], other[path] + by_input: dict[bytes, bytes] = dict( + zip(_binary(ref, "__input_data_hash"), _binary(ref, "__record_id")) + ) + for key, rid in zip( + _binary(oth, "__input_data_hash"), _binary(oth, "__record_id") + ): + if key in by_input: + self.ids[rid] = by_input[key] + self.text = {k.hex(): v.hex() for k, v in self.ids.items()} + self._pattern = ( + re.compile("|".join(sorted(self.text, key=len, reverse=True))) + if self.text + else None + ) + + def value(self, value: Any) -> Any: + """A value with every other-run id replaced, at any depth.""" + if isinstance(value, bytes): + return self.ids.get(value, value) + if isinstance(value, str) and self._pattern is not None: + return self._pattern.sub(lambda m: self.text[m.group(0)], value) + if isinstance(value, list): + return [self.value(v) for v in cast("list[Any]", value)] + if isinstance(value, dict): + return {k: self.value(v) for k, v in cast("dict[str, Any]", value).items()} + return value + + +def normalized_rows(table: pa.Table, ids: IdMap | None) -> list[dict[str, Any]]: + """The rows with generated columns masked and other-run ids replaced.""" + rows = table.to_pylist() + out = [] + for row in rows: + clean = { + name: (None if name in GENERATED else value) for name, value in row.items() + } + out.append(ids.value(clean) if ids is not None else clean) + return out + + +def schema_by_name(table: pa.Table) -> dict[str, tuple[str, bool]]: + """A table's columns by name: large-normalized type and nullability.""" + return { + f.name: (str(normalize_to_large_types(f.type, keep_null=True)), f.nullable) + for f in table.schema + } + + +def as_set(rows: list[dict[str, Any]]) -> list[str]: + """Rows as a sorted list of JSON texts: compared as a multiset.""" + return sorted(json.dumps(r, sort_keys=True, default=repr) for r in rows) + + +def compare_tables( + a: pa.Table, b: pa.Table, *, ordered: bool, ids: IdMap | None = None +) -> list[str]: + """Differences between a reference table ``a`` and ``b``. + + Compares the schemas by name (large types and nullability), then the rows, with + generated columns masked and ``b``'s result ids replaced by ``a``'s (``ids``): + in order when ``ordered``, as a multiset otherwise. + """ + problems = [] + sa, sb = schema_by_name(a), schema_by_name(b) + if sa != sb: + problems.append( + "schema differs: " + + ", ".join( + f"{n}: {sa.get(n)} vs {sb.get(n)}" + for n in sorted(set(sa) | set(sb)) + if sa.get(n) != sb.get(n) + ) + ) + common = [n for n in a.column_names if n in b.column_names] + ra = normalized_rows(a.select(common), None) + rb = normalized_rows(b.select(common), ids) + if ordered: + if ra != rb: + problems.append("rows differ (ordered)") + elif as_set(ra) != as_set(rb): + problems.append("rows differ (as sets)") + return problems + + +def compare_stores( + delta: dict[tuple[str, ...], pa.Table], + other: dict[tuple[str, ...], pa.Table], + ids: IdMap, +) -> list[str]: + """Differences between the reference Delta store and another: the paths, then each + table's schema and rows (as sets: a store keeps no row order).""" + problems = [] + if set(delta) != set(other): + problems.append( + f"paths only in Delta {sorted(set(delta) - set(other))}, only in the other " + f"store {sorted(set(other) - set(delta))}" + ) + for path in sorted(set(delta) & set(other)): + for problem in compare_tables(delta[path], other[path], ordered=False, ids=ids): + problems.append(f"{'/'.join(path)}: {problem}") + return problems + + +# ------------------------------------------------------------------- SpiralDB calls + + +class Calls: + """Counts the SDK calls of a store-mode connector, per table name.""" + + def __init__(self, connector: SpiralDBConnector) -> None: + """Wrap ``connector``'s store so every SDK call it makes is counted.""" + self.counts: Counter[tuple[str, str]] = Counter() + store = connector._store # pyright: ignore[reportPrivateUsage] + assert store is not None + self.store = store + open_table, list_tables = store._open_table, store._list_tables # pyright: ignore[reportPrivateUsage] + names_by_id: dict[str, str] = {} + + def counted_open(name: str) -> Any: + """Open a table by name, counted.""" + self.counts[("open by name", name)] += 1 + table = open_table(name) + if table is None: + return None + names_by_id[str(table.resource_id)] = name + return _Table(table, name, self.counts) + + def counted_list() -> dict[str, str]: + """List the dataset, counted.""" + self.counts[("list dataset", "*")] += 1 + listed = list_tables() + names_by_id.update(listed) + return listed + + client = store._client # pyright: ignore[reportPrivateUsage] + + store._open_table = counted_open # pyright: ignore[reportPrivateUsage] + store._list_tables = counted_list # pyright: ignore[reportPrivateUsage] + store._client = _Client(client, self.counts, names_by_id) # pyright: ignore[reportPrivateUsage] + + def by_path(self) -> dict[str, dict[str, int]]: + """The counts, per table path and kind of call.""" + out: dict[str, dict[str, int]] = defaultdict(dict) + paths = {n: "/".join(p) for n, p in self.store._paths.items()} # pyright: ignore[reportPrivateUsage] + for (what, name), n in sorted(self.counts.items()): + out[paths.get(name, name)][what] = n + return dict(out) + + def total(self) -> int: + """The number of calls counted.""" + return sum(self.counts.values()) + + +class _Client: + """A client whose table openings are counted.""" + + def __init__( + self, client: Any, counts: Counter[tuple[str, str]], names_by_id: dict[str, str] + ) -> None: + """Wrap ``client``; count into ``counts``, naming tables by ``names_by_id``.""" + self._client, self._c, self._names = client, counts, names_by_id + + def project(self, id: str) -> Any: + """A counting project.""" + return _Project(self._client.project(id), self._c) + + def keyed_table_by_id(self, table_id: str, **kw: Any) -> Any: + """Open a table by id, counted.""" + name = self._names.get(table_id, table_id) + self._c[("open by id", name)] += 1 + return _Table(self._client.keyed_table_by_id(table_id, **kw), name, self._c) + + +class _Project: + """A project whose creates are counted.""" + + def __init__(self, project: Any, counts: Counter[tuple[str, str]]) -> None: + """Wrap ``project``; count into ``counts``.""" + self._p, self._c = project, counts + + def create_keyed_table(self, dataset: str, name: str, key: Any, **kw: Any) -> Any: + """Create a table, counted.""" + self._c[("create", name)] += 1 + return _Table( + self._p.create_keyed_table(dataset, name, key, **kw), name, self._c + ) + + +class _Table: + """A keyed table whose calls are counted.""" + + def __init__(self, table: Any, name: str, counts: Counter[tuple[str, str]]) -> None: + """Wrap ``table`` (named ``name``); count into ``counts``.""" + self._t, self._n, self._c = table, name, counts + + def __getattr__(self, attr: str) -> Any: + """Every other attribute is the wrapped table's.""" + return getattr(self._t, attr) + + def get_metadata(self) -> Any: + """Read the metadata, counted.""" + self._c[("metadata read", self._n)] += 1 + return self._t.get_metadata() + + def set_metadata(self, metadata: Any) -> None: + """Write the metadata, counted.""" + self._c[("metadata write", self._n)] += 1 + self._t.set_metadata(metadata) + + def append(self, data: Any) -> Any: + """Commit rows, counted.""" + self._c[("commit", self._n)] += 1 + return _Table(self._t.append(data), self._n, self._c) + + def scan(self, columns: Any = None, **kw: Any) -> Any: + """Scan, counted by kind.""" + kind = "whole-table scan" if columns is None else f"scan of {list(columns)}" + if "limit" in kw: + kind += f" limit {kw['limit']}" + self._c[(kind, self._n)] += 1 + return self._t.scan(columns, **kw) + + +# ------------------------------------------------------------------------ scenarios + + +def open_backend(kind: str, root: Path, resources: ExitStack, run: str) -> Any: + """Return (database, result database, calls) of one backend.""" + if kind == "control": + db = DeltaTableDatabase(root / "control") + return db, db.at("results", run), None + if kind == "delta": + db = DeltaTableDatabase(root / "delta") + return db, db.at("results", run), None + if kind == "fake": + from tests.test_databases import fake_spiral_sdk as fake + + resources.enter_context(fake.install(root / "spiral")) + project, dataset, overrides = "p", "d", None + else: + project = os.environ["SPIRAL_PROJECT_ID"] + dataset = os.environ.get( + "ORCAPOD_SPIRAL_CONFORMANCE_DATASET", "orcapod_conformance" + ) + overrides = { + "server.url": os.environ.get( + "SPIRAL_SERVER_URL", "https://api.spiraldb.dev" + ) + } + connector = SpiralDBConnector(project, dataset, overrides, _store=True) + calls = Calls(connector) + db = ConnectorArrowDatabase(connector) + return db, db.at("results", run), calls + + +def evaluate(kind: str) -> dict[str, Any]: + """Run every scenario on Delta, a second Delta (the control) and the SpiralDB store + of ``kind`` (``fake`` or ``live``); return the report.""" + run = uuid.uuid4().hex[:8] + report: dict[str, Any] = {"backend": kind, "steps": {}, "failures": []} + with tempfile.TemporaryDirectory() as tmp, ExitStack() as resources: + root = Path(tmp) + backends = { + "delta": open_backend("delta", root, resources, run), + "control": open_backend("control", root, resources, run), + "spiral": open_backend(kind, root, resources, run), + } + name = f"eval_{run}" + saved = root / "job.json" + jobs: dict[str, dict[str, PipelineJob]] = defaultdict(dict) + payloads: dict[str, dict[str, list[float]]] = defaultdict(dict) + + def step(label: str, fn: Any) -> None: + """Run one scenario on every backend, then compare.""" + for backend, (db, rdb, calls) in backends.items(): + CALLS.clear() + SENT.clear() + before = calls.total() if calls else 0 + kinds_before = ( + Counter(k for (k, _), n in calls.counts.items() for _ in range(n)) + if calls + else Counter() + ) + start = time.perf_counter() + try: + job = fn(backend, db, rdb) + error = None + except Exception as exc: # noqa: BLE001 # every failure is reported + job, error = None, f"{type(exc).__name__}: {exc}" + took = time.perf_counter() - start + entry: dict[str, Any] = { + "seconds": round(took, 3), + "function_calls": dict(CALLS), + "side_effects_sent": len(SENT), + } + payloads[label][backend] = list(SENT) + if calls is not None: + entry["spiral_calls"] = calls.total() - before + kinds = Counter( + k for (k, _), n in calls.counts.items() for _ in range(n) + ) + entry["spiral_calls_by_kind"] = dict(kinds - kinds_before) + if error: + entry["error"] = error + report["failures"].append(f"{label} on {backend}: {error}") + report["steps"].setdefault(label, {})[backend] = entry + if job is not None: + jobs[label][backend] = job + pair = jobs.get(label, {}) + try: + compare(label, pair) + compare_payloads(label, payloads[label]) + except Exception as exc: # noqa: BLE001 # every failure is reported + report["failures"].append( + f"{label}: comparing: {type(exc).__name__}: {exc}" + ) + + def differences( + label: str, d: PipelineJob, other: PipelineJob, db: Any + ) -> list[str]: + """Every difference of ``other``'s job and store from Delta's, generated + values normalized (see ``compare_tables``).""" + found: list[str] = [] + if node_hashes(d) != node_hashes(other): + found.append("node hashes differ") + reference = stored(backends["delta"][0], name) + theirs = stored(db, name) + ids = IdMap(reference, theirs) + ordered = "async" not in label + rd, ro = node_rows(d), node_rows(other) + for node in sorted(set(rd) | set(ro)): + if node not in rd or node not in ro: + found.append(f"node {node}: in one job only") + continue + for problem in compare_tables( + rd[node], ro[node], ordered=ordered, ids=ids + ): + found.append(f"node {node}: {problem}") + for problem in compare_stores(reference, theirs, ids): + found.append(f"store: {problem}") + return found + + def compare(label: str, pair: dict[str, PipelineJob]) -> None: + """Compare the store, and the control, with Delta: every difference is a + failure (the control's means the normalization missed a generated value).""" + if len(pair) != 3: + return + for backend in ("control", "spiral"): + for problem in differences( + label, pair["delta"], pair[backend], backends[backend][0] + ): + report["failures"].append(f"{label}: {backend}: {problem}") + + def compare_payloads(label: str, sent: dict[str, list[float]]) -> None: + """The side effect's delivered payloads equal Delta's: in order, except + in the async scenario, whose delivery order is not defined.""" + reference = sent.get("delta") + if reference is None: + return + for backend in ("control", "spiral"): + got = sent.get(backend) + if got is None: + continue + if "async" in label: + same = sorted(got) == sorted(reference) + else: + same = got == reference + if not same: + report["failures"].append( + f"{label}: {backend}: side effect payloads {got} vs {reference}" + ) + + def first(backend: str, db: Any, rdb: Any) -> PipelineJob: + """The first run (Delta also saves the job).""" + job = PipelineJob(name=name, database=db) + build(job) + job.run() + if backend == "delta": + job.save(saved) + return job + + def again(backend: str, db: Any, rdb: Any, **options: Any) -> PipelineJob: + """A new job of the same name, run.""" + job = PipelineJob(name=name, database=db) + build(job, **options) + job.run() + return job + + step("first run", first) + step("unchanged rerun", again) + step("added rows", lambda b, db, rdb: again(b, db, rdb, extra=True)) + step( + "changed function version", + lambda b, db, rdb: again(b, db, rdb, extra=True, version="v2.0"), + ) + + def run_async(backend: str, db: Any, rdb: Any) -> PipelineJob: + """A new job, run asynchronously.""" + job = PipelineJob(name=name + "_async", database=db) + build(job) + asyncio.run(job.run_async()) + return job + + step("run_async (first run, compared as sets)", run_async) + + def load_only(backend: str, db: Any, rdb: Any) -> PipelineJob: + """The saved job, loaded and run load-only.""" + job = PipelineJob.load(saved, database=db) + job.bind(sources=sources()) + job.run(load_only=True) + return job + + step("save, load, run(load_only=True)", load_only) + + def cleared(backend: str, db: Any, rdb: Any) -> PipelineJob: + """A run, every node cleared, then another run.""" + job = PipelineJob(name=name, database=db) + build(job) + job.run() + for node in job.nodes.values(): + clear = getattr(node, "clear_cache", None) + if clear is not None: + clear() + job.run() + return job + + step("clear_cache, then run", cleared) + + def separate(backend: str, db: Any, rdb: Any) -> PipelineJob: + """A job with a separate result database.""" + job = PipelineJob(name=name + "_sep", database=db, result_database=rdb) + build(job) + job.run() + return job + + step("separate result database", separate) + + traces: dict[str, str] = {} + for backend in ("delta", "control", "spiral"): + job = jobs.get("first run", {}).get(backend) + if job is None: + continue + try: + trace = job.nodes["means"].trace({"subject_id": "m1"}, "mean_rate_hz") + # Times and run ids are generated: masked. + text = re.sub( + r"\d{4}-\d\d-\d\d \d\d:\d\d:\d\d UTC", "