Skip to content

Commit bf26357

Browse files
rustyconoverclaude
andcommitted
mypy + lint cleanup across buffered_table touched files
The recent buffered_table refactor touched files (worker.py, function_storage.py, function_storage_azure_sql.py, _test_fixtures/ table_in_out.py, table_in_out_function.py) had accumulated mypy and ruff debt — pre-existing in some places, newly introduced by the B.1 helper in others. This commit clears the slate: * table_in_out_function.py: declare ``state_class`` and ``combine`` on the ``TableInOutGenerator`` base class so subclasses on the buffered path don't need ``# type: ignore[attr-defined]`` on every callsite. state_class is constrained to ``type[ArrowSerializableDataclass] | None`` so callers can invoke ``serialize_to_bytes`` / ``deserialize_from_bytes`` without further narrowing. * worker.py: add a runtime ``issubclass`` narrowing in ``_load_buffered_table_params`` so mypy sees the resolver returning a ``type[TableInOutGenerator[Any, Any]]``. Annotate the hot ``state`` variable as ``Any`` (alternates between ArrowSerializableDataclass and whatever ``initial_state()`` returns). Fix unused-ignore comments. Document the two genuine type-ignores at the duck-typed buffered call sites (NoOpCollector → OutputCollector; widened finalize signature). * _test_fixtures/table_in_out.py: ``# type: ignore[override]`` on the buffered-shape ``finalize(finalize_state_id, params)`` overrides (deliberate signature widening from the streaming-shape ``finalize(params)`` base) — with comments explaining why the worker's ``Meta.buffered_table=True`` routing makes this safe at runtime. Remove now-unused ``# type: ignore[override]`` on ``combine`` / ``process`` (the base-class additions made them resolvable). Fix three ``zip()`` strict= warnings and a docstring summary line. * function_storage_azure_sql.py: cast pymssql cursor values through ``Any`` before ``bytes()`` / ``int()`` (cursor's typed-row shim returns a broad union; we know the column is binary / int from the schema). Test result: ``test_mypy_vgi_clean`` now passes (was the long-standing baseline failure). Full vgi-python suite: 30 failed / 1652 passed (one fewer baseline failure than before). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent 19b3b5c commit bf26357

4 files changed

Lines changed: 134 additions & 43 deletions

File tree

‎vgi/_test_fixtures/table_in_out.py‎

Lines changed: 53 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -214,10 +214,19 @@ def combine(
214214
return state_ids
215215

216216
@classmethod
217-
def finalize(
217+
def finalize( # type: ignore[override]
218218
cls, finalize_state_id: int, params: ProcessParams[SingleTableArguments]
219219
) -> Iterator[pa.RecordBatch]:
220-
"""Yield the buffered batches for one finalize_state_id, one per RPC."""
220+
"""Yield the buffered batches for one finalize_state_id, one per RPC.
221+
222+
Buffered-table finalize signature is ``(finalize_state_id, params)``,
223+
which is wider than the streaming-shape ``(params)`` declared on
224+
the TableInOutGenerator base. The ``# type: ignore[override]``
225+
documents that this is a deliberate signature widening — the
226+
worker-side dispatcher (vgi/worker.py:buffered_table_finalize)
227+
only routes Meta.buffered_table=True subclasses through this
228+
path, so the duck-typed call lands correctly at runtime.
229+
"""
221230
for batch_bytes in params.storage.state_log_scan(
222231
b"buf", BoundStorage.pack_int_key(finalize_state_id)
223232
):
@@ -552,7 +561,8 @@ def combine(
552561
stored = params.storage.state_get_many(b"buf", keys)
553562
merged: dict[str, pa.Scalar[Any]] = {name: pa.scalar(0, type=field.type)
554563
for name, field in zip(params.output_schema.names,
555-
params.output_schema)}
564+
params.output_schema,
565+
strict=True)}
556566
for entry in stored:
557567
if entry is None:
558568
continue
@@ -564,17 +574,22 @@ def combine(
564574
return [0]
565575

566576
@classmethod
567-
def finalize(
577+
def finalize( # type: ignore[override]
568578
cls, finalize_state_id: int, params: ProcessParams[SumAllColumnsFunctionArguments]
569579
) -> Iterator[pa.RecordBatch]:
570-
"""Yield one row carrying the merged column sums."""
580+
"""Yield one row carrying the merged column sums.
581+
582+
Buffered-table finalize signature widening — see the
583+
``# type: ignore[override]`` comment on
584+
``BufferInputFunction.finalize`` for rationale.
585+
"""
571586
stored = params.storage.state_get(b"buf", BoundStorage.pack_int_key(finalize_state_id))
572587
if stored is None:
573588
# No data at all — emit zeros so SQL like
574589
# `SELECT * FROM sum_all_columns((SELECT 1 WHERE 1=0))` still
575590
# produces a row with the expected shape.
576591
sums = {name: pa.scalar(0, type=field.type)
577-
for name, field in zip(params.output_schema.names, params.output_schema)}
592+
for name, field in zip(params.output_schema.names, params.output_schema, strict=True)}
578593
yield pa.RecordBatch.from_pydict({name: [val] for name, val in sums.items()},
579594
schema=params.output_schema)
580595
return
@@ -596,8 +611,11 @@ class ExceptionProcessFunction(
596611
):
597612
"""Buffered table function that raises an exception on the second batch."""
598613

599-
# Use our own state class, overriding SumAllColumnsFunction.state_class.
600-
state_class = ExceptionProcessState
614+
# Narrowing state_class from SumAllColumnsState to ExceptionProcessState
615+
# is intentional; both are ArrowSerializableDataclass subclasses, but
616+
# the base class declares state_class with the concrete type for
617+
# type-narrowing in generic contexts.
618+
state_class = ExceptionProcessState # type: ignore[assignment]
601619

602620
class Meta(SumAllColumnsFunction.Meta):
603621
"""Metadata for ExceptionProcessFunction."""
@@ -620,14 +638,19 @@ def process( # type: ignore[override]
620638
batch: pa.RecordBatch,
621639
out: OutputCollector,
622640
) -> None:
623-
"""Raise an exception on the second batch."""
641+
"""Raise an exception on the second batch.
642+
643+
``# type: ignore[override]`` — narrows ``state`` from the parent's
644+
``SumAllColumnsState`` to ``ExceptionProcessState`` (the override
645+
on ``state_class`` above pairs with this type).
646+
"""
624647
state.batch_count += 1
625648
if state.batch_count % 2 == 0:
626649
raise ValueError(f"Intentional exception on batch {state.batch_count}")
627650
# Sink-only — no emit needed.
628651

629652
@classmethod
630-
def combine( # type: ignore[override]
653+
def combine(
631654
cls, state_ids: list[int], params: ProcessParams[SumAllColumnsFunctionArguments]
632655
) -> list[int]:
633656
# Pass-through partitioning: no aggregation across states needed.
@@ -640,7 +663,7 @@ def finalize( # type: ignore[override]
640663
# If we ever reach finalize, emit a zero-sum row (the only behavior
641664
# the existing test asserts is the *exception* path from process).
642665
sums = {name: pa.scalar(0, type=field.type)
643-
for name, field in zip(params.output_schema.names, params.output_schema)}
666+
for name, field in zip(params.output_schema.names, params.output_schema, strict=True)}
644667
yield pa.RecordBatch.from_pydict({name: [val] for name, val in sums.items()},
645668
schema=params.output_schema)
646669

@@ -662,7 +685,7 @@ def finalize( # type: ignore[override]
662685
) -> Iterator[pa.RecordBatch]:
663686
"""Raise an intentional exception when the C++ side pulls a batch."""
664687
raise ValueError("Intentional exception during finalize()")
665-
yield # type: ignore[unreachable] # make this a generator function
688+
yield # make this a generator function
666689

667690

668691
@dataclass(slots=True, kw_only=True)
@@ -812,7 +835,7 @@ class Meta(BufferInputFunction.Meta):
812835
categories = ["test", "crash"]
813836

814837
@classmethod
815-
def process( # type: ignore[override]
838+
def process(
816839
cls,
817840
params: ProcessParams[SingleTableArguments],
818841
state: None,
@@ -838,7 +861,7 @@ class Meta(BufferInputFunction.Meta):
838861
categories = ["test", "crash"]
839862

840863
@classmethod
841-
def combine( # type: ignore[override]
864+
def combine(
842865
cls, state_ids: list[int], params: ProcessParams[SingleTableArguments]
843866
) -> list[int]:
844867
raise RuntimeError("Intentional exception during combine()")
@@ -862,7 +885,7 @@ def finalize( # type: ignore[override]
862885
cls, finalize_state_id: int, params: ProcessParams[SingleTableArguments]
863886
) -> Iterator[pa.RecordBatch]:
864887
raise RuntimeError("Intentional exception during finalize()")
865-
yield # type: ignore[unreachable] # make this a generator function
888+
yield # make this a generator function
866889

867890

868891
class HangOnProcessFunction(BufferInputFunction):
@@ -879,7 +902,7 @@ class Meta(BufferInputFunction.Meta):
879902
categories = ["test", "hang"]
880903

881904
@classmethod
882-
def process( # type: ignore[override]
905+
def process(
883906
cls,
884907
params: ProcessParams[SingleTableArguments],
885908
state: None,
@@ -891,9 +914,10 @@ def process( # type: ignore[override]
891914

892915
@dataclass(kw_only=True)
893916
class LargeStateState(ArrowSerializableDataclass):
894-
"""Holds a single large bytes buffer; the C++ side ships this through
895-
combine/finalize via the RPC's outer envelope, exercising IPC chunking
896-
on the response path.
917+
"""Holds a single large bytes buffer.
918+
919+
The C++ side ships this through combine/finalize via the RPC's outer
920+
envelope, exercising IPC chunking on the response path.
897921
"""
898922

899923
payload: bytes = b""
@@ -942,10 +966,10 @@ def combine(
942966
return state_ids
943967

944968
@classmethod
945-
def finalize(
969+
def finalize( # type: ignore[override]
946970
cls, finalize_state_id: int, params: ProcessParams[SingleTableArguments]
947971
) -> Iterator[pa.RecordBatch]:
948-
972+
"""Buffered-table finalize signature widening — see BufferInputFunction.finalize."""
949973
stored = params.storage.state_get(b"buf", BoundStorage.pack_int_key(finalize_state_id))
950974
if stored is None:
951975
return
@@ -1068,15 +1092,17 @@ def combine(
10681092
return state_ids
10691093

10701094
@classmethod
1071-
def finalize(
1095+
def finalize( # type: ignore[override]
10721096
cls, finalize_state_id: int, params: ProcessParams[SingleTableArguments]
10731097
) -> Iterator[pa.RecordBatch]:
1098+
"""Buffered-table finalize signature widening — see BufferInputFunction.finalize.
10741099
1075-
# NB. There is exactly one finalize() per state_id (combine returned
1076-
# state_ids unchanged), so we only see this thread's log here. To get
1077-
# a globally ordered output the caller should choose Meta.sink_order_dependent
1078-
# OR use a single Sink thread; otherwise per-thread output order is
1079-
# batch_index-ascending only within this slice.
1100+
NB. There is exactly one finalize() per state_id (combine returned
1101+
state_ids unchanged), so we only see this thread's log here. To get
1102+
a globally ordered output the caller should choose Meta.sink_order_dependent
1103+
OR use a single Sink thread; otherwise per-thread output order is
1104+
batch_index-ascending only within this slice.
1105+
"""
10801106
log_bytes = params.storage.state_log_scan(
10811107
b"buf", BoundStorage.pack_int_key(finalize_state_id)
10821108
)

‎vgi/function_storage_azure_sql.py‎

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import struct
2222
import time
2323
from collections.abc import Callable
24+
from typing import Any, cast
2425

2526
import pymssql
2627

@@ -431,7 +432,12 @@ def _do(conn: pymssql.Connection) -> list[bytes | None]:
431432
""", # noqa: S608
432433
(scope_id, ns, *keys),
433434
)
434-
found: dict[bytes, bytes] = {bytes(k): bytes(v) for k, v in cursor.fetchall()}
435+
# pymssql cursor values are typed as a broad Any-equivalent
436+
# union; the columns we SELECT are VARBINARY (function_state.key,
437+
# function_state.value) so the runtime value is always bytes.
438+
found: dict[bytes, bytes] = {
439+
bytes(cast(Any, k)): bytes(cast(Any, v)) for k, v in cursor.fetchall()
440+
}
435441
return [found.get(bytes(k)) for k in keys]
436442

437443
return self._execute_with_retry(_do)
@@ -514,7 +520,7 @@ def _do(conn: pymssql.Connection) -> list[tuple[bytes, bytes]]:
514520
""",
515521
(scope_id, ns),
516522
)
517-
return [(bytes(k), bytes(v)) for k, v in cursor.fetchall()]
523+
return [(bytes(cast(Any, k)), bytes(cast(Any, v))) for k, v in cursor.fetchall()]
518524

519525
return self._execute_with_retry(_do)
520526

@@ -545,7 +551,7 @@ def _do(conn: pymssql.Connection) -> list[tuple[bytes, bytes]]:
545551
)
546552
replay = cursor.fetchall()
547553
if replay:
548-
return [(bytes(k), bytes(v)) for k, v in replay]
554+
return [(bytes(cast(Any, k)), bytes(cast(Any, v))) for k, v in replay]
549555
# Fresh drain: tombstone live rows for this attempt_id, then
550556
# read them back. T-SQL doesn't support UPDATE..RETURNING the
551557
# same way SQLite does; use OUTPUT clause.
@@ -561,7 +567,7 @@ def _do(conn: pymssql.Connection) -> list[tuple[bytes, bytes]]:
561567
)
562568
rows = cursor.fetchall()
563569
conn.commit()
564-
return [(bytes(k), bytes(v)) for k, v in rows]
570+
return [(bytes(cast(Any, k)), bytes(cast(Any, v))) for k, v in rows]
565571

566572
return self._execute_with_retry(_do)
567573

@@ -648,8 +654,10 @@ def _do(conn: pymssql.Connection) -> int:
648654
(scope_id, ns, key, attempt_id),
649655
)
650656
row = cursor.fetchone()
657+
# function_state_log.id is BIGINT IDENTITY → int at runtime;
658+
# pymssql's typed-row narrowing can't see that.
651659
if row is not None:
652-
return int(row[0])
660+
return int(cast(Any, row[0]))
653661
cursor.execute(
654662
"""
655663
INSERT INTO function_state_log
@@ -659,7 +667,9 @@ def _do(conn: pymssql.Connection) -> int:
659667
""",
660668
(scope_id, ns, key, item, attempt_id),
661669
)
662-
new_id = int(cursor.fetchone()[0])
670+
inserted_row = cursor.fetchone()
671+
assert inserted_row is not None, "INSERT ... OUTPUT inserted.id returned no row"
672+
new_id = int(cast(Any, inserted_row[0]))
663673
conn.commit()
664674
return new_id
665675

@@ -686,7 +696,7 @@ def _do(conn: pymssql.Connection) -> list[bytes]:
686696
""",
687697
(scope_id, ns, key),
688698
)
689-
return [bytes(v) for (v,) in cursor.fetchall()]
699+
return [bytes(cast(Any, v)) for (v,) in cursor.fetchall()]
690700

691701
return self._execute_with_retry(_do)
692702

‎vgi/table_in_out_function.py‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,31 @@ class TableInOutGenerator[TArgs, TState = None](TableFunctionBase[TArgs]):
5757
5858
"""
5959

60+
# Subclasses opt into framework-managed state by setting this to a
61+
# concrete ArrowSerializableDataclass type. Default None means
62+
# process()/finalize() get state=None and the framework skips its
63+
# round-trip on the buffered_table path. TableInOutFunction's
64+
# __init_subclass__ infers this from the TState type parameter when a
65+
# subclass declares one. Constrained to ArrowSerializableDataclass so
66+
# the framework can call serialize_to_bytes / deserialize_from_bytes
67+
# on instances without further type narrowing at the call site.
68+
state_class: type[ArrowSerializableDataclass] | None = None
69+
70+
@classmethod
71+
def combine(cls, state_ids: list[int], params: ProcessParams[TArgs]) -> list[int]:
72+
"""Buffered-table only: collapse Sink-thread state_ids into finalize keys.
73+
74+
Default returns state_ids unchanged (pass-through partitioning —
75+
each Sink thread's slice becomes one finalize partition). Override
76+
to merge state across threads (e.g. global sort under
77+
``sink_order_dependent``) and return the keys the source phase
78+
will iterate.
79+
80+
Not invoked on the streaming exchange path; only by
81+
``buffered_table_combine`` when ``Meta.buffered_table = True``.
82+
"""
83+
return state_ids
84+
6085
@classmethod
6186
def has_finalize_override(cls) -> bool:
6287
"""Whether this class's ``finalize``/``finish`` represents real work.

0 commit comments

Comments
 (0)