From 7bec4db09f954c039cbf264a5aa14864eaa83c10 Mon Sep 17 00:00:00 2001 From: Justin Xu Date: Thu, 19 Nov 2026 14:16:58 -0800 Subject: [PATCH] Preserve nullable string array items for Datalab Fast with anyOf --- .../inference/providers/extract/datalab.py | 42 ++++++++++++++++++- .../extract/test_datalab_confidence.py | 17 +++++++- 2 files changed, 57 insertions(+), 2 deletions(-) diff --git a/src/extract_bench/inference/providers/extract/datalab.py b/src/extract_bench/inference/providers/extract/datalab.py index aa2ed676..58c116e5 100644 --- a/src/extract_bench/inference/providers/extract/datalab.py +++ b/src/extract_bench/inference/providers/extract/datalab.py @@ -14,6 +14,7 @@ import os import time from collections.abc import Mapping, Sequence +from copy import deepcopy from datetime import datetime from pathlib import Path from typing import Any, Literal @@ -77,6 +78,45 @@ class ConfidencePollingStatusValues: POLL_ERROR: ConfidencePollingStatus = "poll_error" +def _fast_request_schema(schema: dict[str, Any]) -> dict[str, Any]: + """Fast accepts nullable string array elements when their types are expressed with anyOf.""" + result = deepcopy(schema) + pending = [result] + while len(pending) > 0: + node = pending.pop() + if not isinstance(node, dict): + continue + items = node.get("items") + if isinstance(items, dict) and items.get("type") == ["string", "null"] and "anyOf" not in items: + del items["type"] + items["anyOf"] = [{"type": "string"}, {"type": "null"}] + + # Follow subschemas, including local definitions. Property names and literal + # values (such as examples, defaults and const) can themselves look like schemas. + for key, value in node.items(): + if key in ("properties", "patternProperties", "$defs", "definitions", "dependentSchemas", "dependencies"): + if isinstance(value, dict): + pending.extend(value.values()) + elif key in ("allOf", "anyOf", "oneOf", "prefixItems", "items") and isinstance(value, list): + pending.extend(value) + elif key in ( + "items", + "contains", + "additionalItems", + "unevaluatedItems", + "additionalProperties", + "unevaluatedProperties", + "propertyNames", + "contentSchema", + "if", + "then", + "else", + "not", + ): + pending.append(value) + return result + + @register_provider("datalab_extract") class DatalabExtractProvider(Provider): """ @@ -154,7 +194,7 @@ async def _extract_pdf_async(self, pdf_path: str, schema: dict[str, Any]) -> dic extraction_started = time.perf_counter() pdf_page_count = _read_pdf_page_count(pdf_path) options = ExtractOptions( - page_schema=json.dumps(schema), + page_schema=json.dumps(_fast_request_schema(schema) if self._extraction_mode == "fast" else schema), citation_granularity="phrase", mode=self._parse_mode, output_format=self._output_format, diff --git a/tests/extract_bench/inference/providers/extract/test_datalab_confidence.py b/tests/extract_bench/inference/providers/extract/test_datalab_confidence.py index f5af8285..778d5682 100644 --- a/tests/extract_bench/inference/providers/extract/test_datalab_confidence.py +++ b/tests/extract_bench/inference/providers/extract/test_datalab_confidence.py @@ -2,6 +2,7 @@ import asyncio import json +from copy import deepcopy from pathlib import Path from types import SimpleNamespace @@ -58,9 +59,19 @@ async def run() -> None: "type": "object", "properties": { "total": {"type": ["number", "null"]}, + "items": {"type": ["string", "null"]}, + "rows": {"type": "array", "items": {"$ref": "#/$defs/Row"}}, "bank": {"type": ["object", "null"], "properties": {"name": {"type": "string"}}}, }, } + schema["$defs"] = { + "Row": { + "type": "array", + "items": {"type": ["string", "null"], "maxLength": 12}, + "examples": [{"items": {"type": ["string", "null"]}}], + }, + } + original = deepcopy(schema) submitted_schemas = [] calls = {"submit": 0, "poll": 0} clock = {"now": 0.0} @@ -165,7 +176,11 @@ async def download(request: web.Request) -> web.Response: return with budget.activate(): result = await budget.run_async(provider._extract_pdf_async(str(source), schema)) - assert submitted_schemas == [schema] + assert schema == original + expected = deepcopy(original) + if extraction_mode == "fast": + expected["$defs"]["Row"]["items"] = {"anyOf": [{"type": "string"}, {"type": "null"}], "maxLength": 12} + assert submitted_schemas == [expected] assert json.loads(result["extraction_schema_json"])["total"] == 10 assert result["_config"]["citation_granularity"] == "phrase" assert calls["submit"] == 1