mirror of
https://github.com/lancedb/lancedb.git
synced 2026-12-03 07:45:17 +00:00
fix: encode JSON in RTE merge_insert (#5353)
Unsharded RTE `merge_insert` reaches the shard writer with JSON text,
which fails the writer’s `LargeBinary` schema check. Encode Arrow JSON
with Lance’s JSONB converter before schema alignment so plain JSON text
and `arrow.json` can both be upserted. Require an explicit JSON
extension on binary input before schema alignment can attach the
destination’s JSONB metadata.
The Python regression tests query the updated and inserted rows after
reopening the table and verify that invalid JSON and unmarked binary
writes leave the existing data intact. Overwrite tests cover schema
replacement in both directions between plain Arrow strings and typed
JSON.
PyArrow 16.1 still raises `Unsupported cast from string_view to utf8`
for `StringView` input on sanitized append and merge paths. Ordinary
UTF-8 RTE upserts and default Arrow append with `StringView` pass on
that version.
The RTE conversion and regression build on LH-kevin’s
[601aebe](https://github.com/lancedb/lancedb/commit/601aebe87771422c47156c94b477ca1ce475de6b).
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:
@@ -1269,7 +1269,8 @@ def _align_field(field: pa.Field, target_field: pa.Field) -> pa.Field:
|
||||
# casting the input to that storage type here merely relabels the raw JSON bytes as
|
||||
# JSONB. Lance must see arrow.json so it can perform the JSONB encoding.
|
||||
if _field_extension_name(target_field) == "lance.json":
|
||||
if _field_extension_name(field) == "arrow.json":
|
||||
input_extension = _field_extension_name(field)
|
||||
if input_extension == "arrow.json":
|
||||
return field
|
||||
# Plain JSON text, which is what pyarrow infers for a column of `str`, only
|
||||
# needs the arrow.json label.
|
||||
@@ -1284,6 +1285,11 @@ def _align_field(field: pa.Field, target_field: pa.Field) -> pa.Field:
|
||||
metadata = dict(target_field.metadata or {})
|
||||
metadata[b"ARROW:extension:name"] = b"arrow.json"
|
||||
return pa.field(field.name, json_storage, field.nullable, metadata)
|
||||
if input_extension != "lance.json" and not pa.types.is_null(field.type):
|
||||
raise ValueError(
|
||||
f"Column '{field.name}' requires JSON text or an explicit JSON type, "
|
||||
f"got {field.type}"
|
||||
)
|
||||
if pa.types.is_struct(target_field.type):
|
||||
if pa.types.is_struct(field.type):
|
||||
new_type = pa.struct(
|
||||
|
||||
@@ -88,6 +88,109 @@ def test_lsm_merge_insert_unsharded(tmp_path):
|
||||
assert result.num_rows == 4
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def json_rte_table(tmp_path):
|
||||
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0))
|
||||
schema = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int64(), nullable=False),
|
||||
pa.field("j", pa.string(), metadata={"ARROW:extension:name": "arrow.json"}),
|
||||
]
|
||||
)
|
||||
table = db.create_table(
|
||||
"json_rte", pa.Table.from_pylist([{"id": 1, "j": '{"k": 1}'}], schema=schema)
|
||||
)
|
||||
table.set_unenforced_primary_key("id")
|
||||
table.enable_rte(RTEWriteSpec.unsharded())
|
||||
return table
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"source_type",
|
||||
[
|
||||
pytest.param(pa.string(), id="utf8"),
|
||||
pytest.param(pa.large_string(), id="large-utf8"),
|
||||
pytest.param(
|
||||
pa.json_() if hasattr(pa, "json_") else None,
|
||||
marks=pytest.mark.skipif(
|
||||
not hasattr(pa, "json_"), reason="requires PyArrow JSON type"
|
||||
),
|
||||
id="arrow-json",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_rte_merge_insert_encodes_json(tmp_path, json_rte_table, source_type):
|
||||
values = ['{"k": 9}', '{"k": 2}', None]
|
||||
if isinstance(source_type, pa.ExtensionType):
|
||||
json_column = pa.ExtensionArray.from_storage(
|
||||
source_type, pa.array(values, type=source_type.storage_type)
|
||||
)
|
||||
else:
|
||||
json_column = pa.array(values, type=source_type)
|
||||
source = pa.table({"id": [1, 2, 3], "j": json_column})
|
||||
|
||||
result = (
|
||||
json_rte_table.merge_insert("id")
|
||||
.when_matched_update_all()
|
||||
.when_not_matched_insert_all()
|
||||
.execute(source)
|
||||
)
|
||||
assert result.num_rows == 3
|
||||
assert result.version == 0
|
||||
|
||||
json_rte_table.close_rte_writers()
|
||||
reopened = lancedb.connect(tmp_path).open_table("json_rte")
|
||||
assert reopened.search().to_arrow().sort_by("id").to_pylist() == [
|
||||
{"id": 1, "j": '{"k":9}'},
|
||||
{"id": 2, "j": '{"k":2}'},
|
||||
{"id": 3, "j": None},
|
||||
]
|
||||
matched_ids = (
|
||||
reopened.search()
|
||||
.where("json_extract(j, '$.k') IN ('9', '2')")
|
||||
.select(["id"])
|
||||
.to_arrow()
|
||||
)
|
||||
assert sorted(matched_ids["id"].to_pylist()) == [1, 2]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("binary_type", [pa.binary(), pa.large_binary()])
|
||||
def test_rte_merge_insert_rejects_unmarked_json_bytes(
|
||||
tmp_path, json_rte_table, binary_type
|
||||
):
|
||||
source = pa.table(
|
||||
{"id": [1, 2], "j": pa.array([b'{"k": 9}', b'{"k": 2}'], type=binary_type)}
|
||||
)
|
||||
with pytest.raises(
|
||||
ValueError, match="Column 'j' requires JSON text or an explicit JSON type"
|
||||
):
|
||||
(
|
||||
json_rte_table.merge_insert("id")
|
||||
.when_matched_update_all()
|
||||
.when_not_matched_insert_all()
|
||||
.execute(source)
|
||||
)
|
||||
|
||||
json_rte_table.close_rte_writers()
|
||||
reopened = lancedb.connect(tmp_path).open_table("json_rte")
|
||||
assert reopened.search().to_list() == [{"id": 1, "j": '{"k":1}'}]
|
||||
|
||||
|
||||
def test_rte_merge_insert_rejects_invalid_json_before_writing(tmp_path, json_rte_table):
|
||||
source = pa.table({"id": [1, 2], "j": ['{"k": 9}', "invalid JSON"]})
|
||||
with pytest.raises(RuntimeError, match="Failed to encode JSON in field 'j'"):
|
||||
(
|
||||
json_rte_table.merge_insert("id")
|
||||
.when_matched_update_all()
|
||||
.when_not_matched_insert_all()
|
||||
.execute(source.to_reader(max_chunksize=1))
|
||||
)
|
||||
|
||||
json_rte_table.close_rte_writers()
|
||||
reopened = lancedb.connect(tmp_path).open_table("json_rte")
|
||||
assert reopened.search().to_list() == [{"id": 1, "j": '{"k":1}'}]
|
||||
|
||||
|
||||
def test_lsm_merge_insert_identity(tmp_path):
|
||||
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0))
|
||||
table = db.create_table("t", _region_reader([(1, "us"), (2, "us")]))
|
||||
|
||||
@@ -5032,6 +5032,61 @@ def _json_arrow_table(schema, rows):
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not hasattr(pa, "json_"), reason="requires PyArrow JSON type")
|
||||
def test_overwrite_json_column_uses_arrow_input_schema(tmp_db: DBConnection):
|
||||
schema = pa.schema([pa.field("id", pa.string()), pa.field("j", pa.json_())])
|
||||
table = tmp_db.create_table("t", _json_arrow_table(schema, [("a", '{"k": 1}')]))
|
||||
|
||||
plain = pa.table({"id": ["b", "c"], "j": ["plain text", '{"k": 2}']})
|
||||
table.add(plain, mode="overwrite")
|
||||
table = tmp_db.open_table("t")
|
||||
assert table.schema.field("j").equals(plain.schema.field("j"), check_metadata=True)
|
||||
assert table.search().to_arrow().sort_by("id").to_pylist() == plain.to_pylist()
|
||||
|
||||
table.add(_json_arrow_table(schema, [("d", '{"k": 3}')]), mode="overwrite")
|
||||
table = tmp_db.open_table("t")
|
||||
json_field = table.schema.field("j")
|
||||
assert json_field.type == pa.large_binary()
|
||||
assert (json_field.metadata or {}).get(b"ARROW:extension:name") == b"lance.json"
|
||||
assert table.search().where("json_extract(j, '$.k') = '3'").to_list() == [
|
||||
{"id": "d", "j": '{"k":3}'}
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("operation", ["merge_insert", "sanitized_append"])
|
||||
def test_json_write_rejects_unmarked_binary(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", pa.Table.from_pylist([{"id": 1, "j": '{"k": 1}'}], schema=schema)
|
||||
)
|
||||
source = pa.table(
|
||||
{
|
||||
"id": [1, 2],
|
||||
"j": pa.array([b'{"k": 9}', b'{"k": 2}'], type=pa.large_binary()),
|
||||
}
|
||||
)
|
||||
|
||||
with pytest.raises(
|
||||
ValueError, match="Column 'j' requires JSON text or an explicit JSON type"
|
||||
):
|
||||
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")
|
||||
|
||||
assert tmp_db.open_table("t").search().to_list() == [{"id": 1, "j": '{"k":1}'}]
|
||||
|
||||
|
||||
@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):
|
||||
|
||||
Reference in New Issue
Block a user