← Writing

A Delayed Flush Reverted the Fresh Write

5 min read#Python#asyncio#Concurrency#Autarkia

One JSON file, two write paths: a direct write merges into a fresh read, a deferred one edits an in-memory cache and flushes the whole object two seconds later. Nothing invalidates the cache, so the flush puts the old timestamp back.

Table of Contents

The input to a proactive decision said the user last spoke 4 days and 17 hours ago. The same input quoted a message from a few minutes earlier, and both the chat history and retrieval were fine. Two numbers disagreed, and only one of them was wrong.

The wrong one was last_user_interaction_ts in the state file, stuck four days back. last_sent_ts in the same file was a few minutes old. Something had just written the current time, and two seconds later it was back to the old value.

01Two write paths

The state object has a dozen fields, and the save function has two branches. With a scope it bypasses the cache and does read, merge, write. Without one it edits an in-memory cache, marks it dirty, and schedules a delayed task. Read separately, both look right: clear argument names, an atomic write, and a lock.

python
async def save_proactive_state(self, updates, scope=None):
    if scope is not None:
        state_file = os.path.join(self._get_runtime_dir(scope), "proactive_state.json")
        current_state = await self._read_json_file(state_file)
        current_state.update(updates)
        await self._write_json_file(state_file, current_state)  # 内部拿 _file_lock
        return current_state

    self._proactive_state_cache.update(updates)
    self._pending_updates.update(updates)
    self._dirty = True
    self._ensure_flush_task()   # 2 秒后刷盘

The flush looks reasonable too: the same lock, an atomic write, fsync. The line that decides the behaviour is the third one. It writes _proactive_state_cache, not _pending_updates.

python
async def _flush_pending_updates(self):
    async with self._file_lock:
        state = self._proactive_state_cache   # 整份缓存,不是待写字段
        if state is None:
            return
        state_file = os.path.join(self._get_runtime_dir(), "proactive_state.json")
        await self._write_json_file_unlocked(state_file, state)

The scoped write never touches the cache and never invalidates it; the unscoped write merges its fields into the cache, and the flush writes the whole thing. The lock keeps the two writes from interleaving, but the second writer had already read its base before the first one ran. Serialized writes can still lose an update.

The full sequence:

  • The process starts and loads the cache from disk; last_user_interaction_ts is four days old.
  • The user sends a message. reset_interaction_state does a scoped direct write, so the field becomes the current time; the cache is untouched.
  • In the same turn, set_next_decision_ts and on_assistant_message_sent take the unscoped branch, put next_decision_ts and last_sent_ts into the cache, and schedule the delayed task.
  • Two seconds later the flush overwrites the file with the whole cache. last_user_interaction_ts goes back four days, while the same write leaves next_decision_ts and last_sent_ts fresh.

I wrote a thirty-line script following that order, and the file ended up with the old value while every other field was fresh.

02Two tests, one half each

The old storage tests had one case for the direct write, asserting the new value in the file, and one for the deferred write, asserting that _pending_updates held the value and the task was scheduled. No case did a direct write and then waited for the flush. Each path was correct on its own; only their order was wrong.

The read side also has a sanity check: a timestamp is accepted as long as it is not in the future and not more than 30 days old. Four days passed easily, so the decision code computed four days of silence while the same prompt quoted a message from minutes ago. Seeing those two numbers together, the first guess is usually that the model ignored the context.

Nor did the file look broken: its mtime was just now, last_sent_ts was just now, and only last_user_interaction_ts sat at the old value.

Both paths were already there in the first commit of the repository’s surviving history (the history was rebuilt on 06-18, and both pieces are present in a commit from 06-19), so there is no way to trace who added them or when.

03The pending buffer also needs a destination

The same deferred queue had a second problem: _pending_updates stored fields but not their destination scope. After set_runtime_scope() switched to another role, the flush two seconds later resolved the directory from the current scope, so the previous role’s pending fields landed in the new role’s state file. No error; another role’s last_sent_ts just jumped to now, and its rate limiting drifted with it.

04Re-read the disk before flushing

The fix did not add more locking. The flush re-reads the disk and merges only the pending fields; the direct write and the flush share one lock, and the direct write clears the cache; pending updates record their scope when enqueued, and the flush writes to that scope. The cache goes back to being a fallback for when there is no more authoritative copy.

python
pending = dict(self._pending_updates)
disk_state = await self._read_json_file(state_file)
state = {**disk_state, **pending}

Whenever an object has both a cached write and a direct write that bypasses the cache, a deferred flush must not write the whole object. Either every write goes through the cache, or the flush merges by field. A lock only queues the writes; it has no way to know that the second writer’s base is stale.