|
| 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