Context
An input spec was resolved into a derived object and memoized in a WeakMap keyed by the spec object, with a content-keyed map (JSON string) behind it. Later, an editor started mutating its spec in place on every confirmed action.
The lookup kept returning the object resolved the first time it saw that spec. The view looked right only while a preview was active, because previews were made with structuredClone, so each one was a new key. Unit tests passed because they resolved fresh objects every time. Only a screenshot showed the stale result.
Insight
An identity-keyed cache can’t tell that its key’s contents have changed, so it serves the old result without any error. Memoizing on object identity is only safe if the key is never mutated after the first lookup. Pick one:
- Copy at the boundary: hand the consumer a copy, so every change produces a new key.
- Freeze: make the spec immutable once it has been resolved (
Object.freeze, or at least a documented rule). - Key on content: use a hash or serialization instead of identity.
Snippet
const cache = new WeakMap<Spec, Derived>();function resolve(spec: Spec): Derived { let d = cache.get(spec); if (!d) { d = derive(spec); cache.set(spec, d); } return d;}
spec.items.push(item); // in-place mutation, same keyresolve(spec); // stale: returns the result for the old contents
resolve(structuredClone(spec)); // fix: new key, fresh resultTests that only ever build fresh objects won’t catch this. Add one that mutates a spec after resolving it and resolves it again.