Skip to content

Commit 309ef14

Browse files
rustyconoverclaude
andcommitted
fix: codebase improvements
- Fix flaky test by replacing sleep with polling loop - Consolidate duplicated test client logic into base class - Add automatic SQLite storage cleanup (1% probabilistic) - Unify abstract method pattern (Function.output_schema) - Add InitIdentifierError for consistent error handling 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
1 parent 306449d commit 309ef14

3 files changed

Lines changed: 304 additions & 267 deletions

File tree

‎tests/table_in_out/test_client.py‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -168,10 +168,21 @@ def test_stderr_available_on_error(self) -> None:
168168
client = Client(worker_script)
169169
client.start()
170170

171-
# Give the process a moment to write stderr and exit
172-
time.sleep(0.1)
171+
# Poll for stderr content with timeout instead of fixed sleep
172+
# The worker exits quickly, but the stderr drain thread needs time
173+
timeout = 2.0
174+
poll_interval = 0.05
175+
elapsed = 0.0
176+
stderr_output = ""
177+
178+
while elapsed < timeout:
179+
stderr_output = client.get_worker_stderr()
180+
# Check if we have the expected content
181+
if "Debug: worker starting" in stderr_output:
182+
break
183+
time.sleep(poll_interval)
184+
elapsed += poll_interval
173185

174-
stderr_output = client.get_worker_stderr()
175186
assert "Debug: worker starting" in stderr_output
176187
assert "Error: something went wrong" in stderr_output
177188

‎vgi/function.py‎

Lines changed: 79 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,10 @@
2424
"""
2525

2626
import os
27+
import random
2728
import sqlite3
2829
import uuid
30+
from abc import ABC, abstractmethod
2931
from dataclasses import dataclass, replace
3032
from enum import Enum
3133
from functools import cached_property
@@ -51,6 +53,7 @@
5153
"ArgumentValidationError",
5254
"Arguments",
5355
"Function",
56+
"InitIdentifierError",
5457
"InvocationType",
5558
"InitResult",
5659
"Level",
@@ -64,6 +67,25 @@
6467
]
6568

6669

70+
class InitIdentifierError(ValueError):
71+
"""Raised when an operation requires an init_identifier that hasn't been set.
72+
73+
This typically occurs when:
74+
- store_state() is called before perform_init() or retrieve_init()
75+
- collect_states() is called before perform_init() or retrieve_init()
76+
- Work queue operations are attempted before initialization
77+
78+
The init_identifier is automatically set during:
79+
- perform_init() for the primary worker
80+
- retrieve_init() for secondary workers
81+
82+
Resolution:
83+
- Ensure your function calls super().perform_init() in perform_init()
84+
- Ensure the worker correctly calls retrieve_init() for secondary workers
85+
86+
"""
87+
88+
6789
class SchemaValidationError(Exception):
6890
"""Raised when a batch schema doesn't match the expected schema.
6991
@@ -673,6 +695,10 @@ def create(self, value: bytes) -> bytes:
673695
Unique key for retrieving the value.
674696
675697
"""
698+
# Opportunistically clean old entries (1% of calls)
699+
if random.random() < 0.01:
700+
self.cleanup_old_entries(max_age_days=1.0)
701+
676702
key = uuid.uuid4().bytes
677703

678704
conn = self._connect()
@@ -833,6 +859,10 @@ def store(self, invocation_id: bytes, process_id: int, state_data: bytes) -> Non
833859
state_data: Serialized state bytes.
834860
835861
"""
862+
# Opportunistically clean old entries (1% of calls)
863+
if random.random() < 0.01:
864+
self.cleanup_old_entries(max_age_days=1.0)
865+
836866
conn = self._connect()
837867
try:
838868
conn.execute(
@@ -956,6 +986,37 @@ def cleanup_queue(self, invocation_id: bytes) -> int:
956986
finally:
957987
conn.close()
958988

989+
def cleanup_old_entries(self, max_age_days: float = 1.0) -> int:
990+
"""Remove worker state and work queue entries older than the specified age.
991+
992+
Args:
993+
max_age_days: Maximum age in days for entries to keep.
994+
995+
Returns:
996+
Number of entries deleted (from both tables).
997+
998+
"""
999+
conn = self._connect()
1000+
try:
1001+
cursor1 = conn.execute(
1002+
"""
1003+
DELETE FROM worker_state
1004+
WHERE julianday('now') - created_at > ?
1005+
""",
1006+
(max_age_days,),
1007+
)
1008+
cursor2 = conn.execute(
1009+
"""
1010+
DELETE FROM work_queue
1011+
WHERE julianday('now') - created_at > ?
1012+
""",
1013+
(max_age_days,),
1014+
)
1015+
conn.commit()
1016+
return int(cursor1.rowcount) + int(cursor2.rowcount)
1017+
finally:
1018+
conn.close()
1019+
9591020

9601021
class FunctionInitInput:
9611022
"""Input sent to initialize global state for a Function.
@@ -1004,7 +1065,7 @@ def deserialize_bytes(cls, data: bytes) -> Self:
10041065
return cls.deserialize(batch)
10051066

10061067

1007-
class Function[T: FunctionInitInput](MetadataMixin):
1068+
class Function[T: FunctionInitInput](ABC, MetadataMixin):
10081069
"""Base class for all VGI functions.
10091070
10101071
Functions are instantiated with Invocation describing the invocation,
@@ -1109,9 +1170,10 @@ def create_invocation_id(self) -> bytes:
11091170
return uuid.uuid4().bytes
11101171

11111172
@property
1173+
@abstractmethod
11121174
def output_schema(self) -> pa.Schema:
11131175
"""Return the output schema (must be implemented by subclass)."""
1114-
raise NotImplementedError("Must be implemented by subclass.")
1176+
...
11151177

11161178
def store_state(self, state: Serializable) -> None:
11171179
"""Store this worker's state for later collection.
@@ -1144,12 +1206,9 @@ def process(self, batch: pa.RecordBatch) -> OutputGenerator:
11441206
11451207
"""
11461208
if self.init_identifier is None:
1147-
raise ValueError(
1148-
"init_identifier must be set before storing state. "
1149-
"This is typically set automatically during perform_init() or "
1150-
"retrieve_init(). Ensure your function calls super().perform_init() "
1151-
"in perform_init(), or that the worker correctly calls "
1152-
"retrieve_init() for secondary workers."
1209+
raise InitIdentifierError(
1210+
"Cannot store state: init_identifier is not set. "
1211+
"Call perform_init() or retrieve_init() before storing state."
11531212
)
11541213
self.state_storage.store(
11551214
self.init_identifier,
@@ -1183,12 +1242,9 @@ def finalize(self) -> OutputGenerator:
11831242
11841243
"""
11851244
if self.init_identifier is None:
1186-
raise ValueError(
1187-
"init_identifier must be set before collecting states. "
1188-
"This is typically set automatically during perform_init() or "
1189-
"retrieve_init(). Ensure your function calls super().perform_init() "
1190-
"in perform_init(), or that the worker correctly calls "
1191-
"retrieve_init() for secondary workers."
1245+
raise InitIdentifierError(
1246+
"Cannot collect states: init_identifier is not set. "
1247+
"Call perform_init() or retrieve_init() before collecting states."
11921248
)
11931249
state_bytes_list = self.state_storage.collect_and_delete(self.init_identifier)
11941250
return [state_class.deserialize(data) for data in state_bytes_list]
@@ -1220,10 +1276,9 @@ def perform_init(self, init_input: pa.RecordBatch) -> InitResult:
12201276
12211277
"""
12221278
if self.init_identifier is None:
1223-
raise ValueError(
1224-
"init_identifier must be set before enqueuing work. "
1225-
"Call enqueue_work() after perform_init() has completed, typically "
1226-
"at the end of your perform_init() override or in setup()."
1279+
raise InitIdentifierError(
1280+
"Cannot enqueue work: init_identifier is not set. "
1281+
"Call enqueue_work() after perform_init() has completed."
12271282
)
12281283
return self.state_storage.enqueue_work(self.init_identifier, work_items)
12291284

@@ -1254,12 +1309,9 @@ def process(self) -> OutputGenerator:
12541309
12551310
"""
12561311
if self.init_identifier is None:
1257-
raise ValueError(
1258-
"init_identifier must be set before dequeuing work. "
1259-
"This is typically set automatically during perform_init() or "
1260-
"retrieve_init(). Ensure your function calls super().perform_init() "
1261-
"in perform_init(), or that the worker correctly calls "
1262-
"retrieve_init() for secondary workers."
1312+
raise InitIdentifierError(
1313+
"Cannot dequeue work: init_identifier is not set. "
1314+
"Call perform_init() or retrieve_init() before dequeuing work."
12631315
)
12641316
return self.state_storage.dequeue_work(self.init_identifier)
12651317

@@ -1324,11 +1376,9 @@ def perform_init(self, init_input: pa.RecordBatch) -> InitResult:
13241376
def retrieve_init(self, init_input: InitResult) -> None:
13251377
"""Retrieve and store init data from the storage."""
13261378
if init_input.global_init_identifier is None:
1327-
raise ValueError(
1328-
"global_init_identifier is required but was None. "
1329-
"This indicates the InitResult was not properly initialized. "
1330-
"Ensure perform_init() returns a InitResult with a valid "
1331-
"identifier."
1379+
raise InitIdentifierError(
1380+
"Cannot retrieve init: global_init_identifier in InitResult is None. "
1381+
"Ensure perform_init() returns an InitResult with a valid identifier."
13321382
)
13331383
self.init_identifier = init_input.global_init_identifier
13341384
self.init_data = self.InitDataCls.deserialize_bytes(

0 commit comments

Comments
 (0)