Skip to content

Commit 365707e

Browse files
rustyconoverclaude
andcommitted
feat(fixtures): txfix insert/delete/writes(), simple_writable CTAS; 3.3 docs
txfix (vgi docs/writable_tx_fixtures.md, round 2): - items gains items_insert and items_delete next to items_update, all table_only, result modes up to changes, all with has_finalize. A write call is recorded in writes() at init (seq carried through execution storage), counts its rows per batch and is marked finalized at finalize. - INSERT: id/name required, duplicate id (committed, staged, earlier batch, within the batch), qty >= 0 (at commit on ttx); whole batch validated first. - DELETE: rowid = id, missing or repeated rowids are not counted. - ttx stages inserts and tombstones next to updates: read-your-writes, edits of staged inserts, commit applies, refused commit/rollback discard. - items.qty DEFAULT 0 via Table.defaults; scans read one snapshot. - New writes() function; reset() clears it. State file is txfix-v2.db. simple_writable: - catalog_table_create / catalog_table_drop for tables of the attach (INTEGER/BIGINT/VARCHAR/DOUBLE/BOOLEAN, scan + insert, no rowid), reporting created=false for IF NOT EXISTS on an existing table; live catalog version. - Write functions listed table_only (review follow-up; no vgi test calls them directly). write_options parsing keeps only result_mode. Docs: docs/protocol/write-path-3-3.md (normative) for the three wire changes; function-visibility.md now says a client rejects an unknown visibility before any function of that listing is used (listings are decoded lazily), not "at ATTACH" (also the FunctionInfo docstring). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 2bce3e0 commit 365707e

17 files changed

Lines changed: 917 additions & 142 deletions

‎docs/catalog-interface.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ Enum for filtering objects in `schema_contents()`:
169169

170170
### ScanFunctionResult
171171

172-
Result from `table_scan_function_get()` that tells the VGI DuckDB extension which DuckDB function to call to obtain table data. This enables catalogs to delegate scanning to any DuckDB function (e.g., `read_parquet`, `iceberg_scan`, or a custom VGI table function) with appropriate arguments.
172+
Result from `table_scan_function_get()` that tells the VGI DuckDB extension which DuckDB function to call to obtain table data. (On the wire it travels as the one branch of `catalog_table_scan_branches_get`, which the default `table_scan_branches_get` builds from it; protocol 3.3 removed the single-function RPC.) This enables catalogs to delegate scanning to any DuckDB function (e.g., `read_parquet`, `iceberg_scan`, or a custom VGI table function) with appropriate arguments.
173173

174174
| Field | Type | Description |
175175
|-------|------|-------------|

‎docs/protocol/function-visibility.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,10 @@ SQL functions, cluttering `duckdb_functions()` and letting users call write func
2727
It is absent from `duckdb_functions()` and autocomplete and cannot be called, not even fully
2828
qualified. The client uses it only to resolve the functions tables name.
2929

30-
A client MUST reject any other value at ATTACH with an error that names the function. A worker MUST
31-
NOT send another value.
30+
A client MUST reject any other value before any function from that listing is used, with an error
31+
that names the function. (The DuckDB extension decodes function listings lazily, so the rejection
32+
happens when the listing is first read, not necessarily at ATTACH.) A worker MUST NOT send another
33+
value.
3234

3335
## Listing rule
3436

‎docs/protocol/index.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ Each document declares its own status; “proposed” means the contract is stil
99
| [VGI Runtime-Filter Artifacts](vgi-runtime-filter-artifacts.md) | **Normative optional extension, proposed** | Additional requirements for capability-gated advisory runtime-pruning artifacts. Base filter-v2 conformance does not require this extension. |
1010
| [VGI DuckDB Filter Adapter](vgi-duckdb-filter-adapter.md) | **Informative implementation guide, proposed** | DuckDB 1.5 and 2.0 mappings into the normative filter-v2 wire contract. |
1111
| [Function visibility](function-visibility.md) | **Normative** | Protocol 3.3 `FunctionInfo.visibility` (`public` / `table_only`) and the rule that every function a table names is listed. |
12+
| [Write path changes in 3.3](write-path-3-3.md) | **Normative** | Protocol 3.3: `catalog_table_scan_function_get` removed (branches only), `catalog_table_create` returns `created`, and the write-options batch keeps only `result_mode`. |
1213
| [VGI Secrets](vgi-secrets.md) | **Normative** | How a worker asks for client-side secrets, the two-phase bind, and the layout of the secrets batch. |
1314
| [VGI catalog query pushdown](vgi-catalog-query-pushdown-design.md) | **Informative implementation design, proposed** | Updated 2026-10-06: proposed VGI 2.2 query preparation, DuckDB 1.5 explicit execution, and DuckDB 2.0 bound-plan SQL export for automatic pushdown. |
1415
| [Proposed VGI protocol changes for DuckDB 2.0](vgi-protocol-proposed-changes.md) | **Informative design/audit report** | Rationale, migration inventory, implementation status, and deferred protocol decisions. It is not an implementation specification. |

‎docs/protocol/vgi-protocol-proposed-changes.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -488,7 +488,8 @@ ordered lattice `count < rows < changes`, and therefore promises every lower
488488
mode. Duplicate keys and unknown operations or modes are protocol errors.
489489

490490
The serialized `write_options` batch replaces `return_chunks: bool` with the
491-
required `result_mode: utf8`. `count` returns `(count int64 not null)`. `rows`
491+
required `result_mode: utf8` (since protocol 3.3 the batch holds only that column; see
492+
[write path changes in 3.3](write-path-3-3.md)). `count` returns `(count int64 not null)`. `rows`
492493
returns NEW rows for INSERT/UPDATE and OLD rows for DELETE. `changes` returns
493494
two nullable structs, `old` and `new`, each shaped exactly like the table:
494495
INSERT populates only `new`, DELETE only `old`, and UPDATE both. The operation

‎docs/protocol/write-path-3-3.md‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
# Write path changes in protocol 3.3
2+
3+
**Status: normative.** Part of `vgi.v3` / `3.3.0`, together with
4+
[function visibility](function-visibility.md). The protocol version string does not change again:
5+
a 3.3 peer implements both pages.
6+
7+
Protocol 3.3 makes three wire changes to the table write path and to scan discovery. Each one
8+
removes a compatibility path or a field that could never carry information, or adds one bit the
9+
client needs to get `CREATE TABLE ... AS SELECT` right.
10+
11+
## 1. `catalog_table_scan_function_get` is removed
12+
13+
`catalog_table_scan_branches_get` is the only scan-discovery method. It is **required**: every
14+
worker that serves tables answers it, and a single-source table answers with one branch.
15+
16+
- The method `catalog_table_scan_function_get` is no longer part of `vgi.v3`. Its params schema,
17+
its registry entry and its place in the method-inventory hash are gone from every SDK.
18+
- A client MUST NOT fall back to another method when a worker answers `catalog_table_scan_branches_get`
19+
with `MethodNotImplemented`. That answer is a protocol error naming the worker and the table.
20+
(Before 3.3 the DuckDB extension retried the single-function method and wrapped its answer as
21+
one branch; every worker that needed that fallback predates 3.1 and fails the 3.3 version check
22+
anyway.)
23+
- The inlined `TableInfo.scan_function` is unchanged.
24+
25+
SDK authoring APIs are not part of the wire. In vgi-python a catalog still implements
26+
`CatalogInterface.table_scan_function_get`; the default `table_scan_branches_get` wraps its result as
27+
a one-branch `ScanBranchesResult`. `Client.table_scan_function_get` reads the single function branch
28+
of `catalog_table_scan_branches_get` and raises `CatalogClientError` for a table with any other number
29+
of branches.
30+
31+
## 2. `catalog_table_create` returns `created`
32+
33+
The result of `catalog_table_create` (until 3.2: no result) is one record:
34+
35+
| Field | Arrow type | Meaning |
36+
|---|---|---|
37+
| `created` | `bool`, not null | `true` when this call created the table; `false` when the request's `on_conflict` was `IGNORE` (`CREATE TABLE IF NOT EXISTS`) and a table of that name already existed |
38+
39+
- A worker MUST return `false` only for `IGNORE` on an existing table, and MUST then leave that
40+
table exactly as it was (columns, constraints and rows).
41+
- `REPLACE` that replaces an existing table returns `true`: the call created the new table.
42+
- `ERROR` on an existing name fails the call; there is no result.
43+
- The record carries no `TableInfo`. A client that needs the table's description reads it with
44+
`catalog_table_get` as before.
45+
46+
The client uses `created` for `CREATE TABLE [IF NOT EXISTS] ... AS SELECT`: when it is `false`,
47+
the statement inserts nothing (DuckDB's semantics for native tables); before 3.3 the DuckDB
48+
extension appended the query's rows to the existing table. When a CTAS fails after `created = true`
49+
on a non-transactional attach, the extension drops the table again (best effort). `CREATE OR REPLACE
50+
TABLE ... AS` cannot restore the replaced table if the statement then fails.
51+
52+
In vgi-python, `CatalogInterface.table_create` returns `False` for "already existed" and `True`
53+
or `None` (the historical return) for "created"; the worker sends `TableCreateResponse`.
54+
`Client.table_create` returns the flag.
55+
56+
## 3. The write-options batch keeps only `result_mode`
57+
58+
Every write function call (insert, update, delete) receives the `write_options` named argument: a
59+
serialized one-row Arrow batch. In 3.3 its schema is exactly:
60+
61+
| Column | Arrow type | Values |
62+
|---|---|---|
63+
| `result_mode` | `utf8`, not null | `count`, `rows` or `changes` (see `write_result_modes`) |
64+
65+
The former `on_conflict: utf8` and `on_conflict_columns: list<utf8>` columns are removed. DuckDB's
66+
binder rewrites every `INSERT ... ON CONFLICT` (`DO NOTHING`, `DO UPDATE`) and `INSERT OR REPLACE`
67+
into a `MERGE` before a catalog sees the statement, so those columns could only ever say `throw` and
68+
`[]`. A worker MUST ignore any other column it finds in the batch, so a stray column from an older
69+
client is harmless.
70+
71+
`MERGE` and `INSERT ... ON CONFLICT` on a VGI table are emulated by the client with the table's
72+
ordinary write functions: one write call per `INSERT` / `UPDATE` / `DELETE` action of the MERGE, fed
73+
from a scan of the target joined with the source. Workers see only ordinary write calls. The calls
74+
of one MERGE are atomic together only on a transactional attach, and MERGE requires the table to
75+
have a row id.
76+
77+
In vgi-python, `WriteOptions` has only `result_mode`; its `on_conflict` and `on_conflict_columns`
78+
properties remain, deprecated, and always return `"throw"` and `[]`.

‎mkdocs.yml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,7 @@ nav:
146146
- "Partition distribution (normative)": protocol/partition-distribution.md
147147
- "Filtered scan planning (normative)": protocol/scan-planning.md
148148
- "Function visibility (normative)": protocol/function-visibility.md
149+
- "Write path changes in 3.3 (normative)": protocol/write-path-3-3.md
149150
- "Filter Encoding v2 (normative, proposed)": protocol/vgi-filter-encoding-v2-spec.md
150151
- "Runtime-filter artifacts (optional extension)": protocol/vgi-runtime-filter-artifacts.md
151152
- "Opaque values: sealing (normative)": protocol/vgi-opaque-data-sealing.md

‎tests/catalog/test_declarative.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -240,7 +240,7 @@ def test_function_backed_table_inlines_scan_function(self) -> None:
240240
"""Inline a serialized ScanFunctionResult on function-backed tables.
241241
242242
The C++ extension reads ``TableInfo.scan_function`` and skips the
243-
per-bind ``catalog_table_scan_function_get`` RPC.
243+
per-bind ``catalog_table_scan_branches_get`` RPC.
244244
"""
245245
from vgi_rpc.utils import deserialize_record_batch
246246

@@ -381,7 +381,7 @@ def test_explicit_columns_table_omits_scan_function(self) -> None:
381381
"""Leave scan_function null for explicit-columns tables.
382382
383383
These tables have no declarative ``function=...`` so the C++ extension
384-
falls back to ``catalog_table_scan_function_get`` — which the worker
384+
asks ``catalog_table_scan_branches_get`` — which the worker
385385
may resolve via custom logic (e.g. ``read_parquet`` against S3).
386386
"""
387387
cols = pa.schema([pa.field("id", pa.int64())])

‎tests/catalog/test_function_visibility.py‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -280,11 +280,13 @@ def test_expose_scan_requires_a_function() -> None:
280280

281281

282282
def test_txfix_fixture_contract() -> None:
283-
"""The txfix fixture: items_scan and items_update hidden, labels_scan exposed."""
283+
"""The txfix fixture: items_scan and its three write functions hidden, labels_scan exposed."""
284284
from vgi._test_fixtures.writable_tx import TxfixCatalog
285285

286+
hidden = {"items_scan", "items_insert", "items_update", "items_delete"}
286287
listing = _listing(TxfixCatalog(), ["main"])
287-
assert listing["items_scan"] == FUNCTION_VISIBILITY_TABLE_ONLY
288-
assert listing["items_update"] == FUNCTION_VISIBILITY_TABLE_ONLY
288+
for name in hidden:
289+
assert listing[name] == FUNCTION_VISIBILITY_TABLE_ONLY
289290
assert listing["labels_scan"] is None
290-
assert {name for name, vis in listing.items() if vis is not None} == {"items_scan", "items_update"}
291+
assert listing["writes"] is None
292+
assert {name for name, vis in listing.items() if vis is not None} == hidden

‎tests/catalog/test_serialization.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,7 @@ def test_inlined_scan_function_round_trip(self) -> None:
292292
"""``scan_function`` IPC bytes round-trip through TableInfo serialize/deserialize.
293293
294294
The C++ extension reads this field (when populated) and skips the
295-
per-bind ``catalog_table_scan_function_get`` RPC.
295+
per-bind ``catalog_table_scan_branches_get`` RPC.
296296
"""
297297
columns_schema = schema(id=pa.int64())
298298
columns_bytes = SerializedSchema(columns_schema.serialize().to_pybytes())
Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
# Copyright 2025, 2026 Query Farm LLC - https://query.farm
2+
# ruff: noqa: D103
3+
4+
"""The ``simple_writable`` fixture's created tables (protocol 3.3 CTAS contract).
5+
6+
Mirrors what ``vgi/test/sql/integration/simple_writable/ctas*.test`` need from the
7+
fixture (``docs/writable_tx_fixtures.md``, "simple_writable: created tables"):
8+
``catalog_table_create`` reports ``created`` (false for IF NOT EXISTS on an
9+
existing table, which stays unchanged), created tables scan and insert,
10+
``catalog_table_drop`` removes them, and the write functions are table_only.
11+
"""
12+
13+
from __future__ import annotations
14+
15+
import sys
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.arguments import Arguments
23+
from vgi.catalog import FUNCTION_VISIBILITY_TABLE_ONLY, OnConflict, SchemaObjectType, SerializedSchema
24+
from vgi.client.client import Client
25+
26+
_WORKER = f"{sys.executable} -m vgi._test_fixtures.simple_writable"
27+
_COLUMNS = pa.schema(
28+
[
29+
("i", pa.int32()),
30+
("b", pa.int64()),
31+
("v", pa.string()),
32+
("d", pa.float64()),
33+
("f", pa.bool_()),
34+
]
35+
)
36+
37+
38+
@pytest.fixture
39+
def attached() -> Any:
40+
with Client(_WORKER, pool=None) as client:
41+
result = client.catalog_attach(
42+
name="simple_writable", options={}, data_version_spec=None, implementation_version=None
43+
)
44+
with Client(_WORKER, pool=None, attach_opaque_data=result.attach_opaque_data) as client:
45+
yield client, result.attach_opaque_data
46+
47+
48+
def _create(client: Client, attach: Any, name: str, on_conflict: OnConflict, columns: pa.Schema = _COLUMNS) -> bool:
49+
return client.table_create(
50+
attach_opaque_data=attach,
51+
schema_path=["main"],
52+
name=name,
53+
columns=SerializedSchema(columns.serialize().to_pybytes()),
54+
on_conflict=on_conflict,
55+
)
56+
57+
58+
def _insert(client: Client, name: str, rows: list[dict[str, Any]], schema: pa.Schema = _COLUMNS) -> list[Any]:
59+
options = serialize_record_batch_bytes(pa.RecordBatch.from_pylist([{"result_mode": "rows"}]))
60+
out = client.table_in_out_function(
61+
function_name="simple_writable_insert",
62+
schema_path=["main"],
63+
input=iter([pa.RecordBatch.from_pylist(rows, schema=schema)]),
64+
arguments=Arguments(positional=[pa.scalar(name)], named={"write_options": pa.scalar(options)}),
65+
)
66+
return [row for b in out for row in b.to_pylist()]
67+
68+
69+
def _scan(client: Client, name: str) -> list[dict[str, Any]]:
70+
out = client.table_function(
71+
function_name="simple_writable_scan", schema_path=["main"], arguments=Arguments(positional=[pa.scalar(name)])
72+
)
73+
return [row for b in out for row in b.to_pylist()]
74+
75+
76+
def test_created_flag_and_if_not_exists(attached: Any) -> None:
77+
client, attach = attached
78+
version = client.catalog_version(attach_opaque_data=attach)
79+
assert _create(client, attach, "made", OnConflict.ERROR) is True
80+
assert client.catalog_version(attach_opaque_data=attach) > version
81+
row = {"i": 1, "b": 2, "v": "x", "d": 1.5, "f": True}
82+
assert _insert(client, "made", [row]) == [row]
83+
assert _scan(client, "made") == [row]
84+
# IF NOT EXISTS on an existing table: not created, left exactly as it was.
85+
assert _create(client, attach, "made", OnConflict.IGNORE, pa.schema([("other", pa.int64())])) is False
86+
assert _scan(client, "made") == [row]
87+
assert _create(client, attach, "items", OnConflict.IGNORE) is False
88+
with pytest.raises(Exception, match="already exists"):
89+
_create(client, attach, "made", OnConflict.ERROR)
90+
with pytest.raises(Exception, match="already exists"):
91+
_create(client, attach, "items", OnConflict.ERROR)
92+
# REPLACE drops the old table and its rows first.
93+
assert _create(client, attach, "made", OnConflict.REPLACE, pa.schema([("only", pa.int64())])) is True
94+
assert _scan(client, "made") == []
95+
96+
97+
def test_created_table_is_listed_insert_only_without_rowid(attached: Any) -> None:
98+
client, attach = attached
99+
assert _create(client, attach, "Listed", OnConflict.ERROR) is True
100+
info = client.table_get(attach_opaque_data=attach, schema_path=["main"], name="listed")
101+
assert info is not None
102+
assert info.write_result_modes == {"insert": "rows"}
103+
columns = pa.ipc.read_schema(pa.py_buffer(info.columns))
104+
assert columns.names == _COLUMNS.names
105+
tables = client.schema_contents(
106+
attach_opaque_data=attach, transaction_opaque_data=None, path=["main"], type=SchemaObjectType.TABLE
107+
)
108+
assert "listed" in {t.name for t in tables}
109+
110+
111+
def test_drop_created_table(attached: Any) -> None:
112+
client, attach = attached
113+
_create(client, attach, "gone", OnConflict.ERROR)
114+
client.table_drop(attach_opaque_data=attach, schema_path=["main"], name="gone")
115+
assert client.table_get(attach_opaque_data=attach, schema_path=["main"], name="gone") is None
116+
client.table_drop(attach_opaque_data=attach, schema_path=["main"], name="gone", ignore_not_found=True)
117+
with pytest.raises(Exception, match="does not exist"):
118+
client.table_drop(attach_opaque_data=attach, schema_path=["main"], name="gone")
119+
with pytest.raises(Exception, match="cannot be dropped"):
120+
client.table_drop(attach_opaque_data=attach, schema_path=["main"], name="items")
121+
122+
123+
def test_unsupported_column_type_creates_nothing(attached: Any) -> None:
124+
client, attach = attached
125+
with pytest.raises(Exception, match="unsupported Arrow type"):
126+
_create(client, attach, "bad", OnConflict.ERROR, pa.schema([("t", pa.date32())]))
127+
assert client.table_get(attach_opaque_data=attach, schema_path=["main"], name="bad") is None
128+
129+
130+
def test_write_functions_are_table_only(attached: Any) -> None:
131+
client, attach = attached
132+
infos = client.schema_contents(
133+
attach_opaque_data=attach, transaction_opaque_data=None, path=["main"], type=SchemaObjectType.TABLE_FUNCTION
134+
)
135+
visibility = {info.name: info.visibility for info in infos}
136+
for name in (
137+
"simple_writable_insert",
138+
"simple_writable_update",
139+
"simple_writable_delete",
140+
"simple_writable_broken_returning_insert",
141+
):
142+
assert visibility[name] == FUNCTION_VISIBILITY_TABLE_ONLY
143+
assert visibility["simple_writable_scan"] in (None, "public")

0 commit comments

Comments
 (0)