Skip to content

Commit 2bce3e0

Browse files
rustyconoverclaude
andcommitted
feat(protocol): 3.3 write-path wire changes; regenerate codegen
Three wire changes folded into vgi.v3 3.3.0 (version string unchanged): 1. Remove catalog_table_scan_function_get. catalog_table_scan_branches_get is the only scan-discovery RPC. The worker handler and meta-worker route are gone; CatalogInterface.table_scan_function_get stays as the author API behind the default table_scan_branches_get. Client.table_scan_function_get reads the single branch of branches_get, and the client's MethodNotImplemented fallback is deleted. 2. catalog_table_create returns TableCreateResponse(created: bool not null). CatalogInterface.table_create may return False when IF NOT EXISTS found an existing table (None/True = created); the worker validates the value. Client.table_create returns the flag. Fixture catalogs report it. 3. The write-options batch carries only result_mode. WriteOptions keeps on_conflict / on_conflict_columns as deprecated constant properties. Codegen: name tables drop the removed method (Go/Java raw results, the C++ tamper anchor); vgi-java now generates the TableCreateResponse record. Every SDK's generated registry/schemas/contract hash changes accordingly. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 66fcb87 commit 2bce3e0

17 files changed

Lines changed: 329 additions & 141 deletions

‎CHANGELOG.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,28 @@
22

33
## Unreleased
44

5+
### Protocol 3.3: write-path wire changes
6+
7+
Part of `vgi.v3` / `3.3.0` (the version string does not change again).
8+
9+
- **Removed `catalog_table_scan_function_get`.** `catalog_table_scan_branches_get` is the only scan-discovery RPC
10+
and every worker must answer it; the extension no longer falls back. Author code is unaffected:
11+
`CatalogInterface.table_scan_function_get` still works, wrapped as a one-branch result by the default
12+
`table_scan_branches_get`. `Client.table_scan_function_get` now reads the single branch of
13+
`catalog_table_scan_branches_get` (and raises `CatalogClientError` for a multi-branch table); the client's
14+
`MethodNotImplemented` fallback is gone.
15+
- **`catalog_table_create` returns `TableCreateResponse(created: bool not null)`** (new in `vgi.protocol`).
16+
`CatalogInterface.table_create` may return `False` when `on_conflict` is `IGNORE` and the table already
17+
existed; `True` or `None` (the old return) means it was created. The extension uses it so
18+
`CREATE TABLE IF NOT EXISTS ... AS SELECT` no longer appends into an existing table.
19+
`Client.table_create` returns the flag.
20+
- **The write-options batch carries only `result_mode`.** DuckDB rewrites every `INSERT ... ON CONFLICT` /
21+
`INSERT OR REPLACE` into a MERGE before the catalog sees it, so `on_conflict` / `on_conflict_columns` were only
22+
ever `"throw"` / `[]`. `WriteOptions.on_conflict` and `WriteOptions.on_conflict_columns` remain as deprecated
23+
read-only properties with those values; they are no longer constructor arguments.
24+
- Codegen: every SDK's generated registry and schemas drop the removed method and gain the
25+
`catalog_table_create` result; vgi-java gains the generated `TableCreateResponse` record.
26+
527
### Protocol 3.3: table scans and write functions are table-only
628

729
- **Requires the matching DuckDB extension.** The protocol version is now `vgi.v3` / `3.3.0`; peers match on
Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
# Copyright 2025, 2026 Query Farm LLC - https://query.farm
2+
# ruff: noqa: D103
3+
4+
"""Protocol 3.3 write-path wire changes.
5+
6+
1. ``catalog_table_scan_function_get`` is gone; ``catalog_table_scan_branches_get``
7+
is the only scan-discovery method.
8+
2. ``catalog_table_create`` replies ``TableCreateResponse(created: bool not null)``.
9+
3. The write-options batch carries only ``result_mode``.
10+
"""
11+
12+
from __future__ import annotations
13+
14+
import inspect
15+
from types import SimpleNamespace
16+
from typing import Any
17+
18+
import pyarrow as pa
19+
import pytest
20+
from vgi_rpc.utils import serialize_record_batch_bytes
21+
22+
from vgi.catalog.catalog_interface import CatalogInterface, OnConflict, ReadOnlyCatalogInterface
23+
from vgi.client.catalog_mixin import CatalogClientMixin
24+
from vgi.meta_worker import MetaWorker
25+
from vgi.protocol import TableCreateRequest, TableCreateResponse, VgiProtocol
26+
from vgi.worker import Worker
27+
from vgi.write_results import WriteOptions, write_options
28+
29+
SCHEMA = pa.schema([pa.field("id", pa.int64())])
30+
31+
32+
def _create_request(on_conflict: OnConflict = OnConflict.ERROR) -> TableCreateRequest:
33+
return TableCreateRequest(
34+
attach_opaque_data=b"sealed-attach",
35+
schema_path=["main"],
36+
name="t",
37+
columns=SCHEMA.serialize().to_pybytes(),
38+
on_conflict=on_conflict,
39+
constraint_definitions=[],
40+
)
41+
42+
43+
def _worker(monkeypatch: pytest.MonkeyPatch, result: Any) -> tuple[Worker, list[dict[str, Any]]]:
44+
instance = object.__new__(Worker)
45+
calls: list[dict[str, Any]] = []
46+
47+
def table_create(**kwargs: Any) -> Any:
48+
calls.append(kwargs)
49+
return result
50+
51+
provider = SimpleNamespace(table_create=table_create)
52+
monkeypatch.setattr(instance, "_get_catalog", lambda: provider)
53+
monkeypatch.setattr(instance, "_unwrap_attach", lambda envelope: b"provider-attach")
54+
monkeypatch.setattr(instance, "_enrich_catalog_span", lambda **kwargs: None)
55+
monkeypatch.setattr(instance, "_require_dependency_transaction", lambda *args: None)
56+
monkeypatch.setattr(instance, "_validate_column_definition_expressions", lambda *args: None)
57+
monkeypatch.setattr(
58+
instance, "_effective_catalog_capabilities", lambda envelope: SimpleNamespace(read=[], ddl=[], write=[])
59+
)
60+
return instance, calls
61+
62+
63+
# ---------------------------------------------------------------- change 1
64+
65+
66+
def test_scan_function_get_rpc_removed() -> None:
67+
"""No vgi.v3 method, worker handler or meta-worker route for the legacy RPC remains."""
68+
assert not hasattr(VgiProtocol, "catalog_table_scan_function_get")
69+
assert not hasattr(Worker, "catalog_table_scan_function_get")
70+
assert hasattr(VgiProtocol, "catalog_table_scan_branches_get")
71+
assert "catalog_table_scan_function_get" not in inspect.getsource(MetaWorker)
72+
73+
74+
def test_author_scan_function_api_still_backs_branches_get() -> None:
75+
"""Authors keep ``table_scan_function_get``; the base wraps it as one branch."""
76+
for cls in (CatalogInterface, ReadOnlyCatalogInterface):
77+
assert callable(getattr(cls, "table_scan_function_get", None))
78+
assert callable(getattr(cls, "table_scan_branches_get", None))
79+
80+
81+
def test_client_scan_function_get_reads_the_single_branch() -> None:
82+
"""The client's ``table_scan_function_get`` asks branches_get, never the removed RPC."""
83+
source = inspect.getsource(CatalogClientMixin)
84+
assert "proxy.catalog_table_scan_function_get" not in source
85+
86+
87+
# ---------------------------------------------------------------- change 2
88+
89+
90+
def test_table_create_response_schema() -> None:
91+
field = TableCreateResponse.ARROW_SCHEMA.field("created")
92+
assert field.type == pa.bool_()
93+
assert not field.nullable
94+
assert TableCreateResponse.ARROW_SCHEMA.names == ["created"]
95+
96+
97+
def test_create_method_returns_table_create_response() -> None:
98+
hints = inspect.signature(VgiProtocol.catalog_table_create).return_annotation
99+
assert hints in (TableCreateResponse, "TableCreateResponse")
100+
101+
102+
@pytest.mark.parametrize(
103+
("returned", "created"),
104+
[(None, True), (True, True), (False, False)],
105+
)
106+
def test_worker_reports_created(monkeypatch: pytest.MonkeyPatch, returned: Any, created: bool) -> None:
107+
instance, calls = _worker(monkeypatch, returned)
108+
response = instance.catalog_table_create(_create_request(OnConflict.IGNORE))
109+
assert response == TableCreateResponse(created=created)
110+
assert calls[0]["on_conflict"] == OnConflict.IGNORE
111+
112+
113+
def test_worker_rejects_non_bool_create_result(monkeypatch: pytest.MonkeyPatch) -> None:
114+
instance, _ = _worker(monkeypatch, "yes")
115+
with pytest.raises(TypeError, match="table_create must return bool or None"):
116+
instance.catalog_table_create(_create_request())
117+
118+
119+
def test_table_create_response_round_trips() -> None:
120+
for value in (True, False):
121+
response = TableCreateResponse(created=value)
122+
assert TableCreateResponse.deserialize_from_bytes(response.serialize_to_bytes()) == response
123+
124+
125+
# ---------------------------------------------------------------- change 3
126+
127+
128+
def _call(raw: bytes) -> SimpleNamespace:
129+
from vgi.arguments import Arguments
130+
131+
return SimpleNamespace(arguments=Arguments(named={"write_options": pa.scalar(raw)}))
132+
133+
134+
def test_write_options_has_only_result_mode() -> None:
135+
raw = serialize_record_batch_bytes(pa.RecordBatch.from_pylist([{"result_mode": "rows"}]))
136+
options = write_options(_call(raw))
137+
assert options == WriteOptions(result_mode="rows")
138+
# Deprecated accessors keep the only values DuckDB ever sent.
139+
assert options.on_conflict == "throw"
140+
assert options.on_conflict_columns == []
141+
with pytest.raises(TypeError):
142+
WriteOptions(result_mode="count", on_conflict="nothing") # type: ignore[call-arg]
143+
144+
145+
def test_write_options_ignores_removed_columns_from_an_old_peer() -> None:
146+
raw = serialize_record_batch_bytes(
147+
pa.RecordBatch.from_pylist([{"result_mode": "count", "on_conflict": "nothing", "on_conflict_columns": ["id"]}])
148+
)
149+
options = write_options(_call(raw))
150+
assert options.result_mode == "count"
151+
assert options.on_conflict == "throw"

‎tests/client/test_scan_branches_client.py‎

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,11 @@
88
unrelated code comment ("skip the subprocess branch"). A multi-branch table
99
was therefore invisible to any non-DuckDB caller, not just unsupported by a
1010
higher-level connector. Exercised against `data.multi_branch_numbers` (two
11-
`sequence(50)` arms — `vgi/_test_fixtures/worker.py`) and, for the legacy
12-
fallback, `data.numbers` (an ordinary single-branch table whose worker only
13-
implements the older `table_scan_function_get`).
11+
`sequence(50)` arms — `vgi/_test_fixtures/worker.py`) and `data.numbers` (an
12+
ordinary single-branch table whose catalog implements only the author-facing
13+
`table_scan_function_get`, which the base wraps as one branch). Protocol 3.3
14+
removed the `catalog_table_scan_function_get` RPC: the client's
15+
`table_scan_function_get` reads the single branch of `catalog_table_scan_branches_get`.
1416
"""
1517

1618
from __future__ import annotations
@@ -52,8 +54,8 @@ def test_multi_branch_table_returns_all_branches(client: Any) -> None:
5254
assert branch.source_table is None # function branch, not catalog-table
5355

5456

55-
def test_single_branch_table_falls_back_to_legacy_rpc(client: Any) -> None:
56-
"""`data.numbers` only implements `table_scan_function_get` — the fallback wraps it as one branch."""
57+
def test_single_branch_table_is_one_branch(client: Any) -> None:
58+
"""`data.numbers` only implements `table_scan_function_get` — the base wraps it as one branch."""
5759
result = client.table_scan_branches_get(
5860
attach_opaque_data=_attach_opaque(client),
5961
schema_path=DATA,
@@ -68,3 +70,15 @@ def test_single_branch_table_falls_back_to_legacy_rpc(client: Any) -> None:
6870
name="numbers",
6971
).function_name
7072
)
73+
74+
75+
def test_scan_function_get_refuses_multi_branch_table(client: Any) -> None:
76+
"""Without the legacy RPC, `table_scan_function_get` needs exactly one branch."""
77+
from vgi.client.catalog_mixin import CatalogClientError
78+
79+
with pytest.raises(CatalogClientError, match="2 scan branch"):
80+
client.table_scan_function_get(
81+
attach_opaque_data=_attach_opaque(client),
82+
schema_path=DATA,
83+
name="multi_branch_numbers",
84+
)

‎tests/conformance/test_protocol_inventory.py‎

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -154,15 +154,9 @@ class NotExposed:
154154
"catalog_table_create": ("table_create",),
155155
"catalog_table_constraints_apply": ("table_constraints_apply",),
156156
"catalog_table_drop": ("table_drop",),
157-
"catalog_table_scan_function_get": ("table_scan_function_get",),
158-
"catalog_table_scan_branches_get": NotExposed(
159-
reason=(
160-
"DuckDB-only multi-branch scan planning. The C++ extension fetches "
161-
"scan branches to route reads/writes across heterogeneous sources; "
162-
"non-DuckDB clients scan via catalog_table_scan_function_get. Covered "
163-
"by C++ integration/catalog/multi_branch_*.test."
164-
)
165-
),
157+
# Protocol 3.3: the only scan-discovery RPC (catalog_table_scan_function_get was
158+
# removed); the client's table_scan_function_get reads its single branch.
159+
"catalog_table_scan_branches_get": ("table_scan_branches_get", "table_scan_function_get"),
166160
"catalog_table_column_statistics_get": NotExposed(
167161
reason=(
168162
"DuckDB-only planner hint. Column stats feed the query optimizer. "

‎tests/test_write_results_helpers.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,11 +147,15 @@ def test_write_options_decodes_every_field() -> None:
147147
"""Write options decodes every field."""
148148
raw = _options_bytes(result_mode="rows", on_conflict="update", on_conflict_columns=["id"])
149149
call = _bind_call({"write_options": pa.scalar(raw)})
150-
expected = WriteOptions(result_mode="rows", on_conflict="update", on_conflict_columns=["id"])
150+
# Protocol 3.3 removed on_conflict/on_conflict_columns; a stray column is ignored
151+
# and the deprecated accessors keep their constant values.
152+
expected = WriteOptions(result_mode="rows")
151153
# A BindRequest-like object, BindParams-like (bind_call) and ProcessParams-like (init_call.bind_call).
152154
assert write_options(call) == expected
153155
assert write_options(SimpleNamespace(bind_call=call)) == expected
154156
assert write_options(SimpleNamespace(bind_call=None, init_call=SimpleNamespace(bind_call=call))) == expected
157+
assert expected.on_conflict == "throw"
158+
assert expected.on_conflict_columns == []
155159

156160

157161
def test_write_options_partial_and_invalid() -> None:

‎vgi/_test_fixtures/catalog.py‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -525,8 +525,8 @@ def table_create(
525525
tags: dict[str, str] | None = None,
526526
options: TypedValueBatch | None = None,
527527
layout: TableLayout | None = None,
528-
) -> None:
529-
"""Create a new table."""
528+
) -> bool:
529+
"""Create a new table; ``False`` when IF NOT EXISTS found one (protocol 3.3)."""
530530
if constraint_definitions:
531531
raise NotImplementedError(
532532
"CREATE TABLE with NOT NULL/PRIMARY KEY/UNIQUE/CHECK/FOREIGN KEY constraints is unsupported: "
@@ -541,7 +541,7 @@ def table_create(
541541
msg = f"Table {name!r} already exists in schema {schema_path!r}"
542542
raise ValueError(msg)
543543
if on_conflict == OnConflict.IGNORE:
544-
return
544+
return False
545545
# REPLACE: fall through to create
546546

547547
schema_data.tables[name] = TableData(
@@ -555,6 +555,7 @@ def table_create(
555555
)
556556
)
557557
self._increment_version(attach_opaque_data)
558+
return True
558559

559560
def table_drop(
560561
self,

‎vgi/_test_fixtures/writable/worker.py‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -310,7 +310,7 @@ def table_create(
310310
tags: dict[str, str] | None = None,
311311
options: TypedValueBatch | None = None,
312312
layout: TableLayout | None = None,
313-
) -> None:
313+
) -> bool:
314314
"""Create a new table in the transactor's DuckDB database.
315315
316316
Builds CREATE TABLE DDL from column definitions and constraints.
@@ -325,6 +325,17 @@ def table_create(
325325
# Deserialize columns schema
326326
col_schema = pa.ipc.read_schema(pa.BufferReader(columns)) # type: ignore[arg-type]
327327

328+
if on_conflict == OnConflict.IGNORE and (
329+
self.table_get(
330+
attach_opaque_data=attach_opaque_data,
331+
transaction_opaque_data=transaction_opaque_data,
332+
schema_path=schema_path,
333+
name=name,
334+
)
335+
is not None
336+
):
337+
# Protocol 3.3: report "not created" so CTAS IF NOT EXISTS inserts nothing.
338+
return False
328339
if_not_exists = " IF NOT EXISTS" if on_conflict == OnConflict.IGNORE else ""
329340

330341
# Build column definitions (including defaults from Arrow field metadata)
@@ -340,6 +351,7 @@ def table_create(
340351
ddl = f"CREATE TABLE{if_not_exists} {_qn(schema_path, name)} (\n {columns_sql}\n);"
341352
self._execute_ddl(attach_opaque_data, transaction_opaque_data, ddl)
342353
logger.info("table_create: %s (on_conflict=%s)", name, on_conflict.value)
354+
return True
343355

344356
def table_drop(
345357
self,

‎vgi/catalog/catalog_interface.py‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2445,10 +2445,16 @@ def table_create(
24452445
tags: dict[str, str] | None = None,
24462446
options: TypedValueBatch | None = None,
24472447
layout: TableLayout | None = None,
2448-
) -> None:
2448+
) -> bool | None:
24492449
"""Create a new table with the given name and schema.
24502450
24512451
New metadata, typed options and layout require their selected profiles.
2452+
2453+
Return ``False`` when ``on_conflict`` is ``IGNORE`` and the table already
2454+
existed (it must be left unchanged); ``True`` or ``None`` means this call
2455+
created it. The worker reports this as ``TableCreateResponse.created``
2456+
(protocol 3.3), which keeps ``CREATE TABLE IF NOT EXISTS ... AS SELECT``
2457+
from appending into an existing table.
24522458
"""
24532459
raise UnsupportedOperationError("Table create not implemented.")
24542460

0 commit comments

Comments
 (0)