Updating Memory
Memory updates must be atomic and validated. A partial write or invalid update can corrupt the agent's state and lead to unpredictable behaviour.
6 min•By Priygop Team•Updated 2026
Safe Update Principles
- Write atomically: update state all at once, not field by field, to avoid partial writes
- Validate before writing: check that the new value is valid before overwriting the old one
- Log every write: record what was changed, when, and by which agent step
- Use optimistic locking for concurrent agents: check that state has not changed before writing
- Back up important state before overwriting: keep a previous version in case the update was wrong
Atomic State Update
Atomic State Update
import copy
from datetime import datetime
class SafeStateManager:
def __init__(self):
self._state = {}
self._audit_log = []
def update(self, updates: dict, agent_step: int, validate_fn=None) -> dict:
"""
Apply multiple updates atomically.
validate_fn: optional function that checks the merged state is valid.
"""
# Create a candidate state (don't modify actual state yet)
candidate = copy.deepcopy(self._state)
candidate.update(updates)
# Validate if a validator is provided
if validate_fn:
is_valid, error_msg = validate_fn(candidate)
if not is_valid:
return {"status": "error",
"error": f"State update rejected: {error_msg}"}
# Apply update atomically
self._state = candidate
# Log the update
self._audit_log.append({
"timestamp": datetime.now().isoformat(),
"step": agent_step,
"changes": list(updates.keys())
})
return {"status": "success", "updated_keys": list(updates.keys())}
def validate_task_state(state: dict) -> tuple:
if state.get("step", 0) < 0:
return False, "step cannot be negative"
if state.get("status") not in {"running","complete","failed","waiting","escalated"}:
return False, f"Invalid status: {state.get('status')}"
return True, ""
sm = SafeStateManager()
result = sm.update(
{"step": 1, "status": "running", "last_action": "web_search"},
agent_step=1,
validate_fn=validate_task_state
)
print(result)
print("State:", sm._state)Key Takeaways
- Memory updates must be atomic and validated.
- Write atomically: update state all at once, not field by field, to avoid partial writes
- Validate before writing: check that the new value is valid before overwriting the old one
- Log every write: record what was changed, when, and by which agent step