Skip to content

Commit 91caf53

Browse files
committed
Make ObjectState reconciliation single-notify
1 parent 76c79f0 commit 91caf53

7 files changed

Lines changed: 112 additions & 24 deletions

‎src/objectstate/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,7 @@
240240
mark_ui_hidden_config,
241241
should_hide_ui_parameter,
242242
)
243+
from objectstate.value_semantics import semantic_values_equal
243244

244245
# Snapshot model for time-travel
245246
from objectstate.snapshot_model import Snapshot, StateSnapshot, Timeline
@@ -269,6 +270,7 @@
269270
'mark_ui_special_fields',
270271
'mark_ui_hidden_config',
271272
'should_hide_ui_parameter',
273+
'semantic_values_equal',
272274
# Snapshot model
273275
'Snapshot',
274276
'StateSnapshot',

‎src/objectstate/object_state.py‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -965,11 +965,6 @@ def update_parameter(self, param_name: str, value: Any) -> Set[str]:
965965

966966
# SELF-INVALIDATION: Mark changed fields and same-state inherited siblings.
967967
local_invalidations = set(changed_semantic_params)
968-
# Descendants resolve through ancestor live values. Recompute this state
969-
# before cascading invalidation so child snapshots cannot lag one edit
970-
# behind their parent.
971-
changed_paths = self._ensure_live_resolved(notify_flash=False)
972-
973968
for changed_param in changed_semantic_params:
974969
container_type = self._path_to_type.get(changed_param, type(self.object_instance))
975970
leaf_field_name = changed_param.split('.')[-1] if '.' in changed_param else changed_param
@@ -1032,6 +1027,9 @@ def update_parameter(self, param_name: str, value: Any) -> Set[str]:
10321027
except Exception as e:
10331028
logger.warning(f"Failed to update LIVE thread-local: {e}")
10341029

1030+
# Materialize the origin once after its live context is authoritative,
1031+
# then cascade only to descendants.
1032+
changed_paths = self._ensure_live_resolved(notify_flash=False)
10351033
for changed_param in changed_semantic_params:
10361034
# SCOPE + TYPE + FIELD AWARE INVALIDATION:
10371035
# Get the CONTAINER type for this field (e.g., WellFilterConfig for 'well_filter_config.well_filter')
@@ -1049,7 +1047,8 @@ def update_parameter(self, param_name: str, value: Any) -> Set[str]:
10491047
ObjectStateRegistry.invalidate_by_type_and_scope(
10501048
scope_id=self.scope_id,
10511049
changed_type=container_type,
1052-
field_name=leaf_field_name
1050+
field_name=leaf_field_name,
1051+
include_origin=False,
10531052
)
10541053

10551054
# Increment global token for LiveContextService.collect() cache invalidation

‎src/objectstate/object_state_registry.py‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@ class DeferredFieldInvalidation:
103103
changed_type: ParameterOwner
104104
field_name: str
105105
invalidate_saved: bool = False
106+
include_origin: bool = True
106107

107108

108109
class ObjectStateRegistry:
@@ -228,6 +229,7 @@ def flush_deferred_invalidations(cls) -> None:
228229
changed_type=request.changed_type,
229230
field_name=request.field_name,
230231
invalidate_saved=request.invalidate_saved,
232+
include_origin=request.include_origin,
231233
)
232234
finally:
233235
cls._deferred_invalidation_depth = previous_depth
@@ -634,7 +636,8 @@ def invalidate_by_type_and_scope(
634636
scope_id: Optional[str],
635637
changed_type: ParameterOwner,
636638
field_name: str,
637-
invalidate_saved: bool = False
639+
invalidate_saved: bool = False,
640+
include_origin: bool = True,
638641
) -> None:
639642
"""Invalidate a specific field in states that could inherit from changed_type at scope_id.
640643
@@ -653,6 +656,8 @@ def invalidate_by_type_and_scope(
653656
changed_type: The type of the ObjectState that was modified
654657
field_name: The specific field that changed
655658
invalidate_saved: If True, also invalidate saved_resolved cache for descendants
659+
include_origin: Whether to invalidate the state at ``scope_id`` as
660+
well as its descendants.
656661
"""
657662
changed_scope = cls._normalize_scope_id(scope_id)
658663
if cls._deferred_invalidation_depth > 0:
@@ -662,6 +667,7 @@ def invalidate_by_type_and_scope(
662667
changed_type=changed_type,
663668
field_name=field_name,
664669
invalidate_saved=invalidate_saved,
670+
include_origin=include_origin,
665671
)
666672
)
667673
return
@@ -671,6 +677,7 @@ def invalidate_by_type_and_scope(
671677
changed_type=changed_type,
672678
field_name=field_name,
673679
invalidate_saved=invalidate_saved,
680+
include_origin=include_origin,
674681
)
675682

676683
@classmethod
@@ -680,6 +687,7 @@ def _invalidate_by_type_and_scope_now(
680687
changed_type: ParameterOwner,
681688
field_name: str,
682689
invalidate_saved: bool = False,
690+
include_origin: bool = True,
683691
) -> None:
684692
"""Immediate implementation for scope/type/field-aware invalidation."""
685693
from objectstate.lazy_factory import get_base_type_for_lazy
@@ -703,6 +711,9 @@ def _invalidate_by_type_and_scope_now(
703711

704712
for state in cls._states.values():
705713
state_scope = cls._normalize_scope_id(state.scope_id)
714+
is_self = state_scope == changed_scope
715+
if is_self and not include_origin:
716+
continue
706717

707718
# SCOPE CHECK: must be at or below changed scope
708719
# Global scope (empty string) affects ALL states
@@ -713,7 +724,6 @@ def _invalidate_by_type_and_scope_now(
713724
logger.debug(f"[SCOPE] Global change affects state scope={state_scope!r}")
714725
else:
715726
# Non-global: check exact match or descendant
716-
is_self = (state_scope == changed_scope)
717727
prefix = changed_scope + "::"
718728
is_descendant = state_scope.startswith(prefix)
719729
if not (is_self or is_descendant):

‎src/objectstate/transaction_checkpoint.py‎

Lines changed: 2 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
from objectstate.object_state import ObjectState
1010
from objectstate.object_state_metadata import ObjectStateMetadataStore
11+
from objectstate.value_semantics import semantic_values_equal
1112

1213

1314
@dataclass(frozen=True, slots=True)
@@ -151,28 +152,13 @@ def _changed_fields(self, state: ObjectState) -> set[str]:
151152
fields.update(
152153
key
153154
for key in set(current) | set(target)
154-
if not self._values_equal(
155+
if not semantic_values_equal(
155156
current.get(key, missing),
156157
target.get(key, missing),
157158
)
158159
)
159160
return state._most_specific_notification_fields(fields)
160161

161-
@staticmethod
162-
def _values_equal(left: Any, right: Any) -> bool:
163-
"""Compare checkpoint values without assuming scalar equality."""
164-
165-
if left is right:
166-
return True
167-
try:
168-
comparison = left == right
169-
except Exception:
170-
return False
171-
try:
172-
return bool(comparison)
173-
except (TypeError, ValueError):
174-
return False
175-
176162
@staticmethod
177163
def _copy_mappings(
178164
state: ObjectState,

‎src/objectstate/value_semantics.py‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
"""Shared value comparison semantics for declaration and state reconciliation."""
2+
3+
from __future__ import annotations
4+
5+
from collections.abc import Mapping, Sequence
6+
7+
8+
def semantic_values_equal(left: object, right: object) -> bool:
9+
"""Compare nested values without requiring hashability or scalar equality."""
10+
11+
if left is right:
12+
return True
13+
if isinstance(left, Mapping) and isinstance(right, Mapping):
14+
return left.keys() == right.keys() and all(
15+
semantic_values_equal(left[key], right[key]) for key in left
16+
)
17+
if (
18+
isinstance(left, Sequence)
19+
and isinstance(right, Sequence)
20+
and not isinstance(left, (str, bytes, bytearray))
21+
and not isinstance(right, (str, bytes, bytearray))
22+
):
23+
return len(left) == len(right) and all(
24+
semantic_values_equal(left_value, right_value)
25+
for left_value, right_value in zip(left, right)
26+
)
27+
try:
28+
comparison = left == right
29+
except Exception:
30+
return False
31+
try:
32+
return bool(comparison)
33+
except (TypeError, ValueError):
34+
return False

‎tests/test_object_state_update_instance.py‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,34 @@ def test_update_object_instance_notifies_resolved_changes_and_saved_baseline():
9292
assert state.last_changed_field == "threshold"
9393

9494

95+
def test_update_parameter_notifies_origin_once_and_preserves_dirty_baseline():
96+
state = ObjectState(PlainConfig(), scope_id="config")
97+
ObjectStateRegistry.register(state, _skip_snapshot=True)
98+
events: list[tuple[str, set[str]]] = []
99+
ObjectStateRegistry.add_resolved_changed_callback(
100+
lambda scope_id, changed: events.append((scope_id, set(changed)))
101+
)
102+
103+
state.update_parameter("threshold", 2)
104+
105+
assert events == [("config", {"threshold"})]
106+
assert state.dirty_fields == {"threshold"}
107+
assert state.get_saved_resolved_value("threshold") == 1
108+
109+
110+
def test_update_parameter_notifies_global_scope_origin_once():
111+
state = ObjectState(PlainConfig(), scope_id="")
112+
ObjectStateRegistry.register(state, _skip_snapshot=True)
113+
events: list[tuple[str, set[str]]] = []
114+
ObjectStateRegistry.add_resolved_changed_callback(
115+
lambda scope_id, changed: events.append((scope_id, set(changed)))
116+
)
117+
118+
state.update_parameter("threshold", 2)
119+
120+
assert events == [("", {"threshold"})]
121+
122+
95123
def test_direct_parameter_paths_project_canonical_flat_topology_without_values():
96124
state = ObjectState(ConfigWithNestedTopology(), scope_id="config")
97125

‎tests/test_value_semantics.py‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"""Shared semantic value comparison contracts."""
2+
3+
from objectstate import semantic_values_equal
4+
5+
6+
class AmbiguousEquality:
7+
"""Value whose comparison result cannot be reduced to one truth value."""
8+
9+
def __eq__(self, other: object):
10+
del other
11+
return self
12+
13+
def __bool__(self) -> bool:
14+
raise ValueError("ambiguous")
15+
16+
17+
def test_semantic_values_equal_compares_nested_unhashable_declarations() -> None:
18+
assert semantic_values_equal(
19+
{"channel": ["A", {"threshold": 2}]},
20+
{"channel": ["A", {"threshold": 2}]},
21+
)
22+
assert not semantic_values_equal(
23+
{"channel": ["A", {"threshold": 2}]},
24+
{"channel": ["A", {"threshold": 3}]},
25+
)
26+
27+
28+
def test_semantic_values_equal_treats_ambiguous_equality_as_changed() -> None:
29+
assert not semantic_values_equal(AmbiguousEquality(), AmbiguousEquality())

0 commit comments

Comments
 (0)