3131import sys
3232import threading
3333from dataclasses import dataclass
34- from typing import Any
34+ from typing import Any , cast
3535
3636import pyarrow as pa
3737from vgi_rpc .rpc import OutputCollector
@@ -270,12 +270,43 @@ def _next_int_rowid(spec: TableSpec) -> int:
270270# ---------------------------------------------------------------------------
271271
272272
273+ def _all_nullable_type (t : pa .DataType ) -> pa .DataType :
274+ """``t`` with every nested child field nullable (map keys stay non-nullable)."""
275+ if isinstance (t , pa .MapType ):
276+ return cast (pa .DataType , pa .map_ (t .key_type , _all_nullable_type (t .item_type ), t .keys_sorted ))
277+ if isinstance (t , pa .StructType ):
278+ return cast (pa .DataType , pa .struct ([_all_nullable_field (t .field (i )) for i in range (t .num_fields )]))
279+ if isinstance (t , pa .LargeListType ):
280+ return cast (pa .DataType , pa .large_list (_all_nullable_field (t .value_field )))
281+ if isinstance (t , pa .FixedSizeListType ):
282+ return cast (pa .DataType , pa .list_ (_all_nullable_field (t .value_field ), t .list_size ))
283+ if isinstance (t , pa .ListType ):
284+ return cast (pa .DataType , pa .list_ (_all_nullable_field (t .value_field )))
285+ return t
286+
287+
288+ def _all_nullable_field (f : pa .Field [Any ]) -> pa .Field [Any ]:
289+ return pa .field (f .name , _all_nullable_type (f .type ), nullable = True , metadata = f .metadata )
290+
291+
292+ def _write_input_schema (declared : pa .Schema ) -> pa .Schema :
293+ """What the extension sends a write function: the declared types, every field nullable.
294+
295+ The extension marks every write-input field nullable at every level (vgi
296+ src/storage/vgi_physical_write.cpp NullableWriteInputSchema): NOT NULL is the
297+ worker's to enforce (TypedValueBatch below), and a NULL in a non-nullable
298+ field would make an invalid Arrow batch.
299+ """
300+ return pa .schema ([_all_nullable_field (f ) for f in declared ], metadata = cast (Any , declared .metadata ))
301+
302+
273303def _strict_assert_schema (label : str , actual : pa .Schema , expected : pa .Schema ) -> None :
274304 """Hard-fail if ``actual`` doesn't bit-for-bit equal ``expected``.
275305
276306 The vgi C++ ``ReconcileBatchToSchema`` helper is what makes these
277- schemas equal — DuckDB on its own emits batches with all-nullable
278- fields, ``timestamp[us, tz=session]`` for TZ timestamps, and so on.
307+ schemas equal — DuckDB on its own emits ``timestamp[us, tz=session]``
308+ for TZ timestamps, and so on. Write inputs are compared against
309+ ``_write_input_schema`` (declared types, every field nullable).
279310 A mismatch here means reconciliation regressed.
280311 """
281312 if actual .equals (expected , check_metadata = False ):
@@ -341,7 +372,7 @@ def _generate_rowid(spec: TableSpec, payload: dict[str, Any]) -> Any:
341372
342373
343374class SchemaReconcileInsert (TableInOutGenerator [None , None ]):
344- """INSERT handler — asserts the input batch matches USER_SCHEMA exactly ."""
375+ """INSERT handler — asserts the input batch is USER_SCHEMA with every field nullable ."""
345376
346377 class Meta :
347378 name = "schema_reconcile_insert"
@@ -361,7 +392,7 @@ def process(
361392 ) -> None :
362393 assert params .init_call is not None
363394 spec = _spec_from_args (params .init_call .bind_call .arguments .positional )
364- _strict_assert_schema (f"INSERT[{ spec .name } ]" , batch .schema , USER_SCHEMA )
395+ _strict_assert_schema (f"INSERT[{ spec .name } ]" , batch .schema , _write_input_schema ( USER_SCHEMA ) )
365396 names = [f .name for f in USER_SCHEMA ]
366397 for i in range (batch .num_rows ):
367398 payload = _row_to_dict (batch , i , names )
@@ -400,7 +431,7 @@ def process(
400431 raise ValueError (f"[schema_reconcile] UPDATE[{ spec .name } ] missing rowid column; got: { cols } " )
401432 full = spec .table_schema
402433 for f in batch .schema :
403- expected = full .field (full .get_field_index (f .name ))
434+ expected = _all_nullable_field ( full .field (full .get_field_index (f .name ) ))
404435 if f .nullable != expected .nullable or not f .type .equals (expected .type ):
405436 raise ValueError (
406437 f"[schema_reconcile] UPDATE[{ spec .name } ] field { f .name !r} mismatch "
@@ -440,7 +471,7 @@ def process(
440471 ) -> None :
441472 assert params .init_call is not None
442473 spec = _spec_from_args (params .init_call .bind_call .arguments .positional )
443- _strict_assert_schema (f"DELETE[{ spec .name } ]" , batch .schema , spec .delete_input_schema )
474+ _strict_assert_schema (f"DELETE[{ spec .name } ]" , batch .schema , _write_input_schema ( spec .delete_input_schema ) )
444475 n = 0
445476 for i in range (batch .num_rows ):
446477 rid = batch .column ("rowid" )[i ].as_py ()
0 commit comments