Skip to content

Commit 81258a7

Browse files
rustyconoverclaude
andcommitted
codegen: raw-preserving Nested<T> wrapper for bind_call in Go, Rust, Java, TS, C#
Each typed backend emits the large-values spec §3.3 wrapper for nested records carried as binary (NESTED_BINARY_RECORDS): it holds the received bytes, decodes lazily once on access, re-encodes as the held bytes, serializes once when built from a typed record, compares and prints by bytes. Decode errors name the field path (InitRequest.bind_call: ...). - Go: generated.Nested[T] + <Field>Value() accessors; needs vgi-rpc-go to honour encoding.Binary(Un)Marshaler and export Marshal/UnmarshalRecord. go_registry uses the generated Cardinality/Statistics/Plan requests. - Rust: Nested<T> (Arc bytes + OnceLock) implementing VgiArrow; <field>_value() accessors; validate_arguments(); Vec<Option<T>> for lists of optional items (argument_names nulls were lost). - Java: protocol/Nested<T>; needs vgi-rpc-java's RawBinary hook. list<large_binary> maps to @Arrowfield(LARGE_BINARY) List<byte[]>. - TypeScript: Nested<T> class with generated encode/decode wrapping; ts_client skips Transient fields; decoded embedding-request interfaces live in vgi-protocol-types.ts. - C#: Nested<T>; needs vgi-rpc-csharp's IRawBinary hook. - One generated conformance test per SDK over conformance/nested-binary (spec §3.4 tests 1-3), with freshness tests here. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent c76feaf commit 81258a7

20 files changed

Lines changed: 3558 additions & 46 deletions

‎tests/test_generated_csharp.py‎

Lines changed: 47 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,11 @@
2323

2424
import pytest
2525

26-
from vgi.codegen import csharp_schemas, csharp_types
26+
from vgi.codegen import csharp_nested_test, csharp_schemas, csharp_types
2727

2828
_TYPES = Path("src/QueryFarm.Vgi/Protocol/Generated/VgiProtocolTypes.g.cs")
2929
_SCHEMAS = Path("test/QueryFarm.Vgi.Tests/Generated/VgiProtocolSchemas.g.cs")
30+
_NESTED_TEST = Path(csharp_nested_test.TARGET)
3031

3132
_REGEN_HINT = (
3233
"To regenerate, run:\n"
@@ -51,16 +52,18 @@ def _render(module: object) -> str:
5152
return buf.getvalue()
5253

5354

54-
@pytest.mark.parametrize("module", [csharp_types, csharp_schemas], ids=["types", "schemas"])
55+
@pytest.mark.parametrize(
56+
"module", [csharp_types, csharp_schemas, csharp_nested_test], ids=["types", "schemas", "nested-test"]
57+
)
5558
def test_generator_is_deterministic(module: object) -> None:
5659
"""Calling emit() twice produces byte-identical output."""
5760
assert _render(module) == _render(module)
5861

5962

6063
@pytest.mark.parametrize(
6164
("module", "relative"),
62-
[(csharp_types, _TYPES), (csharp_schemas, _SCHEMAS)],
63-
ids=["types", "schemas"],
65+
[(csharp_types, _TYPES), (csharp_schemas, _SCHEMAS), (csharp_nested_test, _NESTED_TEST)],
66+
ids=["types", "schemas", "nested-test"],
6467
)
6568
def test_checked_in_file_matches_generator(module: object, relative: Path) -> None:
6669
"""Drift check: the checked-in C# matches what the generator produces."""
@@ -109,3 +112,43 @@ def test_enum_members_round_trip_to_their_wire_names() -> None:
109112
derived = csharp_types._to_snake_case(m.name).upper()
110113
rendered = csharp_types._render_enum(e)
111114
assert derived == m.wire_name or f'RpcName("{m.wire_name}")' in rendered, (e.name, m.name)
115+
116+
117+
_EMBEDDING = {
118+
"InitRequest",
119+
"TableFunctionCardinalityRequest",
120+
"TableFunctionStatisticsRequest",
121+
"TableFunctionDynamicToStringRequest",
122+
"TableFunctionPlanRequest",
123+
"TableFunctionProjectionRequest",
124+
}
125+
126+
127+
def test_bind_call_is_the_raw_preserving_wrapper() -> None:
128+
"""Every request embedding bind_call carries it as Nested<BindRequest>, with its field path."""
129+
records = csharp_types.build_model().records
130+
for name in _EMBEDDING:
131+
props = {p.wire_name: p for p in records[name].props}
132+
assert props["bind_call"].clr_type == "Nested<BindRequest>", name
133+
assert props["bind_call"].nested_path == f"{name}.bind_call"
134+
assert f'WithPath("{name}.bind_call")' in csharp_types._render_record(records[name])
135+
# Only the records in NESTED_BINARY_RECORDS: bind_result stays raw bytes.
136+
projection = {p.wire_name: p for p in records["TableFunctionProjectionRequest"].props}
137+
assert projection["bind_result"].clr_type == "byte[]"
138+
assert set(csharp_nested_test.embedding_fields()) == _EMBEDDING
139+
140+
141+
def test_wrapper_is_emitted_once_and_bind_request_ends_with_the_location() -> None:
142+
"""The Nested<T> class is emitted exactly once; arguments is nullable and arguments_location last."""
143+
text = _render(csharp_types)
144+
assert text.count("public sealed class Nested<T>") == 1
145+
assert "IRawBinary<Nested<T>>" in text
146+
props = csharp_types.build_model().records["BindRequest"].props
147+
assert props[-1].wire_name == "arguments_location"
148+
assert props[-1].clr_type == "ArgumentsLocation?"
149+
assert {p.wire_name: p.clr_type for p in props}["arguments"] == "byte[]?"
150+
assert [p.wire_name for p in csharp_types.build_model().records["ArgumentsLocation"].props] == [
151+
"ref",
152+
"size",
153+
"sha256",
154+
]

‎tests/test_generated_go_nested.py‎

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
# Copyright 2025, 2026 Query Farm LLC - https://query.farm
2+
3+
"""The Go raw-preserving nested-record wrapper and its generated conformance test.
4+
5+
`vgi.codegen.go_types` emits a ``bind_call`` (a ``BindRequest`` carried as a
6+
binary IPC stream) as ``Nested[BindRequest]`` (vgi docs/large-values-3.4.md
7+
§3.3); `vgi.codegen.go_nested_test` emits vgi-go's test over the
8+
nested-binary corpus. Drift checks skip when the `vgi-go` checkout is not
9+
next to vgi-python; ``VGI_GO_NESTED_TEST_GO`` overrides the test's location.
10+
"""
11+
12+
from __future__ import annotations
13+
14+
import io
15+
import os
16+
from pathlib import Path
17+
18+
import pytest
19+
20+
from vgi.codegen import go_nested_test, go_types
21+
22+
_EMBEDDING = {
23+
"InitRequest",
24+
"TableFunctionCardinalityRequest",
25+
"TableFunctionStatisticsRequest",
26+
"TableFunctionDynamicToStringRequest",
27+
"TableFunctionPlanRequest",
28+
"TableFunctionProjectionRequest",
29+
}
30+
31+
32+
def _types() -> str:
33+
buf = io.StringIO()
34+
go_types.emit(buf)
35+
return buf.getvalue()
36+
37+
38+
def _test() -> str:
39+
buf = io.StringIO()
40+
go_nested_test.emit(buf)
41+
return buf.getvalue()
42+
43+
44+
def test_bind_call_is_the_raw_preserving_wrapper() -> None:
45+
"""Exactly the six embedding requests carry a nested BindRequest, as a binary column."""
46+
nested = {r.name: f for r in go_types.build_records() for f in r.fields if f.nested is not None}
47+
assert set(nested) == _EMBEDDING
48+
for f in nested.values():
49+
assert (f.wire_name, f.go_type, f.options, f.nested) == (
50+
"bind_call",
51+
"Nested[BindRequest]",
52+
["binary"],
53+
"BindRequest",
54+
)
55+
56+
57+
def test_other_nested_binary_records_stay_bytes() -> None:
58+
"""Only NESTED_BINARY_RECORDS get the wrapper; e.g. the projection's bind_result stays []byte."""
59+
record = next(r for r in go_types.build_records() if r.name == "TableFunctionProjectionRequest")
60+
assert {f.wire_name: f.go_type for f in record.fields}["bind_result"] == "[]byte"
61+
62+
63+
def test_wrapper_and_accessors_are_emitted() -> None:
64+
"""One generic wrapper, plus a path-naming accessor per embedding record."""
65+
text = _types()
66+
assert text.count("type Nested[T any] struct {") == 1
67+
for name in _EMBEDDING:
68+
assert f"func (r {name}) BindCallValue() (BindRequest, error) {{" in text
69+
assert f'fmt.Errorf("{name}.bind_call: %w", err)' in text
70+
assert "func (n Nested[T]) MarshalBinary() ([]byte, error) {" in text
71+
assert "func (n *Nested[T]) UnmarshalBinary(data []byte) error {" in text
72+
73+
74+
def test_conformance_test_covers_every_embedding_record() -> None:
75+
"""The generated test has a case and a schema check for each embedding record."""
76+
text = _test()
77+
for name in _EMBEDDING:
78+
assert f'"{name}": nestedCase[generated.{name}]{{' in text
79+
assert f'{{"{name}", generated.{name}{{}}, generated.{name}Schema}},' in text
80+
assert _test() == text
81+
82+
83+
def test_checked_in_conformance_test_matches_generator() -> None:
84+
"""Drift check against vgi-go's checked-in test."""
85+
override = os.environ.get("VGI_GO_NESTED_TEST_GO")
86+
path = Path(override) if override else Path(__file__).resolve().parents[2] / "vgi-go" / go_nested_test.TARGET
87+
if not path.exists():
88+
pytest.skip(f"{path} not found; set VGI_GO_NESTED_TEST_GO or check out vgi-go next to vgi-python")
89+
assert path.read_text() == _test(), (
90+
f"{path} is stale; run uv run --project ~/Development/vgi-python python scripts/regen_generated.py"
91+
)
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# Copyright 2025, 2026 Query Farm LLC - https://query.farm
2+
3+
"""Drift + determinism tests for `vgi.codegen.java_nested_test`.
4+
5+
vgi-java checks in the generated nested-binary conformance test at
6+
``java_nested_test.TARGET``; it must match what the generator emits now.
7+
Skipped when the `vgi-java` checkout isn't present (``VGI_JAVA_ROOT`` overrides
8+
the search, as for `tests/test_generated_java_types.py`).
9+
"""
10+
11+
from __future__ import annotations
12+
13+
from vgi.codegen import java_nested_test
14+
15+
from .test_generated_java_types import _REGEN_HINT, _vgi_java_root
16+
17+
18+
def test_generator_is_deterministic() -> None:
19+
"""Rendering twice produces byte-identical output."""
20+
assert java_nested_test.render() == java_nested_test.render()
21+
22+
23+
def test_targets_vgi_java() -> None:
24+
"""The test lands in vgi-java's generated test package."""
25+
assert java_nested_test.REPO == "vgi-java"
26+
assert java_nested_test.TARGET.endswith("/generated/NestedBinaryConformanceTest.java")
27+
28+
29+
def test_typed_construction_tracks_the_generated_records() -> None:
30+
"""The constructor calls have one argument per generated component."""
31+
text = java_nested_test.render()
32+
assert 'new BindRequest(\n "typed_construction",' in text
33+
assert "new InitRequest(\n wrapped," in text
34+
35+
36+
def test_checked_in_test_matches_generator() -> None:
37+
"""Drift check against the vgi-java checkout."""
38+
import pytest
39+
40+
path = _vgi_java_root() / java_nested_test.TARGET
41+
if not path.parent.parent.is_dir():
42+
pytest.skip(f"{path.parent.parent} not found; set VGI_JAVA_ROOT or check out vgi-java")
43+
assert path.exists(), f"{path} is missing.\n{_REGEN_HINT}"
44+
assert path.read_text() == java_nested_test.render(), f"{path} is stale.\n{_REGEN_HINT}"

‎tests/test_generated_java_types.py‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,8 +99,14 @@ def test_checked_in_java_matches_generator(record: str, relative: str) -> None:
9999

100100
def _derive(java_type: str, annotations: str) -> pa.DataType:
101101
override = re.search(r"@ArrowField\(ArrowFieldType\.(\w+)\)", annotations)
102+
if override and java_type.startswith("List<"):
103+
# On a List the override is the ELEMENT type (SchemaDerivation.buildOverriddenChild).
104+
return pa.list_(pa.field("item", _OVERRIDES[override.group(1)], nullable=True))
102105
if override:
103106
return _OVERRIDES[override.group(1)]
107+
if java_type.startswith(f"{java_types.NESTED_CLASS}<"):
108+
# Nested<T> implements vgi-rpc-java's RawBinary: carried as binary.
109+
return pa.binary()
104110
if java_type.startswith("List<"):
105111
element = java_type[5:-1]
106112
return pa.list_(pa.field("item", _derive(element, ""), nullable=True))
@@ -151,3 +157,31 @@ def test_unsupported_arrow_type_is_refused() -> None:
151157
)
152158
with pytest.raises(GeneratorError):
153159
java_types._component(pa.field("nested", pa.list_(pa.list_(pa.field("renamed", pa.string())))), "X")
160+
161+
162+
def test_nested_binary_records_use_the_wrapper() -> None:
163+
"""``bind_call`` is the raw-preserving ``Nested<BindRequest>``; other binary records stay ``byte[]``."""
164+
init = java_types.render("InitRequest")
165+
assert " Nested<BindRequest> bind_call," in init
166+
projection = java_types.render("TableFunctionProjectionRequest")
167+
assert " Nested<BindRequest> bind_call," in projection
168+
assert " byte[] bind_result," in projection
169+
bind = java_types.render("BindRequest")
170+
assert " @Nullable byte[] arguments," in bind
171+
assert " @Nullable ArgumentsLocation arguments_location) implements" in bind
172+
173+
174+
def test_nested_wrapper_is_emitted_beside_the_records() -> None:
175+
"""The wrapper class is a generated target and implements the codec's raw-binary hook."""
176+
assert (java_types.NESTED_CLASS, f"{java_types.JAVA_PROTOCOL_DIR}/Nested.java") in java_types.targets()
177+
text = java_types.render(java_types.NESTED_CLASS)
178+
assert "public final class Nested<T extends ArrowSerializableRecord> implements RawBinary {" in text
179+
assert "public static Nested<?> fromRawBinary(byte[] bytes, Type componentType, String path)" in text
180+
181+
182+
def test_large_binary_list_takes_the_element_override() -> None:
183+
"""``list<large_binary>`` maps to ``@ArrowField(LARGE_BINARY) List<byte[]>``."""
184+
field = pa.field("join_keys", pa.list_(pa.large_binary()))
185+
component = java_types._component(field, "X")
186+
assert component.java_type == "List<byte[]>"
187+
assert component.annotations == ("@Nullable", "@ArrowField(ArrowFieldType.LARGE_BINARY)")
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# Copyright 2025, 2026 Query Farm LLC - https://query.farm
2+
3+
"""Drift + shape tests for `vgi.codegen.rust_nested_test`.
4+
5+
The test itself runs in vgi-rust (`cargo test -p vgi-protocol --test
6+
nested_binary`) against the corpus `vgi.codegen.nested_binary_fixtures` copies
7+
there. From here: the emission is deterministic, covers every embedding
8+
record, and the checked-in file is current.
9+
10+
Skipped when the sibling `vgi-rust` checkout is not present;
11+
``VGI_RUST_NESTED_TEST_RS`` overrides the location.
12+
"""
13+
14+
from __future__ import annotations
15+
16+
import io
17+
import os
18+
from pathlib import Path
19+
20+
import pytest
21+
22+
from vgi.codegen import rust_nested_test, rust_types
23+
24+
25+
def _emitted() -> str:
26+
buf = io.StringIO()
27+
rust_nested_test.emit(buf)
28+
return buf.getvalue()
29+
30+
31+
def _checked_in_path() -> Path:
32+
override = os.environ.get("VGI_RUST_NESTED_TEST_RS")
33+
if override:
34+
return Path(override)
35+
return Path(__file__).resolve().parents[2] / "vgi-rust" / rust_nested_test.TARGET
36+
37+
38+
def test_generator_is_deterministic() -> None:
39+
"""Calling emit() twice produces byte-identical output."""
40+
assert _emitted() == _emitted()
41+
42+
43+
def test_every_embedding_record_is_checked() -> None:
44+
"""Each generated record holding a `Nested<BindRequest>` gets a byte-identity case."""
45+
src = _emitted()
46+
embedding = [s.name for s in rust_types.build_model() if any(f.nested == "BindRequest" for f in s.fields)]
47+
assert len(embedding) == 6
48+
for name in embedding:
49+
assert f'"{name}" => {{' in src, name
50+
assert f"check_embedding::<{name}>" in src, name
51+
for test in (
52+
"byte_identity_round_trip",
53+
"typed_construction_round_trips",
54+
"null_arguments_and_exactly_one",
55+
"decode_errors_surface_at_access_with_the_field_path",
56+
):
57+
assert f"fn {test}()" in src
58+
59+
60+
def test_emitted_lines_fit_rustfmt_width() -> None:
61+
"""vgi-rust CI runs `cargo fmt --check` (100 columns)."""
62+
for line in _emitted().splitlines():
63+
if line.lstrip().startswith("//"):
64+
continue
65+
assert len(line) <= 100, line
66+
67+
68+
def test_checked_in_test_matches_generator() -> None:
69+
"""The file committed in vgi-rust must equal what the generator emits now."""
70+
path = _checked_in_path()
71+
if not path.exists():
72+
pytest.skip(f"vgi-rust nested-binary test not found at {path}")
73+
assert path.read_text(encoding="utf-8") == _emitted(), (
74+
f"{path} is stale. Run: uv run --project ~/Development/vgi-python python scripts/regen_generated.py"
75+
)

‎tests/test_generated_rust_types.py‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,3 +115,53 @@ def test_checked_in_rust_matches_generator() -> None:
115115
if not path.exists():
116116
pytest.skip(f"vgi-rust checkout not found at {path}")
117117
assert path.read_text(encoding="utf-8") == _emitted(), f"{path} is stale.\n\n{_REGEN_HINT}"
118+
119+
120+
def test_nested_binary_records_become_raw_preserving_wrappers() -> None:
121+
"""`bind_call` (a BindRequest carried as binary) is `Nested<BindRequest>`; other binary records stay bytes."""
122+
by_name = {s.name: {f.wire_name: f for f in s.fields} for s in rust_types.build_model()}
123+
embedding = {name for name, fields in by_name.items() if "bind_call" in fields}
124+
assert embedding == {
125+
"InitRequest",
126+
"TableFunctionCardinalityRequest",
127+
"TableFunctionStatisticsRequest",
128+
"TableFunctionDynamicToStringRequest",
129+
"TableFunctionPlanRequest",
130+
"TableFunctionProjectionRequest",
131+
}
132+
for name in embedding:
133+
field = by_name[name]["bind_call"]
134+
assert field.rust_type == "Nested<BindRequest>", name
135+
assert field.nested == "BindRequest"
136+
# Records outside NESTED_BINARY_RECORDS keep plain bytes (spec §3.2).
137+
assert by_name["TableFunctionProjectionRequest"]["bind_result"].rust_type == "Bytes"
138+
assert by_name["BindRequest"]["arguments"].rust_type == "Option<Bytes>"
139+
assert by_name["BindRequest"]["arguments_location"].rust_type == "Option<ArgumentsLocation>"
140+
assert list(by_name["BindRequest"])[-1] == "arguments_location"
141+
142+
143+
def test_nested_runtime_accessors_and_validation_are_emitted() -> None:
144+
"""One `Nested<T>` runtime, a path-naming accessor per wrapped field, and the exactly-one rule."""
145+
src = _emitted()
146+
assert src.count("pub struct Nested<T> {") == 1
147+
assert "impl<T: ::vgi_rpc::VgiArrow> ::vgi_rpc::VgiArrow for Nested<T>" in src
148+
assert 'get_at("InitRequest.bind_call")' in src
149+
assert "pub fn bind_call_value(&self) -> ::vgi_rpc::Result<&BindRequest>" in src
150+
assert "pub fn validate_arguments(&self) -> ::vgi_rpc::Result<()>" in src
151+
assert '"invalid_bind_request"' in src
152+
assert '"invalid_arguments_ref"' in src
153+
154+
155+
def test_list_items_typed_optional_in_python_are_option_in_rust() -> None:
156+
"""`list[str | None]` keeps null items: Vec<Option<String>>, same derived schema."""
157+
by_name = {s.name: {f.wire_name: f.rust_type for f in s.fields} for s in rust_types.build_model()}
158+
assert by_name["BindRequest"]["argument_names"] == "Option<Vec<Option<String>>>"
159+
assert by_name["BindRequest"]["schema_path"] == "Option<Vec<String>>"
160+
161+
162+
def test_emitted_lines_fit_rustfmt_width() -> None:
163+
"""vgi-rust CI runs `cargo fmt --check`; nothing generated may exceed rustfmt's 100 columns (doc comments aside)."""
164+
for line in _emitted().splitlines():
165+
if line.lstrip().startswith(("//", '"')): # rustfmt never breaks comments or string literals
166+
continue
167+
assert len(line) <= 100, line

0 commit comments

Comments
 (0)