diff --git a/AGENTS.md b/AGENTS.md
index 578e9995..fcebe89a 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -218,7 +218,7 @@ Contains the test cases.
```
### 4. BigQuery Reporting (Centralized Metrics)
-To upload metrics directly to Google BigQuery and create Looker Studio dashboard links, configure the `bigquery` key in your `reporting` section:
+To upload metrics directly to Google BigQuery (via streaming inserts, `tabledata.insertAll`, into `configs`, `results`, `scores`, `summary`, and `run_stats`) and create Looker Studio dashboard links, configure the `bigquery` key in your `reporting` section (see [run-config.md](docs/configs/run-config.md#5-reporting-configurations) for batching, truncation, and retry details):
```yaml
reporting:
@@ -226,6 +226,7 @@ reporting:
gcp_project_id: 'your-gcp-project-id'
dataset_id: 'evalbench' # Optional, defaults to 'evalbench'
dataset_location: 'US' # Optional, defaults to 'US'
+ chunk_size: 500 # Optional, max rows per streaming batch
```
---
diff --git a/docs/configs/run-config.md b/docs/configs/run-config.md
index ebfdc140..3971f35e 100644
--- a/docs/configs/run-config.md
+++ b/docs/configs/run-config.md
@@ -150,11 +150,18 @@ The `reporting` section specifies how and where the evaluation results will be r
| ---------- | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `truncate_execution_outputs`| Optional (defaults to 250 rows) | This allows overriding the truncation of outputs in reporting (CSVs, BQ) to the number of rows specified. This affects the following reporting fields: `generated_result`, `golden_result`, `golden_eval_results` `eval_results`. This prevents logging incredibly large results with potentially thousands or millions of rows. *NOTE: This does not affect any logic other than reporting.* |
| `csv` | Optional | Configuration for CSV reporting.
**Subkey:** `output_directory` specifies the directory where CSV results will be saved (e.g., `'results'`). |
-| `bigquery` | Optional | Configuration for reporting to Google BigQuery.
**Subkeys:** `gcp_project_id` specifies the Google Cloud Project ID for BigQuery integration (e.g., `my_cool_gcp_project`). `dataset_id` overrides the BigQuery dataset that results are written to (`.`), defaulting to `evalbench`. |
+| `bigquery` | Optional | Configuration for reporting to Google BigQuery via streaming inserts (`tabledata.insertAll`).
**Subkeys:** `gcp_project_id` specifies the Google Cloud Project ID for BigQuery integration (e.g., `my_cool_gcp_project`). `dataset_id` overrides the BigQuery dataset (`.`), defaulting to `evalbench`. `dataset_location` sets the dataset region, defaulting to `US`. `chunk_size` sets the maximum rows per streaming batch, defaulting to `500`. |
---
> bigquery project_id: You can globally set your GCP project_id using the environment variables `EVAL_GCP_PROJECT_ID` or identify it separately.
+### BigQuery streaming notes
+
+- **Tables and quota:** `bigquery` appends rows to `configs`, `results`, `scores`, `summary`, and (for multi-trial agent runs) `run_stats` using streaming inserts (`tabledata.insertAll`) rather than batch load jobs, avoiding BigQuery's 1,500 load-jobs-per-table daily limit. Note that streaming inserts are billed per GB ingested and require `bigquery.tables.updateData` (plus `bigquery.datasets.create`, `bigquery.tables.create`, and `bigquery.tables.update` when auto-creating or evolving tables).
+- **Schema evolution and retries:** Missing tables are created automatically and new top-level columns are appended via `update_table`. Transient transport errors retry with a 30 s per-request timeout and 120 s deadline (excluding `SSLError`), and post-DDL streaming cache lag (`404 NotFound` or verified `no such field`) retries up to 120 s using stable per-row `insertId` values for best-effort deduplication. Missing fields absent from the server schema (such as unknown nested `RECORD` subfields) fail immediately.
+- **Batching and oversized rows:** Batches are capped at both `chunk_size` rows and 8 MiB serialized payload (below BigQuery's 10 MB `insertAll` limit). If a single row exceeds 8 MiB, its largest non-repeated `STRING` columns are truncated with `... [truncated for BigQuery streaming size limit]` and a warning. If a row still exceeds 8 MiB (for example, an oversized `JSON`, `RECORD`, or `REPEATED` column), all other valid rows are still streamed and `store()` then raises `RuntimeError` listing the skipped rows.
+- **Numeric columns in `summary` and `scores`:** To match historical schemas, `metric_score`, `totalLatencyMs`, `total_results_count`, and `correct_results_count` round fractional floats to `INTEGER`; multi-trial suite stats (`pass_rate`, `interval_low`, `interval_high`, `flakiness`, `confidence`, `flaky_scenarios`, `trial_min`, `trial_median`, `trial_max`) stay numeric; other non-repeated float columns are inferred as `STRING`. Exact whole floats (from nullable pandas integer columns widened to `float64`) convert losslessly to `INTEGER`; fractional floats in other `INTEGER` columns are not rounded.
+
## Example Configuration Snippet
Below is an example snippet of how this configuration file might appear:
diff --git a/evalbench/reporting/bqstore.py b/evalbench/reporting/bqstore.py
index 8f6f1cc3..00db7ee5 100644
--- a/evalbench/reporting/bqstore.py
+++ b/evalbench/reporting/bqstore.py
@@ -1,13 +1,24 @@
-from google.cloud import bigquery
-from google.api_core.exceptions import TooManyRequests, ServiceUnavailable
+from collections.abc import Iterator, Sequence
+import json
import logging
import re
+import time
+from typing import Any
+import urllib.parse
+import uuid
+
+from google.api_core.exceptions import (
+ Conflict,
+ NotFound,
+ PreconditionFailed,
+)
+from google.cloud import bigquery
+from google.cloud.bigquery import retry as bq_retry
import pandas as pd
from reporting.report import Reporter, STORETYPE
from reporting.runstats import _SUITE_COLUMNS
+import requests
from util.gcp import get_gcp_project
-import urllib.parse
-import time
try:
import google.colab # type: ignore
@@ -18,6 +29,58 @@
_IN_COLAB = False
_DEFAULT_CHUNK_SIZE = 500
+# BigQuery tabledata.insertAll caps each HTTP request at 10 MB; flush below 8 MiB
+# so large multi-turn conversation_history rows stay well below the wire cap.
+_MAX_STREAMING_REQUEST_BYTES = 8 * 1024 * 1024
+# Per-row insertAll JSON wrapper: {"json": , "insertId": ""},
+_INSERT_ROW_WRAPPER_OVERHEAD_BYTES = 64
+_TRUNCATION_SUFFIX = "... [truncated for BigQuery streaming size limit]"
+_MAX_SCHEMA_UPDATE_RETRIES = 5
+# Per-attempt HTTP request timeout passed to insert_rows_json() so stalled
+# sockets time out into retry instead of hanging indefinitely.
+_STREAMING_REQUEST_TIMEOUT_SECONDS = 30.0
+
+
+def _should_retry_streaming_transport(exc: Exception) -> bool:
+ """Delegates to BigQuery's retry predicate while never retrying SSLError.
+
+ Older google-cloud-bigquery releases (including 3.40.1) match SSLError via
+ its requests.exceptions.ConnectionError base class, even though
+ insert_rows_json treats SSLError as a non-retryable request failure.
+ """
+ if isinstance(exc, requests.exceptions.SSLError):
+ return False
+ return bq_retry.DEFAULT_RETRY._predicate(exc)
+
+
+# Delegate HTTP/transport retries to google-cloud-bigquery's built-in retry
+# policy (covers rateLimitExceeded including 403, backendError, internalError,
+# badGateway, 429/500/502/503, requests/TransportError, excluding SSLError),
+# bounded to 120s so outer schema-lag retries never stack multiple 600s waits.
+_STREAMING_TRANSPORT_RETRY = bq_retry.DEFAULT_RETRY.with_predicate(
+ _should_retry_streaming_transport
+).with_deadline(120.0)
+# BigQuery insertAll metadata cache can lag after create_table or update_table;
+# total backoff budget is 120s (2 + 4 + 8 + 16 + 30 + 30 + 30).
+_STREAMING_RETRY_DELAYS = (2, 4, 8, 16, 30, 30, 30)
+_NO_SUCH_FIELD_RE = re.compile(r"no such field:\s*([^\s,;:]+)", re.IGNORECASE)
+_ARRAY_INDEX_RE = re.compile(r"\[\d+\]")
+_SUMMARY_AND_SCORES_INT_COLS = frozenset({
+ "metric_score",
+ "totalLatencyMs",
+ "total_results_count",
+ "correct_results_count",
+})
+_SUMMARY_AND_SCORES_INT_COLS_LOWER = frozenset(
+ col.lower() for col in _SUMMARY_AND_SCORES_INT_COLS
+)
+_SUITE_COLUMNS_LOWER = frozenset(col.lower() for col in _SUITE_COLUMNS)
+_TRANSIENT_ROW_ERROR_REASONS = frozenset({
+ "backendError",
+ "internalError",
+ "rateLimitExceeded",
+ "timeout",
+})
_REPORT_QUERY = """
WITH all_runs_with_set_tag AS (
@@ -74,24 +137,438 @@ def _column_name(name) -> str:
return f"_{name}" if name[:1].isdigit() else name
-def _split_dataframe(df, chunk_size):
- """Splits a pandas DataFrame into chunks of a specified size.
-
- Args:
- df: The DataFrame to split.
- chunk_size: The desired size of each chunk.
-
- Yields:
- A generator that yields each chunk of the DataFrame.
- """
+def _split_dataframe(df: pd.DataFrame, chunk_size: int) -> Iterator[pd.DataFrame]:
+ """Splits a pandas DataFrame into chunks of a specified size."""
num_chunks = len(df) // chunk_size + (len(df) % chunk_size > 0)
for i in range(num_chunks):
start = i * chunk_size
- # Py/Pandas slicing handles not going out of bound
end = (i + 1) * chunk_size
yield df[start:end]
+def _infer_schema(
+ df: pd.DataFrame, store_type: STORETYPE | None = None
+) -> list[bigquery.SchemaField]:
+ """Infers BigQuery SchemaFields via pandas-gbq with EvalBench overrides."""
+ # Lazy import so importing reporting.bqstore (via reporting/__init__.py on
+ # every startup) does not load pandas-gbq unless creating a table or adding
+ # columns. google-cloud-bigquery itself delegates to this helper in place
+ # of its deprecated _pandas_helpers.dataframe_to_bq_schema.
+ from pandas_gbq.schema.pandas_to_bigquery import (
+ dataframe_to_bigquery_fields,
+ )
+
+ overrides: list[bigquery.SchemaField] = []
+ if store_type in (STORETYPE.SUMMARY, STORETYPE.SCORES):
+ overrides = [
+ bigquery.SchemaField(str(col), "INTEGER")
+ for col in df.columns
+ if str(col).lower() in _SUMMARY_AND_SCORES_INT_COLS_LOWER
+ ]
+
+ fields = list(
+ dataframe_to_bigquery_fields(
+ df, override_bigquery_fields=overrides or None, index=False
+ )
+ )
+ if store_type in (STORETYPE.SUMMARY, STORETYPE.SCORES):
+ # Preserve legacy bqstore behavior: non-int float columns in SUMMARY /
+ # SCORES are stored as STRING to avoid int/float schema lock conflicts.
+ # Multi-trial suite stats stay floats so BigQuery SQL can aggregate them.
+ fields = [
+ bigquery.SchemaField(f.name, "STRING")
+ if (
+ f.mode != "REPEATED"
+ and f.field_type.upper() in ("FLOAT", "FLOAT64")
+ and f.name.lower() not in _SUITE_COLUMNS_LOWER
+ )
+ else f
+ for f in fields
+ ]
+ return fields
+
+
+def _coerce_json_value(
+ val: Any,
+ field: bigquery.SchemaField | None,
+ *,
+ round_float_to_int: bool = False,
+) -> Any:
+ """Normalizes a pandas.to_json() value for BigQuery tabledata.insertAll."""
+ if val is None:
+ return None
+ if field is not None and field.mode == "REPEATED":
+ items = val if isinstance(val, list) else [val]
+ elem_field = bigquery.SchemaField(
+ field.name, field.field_type, mode="NULLABLE", fields=field.fields
+ )
+ return [
+ v for e in items
+ if (v := _coerce_json_value(e, elem_field)) is not None
+ ]
+
+ ftype = field.field_type.upper() if field is not None else "STRING"
+ if ftype == "STRING":
+ if isinstance(val, str):
+ return val
+ if isinstance(val, float):
+ return str(int(val)) if val.is_integer() else str(val)
+ return (
+ json.dumps(val, allow_nan=False)
+ if isinstance(val, (dict, list))
+ else str(val)
+ )
+
+ # Empty strings in dtype="string" DataFrames represent NULL for non-STRING columns.
+ if isinstance(val, str) and not val.strip():
+ return None
+ if ftype in ("INTEGER", "INT64") and isinstance(val, float):
+ # Nullable pandas int columns widen to float64 (e.g. 1.0); convert exact
+ # whole floats losslessly, and only round non-integral floats on the
+ # legacy SUMMARY/SCORES integer columns.
+ if val.is_integer():
+ return int(val)
+ if round_float_to_int:
+ return int(round(val))
+ return val
+ if ftype == "DATETIME":
+ try:
+ ts = pd.Timestamp(val)
+ except (TypeError, ValueError):
+ return val
+ if pd.isna(ts):
+ return None
+ if ts.tzinfo is not None:
+ ts = ts.tz_convert("UTC").tz_localize(None)
+ return ts.isoformat(timespec="microseconds")
+ if ftype == "DATE" and isinstance(val, str) and "T" in val:
+ return val.split("T", 1)[0]
+ if ftype == "JSON" and not isinstance(val, str):
+ return json.dumps(val, allow_nan=False)
+ return val
+
+
+def _dataframe_to_json_rows(
+ chunk: pd.DataFrame,
+ schema: Sequence[bigquery.SchemaField],
+ store_type: STORETYPE | None = None,
+) -> list[dict[str, Any]]:
+ """Converts a DataFrame chunk to BigQuery insertAll JSON dicts via pandas.to_json()."""
+ schema_by_lower = {field.name.lower(): field for field in schema}
+ round_int_cols = (
+ _SUMMARY_AND_SCORES_INT_COLS_LOWER
+ if store_type in (STORETYPE.SUMMARY, STORETYPE.SCORES)
+ else frozenset()
+ )
+ # pandas.to_json() handles NumPy scalars, NaN/Inf/pd.NA/pd.NaT -> null
+ # (including inside nested dicts/lists), exact 64-bit ints, and ISO dates.
+ raw_rows = json.loads(
+ chunk.to_json(
+ orient="records",
+ date_format="iso",
+ date_unit="us",
+ default_handler=str,
+ )
+ )
+ rows: list[dict[str, Any]] = []
+ for record in raw_rows:
+ row: dict[str, Any] = {}
+ for col, val in record.items():
+ field = schema_by_lower.get(str(col).lower())
+ target_col = field.name if field is not None else str(col)
+ should_round = (
+ field is not None
+ and field.mode != "REPEATED"
+ and field.name.lower() in round_int_cols
+ )
+ coerced = _coerce_json_value(
+ val, field, round_float_to_int=should_round
+ )
+ if coerced is not None:
+ row[target_col] = coerced
+ rows.append(row)
+ return rows
+
+
+def _serialized_row_bytes(row: dict[str, Any]) -> int:
+ """Returns approximate wire size of a row including insertAll wrapper."""
+ return (
+ len(json.dumps(row, allow_nan=False).encode("utf-8"))
+ + _INSERT_ROW_WRAPPER_OVERHEAD_BYTES
+ )
+
+
+def _string_column_names(
+ schema: Sequence[bigquery.SchemaField],
+) -> frozenset[str]:
+ """Returns non-repeated STRING column names safe to truncate on oversize."""
+ return frozenset(
+ f.name
+ for f in schema
+ if f.mode != "REPEATED" and f.field_type.upper() == "STRING"
+ )
+
+
+def _truncate_str_to_json_bytes(
+ val: str, target_json_bytes: int
+) -> str | None:
+ """Truncates `val` with a marker so its JSON size fits `target_json_bytes`."""
+ suffix = _TRUNCATION_SUFFIX
+ min_bytes = len(json.dumps(suffix, allow_nan=False).encode("utf-8"))
+ if target_json_bytes < min_bytes:
+ return None
+ cur_bytes = len(json.dumps(val, allow_nan=False).encode("utf-8"))
+ if cur_bytes <= min_bytes:
+ return None
+ budget = max(0, target_json_bytes - min_bytes)
+ cut = min(len(val), int(len(val) * (budget / cur_bytes)))
+ while cut > 0:
+ candidate = val[:cut] + suffix
+ cand_bytes = len(json.dumps(candidate, allow_nan=False).encode("utf-8"))
+ if cand_bytes <= target_json_bytes:
+ return candidate
+ overflow = cand_bytes - target_json_bytes
+ step = max(1, int(overflow * (cut / max(1, cand_bytes - min_bytes))) + 1)
+ cut = max(0, cut - step)
+ return suffix
+
+
+def _fit_row_to_limit(
+ row: dict[str, Any],
+ string_cols: frozenset[str],
+ max_bytes: int,
+ table: str,
+) -> dict[str, Any] | None:
+ """Fits a single row within `max_bytes` by truncating STRING columns.
+
+ Returns the original row if already within budget, a copy with the largest
+ non-repeated STRING columns truncated if needed, or None if the row still
+ exceeds `max_bytes` (e.g. an oversized JSON/RECORD/REPEATED field).
+ """
+ original_bytes = _serialized_row_bytes(row)
+ if original_bytes <= max_bytes:
+ return row
+
+ truncated = dict(row)
+ truncated_cols: list[str] = []
+ unshrinkable: set[str] = set()
+ current_bytes = original_bytes
+ suffix_bytes = len(
+ json.dumps(_TRUNCATION_SUFFIX, allow_nan=False).encode("utf-8")
+ )
+
+ while current_bytes > max_bytes:
+ candidates = [
+ (
+ len(json.dumps(val, allow_nan=False).encode("utf-8")),
+ col,
+ val,
+ )
+ for col, val in truncated.items()
+ if col in string_cols
+ and col not in unshrinkable
+ and isinstance(val, str)
+ ]
+ if not candidates:
+ break
+ val_bytes, col, val = max(candidates)
+ target = max(suffix_bytes, val_bytes - (current_bytes - max_bytes))
+ shrunk = _truncate_str_to_json_bytes(val, target)
+ unshrinkable.add(col)
+ if shrunk is None or shrunk == val:
+ continue
+ truncated[col] = shrunk
+ truncated_cols.append(col)
+ current_bytes = _serialized_row_bytes(truncated)
+
+ row_ident = (
+ row.get("id")
+ or row.get("eval_id")
+ or row.get("scenario_id")
+ or row.get("job_id")
+ )
+ if current_bytes > max_bytes:
+ logging.error(
+ "Skipping oversized BigQuery streaming row for %s "
+ "(id=%s, bytes=%d, limit=%d) after truncating STRING columns %s.",
+ table,
+ row_ident,
+ current_bytes,
+ max_bytes,
+ truncated_cols,
+ )
+ return None
+
+ logging.warning(
+ "Truncated oversized BigQuery streaming row for %s "
+ "(id=%s, original_bytes=%d, truncated_bytes=%d, limit=%d, columns=%s).",
+ table,
+ row_ident,
+ original_bytes,
+ current_bytes,
+ max_bytes,
+ truncated_cols,
+ )
+ return truncated
+
+
+def _fit_rows_with_positions(
+ positions: Sequence[int],
+ rows: Sequence[dict[str, Any]],
+ schema: Sequence[bigquery.SchemaField],
+ max_bytes: int,
+ table: str,
+ row_ids: Sequence[str] | None = None,
+ skipped_rows: list[str] | None = None,
+) -> tuple[list[int], list[dict[str, Any]], list[str]]:
+ """Applies `_fit_row_to_limit` while keeping positions and row_ids aligned."""
+ string_cols = _string_column_names(schema)
+ kept_positions: list[int] = []
+ kept_rows: list[dict[str, Any]] = []
+ kept_row_ids: list[str] = []
+ for idx, (pos, row) in enumerate(zip(positions, rows)):
+ fitted = _fit_row_to_limit(row, string_cols, max_bytes, table)
+ if fitted is None:
+ if skipped_rows is not None:
+ row_ident = (
+ row.get("id")
+ or row.get("eval_id")
+ or row.get("scenario_id")
+ or row.get("job_id")
+ or f"pos={pos}"
+ )
+ skipped_rows.append(
+ f"{row_ident} ({_serialized_row_bytes(row)} bytes)"
+ )
+ continue
+ kept_positions.append(pos)
+ kept_rows.append(fitted)
+ if row_ids is not None:
+ kept_row_ids.append(row_ids[idx])
+ return kept_positions, kept_rows, kept_row_ids
+
+
+def _iter_streaming_batches(
+ rows: Sequence[dict[str, Any]],
+ max_rows: int,
+ max_bytes: int | None = None,
+) -> Iterator[list[dict[str, Any]]]:
+ """Splits JSON rows by both count and serialized byte size for insertAll."""
+ if max_bytes is None:
+ max_bytes = _MAX_STREAMING_REQUEST_BYTES
+ batch: list[dict[str, Any]] = []
+ batch_bytes = 0
+ for row in rows:
+ row_bytes = _serialized_row_bytes(row)
+ if batch and (
+ len(batch) >= max_rows or batch_bytes + row_bytes > max_bytes
+ ):
+ yield batch
+ batch = []
+ batch_bytes = 0
+ batch.append(row)
+ batch_bytes += row_bytes
+ if batch:
+ yield batch
+
+
+def _extract_missing_field_paths(
+ errors: Sequence[dict[str, Any]],
+) -> list[str | None]:
+ """Extracts field paths from 'no such field' insertAll row errors."""
+ paths: list[str | None] = []
+ for row_err in errors:
+ for err in row_err.get("errors") or []:
+ message = str(err.get("message") or "")
+ if "no such field" not in message.lower():
+ continue
+ match = _NO_SUCH_FIELD_RE.search(message)
+ msg_path = (
+ _ARRAY_INDEX_RE.sub("", match.group(1)).strip("`\"'").rstrip(".")
+ if match
+ else ""
+ )
+ loc_raw = str(err.get("location") or "").strip()
+ loc_path = (
+ _ARRAY_INDEX_RE.sub("", loc_raw).strip("`\"'").rstrip(".")
+ if loc_raw
+ else ""
+ )
+ if loc_path and (
+ not msg_path
+ or loc_path.lower() == msg_path.lower()
+ or loc_path.lower().endswith("." + msg_path.lower())
+ ):
+ paths.append(loc_path)
+ elif msg_path:
+ paths.append(msg_path)
+ else:
+ paths.append(None)
+ return paths
+
+
+def _schema_contains_field_path(
+ schema: Sequence[bigquery.SchemaField], field_path: str
+) -> bool:
+ """Returns True when a dot-separated field path exists in `schema`."""
+ parts = [part.lower() for part in field_path.split(".") if part]
+ if not parts:
+ return False
+ current_fields = schema
+ for part in parts:
+ match = next(
+ (f for f in current_fields if f.name.lower() == part), None
+ )
+ if match is None:
+ return False
+ current_fields = match.fields
+ return True
+
+
+def _has_schema_lag_error(errors: Sequence[dict[str, Any]]) -> bool:
+ """Returns True when any insert_rows_json row error reports 'no such field'."""
+ return bool(_extract_missing_field_paths(errors))
+
+
+def _all_missing_fields_in_schema(
+ errors: Sequence[dict[str, Any]], schema: Sequence[bigquery.SchemaField]
+) -> bool:
+ """Returns True only if every 'no such field' path exists in `schema`."""
+ paths = _extract_missing_field_paths(errors)
+ return bool(paths) and all(
+ path is not None and _schema_contains_field_path(schema, path)
+ for path in paths
+ )
+
+
+def _is_transient_insert_error(errors: Sequence[dict[str, Any]]) -> bool:
+ """Returns True when insert_rows_json row errors are transient or schema-lag."""
+ if not errors:
+ return False
+ saw_retryable = False
+ for row_err in errors:
+ item_errors = row_err.get("errors") or []
+ if not item_errors:
+ return False
+ for err in item_errors:
+ reason = str(err.get("reason") or "")
+ message = str(err.get("message") or "").lower()
+ if reason == "stopped":
+ # BigQuery aborts sibling rows with reason="stopped" whenever
+ # skip_invalid_rows=False and another row in the batch fails.
+ continue
+ if reason in _TRANSIENT_ROW_ERROR_REASONS:
+ saw_retryable = True
+ continue
+ # tabledata.insertAll caches schemas briefly after create_table or
+ # update_table and can report "no such field" for a few seconds.
+ if "no such field" in message:
+ saw_retryable = True
+ continue
+ return False
+ return saw_retryable
+
+
class BigQueryReporter(Reporter):
def __init__(self, reporting_config, job_id, run_time):
super().__init__(reporting_config, job_id, run_time)
@@ -111,119 +588,325 @@ def __init__(self, reporting_config, job_id, run_time):
# Make chunk size configurable, defaulting to 500
self.chunk_size = int(reporting_config.get(
"chunk_size") or _DEFAULT_CHUNK_SIZE)
+ self._dataset_ensured = False
+ self._tables: dict[str, bigquery.Table] = {}
+
+ def _ensure_dataset(self) -> None:
+ if self._dataset_ensured:
+ return
+ dataset = bigquery.Dataset(self.dataset_path)
+ dataset.location = self.location
+ self.client.create_dataset(dataset, exists_ok=True, timeout=30)
+ self._dataset_ensured = True
+
+ def _ensure_table_and_schema(
+ self,
+ table_id: str,
+ df: pd.DataFrame,
+ store_type: STORETYPE | None = None,
+ ) -> bigquery.Table:
+ """Ensures `table_id` exists and includes any new columns in `df`."""
+ table_obj = self._tables.get(table_id)
+ if table_obj is None:
+ try:
+ table_obj = self.client.get_table(table_id)
+ except NotFound:
+ schema = _infer_schema(df, store_type)
+ table_obj = self.client.create_table(
+ bigquery.Table(table_id, schema=schema), exists_ok=True
+ )
+ if not table_obj.schema:
+ table_obj = self.client.get_table(table_id)
+
+ existing_lower = {field.name.lower() for field in table_obj.schema}
+ missing_cols = [
+ col for col in df.columns if str(col).lower() not in existing_lower
+ ]
+ if missing_cols:
+ for attempt in range(_MAX_SCHEMA_UPDATE_RETRIES):
+ # Refresh before patching in case another worker added the field.
+ table_obj = self.client.get_table(table_id)
+ existing_lower = {
+ field.name.lower() for field in table_obj.schema
+ }
+ missing_cols = [
+ col for col in df.columns
+ if str(col).lower() not in existing_lower
+ ]
+ if not missing_cols:
+ break
+ added_fields = _infer_schema(df[missing_cols], store_type)
+ table_obj.schema = list(table_obj.schema) + added_fields
+ try:
+ table_obj = self.client.update_table(table_obj, ["schema"])
+ break
+ except (Conflict, PreconditionFailed):
+ if attempt == _MAX_SCHEMA_UPDATE_RETRIES - 1:
+ raise
+ time.sleep(0.5 * (2 ** attempt))
+
+ self._tables[table_id] = table_obj
+ return table_obj
+
+ def _resolve_table_id(self, store_type: STORETYPE) -> str:
+ if store_type == STORETYPE.CONFIGS:
+ return self.configs_table
+ if store_type == STORETYPE.EVALS:
+ return self.results_table
+ if store_type == STORETYPE.SCORES:
+ return self.scores_table
+ if store_type == STORETYPE.SUMMARY:
+ return self.summary_table
+ raise ValueError(f"Unsupported store type: {store_type}")
+
+ def _refresh_schema(
+ self,
+ table_id: str,
+ results: pd.DataFrame,
+ store_type: STORETYPE | None,
+ current_schema: list[bigquery.SchemaField],
+ chunk: pd.DataFrame,
+ pending_positions: list[int],
+ pending_rows: list[dict[str, Any]],
+ pending_row_ids: list[str],
+ max_bytes: int,
+ skipped_rows: list[str],
+ ) -> tuple[
+ list[bigquery.SchemaField],
+ list[int],
+ list[dict[str, Any]],
+ list[str],
+ ]:
+ """Refreshes cached table schema and re-coerces pending rows if it changed."""
+ self._tables.pop(table_id, None)
+ refreshed = self._ensure_table_and_schema(table_id, results, store_type)
+ refreshed_schema = list(refreshed.schema)
+ if refreshed_schema != current_schema:
+ current_schema = refreshed_schema
+ recoerced = _dataframe_to_json_rows(
+ chunk.iloc[pending_positions], current_schema, store_type
+ )
+ pending_positions, pending_rows, pending_row_ids = (
+ _fit_rows_with_positions(
+ pending_positions,
+ recoerced,
+ current_schema,
+ max_bytes,
+ table_id,
+ row_ids=pending_row_ids,
+ skipped_rows=skipped_rows,
+ )
+ )
+ return current_schema, pending_positions, pending_rows, pending_row_ids
def store(self, results, type: STORETYPE):
- if type == STORETYPE.CONFIGS:
- table = self.configs_table
- elif type == STORETYPE.EVALS:
- table = self.results_table
- elif type == STORETYPE.SCORES:
- table = self.scores_table
- elif type == STORETYPE.SUMMARY:
- table = self.summary_table
- self._load(results, table, label=str(type), store_type=type)
+ if results is None or results.empty:
+ logging.info(f"No results to store for {type}")
+ return
+ table = self._resolve_table_id(type)
+ self._stream(results, table, label=str(type), store_type=type)
def store_run_stats(self, run_stats):
+ if run_stats is None or run_stats.empty:
+ logging.info("No results to store for run stats")
+ return
# The stats have one column for each metric of the job. A metric
# name is not always a valid BigQuery column name.
columns = [_column_name(name) for name in run_stats.columns]
- self._load(
- run_stats.set_axis(columns, axis=1), self.run_stats_table,
- label="run stats")
-
- def _load(self, results, table, label: str, store_type=None):
- """Appends the rows of `results` to `table`.
+ self._stream(
+ run_stats.set_axis(columns, axis=1),
+ self.run_stats_table,
+ label="run stats",
+ )
- `label` names the rows in the log. `store_type` is the STORETYPE of
- the rows, if they have one.
- """
+ def _stream(
+ self,
+ results: pd.DataFrame,
+ table: str,
+ label: str,
+ store_type: STORETYPE | None = None,
+ ) -> None:
+ """Streams `results` rows into `table` via tabledata.insertAll."""
if results is None or results.empty:
logging.info(f"No results to store for {label}")
return
- dataset = bigquery.Dataset(self.dataset_path)
- dataset.location = self.location
- dataset = self.client.create_dataset(
- dataset, exists_ok=True, timeout=30)
- logging.info(
- "Created dataset {}.{} for {}".format(
- self.client.project, dataset.dataset_id, label
- )
- )
- job_config = bigquery.LoadJobConfig()
- job_config.autodetect = True
- job_config.allow_quoted_newlines = True
- job_config.schema_update_options = [
- bigquery.SchemaUpdateOption.ALLOW_FIELD_ADDITION,
- bigquery.SchemaUpdateOption.ALLOW_FIELD_RELAXATION,
- ]
+ self._ensure_dataset()
- # Chunk this to avoid BQ OOM
- job_config.write_disposition = (
- bigquery.job.WriteDisposition.WRITE_APPEND # type: ignore
- )
- for chunk in _split_dataframe(results, self.chunk_size):
- # Workaround for pyarrow truncation error when inserting floats
- # into INT64 columns. This happens if BQ autodetected a column as
- # INT64 in a previous run. Casting to string avoids the client-side
- # pyarrow crash and lets BQ handle the conversion.
- if store_type in [STORETYPE.SUMMARY, STORETYPE.SCORES]:
- chunk = chunk.copy()
- # 1. Identify columns that BQ might have already locked
- # as INT64 common ones are 'metric_score', etc.
- int_cols = [
- "metric_score", "totalLatencyMs",
- "total_results_count", "correct_results_count"
- ]
- for col in int_cols:
- if col in chunk.columns:
- # Round and cast to Int64 (nullable integer type)
- chunk[col] = pd.to_numeric(
- chunk[col], errors="coerce"
- ).round().astype("Int64")
-
- # 2. For any remaining float columns that aren't in our
- # "must-be-int" list, we cast to string to avoid pyarrow's
- # strict truncation check if BQ thinks it's an int.
- # The suite stats of a multi-trial run stay floats, so a
- # query can aggregate them. They are new columns, so BQ has
- # no INT64 type for them from a previous run.
- float_cols = chunk.select_dtypes(
- include=["float64", "float32"]
- ).columns
- for col in float_cols:
- if col not in int_cols and col not in _SUITE_COLUMNS:
- # Convert to string and strip .0 if effectively int
- chunk[col] = (
- chunk[col]
- .astype(str)
- .str.replace(r"\.0$", "", regex=True)
- .replace("nan", None)
- )
+ # Use BigQuery streaming inserts (tabledata.insertAll) instead of per-eval
+ # load jobs so high-concurrency CI suites never exhaust BigQuery's hard
+ # 1,500 load_job_per_table.long daily limit.
+ max_bytes = _MAX_STREAMING_REQUEST_BYTES
+ max_attempts = len(_STREAMING_RETRY_DELAYS) + 1
+ skipped_rows: list[str] = []
- # Retry loop for BQ load job to handle transient rate limits
- max_retries = 5
- initial_delay = 2
- backoff_factor = 2
+ table_obj = self._ensure_table_and_schema(table, results, store_type)
+ current_schema = list(table_obj.schema)
- for attempt in range(max_retries):
- try:
- job = self.client.load_table_from_dataframe(
- chunk, table, job_config=job_config
+ for chunk in _split_dataframe(results, self.chunk_size):
+ chunk_schema = current_schema
+ raw_json_rows = _dataframe_to_json_rows(
+ chunk, chunk_schema, store_type
+ )
+ fitted_positions, fitted_rows, _ = _fit_rows_with_positions(
+ range(len(raw_json_rows)),
+ raw_json_rows,
+ chunk_schema,
+ max_bytes,
+ table,
+ skipped_rows=skipped_rows,
+ )
+ chunk_offset = 0
+
+ for batch in _iter_streaming_batches(
+ fitted_rows, self.chunk_size, max_bytes=max_bytes
+ ):
+ batch_len = len(batch)
+ pending_positions = list(
+ fitted_positions[chunk_offset:chunk_offset + batch_len]
+ )
+ chunk_offset += batch_len
+ if current_schema != chunk_schema:
+ recoerced = _dataframe_to_json_rows(
+ chunk.iloc[pending_positions],
+ current_schema,
+ store_type,
)
- job.result() # Wait for the job to complete.
- break # Success, exit retry loop
- except (TooManyRequests, ServiceUnavailable) as e:
- if attempt == max_retries - 1:
- logging.error(
- f"BQ write failed after {max_retries} attempts: {e}")
- raise
- delay = initial_delay * (backoff_factor ** attempt)
- logging.warning(
- f"BQ write failed with transient error: {e}. "
- f"Retrying in {delay}s... (Attempt {attempt + 1}/{max_retries})"
+ pending_positions, pending_rows, _ = (
+ _fit_rows_with_positions(
+ pending_positions,
+ recoerced,
+ current_schema,
+ max_bytes,
+ table,
+ skipped_rows=skipped_rows,
+ )
)
- time.sleep(delay)
+ if not pending_rows:
+ continue
+ else:
+ pending_rows = batch
+ pending_row_ids = [str(uuid.uuid4()) for _ in pending_rows]
+
+ for attempt in range(max_attempts):
+ try:
+ errors = self.client.insert_rows_json(
+ table,
+ pending_rows,
+ row_ids=pending_row_ids,
+ retry=_STREAMING_TRANSPORT_RETRY,
+ timeout=_STREAMING_REQUEST_TIMEOUT_SECONDS,
+ )
+ if not errors:
+ break
+ if (
+ attempt < max_attempts - 1
+ and _is_transient_insert_error(errors)
+ ):
+ failed_indices = sorted({
+ err["index"]
+ for err in errors
+ if isinstance(err.get("index"), int)
+ and 0 <= err["index"] < len(pending_rows)
+ })
+ if failed_indices:
+ pending_positions = [
+ pending_positions[i]
+ for i in failed_indices
+ ]
+ pending_rows = [
+ pending_rows[i] for i in failed_indices
+ ]
+ pending_row_ids = [
+ pending_row_ids[i] for i in failed_indices
+ ]
+ if _has_schema_lag_error(errors):
+ (
+ current_schema,
+ pending_positions,
+ pending_rows,
+ pending_row_ids,
+ ) = self._refresh_schema(
+ table,
+ results,
+ store_type,
+ current_schema,
+ chunk,
+ pending_positions,
+ pending_rows,
+ pending_row_ids,
+ max_bytes,
+ skipped_rows,
+ )
+ if not pending_rows:
+ break
+ # Only treat "no such field" as retryable schema
+ # lag when every reported field path actually
+ # exists in the refreshed server schema.
+ if not _all_missing_fields_in_schema(
+ errors, current_schema
+ ):
+ raise RuntimeError(
+ f"BigQuery streaming insert into "
+ f"{table} failed with missing field(s) "
+ f"absent from table schema: "
+ f"{errors[:3]}"
+ )
+ delay = _STREAMING_RETRY_DELAYS[attempt]
+ logging.warning(
+ "BQ streaming write had transient/schema-lag "
+ f"errors: {errors[:2]}. Retrying in {delay}s... "
+ f"(Attempt {attempt + 1}/{max_attempts})"
+ )
+ time.sleep(delay)
+ continue
+ raise RuntimeError(
+ f"BigQuery streaming insert into {table} failed: "
+ f"{errors[:3]}"
+ )
+ except NotFound as e:
+ # DEFAULT_RETRY does not retry 404; handle propagation
+ # lag after create_table or concurrent table recreation.
+ if attempt == max_attempts - 1:
+ logging.error(
+ f"BQ write failed after {max_attempts} "
+ f"attempts: {e}"
+ )
+ raise
+ (
+ current_schema,
+ pending_positions,
+ pending_rows,
+ pending_row_ids,
+ ) = self._refresh_schema(
+ table,
+ results,
+ store_type,
+ current_schema,
+ chunk,
+ pending_positions,
+ pending_rows,
+ pending_row_ids,
+ max_bytes,
+ skipped_rows,
+ )
+ if not pending_rows:
+ break
+ delay = _STREAMING_RETRY_DELAYS[attempt]
+ logging.warning(
+ f"BQ table not yet visible for streaming: {e}. "
+ f"Retrying in {delay}s... "
+ f"(Attempt {attempt + 1}/{max_attempts})"
+ )
+ time.sleep(delay)
+
+ if skipped_rows:
+ raise RuntimeError(
+ f"BigQuery streaming insert into {table} skipped "
+ f"{len(skipped_rows)} oversized row(s) exceeding {max_bytes} "
+ f"bytes after truncating STRING columns (all other rows were "
+ f"written): {skipped_rows[:3]}"
+ )
def print_dashboard_links(self):
report_date = self.run_time.strftime("%Y-%m-%d")
diff --git a/evalbench/test/bqstore_test.py b/evalbench/test/bqstore_test.py
index 6640df27..351d7111 100644
--- a/evalbench/test/bqstore_test.py
+++ b/evalbench/test/bqstore_test.py
@@ -1,78 +1,1075 @@
-"""The BigQuery reporter."""
-
-from unittest import mock
+import datetime
+import json
+import math
+import os
+import subprocess
+import sys
+import unittest
+from unittest.mock import MagicMock, patch
+from google.api_core.exceptions import (
+ BadGateway,
+ Conflict,
+ Forbidden,
+ InternalServerError,
+ NotFound,
+ PreconditionFailed,
+ RetryError,
+ ServiceUnavailable,
+ TooManyRequests,
+)
+from google.auth import exceptions as auth_exceptions
+from google.cloud import bigquery
+import numpy as np
import pandas as pd
-import pytest
-
-from reporting import bqstore
+from reporting.bqstore import (
+ BigQueryReporter,
+ _STREAMING_REQUEST_TIMEOUT_SECONDS,
+ _STREAMING_RETRY_DELAYS,
+ _STREAMING_TRANSPORT_RETRY,
+ _TRUNCATION_SUFFIX,
+ _all_missing_fields_in_schema,
+ _coerce_json_value,
+ _dataframe_to_json_rows,
+ _fit_row_to_limit,
+ _infer_schema,
+ _is_transient_insert_error,
+ _iter_streaming_batches,
+ _serialized_row_bytes,
+)
from reporting.report import STORETYPE
+import requests
+
+
+class TestBigQueryReporterStreaming(unittest.TestCase):
+
+ def setUp(self):
+ self.run_time = datetime.datetime(2026, 11, 18, 3, 15, 0)
+ self.mock_client_patcher = patch("reporting.bqstore.bigquery.Client")
+ self.mock_bq_client_cls = self.mock_client_patcher.start()
+ self.mock_client = MagicMock()
+ self.mock_bq_client_cls.return_value = self.mock_client
+
+ self.reporter = BigQueryReporter(
+ {"gcp_project_id": "test-project", "dataset_id": "evalbench"},
+ job_id="job-123",
+ run_time=self.run_time,
+ )
+
+ def tearDown(self):
+ self.mock_client_patcher.stop()
+
+ def test_store_uses_streaming_insert_rows_json_and_zero_load_jobs(self):
+ configs_schema = [
+ bigquery.SchemaField("job_id", "STRING"),
+ bigquery.SchemaField("run_time", "DATETIME"),
+ bigquery.SchemaField("config", "STRING"),
+ bigquery.SchemaField("value", "STRING"),
+ ]
+ table_obj = bigquery.Table(
+ "test-project.evalbench.configs", schema=configs_schema
+ )
+ self.mock_client.get_table.return_value = table_obj
+ self.mock_client.insert_rows_json.return_value = []
+
+ df = pd.DataFrame([
+ {
+ "job_id": "job-123",
+ "run_time": self.run_time,
+ "config": "model_config.generator",
+ "value": "agy_cli",
+ },
+ {
+ "job_id": "job-123",
+ "run_time": self.run_time,
+ "config": "experiment_config.empty_val",
+ "value": pd.NA,
+ },
+ ])
+
+ self.reporter.store(df, STORETYPE.CONFIGS)
+
+ self.mock_client.load_table_from_dataframe.assert_not_called()
+ self.mock_client.insert_rows_json.assert_called_once()
+ target_table, rows = self.mock_client.insert_rows_json.call_args[0]
+ self.assertEqual(target_table, "test-project.evalbench.configs")
+ self.assertEqual(
+ rows,
+ [
+ {
+ "job_id": "job-123",
+ "run_time": "2026-11-18T03:15:00.000000",
+ "config": "model_config.generator",
+ "value": "agy_cli",
+ },
+ {
+ "job_id": "job-123",
+ "run_time": "2026-11-18T03:15:00.000000",
+ "config": "experiment_config.empty_val",
+ },
+ ],
+ )
+
+ def test_store_creates_missing_table_and_rounds_summary_integers(self):
+ self.mock_client.get_table.side_effect = NotFound("Table not found")
+
+ def _create_table(table_arg, exists_ok=False):
+ return table_arg
+
+ self.mock_client.create_table.side_effect = _create_table
+ self.mock_client.insert_rows_json.return_value = []
+
+ summary_df = pd.DataFrame([
+ {
+ "metric_name": "goal_completion",
+ "metric_score": 100.0,
+ "correct_results_count": 1.67,
+ "total_results_count": 2,
+ "extra_ratio": 0.75,
+ "job_id": "job-123",
+ "run_time": self.run_time,
+ }
+ ])
+
+ self.reporter.store(summary_df, STORETYPE.SUMMARY)
+
+ self.mock_client.create_table.assert_called_once()
+ created_table = self.mock_client.create_table.call_args[0][0]
+ schema_types = {f.name: f.field_type for f in created_table.schema}
+ self.assertEqual(schema_types["metric_score"], "INTEGER")
+ self.assertEqual(schema_types["correct_results_count"], "INTEGER")
+ self.assertEqual(schema_types["total_results_count"], "INTEGER")
+ self.assertEqual(schema_types["extra_ratio"], "STRING")
+ self.assertEqual(schema_types["run_time"], "DATETIME")
+
+ _, rows = self.mock_client.insert_rows_json.call_args[0]
+ self.assertEqual(rows[0]["correct_results_count"], 2)
+ self.assertEqual(rows[0]["metric_score"], 100)
+ self.assertEqual(rows[0]["total_results_count"], 2)
+ self.assertEqual(rows[0]["extra_ratio"], "0.75")
+
+ def test_store_adds_missing_columns_to_existing_table_schema(self):
+ existing_table = bigquery.Table(
+ "test-project.evalbench.results",
+ schema=[
+ bigquery.SchemaField("job_id", "STRING"),
+ bigquery.SchemaField("eval_id", "STRING"),
+ ],
+ )
+ updated_table = bigquery.Table(
+ "test-project.evalbench.results",
+ schema=[
+ bigquery.SchemaField("job_id", "STRING"),
+ bigquery.SchemaField("eval_id", "STRING"),
+ bigquery.SchemaField("accumulated_skills", "STRING"),
+ ],
+ )
+ self.mock_client.get_table.side_effect = [existing_table, existing_table]
+ self.mock_client.update_table.return_value = updated_table
+ self.mock_client.insert_rows_json.return_value = []
+
+ results_df = pd.DataFrame([
+ {
+ "job_id": "job-123",
+ "eval_id": "scenario-1",
+ "accumulated_skills": "['bigquery']",
+ }
+ ])
+
+ self.reporter.store(results_df, STORETYPE.EVALS)
+
+ self.mock_client.update_table.assert_called_once()
+ patched_table = self.mock_client.update_table.call_args[0][0]
+ self.assertEqual(
+ [f.name for f in patched_table.schema],
+ ["job_id", "eval_id", "accumulated_skills"],
+ )
+ _, rows = self.mock_client.insert_rows_json.call_args[0]
+ self.assertEqual(rows[0]["accumulated_skills"], "['bigquery']")
+
+ def test_store_handles_repeated_fields_and_float_nan_safely(self):
+ scores_table = bigquery.Table(
+ "test-project.evalbench.scores",
+ schema=[
+ bigquery.SchemaField("id", "STRING"),
+ bigquery.SchemaField("comparator", "STRING"),
+ bigquery.SchemaField("score", "FLOAT"),
+ bigquery.SchemaField("dialects", "STRING", mode="REPEATED"),
+ bigquery.SchemaField("job_id", "STRING"),
+ ],
+ )
+ self.mock_client.get_table.return_value = scores_table
+ self.mock_client.insert_rows_json.return_value = []
+
+ scores_df = pd.DataFrame([
+ {
+ "id": "s1",
+ "comparator": "goal_completion",
+ "score": 95.5,
+ "dialects": ["bigquery"],
+ "job_id": "job-123",
+ },
+ {
+ "id": "s2",
+ "comparator": "goal_completion",
+ "score": math.nan,
+ "dialects": None,
+ "job_id": "job-123",
+ },
+ ])
+
+ self.reporter.store(scores_df, STORETYPE.SCORES)
+
+ _, rows = self.mock_client.insert_rows_json.call_args[0]
+ self.assertEqual(rows[0]["score"], 95.5)
+ self.assertEqual(rows[0]["dialects"], ["bigquery"])
+ self.assertNotIn("score", rows[1])
+ self.assertNotIn("dialects", rows[1])
+
+ @patch("reporting.bqstore.time.sleep")
+ def test_store_delegates_transport_retry_and_retries_verified_schema_lag(
+ self, mock_sleep
+ ):
+ # Verify the retry object passed to insert_rows_json matches real BQ
+ # transport exceptions and is bounded to 120s.
+ self.assertEqual(_STREAMING_TRANSPORT_RETRY._deadline, 120.0)
+ predicate = _STREAMING_TRANSPORT_RETRY._predicate
+ for retryable in (
+ ServiceUnavailable("503"),
+ BadGateway("502"),
+ TooManyRequests("429"),
+ InternalServerError("500"),
+ Forbidden("403 rate", errors=[{"reason": "rateLimitExceeded"}]),
+ requests.exceptions.Timeout("read timeout"),
+ ConnectionError("reset"),
+ auth_exceptions.TransportError("token refresh"),
+ ):
+ self.assertTrue(predicate(retryable), f"expected retryable: {retryable!r}")
+ for non_retryable in (
+ Forbidden("403 Access Denied"),
+ requests.exceptions.SSLError("ssl"),
+ NotFound("404"),
+ ):
+ self.assertFalse(
+ predicate(non_retryable), f"expected non-retryable: {non_retryable!r}"
+ )
+ # Ensure SSLError stays non-retryable even on google-cloud-bigquery 3.40.1
+ # where DEFAULT_RETRY._predicate returns True (SSLError subclasses ConnectionError).
+ with patch.object(
+ bigquery.retry.DEFAULT_RETRY, "_predicate", return_value=True
+ ):
+ self.assertFalse(predicate(requests.exceptions.SSLError("ssl")))
+
+ table_obj = bigquery.Table(
+ "test-project.evalbench.configs",
+ schema=[
+ bigquery.SchemaField("job_id", "STRING"),
+ bigquery.SchemaField("config", "STRING"),
+ ],
+ )
+ self.mock_client.get_table.return_value = table_obj
+ self.mock_client.insert_rows_json.side_effect = [
+ [{
+ "index": 0,
+ "errors": [{"reason": "invalid", "message": "no such field: config."}],
+ }],
+ [],
+ ]
+
+ df = pd.DataFrame([{"job_id": "job-123", "config": "k"}])
+ self.reporter.store(df, STORETYPE.CONFIGS)
+ self.assertEqual(self.mock_client.insert_rows_json.call_count, 2)
+ self.assertIs(
+ self.mock_client.insert_rows_json.call_args.kwargs["retry"],
+ _STREAMING_TRANSPORT_RETRY,
+ )
+ self.assertEqual(
+ self.mock_client.insert_rows_json.call_args.kwargs["timeout"],
+ _STREAMING_REQUEST_TIMEOUT_SECONDS,
+ )
+ self.assertEqual(mock_sleep.call_count, 1)
+
+ # RetryError (raised when DEFAULT_RETRY exhausts its deadline) must not
+ # trigger another outer retry loop.
+ mock_sleep.reset_mock()
+ self.mock_client.insert_rows_json.side_effect = RetryError(
+ "Timeout of 120.0s exceeded", ServiceUnavailable("503")
+ )
+ with self.assertRaises(RetryError):
+ self.reporter.store(df, STORETYPE.CONFIGS)
+ mock_sleep.assert_not_called()
+
+ # Permanent 403 Forbidden (e.g. IAM deny or hard quotaExceeded) fails
+ # immediately without sleeping or retrying.
+ self.mock_client.insert_rows_json.side_effect = Forbidden(
+ "403 Access Denied"
+ )
+ with self.assertRaises(Forbidden):
+ self.reporter.store(df, STORETYPE.CONFIGS)
+ mock_sleep.assert_not_called()
+
+ @patch("reporting.bqstore.time.sleep")
+ def test_store_fails_fast_on_permanent_no_such_field_errors(
+ self, mock_sleep
+ ):
+ schema = [
+ bigquery.SchemaField("job_id", "STRING"),
+ bigquery.SchemaField(
+ "meta",
+ "RECORD",
+ fields=[bigquery.SchemaField("tag", "STRING")],
+ ),
+ bigquery.SchemaField("extra", "STRING"),
+ ]
+ table_obj = bigquery.Table("test-project.evalbench.configs", schema=schema)
+ self.mock_client.get_table.return_value = table_obj
+
+ # Nested RECORD subfield missing: location="meta.extra" must not match
+ # the unrelated top-level "extra" column.
+ self.mock_client.insert_rows_json.return_value = [{
+ "index": 0,
+ "errors": [{
+ "reason": "invalid",
+ "location": "meta.extra",
+ "message": "no such field: extra.",
+ }],
+ }]
+ df = pd.DataFrame([{"job_id": "job-123", "meta": {"tag": "ok", "extra": 1}}])
+ with self.assertRaisesRegex(RuntimeError, "absent from table schema"):
+ self.reporter.store(df, STORETYPE.CONFIGS)
+ self.assertEqual(self.mock_client.insert_rows_json.call_count, 1)
+ mock_sleep.assert_not_called()
+
+ # Unknown top-level field and unparseable "no such field." also return False.
+ self.assertFalse(
+ _all_missing_fields_in_schema(
+ [{"index": 0, "errors": [{"message": "no such field: ghost."}]}],
+ schema,
+ )
+ )
+ self.assertFalse(
+ _all_missing_fields_in_schema(
+ [{"index": 0, "errors": [{"message": "no such field."}]}],
+ schema,
+ )
+ )
+ # Existing nested / array-indexed path is recognized as schema lag.
+ self.assertTrue(
+ _all_missing_fields_in_schema(
+ [{
+ "index": 0,
+ "errors": [{
+ "location": "meta[0].tag",
+ "message": "no such field.",
+ }],
+ }],
+ schema,
+ )
+ )
+
+ @patch("reporting.bqstore.time.sleep")
+ def test_store_retries_multi_row_stopped_siblings_with_stable_row_ids(
+ self, mock_sleep
+ ):
+ table_obj = bigquery.Table(
+ "test-project.evalbench.configs",
+ schema=[
+ bigquery.SchemaField("job_id", "STRING"),
+ bigquery.SchemaField("config", "STRING"),
+ ],
+ )
+ self.mock_client.get_table.return_value = table_obj
+ self.mock_client.insert_rows_json.side_effect = [
+ [
+ {
+ "index": 0,
+ "errors": [{
+ "reason": "invalid",
+ "message": "no such field: config.",
+ }],
+ },
+ {
+ "index": 1,
+ "errors": [{"reason": "stopped", "message": ""}],
+ },
+ ],
+ [],
+ ]
+
+ df = pd.DataFrame([
+ {"job_id": "job-123", "config": "k1"},
+ {"job_id": "job-123", "config": "k2"},
+ ])
+ self.reporter.store(df, STORETYPE.CONFIGS)
+
+ self.assertEqual(self.mock_client.insert_rows_json.call_count, 2)
+ self.assertEqual(mock_sleep.call_count, 1)
+ first_call = self.mock_client.insert_rows_json.call_args_list[0]
+ second_call = self.mock_client.insert_rows_json.call_args_list[1]
+ self.assertEqual(len(first_call.kwargs["row_ids"]), 2)
+ self.assertEqual(
+ first_call.kwargs["row_ids"], second_call.kwargs["row_ids"]
+ )
+
+ @patch("reporting.bqstore.time.sleep")
+ def test_store_partial_transient_error_retries_only_failed_rows_without_get_table(
+ self, mock_sleep
+ ):
+ table_obj = bigquery.Table(
+ "test-project.evalbench.configs",
+ schema=[
+ bigquery.SchemaField("job_id", "STRING"),
+ bigquery.SchemaField("config", "STRING"),
+ ],
+ )
+ self.mock_client.get_table.return_value = table_obj
+ self.mock_client.insert_rows_json.side_effect = [
+ [{
+ "index": 1,
+ "errors": [{"reason": "backendError", "message": "try again"}],
+ }],
+ [],
+ ]
+
+ df = pd.DataFrame([
+ {"job_id": "job-123", "config": "k0"},
+ {"job_id": "job-123", "config": "k1"},
+ {"job_id": "job-123", "config": "k2"},
+ ])
+ self.reporter.store(df, STORETYPE.CONFIGS)
+
+ self.assertEqual(self.mock_client.insert_rows_json.call_count, 2)
+ # Pure transient backendError must not trigger extra get_table RPCs.
+ self.assertEqual(self.mock_client.get_table.call_count, 1)
+ first_call = self.mock_client.insert_rows_json.call_args_list[0]
+ second_call = self.mock_client.insert_rows_json.call_args_list[1]
+ self.assertEqual(len(second_call.args[1]), 1)
+ self.assertEqual(second_call.args[1][0]["config"], "k1")
+ self.assertEqual(
+ second_call.kwargs["row_ids"], [first_call.kwargs["row_ids"][1]]
+ )
+
+ @patch("reporting.bqstore.time.sleep")
+ def test_store_permanent_row_error_with_stopped_sibling_fails_fast(
+ self, mock_sleep
+ ):
+ table_obj = bigquery.Table(
+ "test-project.evalbench.configs",
+ schema=[
+ bigquery.SchemaField("job_id", "STRING"),
+ bigquery.SchemaField("config", "STRING"),
+ ],
+ )
+ self.mock_client.get_table.return_value = table_obj
+ self.mock_client.insert_rows_json.return_value = [
+ {
+ "index": 0,
+ "errors": [{"reason": "invalid", "message": "bad integer"}],
+ },
+ {
+ "index": 1,
+ "errors": [{"reason": "stopped", "message": ""}],
+ },
+ ]
+
+ df = pd.DataFrame([
+ {"job_id": "job-123", "config": "k0"},
+ {"job_id": "job-123", "config": "k1"},
+ ])
+ with self.assertRaises(RuntimeError):
+ self.reporter.store(df, STORETYPE.CONFIGS)
+ self.assertEqual(self.mock_client.insert_rows_json.call_count, 1)
+ mock_sleep.assert_not_called()
+
+ @patch("reporting.bqstore.time.sleep")
+ def test_store_re_coerces_pending_rows_when_schema_changes_on_not_found(
+ self, mock_sleep
+ ):
+ old_table = bigquery.Table(
+ "test-project.evalbench.scores",
+ schema=[
+ bigquery.SchemaField("id", "STRING"),
+ bigquery.SchemaField("metric_score", "STRING"),
+ ],
+ )
+ recreated_table = bigquery.Table(
+ "test-project.evalbench.scores",
+ schema=[
+ bigquery.SchemaField("id", "STRING"),
+ bigquery.SchemaField("metric_score", "INTEGER"),
+ ],
+ )
+ self.mock_client.get_table.side_effect = [old_table, recreated_table]
+ self.mock_client.insert_rows_json.side_effect = [
+ NotFound("Table was recreated"),
+ [],
+ ]
+
+ df = pd.DataFrame([{"id": "s1", "metric_score": 95.6}])
+ self.reporter.store(df, STORETYPE.SCORES)
+
+ self.assertEqual(self.mock_client.insert_rows_json.call_count, 2)
+ first_rows = self.mock_client.insert_rows_json.call_args_list[0].args[1]
+ second_rows = self.mock_client.insert_rows_json.call_args_list[1].args[1]
+ self.assertEqual(first_rows[0]["metric_score"], "95.6")
+ self.assertEqual(second_rows[0]["metric_score"], 96)
+
+ @patch("reporting.bqstore.time.sleep")
+ def test_store_raises_not_found_after_exhausting_120s_retry_budget(
+ self, mock_sleep
+ ):
+ self.assertGreaterEqual(sum(_STREAMING_RETRY_DELAYS), 120)
+ table_obj = bigquery.Table(
+ "test-project.evalbench.configs",
+ schema=[bigquery.SchemaField("job_id", "STRING")],
+ )
+ self.mock_client.get_table.return_value = table_obj
+ self.mock_client.insert_rows_json.side_effect = NotFound("missing")
+
+ df = pd.DataFrame([{"job_id": "job-123"}])
+ with self.assertRaises(NotFound):
+ self.reporter.store(df, STORETYPE.CONFIGS)
+ self.assertEqual(
+ self.mock_client.insert_rows_json.call_count,
+ len(_STREAMING_RETRY_DELAYS) + 1,
+ )
+ self.assertEqual(
+ [c.args[0] for c in mock_sleep.call_args_list],
+ list(_STREAMING_RETRY_DELAYS),
+ )
+
+ @patch("reporting.bqstore.time.sleep")
+ def test_update_table_retries_multiple_concurrent_conflicts(self, mock_sleep):
+ final_table = bigquery.Table(
+ "test-project.evalbench.results",
+ schema=[
+ bigquery.SchemaField("job_id", "STRING"),
+ bigquery.SchemaField("new_col", "STRING"),
+ ],
+ )
+ # Return a fresh Table per get_table() call, matching BigQuery client
+ # behavior (update_table mutates table_obj.schema on the local object).
+ self.mock_client.get_table.side_effect = lambda _: bigquery.Table(
+ "test-project.evalbench.results",
+ schema=[bigquery.SchemaField("job_id", "STRING")],
+ )
+ self.mock_client.update_table.side_effect = [
+ PreconditionFailed("etag mismatch 1"),
+ Conflict("etag mismatch 2"),
+ final_table,
+ ]
+ self.mock_client.insert_rows_json.return_value = []
+
+ df = pd.DataFrame([{"job_id": "job-123", "new_col": "v"}])
+ self.reporter.store(df, STORETYPE.EVALS)
+
+ self.assertEqual(self.mock_client.update_table.call_count, 3)
+ self.assertEqual(mock_sleep.call_count, 2)
+
+ def test_infer_schema_uses_pandas_gbq_for_full_df_mixed_and_numpy_types(self):
+ df = pd.DataFrame({
+ "mixed_obj": pd.Series([100, "N/A"], dtype="object"),
+ "int_and_float": pd.Series([1, 2.5], dtype="object"),
+ "numpy_int": pd.Series([np.int64(7), None], dtype="object"),
+ "dialects": pd.Series([None, ["bigquery"]], dtype="object"),
+ })
+ fields = {f.name: f for f in _infer_schema(df, STORETYPE.EVALS)}
+ self.assertEqual(fields["mixed_obj"].field_type, "STRING")
+ self.assertEqual(fields["int_and_float"].field_type, "FLOAT")
+ self.assertEqual(fields["numpy_int"].field_type, "INTEGER")
+ self.assertEqual(fields["dialects"].mode, "REPEATED")
+ self.assertEqual(fields["dialects"].field_type, "STRING")
+
+ # All-null in chunk 0 but populated as REPEATED in chunk 1 must infer
+ # REPEATED STRING across the whole DataFrame before chunking.
+ self.reporter.chunk_size = 1
+ self.mock_client.get_table.side_effect = NotFound("missing")
+ self.mock_client.create_table.side_effect = (
+ lambda table_arg, exists_ok=False: table_arg
+ )
+ self.mock_client.insert_rows_json.return_value = []
+ multi_chunk_df = pd.DataFrame({
+ "id": ["s1", "s2"],
+ "dialects": pd.Series([None, ["bigquery"]], dtype="object"),
+ })
+ self.reporter.store(multi_chunk_df, STORETYPE.SCORES)
+ created_table = self.mock_client.create_table.call_args[0][0]
+ created_fields = {f.name: f for f in created_table.schema}
+ self.assertEqual(created_fields["dialects"].mode, "REPEATED")
+ self.assertEqual(created_fields["dialects"].field_type, "STRING")
+
+ def test_dataframe_to_json_rows_serialization_edge_cases(self):
+ schema = [
+ bigquery.SchemaField("big_int", "INT64"),
+ bigquery.SchemaField("big_int_str", "INT64"),
+ bigquery.SchemaField("dt_offset", "DATETIME"),
+ bigquery.SchemaField("dt_empty", "DATETIME"),
+ bigquery.SchemaField("ts_empty", "TIMESTAMP"),
+ bigquery.SchemaField("d_from_dt", "DATE"),
+ bigquery.SchemaField("json_col", "JSON"),
+ bigquery.SchemaField("json_str_col", "JSON"),
+ bigquery.SchemaField("dict_str", "STRING"),
+ bigquery.SchemaField("inf_float", "FLOAT"),
+ bigquery.SchemaField(
+ "meta",
+ "RECORD",
+ fields=[
+ bigquery.SchemaField("count", "INT64"),
+ bigquery.SchemaField("tag", "STRING"),
+ ],
+ ),
+ ]
+ big_int = 9007199254740993 # 2**53 + 1
+ df = pd.DataFrame([
+ {
+ "big_int": big_int,
+ "big_int_str": str(big_int),
+ "dt_offset": "2026-11-18T03:15:00-07:00",
+ "dt_empty": "",
+ "ts_empty": " ",
+ "d_from_dt": self.run_time,
+ "json_col": {"a": float("nan"), "b": 1},
+ "json_str_col": '{"k": 2}',
+ "dict_str": {"nested": "v"},
+ "inf_float": float("inf"),
+ "meta": {"COUNT": 42, "tag": "ok"},
+ },
+ {
+ "big_int": 1,
+ "big_int_str": "",
+ "dt_offset": "2026-11-18 03:15:00",
+ "dt_empty": None,
+ "ts_empty": None,
+ "d_from_dt": "",
+ "json_col": None,
+ "json_str_col": " ",
+ "dict_str": None,
+ "inf_float": None,
+ "meta": None,
+ },
+ ])
+
+ rows = _dataframe_to_json_rows(df, schema)
+ row = rows[0]
+ self.assertEqual(row["big_int"], big_int)
+ self.assertEqual(row["big_int_str"], str(big_int))
+ self.assertEqual(row["dt_offset"], "2026-11-18T10:15:00.000000")
+ self.assertNotIn("dt_empty", row)
+ self.assertNotIn("ts_empty", row)
+ self.assertEqual(row["d_from_dt"], "2026-11-18")
+ self.assertEqual(json.loads(row["json_col"]), {"a": None, "b": 1})
+ self.assertEqual(json.loads(row["json_str_col"]), {"k": 2})
+ self.assertEqual(json.loads(row["dict_str"]), {"nested": "v"})
+ self.assertNotIn("inf_float", row)
+ self.assertEqual(row["meta"], {"COUNT": 42, "tag": "ok"})
+ # Naive DATETIME in the same column as a tz-offset string must not be shifted.
+ self.assertEqual(rows[1]["dt_offset"], "2026-11-18T03:15:00.000000")
+ self.assertNotIn("big_int_str", rows[1])
+ self.assertNotIn("d_from_dt", rows[1])
+ self.assertNotIn("json_str_col", rows[1])
+
+ def test_iter_streaming_batches_splits_by_byte_size(self):
+ rows = [
+ {"id": "1", "payload": "a" * 80},
+ {"id": "2", "payload": "b" * 80},
+ {"id": "3", "payload": "c" * 80},
+ ]
+ # Each row is ~103 JSON bytes + 64-byte insertAll wrapper (~167 bytes).
+ batches = list(_iter_streaming_batches(rows, max_rows=10, max_bytes=220))
+ self.assertEqual(len(batches), 3)
+ self.assertEqual([b[0]["id"] for b in batches], ["1", "2", "3"])
+
+ def test_float_rounding_is_limited_to_summary_and_scores_int_columns(self):
+ schema = [
+ bigquery.SchemaField("metric_score", "INTEGER"),
+ bigquery.SchemaField("totallatencyms", "INTEGER"),
+ bigquery.SchemaField("score", "INTEGER"),
+ bigquery.SchemaField("nullable_count", "INTEGER"),
+ ]
+ df = pd.DataFrame([
+ {
+ "metric_score": 95.6,
+ "totallatencyms": 12.4,
+ "score": 88.7,
+ "nullable_count": 5,
+ },
+ {
+ "metric_score": 50.0,
+ "totallatencyms": 10.0,
+ "score": 40.0,
+ "nullable_count": None,
+ },
+ ])
+ scores_rows = _dataframe_to_json_rows(df, schema, STORETYPE.SCORES)
+ self.assertEqual(scores_rows[0]["metric_score"], 96)
+ self.assertEqual(scores_rows[0]["totallatencyms"], 12)
+ # Non-allowlisted INTEGER column keeps its fractional float unrounded.
+ self.assertEqual(scores_rows[0]["score"], 88.7)
+ # Nullable pandas int widened to 5.0 converts losslessly to int 5.
+ self.assertEqual(scores_rows[0]["nullable_count"], 5)
+ self.assertIsInstance(scores_rows[0]["nullable_count"], int)
+
+ # Even allowlisted names are NOT rounded outside SUMMARY/SCORES.
+ evals_rows = _dataframe_to_json_rows(df, schema, STORETYPE.EVALS)
+ self.assertEqual(evals_rows[0]["metric_score"], 95.6)
+ self.assertEqual(evals_rows[0]["totallatencyms"], 12.4)
+ self.assertEqual(evals_rows[0]["nullable_count"], 5)
+
+ def test_oversized_single_row_truncates_strings_and_skips_unshrinkable_rows(
+ self,
+ ):
+ schema = [
+ bigquery.SchemaField("id", "STRING"),
+ bigquery.SchemaField("conversation_history", "STRING"),
+ bigquery.SchemaField("extra_log", "STRING"),
+ bigquery.SchemaField("raw_json", "JSON"),
+ ]
+ table_obj = bigquery.Table("test-project.evalbench.results", schema=schema)
+ self.mock_client.get_table.return_value = table_obj
+ self.mock_client.insert_rows_json.return_value = []
+
+ # Row 0: oversized STRING with quotes/emoji -> truncated to fit.
+ # Row 1: oversized JSON (non-STRING) -> must NOT corrupt JSON; skipped.
+ # Row 2: normal row -> still streamed after the skipped row.
+ df = pd.DataFrame([
+ {
+ "id": "r-trunc",
+ "conversation_history": '"🚀' * 200,
+ "extra_log": "y" * 200,
+ "raw_json": '{"ok": 1}',
+ },
+ {
+ "id": "r-skip",
+ "conversation_history": "short",
+ "extra_log": "ok",
+ "raw_json": json.dumps({"blob": "z" * 600}),
+ },
+ {
+ "id": "r-ok",
+ "conversation_history": "hello",
+ "extra_log": "ok",
+ "raw_json": '{"ok": 2}',
+ },
+ ])
+ limit = 420
+ # Truncatable STRING row alone succeeds without raising.
+ with patch("reporting.bqstore._MAX_STREAMING_REQUEST_BYTES", limit):
+ self.reporter.store(df.iloc[[0]], STORETYPE.EVALS)
+ self.mock_client.insert_rows_json.reset_mock()
+
+ # With an unshrinkable JSON row present, valid sibling rows are still
+ # streamed and store() raises RuntimeError listing the skipped row.
+ with patch("reporting.bqstore._MAX_STREAMING_REQUEST_BYTES", limit):
+ with self.assertRaisesRegex(RuntimeError, "r-skip"):
+ self.reporter.store(df, STORETYPE.EVALS)
+
+ sent_rows = [
+ row
+ for call in self.mock_client.insert_rows_json.call_args_list
+ for row in call.args[1]
+ ]
+ self.assertEqual([r["id"] for r in sent_rows], ["r-trunc", "r-ok"])
+ self.assertLessEqual(_serialized_row_bytes(sent_rows[0]), limit)
+ self.assertTrue(
+ sent_rows[0]["conversation_history"].endswith(_TRUNCATION_SUFFIX)
+ )
+ self.assertEqual(sent_rows[0]["raw_json"], '{"ok": 1}')
+
+ # Direct helper check: tiny limit smaller than suffix skips cleanly.
+ self.assertIsNone(
+ _fit_row_to_limit(
+ {"id": "x", "conversation_history": "a" * 200},
+ frozenset({"id", "conversation_history"}),
+ max_bytes=80,
+ table="p.d.t",
+ )
+ )
+
+ # Skipping row 0 (oversized JSON) must keep pending_positions aligned
+ # when row 1 hits NotFound and is re-coerced against a recreated schema.
+ self.reporter._tables.clear()
+ self.mock_client.reset_mock()
+ old_scores = bigquery.Table(
+ "test-project.evalbench.scores",
+ schema=[
+ bigquery.SchemaField("id", "STRING"),
+ bigquery.SchemaField("metric_score", "STRING"),
+ bigquery.SchemaField("raw_json", "JSON"),
+ ],
+ )
+ new_scores = bigquery.Table(
+ "test-project.evalbench.scores",
+ schema=[
+ bigquery.SchemaField("id", "STRING"),
+ bigquery.SchemaField("metric_score", "INTEGER"),
+ bigquery.SchemaField("raw_json", "JSON"),
+ ],
+ )
+ self.mock_client.get_table.side_effect = [old_scores, new_scores]
+ self.mock_client.insert_rows_json.side_effect = [
+ NotFound("recreated"),
+ [],
+ ]
+ scores_df = pd.DataFrame([
+ {
+ "id": "s-skip",
+ "metric_score": 10.2,
+ "raw_json": json.dumps({"blob": "z" * 600}),
+ },
+ {
+ "id": "s-keep",
+ "metric_score": 95.6,
+ "raw_json": '{"ok": 1}',
+ },
+ ])
+ with patch("reporting.bqstore._MAX_STREAMING_REQUEST_BYTES", 300):
+ with self.assertRaisesRegex(RuntimeError, "s-skip"):
+ self.reporter.store(scores_df, STORETYPE.SCORES)
+ retry_rows = self.mock_client.insert_rows_json.call_args_list[1].args[1]
+ self.assertEqual(len(retry_rows), 1)
+ self.assertEqual(retry_rows[0]["id"], "s-keep")
+ self.assertEqual(retry_rows[0]["metric_score"], 96)
+
+ def test_store_writes_each_type_to_its_table(self):
+ self.mock_client.insert_rows_json.return_value = []
+ for store_type, table_name in (
+ (STORETYPE.CONFIGS, "configs"),
+ (STORETYPE.EVALS, "results"),
+ (STORETYPE.SCORES, "scores"),
+ (STORETYPE.SUMMARY, "summary"),
+ ):
+ self.mock_client.get_table.return_value = bigquery.Table(
+ f"test-project.evalbench.{table_name}",
+ schema=[bigquery.SchemaField("job_id", "STRING")],
+ )
+ self.mock_client.insert_rows_json.reset_mock()
+ self.reporter.store(pd.DataFrame([{"job_id": "job-1"}]), store_type)
+ self.mock_client.insert_rows_json.assert_called_once()
+ self.assertEqual(
+ self.mock_client.insert_rows_json.call_args.args[0],
+ f"test-project.evalbench.{table_name}",
+ )
+
+ def test_suite_stats_of_the_summary_stay_numbers(self):
+ self.mock_client.get_table.side_effect = NotFound("missing")
+ self.mock_client.create_table.side_effect = (
+ lambda table_arg, exists_ok=False: table_arg
+ )
+ self.mock_client.insert_rows_json.return_value = []
+
+ summary_df = pd.DataFrame([
+ {
+ "metric_name": "goal_completion",
+ "metric_score": 50.0,
+ "pass_rate": 0.5,
+ "interval_low": 0.0945,
+ "flaky_scenarios": 1,
+ "trial_median": float("nan"),
+ "legacy_ratio": 0.25,
+ },
+ {
+ "metric_name": "turn_count",
+ "metric_score": 3.0,
+ "pass_rate": float("nan"),
+ "interval_low": float("nan"),
+ "flaky_scenarios": None,
+ "trial_median": 3.0,
+ "legacy_ratio": 0.75,
+ },
+ ]).astype({"flaky_scenarios": "Int64"})
+
+ self.reporter.store(summary_df, STORETYPE.SUMMARY)
+ created_table = self.mock_client.create_table.call_args.args[0]
+ schema_types = {f.name: f.field_type for f in created_table.schema}
+ for column in ("pass_rate", "interval_low", "trial_median"):
+ self.assertIn(schema_types[column], ("FLOAT", "FLOAT64"))
+ self.assertIn(schema_types["flaky_scenarios"], ("INTEGER", "INT64"))
+ self.assertIn(schema_types["metric_score"], ("INTEGER", "INT64"))
+ self.assertEqual(schema_types["legacy_ratio"], "STRING")
+
+ rows = self.mock_client.insert_rows_json.call_args.args[1]
+ self.assertEqual(rows[0]["pass_rate"], 0.5)
+ self.assertEqual(rows[0]["flaky_scenarios"], 1)
+ self.assertEqual(rows[0]["metric_score"], 50)
+ self.assertEqual(rows[0]["legacy_ratio"], "0.25")
+ self.assertEqual(rows[1]["trial_median"], 3.0)
+
+ def test_run_stats_go_to_the_run_stats_table_with_valid_column_names(self):
+ self.mock_client.get_table.side_effect = NotFound("missing")
+ self.mock_client.create_table.side_effect = (
+ lambda table_arg, exists_ok=False: table_arg
+ )
+ self.mock_client.insert_rows_json.return_value = []
+
+ self.reporter.store_run_stats(pd.DataFrame([
+ {
+ "scenario_id": "s1",
+ "pass_rate": 0.5,
+ "my-scorer.v2_pass_rate": 1.0,
+ "3p_latency_max": 2.0,
+ }
+ ]))
+ created_table = self.mock_client.create_table.call_args.args[0]
+ self.assertEqual(
+ [f.name for f in created_table.schema],
+ ["scenario_id", "pass_rate", "my_scorer_v2_pass_rate", "_3p_latency_max"],
+ )
+ schema_types = {f.name: f.field_type for f in created_table.schema}
+ self.assertIn(schema_types["pass_rate"], ("FLOAT", "FLOAT64"))
+
+ table, rows = self.mock_client.insert_rows_json.call_args.args
+ self.assertEqual(table, "test-project.evalbench.run_stats")
+ self.assertEqual(
+ rows,
+ [{
+ "scenario_id": "s1",
+ "pass_rate": 0.5,
+ "my_scorer_v2_pass_rate": 1.0,
+ "_3p_latency_max": 2.0,
+ }],
+ )
+
+ def test_empty_run_stats_are_not_loaded(self):
+ self.reporter.store_run_stats(pd.DataFrame())
+ self.reporter.store_run_stats(None)
+ self.mock_client.create_dataset.assert_not_called()
+ self.mock_client.insert_rows_json.assert_not_called()
+
+ def test_bqstore_imports_without_pandas_gbq_private_module(self):
+ env = dict(os.environ)
+ repo_root = os.path.abspath(
+ os.path.join(os.path.dirname(__file__), "..", "..")
+ )
+ env["PYTHONPATH"] = (
+ os.path.join(repo_root, "evalbench") + os.pathsep + repo_root
+ )
+ proc = subprocess.run(
+ [
+ sys.executable,
+ "-c",
+ "import sys; "
+ "sys.modules['pandas_gbq'] = None; "
+ "sys.modules['pandas_gbq.schema'] = None; "
+ "sys.modules['pandas_gbq.schema.pandas_to_bigquery'] = None; "
+ "import reporting.bqstore",
+ ],
+ env=env,
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ self.assertEqual(proc.returncode, 0, msg=proc.stderr)
+
+ def test_empty_input_and_unsupported_store_type_and_helper_guards(self):
+ self.reporter.store(None, STORETYPE.CONFIGS)
+ self.reporter.store(pd.DataFrame(), STORETYPE.CONFIGS)
+ self.mock_client.create_dataset.assert_not_called()
+
+ with self.assertRaises(ValueError):
+ self.reporter.store(pd.DataFrame([{"a": 1}]), "INVALID_TYPE")
+
+ # Unparseable DATETIME returns raw value; "NaT" maps to None.
+ dt_field = bigquery.SchemaField("dt", "DATETIME")
+ self.assertEqual(_coerce_json_value("not-a-date", dt_field), "not-a-date")
+ self.assertIsNone(_coerce_json_value("NaT", dt_field))
+
+ # Empty error lists and row errors with no inner error entries are non-retryable.
+ self.assertFalse(_is_transient_insert_error([]))
+ self.assertFalse(_is_transient_insert_error([{"index": 0, "errors": []}]))
+
+ @patch("reporting.bqstore.time.sleep")
+ def test_schema_edge_paths_empty_create_race_exhaustion_and_multi_batch_refresh(
+ self, mock_sleep
+ ):
+ # 1. create_table returning empty schema triggers fallback get_table().
+ populated_table = bigquery.Table(
+ "test-project.evalbench.configs",
+ schema=[bigquery.SchemaField("job_id", "STRING")],
+ )
+ self.mock_client.get_table.side_effect = [
+ NotFound("missing"),
+ populated_table,
+ ]
+ self.mock_client.create_table.return_value = bigquery.Table(
+ "test-project.evalbench.configs"
+ )
+ self.mock_client.insert_rows_json.return_value = []
+ self.reporter.store(pd.DataFrame([{"job_id": "j1"}]), STORETYPE.CONFIGS)
+ self.assertEqual(self.mock_client.get_table.call_count, 2)
+
+ # 2. Another worker adds missing column before update_table -> no update_table call.
+ self.reporter._tables.clear()
+ self.mock_client.reset_mock()
+ stale_table = bigquery.Table(
+ "test-project.evalbench.results",
+ schema=[bigquery.SchemaField("job_id", "STRING")],
+ )
+ already_updated = bigquery.Table(
+ "test-project.evalbench.results",
+ schema=[
+ bigquery.SchemaField("job_id", "STRING"),
+ bigquery.SchemaField("new_col", "STRING"),
+ ],
+ )
+ self.mock_client.get_table.side_effect = [stale_table, already_updated]
+ self.mock_client.insert_rows_json.return_value = []
+ self.reporter.store(
+ pd.DataFrame([{"job_id": "j1", "new_col": "v"}]), STORETYPE.EVALS
+ )
+ self.mock_client.update_table.assert_not_called()
+
+ # 3. update_table exhausting all 5 conflict retries re-raises PreconditionFailed.
+ self.reporter._tables.clear()
+ self.mock_client.reset_mock()
+ self.mock_client.get_table.side_effect = lambda _: bigquery.Table(
+ "test-project.evalbench.results",
+ schema=[bigquery.SchemaField("job_id", "STRING")],
+ )
+ self.mock_client.update_table.side_effect = PreconditionFailed("etag")
+ with self.assertRaises(PreconditionFailed):
+ self.reporter.store(
+ pd.DataFrame([{"job_id": "j1", "new_col": "v"}]), STORETYPE.EVALS
+ )
+ self.assertEqual(self.mock_client.update_table.call_count, 5)
+
+ # 4. Schema change during batch 1 of a multi-batch chunk re-coerces batch 2 too.
+ self.reporter._tables.clear()
+ self.mock_client.reset_mock()
+ old_scores = bigquery.Table(
+ "test-project.evalbench.scores",
+ schema=[
+ bigquery.SchemaField("id", "STRING"),
+ bigquery.SchemaField("metric_score", "STRING"),
+ ],
+ )
+ new_scores = bigquery.Table(
+ "test-project.evalbench.scores",
+ schema=[
+ bigquery.SchemaField("id", "STRING"),
+ bigquery.SchemaField("metric_score", "INTEGER"),
+ ],
+ )
+ self.mock_client.get_table.side_effect = [old_scores, new_scores]
+ self.mock_client.insert_rows_json.side_effect = [
+ NotFound("recreated"),
+ [],
+ [],
+ ]
+ # Force 2 streaming batches within 1 DataFrame chunk via max_bytes patch.
+ with patch("reporting.bqstore._MAX_STREAMING_REQUEST_BYTES", 140):
+ self.reporter.store(
+ pd.DataFrame([
+ {"id": "s1", "metric_score": 95.6},
+ {"id": "s2", "metric_score": 88.2},
+ ]),
+ STORETYPE.SCORES,
+ )
+ self.assertEqual(self.mock_client.insert_rows_json.call_count, 3)
+ batch1_retry = self.mock_client.insert_rows_json.call_args_list[1].args[1]
+ batch2_rows = self.mock_client.insert_rows_json.call_args_list[2].args[1]
+ self.assertEqual(batch1_retry[0]["metric_score"], 96)
+ self.assertEqual(batch2_rows[0]["metric_score"], 88)
-@pytest.fixture
-def reporter():
- """Returns a reporter with a fake BigQuery client."""
- with mock.patch.object(bqstore.bigquery, "Client"):
- yield bqstore.BigQueryReporter(
- {"gcp_project_id": "my-project"}, "job-1", None)
-
-
-def _loads(reporter):
- """Returns the (frame, table) pair of each load job."""
- calls = reporter.client.load_table_from_dataframe.call_args_list
- return [(call.args[0], call.args[1]) for call in calls]
-
-
-@pytest.mark.parametrize("store_type, table", [
- (STORETYPE.CONFIGS, "configs"),
- (STORETYPE.EVALS, "results"),
- (STORETYPE.SCORES, "scores"),
- (STORETYPE.SUMMARY, "summary"),
-])
-def test_store_writes_each_type_to_its_table(reporter, store_type, table):
- reporter.store(pd.DataFrame([{"job_id": "job-1"}]), store_type)
- [(_, loaded_table)] = _loads(reporter)
- assert loaded_table == f"my-project.evalbench.{table}"
-
-
-def test_suite_stats_of_the_summary_stay_numbers(reporter):
- reporter.store(pd.DataFrame([
- {"metric_name": "goal_completion", "metric_score": 50.0,
- "pass_rate": 0.5, "interval_low": 0.0945, "flaky_scenarios": 1,
- "trial_median": float("nan")},
- {"metric_name": "turn_count", "metric_score": 3.0,
- "pass_rate": float("nan"), "interval_low": float("nan"),
- "flaky_scenarios": None, "trial_median": 3.0},
- ]).astype({"flaky_scenarios": "Int64"}), STORETYPE.SUMMARY)
- [(frame, _)] = _loads(reporter)
- for column in ("pass_rate", "interval_low", "trial_median"):
- assert frame[column].dtype == "float64"
- assert frame["pass_rate"][0] == 0.5
- assert frame["flaky_scenarios"].dtype == "Int64"
- # The existing columns keep their type.
- assert frame["metric_score"].dtype == "Int64"
-
-
-def test_run_stats_go_to_the_run_stats_table(reporter):
- reporter.store_run_stats(pd.DataFrame(
- [{"scenario_id": "s1", "pass_rate": 0.5}]))
- [(frame, table)] = _loads(reporter)
- assert table == "my-project.evalbench.run_stats"
- assert frame.to_dict(orient="records") == [
- {"scenario_id": "s1", "pass_rate": 0.5}]
- # The pass rate stays a number, so a query can aggregate it.
- assert frame["pass_rate"].dtype == "float64"
-
-
-def test_run_stats_column_names_are_valid_in_bigquery(reporter):
- reporter.store_run_stats(pd.DataFrame(
- [{"scenario_id": "s1", "my-scorer.v2_pass_rate": 1.0,
- "3p_latency_max": 2.0}]))
- [(frame, _)] = _loads(reporter)
- assert list(frame.columns) == [
- "scenario_id", "my_scorer_v2_pass_rate", "_3p_latency_max"]
-
-
-def test_empty_run_stats_are_not_loaded(reporter):
- reporter.store_run_stats(pd.DataFrame())
- assert _loads(reporter) == []
+if __name__ == "__main__":
+ unittest.main()