fix(state): persist explicitly supplied states in StateManagerDisk

Merged
FA
3mo ago
+134-2

Summary

StateManagerDisk.set_state silently lost data when called with a state instance that was not the one returned by get_state:

  • The debounced write queue kept the first queued object and ignored later calls, so the new instance never reached disk.
  • The in-memory cache (self.states) was never updated, so subsequent get_state calls returned the stale instance.
  • A freshly constructed instance has no touched flags set, so even the immediate write path skipped it entirely.

Approach

Alternative implementation of #6807 (thanks @harsh21234i for the analysis and regression tests). Instead of threading a force_write parameter through QueueItem, set_state_for_substate, and both flush paths, this encodes the persistence decision where it already lives: the state's own _was_touched flag.

set_state does one O(1) identity check against the cache. If the supplied instance is not the cached one, it marks the whole tree touched — the existing touched-driven machinery then persists it with zero signature changes to set_state_for_substate or the flush paths. The flag is sticky until write time, which also covers accumulation across debounced updates for free. Setting _was_touched externally is an established pattern (_screenshot.py, vars/base.py), the flag is stripped on pickling, and its docstring states it exists exactly for this purpose ("determines whether this state instance should be persisted").

Also:

  • Queued QueueItems are updated in place (queued_item.state = state) instead of ignored, per masenf's preference in #6807.
  • The cache is updated on both paths (after the write on the immediate path, so a failed write is not cached).
  • set_state records _token_last_touched, so a token that is only ever written still expires instead of leaking cache entries.

Non-BaseState tokens need no marking: their get_and_reset_touched_state always returns True.

Testing

Regression tests (ported from #6807, written to fail before the fix): latest-queued-value flush, cache replacement for arbitrary instances (both debounce modes), and persistence of an untouched BaseState (both debounce modes).

Fixes #6806