diff --git a/docs/design/measurement-result-parquet.md b/docs/design/measurement-result-parquet.md index 10cc698..9ab2a08 100644 --- a/docs/design/measurement-result-parquet.md +++ b/docs/design/measurement-result-parquet.md @@ -135,7 +135,7 @@ Only the first is a compatible change. The others are a new message contract, wh The program reads each document strictly and checks it as `bx validate` does, then writes all documents given to it as the rows of one file. It runs from a checkout, since `tools/` is not part of the installed package: ```bash -pip install -e . +pip install -e '.[parquet]' python tools/json_to_parquet.py results.parquet \ src/benchx/schemas/measurement-result/0.1.0/examples/*.json ``` diff --git a/src/benchx/_pyarrow.py b/src/benchx/_pyarrow.py new file mode 100644 index 0000000..f5ab80c --- /dev/null +++ b/src/benchx/_pyarrow.py @@ -0,0 +1,40 @@ +"""Lazy PyArrow availability checks and guarded imports. + +Importing this module never imports `pyarrow`, so minimal installs without the +`benchx[parquet]` extra can check availability and run JSON-only paths cleanly. +""" + +from __future__ import annotations + +import importlib.util +import sys + + +def is_pyarrow_missing(exc: ModuleNotFoundError) -> bool: + """Whether `exc` is specifically a missing `pyarrow` dependency.""" + return bool(exc.name and exc.name.split(".")[0] == "pyarrow") + + +def has_pyarrow() -> bool: + """Whether `pyarrow` is importable, without importing it.""" + if "pyarrow" in sys.modules: + return sys.modules["pyarrow"] is not None + try: + return importlib.util.find_spec("pyarrow") is not None + except (ValueError, ModuleNotFoundError): + return False + + +def require_pyarrow(feature: str = "Parquet support"): + """Import and return `(pyarrow, pyarrow.parquet)`, or explain the `benchx[parquet]` extra.""" + try: + import pyarrow as pa + import pyarrow.parquet as pq + except ModuleNotFoundError as exc: + if is_pyarrow_missing(exc): + raise ModuleNotFoundError( + f"{feature} requires pyarrow; install it with `pip install 'benchx[parquet]'`.", + name="pyarrow", + ) from exc + raise + return pa, pq diff --git a/src/benchx/cli.py b/src/benchx/cli.py index f26d5c4..3774d33 100644 --- a/src/benchx/cli.py +++ b/src/benchx/cli.py @@ -24,6 +24,7 @@ from . import tables as tables_mod from . import target as target_mod from . import views as views_mod +from ._pyarrow import is_pyarrow_missing from .core.validation import Kind from .results import MemoryStore, warning_codes @@ -305,7 +306,7 @@ def _open_store(path, command: str, *, hint: str | None = None): try: return Store(path) except ModuleNotFoundError as exc: - if exc.name and exc.name.split(".")[0] == "pyarrow": + if is_pyarrow_missing(exc): suffix = f", or {hint}" if hint else "" say.error( f"bx {command}: error: Parquet store ({path}) requires pyarrow; " @@ -1222,7 +1223,7 @@ def _run_build(out_dir: Path) -> dict | None: try: return views_mod.build_site(out_dir, **build_kwargs) except ModuleNotFoundError as exc: - if exc.name and exc.name.split(".")[0] == "pyarrow": + if is_pyarrow_missing(exc): hint = "" if "store_path" in source_kwargs: hint = ", or pass --results DIR to build views from JSON results directly" diff --git a/src/benchx/config.py b/src/benchx/config.py index 030a701..dee1a15 100644 --- a/src/benchx/config.py +++ b/src/benchx/config.py @@ -18,14 +18,13 @@ """ import copy -import importlib.util import json import os -import sys from dataclasses import dataclass from pathlib import Path from . import adapters, core +from ._pyarrow import has_pyarrow from .core import loader CONFIG_FILE = "benchx.conf.json" @@ -39,13 +38,6 @@ REQUIRED = object() -def _has_pyarrow() -> bool: - """Whether pyarrow is importable, without importing it.""" - if "pyarrow" in sys.modules: - return sys.modules["pyarrow"] is not None - return importlib.util.find_spec("pyarrow") is not None - - def _default_store_in(directory: Path) -> Path: """Pick the default store file in `directory`: keep whichever already exists (preferring Parquet so an existing Parquet store is never silently split into @@ -56,7 +48,7 @@ def _default_store_in(directory: Path) -> Path: jsonl_path = directory / DEFAULT_JSON_STORE if jsonl_path.exists(): return jsonl_path - return parquet_path if _has_pyarrow() else jsonl_path + return parquet_path if has_pyarrow() else jsonl_path class ConfigError(Exception): diff --git a/src/benchx/core/catalog.py b/src/benchx/core/catalog.py index 48f1da8..fcb996b 100644 --- a/src/benchx/core/catalog.py +++ b/src/benchx/core/catalog.py @@ -118,14 +118,19 @@ def _format_checker(schema: dict) -> FormatChecker: return checker +def schema(kind: str, version: str) -> dict | None: + """The raw JSON Schema dict for `kind` at `version`, without building a validator.""" + named = release(kind, version) + return _read(kind, named) if named else None + + @cache def lookup(kind: str, version: str) -> Draft202012Validator | None: - named = release(kind, version) - schema = _read(kind, named) if named else None - if schema is None: + schema_doc = schema(kind, version) + if schema_doc is None: return None - return Draft202012Validator(schema, format_checker=_format_checker(schema), registry=_registry()) + return Draft202012Validator(schema_doc, format_checker=_format_checker(schema_doc), registry=_registry()) @cache diff --git a/src/benchx/parquet.py b/src/benchx/parquet.py index 883dc77..b866c29 100644 --- a/src/benchx/parquet.py +++ b/src/benchx/parquet.py @@ -9,43 +9,54 @@ from datetime import datetime -try: - import pyarrow as pa -except ModuleNotFoundError as exc: - if exc.name and exc.name.split(".")[0] == "pyarrow": - raise ModuleNotFoundError( - "Parquet support requires pyarrow; install it with `pip install 'benchx[parquet]'`.", - name="pyarrow", - ) from exc - raise -import rfc8785 - +from ._pyarrow import require_pyarrow from .core import catalog from .core.hashing import canonical, sha256_hex -_VALIDATOR = catalog.lookup("measurement-result", catalog.MEASUREMENT_RESULT) -if _VALIDATOR is None: +pa, _ = require_pyarrow("Parquet support") + +RESULT_SCHEMA = catalog.schema("measurement-result", catalog.MEASUREMENT_RESULT) +if RESULT_SCHEMA is None: raise RuntimeError( f"result schema not found under {catalog.SCHEMAS}; " "reinstall benchx, or set BENCHX_SCHEMAS to a directory of schemas" ) -RESULT_SCHEMA = _VALIDATOR.schema TIMESTAMP = pa.timestamp("us", tz="UTC") +JSON_TYPE = pa.json_() SCALARS = {"string": pa.string(), "integer": pa.int64(), "number": pa.float64(), "boolean": pa.bool_()} - - -def arrow_type(node, defs, json_type): +_ALLOF_ASSERTION_KEYS = frozenset({"required", "not", "if", "then", "else", "description", "$comment"}) + + +def _resolve_ref(node: dict, defs: dict) -> dict: + seen: set[str] = set() + while "$ref" in node: + ref = node["$ref"] + if not isinstance(ref, str) or not ref.startswith("#/$defs/"): + raise ValueError(f"unsupported $ref: {ref!r}") + name = ref.removeprefix("#/$defs/") + if name in seen: + raise ValueError(f"cyclic $ref: {ref!r}") + if name not in defs: + raise ValueError(f"unknown $ref: {ref!r}") + seen.add(name) + node = defs[name] + return node + + +def arrow_type(node, defs): """Map one JSON Schema node to an Arrow type.""" - if "$ref" in node: - node = defs[node["$ref"].rsplit("/", 1)[-1]] - nested = lambda n: arrow_type(n, defs, json_type) # noqa: E731 + node = _resolve_ref(node, defs) if "allOf" in node and "type" not in node: # a reference narrowed by assertions - if "$ref" not in node["allOf"][0]: + parts = node["allOf"] + if not isinstance(parts, list) or not parts or not isinstance(parts[0], dict) or "$ref" not in parts[0]: raise ValueError(f"unsupported allOf without a leading reference: {node}") - return nested(node["allOf"][0]) + for extra in parts[1:]: + if not isinstance(extra, dict) or not set(extra) <= _ALLOF_ASSERTION_KEYS: + raise ValueError(f"unsupported allOf assertion: {node}") + return arrow_type(parts[0], defs) if "oneOf" in node: # union of closed objects, or number-or-object observation - branches = [defs[b["$ref"].rsplit("/", 1)[-1]] if "$ref" in b else b for b in node["oneOf"]] + branches = [_resolve_ref(b, defs) for b in node["oneOf"]] objects = [b for b in branches if b.get("type") == "object"] others = [b for b in branches if b.get("type") != "object"] closed = all(b.get("additionalProperties") is False and "properties" in b for b in objects) @@ -54,13 +65,17 @@ def arrow_type(node, defs, json_type): bare = [b.get("type") for b in others] == ["number"] and len(objects) == 1 if not objects or not closed or (others and not bare): raise ValueError(f"unsupported oneOf: {node}") - if others and nested(objects[0]["properties"].get("value", {})) != SCALARS["number"]: - raise ValueError(f"unsupported oneOf: a bare number needs a number `value` to be stored in: {node}") + if others: + props = objects[0]["properties"] + if "value" not in props or arrow_type(props["value"], defs) != SCALARS["number"]: + raise ValueError(f"unsupported oneOf: a bare number needs a number `value` to be stored in: {node}") + if not set(objects[0].get("required", [])) <= {"value"}: + raise ValueError(f"unsupported oneOf: bare number requires only `value`: {node}") required = set.intersection(*(set(b.get("required", [])) for b in objects)) types = {} # in first-appearance order for b in objects: for k, v in b["properties"].items(): - t = nested(v) + t = arrow_type(v, defs) if types.setdefault(k, t) != t: raise ValueError(f"oneOf alternatives disagree on the type of {k!r}: {types[k]} and {t}") return pa.struct([pa.field(k, t, k not in required) for k, t in types.items()]) @@ -70,33 +85,84 @@ def arrow_type(node, defs, json_type): raise ValueError(f"unsupported const or enum: {node}") return pa.string() if literals == {str} else pa.int64() if node.get("type") == "array": - return pa.list_(pa.field("element", nested(node["items"]), False)) + if "items" not in node: + raise ValueError(f"unsupported array without items: {node}") + return pa.list_(pa.field("element", arrow_type(node["items"], defs), False)) if node.get("type") == "object": if node.get("additionalProperties") is not False or "properties" not in node: - return json_type + return JSON_TYPE required = node.get("required", []) - return pa.struct([pa.field(k, nested(v), k not in required) for k, v in node["properties"].items()]) - if node.get("format") == "date-time": + return pa.struct([pa.field(k, arrow_type(v, defs), k not in required) for k, v in node["properties"].items()]) + if node.get("format") == "date-time" and node.get("type") in (None, "string"): return TIMESTAMP scalar = node.get("type") - return SCALARS[scalar] if isinstance(scalar, str) else json_type # mixed primitives stay JSON + if isinstance(scalar, str) and scalar in SCALARS: + return SCALARS[scalar] + if isinstance(scalar, list) and scalar and set(scalar) <= (set(SCALARS) | {"null"}): + return JSON_TYPE # mixed primitives stay JSON + raise ValueError(f"unsupported schema node: {node}") + + +def _is_bare_number(value) -> bool: + return isinstance(value, (int, float)) and not isinstance(value, bool) def to_row(data_type, value): """Shape one message value for its Arrow type.""" - if value is None: - return None - if pa.types.is_struct(data_type): - if not isinstance(value, dict): # a bare observation number - value = {"value": value} - return {f.name: to_row(f.type, value.get(f.name)) for f in data_type} - if pa.types.is_list(data_type): - return [to_row(data_type.value_type, v) for v in value] - if data_type == pa.json_(): # open object as canonical JSON - return rfc8785.dumps(value).decode() + conv = _compile_row(data_type) + if conv is None: + if value is not None and pa.types.is_struct(data_type) and not isinstance(value, dict): + raise TypeError(f"expected dict for struct {data_type}, got {type(value).__name__}") + return value + return conv(value) + + +def _compile_row(data_type): + """Compile a specialized converter for `data_type`, or `None` when identity suffices.""" + if data_type == JSON_TYPE: + return lambda v: None if v is None else canonical(v).decode() if data_type == TIMESTAMP: - return datetime.fromisoformat(value) - return value + return lambda v: None if v is None else datetime.fromisoformat(v) + if pa.types.is_list(data_type): + elem = _compile_row(data_type.value_type) + if elem is None: + return None + return lambda v: None if v is None else [elem(x) for x in v] + if pa.types.is_struct(data_type): + transforms = {f.name: fn for f in data_type if (fn := _compile_row(f.type)) is not None} + allows_bare = data_type.get_field_index("value") >= 0 + if not transforms and not allows_bare: + return None + + def convert_struct(v): + if v is None: + return None + if not isinstance(v, dict): + if allows_bare and _is_bare_number(v): + return {"value": v} + raise TypeError(f"expected dict for struct {data_type}, got {type(v).__name__}") + if not transforms: + return v + return {k: transforms[k](val) if k in transforms else val for k, val in v.items()} + + return convert_struct + return None + + +def _storage_type(dtype: pa.DataType) -> pa.DataType: + """Replace `arrow.json` with `string` so `pa.Table.from_pylist` can build nested values.""" + if dtype == JSON_TYPE: + return pa.string() + if pa.types.is_struct(dtype): + return pa.struct([pa.field(f.name, _storage_type(f.type), f.nullable) for f in dtype]) + if pa.types.is_list(dtype): + elem = dtype.value_field + return pa.list_(pa.field(elem.name, _storage_type(elem.type), elem.nullable)) + return dtype + + +def _storage_schema(schema: pa.Schema) -> pa.Schema: + return pa.schema([pa.field(f.name, _storage_type(f.type), f.nullable) for f in schema]) # Columns the store derives at ingest, beside the message columns. @@ -107,14 +173,12 @@ def to_row(data_type, value): pa.field("attempt_signature", pa.string(), False), # schema §5.3 attempt integrity # The document itself, canonical: the message columns cannot reproduce it (a bare # number and a structured observation map alike), and the comparator reads it. - pa.field("document", pa.json_(), False), + pa.field("document", JSON_TYPE, False), pa.field("work_order_ref", pa.string()), - pa.field("work_order", pa.json_()), # the referenced order, when it was delivered + pa.field("work_order", JSON_TYPE), # the referenced order, when it was delivered ] -_DEFS = RESULT_SCHEMA["$defs"] -_BUILD = arrow_type(RESULT_SCHEMA, _DEFS, pa.string()) -_FINAL = arrow_type(RESULT_SCHEMA, _DEFS, pa.json_()) +_FINAL = arrow_type(RESULT_SCHEMA, RESULT_SCHEMA["$defs"]) # Which message schema a file was written under; the checksum tells drafts # apart that change under one URI (measurement-result-parquet.md §3). _METADATA = { @@ -123,21 +187,23 @@ def to_row(data_type, value): } MESSAGE_SCHEMA = pa.schema(list(_FINAL), metadata=_METADATA) RESULTS_SCHEMA = pa.schema(list(_FINAL) + DERIVED, metadata=_METADATA) +_MESSAGE_BUILD_SCHEMA = _storage_schema(MESSAGE_SCHEMA) +_RESULTS_BUILD_SCHEMA = _storage_schema(RESULTS_SCHEMA) +_to_message_row = _compile_row(_FINAL) or (lambda doc: doc) -def _table(rows: list[dict], extra: list[pa.Field], schema: pa.Schema) -> pa.Table: +def _table(rows: list[dict], build_schema: pa.Schema, schema: pa.Schema) -> pa.Table: # Build with strings, then cast: PyArrow cannot fill nested JSON fields # from Python values directly. - build = [pa.field(f.name, pa.string(), f.nullable) if f.type == pa.json_() else f for f in extra] - return pa.Table.from_pylist(rows, schema=pa.schema(list(_BUILD) + build)).cast(schema) + return pa.Table.from_pylist(rows, schema=build_schema).cast(schema) def message_table(documents: list[dict]) -> pa.Table: """One row per validated result: the message columns alone.""" - return _table([to_row(_FINAL, doc) for doc in documents], [], MESSAGE_SCHEMA) + return _table([_to_message_row(doc) for doc in documents], _MESSAGE_BUILD_SCHEMA, MESSAGE_SCHEMA) def results_table(documents: list[dict], derived: list[dict]) -> pa.Table: """One row per result: the message columns, then the derived columns.""" - rows = [{**to_row(_FINAL, doc), **extra} for doc, extra in zip(documents, derived)] - return _table(rows, DERIVED, RESULTS_SCHEMA) + rows = [{**_to_message_row(doc), **extra} for doc, extra in zip(documents, derived, strict=True)] + return _table(rows, _RESULTS_BUILD_SCHEMA, RESULTS_SCHEMA) diff --git a/src/benchx/results.py b/src/benchx/results.py index e8ca51a..a82c695 100644 --- a/src/benchx/results.py +++ b/src/benchx/results.py @@ -117,6 +117,7 @@ def ingest_documents( accepted, derived = [], [] outcome = {"ingested": 0, "duplicate": 0, "rejected": []} used_orders, without_order = set(), 0 + encoded_orders: dict[str, str] = {} for name, text in documents: doc, errors = loader.parse(text) if doc is not None: @@ -191,8 +192,13 @@ def ingest_documents( order = orders.get(ref) if order is None: without_order += 1 + encoded_order = None else: used_orders.add(ref) + encoded_order = encoded_orders.get(ref) + if encoded_order is None: + encoded_order = core.canonical(order).decode() + encoded_orders[ref] = encoded_order accepted.append(doc) derived.append( { @@ -202,7 +208,7 @@ def ingest_documents( "attempt_signature": signature, "document": canonical.decode(), "work_order_ref": ref, - "work_order": core.canonical(order).decode() if order is not None else None, + "work_order": encoded_order, } ) outcome["ingested"] += 1 diff --git a/src/benchx/store.py b/src/benchx/store.py index 8a2f9fc..77feac7 100644 --- a/src/benchx/store.py +++ b/src/benchx/store.py @@ -17,11 +17,13 @@ import logging import os import statistics +import tempfile import time from datetime import datetime from pathlib import Path from . import core, identity +from ._pyarrow import require_pyarrow from .projection import Projection from .results import ingest_documents, store_project, sweep_paths, warning_codes @@ -33,16 +35,7 @@ def _is_json_path(path: Path) -> bool: def _require_pyarrow(): - try: - import pyarrow as pa - import pyarrow.parquet as pq - except ModuleNotFoundError as exc: - if exc.name and exc.name.split(".")[0] == "pyarrow": - raise ModuleNotFoundError( - "Parquet store requires pyarrow; install it with `pip install 'benchx[parquet]'`.", - name="pyarrow", - ) from exc - raise + pa, pq = require_pyarrow("Parquet store") from . import parquet return pa, pq, parquet @@ -107,28 +100,35 @@ def _index(self) -> list[dict]: } ) return out - table = self._table( - [ - "producer", - "ingest_key", - "attempt_key", - "payload_sha256", - "attempt_signature", - "store_project", - "measurement", - ] - ) + cols = [ + "producer.name", + "ingest_key", + "attempt_key", + "payload_sha256", + "attempt_signature", + "store_project", + "measurement.quantity.name", + "measurement.quantity.unit", + ] + table = self._table(cols) if table is None: return [] - producers = table.column("producer").combine_chunks().field("name").to_pylist() - quantity = table.column("measurement").combine_chunks().field("quantity") - rest = table.select( - ["ingest_key", "attempt_key", "payload_sha256", "attempt_signature", "store_project"] - ).to_pylist() + producers, ingest_keys, attempt_keys, payloads, signatures, projects, quantities, units = ( + table.column(i).to_pylist() for i in range(len(cols)) + ) return [ - dict(row, producer=p, quantity=q, unit=u) - for row, p, q, u in zip( - rest, producers, quantity.field("name").to_pylist(), quantity.field("unit").to_pylist() + { + "producer": p, + "ingest_key": ik, + "attempt_key": ak, + "payload_sha256": ps, + "attempt_signature": sig, + "store_project": sp, + "quantity": q, + "unit": u, + } + for p, ik, ak, ps, sig, sp, q, u in zip( + producers, ingest_keys, attempt_keys, payloads, signatures, projects, quantities, units ) ] @@ -138,15 +138,18 @@ def _documents(self, run_key=None) -> list[dict]: found = docs if run_key is None else [d for d in docs if d["provenance"]["run_key"] == run_key] logger.debug("documents(%s): %d of %d stored document(s)", run_key, len(found), len(docs)) return found - table = self._table(["provenance", "document"]) + if run_key is None: + table = self._table(["document"]) + if table is None: + return [] + found = [json.loads(text) for text in table.column(0).to_pylist()] + logger.debug("documents(%s): %d of %d stored document(s)", run_key, len(found), table.num_rows) + return found + table = self._table(["provenance.run_key", "document"]) if table is None: return [] - run_keys = table.column("provenance").combine_chunks().field("run_key").to_pylist() - found = [ - json.loads(text) - for r, text in zip(run_keys, table.column("document").to_pylist()) - if run_key is None or r == run_key - ] + run_keys = table.column(0).to_pylist() + found = [json.loads(text) for r, text in zip(run_keys, table.column(1).to_pylist()) if r == run_key] logger.debug("documents(%s): %d of %d stored document(s)", run_key, len(found), len(run_keys)) return found @@ -213,14 +216,26 @@ def head( } ) return len(all_rows), rows[::-1] - table = self._table( - ["ingest_key", "revision", "coordinates", "measurement", "provenance", "store_project", "document"] - ) + cols = [ + "store_project", + "coordinates.workload.name", + "measurement.kind", + "provenance.started_at", + "provenance.run_key", + "measurement.quantity.name", + "measurement.quantity.unit", + "measurement.status", + "measurement.observations", + "revision.key", + "provenance.labels", + "document", + ] + table = self._table(cols) if table is None: return 0, [] - projects = table.column("store_project").to_pylist() - names = table.column("coordinates").combine_chunks().field("workload").field("name").to_pylist() - kinds = table.column("measurement").combine_chunks().field("kind").to_pylist() + projects = table.column(0).to_pylist() + names = table.column(1).to_pylist() + kinds = table.column(2).to_pylist() kept = [ i for i, (pr, name, kind) in enumerate(zip(projects, names, kinds)) @@ -231,23 +246,27 @@ def head( kept = kept[max(0, len(kept) - n) :] if not kept: return table.num_rows, [] + sub = table.take(kept) + col_lists = [sub.column(i).to_pylist() for i in range(len(cols))] rows = [] - for position, row in zip(kept, table.take(kept).to_pylist()): - values = [o["value"] for o in row["measurement"]["observations"] or []] + for position, (pr, name, _kind, started_at, run_key, qname, qunit, status, obs, rev_key, labels, doc) in zip( + kept, zip(*col_lists) + ): + values = [o["value"] for o in obs or []] rows.append( { "row": position, - "started_at": row["provenance"]["started_at"], - "run_key": row["provenance"]["run_key"], - "project": row["store_project"], - "workload": row["coordinates"]["workload"]["name"], - "quantity": row["measurement"]["quantity"]["name"], - "unit": row["measurement"]["quantity"]["unit"], - "status": row["measurement"]["status"], + "started_at": started_at, + "run_key": run_key, + "project": pr, + "workload": name, + "quantity": qname, + "unit": qunit, + "status": status, "median": statistics.median(values) if values else None, - "revision": row["revision"]["key"], - "labels": row["provenance"]["labels"], - "document": row["document"], + "revision": rev_key, + "labels": labels, + "document": doc, } ) return table.num_rows, rows[::-1] @@ -332,24 +351,12 @@ def _write_json(self, new_rows: list[dict]) -> None: if existing and not existing.endswith("\n"): existing += "\n" appended = "".join(json.dumps(row, separators=(",", ":"), ensure_ascii=False) + "\n" for row in new_rows) - tmp = self.path.with_name(f".{self.path.name}.tmp") - try: - self.path.parent.mkdir(parents=True, exist_ok=True) - with open(tmp, "w", encoding="utf-8") as f: - f.write(existing) - f.write(appended) - f.flush() - os.fsync(f.fileno()) - os.replace(tmp, self.path) - except OSError as e: # disk full, permissions: the results are still in their files - logger.error( - "cannot write %s (%d row(s) were to be added): %s; a partial %s may be left behind", - self.path, - len(new_rows), - e.strerror or e, - tmp, - ) - raise + _atomic_write( + self.path, + len(new_rows), + "w", + lambda f: (f.write(existing), f.write(appended)), + ) logger.debug( "wrote %s: %d row(s) added to %d, %.2f s", self.path, len(new_rows), old_count, time.monotonic() - started ) @@ -361,35 +368,44 @@ def _write_parquet(self, new) -> None: # Rows written under an older message schema are carried over, with # nulls in any column or nested field the schema has since gained. table = new if old is None else self._pa.concat_tables([old, new], promote_options="permissive") - if old is not None and logger.isEnabledFor(logging.DEBUG): - before, after = _fields(old.schema, self._pa), _fields(table.schema, self._pa) - added = sorted(set(after) - set(before)) - widened = sorted( - f"{path}: {before[path]} to {after[path]}" for path in before if before[path] != after[path] - ) - if added or widened: # permissive promotion adds nested fields and widens types, not only columns - logger.debug( - "%s: the schema was promoted: added %s; widened %s", + if old is not None: + old_uri = (old.schema.metadata or {}).get(b"benchx.schema_uri") + new_uri = (new.schema.metadata or {}).get(b"benchx.schema_uri") + if old_uri and new_uri and old_uri != new_uri: + logger.warning( + "%s: appending schema %s to store written under %s", self.path, - ", ".join(added) or "nothing", - ", ".join(widened) or "nothing", + new_uri.decode(errors="replace"), + old_uri.decode(errors="replace"), ) - tmp = self.path.with_name(f".{self.path.name}.tmp") - try: - self.path.parent.mkdir(parents=True, exist_ok=True) - self._pq.write_table(table.replace_schema_metadata(new.schema.metadata), tmp, compression="zstd") - with open(tmp, "rb") as f: - os.fsync(f.fileno()) - os.replace(tmp, self.path) - except OSError as e: # disk full, permissions: the results are still in their files - logger.error( - "cannot write %s (%d row(s) were to be added): %s; a partial %s may be left behind", - self.path, - new.num_rows, - e.strerror or e, - tmp, - ) - raise + before = _fields(old.schema, self._pa) + new_fields = _fields(new.schema, self._pa) + removed = sorted(set(before) - set(new_fields)) + if removed: + logger.warning( + "%s: store has field(s) absent from the current schema (null in new rows): %s", + self.path, + ", ".join(removed), + ) + if logger.isEnabledFor(logging.DEBUG): + after = _fields(table.schema, self._pa) + added = sorted(set(after) - set(before)) + widened = sorted( + f"{path}: {before[path]} to {after[path]}" for path in before if before[path] != after[path] + ) + if added or widened: # permissive promotion adds nested fields and widens types, not only columns + logger.debug( + "%s: the schema was promoted: added %s; widened %s", + self.path, + ", ".join(added) or "nothing", + ", ".join(widened) or "nothing", + ) + _atomic_write( + self.path, + new.num_rows, + "wb", + lambda f: self._pq.write_table(table.replace_schema_metadata(new.schema.metadata), f, compression="zstd"), + ) logger.debug( "wrote %s: %d row(s) added to %d, %.2f s", self.path, @@ -399,6 +415,31 @@ def _write_parquet(self, new) -> None: ) +def _atomic_write(path: Path, row_count: int, mode: str, write_fn) -> None: + """Write via a sibling temp file, fsync, and replace atomically, cleaning up on failure.""" + path.parent.mkdir(parents=True, exist_ok=True) + kwargs = {"encoding": "utf-8"} if "b" not in mode else {} + tmp: Path | None = None + try: + with tempfile.NamedTemporaryFile( + mode=mode, dir=path.parent, prefix=f".{path.name}.", suffix=".tmp", delete=False, **kwargs + ) as f: + tmp = Path(f.name) + write_fn(f) + f.flush() + os.fsync(f.fileno()) + os.replace(tmp, path) + except OSError as e: # disk full, permissions: the results are still in their files + if tmp is not None: + tmp.unlink(missing_ok=True) + logger.error("cannot write %s (%d row(s) were to be added): %s", path, row_count, e.strerror or e) + raise + except BaseException: + if tmp is not None: + tmp.unlink(missing_ok=True) + raise + + def _fields(schema, pa) -> dict[str, str]: """Every leaf of a schema by dotted path, with its type: what a schema promotion can change.""" found = {} @@ -407,6 +448,8 @@ def walk(prefix, kind): if pa.types.is_struct(kind): for child in kind: walk(f"{prefix}.{child.name}", child.type) + elif pa.types.is_list(kind) or pa.types.is_large_list(kind): + walk(f"{prefix}[]", kind.value_type) else: found[prefix] = str(kind) diff --git a/src/benchx/views/inputs.py b/src/benchx/views/inputs.py index 84835c8..385eb6a 100644 --- a/src/benchx/views/inputs.py +++ b/src/benchx/views/inputs.py @@ -22,7 +22,9 @@ import rfc8785 from .. import identity, projection +from .._pyarrow import require_pyarrow as _require_pyarrow from ..results import MemoryStore +from ..store import JSON_SUFFIXES UTC = dt.UTC _HEX_RE = re.compile(r"^[0-9a-fA-F]{7,40}$") @@ -60,20 +62,6 @@ def short_sha(sha: str) -> str: return sha[:12] -def _require_pyarrow(feature: str = "Parquet view support"): - try: - import pyarrow as pa - import pyarrow.parquet as pq - except ModuleNotFoundError as exc: - if exc.name and exc.name.split(".")[0] == "pyarrow": - raise ModuleNotFoundError( - f"{feature} requires pyarrow; install it with `pip install 'benchx[parquet]'`.", - name="pyarrow", - ) from exc - raise - return pa, pq - - def parse_time(value) -> dt.datetime | None: """Parse an ISO-8601 timestamp or datetime into a UTC datetime (or None).""" if value is None or value == "": @@ -609,7 +597,7 @@ def read_store(store_path: str | Path, *, repo: Path | None = None) -> tuple[lis path = check_local_path(store_path) if not path.is_file(): raise ViewError(f"store not found: {path}") - if path.suffix.lower() in (".jsonl", ".json", ".ndjson"): + if path.suffix.lower() in JSON_SUFFIXES: raw_points = _read_jsonl_points(path, distinguish_dirty=True) else: _require_pyarrow("reading a Parquet store") diff --git a/src/benchx/views/site.py b/src/benchx/views/site.py index 50bba3e..f5d108c 100644 --- a/src/benchx/views/site.py +++ b/src/benchx/views/site.py @@ -5,15 +5,14 @@ import errno import functools import http.server -import importlib.util import json import re import shutil -import sys import webbrowser from pathlib import Path from urllib.parse import quote +from .._pyarrow import has_pyarrow from . import inputs, payloads from . import marts as marts_mod @@ -34,15 +33,6 @@ ) -def _has_pyarrow() -> bool: - if "pyarrow" in sys.modules: - return sys.modules["pyarrow"] is not None - try: - return importlib.util.find_spec("pyarrow") is not None - except (ValueError, ModuleNotFoundError): - return False - - def _github_commit_url(source_uri: str | None) -> str | None: if not source_uri: return None @@ -148,7 +138,7 @@ def build_site( # Validate project metadata and optional PyArrow requirements before touching `out`. project = resolve_project(project_file=project_file, title=title, config=config) if write_marts is None: - emit_marts = _has_pyarrow() + emit_marts = has_pyarrow() else: emit_marts = bool(write_marts) if emit_marts: diff --git a/tests/test_logging_silent.py b/tests/test_logging_silent.py index f5e8039..238a2cb 100644 --- a/tests/test_logging_silent.py +++ b/tests/test_logging_silent.py @@ -239,7 +239,7 @@ def test_the_store_says_what_it_swept_what_it_refused_and_what_it_read(session, store_path = config.load(tmp).store_path with caplog.at_level(logging.DEBUG, logger="benchx"): Store(store_path).documents("S") - read_needle = " row(s), provenance, document" if HAS_PYARROW else " row(s)" + read_needle = " row(s), provenance.run_key, document" if HAS_PYARROW else " row(s)" assert any("read " in m and read_needle in m for _, m in records(caplog)) assert any(m.startswith("documents(S): ") for _, m in records(caplog)) absent_path = tmp / ("absent.parquet" if HAS_PYARROW else "absent.jsonl") diff --git a/tests/test_parquet.py b/tests/test_parquet.py index 7ee75c8..ca344ac 100644 --- a/tests/test_parquet.py +++ b/tests/test_parquet.py @@ -4,7 +4,8 @@ import importlib.util import json import re -from datetime import datetime +import sys +from datetime import UTC, datetime from pathlib import Path import pytest @@ -13,9 +14,11 @@ pa = pytest.importorskip("pyarrow") import pyarrow.parquet as pq -from benchx import parquet +from benchx import _pyarrow, core, parquet +from benchx import store as store_mod from benchx.core import loader from benchx.core.catalog import SCHEMAS +from benchx.results import ingest_documents EXAMPLES = sorted((SCHEMAS / "measurement-result" / "0.1.0" / "examples").glob("*.json")) # The tool lives in the checkout, not the package, so an installed copy skips its tests. @@ -166,6 +169,13 @@ def closed(json_type): [ {"const": True}, {"enum": ["a", 1]}, + {"enum": []}, + {}, + {"type": "null"}, + {"type": "array"}, + {"$ref": "https://example.com/external.json"}, + {"$ref": "#/$defs/missing"}, + {"anyOf": [{"type": "string"}, {"type": "integer"}]}, {"oneOf": [{"type": "string"}, {"type": "integer"}]}, {"oneOf": [closed("string"), closed("integer")]}, {"oneOf": [closed("string"), {"type": "object", "properties": {"y": {"type": "string"}}}]}, # open @@ -173,12 +183,229 @@ def closed(json_type): {"oneOf": [{"type": "string"}, closed("string")]}, # a bare value that is not a number {"oneOf": [{"type": "number"}, closed("number")]}, # no `value` to hold the bare number {"oneOf": [{"type": "number"}, closed("number"), closed("number")]}, + { + "oneOf": [ + {"type": "number"}, + { + "type": "object", + "additionalProperties": False, + "required": ["value", "other"], + "properties": {"value": {"type": "number"}, "other": {"type": "string"}}, + }, + ] + }, + {"allOf": []}, {"allOf": [{"minLength": 1}, closed("string")]}, # no leading reference + {"allOf": [{"$ref": "#/$defs/x"}, {"properties": {"extra": {"type": "string"}}}]}, ], ) def test_unsupported_nodes_fail(node): with pytest.raises(ValueError): - parquet.arrow_type(node, {}, pa.json_()) + parquet.arrow_type(node, {"x": {"type": "string"}}) + + +def test_chained_and_cyclic_refs(): + defs = { + "a": {"$ref": "#/$defs/b"}, + "b": {"type": "string"}, + "cycle_a": {"$ref": "#/$defs/cycle_b"}, + "cycle_b": {"$ref": "#/$defs/cycle_a"}, + } + assert parquet.arrow_type({"$ref": "#/$defs/a"}, defs) == pa.string() + with pytest.raises(ValueError, match="cyclic"): + parquet.arrow_type({"$ref": "#/$defs/cycle_a"}, defs) + + +def test_empty_message_table(): + empty = parquet.message_table([]) + assert empty.num_rows == 0 + assert empty.schema == parquet.MESSAGE_SCHEMA + + +def test_results_table_and_mismatched_lengths(messages): + documents = [(path.name, path.read_text(encoding="utf-8")) for path in EXAMPLES] + accepted, derived, outcome = ingest_documents(documents) + assert outcome["rejected"] == [] + tbl = parquet.results_table(accepted, derived) + assert tbl.schema == parquet.RESULTS_SCHEMA + assert tbl.num_rows == len(messages) + with pytest.raises(ValueError): + parquet.results_table(accepted, derived[:-1]) + + +def test_sub_microsecond_timestamp_truncation(messages): + doc = json.loads(json.dumps(messages[0])) + doc["provenance"]["started_at"] = "2026-07-18T09:12:44.123456789Z" + assert core.check(doc, "measurement-result") == [] + tbl = parquet.message_table([doc]) + assert tbl.column("provenance").to_pylist()[0]["started_at"] == datetime(2026, 7, 18, 9, 12, 44, 123456, tzinfo=UTC) + + +def test_all_optional_schema_branches(messages): + base = json.loads(json.dumps(messages[0])) + censored = json.loads(json.dumps(base)) + censored["ingest_key"] += ":censored" + censored["measurement"] = { + "quantity": {"name": "wall-time", "unit": "s"}, + "status": "censored", + "reason": "timeout", + "constraint": { + "kind": "interval", + "lower": 0.0, + "upper": 10.0, + "lower_inclusive": True, + "upper_inclusive": False, + "cause": "wall-clock-limit", + }, + } + + rich = json.loads(json.dumps(base)) + rich["ingest_key"] += ":rich" + rich["coordinates"]["environment"]["system"] = {"os": None, "kernel": "6.8"} + rich["measurement"] = { + "quantity": {"name": "overhead-ratio", "unit": "1"}, + "status": "success", + "observations": [ + { + "value": 1.25, + "ordinal": 0, + "slot": 0, + "time": "2026-07-18T09:12:44.123456789Z", + "group": "g1", + "pair": "p1", + "included": True, + "exclusion_reason": "none", + } + ], + "derivation": { + "name": "ratio", + "method_version": "benchx/ratio/v1", + "input_level": "observations", + "inputs": [ + {"role": "numerator", "quantity": "wall-time"}, + {"role": "denominator", "quantity": "wall-time"}, + ], + }, + "summaries": [ + { + "type": "source_bounds", + "statistic": "mean", + "label": "range", + "lower": 1.0, + "upper": 2.0, + "source": "producer", + }, + { + "type": "standard_uncertainty", + "statistic": "mean", + "value": 0.1, + "method": "bootstrap", + "source": "producer", + }, + { + "type": "expanded_uncertainty", + "statistic": "mean", + "value": 0.2, + "coverage_factor": 2.0, + "level": 0.95, + "method": "normal", + "source": "producer", + }, + ], + } + rich["provenance"]["references"] = [ + {"role": "numerator", "result": {"producer": base["producer"]["name"], "ingest_key": base["ingest_key"]}} + ] + rich["quality"] = {"warnings": ["sample-warning"], "validation": {"correctness": "pass"}} + + for doc in (censored, rich): + assert core.check(doc, "measurement-result") == [] + + tbl = parquet.message_table([censored, rich]) + row_type = pa.struct(list(tbl.schema)) + for doc, row in zip([censored, rich], tbl.to_pylist()): + assert _stored(row_type, row) == _reported(row_type, doc) + + +def test_to_row_rejects_bare_scalar_for_non_observation_struct(messages): + no_value_struct = pa.struct([pa.field("name", pa.string(), False)]) + bare_value_struct = pa.struct([pa.field("value", pa.float64(), False)]) + obs_struct = parquet.MESSAGE_SCHEMA.field("measurement").type.field("observations").type.value_type + assert parquet.to_row(pa.string(), "ok") == "ok" + assert parquet.to_row(bare_value_struct, None) is None + assert parquet.to_row(bare_value_struct, 2.5) == {"value": 2.5} + assert parquet.to_row(bare_value_struct, {"value": 2.5}) == {"value": 2.5} + assert parquet.to_row(parquet._FINAL, messages[0]) == parquet._to_message_row(messages[0]) + assert parquet.arrow_type({"type": ["string", "number", "null"]}, {}) == parquet.JSON_TYPE + with pytest.raises(TypeError): + parquet.to_row(no_value_struct, 1.5) + with pytest.raises(TypeError): + parquet.to_row(obs_struct, True) + with pytest.raises(TypeError): + parquet.to_row(bare_value_struct, True) + + +def test_pyarrow_helper_edge_cases(monkeypatch): + monkeypatch.delitem(sys.modules, "pyarrow", raising=False) + monkeypatch.setattr(_pyarrow.importlib.util, "find_spec", lambda name: object()) + assert _pyarrow.has_pyarrow() is True + monkeypatch.setattr( + _pyarrow.importlib.util, "find_spec", lambda name: (_ for _ in ()).throw(ValueError("bad spec")) + ) + assert _pyarrow.has_pyarrow() is False + + real_import = __import__ + + def fail_other(name, *args, **kwargs): + if name == "pyarrow": + raise ModuleNotFoundError("No module named 'other_dep'", name="other_dep") + return real_import(name, *args, **kwargs) + + monkeypatch.setattr("builtins.__import__", fail_other) + with pytest.raises(ModuleNotFoundError, match="other_dep"): + _pyarrow.require_pyarrow("test") + + +def test_store_fields_walks_list_of_struct(): + fields = store_mod._fields(parquet.RESULTS_SCHEMA, pa) + assert fields["measurement.observations[].value"] == "double" + assert fields["provenance.artifacts[].uri"] == "string" + + +def test_store_atomic_write_cleans_up_tmp_on_error(tmp_path, monkeypatch, caplog): + store_path = tmp_path / "store.parquet" + store = store_mod.Store(store_path) + docs = [(EXAMPLES[0].name, EXAMPLES[0].read_text(encoding="utf-8"))] + store.ingest(docs) + + monkeypatch.setattr( + store._pq, + "write_table", + lambda *a, **k: (_ for _ in ()).throw(pa.ArrowInvalid("bad column")), + ) + with pytest.raises(pa.ArrowInvalid): + store._write_parquet(parquet.results_table(*ingest_documents(docs)[:2])) + assert not list(tmp_path.glob(".*.tmp")) + + monkeypatch.setattr( + store._pq, + "write_table", + lambda *a, **k: (_ for _ in ()).throw(OSError(28, "No space left")), + ) + with pytest.raises(OSError): + store._write_parquet(parquet.results_table(*ingest_documents(docs)[:2])) + assert not list(tmp_path.glob(".*.tmp")) + + # Appending to a table with a different schema_uri or a removed field logs a warning. + monkeypatch.undo() + old = pq.read_table(store_path) + altered_meta = {**(old.schema.metadata or {}), b"benchx.schema_uri": b"urn:benchx:schema:measurement-result:0.0.1"} + with_legacy = old.replace_schema_metadata(altered_meta).append_column("legacy", pa.array(["x"])) + pq.write_table(with_legacy, store_path) + with caplog.at_level("WARNING", logger="benchx.store"): + store._write_parquet(parquet.results_table(*ingest_documents(docs)[:2])) + assert any("appending schema" in r.message for r in caplog.records) + assert any("absent from the current schema" in r.message and "legacy" in r.message for r in caplog.records) @pytest.fixture diff --git a/tools/json_to_parquet.py b/tools/json_to_parquet.py index 8657990..d3d927e 100644 --- a/tools/json_to_parquet.py +++ b/tools/json_to_parquet.py @@ -6,21 +6,23 @@ from the shipped result schema, so this program cannot drift from it. See docs/design/measurement-result-parquet.md. Run it from a checkout: - pip install -e . + pip install -e '.[parquet]' python tools/json_to_parquet.py results.parquet \ src/benchx/schemas/measurement-result/0.1.0/examples/*.json """ +import os import sys +import tempfile from pathlib import Path -import pyarrow.parquet as pq - from benchx import core, parquet +from benchx._pyarrow import require_pyarrow def main(output, *paths): """Write the documents at `paths` to `output`; nothing is written if one is invalid.""" + _, pq = require_pyarrow("json_to_parquet") documents, failed = [], False for path in paths: inspection = core.inspect(Path(path), "measurement-result") @@ -30,7 +32,22 @@ def main(output, *paths): documents.append(inspection.data) if failed: return 1 - pq.write_table(parquet.message_table(documents), output, compression="zstd") + out = Path(output) + out.parent.mkdir(parents=True, exist_ok=True) + tmp: Path | None = None + try: + with tempfile.NamedTemporaryFile( + mode="wb", dir=out.parent, prefix=f".{out.name}.", suffix=".tmp", delete=False + ) as f: + tmp = Path(f.name) + pq.write_table(parquet.message_table(documents), f, compression="zstd") + f.flush() + os.fsync(f.fileno()) + os.replace(tmp, out) + except BaseException: + if tmp is not None: + tmp.unlink(missing_ok=True) + raise return 0