Skip to content

Commit 0fd0a4e

Browse files
committed
feat: define protocol 3.1 partition distribution
1 parent c1e6c36 commit 0fd0a4e

13 files changed

Lines changed: 373 additions & 38 deletions

‎docs/catalog_publication.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Batched catalog contents and reusable publications
22

3-
VGI wire revision **3.0.0** uses the `vgi.v3` route and retains
3+
VGI wire revision **3.1.0** uses the `vgi.v3` route and retains
44
`catalog_contents` with six catalog-wide Arrow IPC streams: schemas, tables,
55
views, functions, macros and indexes. Each stream can contain multiple batches.
66
Null means an empty category. Function and macro subtype fields remain intact.

‎docs/protocol/macro-contract.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ Status: development contract for the combined successor protocol. The wire
44
records use one canonical overload-family representation while builds remain
55
on DuckDB 1.5. Native SQL CREATE MACRO remains unsupported; creation through
66
the catalog API and native discovery/execution are distinct paths.
7-
The breaking successor uses `vgi.v3` / `3.0.0`; it is incompatible with
7+
The breaking successor uses `vgi.v3` / `3.1.0`; it is incompatible with
88
released `vgi.v2` implementations.
99

1010
The [October 23 combined review](shared-catalog-values.md#combined-protocol-review--october-23-2026)
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
# Partition distribution metadata
2+
3+
Protocol 3.1 describes scan distribution with two independent facts:
4+
5+
- `PlanResponse.key_grouping` says that every row produced by one split has one
6+
exact transformed key tuple. This is the contract needed by Spark's
7+
key-grouped input partitions.
8+
- `PlanResponse.range_partitioning` says that splits belong to exact, ordered
9+
ranges separated by shared split points. This is the contract needed by
10+
DataFusion's range partitioning.
11+
12+
Neither field implies the other. `sort_order` continues to describe order
13+
*within* a split, while `ScanSplit.column_bounds` contains pruning statistics
14+
only. A client must not promote bounds, Hive-style directory values, or the
15+
deprecated protocol-2 `partitioning` field into an exact distribution claim.
16+
17+
## Transform specification
18+
19+
A `TransformSpec` contains:
20+
21+
- `id`: a versioned registry name such as `vgi.identity/1` or
22+
`iceberg.bucket/1`;
23+
- `inputs`: one or more serialized `FieldPath` records; and
24+
- optional `parameters`: an Arrow IPC record batch containing exactly one row.
25+
26+
`FieldPath.components` preserves identifier boundaries. For example,
27+
`["customer", "region.code"]` means nested field `region.code` under
28+
`customer`; it is not the three-part dotted path `customer.region.code`.
29+
30+
The one-row parameter batch may have any number of named, typed columns. This
31+
allows a transform to carry, for example, an `int32` bucket count, a string
32+
calendar name, and a Boolean mode flag without adding transform-specific wire
33+
fields. Parameter names, Arrow types, null values, and transform-registry
34+
semantics are all part of the transform identity. Arbitrary recursive
35+
expressions are deliberately outside this contract.
36+
37+
The initial portable profile contains only `vgi.identity/1`, with exactly one
38+
input and no parameter batch. An adapter that does not implement a transform's
39+
registered semantics exactly must report unknown partitioning. It must not
40+
approximate another engine's bucket, truncate, hash, collation, or time-zone
41+
rules.
42+
43+
## Exact key grouping
44+
45+
`KeyGrouping.keys` is the ordered tuple of transforms. When it is present:
46+
47+
1. every ordinary split has a `key_value` batch;
48+
2. that batch has exactly one row and one column per transform, in key order;
49+
3. each column has the registered output type of its transform; and
50+
4. every row emitted by the split evaluates to that tuple under null-safe
51+
equality.
52+
53+
Several splits may have the same key. A split without a key, or a key whose
54+
shape or type is invalid, makes the grouping claim unusable. The no-split
55+
sentinel does not carry a grouping claim.
56+
57+
Spark maps a supported grouping to `KeyGroupedPartitioning`; every physical
58+
input partition exposes its tuple through `HasPartitionKey`. The current Spark
59+
adapter accepts only the portable identity profile. Mixed scan branches must
60+
advertise the same grouping, otherwise the complete scan reports unknown
61+
partitioning.
62+
63+
The DuckDB 2 adapter uses the same exact tuple for
64+
`SINGLE_VALUE_PARTITIONS`, but only when the function has already declared
65+
that optimization at bind time and its annotated partition fields exactly
66+
match the identity-key sequence. The plan metadata cannot independently opt a
67+
function into the optimization because it arrives after physical planning.
68+
Workers without a supported grouping continue to use the existing per-batch
69+
`vgi_partition_values` metadata path.
70+
71+
## Exact range partitioning
72+
73+
`RangePartitioning.keys` is an ordered tuple of `RangeKey` records. Each range
74+
key combines a transform with an ascending/descending direction and a null
75+
ordering. `split_points` has one column per range key, using each transform's
76+
output type.
77+
78+
For `N` split-point rows there are `N + 1` ranges. The rows must be strictly
79+
ordered by the declared lexicographic comparator. A value equal to split point
80+
`i` belongs to range `i + 1`; ranges are therefore half-open at their lower
81+
boundary except for the first range. Each ordinary split supplies a zero-based
82+
`range_index`, and all of its output belongs to that exact range. More than one
83+
split may share a range, and a range may contain no splits.
84+
85+
DataFusion maps this metadata to physical `RangePartitioning` only when it can
86+
preserve one output partition per range within the requested parallelism and
87+
worker cap. It currently accepts only top-level `vgi.identity/1` keys whose
88+
split-point Arrow types match the output schema. Otherwise it retains the
89+
splits but reports `UnknownPartitioning`.
90+
91+
## Pagination and compatibility
92+
93+
Distribution metadata is a property of the complete plan. Every page reached
94+
through `next_cursors` must repeat byte-identical `key_grouping` and
95+
`range_partitioning` values, and the split-local values on that page must obey
96+
them. A client must discard the distribution claim or reject a malformed plan
97+
if pages disagree; it must never combine inconsistent claims.
98+
99+
Protocol 3.1 producers should use `key_grouping`, `range_partitioning`,
100+
`key_value`, `range_index`, and `column_bounds`. The deprecated
101+
`PlanResponse.partitioning` and `ScanSplit.partition_bounds` fields remain on
102+
the wire for protocol-2 compatibility, but do not carry the exact semantics
103+
required by the new engine mappings.

‎docs/protocol/projection-expressions.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# Optional scalar projection expressions
22

33
This contract is part of the combined, unpublished DuckDB 2.0 protocol
4-
transition, identified as `vgi.v3` / `3.0.0`. It can be implemented and tested
4+
transition, identified as `vgi.v3` / `3.1.0`. It can be implemented and tested
55
while the native adapter still builds against DuckDB 1.5. The successor is
66
unpublished and still requires coordinated release qualification.
77

‎docs/protocol/shared-catalog-values.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ records and bounded reference behavior on the DuckDB 2.0 preparation branch.
55
The combined-design section distinguishes implemented SQL/constraint records
66
and reference proofs from the remaining public API and execution work. Both are
77
part of one combined successor contract. Published main now uses `vgi.v2` / `2.2.0`. The
8-
unpublished successor now uses `vgi.v3` / `3.0.0` for its incompatible changes.
8+
unpublished successor now uses `vgi.v3` / `3.1.0` for its incompatible changes.
99
This selects the protocol identity; final coordinated release qualification remains open. The development snapshot
1010
carries typed schema/table options,
1111
layouts, raw column mutation paths, and capability negotiation. See the

‎docs/protocol/vgi-catalog-query-pushdown-design.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ and automatic pushdown remain read-only.
1313
The implementation belongs to the **combined successor protocol release**, alongside the
1414
catalog/type changes in the [manifest](duckdb-2.0-manifest.json). It does not reserve a separate
1515
minor release. Published main now uses `vgi.v2` / `2.2.0`; the prepared successor
16-
now uses `vgi.v3` / `3.0.0`. Separate versioned endpoints/processes, draining old
16+
now uses `vgi.v3` / `3.1.0`. Separate versioned endpoints/processes, draining old
1717
sessions, and reattaching/repreparing remain the migration policy. Coordinated
1818
release qualification is still required. See the
1919
[latest-main integration checkpoint](duckdb-2.0-main-integration-2026-10-24.md).
@@ -1361,7 +1361,7 @@ universal speedup percentage; establish budgets from these measurements before d
13611361
## 13. Compatibility, alternatives, and launch gates
13621362

13631363
Published main now uses **2.2.0** under **`vgi.v2`**. The prepared Python SDK, other SDKs and extension
1364-
use **3.0.0** under **`vgi.v3`**.
1364+
use **3.1.0** under **`vgi.v3`**.
13651365
The query capability, preparation/release RPCs and parameter metadata join the combined breaking
13661366
successor contract. The selected major version and routing/migration policy apply to that package;
13671367
do not publish this development surface as a compatible 2.2.0 update.

‎mkdocs.yml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,7 @@ nav:
143143
- Argument Serialization: argument-serialization.md
144144
- Protocol:
145145
- protocol/index.md
146+
- "Partition distribution (normative)": protocol/partition-distribution.md
146147
- "Filter Encoding v2 (normative, proposed)": protocol/vgi-filter-encoding-v2-spec.md
147148
- "Runtime-filter artifacts (optional extension)": protocol/vgi-runtime-filter-artifacts.md
148149
- "Opaque values: sealing (normative)": protocol/vgi-opaque-data-sealing.md

‎tests/conformance/test_protocol_version.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,15 +32,15 @@
3232

3333
def test_client_protocol_version_is_canonical() -> None:
3434
"""Sanity-check the constants this test reasons about haven't drifted apart."""
35-
assert CLIENT_PROTOCOL_VERSION == "3.0.0"
35+
assert CLIENT_PROTOCOL_VERSION == "3.1.0"
3636
assert VgiProtocol.protocol_name == "vgi.v3"
3737
# The fixture must be a genuine mismatch in the major/minor that the
3838
# framework compares; a patch-only difference would (correctly) pass.
3939
assert BAD_PROTOCOL_VERSION.split(".")[:2] != CLIENT_PROTOCOL_VERSION.split(".")[:2]
4040

4141

4242
def test_mismatched_worker_protocol_version_raises() -> None:
43-
"""A worker enforcing 99.0.0 must reject the 3.0.0 client at dispatch."""
43+
"""A worker enforcing 99.0.0 must reject the 3.1.0 client at dispatch."""
4444
with Client("vgi-fixture-bad-protocol-worker") as client, pytest.raises(ClientError) as exc_info:
4545
list(
4646
client.table_function(
@@ -55,5 +55,5 @@ def test_mismatched_worker_protocol_version_raises() -> None:
5555
assert "protocol_version mismatch" in message
5656
assert CLIENT_PROTOCOL_VERSION in message
5757
assert BAD_PROTOCOL_VERSION in message
58-
# Directional hint: the client (3.0.0) is older than the worker (99.0.0).
58+
# Directional hint: the client (3.1.0) is older than the worker (99.0.0).
5959
assert "upgrade the VGI extension/client" in message
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
# Copyright 2025, 2026 Query Farm LLC - https://query.farm
2+
3+
"""Protocol-3 partition-distribution record tests."""
4+
5+
from __future__ import annotations
6+
7+
import pyarrow as pa
8+
import pytest
9+
10+
from vgi.protocol import (
11+
FieldPath,
12+
KeyGrouping,
13+
OrderByDirection,
14+
OrderByNullOrder,
15+
PartitionTransform,
16+
PlanResponse,
17+
RangeKey,
18+
RangePartitioning,
19+
ScanSplit,
20+
TransformSpec,
21+
)
22+
23+
24+
def encoded(value: object) -> bytes:
25+
"""Serialize one Arrow record into its IPC wire bytes."""
26+
return value.serialize_to_bytes() # type: ignore[attr-defined, no-any-return]
27+
28+
29+
def identity(name: str) -> TransformSpec:
30+
"""Build an identity transform over one top-level field."""
31+
return TransformSpec(
32+
id="vgi.identity/1",
33+
inputs=[encoded(FieldPath(components=[name]))],
34+
)
35+
36+
37+
def test_transform_parameters_are_named_typed_and_not_limited_to_one_int64() -> None:
38+
"""Transform parameters retain multiple names and Arrow types."""
39+
parameters = pa.record_batch(
40+
[pa.array([16], type=pa.int32()), pa.array(["murmur3"], type=pa.string()), pa.array([True])],
41+
names=["buckets", "algorithm", "nulls_equal"],
42+
)
43+
transform = TransformSpec(
44+
id="example.bucket/2",
45+
inputs=[encoded(FieldPath(components=["customer", "id"]))],
46+
parameters=parameters,
47+
)
48+
49+
decoded = TransformSpec.deserialize_from_bytes(encoded(transform))
50+
assert decoded.id == "example.bucket/2"
51+
assert decoded.parameters is not None
52+
assert decoded.parameters.equals(parameters)
53+
54+
55+
def test_protocol_2_partition_transform_remains_decodable_during_migration() -> None:
56+
"""Protocol 3.1 retains the deprecated producer-side compatibility type."""
57+
transform = PartitionTransform(column="customer_id", transform="bucket", param=16)
58+
59+
assert PartitionTransform.deserialize_from_bytes(encoded(transform)) == transform
60+
61+
62+
def test_key_grouping_and_range_partitioning_round_trip_independently() -> None:
63+
"""Grouping and range claims coexist without sharing a kind enum."""
64+
transform = identity("event_time")
65+
grouping = KeyGrouping(keys=[encoded(transform)])
66+
range_key = RangeKey(
67+
transform=encoded(transform),
68+
direction=OrderByDirection.ASC,
69+
null_order=OrderByNullOrder.NULLS_LAST,
70+
)
71+
ranges = RangePartitioning(
72+
keys=[encoded(range_key)],
73+
split_points=pa.record_batch([pa.array([10, 20], type=pa.int64())], names=["event_time"]),
74+
)
75+
key_value = pa.record_batch([pa.array([10], type=pa.int64())], names=["event_time"])
76+
response = PlanResponse(
77+
splits=[encoded(ScanSplit(payload=b"split-1", key_value=key_value, range_index=1))],
78+
key_grouping=encoded(grouping),
79+
range_partitioning=encoded(ranges),
80+
)
81+
82+
decoded = PlanResponse.deserialize_from_bytes(encoded(response))
83+
assert KeyGrouping.deserialize_from_bytes(decoded.key_grouping).keys == grouping.keys # type: ignore[arg-type]
84+
decoded_ranges = RangePartitioning.deserialize_from_bytes(decoded.range_partitioning) # type: ignore[arg-type]
85+
assert decoded_ranges.split_points.equals(ranges.split_points)
86+
decoded_split = ScanSplit.deserialize_from_bytes(decoded.splits[0]) # type: ignore[arg-type]
87+
assert decoded_split.range_index == 1
88+
assert decoded_split.key_value is not None and decoded_split.key_value.equals(key_value)
89+
90+
91+
def test_distribution_records_reject_ambiguous_shapes() -> None:
92+
"""Malformed parameter batches and split-point widths fail closed."""
93+
with pytest.raises(ValueError, match="exactly one row"):
94+
TransformSpec(
95+
id="example.bucket/1",
96+
inputs=[encoded(FieldPath(components=["id"]))],
97+
parameters=pa.record_batch([pa.array([8, 16])], names=["buckets"]),
98+
)
99+
100+
with pytest.raises(ValueError, match="width"):
101+
RangePartitioning(
102+
keys=[
103+
encoded(
104+
RangeKey(
105+
transform=encoded(identity("id")),
106+
direction=OrderByDirection.ASC,
107+
null_order=OrderByNullOrder.NULLS_LAST,
108+
)
109+
)
110+
],
111+
split_points=pa.record_batch(
112+
[pa.array([10]), pa.array([20])],
113+
names=["id", "extra"],
114+
),
115+
)

‎vgi/_test_fixtures/table/splits.py‎

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@
3737
from vgi.cache_control import CacheControl
3838
from vgi.filter_v2 import replaying_accepted_state
3939
from vgi.metadata import FunctionExample, PartitionKind
40-
from vgi.protocol import PlanResponse, ScanSplit, VgiOutputCollector
40+
from vgi.protocol import FieldPath, KeyGrouping, PlanResponse, ScanSplit, TransformSpec, VgiOutputCollector
4141
from vgi.schema_utils import partition_field, schema
4242

4343
if TYPE_CHECKING:
@@ -889,17 +889,27 @@ class Meta:
889889

890890
@classmethod
891891
def on_plan(cls, params: BindParams[SplitPartitionArgs], request: Any) -> PlanResponse:
892-
"""One split per country, each naming its own partition."""
892+
"""One split per country, carrying its exact protocol-3.1 key."""
893+
key_grouping = KeyGrouping(
894+
keys=[
895+
TransformSpec(
896+
id="vgi.identity/1",
897+
inputs=[FieldPath(components=["country"]).serialize_to_bytes()],
898+
).serialize_to_bytes()
899+
]
900+
).serialize_to_bytes()
893901
return PlanResponse(
894902
splits=[
895903
ScanSplit(
896904
payload=country.encode("ascii"),
897905
estimated_rows=params.args.rows_per_country,
898906
rows_exact=True,
907+
key_value=pa.RecordBatch.from_pydict({"country": [country]}),
899908
)
900909
for country in _PART_COUNTRIES
901910
],
902911
estimated_total_splits=len(_PART_COUNTRIES),
912+
key_grouping=key_grouping,
903913
)
904914

905915
@classmethod
@@ -940,12 +950,18 @@ def process(
940950
# assertion unchanged — the file could not detect the exact failure
941951
# it exists to detect.
942952
base = _PART_COUNTRIES.index(country) * 100
943-
out.emit(
944-
pa.RecordBatch.from_pydict(
945-
{"country": [country] * rows, "sales": [base + i + 1 for i in range(rows)]},
946-
schema=_PART_ROW,
947-
)
953+
batch = pa.RecordBatch.from_pydict(
954+
{"country": [country] * rows, "sales": [base + i + 1 for i in range(rows)]},
955+
schema=_PART_ROW,
948956
)
957+
# Bypass the legacy per-batch vgi_partition_values metadata. The
958+
# DuckDB adapter must source this split's SINGLE_VALUE partition
959+
# tuple from ScanSplit.key_value; if it falls back, the existing
960+
# C++ missing-metadata check makes this integration test fail.
961+
inner = out
962+
while hasattr(inner, "_inner"):
963+
inner = inner._inner
964+
inner.emit(batch)
949965
return
950966

951967

0 commit comments

Comments
 (0)