Skip to content

Commit 20aa1a6

Browse files
rustyconoverclaude
andcommitted
Add the txfix writable-table and transaction-hook fixture worker
vgi-fixture-writable-tx-worker implements vgi docs/writable_tx_fixtures.md (test/sql/integration/writable_tx/*.test) using only public API: a declarative catalog whose items table declares an update function with write_result_modes {"update": "changes"}, a token (secret, typed str | None) and a transactional ATTACH option carried with pack_attach_options, a per-attach supports_transactions, and the catalog transaction hooks. UPDATE stages under the plaintext transaction id on a transactional attach; commit applies or refuses, rollback discards. State is one SQLite file under $VGI_TXFIX_STATE_DIR, partitioned by token. ci/run-integration.sh opts every lane in (VGI_WRITABLE_TX_FIXTURES=1, VGI_WRITABLE_TX_WORKER as a path, launch:<path>, or a booted HTTP server on the http lane) with a per-run state directory. The release workflow builds a writable-tx fixture image. tests/conformance/test_writable_tx.py drives the fixture through the Client over subprocess and HTTP, including the changes write result mode DuckDB never requests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 894fcc0 commit 20aa1a6

6 files changed

Lines changed: 834 additions & 1 deletion

File tree

‎.github/workflows/release.yml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ jobs:
8181
- { short: bad-protocol, worker: vgi-fixture-bad-protocol-worker }
8282
- { short: bad-enum, worker: vgi-fixture-bad-enum-worker }
8383
- { short: simple-writable, worker: vgi-fixture-simple-writable-worker }
84+
- { short: writable-tx, worker: vgi-fixture-writable-tx-worker }
8485
steps:
8586
- uses: actions/checkout@v7
8687

‎ci/README.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,13 @@ matrix; `stdio` remains available for local compatibility testing:
9090
runner links httpfs; standalone mode injects `LOAD httpfs` before worker
9191
attachments.
9292

93+
The `writable_tx/*.test` writable-table and transaction-hook fixtures run on
94+
every lane against `VGI_WRITABLE_TX_WORKER` (`vgi-fixture-writable-tx-worker`,
95+
the `txfix` catalog of vgi `docs/writable_tx_fixtures.md`): a plain path on
96+
stdio, `launch:` on the launcher lanes, and a booted HTTP server on the http
97+
lane (the tests check that transaction ids survive the HTTP sealing).
98+
`VGI_TXFIX_STATE_DIR` points at a per-run temp directory.
99+
93100
The `simple_writable/*.test` write-path tests (INSERT/UPDATE/DELETE/RETURNING)
94101
run on **every** lane against `VGI_SIMPLE_WRITABLE_WORKER`
95102
(`vgi-fixture-simple-writable-worker`), in their own `haybarn-unittest`

‎ci/run-integration.sh‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,8 @@ VERSIONED_TABLES="$BIN_DIR/vgi-fixture-versioned-tables-worker"
5454
ATTACH_OPTIONS="$BIN_DIR/vgi-fixture-attach-options-worker"
5555
BAD_PROTOCOL="$BIN_DIR/vgi-fixture-bad-protocol-worker"
5656
SIMPLE_WRITABLE="$BIN_DIR/vgi-fixture-simple-writable-worker"
57-
for b in "$WORKER" "$VERSIONED" "$VERSIONED_TABLES" "$ATTACH_OPTIONS" "$BAD_PROTOCOL" "$SIMPLE_WRITABLE"; do
57+
WRITABLE_TX="$BIN_DIR/vgi-fixture-writable-tx-worker"
58+
for b in "$WORKER" "$VERSIONED" "$VERSIONED_TABLES" "$ATTACH_OPTIONS" "$BAD_PROTOCOL" "$SIMPLE_WRITABLE" "$WRITABLE_TX"; do
5859
[ -x "$b" ] || { echo "::error::missing fixture worker $b (run: uv sync --all-extras)"; exit 1; }
5960
done
6061

@@ -239,13 +240,22 @@ export VGI_DATABASE_PACKAGE_WORKER="$WORKER"
239240
# (vgi docs/secret_lookup_fixtures.md), so opt in to secret/secret_lookup_*.test
240241
# on every lane.
241242
export VGI_SECRET_LOOKUP_FIXTURES=1
243+
# The txfix worker implements the writable-table and transaction-hook fixtures
244+
# (vgi docs/writable_tx_fixtures.md), so opt in to writable_tx/*.test on every
245+
# lane. VGI_WRITABLE_TX_WORKER is set per lane below (a path, launch:<path>, or
246+
# the http:// URL of a booted server). Its state file lives in a directory
247+
# private to this run, so lanes running at once on one host don't share rows.
248+
export VGI_WRITABLE_TX_FIXTURES=1
249+
VGI_TXFIX_STATE_DIR="$(mktemp -d)"
250+
export VGI_TXFIX_STATE_DIR
242251

243252
case "$TRANSPORT" in
244253
stdio)
245254
# Subprocess transport — the only lane that spawns a
246255
# fresh worker process per DuckDB connection, and so the only one that can
247256
# host the crash / pool-recovery tests below.
248257
export VGI_TEST_WORKER="$WORKER"
258+
export VGI_WRITABLE_TX_WORKER="$WRITABLE_TX"
249259
# Presence gate for the crash / pool-recovery tests
250260
# (table_in_out/table_buffering_{worker_crash,pool_recovery}). The value is
251261
# not a worker spec — the SQL attaches the normal pooled worker; this just
@@ -295,6 +305,7 @@ case "$TRANSPORT" in
295305
# left UNSET (as in test_launcher), so attach/versioned_tables_*_http and
296306
# versioning_http skip — they're covered over http on the stdio lane.
297307
export VGI_TEST_WORKER="launch:${WORKER}"
308+
export VGI_WRITABLE_TX_WORKER="launch:${WRITABLE_TX}"
298309
export VGI_VERSIONED_WORKER="launch:${VERSIONED}"
299310
export VGI_VERSIONED_TABLES_WORKER="launch:${VERSIONED_TABLES}"
300311
export VGI_ATTACH_OPTIONS_WORKER="launch:${ATTACH_OPTIONS}"
@@ -313,6 +324,10 @@ case "$TRANSPORT" in
313324
# — they are covered over http on the stdio lane, which boots those workers.
314325
boot_http_worker "$WORKER"; port="$BOOTED_PORT"
315326
export VGI_TEST_WORKER="http://localhost:${port}"
327+
# writable_tx/* asserts the transaction id survives the HTTP transport's
328+
# sealing, so the txfix worker is served over HTTP too.
329+
boot_http_worker "$WRITABLE_TX"; txfix_port="$BOOTED_PORT"
330+
export VGI_WRITABLE_TX_WORKER="http://localhost:${txfix_port}"
316331
SUITE_GLOB="test/sql/integration/*"
317332
;;
318333
*)

‎packages/vgi-fixtures/pyproject.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ vgi-fixture-bad-protocol-worker = "vgi._test_fixtures.bad_protocol:main"
4949
vgi-fixture-bad-enum-worker = "vgi._test_fixtures.bad_enum:main"
5050
vgi-fixture-writable-worker = "vgi._test_fixtures.writable.worker:main"
5151
vgi-fixture-simple-writable-worker = "vgi._test_fixtures.simple_writable:main"
52+
vgi-fixture-writable-tx-worker = "vgi._test_fixtures.writable_tx:main"
5253

5354
[tool.uv.sources]
5455
vgi-python = { workspace = true }
Lines changed: 190 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,190 @@
1+
# Copyright 2025, 2026 Query Farm LLC - https://query.farm
2+
3+
"""Conformance for ``vgi/test/sql/integration/writable_tx/``: the ``txfix`` fixture worker.
4+
5+
Drives ``vgi._test_fixtures.writable_tx`` through the Python ``Client`` over a
6+
subprocess and over HTTP (where the worker seals attach and transaction data
7+
on the wire), checking what the C++ suite checks through DuckDB: ATTACH options
8+
(including a secret) reach every function, ``supports_transactions`` is per
9+
attach, the transaction hooks see the same plaintext id as functions, UPDATE
10+
stages under it and commit applies or refuses it. Also covers the ``changes``
11+
write result mode, which DuckDB never requests.
12+
"""
13+
14+
from __future__ import annotations
15+
16+
import os
17+
import subprocess
18+
import sys
19+
import threading
20+
import uuid
21+
from collections.abc import Iterator
22+
from contextlib import contextmanager
23+
from typing import Any
24+
25+
import pyarrow as pa
26+
import pytest
27+
from vgi_rpc.utils import serialize_record_batch_bytes
28+
29+
from tests._http_fixtures import wait_for_http_server
30+
from vgi.arguments import Arguments
31+
from vgi.client.client import Client
32+
33+
pytest.importorskip("vgi._test_fixtures.writable_tx")
34+
35+
_WORKER = [sys.executable, "-m", "vgi._test_fixtures.writable_tx"]
36+
37+
38+
@contextmanager
39+
def _http_server(env: dict[str, str]) -> Iterator[str]:
40+
proc = subprocess.Popen(
41+
[*_WORKER, "--http", "--port", "0"],
42+
env=env,
43+
stdout=subprocess.PIPE,
44+
stderr=subprocess.STDOUT,
45+
text=True,
46+
)
47+
try:
48+
assert proc.stdout is not None
49+
port = None
50+
for line in proc.stdout:
51+
if line.startswith("PORT:"):
52+
port = int(line.strip().split(":", 1)[1])
53+
break
54+
assert port is not None, "txfix worker never reported its port"
55+
# Keep draining so a chatty server never blocks on a full pipe.
56+
threading.Thread(target=lambda: [None for _ in proc.stdout or []], daemon=True).start()
57+
url = f"http://127.0.0.1:{port}"
58+
wait_for_http_server(url)
59+
yield url
60+
finally:
61+
proc.terminate()
62+
proc.wait(timeout=10)
63+
64+
65+
@pytest.fixture
66+
def token() -> str:
67+
"""A token of this test's own: the fixture partitions its state by token.
68+
69+
The state directory stays at its default: the client's catalog RPCs reuse
70+
pooled worker processes across tests, so a per-test
71+
``VGI_TXFIX_STATE_DIR`` would not reach all of them.
72+
"""
73+
return f"tok-{uuid.uuid4().hex}"
74+
75+
76+
@pytest.fixture(params=["subprocess", "http"])
77+
def connect(request: pytest.FixtureRequest) -> Iterator[Any]:
78+
"""Yield ``connect(attach_opaque_data=None) -> Client`` for one transport."""
79+
if request.param == "subprocess":
80+
command = " ".join(_WORKER)
81+
yield lambda attach=None: Client(command, pool=None, attach_opaque_data=attach)
82+
return
83+
pytest.importorskip("vgi_rpc.http")
84+
with _http_server(dict(os.environ)) as url:
85+
yield lambda attach=None: Client.from_http(url, attach_opaque_data=attach)
86+
87+
88+
def _attach(connect: Any, **options: Any) -> tuple[Any, Any]:
89+
with connect() as client:
90+
result = client.catalog_attach(
91+
name="txfix", options=options, data_version_spec=None, implementation_version=None
92+
)
93+
return result, connect(result.attach_opaque_data)
94+
95+
96+
def _table(client: Client, name: str, tx: bytes | None = None) -> list[dict[str, Any]]:
97+
batches = list(client.table_function(function_name=name, schema_path=["main"], transaction_opaque_data=tx))
98+
return [row for b in batches for row in b.to_pylist()]
99+
100+
101+
def _update(client: Client, rows: list[dict[str, Any]], mode: str, tx: bytes | None = None) -> list[dict[str, Any]]:
102+
options = serialize_record_batch_bytes(pa.RecordBatch.from_pylist([{"result_mode": mode}]))
103+
batch = pa.RecordBatch.from_pylist(rows, schema=pa.schema([("qty", pa.int64()), ("rowid", pa.int64())]))
104+
out = client.table_in_out_function(
105+
function_name="items_update",
106+
schema_path=["main"],
107+
input=iter([batch]),
108+
arguments=Arguments(named={"write_options": pa.scalar(options)}),
109+
transaction_opaque_data=tx,
110+
)
111+
return [row for b in out for row in b.to_pylist()]
112+
113+
114+
def test_attach_options_and_per_attach_transactions(connect: Any, token: str) -> None:
115+
"""Attach options and per attach transactions."""
116+
plain, client = _attach(connect, token=token)
117+
assert plain.supports_transactions is False
118+
assert plain.attach_opaque_data_required is True
119+
with client:
120+
assert _table(client, "whoami") == [{"token": token, "transactional": False}]
121+
assert _table(client, "reset") == [{"ok": True}]
122+
tx_result, tx_client = _attach(connect, token=token, transactional=True)
123+
assert tx_result.supports_transactions is True
124+
with tx_client:
125+
assert _table(tx_client, "whoami") == [{"token": token, "transactional": True}]
126+
anonymous, anon_client = _attach(connect)
127+
with anon_client:
128+
assert _table(anon_client, "whoami") == [{"token": None, "transactional": False}]
129+
130+
131+
def test_update_modes_on_a_plain_attach(connect: Any, token: str) -> None:
132+
"""Update modes on a plain attach."""
133+
_, client = _attach(connect, token=token)
134+
with client:
135+
_table(client, "reset")
136+
assert _update(client, [{"qty": 11, "rowid": 1}], "count") == [{"count": 1}]
137+
assert _update(client, [{"qty": 12, "rowid": 1}], "rows") == [{"id": 1, "name": "a", "qty": 12}]
138+
assert _update(client, [{"qty": 13, "rowid": 1}], "changes") == [
139+
{"old": {"id": 1, "name": "a", "qty": 12}, "new": {"id": 1, "name": "a", "qty": 13}}
140+
]
141+
with pytest.raises(Exception, match="qty must be >= 0"):
142+
_update(client, [{"qty": -1, "rowid": 2}], "count")
143+
assert [r["qty"] for r in _table(client, "items_scan")] == [13, 20, 30]
144+
145+
146+
def test_transaction_hooks_see_the_function_plaintext(connect: Any, token: str) -> None:
147+
"""Transaction hooks see the function plaintext."""
148+
_, plain = _attach(connect, token=token)
149+
_, client = _attach(connect, token=token, transactional=True)
150+
attach = client._attach_opaque_data
151+
with plain, client:
152+
_table(plain, "reset")
153+
# Commit: staged, read-your-writes, then visible to the other attach.
154+
tx = client.catalog_transaction_begin(attach_opaque_data=attach)
155+
assert tx is not None
156+
(current,) = _table(client, "current_tx", tx)
157+
assert current["in_tx"] is True and len(current["tx_id"]) == 32
158+
assert _update(client, [{"qty": 99, "rowid": 2}], "rows", tx) == [{"id": 2, "name": "b", "qty": 99}]
159+
assert [r["qty"] for r in _table(client, "items_scan", tx)] == [10, 99, 30]
160+
assert [r["qty"] for r in _table(plain, "items_scan")] == [10, 20, 30]
161+
client.catalog_transaction_commit(attach_opaque_data=attach, transaction_opaque_data=tx)
162+
assert [r["qty"] for r in _table(plain, "items_scan")] == [10, 99, 30]
163+
164+
# Refused commit: nothing applies.
165+
tx2 = client.catalog_transaction_begin(attach_opaque_data=attach)
166+
assert tx2 is not None
167+
_update(client, [{"qty": -5, "rowid": 3}], "count", tx2)
168+
with pytest.raises(Exception, match="commit refused: qty -5 for id 3"):
169+
client.catalog_transaction_commit(attach_opaque_data=attach, transaction_opaque_data=tx2)
170+
assert [r["qty"] for r in _table(plain, "items_scan")] == [10, 99, 30]
171+
172+
# Rollback.
173+
tx3 = client.catalog_transaction_begin(attach_opaque_data=attach)
174+
assert tx3 is not None
175+
_update(client, [{"qty": 1, "rowid": 1}], "count", tx3)
176+
client.catalog_transaction_rollback(attach_opaque_data=attach, transaction_opaque_data=tx3)
177+
assert [r["qty"] for r in _table(plain, "items_scan")] == [10, 99, 30]
178+
179+
events = _table(client, "events")
180+
assert [(e["kind"], e["ok"]) for e in events] == [
181+
("begin", True),
182+
("commit", True),
183+
("begin", True),
184+
("commit", False),
185+
("begin", True),
186+
("rollback", True),
187+
]
188+
# The hooks saw the plaintext the function saw, not the (sealed, on HTTP) wire bytes.
189+
assert events[0]["tx_id"] == events[1]["tx_id"] == current["tx_id"]
190+
assert len({events[0]["tx_id"], events[2]["tx_id"], events[4]["tx_id"]}) == 3

0 commit comments

Comments
 (0)