fix(python): support legacy StringView JSON writes (#5357)

PyArrow 16.1 is in the Python SDK's supported range and cannot cast
`StringView` to UTF-8. For a JSON column, sanitized `add()` and
`merge_insert()` fail at that cast before Lance can encode the input as
JSONB.

Convert top-level JSON `StringView` columns at the shared Python cast
boundary. Use Arrow's cast when available and materialize UTF-8 values
when the kernel is missing. The aligned column carries `arrow.json`
metadata and preserves nulls.

Both write regressions fail on PyArrow 16.1 before the fix and pass
after it. They consume multiple batches and verify JSON queries after
reopening. The RTE JSON upsert regression also exercises `StringView`
input.

This carries forward [LH-kevin’s
fix](https://github.com/lancedb/lancedb/commit/481e13d95c3471c80a781ba4e0b21004afbb246b).
Related to #4038 and #4035.

Co-authored-by: LH-kevin <186923068+LH-kevin@users.noreply.github.com>

---------

Co-authored-by: LH-kevin <186923068+LH-kevin@users.noreply.github.com>
This commit is contained in:
Xuanwo
2026-12-02 13:51:56 +00:00
committed by GitHub
co-authored by LH-kevin
parent 0a14761f0e
commit d87b721604
3 changed files with 59 additions and 0 deletions
+19
View File
@@ -803,9 +803,20 @@ def _cast_to_target_schema(
)
reordered_schema = pa.schema(fields, metadata=target_schema.metadata)
json_string_views = [
(index, field)
for index, (source, field) in enumerate(zip(reader.schema, reordered_schema))
if pa.types.is_string_view(source.type)
and pa.types.is_string(field.type)
and _field_extension_name(field) == "arrow.json"
]
def gen():
for batch in reader:
batch = _coerce_blob_write_columns(batch, reordered_schema)
for index, field in json_string_views:
column = _cast_json_string_view(batch.column(index))
batch = batch.set_column(index, field, column)
# Table but not RecordBatch has cast.
cast_batches = (
pa.Table.from_batches([batch]).cast(reordered_schema).to_batches()
@@ -1229,6 +1240,14 @@ def _arrow_json_storage_type(input_type: pa.DataType) -> Optional[pa.DataType]:
return None
def _cast_json_string_view(column: pa.Array) -> pa.Array:
try:
return column.cast(pa.string())
except pa.ArrowNotImplementedError:
# PyArrow 16 exposes StringView without a StringView-to-Utf8 cast.
return pa.array(column.to_pylist(), type=pa.string())
def _align_field(field: pa.Field, target_field: pa.Field) -> pa.Field:
if is_blob_v2_field(target_field):
source_type = field.type
@@ -110,6 +110,7 @@ def json_rte_table(tmp_path):
[
pytest.param(pa.string(), id="utf8"),
pytest.param(pa.large_string(), id="large-utf8"),
pytest.param(pa.string_view(), id="utf8-view"),
pytest.param(
pa.json_() if hasattr(pa, "json_") else None,
marks=pytest.mark.skipif(
+39
View File
@@ -5087,6 +5087,45 @@ def test_json_write_rejects_unmarked_binary(tmp_db: DBConnection, operation):
assert tmp_db.open_table("t").search().to_list() == [{"id": 1, "j": '{"k":1}'}]
@pytest.mark.parametrize("operation", ["sanitized_append", "merge_insert"])
def test_json_write_with_legacy_string_view(tmp_db: DBConnection, operation):
schema = pa.schema(
[
pa.field("id", pa.int64()),
pa.field("j", pa.string(), metadata={"ARROW:extension:name": "arrow.json"}),
]
)
table = tmp_db.create_table("t", schema=schema)
if operation == "merge_insert":
table.add([{"id": 1, "j": '{"k": 0}'}])
source = pa.table(
{
"id": [1, 2, 3],
"j": pa.array(['{"k": 9}', '{ "k": 2 }', None], type=pa.string_view()),
}
).to_reader(max_chunksize=1)
if operation == "merge_insert":
(
table.merge_insert("id")
.when_matched_update_all()
.when_not_matched_insert_all()
.execute(source)
)
else:
table.add(source, on_bad_vectors="fill")
reopened = tmp_db.open_table("t")
assert reopened.search().to_arrow().sort_by("id").to_pylist() == [
{"id": 1, "j": '{"k":9}'},
{"id": 2, "j": '{"k":2}'},
{"id": 3, "j": None},
]
matches = reopened.search().where("json_extract(j, '$.k') IN ('9', '2')").to_list()
assert sorted(row["id"] for row in matches) == [1, 2]
@pytest.mark.skipif(not hasattr(pa, "json_"), reason="requires PyArrow JSON type")
@pytest.mark.asyncio
async def test_merge_insert_encodes_json(mem_db_async: AsyncConnection):