Skip to content

Commit 9c32ce6

Browse files
committed
fix missing file
1 parent 4119297 commit 9c32ce6

1 file changed

Lines changed: 323 additions & 0 deletions

File tree

‎tests/test_typed_work_queue.py‎

Lines changed: 323 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,323 @@
1+
"""Tests for typed work queue methods: enqueue_work_items and dequeue_work_item."""
2+
3+
from __future__ import annotations
4+
5+
import pickle
6+
from dataclasses import dataclass
7+
from typing import Any, ClassVar, Self, cast
8+
9+
import pyarrow as pa
10+
11+
from vgi.arguments import Arg, Arguments
12+
from vgi.function import Serializable
13+
from vgi.invocation import InitResult
14+
from vgi.table_function import (
15+
Output,
16+
OutputGenerator,
17+
TableCardinality,
18+
TableFunctionGenerator,
19+
TableFunctionInitInput,
20+
)
21+
from vgi.testing import TableFunctionTestClient
22+
23+
24+
@dataclass
25+
class RangeWorkItem:
26+
"""A work item representing a range of integers to generate."""
27+
28+
start: int
29+
end: int
30+
31+
def serialize(self) -> bytes:
32+
"""Serialize this work item to bytes."""
33+
return pickle.dumps((self.start, self.end))
34+
35+
@classmethod
36+
def deserialize(cls, data: bytes) -> Self:
37+
"""Deserialize a work item from bytes."""
38+
start, end = pickle.loads(data)
39+
return cls(start, end)
40+
41+
42+
@dataclass
43+
class FileChunk:
44+
"""A work item representing a chunk of a file to process."""
45+
46+
path: str
47+
offset: int
48+
length: int
49+
50+
def serialize(self) -> bytes:
51+
"""Serialize this work item to bytes."""
52+
return pickle.dumps(
53+
{
54+
"path": self.path,
55+
"offset": self.offset,
56+
"length": self.length,
57+
}
58+
)
59+
60+
@classmethod
61+
def deserialize(cls, data: bytes) -> Self:
62+
"""Deserialize a work item from bytes."""
63+
d = pickle.loads(data)
64+
return cls(path=d["path"], offset=d["offset"], length=d["length"])
65+
66+
67+
class TypedPartitionedRangeFunction(TableFunctionGenerator):
68+
"""A table function that uses typed work queue methods.
69+
70+
This is similar to PartitionedRangeFunction but uses the typed
71+
enqueue_work_items and dequeue_work_item methods.
72+
"""
73+
74+
class Meta:
75+
"""Metadata for TypedPartitionedRangeFunction."""
76+
77+
name = "typed_partitioned_range"
78+
description = "Generates a partitioned range using typed work queue"
79+
max_workers = 1 # Single worker for deterministic testing
80+
81+
count: int = Arg[int](0, doc="Total count") # type: ignore[assignment]
82+
83+
CHUNK_SIZE: ClassVar[int] = 10
84+
85+
@property
86+
def output_schema(self) -> pa.Schema:
87+
"""Return output schema with single integer column."""
88+
return pa.schema([pa.field("value", pa.int64())])
89+
90+
@property
91+
def cardinality(self) -> TableCardinality:
92+
"""Return cardinality estimate."""
93+
return TableCardinality(estimate=self.count, max=self.count)
94+
95+
def initialize_global_state(self, init_input: pa.RecordBatch) -> InitResult:
96+
"""Populate the work queue with typed range work items."""
97+
self.init_input = TableFunctionInitInput.deserialize(init_input)
98+
self.execution_identifier = self.storage.global_put(self.init_input.serialize())
99+
100+
# Create typed work items
101+
work_items: list[RangeWorkItem] = []
102+
for start in range(0, self.count, self.CHUNK_SIZE):
103+
end = min(start + self.CHUNK_SIZE, self.count)
104+
work_items.append(RangeWorkItem(start=start, end=end))
105+
106+
if work_items:
107+
self.enqueue_work_items(work_items)
108+
109+
return InitResult(self.execution_identifier)
110+
111+
def process(self) -> OutputGenerator:
112+
"""Generate values by pulling typed work items from the queue."""
113+
while True:
114+
item = self.dequeue_work_item(RangeWorkItem)
115+
if item is None:
116+
break
117+
118+
# item is fully typed as RangeWorkItem
119+
values = list(range(item.start, item.end))
120+
yield Output(
121+
pa.RecordBatch.from_pydict({"value": values}, schema=self.output_schema)
122+
)
123+
124+
125+
class FileProcessingFunction(TableFunctionGenerator):
126+
"""A table function that simulates file chunk processing with typed work items."""
127+
128+
class Meta:
129+
"""Metadata for FileProcessingFunction."""
130+
131+
name = "file_processing"
132+
description = "Simulates processing file chunks"
133+
max_workers = 1
134+
135+
num_files: int = Arg[int](0, doc="Number of files") # type: ignore[assignment]
136+
chunks_per_file: int = Arg[int](1, doc="Chunks per file") # type: ignore[assignment]
137+
138+
@property
139+
def output_schema(self) -> pa.Schema:
140+
"""Return output schema with file chunk columns."""
141+
return pa.schema(
142+
cast(
143+
list[tuple[str, pa.DataType]],
144+
[
145+
("path", pa.string()),
146+
("offset", pa.int64()),
147+
("length", pa.int64()),
148+
],
149+
)
150+
)
151+
152+
@property
153+
def cardinality(self) -> TableCardinality:
154+
"""Return cardinality estimate."""
155+
return TableCardinality(
156+
estimate=self.num_files * self.chunks_per_file,
157+
max=self.num_files * self.chunks_per_file,
158+
)
159+
160+
def initialize_global_state(self, init_input: pa.RecordBatch) -> InitResult:
161+
"""Populate the work queue with file chunks."""
162+
self.init_input = TableFunctionInitInput.deserialize(init_input)
163+
self.execution_identifier = self.storage.global_put(self.init_input.serialize())
164+
165+
# Create file chunk work items
166+
work_items: list[FileChunk] = []
167+
for i in range(self.num_files):
168+
for j in range(self.chunks_per_file):
169+
work_items.append(
170+
FileChunk(
171+
path=f"/data/file_{i}.csv",
172+
offset=j * 1000,
173+
length=1000,
174+
)
175+
)
176+
177+
if work_items:
178+
self.enqueue_work_items(work_items)
179+
180+
return InitResult(self.execution_identifier)
181+
182+
def process(self) -> OutputGenerator:
183+
"""Process file chunks from the typed work queue."""
184+
while True:
185+
chunk = self.dequeue_work_item(FileChunk)
186+
if chunk is None:
187+
break
188+
189+
# chunk is fully typed as FileChunk
190+
yield Output(
191+
pa.RecordBatch.from_pydict(
192+
{
193+
"path": [chunk.path],
194+
"offset": [chunk.offset],
195+
"length": [chunk.length],
196+
},
197+
schema=self.output_schema,
198+
)
199+
)
200+
201+
202+
def _sorted_values(values: list[Any]) -> list[int]:
203+
"""Sort a list of values, filtering out None."""
204+
return sorted(v for v in values if v is not None)
205+
206+
207+
class TestTypedWorkQueueMethods:
208+
"""Tests for enqueue_work_items and dequeue_work_item methods."""
209+
210+
def test_typed_range_generates_correct_values(self) -> None:
211+
"""Typed work queue should produce the complete range of values."""
212+
with TableFunctionTestClient(TypedPartitionedRangeFunction) as client:
213+
outputs = list(
214+
client.table_function(arguments=Arguments(positional=(pa.scalar(25),)))
215+
)
216+
217+
table = pa.Table.from_batches(outputs)
218+
assert table.num_rows == 25
219+
220+
values = _sorted_values(table.column("value").to_pylist())
221+
assert values == list(range(25))
222+
223+
def test_typed_range_empty_count(self) -> None:
224+
"""Typed work queue with count=0 should produce no output."""
225+
with TableFunctionTestClient(TypedPartitionedRangeFunction) as client:
226+
outputs = list(
227+
client.table_function(arguments=Arguments(positional=(pa.scalar(0),)))
228+
)
229+
230+
assert len(outputs) == 0
231+
232+
def test_typed_range_single_chunk(self) -> None:
233+
"""Typed work queue with small count should produce single chunk."""
234+
with TableFunctionTestClient(TypedPartitionedRangeFunction) as client:
235+
outputs = list(
236+
client.table_function(arguments=Arguments(positional=(pa.scalar(5),)))
237+
)
238+
239+
table = pa.Table.from_batches(outputs)
240+
assert table.num_rows == 5
241+
242+
values = _sorted_values(table.column("value").to_pylist())
243+
assert values == list(range(5))
244+
245+
def test_file_processing_generates_all_chunks(self) -> None:
246+
"""File processing function should generate all file chunks."""
247+
with TableFunctionTestClient(FileProcessingFunction) as client:
248+
outputs = list(
249+
client.table_function(
250+
arguments=Arguments(positional=(pa.scalar(3), pa.scalar(2)))
251+
)
252+
)
253+
254+
table = pa.Table.from_batches(outputs)
255+
assert table.num_rows == 6 # 3 files * 2 chunks
256+
257+
# Verify we got all expected file paths
258+
paths = set(table.column("path").to_pylist())
259+
assert paths == {"/data/file_0.csv", "/data/file_1.csv", "/data/file_2.csv"}
260+
261+
def test_file_processing_chunk_structure(self) -> None:
262+
"""File chunks should have correct offset and length."""
263+
with TableFunctionTestClient(FileProcessingFunction) as client:
264+
outputs = list(
265+
client.table_function(
266+
arguments=Arguments(positional=(pa.scalar(1), pa.scalar(3)))
267+
)
268+
)
269+
270+
table = pa.Table.from_batches(outputs)
271+
assert table.num_rows == 3
272+
273+
# All from same file
274+
paths = table.column("path").to_pylist()
275+
assert all(p == "/data/file_0.csv" for p in paths)
276+
277+
# Offsets should be 0, 1000, 2000
278+
offsets = _sorted_values(table.column("offset").to_pylist())
279+
assert offsets == [0, 1000, 2000]
280+
281+
# All lengths should be 1000
282+
lengths = table.column("length").to_pylist()
283+
assert all(ln == 1000 for ln in lengths)
284+
285+
286+
class TestSerializableProtocol:
287+
"""Tests for the Serializable protocol implementation."""
288+
289+
def test_range_work_item_roundtrip(self) -> None:
290+
"""RangeWorkItem should serialize and deserialize correctly."""
291+
original = RangeWorkItem(start=100, end=200)
292+
serialized = original.serialize()
293+
restored = RangeWorkItem.deserialize(serialized)
294+
295+
assert restored.start == 100
296+
assert restored.end == 200
297+
298+
def test_file_chunk_roundtrip(self) -> None:
299+
"""FileChunk should serialize and deserialize correctly."""
300+
original = FileChunk(path="/data/test.csv", offset=5000, length=1000)
301+
serialized = original.serialize()
302+
restored = FileChunk.deserialize(serialized)
303+
304+
assert restored.path == "/data/test.csv"
305+
assert restored.offset == 5000
306+
assert restored.length == 1000
307+
308+
def test_range_work_item_conforms_to_serializable(self) -> None:
309+
"""RangeWorkItem should satisfy the Serializable protocol."""
310+
item = RangeWorkItem(start=0, end=10)
311+
312+
# Check it has the required methods
313+
assert hasattr(item, "serialize")
314+
assert hasattr(RangeWorkItem, "deserialize")
315+
assert callable(item.serialize)
316+
assert callable(RangeWorkItem.deserialize)
317+
318+
# Protocol conformance (structural typing)
319+
def accepts_serializable(s: Serializable) -> bytes:
320+
return s.serialize()
321+
322+
result = accepts_serializable(item)
323+
assert isinstance(result, bytes)

0 commit comments

Comments
 (0)