Skip to content

Commit 7217341

Browse files
committed
Preserve lazy config validation and field-cache isolation
1 parent fe53ba6 commit 7217341

2 files changed

Lines changed: 133 additions & 47 deletions

File tree

‎src/objectstate/lazy_factory.py‎

Lines changed: 48 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -594,6 +594,31 @@ def _find_mro_concrete_value(base_class, name):
594594
return next((getattr(cls, name) for cls in base_class.__mro__
595595
if _has_concrete_field_override(cls, name)), None)
596596

597+
def _standalone_field_value(self, name):
598+
"""Resolve one inherited field without an active config context."""
599+
instance_type = object.__getattribute__(self, '__class__')
600+
base_type = get_base_type_for_lazy(instance_type) or instance_type
601+
mro_value = _find_mro_concrete_value(base_type, name)
602+
if mro_value is not None:
603+
return mro_value
604+
605+
fields_by_name = instance_type.__dict__.get('_fields_by_name')
606+
if fields_by_name is None:
607+
field_tuple = fields(instance_type)
608+
fields_by_name = {item.name: item for item in field_tuple}
609+
instance_type._fields_by_name = fields_by_name
610+
field_definition = fields_by_name.get(name)
611+
if field_definition and '_inherited_default' in field_definition.metadata:
612+
inherited = field_definition.metadata['_inherited_default']
613+
if inherited is not MISSING:
614+
return inherited
615+
factory = field_definition.metadata.get(
616+
'_inherited_default_factory', MISSING
617+
)
618+
if factory is not MISSING:
619+
return factory()
620+
return None
621+
597622
def __getattribute__(self: Any, name: str) -> Any:
598623
"""
599624
Three-stage resolution using new context system.
@@ -612,9 +637,8 @@ def __getattribute__(self: Any, name: str) -> Any:
612637
# Use object.__getattribute__ for __class__ to avoid recursion.
613638
# Lazily populate if not yet set (e.g. class created outside _create_lazy_dataclass_unified).
614639
_cls = object.__getattribute__(self, '__class__')
615-
try:
616-
_fns = _cls._field_names_set
617-
except AttributeError:
640+
_fns = _cls.__dict__.get('_field_names_set')
641+
if _fns is None:
618642
_ft = fields(_cls)
619643
_fns = frozenset(f.name for f in _ft)
620644
_cls._field_names_set = _fns
@@ -650,6 +674,8 @@ def __getattribute__(self: Any, name: str) -> Any:
650674
# Stage 3: Inheritance resolution using same merged context
651675
try:
652676
current_context = current_temp_global.get()
677+
if current_context is None:
678+
return _standalone_field_value(self, name)
653679
available_configs = extract_all_configs(current_context)
654680
resolved_value = resolve_field_inheritance(self, name, available_configs)
655681

@@ -658,7 +684,7 @@ def __getattribute__(self: Any, name: str) -> Any:
658684

659685
# For nested dataclass fields, return lazy instance
660686
# PERFORMANCE: O(1) dict lookup instead of O(n) linear scan
661-
_fbm = getattr(self.__class__, '_fields_by_name', None)
687+
_fbm = self.__class__.__dict__.get('_fields_by_name')
662688
if _fbm is None:
663689
_ft = fields(self.__class__)
664690
_fbm = {f.name: f for f in _ft}
@@ -667,43 +693,10 @@ def __getattribute__(self: Any, name: str) -> Any:
667693
if field_obj and is_dataclass(field_obj.type):
668694
return field_obj.type()
669695

670-
# Fallback to inherited default from parent class (for standalone usage)
671-
if field_obj and '_inherited_default' in field_obj.metadata:
672-
inherited = field_obj.metadata['_inherited_default']
673-
if inherited is not MISSING:
674-
return inherited
675-
# Check for default_factory
676-
factory = field_obj.metadata.get('_inherited_default_factory', MISSING)
677-
if factory is not MISSING:
678-
return factory()
679-
680-
return None
696+
return _standalone_field_value(self, name)
681697

682698
except LookupError:
683-
# No context available - fallback to MRO concrete values
684-
# For LazyDataclass types, get the base type; for concrete types, use self.__class__ directly
685-
base_type = get_base_type_for_lazy(self.__class__) or self.__class__
686-
mro_value = _find_mro_concrete_value(base_type, name)
687-
if mro_value is not None:
688-
return mro_value
689-
690-
# Also check inherited default metadata
691-
# PERFORMANCE: O(1) dict lookup instead of O(n) linear scan
692-
_fbm = getattr(self.__class__, '_fields_by_name', None)
693-
if _fbm is None:
694-
_ft = fields(self.__class__)
695-
_fbm = {f.name: f for f in _ft}
696-
self.__class__._fields_by_name = _fbm
697-
field_obj = _fbm.get(name)
698-
if field_obj and '_inherited_default' in field_obj.metadata:
699-
inherited = field_obj.metadata['_inherited_default']
700-
if inherited is not MISSING:
701-
return inherited
702-
factory = field_obj.metadata.get('_inherited_default_factory', MISSING)
703-
if factory is not MISSING:
704-
return factory()
705-
706-
return None
699+
return _standalone_field_value(self, name)
707700
return __getattribute__
708701

709702
@staticmethod
@@ -1097,12 +1090,13 @@ def patch_lazy_constructors(types: Optional[List[Type]] = None):
10971090
original_constructors[lazy_type] = lazy_type.__init__
10981091

10991092
# Create patched constructor that uses raw values
1100-
def create_patched_init(dataclass_type):
1093+
def create_patched_init(dataclass_type, original_init):
11011094
def patched_init(self, **kwargs):
1102-
# Use raw value approach instead of calling original constructor
1103-
# This prevents lazy resolution during code execution, while still
1104-
# honoring default_factory for nested lazy configs so attributes
1105-
# are not left as None (e.g., path_planning_config).
1095+
# Materialize the raw constructor payload without reading fields
1096+
# through lazy ``__getattribute__``. The nominal constructor must
1097+
# still run: it owns dataclass ``__post_init__`` validation and any
1098+
# other declaration-level invariants.
1099+
raw_values = {}
11061100
for field_definition in dataclasses.fields(dataclass_type):
11071101
if field_definition.name in kwargs:
11081102
value = kwargs[field_definition.name]
@@ -1113,15 +1107,22 @@ def patched_init(self, **kwargs):
11131107
else:
11141108
value = None
11151109

1116-
object.__setattr__(self, field_definition.name, value)
1110+
raw_values[field_definition.name] = value
1111+
1112+
original_init(self, **raw_values)
11171113

1118-
# Track explicit fields for downstream logic that inspects this flag
1114+
# The generated lazy constructor tracks every received keyword.
1115+
# Restore the authored subset because the remaining raw values were
1116+
# supplied only to preserve inheritance during reconstruction.
11191117
object.__setattr__(self, '_explicitly_set_fields', set(kwargs.keys()))
11201118

11211119
return patched_init
11221120

11231121
# Apply the patch
1124-
lazy_type.__init__ = create_patched_init(lazy_type)
1122+
lazy_type.__init__ = create_patched_init(
1123+
lazy_type,
1124+
original_constructors[lazy_type],
1125+
)
11251126

11261127
try:
11271128
yield

‎tests/test_lazy_factory.py‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,73 @@ class StreamingConfig(BaseConfig):
7878
assert StreamingConfig().inherited is None
7979

8080

81+
def test_cleared_context_resolves_inherited_standalone_default() -> None:
82+
from objectstate.context_manager import current_temp_global
83+
from objectstate.lazy_factory import (
84+
bind_lazy_resolution_to_class,
85+
get_inherited_field_names,
86+
rebuild_with_none_defaults,
87+
)
88+
89+
@dataclass
90+
class DisplayConfig:
91+
dimension_mode: str = "stack"
92+
93+
@dataclass
94+
class StreamingConfig(DisplayConfig):
95+
enabled: bool = False
96+
97+
StreamingConfig = rebuild_with_none_defaults(
98+
StreamingConfig,
99+
get_inherited_field_names(StreamingConfig),
100+
)
101+
bind_lazy_resolution_to_class(StreamingConfig)
102+
context_token = current_temp_global.set(None)
103+
try:
104+
assert object.__getattribute__(StreamingConfig(), "dimension_mode") is None
105+
assert StreamingConfig().dimension_mode == "stack"
106+
finally:
107+
current_temp_global.reset(context_token)
108+
109+
110+
def test_lazy_field_cache_is_owned_by_exact_runtime_class() -> None:
111+
from objectstate.context_manager import current_temp_global
112+
from objectstate.lazy_factory import (
113+
bind_lazy_resolution_to_class,
114+
get_inherited_field_names,
115+
rebuild_with_none_defaults,
116+
)
117+
118+
@dataclass
119+
class StreamingDefaults:
120+
enabled: bool | None = None
121+
122+
@dataclass
123+
class DisplayConfig:
124+
dimension_mode: str = "stack"
125+
126+
@dataclass
127+
class ViewerConfig(StreamingDefaults, DisplayConfig):
128+
pass
129+
130+
ViewerConfig = rebuild_with_none_defaults(
131+
ViewerConfig,
132+
get_inherited_field_names(ViewerConfig),
133+
)
134+
bind_lazy_resolution_to_class(StreamingDefaults)
135+
bind_lazy_resolution_to_class(ViewerConfig)
136+
context_token = current_temp_global.set(None)
137+
try:
138+
assert StreamingDefaults().enabled is None
139+
assert "_field_names_set" in StreamingDefaults.__dict__
140+
assert "_field_names_set" not in ViewerConfig.__dict__
141+
assert ViewerConfig().dimension_mode == "stack"
142+
assert "_field_names_set" in ViewerConfig.__dict__
143+
assert "dimension_mode" in ViewerConfig.__dict__["_field_names_set"]
144+
finally:
145+
current_temp_global.reset(context_token)
146+
147+
81148
def test_none_default_rebuild_preserves_declaration_metadata_and_validation() -> None:
82149
from objectstate.lazy_factory import rebuild_with_none_defaults
83150

@@ -301,6 +368,24 @@ class LazyConfig:
301368
LazyConfig()
302369

303370

371+
def test_patch_lazy_constructors_preserves_nominal_validation_and_authored_fields():
372+
@dataclass
373+
class BaseConfig(AnnotatedDataclassValidationMixin):
374+
count: int = 1
375+
label: str = "default"
376+
377+
lazy_config_type = LazyDataclassFactory.make_lazy_simple(BaseConfig)
378+
379+
with patch_lazy_constructors(types=[lazy_config_type]):
380+
candidate = lazy_config_type(count=3)
381+
with pytest.raises(TypeError, match="LazyBaseConfig.count"):
382+
lazy_config_type(count="invalid")
383+
384+
assert object.__getattribute__(candidate, "count") == 3
385+
assert object.__getattribute__(candidate, "label") is None
386+
assert candidate.__dict__["_explicitly_set_fields"] == {"count"}
387+
388+
304389
def test_nested_lazy_dataclass():
305390
"""Test creating lazy dataclass with nested dataclass fields."""
306391
@dataclass

0 commit comments

Comments
 (0)