Skip to content

Commit d55e8ff

Browse files
rustyconoverclaude
andcommitted
table_buffering: S5 — robust _finalize_state_class resolution
Walk cls.__mro__ instead of only cls.__dict__["__orig_bases__"] so generic- through inheritance chains correctly resolve TFinalizeState: class Mid[X](TableBufferingFunction[Args, X]): ... class Concrete(Mid[State]): ... # was: _finalize_state_class = None The old code only inspected the leaf class's directly-declared bases. When the leaf parameterized an intermediate generic instead of TableBufferingFunction itself, ``origin`` was a TBF subclass (not TBF), ``len(type_args)`` was 1 (only the intermediate's TypeVar binding), the loop bailed, and the state class was silently lost. The new walk builds a TypeVar→concrete substitution map level by level and resolves when it reaches a base whose origin is TableBufferingFunction directly. Sentinel _UNCHANGED distinguishes "no parameterization found in chain" (leave inherited class attribute alone) from "explicitly None" (no per-tick state). Test suite test_table_buffering_function.py covers: - direct parameterization (regression baseline) - non-reparameterized subclass (attribute inheritance) - single-level generic-through (the bug) - two-level generic-through chain (substitution propagation) - explicit None state Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent 65654a2 commit d55e8ff

3 files changed

Lines changed: 302 additions & 28 deletions

File tree

‎.gitattributes‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,5 @@
11

22
# Use bd merge for beads JSONL files
3+
4+
# Use bd merge for beads JSONL files
5+
.beads/issues.jsonl merge=beads
Lines changed: 201 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
1+
"""Unit tests for ``vgi.table_buffering_function``.
2+
3+
Currently focused on the ``__init_subclass__`` machinery — specifically
4+
TFinalizeState resolution under non-trivial generic inheritance chains.
5+
"""
6+
7+
from __future__ import annotations
8+
9+
from dataclasses import dataclass
10+
11+
import pyarrow as pa
12+
from vgi_rpc import ArrowSerializableDataclass
13+
14+
from vgi._test_fixtures.table_in_out import SingleTableArguments
15+
from vgi.table_buffering_function import (
16+
TableBufferingFunction,
17+
)
18+
19+
20+
@dataclass(frozen=True, slots=True, kw_only=True)
21+
class _StateA(ArrowSerializableDataclass):
22+
"""A concrete finalize-state dataclass."""
23+
24+
log_id: int = 0
25+
26+
@classmethod
27+
def arrow_schema(cls) -> pa.Schema:
28+
"""Wire layout for _StateA."""
29+
return pa.schema([pa.field("log_id", pa.int64())])
30+
31+
32+
@dataclass(frozen=True, slots=True, kw_only=True)
33+
class _StateB(ArrowSerializableDataclass):
34+
"""A different concrete finalize-state dataclass."""
35+
36+
cursor: bytes = b""
37+
38+
@classmethod
39+
def arrow_schema(cls) -> pa.Schema:
40+
"""Wire layout for _StateB."""
41+
return pa.schema([pa.field("cursor", pa.binary())])
42+
43+
44+
# Stub implementations that satisfy the abstractmethod requirements without
45+
# doing real work — these tests are purely about class-time resolution.
46+
47+
def _stub_process(cls, batch, params): # noqa: ARG001 - test stub
48+
return b""
49+
50+
51+
def _stub_combine(cls, state_ids, params): # noqa: ARG001 - test stub
52+
return state_ids
53+
54+
55+
def _stub_finalize(cls, params, finalize_state_id, state, out): # noqa: ARG001 - test stub
56+
out.finish()
57+
58+
59+
def _attach_stub_methods(cls: type) -> type:
60+
cls.process = classmethod(_stub_process)
61+
cls.combine = classmethod(_stub_combine)
62+
cls.finalize = classmethod(_stub_finalize)
63+
return cls
64+
65+
66+
# ---------------------------------------------------------------------------
67+
# Case 1: direct parameterization at the leaf — baseline that the old code
68+
# already handled correctly. Kept as a regression net.
69+
# ---------------------------------------------------------------------------
70+
71+
@_attach_stub_methods
72+
class DirectChild(TableBufferingFunction[SingleTableArguments, _StateA]):
73+
"""Baseline: direct generic parameterization at the leaf class."""
74+
75+
class Meta:
76+
"""Test fixture metadata."""
77+
78+
name = "direct_child"
79+
80+
81+
def test_direct_parameterization_resolves() -> None:
82+
"""``Foo(TableBufferingFunction[Args, State])`` resolves State directly."""
83+
assert DirectChild._finalize_state_class is _StateA
84+
85+
86+
# ---------------------------------------------------------------------------
87+
# Case 2: subclass without re-parameterization — should inherit via the
88+
# normal class-attribute lookup (we don't overwrite cls._finalize_state_class
89+
# when no __orig_bases__ binding is found, returning the _UNCHANGED sentinel).
90+
# ---------------------------------------------------------------------------
91+
92+
@_attach_stub_methods
93+
class NonParameterizedGrandchild(DirectChild):
94+
"""Subclass that doesn't re-parameterize — must inherit DirectChild's state."""
95+
96+
class Meta:
97+
"""Test fixture metadata."""
98+
99+
name = "non_parameterized_grandchild"
100+
101+
102+
def test_subclass_without_reparameterization_inherits() -> None:
103+
"""``class Foo(DirectChild): ...`` inherits DirectChild._finalize_state_class."""
104+
assert NonParameterizedGrandchild._finalize_state_class is _StateA
105+
106+
107+
# ---------------------------------------------------------------------------
108+
# Case 3: generic-through intermediate — the bug the new MRO walk fixes.
109+
#
110+
# class Mid[X](TableBufferingFunction[Args, X]): ...
111+
# class Concrete(Mid[State]): ← state must resolve through Mid's binding
112+
#
113+
# The OLD resolution walked only Concrete.__orig_bases__ = (Mid[State],),
114+
# saw origin=Mid (a TBF subclass, not TBF itself), tried type_args[1] (out
115+
# of range, only one arg), bailed, and left _finalize_state_class as None.
116+
# ---------------------------------------------------------------------------
117+
118+
@_attach_stub_methods
119+
class GenericMid[X: ArrowSerializableDataclass](TableBufferingFunction[SingleTableArguments, X]):
120+
"""Intermediate generic that passes State through unbound."""
121+
122+
class Meta:
123+
"""Test fixture metadata."""
124+
125+
name = "generic_mid"
126+
127+
128+
@_attach_stub_methods
129+
class ConcreteFromGenericMid(GenericMid[_StateB]):
130+
"""Leaf that binds the intermediate's TypeVar to a concrete dataclass."""
131+
132+
class Meta:
133+
"""Test fixture metadata."""
134+
135+
name = "concrete_from_generic_mid"
136+
137+
138+
def test_generic_through_intermediate_resolves() -> None:
139+
"""``class Concrete(Mid[State])`` resolves State even when Mid is a TBF subclass.
140+
141+
This is the S5 fix. With the old code, ``_finalize_state_class`` would
142+
have been ``None`` on ``ConcreteFromGenericMid``; with the MRO walk it
143+
correctly resolves to ``_StateB``.
144+
"""
145+
assert ConcreteFromGenericMid._finalize_state_class is _StateB
146+
# The intermediate generic itself stays unresolved (its TypeVar is still
147+
# unbound from its own POV; only its leaf children bind it).
148+
assert GenericMid._finalize_state_class is None
149+
150+
151+
# ---------------------------------------------------------------------------
152+
# Case 4: two-level generic-through chain — substitutions propagate.
153+
#
154+
# class Mid[X](TableBufferingFunction[Args, X]): ...
155+
# class Outer[Y](Mid[Y]): ...
156+
# class Leaf(Outer[State]): ← Y → State, then X → Y → State.
157+
# ---------------------------------------------------------------------------
158+
159+
@_attach_stub_methods
160+
class GenericOuter[Y: ArrowSerializableDataclass](GenericMid[Y]):
161+
"""Two-level generic-through; rebinds the intermediate's TypeVar to its own."""
162+
163+
class Meta:
164+
"""Test fixture metadata."""
165+
166+
name = "generic_outer"
167+
168+
169+
@_attach_stub_methods
170+
class TwoLevelLeaf(GenericOuter[_StateA]):
171+
"""Leaf binding the outer-level TypeVar; must resolve transitively."""
172+
173+
class Meta:
174+
"""Test fixture metadata."""
175+
176+
name = "two_level_leaf"
177+
178+
179+
def test_two_level_generic_through_chain_resolves() -> None:
180+
"""Substitutions propagate across multi-level generic-through chains."""
181+
assert TwoLevelLeaf._finalize_state_class is _StateA
182+
assert GenericOuter._finalize_state_class is None
183+
184+
185+
# ---------------------------------------------------------------------------
186+
# Case 5: explicit ``None`` finalize state — preserved through the chain.
187+
# ---------------------------------------------------------------------------
188+
189+
@_attach_stub_methods
190+
class NoStateFunc(TableBufferingFunction[SingleTableArguments, None]):
191+
"""Function that opts out of per-tick finalize state."""
192+
193+
class Meta:
194+
"""Test fixture metadata."""
195+
196+
name = "no_state_func"
197+
198+
199+
def test_explicit_none_state_resolves_to_none() -> None:
200+
"""``TableBufferingFunction[Args, None]`` resolves to None (no per-tick state)."""
201+
assert NoStateFunc._finalize_state_class is None

‎vgi/table_buffering_function.py‎

Lines changed: 98 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131

3232
from abc import abstractmethod
3333
from dataclasses import dataclass
34-
from typing import TYPE_CHECKING, ClassVar, TypeVar, get_args, get_origin
34+
from typing import TYPE_CHECKING, Any, ClassVar, TypeVar, get_args, get_origin
3535

3636
import pyarrow as pa
3737
from vgi_rpc import ArrowSerializableDataclass
@@ -56,6 +56,77 @@
5656
]
5757

5858

59+
# Sentinel meaning "no parameterization of TableBufferingFunction was found
60+
# in the MRO walk; leave the existing class attribute alone (inherits via
61+
# normal MRO lookup from a base that did resolve)". Distinguished from None
62+
# (a valid resolved value meaning "no per-tick state").
63+
_UNCHANGED: Any = object()
64+
65+
66+
def _resolve_finalize_state_class(
67+
cls: type,
68+
) -> type[ArrowSerializableDataclass] | None | Any:
69+
"""Walk ``cls.__mro__`` to resolve ``TFinalizeState`` to a concrete type.
70+
71+
Returns the resolved class, ``None`` (state explicitly disabled), or
72+
the ``_UNCHANGED`` sentinel when no TBF parameterization is found.
73+
74+
Handles generic-through chains by maintaining a TypeVar→concrete
75+
substitution map as we walk from most-derived to base. When an
76+
intermediate class binds a TypeVar to a concrete type, later levels
77+
that reference that TypeVar in their own bases get substituted.
78+
"""
79+
# Walk lazy-imported to avoid the forward-reference dance.
80+
substitutions: dict[TypeVar, Any] = {}
81+
saw_parameterization = False
82+
83+
for klass in cls.__mro__:
84+
# __orig_bases__ is per-class (not inherited); look it up directly
85+
# on klass without falling back to attribute resolution.
86+
orig_bases = klass.__dict__.get("__orig_bases__", ())
87+
for base in orig_bases:
88+
origin = get_origin(base)
89+
if origin is None or not isinstance(origin, type):
90+
continue
91+
if not issubclass(origin, TableBufferingFunction):
92+
continue
93+
saw_parameterization = True
94+
type_args = get_args(base)
95+
96+
if origin is TableBufferingFunction:
97+
# Direct parameterization: TableBufferingFunction[TArgs, TState].
98+
if len(type_args) < 2:
99+
continue
100+
state = type_args[1]
101+
# Resolve transitively through prior substitutions.
102+
while isinstance(state, TypeVar) and state in substitutions:
103+
state = substitutions[state]
104+
if state is None or state is type(None):
105+
return None
106+
if isinstance(state, TypeVar):
107+
# Still unresolved — generic-through to a leaf class
108+
# that we either haven't seen yet (impossible: we walk
109+
# most-derived first) or that didn't bind. Leave None.
110+
return None
111+
return state
112+
113+
# Intermediate parameterized base — record TypeVar substitutions
114+
# so the next iteration up the MRO can use them.
115+
type_params: tuple[TypeVar, ...] = getattr(origin, "__parameters__", ())
116+
# strict=False on purpose: an intermediate generic may declare
117+
# more TypeVars than the parameterization binds (callers can
118+
# leave trailing positions unbound by intent), in which case
119+
# ``zip`` should silently truncate.
120+
for tv, ta in zip(type_params, type_args, strict=False):
121+
# If ta itself is a TypeVar resolved earlier (deeper-nested
122+
# generic), chase the chain to its concrete binding.
123+
while isinstance(ta, TypeVar) and ta in substitutions:
124+
ta = substitutions[ta]
125+
substitutions[tv] = ta
126+
127+
return _UNCHANGED if not saw_parameterization else None
128+
129+
59130
@dataclass(slots=True, frozen=True, kw_only=True)
60131
class TableBufferingParams[TArgs](ProcessParams[TArgs]):
61132
"""Params for ``TableBufferingFunction`` callbacks.
@@ -141,33 +212,32 @@ class Meta:
141212
def __init_subclass__(cls) -> None: # noqa: D105 — internal hook
142213
super().__init_subclass__()
143214

144-
# Resolve ``TFinalizeState`` from this class's directly-declared
145-
# ``__orig_bases__`` (i.e. the ``TableBufferingFunction[Args, State]``
146-
# specialization). When the subclass doesn't re-parameterize the base
147-
# (e.g. ``class Foo(BufferInputFunction): ...``) we leave the parent's
148-
# resolution alone via normal class-attribute inheritance.
149-
# ``TableFunctionBase.__init_subclass__`` (called via super() above)
150-
# has already validated that ``state_type`` is None or an
151-
# ``ArrowSerializableDataclass`` subclass; we just record it.
152-
for base in cls.__dict__.get("__orig_bases__", ()):
153-
origin = get_origin(base)
154-
if origin is None or not (
155-
isinstance(origin, type) and issubclass(origin, TableBufferingFunction)
156-
):
157-
continue
158-
type_args = get_args(base)
159-
if len(type_args) < 2:
160-
continue
161-
state_type = type_args[1]
162-
if state_type is None or state_type is type(None):
163-
cls._finalize_state_class = None
164-
elif isinstance(state_type, TypeVar):
165-
# Generic-through (e.g. ``class Foo[X](TableBufferingFunction[Args, X]): ...``).
166-
# Concrete subclasses below this one will resolve it.
167-
pass
168-
else:
169-
cls._finalize_state_class = state_type
170-
break
215+
# Resolve ``TFinalizeState`` by walking the MRO chain of
216+
# generic-parameterizations. The naive "look at cls.__orig_bases__"
217+
# approach handles ``class Foo(TableBufferingFunction[Args, State])``
218+
# but silently loses the state type on intermediate generics:
219+
#
220+
# class Mid[X](TableBufferingFunction[Args, X]): ...
221+
# class Concrete(Mid[MyState]): # bug: TFinalizeState = None
222+
#
223+
# ``Concrete.__orig_bases__`` is ``(Mid[MyState],)``; the old loop
224+
# saw origin=Mid (a TBF subclass), tried ``type_args[1]`` (out of
225+
# range, only one arg), and bailed, leaving _finalize_state_class
226+
# unset → MyState lost. We instead walk ``cls.__mro__``, build a
227+
# TypeVar→concrete substitution map level by level, and resolve
228+
# when we reach a base whose origin is TableBufferingFunction
229+
# itself. ``TableFunctionBase.__init_subclass__`` (via super())
230+
# has already validated state_type when it was first introduced.
231+
resolved = _resolve_finalize_state_class(cls)
232+
if resolved is _UNCHANGED:
233+
# No parameterization found in the MRO walk — leave the
234+
# inherited class-attribute value alone (covers
235+
# ``class Foo(BufferInputFunction): ...`` where Foo doesn't
236+
# re-parameterize and just inherits BufferInputFunction's
237+
# resolved class).
238+
pass
239+
else:
240+
cls._finalize_state_class = resolved
171241

172242
meta = getattr(cls, "Meta", None)
173243
if meta is None:

0 commit comments

Comments
 (0)