Skip to content

Commit 519ba40

Browse files
rustyconoverclaude
andcommitted
refactor: consolidate _OutputComplete classes into shared module
Extract the nearly identical _OutputComplete class from scalar_function.py, table_function.py, and table_in_out_function.py into a shared output_complete.py module. This reduces code duplication by consolidating three classes into one: - _ScalarOutputComplete (scalar_function.py) - _OutputComplete (table_function.py) - _OutputComplete (table_in_out_function.py) The unified OutputComplete class handles all use cases with a single from_process_result() method that accepts Output, Message, or None. Also fixes a pre-existing mypy error in vgi/examples/table.py by adding the missing type parameter to pa.Field. Closes: vgi-python-6o0 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
1 parent 8682e0f commit 519ba40

6 files changed

Lines changed: 96 additions & 139 deletions

File tree

‎.beads/issues.jsonl‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
{"id":"vgi-python-3fq","title":"Abstract common worker batch processing logic","description":"Worker batch processing methods _process_scalar_batches (377-466), _process_batches (468-550), and _generate_batches (552-593) share significant structure: IPC writer/reader setup, batch counting/logging, main processing loop. Extract common logic to reduce duplication - consider a BatchProcessor helper class or template method pattern.","status":"open","priority":2,"issue_type":"task","created_at":"2026-01-04T20:06:53.350497-05:00","created_by":"rusty","updated_at":"2026-01-04T20:07:37.598552-05:00"}
55
{"id":"vgi-python-5er","title":"Extract _should_terminate into shared base class","description":"Identical _should_terminate method is copy-pasted in all three function modules. Implementation is always: check if log_message exists and level is EXCEPTION. Move to shared base class (Function or new ProcessingMixin) to eliminate duplication.","status":"open","priority":3,"issue_type":"task","created_at":"2026-01-04T20:06:41.190482-05:00","created_by":"rusty","updated_at":"2026-01-04T20:07:16.071737-05:00","dependencies":[{"issue_id":"vgi-python-5er","depends_on_id":"vgi-python-6o0","type":"blocks","created_at":"2026-01-04T20:07:49.283865-05:00","created_by":"rusty"}]}
66
{"id":"vgi-python-67w","title":"Create example function using DuckDB settings","description":"Create an example function that demonstrates using DuckDB settings to determine its output.\n\nRequirements:\n- Function declares required_settings in Meta\n- Output schema depends on a setting value (e.g., include extra column based on setting)\n- Clear documentation showing the pattern\n\nExample ideas:\n1. TimezoneAwareFunction: Output includes timezone info based on 'timezone' setting\n2. VerboseOutput: Adds debug columns when 'debug_mode' setting is true\n3. NumericPrecision: Uses 'numeric_precision' to determine output type precision\n\nAdd to vgi/examples/ and register in ExampleWorker.","status":"closed","priority":2,"issue_type":"task","created_at":"2026-01-04T13:05:48.503681-05:00","created_by":"rusty","updated_at":"2026-01-04T13:22:23.779895-05:00","closed_at":"2026-01-04T13:22:23.779895-05:00","close_reason":"Added SettingsAwareFunction example","dependencies":[{"issue_id":"vgi-python-67w","depends_on_id":"vgi-python-c2b","type":"blocks","created_at":"2026-01-04T13:06:13.865474-05:00","created_by":"rusty"},{"issue_id":"vgi-python-67w","depends_on_id":"vgi-python-ivf","type":"blocks","created_at":"2026-01-04T13:06:13.890269-05:00","created_by":"rusty"},{"issue_id":"vgi-python-67w","depends_on_id":"vgi-python-bqb","type":"blocks","created_at":"2026-01-04T13:06:13.912531-05:00","created_by":"rusty"},{"issue_id":"vgi-python-67w","depends_on_id":"vgi-python-a99","type":"blocks","created_at":"2026-01-04T13:06:13.936552-05:00","created_by":"rusty"},{"issue_id":"vgi-python-67w","depends_on_id":"vgi-python-j4t","type":"blocks","created_at":"2026-01-04T13:06:13.958494-05:00","created_by":"rusty"}]}
7-
{"id":"vgi-python-6o0","title":"Consolidate _OutputComplete classes into shared module","description":"Three nearly identical _OutputComplete classes exist in scalar_function.py:168-197 (_ScalarOutputComplete), table_function.py:136-175 (_OutputComplete), and table_in_out_function.py:356-400 (_OutputComplete). All are frozen dataclasses with batch field, log_message field, and from_process_result() classmethod. Extract to shared module (e.g., vgi/protocol_types.py) with a single parameterized class.","status":"open","priority":2,"issue_type":"task","created_at":"2026-01-04T20:06:40.893139-05:00","created_by":"rusty","updated_at":"2026-01-04T20:07:15.806567-05:00"}
7+
{"id":"vgi-python-6o0","title":"Consolidate _OutputComplete classes into shared module","description":"Three nearly identical _OutputComplete classes exist in scalar_function.py:168-197 (_ScalarOutputComplete), table_function.py:136-175 (_OutputComplete), and table_in_out_function.py:356-400 (_OutputComplete). All are frozen dataclasses with batch field, log_message field, and from_process_result() classmethod. Extract to shared module (e.g., vgi/protocol_types.py) with a single parameterized class.","status":"in_progress","priority":2,"issue_type":"task","created_at":"2026-01-04T20:06:40.893139-05:00","created_by":"rusty","updated_at":"2026-01-04T21:08:41.602491-05:00"}
88
{"id":"vgi-python-79e","title":"Unify ProtocolInput classes with shared base","description":"ProtocolInput classes in scalar_function.py:151-166 and table_in_out_function.py:109-142 have similar structure with batch and metadata fields. The table_in_out version adds is_finalize logic. Create shared base ProtocolInput in protocol_types.py with table_in_out extending it.","status":"open","priority":3,"issue_type":"task","created_at":"2026-01-04T20:06:41.31917-05:00","created_by":"rusty","updated_at":"2026-01-04T20:07:16.240397-05:00"}
99
{"id":"vgi-python-a99","title":"Add settings accessor to function base classes","description":"Add a property to access DuckDB settings values in function implementations.\n\nChanges needed:\n- Add 'settings: dict[str, str]' property to Function base class\n- Property should return self.invocation.duckdb_settings or empty dict\n- Add convenience method like 'get_setting(name, default=None)'\n- Update ScalarFunction, TableFunctionGenerator, TableInOutFunction\n\nExample usage in function:\ndef compute(self, batch):\n tz = self.get_setting('timezone', 'UTC')\n # or\n tz = self.settings.get('timezone', 'UTC')","status":"closed","priority":2,"issue_type":"task","created_at":"2026-01-04T13:05:48.221602-05:00","created_by":"rusty","updated_at":"2026-01-04T13:20:41.171991-05:00","closed_at":"2026-01-04T13:20:41.171991-05:00","close_reason":"Implementation complete, all tests pass","dependencies":[{"issue_id":"vgi-python-a99","depends_on_id":"vgi-python-aad","type":"blocks","created_at":"2026-01-04T13:06:13.738212-05:00","created_by":"rusty"}]}
1010
{"id":"vgi-python-aad","title":"Design: DuckDB settings/pragmas access for VGI functions","description":"Design how VGI functions can declare required DuckDB settings/pragmas in their Meta class, and how these settings values should be passed during the bind phase.\n\nKey design decisions:\n1. How to declare required settings in function Meta (e.g., required_settings = ['timezone', 'threads'])\n2. How to add settings to Invocation dataclass\n3. How settings values should be accessed in function code\n4. Serialization format for settings in Arrow IPC\n\nRecommendation: Add 'duckdb_settings: dict[str, str] | None' to Invocation and 'required_settings: list[str]' to Meta class.","status":"closed","priority":1,"issue_type":"task","created_at":"2026-01-04T13:05:47.619105-05:00","created_by":"rusty","updated_at":"2026-01-04T13:11:13.197139-05:00","closed_at":"2026-01-04T13:11:13.197139-05:00","close_reason":"Design document created at docs/design-duckdb-settings.md"}

‎vgi/examples/table.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -694,7 +694,7 @@ def output_schema(self) -> pa.Schema:
694694
When vgi_verbose_mode is "true", includes an extra "details" column.
695695
This demonstrates how settings can affect the bind result.
696696
"""
697-
fields: list[pa.Field] = [
697+
fields: list[pa.Field[pa.DataType]] = [
698698
pa.field("id", pa.int64()),
699699
pa.field("value", pa.float64()),
700700
]

‎vgi/output_complete.py‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
"""Internal output normalization for VGI function generators.
2+
3+
This module provides the _OutputComplete class used by all function types
4+
to normalize generator yields into a consistent format with guaranteed
5+
non-None batches.
6+
7+
This is an internal module - users should not import from here directly.
8+
"""
9+
10+
from dataclasses import dataclass
11+
from typing import TYPE_CHECKING
12+
13+
import pyarrow as pa
14+
15+
import vgi.log
16+
17+
if TYPE_CHECKING:
18+
from vgi.table_function import Output as TableOutput
19+
from vgi.table_in_out_function import Output as TableInOutOutput
20+
21+
__all__ = ["OutputComplete"]
22+
23+
24+
@dataclass(frozen=True, slots=True)
25+
class OutputComplete:
26+
"""Internal: Output with guaranteed non-None batch.
27+
28+
Used by the framework to normalize generator yields. When the user yields
29+
None, Output with None batch, or Message, this class ensures we always
30+
have a valid RecordBatch for the protocol.
31+
32+
Attributes:
33+
batch: Always a valid RecordBatch (never None).
34+
has_more: If True, generator expects another send() call.
35+
Only used by TableInOutGeneratorFunction.
36+
log_message: Present when user yielded Message directly.
37+
38+
"""
39+
40+
batch: pa.RecordBatch
41+
has_more: bool = False
42+
log_message: vgi.log.Message | None = None
43+
44+
@classmethod
45+
def from_process_result(
46+
cls,
47+
source: "vgi.log.Message | TableOutput | TableInOutOutput | None",
48+
empty_batch: pa.RecordBatch,
49+
) -> "OutputComplete":
50+
"""Create from user's yield value.
51+
52+
Args:
53+
source: What the user yielded (Output, Message, or None).
54+
empty_batch: Empty batch to substitute when needed.
55+
56+
Returns:
57+
Normalized output with guaranteed non-None batch.
58+
59+
"""
60+
if source is None:
61+
return cls(batch=empty_batch)
62+
if isinstance(source, vgi.log.Message):
63+
# When yielding a log message, has_more=True so the caller
64+
# re-sends the current input after the message is processed
65+
return cls(batch=empty_batch, has_more=True, log_message=source)
66+
# source is Output (either TableOutput or TableInOutOutput)
67+
# TableOutput doesn't have has_more, TableInOutOutput does
68+
has_more = getattr(source, "has_more", False)
69+
return cls(
70+
batch=source.batch if source.batch is not None else empty_batch,
71+
has_more=has_more,
72+
)

‎vgi/scalar_function.py‎

Lines changed: 8 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ def compute(self, batch: pa.RecordBatch) -> pa.Array:
5050
import vgi.function
5151
import vgi.log
5252
from vgi.exceptions import SchemaValidationError
53+
from vgi.output_complete import OutputComplete
5354
from vgi.table_function import Output, ProtocolOutput
5455

5556
__all__ = [
@@ -165,37 +166,6 @@ class ProtocolInput:
165166
metadata: pa.KeyValueMetadata | None = None
166167

167168

168-
@dataclass(frozen=True, slots=True)
169-
class _ScalarOutputComplete:
170-
"""Internal: Output with guaranteed non-None batch for scalar functions."""
171-
172-
batch: pa.RecordBatch
173-
log_message: vgi.log.Message | None = None
174-
175-
@classmethod
176-
def from_process_result(
177-
cls,
178-
source: vgi.log.Message | Output,
179-
empty_batch: pa.RecordBatch,
180-
) -> _ScalarOutputComplete:
181-
"""Create from user's yield value.
182-
183-
Args:
184-
source: What the user yielded (Output or Message).
185-
empty_batch: Empty batch to substitute when yielding Message.
186-
187-
Returns:
188-
Normalized output with guaranteed non-None batch.
189-
190-
"""
191-
if isinstance(source, vgi.log.Message):
192-
return cls(batch=empty_batch, log_message=source)
193-
# source is Output
194-
return cls(
195-
batch=source.batch if source.batch is not None else empty_batch,
196-
)
197-
198-
199169
class ScalarFunctionGenerator(vgi.function.Function[vgi.function.FunctionInitInput]):
200170
"""Generator-based base class for scalar functions.
201171
@@ -299,23 +269,23 @@ def _process_and_validate(
299269
self,
300270
generator: ScalarOutputGenerator,
301271
input_batch: pa.RecordBatch,
302-
) -> _ScalarOutputComplete:
272+
) -> OutputComplete:
303273
"""Process a batch and validate schemas and row count.
304274
305275
Args:
306276
generator: The user's process() generator.
307277
input_batch: The input RecordBatch to process.
308278
309279
Returns:
310-
_ScalarOutputComplete with validated output batch.
280+
OutputComplete with validated output batch.
311281
312282
Raises:
313283
SchemaValidationError: If input or output batch schema doesn't match.
314284
RowCountMismatchError: If output row count doesn't match input.
315285
316286
"""
317287
self._validate_input_schema(input_batch)
318-
result: _ScalarOutputComplete = _ScalarOutputComplete.from_process_result(
288+
result: OutputComplete = OutputComplete.from_process_result(
319289
generator.send(input_batch),
320290
self.empty_output_batch,
321291
)
@@ -330,22 +300,22 @@ def _process_with_exception_handling(
330300
self,
331301
generator: ScalarOutputGenerator,
332302
input_batch: pa.RecordBatch,
333-
) -> _ScalarOutputComplete:
303+
) -> OutputComplete:
334304
"""Process a batch with exception handling.
335305
336306
Wraps _process_and_validate to catch exceptions and convert them
337-
to _ScalarOutputComplete with an error log message.
307+
to OutputComplete with an error log message.
338308
"""
339309
try:
340310
return self._process_and_validate(generator, input_batch)
341311
except Exception as e:
342-
return _ScalarOutputComplete(
312+
return OutputComplete(
343313
batch=self.empty_output_batch,
344314
log_message=vgi.log.Message.from_exception(e),
345315
)
346316

347317
@final
348-
def _should_terminate(self, result: _ScalarOutputComplete) -> bool:
318+
def _should_terminate(self, result: OutputComplete) -> bool:
349319
"""Check if processing should terminate due to an exception."""
350320
return (
351321
result.log_message is not None

‎vgi/table_function.py‎

Lines changed: 7 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
import vgi.function
3232
import vgi.ipc_utils
3333
import vgi.log
34+
from vgi.output_complete import OutputComplete
3435

3536
__all__ = [
3637
"TableCardinality",
@@ -133,47 +134,6 @@ class Output:
133134
OutputGenerator = Generator[vgi.log.Message | Output, None, None]
134135

135136

136-
@dataclass(frozen=True, slots=True)
137-
class _OutputComplete:
138-
"""Internal: Output with guaranteed non-None batch.
139-
140-
Used by the framework to normalize generator yields. When the user yields
141-
None, Output with None batch, or Message, this class ensures we always
142-
have a valid RecordBatch for the protocol.
143-
144-
Attributes:
145-
batch: Always a valid RecordBatch (never None).
146-
log_message: Present when user yielded Message directly.
147-
148-
"""
149-
150-
batch: pa.RecordBatch
151-
log_message: vgi.log.Message | None = None
152-
153-
@classmethod
154-
def from_process_result(
155-
cls,
156-
source: vgi.log.Message | Output,
157-
empty_batch: pa.RecordBatch,
158-
) -> "_OutputComplete":
159-
"""Create from user's yield value.
160-
161-
Args:
162-
source: What the user yielded (Output or Message).
163-
empty_batch: Empty batch to substitute when needed.
164-
165-
Returns:
166-
Normalized output with guaranteed non-None batch.
167-
168-
"""
169-
if isinstance(source, vgi.log.Message):
170-
return cls(batch=empty_batch, log_message=source)
171-
# source is Output
172-
return cls(
173-
batch=source.batch if source.batch is not None else empty_batch,
174-
)
175-
176-
177137
@dataclass(frozen=True, slots=True)
178138
class ProtocolOutput:
179139
"""Output yielded by the generator after each send().
@@ -210,7 +170,7 @@ def metadata(
210170
)
211171

212172
@classmethod
213-
def from_process_result(cls, process_result: "_OutputComplete") -> "ProtocolOutput":
173+
def from_process_result(cls, process_result: "OutputComplete") -> "ProtocolOutput":
214174
"""Create a ProtocolOutput from an Output and status.
215175
216176
Args:
@@ -383,7 +343,7 @@ def process(self) -> OutputGenerator:
383343
"""
384344

385345
@final
386-
def _process_and_validate(self, generator: OutputGenerator) -> _OutputComplete:
346+
def _process_and_validate(self, generator: OutputGenerator) -> OutputComplete:
387347
"""Process a batch and validate the output schema.
388348
389349
Converts the result of the generator to OutputComplete, and
@@ -399,7 +359,7 @@ def _process_and_validate(self, generator: OutputGenerator) -> _OutputComplete:
399359
SchemaValidationError: If output batch schema doesn't match.
400360
401361
"""
402-
result: _OutputComplete = _OutputComplete.from_process_result(
362+
result: OutputComplete = OutputComplete.from_process_result(
403363
generator.send(None),
404364
self.empty_output_batch,
405365
)
@@ -410,7 +370,7 @@ def _process_and_validate(self, generator: OutputGenerator) -> _OutputComplete:
410370
def _process_with_exception_handling(
411371
self,
412372
generator: OutputGenerator,
413-
) -> _OutputComplete:
373+
) -> OutputComplete:
414374
"""Process a batch with exception handling.
415375
416376
Wraps _process_and_validate to catch exceptions and convert them
@@ -424,13 +384,13 @@ def _process_with_exception_handling(
424384
except StopIteration:
425385
raise
426386
except Exception as e:
427-
return _OutputComplete(
387+
return OutputComplete(
428388
batch=self.empty_output_batch,
429389
log_message=vgi.log.Message.from_exception(e),
430390
)
431391

432392
@final
433-
def _should_terminate(self, result: _OutputComplete) -> bool:
393+
def _should_terminate(self, result: OutputComplete) -> bool:
434394
"""Check if processing should terminate due to an exception."""
435395
return (
436396
result.log_message is not None

0 commit comments

Comments
 (0)