|
| 1 | +"""Tests for scalar function base classes.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from typing import Any |
| 6 | + |
| 7 | +import pyarrow as pa |
| 8 | +import pytest |
| 9 | +import structlog |
| 10 | + |
| 11 | +from vgi.arguments import Arg |
| 12 | +from vgi.function import Arguments, Invocation |
| 13 | +from vgi.log import Level, Message |
| 14 | +from vgi.scalar_function import ( |
| 15 | + Output, |
| 16 | + OutputGenerator, |
| 17 | + ProtocolInput, |
| 18 | + ScalarFunction, |
| 19 | + ScalarFunctionGenerator, |
| 20 | +) |
| 21 | +from vgi.table_function import SchemaValidationError |
| 22 | + |
| 23 | + |
| 24 | +def create_invocation(input_schema: pa.Schema) -> Invocation: |
| 25 | + """Create a test invocation with the given input schema.""" |
| 26 | + return Invocation( |
| 27 | + function_name="test_function", |
| 28 | + in_out_function_input_schema=input_schema, |
| 29 | + correlation_id="test-correlation", |
| 30 | + invocation_id=b"test-invocation", |
| 31 | + arguments=Arguments(), |
| 32 | + ) |
| 33 | + |
| 34 | + |
| 35 | +class TestScalarFunctionGenerator: |
| 36 | + """Tests for the generator-based ScalarFunctionGenerator.""" |
| 37 | + |
| 38 | + def test_basic_process(self) -> None: |
| 39 | + """Test basic processing of batches.""" |
| 40 | + |
| 41 | + class DoubleColumn(ScalarFunctionGenerator): |
| 42 | + @property |
| 43 | + def output_schema(self) -> pa.Schema: |
| 44 | + return pa.schema([("result", pa.int64())]) |
| 45 | + |
| 46 | + def process(self, batch: pa.RecordBatch) -> OutputGenerator: |
| 47 | + _ = yield None |
| 48 | + import pyarrow.compute as pc |
| 49 | + |
| 50 | + while True: |
| 51 | + result = pc.multiply(batch.column("x"), 2) |
| 52 | + output = pa.RecordBatch.from_arrays( |
| 53 | + [result], schema=self.output_schema |
| 54 | + ) |
| 55 | + received = yield Output(output) |
| 56 | + if received is None: |
| 57 | + break |
| 58 | + batch = received |
| 59 | + |
| 60 | + input_schema = pa.schema([("x", pa.int64())]) |
| 61 | + invocation = create_invocation(input_schema) |
| 62 | + logger = structlog.get_logger() |
| 63 | + |
| 64 | + func = DoubleColumn(invocation=invocation, logger=logger) |
| 65 | + |
| 66 | + # Run the protocol |
| 67 | + generator = func.run() |
| 68 | + next(generator) # Prime |
| 69 | + |
| 70 | + # Send a batch |
| 71 | + input_batch = pa.RecordBatch.from_pydict( |
| 72 | + {"x": [1, 2, 3]}, schema=input_schema |
| 73 | + ) |
| 74 | + output = generator.send(ProtocolInput(batch=input_batch)) |
| 75 | + |
| 76 | + assert output.batch is not None |
| 77 | + assert output.batch.num_rows == 3 |
| 78 | + assert output.batch.column("result").to_pylist() == [2, 4, 6] |
| 79 | + |
| 80 | + def test_requires_input_schema(self) -> None: |
| 81 | + """Test that input schema is required.""" |
| 82 | + |
| 83 | + class TestFunc(ScalarFunctionGenerator): |
| 84 | + @property |
| 85 | + def output_schema(self) -> pa.Schema: |
| 86 | + return pa.schema([("result", pa.int64())]) |
| 87 | + |
| 88 | + def process(self, batch: pa.RecordBatch) -> OutputGenerator: |
| 89 | + _ = yield None |
| 90 | + |
| 91 | + invocation = Invocation( |
| 92 | + function_name="test", |
| 93 | + in_out_function_input_schema=None, |
| 94 | + correlation_id="test", |
| 95 | + invocation_id=None, |
| 96 | + arguments=Arguments(), |
| 97 | + ) |
| 98 | + |
| 99 | + with pytest.raises(ValueError, match="requires an input schema"): |
| 100 | + TestFunc(invocation=invocation, logger=structlog.get_logger()) |
| 101 | + |
| 102 | + def test_requires_single_column_output(self) -> None: |
| 103 | + """Test that output schema must have exactly one column.""" |
| 104 | + |
| 105 | + class TwoColumnOutput(ScalarFunctionGenerator): |
| 106 | + @property |
| 107 | + def output_schema(self) -> pa.Schema: |
| 108 | + return pa.schema([("a", pa.int64()), ("b", pa.int64())]) |
| 109 | + |
| 110 | + def process(self, batch: pa.RecordBatch) -> OutputGenerator: |
| 111 | + _ = yield None |
| 112 | + |
| 113 | + input_schema = pa.schema([("x", pa.int64())]) |
| 114 | + invocation = create_invocation(input_schema) |
| 115 | + |
| 116 | + with pytest.raises(SchemaValidationError, match="exactly 1 output column"): |
| 117 | + TwoColumnOutput(invocation=invocation, logger=structlog.get_logger()) |
| 118 | + |
| 119 | + def test_log_message_support(self) -> None: |
| 120 | + """Test that log messages can be yielded.""" |
| 121 | + |
| 122 | + class LoggingScalar(ScalarFunctionGenerator): |
| 123 | + @property |
| 124 | + def output_schema(self) -> pa.Schema: |
| 125 | + return pa.schema([("result", pa.int64())]) |
| 126 | + |
| 127 | + def process(self, batch: pa.RecordBatch) -> OutputGenerator: |
| 128 | + _ = yield None |
| 129 | + import pyarrow.compute as pc |
| 130 | + |
| 131 | + while True: |
| 132 | + yield Message(Level.INFO, f"Processing {batch.num_rows} rows") |
| 133 | + result = pc.multiply(batch.column("x"), 2) |
| 134 | + output = pa.RecordBatch.from_arrays( |
| 135 | + [result], schema=self.output_schema |
| 136 | + ) |
| 137 | + received = yield Output(output) |
| 138 | + if received is None: |
| 139 | + break |
| 140 | + batch = received |
| 141 | + |
| 142 | + input_schema = pa.schema([("x", pa.int64())]) |
| 143 | + invocation = create_invocation(input_schema) |
| 144 | + func = LoggingScalar(invocation=invocation, logger=structlog.get_logger()) |
| 145 | + |
| 146 | + generator = func.run() |
| 147 | + next(generator) |
| 148 | + |
| 149 | + input_batch = pa.RecordBatch.from_pydict( |
| 150 | + {"x": [1, 2, 3]}, schema=input_schema |
| 151 | + ) |
| 152 | + |
| 153 | + # First yield should be the log message |
| 154 | + output = generator.send(ProtocolInput(batch=input_batch)) |
| 155 | + assert output.log_message is not None |
| 156 | + assert output.log_message.level == Level.INFO |
| 157 | + assert "Processing 3 rows" in output.log_message.message |
| 158 | + |
| 159 | + # Re-send to get actual output |
| 160 | + output = generator.send(ProtocolInput(batch=input_batch)) |
| 161 | + assert output.batch is not None |
| 162 | + assert output.batch.column("result").to_pylist() == [2, 4, 6] |
| 163 | + |
| 164 | + |
| 165 | +class TestScalarFunction: |
| 166 | + """Tests for the callback-based ScalarFunction.""" |
| 167 | + |
| 168 | + def test_basic_compute(self) -> None: |
| 169 | + """Test basic compute() method.""" |
| 170 | + |
| 171 | + class DoubleColumn(ScalarFunction): |
| 172 | + column = Arg[str](0) |
| 173 | + |
| 174 | + @property |
| 175 | + def output_type(self) -> pa.DataType: |
| 176 | + return pa.int64() |
| 177 | + |
| 178 | + def compute(self, batch: pa.RecordBatch) -> pa.Array[Any]: |
| 179 | + import pyarrow.compute as pc |
| 180 | + |
| 181 | + return pc.multiply(batch.column(self.column), 2) |
| 182 | + |
| 183 | + input_schema = pa.schema([("x", pa.int64())]) |
| 184 | + invocation = Invocation( |
| 185 | + function_name="test", |
| 186 | + in_out_function_input_schema=input_schema, |
| 187 | + correlation_id="test", |
| 188 | + invocation_id=None, |
| 189 | + arguments=Arguments(positional=(pa.scalar("x"),)), |
| 190 | + ) |
| 191 | + |
| 192 | + func = DoubleColumn(invocation=invocation, logger=structlog.get_logger()) |
| 193 | + |
| 194 | + # Run the protocol |
| 195 | + generator = func.run() |
| 196 | + next(generator) |
| 197 | + |
| 198 | + input_batch = pa.RecordBatch.from_pydict( |
| 199 | + {"x": [1, 2, 3]}, schema=input_schema |
| 200 | + ) |
| 201 | + output = generator.send(ProtocolInput(batch=input_batch)) |
| 202 | + |
| 203 | + assert output.batch is not None |
| 204 | + assert output.batch.num_rows == 3 |
| 205 | + assert output.batch.column("result").to_pylist() == [2, 4, 6] |
| 206 | + |
| 207 | + def test_custom_output_name(self) -> None: |
| 208 | + """Test custom output column name.""" |
| 209 | + |
| 210 | + class CustomName(ScalarFunction): |
| 211 | + @property |
| 212 | + def output_name(self) -> str: |
| 213 | + return "doubled" |
| 214 | + |
| 215 | + @property |
| 216 | + def output_type(self) -> pa.DataType: |
| 217 | + return pa.int64() |
| 218 | + |
| 219 | + def compute(self, batch: pa.RecordBatch) -> pa.Array[Any]: |
| 220 | + import pyarrow.compute as pc |
| 221 | + |
| 222 | + return pc.multiply(batch.column("x"), 2) |
| 223 | + |
| 224 | + input_schema = pa.schema([("x", pa.int64())]) |
| 225 | + invocation = create_invocation(input_schema) |
| 226 | + |
| 227 | + func = CustomName(invocation=invocation, logger=structlog.get_logger()) |
| 228 | + assert func.output_schema.names == ["doubled"] |
| 229 | + |
| 230 | + def test_log_method(self) -> None: |
| 231 | + """Test self.log() method.""" |
| 232 | + |
| 233 | + class LoggingFunc(ScalarFunction): |
| 234 | + @property |
| 235 | + def output_type(self) -> pa.DataType: |
| 236 | + return pa.int64() |
| 237 | + |
| 238 | + def compute(self, batch: pa.RecordBatch) -> pa.Array[Any]: |
| 239 | + import pyarrow.compute as pc |
| 240 | + |
| 241 | + self.log(Level.INFO, f"Processing {batch.num_rows} rows") |
| 242 | + return pc.multiply(batch.column("x"), 2) |
| 243 | + |
| 244 | + input_schema = pa.schema([("x", pa.int64())]) |
| 245 | + invocation = create_invocation(input_schema) |
| 246 | + func = LoggingFunc(invocation=invocation, logger=structlog.get_logger()) |
| 247 | + |
| 248 | + generator = func.run() |
| 249 | + next(generator) |
| 250 | + |
| 251 | + input_batch = pa.RecordBatch.from_pydict( |
| 252 | + {"x": [1, 2, 3]}, schema=input_schema |
| 253 | + ) |
| 254 | + |
| 255 | + # First yield should be the log message |
| 256 | + output = generator.send(ProtocolInput(batch=input_batch)) |
| 257 | + assert output.log_message is not None |
| 258 | + assert output.log_message.level == Level.INFO |
| 259 | + assert "Processing 3 rows" in output.log_message.message |
| 260 | + |
| 261 | + # Re-send to get actual output |
| 262 | + output = generator.send(ProtocolInput(batch=input_batch)) |
| 263 | + assert output.batch is not None |
| 264 | + assert output.batch.column("result").to_pylist() == [2, 4, 6] |
| 265 | + |
| 266 | + def test_row_count_validation(self) -> None: |
| 267 | + """Test that row count mismatch raises error.""" |
| 268 | + |
| 269 | + class WrongRowCount(ScalarFunction): |
| 270 | + @property |
| 271 | + def output_type(self) -> pa.DataType: |
| 272 | + return pa.int64() |
| 273 | + |
| 274 | + def compute(self, batch: pa.RecordBatch) -> pa.Array[Any]: |
| 275 | + # Return wrong number of rows |
| 276 | + return pa.array([1, 2]) |
| 277 | + |
| 278 | + input_schema = pa.schema([("x", pa.int64())]) |
| 279 | + invocation = create_invocation(input_schema) |
| 280 | + func = WrongRowCount(invocation=invocation, logger=structlog.get_logger()) |
| 281 | + |
| 282 | + generator = func.run() |
| 283 | + next(generator) |
| 284 | + |
| 285 | + input_batch = pa.RecordBatch.from_pydict( |
| 286 | + {"x": [1, 2, 3]}, schema=input_schema |
| 287 | + ) |
| 288 | + output = generator.send(ProtocolInput(batch=input_batch)) |
| 289 | + |
| 290 | + # Should have an exception log message |
| 291 | + assert output.log_message is not None |
| 292 | + assert output.log_message.level == Level.EXCEPTION |
| 293 | + assert "same row count" in output.log_message.message.lower() |
| 294 | + |
| 295 | + def test_empty_batch(self) -> None: |
| 296 | + """Test handling of empty batches.""" |
| 297 | + |
| 298 | + class DoubleFunc(ScalarFunction): |
| 299 | + @property |
| 300 | + def output_type(self) -> pa.DataType: |
| 301 | + return pa.int64() |
| 302 | + |
| 303 | + def compute(self, batch: pa.RecordBatch) -> pa.Array[Any]: |
| 304 | + import pyarrow.compute as pc |
| 305 | + |
| 306 | + return pc.multiply(batch.column("x"), 2) |
| 307 | + |
| 308 | + input_schema = pa.schema([("x", pa.int64())]) |
| 309 | + invocation = create_invocation(input_schema) |
| 310 | + func = DoubleFunc(invocation=invocation, logger=structlog.get_logger()) |
| 311 | + |
| 312 | + generator = func.run() |
| 313 | + next(generator) |
| 314 | + |
| 315 | + # Empty batch |
| 316 | + input_batch = pa.RecordBatch.from_pydict({"x": []}, schema=input_schema) |
| 317 | + output = generator.send(ProtocolInput(batch=input_batch)) |
| 318 | + |
| 319 | + assert output.batch is not None |
| 320 | + assert output.batch.num_rows == 0 |
0 commit comments