Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 1 addition & 1 deletion docs/design/measurement-result-parquet.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```
Expand Down
40 changes: 40 additions & 0 deletions src/benchx/_pyarrow.py
Original file line number Diff line number Diff line change
@@ -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
5 changes: 3 additions & 2 deletions src/benchx/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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; "
Expand Down Expand Up @@ -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"
Expand Down
12 changes: 2 additions & 10 deletions src/benchx/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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
Expand All @@ -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):
Expand Down
13 changes: 9 additions & 4 deletions src/benchx/core/catalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
174 changes: 120 additions & 54 deletions src/benchx/parquet.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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()])
Expand All @@ -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.
Expand All @@ -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 = {
Expand All @@ -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)
Loading
Loading