Skip to content

Commit 0fdee60

Browse files
trissimclaude
andauthored
a write snapshots only what it changed; a clean state resolves its saved epoch once (#70)
* a write snapshots only what it changed; a clean state resolves its saved epoch once Two costs that grew with every registered state, measured in Toad's Qt client: - record_snapshot found which clean scopes share an object with a changed one by deep-copying every registered state's values on every write, though it copies only the changed ones. Each scope now keeps the objects its values reached when it was last captured (SnapshotReach, which holds them so their ids stay theirs). A scope left clean keeps that capture in the next snapshot and reaches the same objects, so only the scopes being captured are walked. A clean scope that shares an object with one of them is still captured with it, and time travel forgets what scopes reached, since restored scopes hold copies. - A state opened or saved under ancestors holding exactly their saved parameters resolved every field twice in __init__ (live, then saved) and again in mark_saved. While this state and every registered ancestor are not raw-dirty, both epochs read the same values, so the saved epoch is the live snapshot, copied as the saved parameters are (a live value changed in place stays dirty). Otherwise it is resolved on its own, as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RnH6dT7wdh7i4tjJZQdFu3 * lint: dict annotations, the sharing scope registered without an unused name, one long line wrapped Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RnH6dT7wdh7i4tjJZQdFu3 --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 93c87f4 commit 0fdee60

3 files changed

Lines changed: 134 additions & 22 deletions

File tree

‎src/objectstate/object_state.py‎

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,7 @@ def __init__(
246246
#
247247
# If we used copy.deepcopy(_live_resolved), we'd bake in ancestor's unsaved
248248
# edits, causing inverted dirty state when ancestor is saved/reset.
249-
self._saved_resolved = self._compute_resolved_snapshot(use_saved=True)
249+
self._saved_resolved = self._saved_resolved_snapshot()
250250

251251
# DEBUG: Log live vs saved at registration
252252
logger.debug(f"🔵 INIT_RESOLVED: scope={self.scope_id!r} obj_type={type(self.object_instance).__name__}")
@@ -2051,6 +2051,34 @@ def prepare_for_snapshot_capture(self) -> None:
20512051

20522052
# ==================== SAVED STATE / DIRTY TRACKING ====================
20532053

2054+
def _saved_resolved_snapshot(self) -> dict[str, Any]:
2055+
"""The saved epoch's resolved values: the live ones while the two epochs read the
2056+
same values, resolved on their own otherwise.
2057+
2058+
The saved epoch reads this state's saved parameters and each registered ancestor's
2059+
saved object; the live epoch reads the current ones. While this state and every
2060+
ancestor hold exactly their saved parameters, both epochs read the same values and
2061+
resolve alike, so a state opened or saved under clean ancestors (every view opened
2062+
over saved settings) resolves its fields once instead of once per epoch.
2063+
"""
2064+
if self._saved_epoch_is_live():
2065+
# The saved sources first: bringing the live snapshot up to date resolves the
2066+
# saved one again when its sources are not yet the ones recorded.
2067+
self._resolved_from[True] = self._resolution_sources(sync_delegates=False)[True]
2068+
self._ensure_live_resolved(notify_flash=False)
2069+
# Copied as the saved parameters are: a live value changed in place stays dirty.
2070+
return self._copy_parameters_for_saved_baseline(self._live_resolved)
2071+
return self._compute_resolved_snapshot(use_saved=True)
2072+
2073+
def _saved_epoch_is_live(self) -> bool:
2074+
if self.is_raw_dirty:
2075+
return False
2076+
return not any(
2077+
state.is_raw_dirty
2078+
for _, state in ObjectStateRegistry.registered_ancestors(self.scope_id)
2079+
if state is not self
2080+
)
2081+
20542082
def _compute_resolved_snapshot(self, use_saved: bool = False) -> dict[str, Any]:
20552083
"""Resolve editor fields using the selected live or saved ancestor epoch."""
20562084
if not isinstance(self.parameters, dict):
@@ -2243,7 +2271,7 @@ def mark_saved(self) -> None:
22432271
# Compute new saved resolved using SAVED ancestor baselines (use_saved=True)
22442272
# This ensures saved baseline is computed relative to other saved baselines
22452273
logger.debug(f"🔧 mark_saved: Computing new saved_resolved for scope={self.scope_id!r}")
2246-
new_saved_resolved = self._compute_resolved_snapshot(use_saved=True)
2274+
new_saved_resolved = self._saved_resolved_snapshot()
22472275
logger.debug(f"🔧 mark_saved: New saved_resolved computed, keys={list(new_saved_resolved.keys())[:5]}...")
22482276

22492277
# Update saved resolved baseline

‎src/objectstate/object_state_registry.py‎

Lines changed: 65 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,22 @@
4242
logger = logging.getLogger(__name__)
4343

4444

45+
@dataclass(frozen=True)
46+
class SnapshotReach:
47+
"""The objects one scope's values reached when ``capture`` was taken of them.
48+
49+
``held`` keeps those objects alive while this is kept, so an identity in
50+
``identities`` stays theirs and is never another object's reused id.
51+
"""
52+
53+
identities: frozenset
54+
held: list
55+
capture: object = None
56+
57+
def of(self, capture: object) -> "SnapshotReach":
58+
return SnapshotReach(self.identities, self.held, capture)
59+
60+
4561
class ObjectStateRegistrySubscription:
4662
"""Idempotent ownership handle for one registry callback registration."""
4763

@@ -215,6 +231,11 @@ class attributes, so two independent registries cannot exist.
215231
_on_unregister_callbacks: List[Callable[[str, 'ObjectState'], None]] = []
216232
_deferred_invalidations: Set[DeferredFieldInvalidation] = set()
217233
_snapshot_dirty_scopes: Set[str] = set()
234+
# The objects each scope's values reached when it was last captured, with the capture
235+
# they belong to. A scope left clean since keeps that capture in the next snapshot and
236+
# reaches the same objects, so a snapshot walks only the scopes it captures to find
237+
# which clean ones share an object with them (`_record_snapshot_internal`).
238+
_snapshot_reach: dict[str, "SnapshotReach"] = {}
218239

219240
# Time-travel completion callbacks - UI subscribes to reopen windows for dirty states
220241
# Callbacks receive (dirty_states, triggering_scope) where:
@@ -585,6 +606,7 @@ def clear(cls) -> None:
585606
cls._deferred_invalidations.clear()
586607
_live_invalidation_deferrals.set(0)
587608
cls._snapshot_dirty_scopes.clear()
609+
cls._snapshot_reach.clear()
588610
cls._snapshots.clear()
589611
cls._timelines.clear()
590612
cls._current_head = None
@@ -1248,8 +1270,10 @@ def _record_snapshot_internal(
12481270

12491271
for state in cls._states.values():
12501272
state.validate_metadata_contracts("snapshot")
1251-
capture_values = {
1252-
key: StateSnapshot(
1273+
1274+
def capture_values(key: str) -> StateSnapshot:
1275+
state = cls._states[key]
1276+
return StateSnapshot(
12531277
saved_resolved=state._saved_resolved,
12541278
live_resolved=state._live_resolved,
12551279
parameters=state.parameters,
@@ -1258,27 +1282,46 @@ def _record_snapshot_internal(
12581282
construction=state.construction_binding(),
12591283
meta=state.copy_metadata_for_snapshot(),
12601284
)
1261-
for key, state in cls._states.items()
1262-
}
1285+
1286+
def walked(values: StateSnapshot) -> SnapshotReach:
1287+
memo: dict[int, Any] = {}
1288+
copy.deepcopy(values, memo)
1289+
return SnapshotReach(
1290+
frozenset(memo) - {id(memo), id(values), id(values.construction)},
1291+
memo.get(id(memo), []),
1292+
)
1293+
12631294
# A changed scope also invalidates immutable snapshots that share a
12641295
# copied object with it. Independent clean scopes retain structural
12651296
# sharing; connected scopes are copied together with one graph memo.
1266-
alias_scopes: Dict[int, Set[str]] = {}
1267-
for key, values in capture_values.items():
1268-
memo: Dict[int, Any] = {}
1269-
copy.deepcopy(values, memo)
1270-
for identity in memo:
1271-
if identity not in (id(memo), id(values), id(values.construction)):
1272-
alias_scopes.setdefault(identity, set()).add(key)
1273-
pending = list(snapshot_candidate_keys)
1274-
while pending:
1275-
key = pending.pop()
1276-
for scopes in alias_scopes.values():
1277-
if key in scopes:
1278-
additional = scopes - snapshot_candidate_keys
1279-
snapshot_candidate_keys.update(additional)
1280-
pending.extend(additional)
1281-
captured = copy.deepcopy({key: capture_values[key] for key in snapshot_candidate_keys})
1297+
# Only the scopes being captured are walked: a clean scope reaches what
1298+
# it reached when its kept capture was taken.
1299+
values_of = {key: capture_values(key) for key in snapshot_candidate_keys}
1300+
reach = {key: walked(values) for key, values in values_of.items()}
1301+
for key in current_state_keys - snapshot_candidate_keys:
1302+
kept = cls._snapshot_reach.get(key)
1303+
if kept is not None and kept.capture is all_states.get(key):
1304+
reach[key] = kept
1305+
else:
1306+
values_of[key] = capture_values(key)
1307+
reach[key] = cls._snapshot_reach[key] = walked(values_of[key]).of(all_states[key])
1308+
shared = set().union(*(reach[key].identities for key in snapshot_candidate_keys))
1309+
clean = current_state_keys - snapshot_candidate_keys
1310+
joined = True
1311+
while joined:
1312+
joined = {key for key in clean if not reach[key].identities.isdisjoint(shared)}
1313+
clean -= joined
1314+
snapshot_candidate_keys |= joined
1315+
for key in joined:
1316+
shared |= reach[key].identities
1317+
captured = copy.deepcopy({
1318+
key: values_of[key] if key in values_of else capture_values(key)
1319+
for key in snapshot_candidate_keys
1320+
})
1321+
for key in snapshot_candidate_keys:
1322+
cls._snapshot_reach[key] = reach[key].of(captured[key])
1323+
for key in set(cls._snapshot_reach) - current_state_keys:
1324+
del cls._snapshot_reach[key]
12821325

12831326
with TimeTravelProfiler.phase(
12841327
"objectstate.snapshot_capture_states",
@@ -1967,6 +2010,8 @@ def time_travel_to_snapshot(cls, snapshot_id: str) -> bool:
19672010
}
19682011
cls._current_head = snapshot_id
19692012
cls._in_time_travel = True
2013+
# Restored scopes hold copies of the snapshot's values, not what they reached before.
2014+
cls._snapshot_reach.clear()
19702015
try:
19712016
with TimeTravelProfiler.phase(
19722017
"objectstate.reconcile_scopes",

‎tests/test_construction_history.py‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -479,3 +479,42 @@ def test_failed_attachment_rolls_back_complete_graph_and_loaded_history(tmp_path
479479
assert path.read_bytes() == file_bytes
480480

481481

482+
483+
484+
def test_a_snapshot_walks_only_the_scopes_it_captures():
485+
"""An edit walks and copies the edited scope; an independent clean scope keeps its
486+
capture and the objects it reached then, unwalked, while one that shares an object
487+
with the edited scope is captured with it. Time travel forgets what scopes reached."""
488+
shared = [1, 2]
489+
edited = register(Config(items=shared), "edited")
490+
register(Config(items=shared), "sharing")
491+
independent = [register(Config(value=number), f"independent-{number}") for number in range(5)]
492+
baseline = ObjectStateRegistry._snapshots[record("baseline")]
493+
reached = {
494+
state.scope_id: ObjectStateRegistry._snapshot_reach[state.scope_id] for state in independent
495+
}
496+
edited.update_parameter("value", 3)
497+
after = ObjectStateRegistry.get_branch_history()[-1]
498+
for state in independent:
499+
assert after.all_states[state.scope_id] is baseline.all_states[state.scope_id]
500+
assert ObjectStateRegistry._snapshot_reach[state.scope_id] is reached[state.scope_id]
501+
assert after.all_states["sharing"] is not baseline.all_states["sharing"]
502+
assert after.all_states["edited"].parameters["value"] == 3
503+
assert ObjectStateRegistry.time_travel_to_snapshot(baseline.id)
504+
assert ObjectStateRegistry._snapshot_reach == {}
505+
506+
507+
def test_a_state_opened_under_saved_ancestors_resolves_its_saved_epoch_as_its_live_one():
508+
"""Under ancestors holding their saved values, the saved epoch reads what the live one
509+
reads: it is the live snapshot, copied, so a live value changed in place is dirty. An
510+
ancestor with unsaved values gives the saved epoch its own resolution."""
511+
parent = register(Config(value=4, items=[1]), "clean-parent")
512+
child = register(LazyDataclassFactory.make_lazy_simple(Config)(), "clean-parent::child")
513+
assert child._saved_resolved == child._live_resolved
514+
assert child._saved_resolved["items"] is not child._live_resolved["items"]
515+
parent.update_parameter("value", 5)
516+
late = ObjectState(
517+
LazyDataclassFactory.make_lazy_simple(Config)(), scope_id="clean-parent::late"
518+
)
519+
assert late._live_resolved["value"] == 5
520+
assert late._saved_resolved["value"] == 4

0 commit comments

Comments
 (0)