|
| 1 | +"""Partitioned-queue fixtures that opt in to ``supports_batch_index``. |
| 2 | +
|
| 3 | +These exist so SQL integration tests can verify the batch_index feature: |
| 4 | +
|
| 5 | +* ``partitioned_batch_index(count)`` — single-column ``n int64`` output; |
| 6 | + parallel scan with FIXED_ORDER preservation. Each queue item is tagged |
| 7 | + with a stable partition_id; the worker emits Arrow batches tagged with |
| 8 | + that id via ``out.emit(batch, batch_index=partition_id)``. The DuckDB |
| 9 | + extension reads the tag from each batch's KeyValueMetadata, threads it |
| 10 | + through ``TableFunction::get_partition_data``, and ordered sinks |
| 11 | + (``PhysicalBatchCollector``, ``PhysicalBatchInsert``, |
| 12 | + ``PhysicalBatchCopyToFile``, ``PhysicalLimit``) reassemble output in |
| 13 | + partition_id order. The FIXED_ORDER ``MaxThreads=1`` clamp is dropped |
| 14 | + for opted-in functions. |
| 15 | +
|
| 16 | +* ``partitioned_batch_index_marked(count, chunk_size)`` — two-column |
| 17 | + ``(partition_id int64, seq int64)`` output. Lets tests directly |
| 18 | + observe partition boundaries in the output stream (e.g. "no row with |
| 19 | + partition_id=N appears after a row with partition_id=N+1"). Projection |
| 20 | + pushdown is disabled so the ``partition_id`` column survives even |
| 21 | + ``SELECT seq FROM …`` queries. |
| 22 | +
|
| 23 | +The worker uses the existing in-process ``state`` to carry per-worker |
| 24 | +cursor information across ``process()`` calls — same approach as |
| 25 | +``_BasePartitionedOrderMode`` in ``order_modes.py``. HTTP transport's |
| 26 | +existing STATE_KEY mechanism (in vgi_rpc.http) round-trips this state |
| 27 | +across requests; nothing new is added for HTTP resumption. |
| 28 | +""" |
| 29 | + |
| 30 | +from __future__ import annotations |
| 31 | + |
| 32 | +import struct |
| 33 | +from dataclasses import dataclass |
| 34 | +from typing import Annotated, ClassVar |
| 35 | + |
| 36 | +import pyarrow as pa |
| 37 | +from vgi_rpc import ArrowSerializableDataclass |
| 38 | +from vgi_rpc.rpc import OutputCollector |
| 39 | + |
| 40 | +from vgi._test_fixtures.table._common import _cardinality_from_count |
| 41 | +from vgi.arguments import Arg |
| 42 | +from vgi.invocation import GlobalInitResponse |
| 43 | +from vgi.metadata import FunctionExample, OrderPreservation |
| 44 | +from vgi.schema_utils import schema |
| 45 | +from vgi.table_function import ( |
| 46 | + InitParams, |
| 47 | + ProcessParams, |
| 48 | + TableFunctionGenerator, |
| 49 | + bind_fixed_schema, |
| 50 | +) |
| 51 | + |
| 52 | + |
| 53 | +# Queue-item encoding: (partition_id, start, end) packed as three uint64s. |
| 54 | +# Decoded by ``process()`` on the worker; partition_id is what the worker |
| 55 | +# emits to DuckDB via the batch_index= kwarg. |
| 56 | +_ITEM_FMT = ">QQQ" |
| 57 | +_ITEM_SIZE = struct.calcsize(_ITEM_FMT) |
| 58 | + |
| 59 | + |
| 60 | +# ============================================================================= |
| 61 | +# Single-column variant: partitioned_batch_index(count) |
| 62 | +# ============================================================================= |
| 63 | + |
| 64 | + |
| 65 | +@dataclass(slots=True, frozen=True) |
| 66 | +class _BatchIndexArgs: |
| 67 | + """Arguments for ``partitioned_batch_index``.""" |
| 68 | + |
| 69 | + count: Annotated[int, Arg(0, doc="Total number of integers to generate", ge=0)] |
| 70 | + |
| 71 | + |
| 72 | +@dataclass(kw_only=True) |
| 73 | +class _BatchIndexState(ArrowSerializableDataclass): |
| 74 | + """Per-worker cursor state. |
| 75 | +
|
| 76 | + ``partition_id`` is the queue-push order of the current work item; emitted |
| 77 | + on every Arrow batch via the batch_index= kwarg. ``current_idx`` advances |
| 78 | + through ``[current_start, current_end)`` as the worker produces batches. |
| 79 | + All three reset to None at the moment a partition is exhausted; the next |
| 80 | + ``process()`` call pops a fresh item. |
| 81 | + """ |
| 82 | + |
| 83 | + partition_id: int | None = None |
| 84 | + current_start: int | None = None |
| 85 | + current_end: int | None = None |
| 86 | + current_idx: int = 0 |
| 87 | + |
| 88 | + |
| 89 | +@bind_fixed_schema |
| 90 | +@_cardinality_from_count |
| 91 | +class PartitionedBatchIndexFunction(TableFunctionGenerator[_BatchIndexArgs, _BatchIndexState]): |
| 92 | + """Parallel-scan sequence with batch_index ordering. |
| 93 | +
|
| 94 | + The primary worker enqueues N work items at on_init, each encoding |
| 95 | + ``(partition_id, start, end)``. Any worker pulls the next item via |
| 96 | + ``queue_pop``; emits a stream of Arrow batches tagged with |
| 97 | + partition_id; advances to the next item when exhausted. DuckDB's |
| 98 | + ordered sinks reassemble output in partition_id order — final output |
| 99 | + matches a single-threaded scan, but the source itself fans out across |
| 100 | + threads. |
| 101 | + """ |
| 102 | + |
| 103 | + CHUNK_SIZE: ClassVar[int] = 1000 |
| 104 | + BATCH_SIZE: ClassVar[int] = 1000 |
| 105 | + |
| 106 | + FIXED_SCHEMA: ClassVar[pa.Schema] = schema(n=pa.int64()) |
| 107 | + |
| 108 | + class Meta: |
| 109 | + name = "partitioned_batch_index" |
| 110 | + description = ( |
| 111 | + "Multi-worker partitioned sequence with per-batch batch_index " |
| 112 | + "tagging; parallel scan + ordered sink reassembly." |
| 113 | + ) |
| 114 | + categories = ["generator", "utility"] |
| 115 | + preserves_order = OrderPreservation.FIXED_ORDER |
| 116 | + supports_batch_index = True |
| 117 | + examples = [ |
| 118 | + FunctionExample( |
| 119 | + sql="SELECT * FROM partitioned_batch_index(100)", |
| 120 | + description=( |
| 121 | + "Generate 0..99 in parallel; DuckDB sinks reassemble " |
| 122 | + "output in partition_id (insertion) order." |
| 123 | + ), |
| 124 | + ), |
| 125 | + ] |
| 126 | + |
| 127 | + @classmethod |
| 128 | + def on_init(cls, params: InitParams[_BatchIndexArgs]) -> GlobalInitResponse: |
| 129 | + work_items: list[bytes] = [] |
| 130 | + for partition_id, start_idx in enumerate(range(0, params.args.count, cls.CHUNK_SIZE)): |
| 131 | + end_idx = min(start_idx + cls.CHUNK_SIZE, params.args.count) |
| 132 | + work_items.append(struct.pack(_ITEM_FMT, partition_id, start_idx, end_idx)) |
| 133 | + params.storage.queue_push(work_items) |
| 134 | + return GlobalInitResponse() |
| 135 | + |
| 136 | + @classmethod |
| 137 | + def initial_state(cls, params: ProcessParams[_BatchIndexArgs]) -> _BatchIndexState: |
| 138 | + return _BatchIndexState() |
| 139 | + |
| 140 | + @classmethod |
| 141 | + def process( |
| 142 | + cls, |
| 143 | + params: ProcessParams[_BatchIndexArgs], |
| 144 | + state: _BatchIndexState, |
| 145 | + out: OutputCollector, |
| 146 | + ) -> None: |
| 147 | + if state.partition_id is None or state.current_idx >= (state.current_end or 0): |
| 148 | + work_data = params.storage.queue_pop() |
| 149 | + if work_data is None: |
| 150 | + out.finish() |
| 151 | + return |
| 152 | + partition_id, start, end = struct.unpack(_ITEM_FMT, work_data) |
| 153 | + state.partition_id = partition_id |
| 154 | + state.current_start = start |
| 155 | + state.current_end = end |
| 156 | + state.current_idx = start |
| 157 | + |
| 158 | + batch_end_idx = min(state.current_idx + cls.BATCH_SIZE, state.current_end or 0) |
| 159 | + values = list(range(state.current_idx, batch_end_idx)) |
| 160 | + out.emit( |
| 161 | + pa.RecordBatch.from_pydict({"n": values}, schema=params.output_schema), |
| 162 | + batch_index=state.partition_id, |
| 163 | + ) |
| 164 | + state.current_idx = batch_end_idx |
| 165 | + |
| 166 | + |
| 167 | +# ============================================================================= |
| 168 | +# Two-column variant: partitioned_batch_index_marked(count, chunk_size) |
| 169 | +# ============================================================================= |
| 170 | + |
| 171 | + |
| 172 | +@dataclass(slots=True, frozen=True) |
| 173 | +class _BatchIndexMarkedArgs: |
| 174 | + """Arguments for ``partitioned_batch_index_marked``.""" |
| 175 | + |
| 176 | + count: Annotated[int, Arg(0, doc="Total number of rows to generate", ge=0)] |
| 177 | + chunk_size: Annotated[int, Arg("chunk_size", default=1000, doc="Rows per partition", ge=1)] |
| 178 | + |
| 179 | + |
| 180 | +@dataclass(kw_only=True) |
| 181 | +class _BatchIndexMarkedState(ArrowSerializableDataclass): |
| 182 | + partition_id: int | None = None |
| 183 | + current_start: int | None = None |
| 184 | + current_end: int | None = None |
| 185 | + current_idx: int = 0 |
| 186 | + |
| 187 | + |
| 188 | +@bind_fixed_schema |
| 189 | +@_cardinality_from_count |
| 190 | +class PartitionedBatchIndexMarkedFunction( |
| 191 | + TableFunctionGenerator[_BatchIndexMarkedArgs, _BatchIndexMarkedState] |
| 192 | +): |
| 193 | + """Two-column batch_index fixture for direct ordering observation. |
| 194 | +
|
| 195 | + Output rows are ``(partition_id, seq)`` where ``partition_id`` is the |
| 196 | + queue-push order (matches the emitted batch_index) and ``seq`` counts |
| 197 | + up within each partition starting at 0. Tests assert that no row with |
| 198 | + a higher partition_id appears before a row with a lower one — proving |
| 199 | + that DuckDB's sink-side reassembly worked. |
| 200 | +
|
| 201 | + Projection pushdown is OFF on this fixture so ``SELECT seq FROM …`` |
| 202 | + still gets the partition_id column emitted by the worker; the C++ |
| 203 | + extension's projection then drops it after the ordering metadata has |
| 204 | + been observed. |
| 205 | + """ |
| 206 | + |
| 207 | + BATCH_SIZE: ClassVar[int] = 256 |
| 208 | + |
| 209 | + FIXED_SCHEMA: ClassVar[pa.Schema] = schema( |
| 210 | + partition_id=pa.int64(), |
| 211 | + seq=pa.int64(), |
| 212 | + ) |
| 213 | + |
| 214 | + class Meta: |
| 215 | + name = "partitioned_batch_index_marked" |
| 216 | + description = ( |
| 217 | + "Two-column batch_index demo: rows are (partition_id, seq). Tests " |
| 218 | + "assert that DuckDB's ordered sinks reassemble output in " |
| 219 | + "partition_id order under parallel execution." |
| 220 | + ) |
| 221 | + categories = ["generator", "utility", "testing"] |
| 222 | + preserves_order = OrderPreservation.FIXED_ORDER |
| 223 | + supports_batch_index = True |
| 224 | + projection_pushdown = False |
| 225 | + examples = [ |
| 226 | + FunctionExample( |
| 227 | + sql="SELECT * FROM partitioned_batch_index_marked(100, chunk_size := 25) LIMIT 5", |
| 228 | + description="First 5 rows of partition 0", |
| 229 | + ), |
| 230 | + ] |
| 231 | + |
| 232 | + @classmethod |
| 233 | + def on_init(cls, params: InitParams[_BatchIndexMarkedArgs]) -> GlobalInitResponse: |
| 234 | + work_items: list[bytes] = [] |
| 235 | + chunk_size = params.args.chunk_size |
| 236 | + for partition_id, start_idx in enumerate(range(0, params.args.count, chunk_size)): |
| 237 | + end_idx = min(start_idx + chunk_size, params.args.count) |
| 238 | + work_items.append(struct.pack(_ITEM_FMT, partition_id, start_idx, end_idx)) |
| 239 | + params.storage.queue_push(work_items) |
| 240 | + return GlobalInitResponse() |
| 241 | + |
| 242 | + @classmethod |
| 243 | + def initial_state( |
| 244 | + cls, params: ProcessParams[_BatchIndexMarkedArgs] |
| 245 | + ) -> _BatchIndexMarkedState: |
| 246 | + return _BatchIndexMarkedState() |
| 247 | + |
| 248 | + @classmethod |
| 249 | + def process( |
| 250 | + cls, |
| 251 | + params: ProcessParams[_BatchIndexMarkedArgs], |
| 252 | + state: _BatchIndexMarkedState, |
| 253 | + out: OutputCollector, |
| 254 | + ) -> None: |
| 255 | + if state.partition_id is None or state.current_idx >= (state.current_end or 0): |
| 256 | + work_data = params.storage.queue_pop() |
| 257 | + if work_data is None: |
| 258 | + out.finish() |
| 259 | + return |
| 260 | + partition_id, start, end = struct.unpack(_ITEM_FMT, work_data) |
| 261 | + state.partition_id = partition_id |
| 262 | + state.current_start = start |
| 263 | + state.current_end = end |
| 264 | + state.current_idx = start |
| 265 | + |
| 266 | + batch_end_idx = min(state.current_idx + cls.BATCH_SIZE, state.current_end or 0) |
| 267 | + rows = batch_end_idx - state.current_idx |
| 268 | + partition_ids = [state.partition_id] * rows |
| 269 | + seqs = list(range(state.current_idx - (state.current_start or 0), |
| 270 | + batch_end_idx - (state.current_start or 0))) |
| 271 | + out.emit( |
| 272 | + pa.RecordBatch.from_pydict( |
| 273 | + {"partition_id": partition_ids, "seq": seqs}, |
| 274 | + schema=params.output_schema, |
| 275 | + ), |
| 276 | + batch_index=state.partition_id, |
| 277 | + ) |
| 278 | + state.current_idx = batch_end_idx |
0 commit comments