Skip to content

A platform for community discussion. Free, open, simple.

PERF: Prevent unbounded growth of store identity map (#37163)

Sérgio Saquetim8160411cd248
diff --git a/frontend/discourse/app/lib/weak-value-map.js b/frontend/discourse/app/lib/weak-value-map.js
new file mode 100644
index 00000000000..4bf88951594
--- /dev/null
+++ b/frontend/discourse/app/lib/weak-value-map.js
@@ -0,0 +1,252 @@
+/**
+ * A Map that holds weak references to its values, allowing them to be
+ * garbage collected when no other references exist.
+ *
+ * Use cases:
+ * - Caches that won't grow forever: cached values are automatically evicted
+ * when no longer referenced elsewhere, preventing memory leaks.
+ * - Identity maps: ensures the same key always returns the same object instance
+ * while allowing unused entries to be garbage collected.
+ * - Memoization: stores computed results that can be recalculated if evicted.
+ *
+ * This class provides the same API as the standard Map, but values may
+ * disappear if they are garbage collected. Methods like `get()` and iterators
+ * will return `undefined` or skip entries whose values have been collected.
+ *
+ * @template K - The key type.
+ * @template {object} V - The value type. Must be an object since WeakRef
+ * only works with objects.
+ */
+class WeakValueMap {
+ #map = new Map();
+ #registry;
+
+ constructor() {
+ this.#registry = new FinalizationRegistry((key) => {
+ const ref = this.#map.get(key);
+ // Only delete if the ref is dead. A new value might have been set
+ // for this key after the old value was garbage collected.
+ if (ref && ref.deref() === undefined) {
+ this.#map.delete(key);
+ }
+ });
+ }
+
+ /**
+ * Scans the map and removes entries whose values have been garbage collected.
+ *
+ * This method serves as a backup cleanup mechanism in case the
+ * FinalizationRegistry doesn't run promptly. It uses an early-exit
+ * optimization: if the first SAMPLE_SIZE entries are all live, we assume
+ * the registry is doing its job and skip the full scan. If any dead entry
+ * is found in the sample, we continue scanning the entire map since dead
+ * refs tend to cluster (e.g., after route transitions drop many models).
+ */
+ #sweep() {
+ const SAMPLE_SIZE = 20;
+ let checked = 0;
+ let foundDead = false;
+
+ for (const [key, ref] of this.#map) {
+ const dead = ref.deref() === undefined;
+
+ if (dead) {
+ this.#map.delete(key);
+ foundDead = true;
+ }
+
+ checked++;
+
+ // Early exit: if first N entries are all live, assume registry is working
+ if (!foundDead && checked >= SAMPLE_SIZE) {
+ return;
+ }
+ }
+ }
+
+ /**
+ * Returns the number of entries in the map.
+ *
+ * Note: This value may be inaccurate because it can include entries whose
+ * values have been garbage collected but not yet cleaned up by the
+ * FinalizationRegistry. For an accurate count, iterate over the map.
+ *
+ * @returns {number}
+ */
+ get size() {
+ return this.#map.size;
+ }
+
+ /**
+ * Gets the value associated with a key.
+ *
+ * @param {K} key - The key to look up.
+ * @returns {V | undefined} The value, or undefined if the key doesn't exist
+ * or its value has been garbage collected.
+ */
+ get(key) {
+ // ~1% chance to sweep on each get
+ if (Math.random() < 0.01) {
+ this.#sweep();
+ }
+
+ const ref = this.#map.get(key);
+ if (ref) {
+ const value = ref.deref();
+ if (value !== undefined) {
+ return value;
+ }
+ // Value was garbage collected, clean up the entry.
+ this.#map.delete(key);
+ }
+ return undefined;
+ }
+
+ /**
+ * Sets a value for a key.
+ *
+ * @param {K} key - The key to set.
+ * @param {V} value - The value to associate with the key.
+ * @returns {this} The map instance for chaining.
+ */
+ set(key, value) {
+ const existingRef = this.#map.get(key);
+ if (existingRef) {
+ const oldValue = existingRef.deref();
+ if (oldValue !== undefined) {
+ this.#registry.unregister(oldValue);
+ }
+ }
+
+ this.#map.set(key, new WeakRef(value));
+ this.#registry.register(value, key, value);
+ return this;
+ }
+
+ /**
+ * Checks if a key exists and its value is still alive.
+ *
+ * @param {K} key - The key to check.
+ * @returns {boolean} True if the key exists and its value hasn't been
+ * garbage collected.
+ */
+ has(key) {
+ return this.get(key) !== undefined;
+ }
+
+ /**
+ * Deletes an entry by key.
+ *
+ * @param {K} key - The key to delete.
+ * @returns {boolean} True if an entry was deleted.
+ */
+ delete(key) {
+ const ref = this.#map.get(key);
+ if (ref) {
+ const value = ref.deref();
+ if (value !== undefined) {
+ this.#registry.unregister(value);
+ }
+ this.#map.delete(key);
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Removes all entries from the map.
+ */
+ clear() {
+ for (const ref of this.#map.values()) {
+ const value = ref.deref();
+ if (value !== undefined) {
+ this.#registry.unregister(value);
+ }
+ }
+ this.#map.clear();
+ }
+
+ /**
+ * Returns an iterator over the keys in the map. Keys whose values have
+ * been garbage collected are skipped and cleaned up.
+ *
+ * @returns {Generator<K>}
+ */
+ *keys() {
+ for (const [key, ref] of this.#map) {
+ const value = ref.deref();
+ if (value !== undefined) {
+ yield key;
+ } else {
+ this.#map.delete(key);
+ }
+ }
+ }
+
+ /**
+ * Returns an iterator over the values in the map. Entries whose values
+ * have been garbage collected are skipped and cleaned up.
+ *
+ * @returns {Generator<V>}
+ */
+ *values() {
+ for (const [key, ref] of this.#map) {
+ const value = ref.deref();
+ if (value !== undefined) {
+ yield value;
+ } else {
+ this.#map.delete(key);
+ }
+ }
+ }
+
+ /**
+ * Returns an iterator over [key, value] pairs in the map. Entries whose
+ * values have been garbage collected are skipped and cleaned up.
+ *
+ * @returns {Generator<[K, V]>}
+ */
+ *entries() {
+ for (const [key, ref] of this.#map) {
+ const value = ref.deref();
+ if (value !== undefined) {
+ yield [key, value];
+ } else {
+ this.#map.delete(key);
+ }
+ }
+ }
+
+ /**
+ * Executes a callback for each live entry in the map.
+ *
+ * @param {(value: V, key: K, map: WeakValueMap<K, V>) => void} callback -
+ * The function to execute for each entry.
+ * @param {*} [thisArg] - Value to use as `this` when executing the callback.
+ */
+ forEach(callback, thisArg) {
+ for (const [key, value] of this) {
+ callback.call(thisArg, value, key, this);
+ }
+ }
+
+ /**
+ * Returns an iterator over [key, value] pairs, same as entries().
+ *
+ * @returns {Generator<[K, V]>}
+ */
+ [Symbol.iterator]() {
+ return this.entries();
+ }
+
+ /**
+ * Returns the string tag for the object, used by Object.prototype.toString().
+ *
+ * @returns {string}
+ */
+ get [Symbol.toStringTag]() {
+ return "WeakValueMap";
+ }
+}
+
+export default WeakValueMap;
diff --git a/frontend/discourse/app/services/store.js b/frontend/discourse/app/services/store.js
index 5eecc3eae42..a34759b621d 100644
--- a/frontend/discourse/app/services/store.js
+++ b/frontend/discourse/app/services/store.js
@@ -7,50 +7,44 @@ import { Promise } from "rsvp";
import { ajax } from "discourse/lib/ajax";
import { getRegister } from "discourse/lib/get-owner";
import { cleanNullQueryParams } from "discourse/lib/utilities";
+import WeakValueMap from "discourse/lib/weak-value-map";
import RestModel from "discourse/models/rest";
import ResultSet from "discourse/models/result-set";
-let _identityMap;
+let _identityMap = new Map();
+
+function getTypeMap(type) {
+ let typeMap = _identityMap.get(type);
+ if (!typeMap) {
+ typeMap = new WeakValueMap();
+ _identityMap.set(type, typeMap);
+ }
+ return typeMap;
+}
// You should only call this if you're a test scaffold
function flushMap() {
- _identityMap = {};
+ for (const typeMap of _identityMap.values()) {
+ typeMap.clear();
+ }
+ _identityMap.clear();
}
function storeMap(type, id, obj) {
if (!id) {
return;
}
-
- _identityMap[type] = _identityMap[type] || {};
- _identityMap[type][id] = obj;
+ getTypeMap(type).set(id, obj);
}
function fromMap(type, id) {
- const byType = _identityMap[type];
- if (byType && byType.hasOwnProperty(id)) {
- return byType[id];
- }
+ return _identityMap.get(type)?.get(id);
}
function removeMap(type, id) {
- const byType = _identityMap[type];
- if (byType && byType.hasOwnProperty(id)) {
- delete byType[id];
- }
+ _identityMap.get(type)?.delete(id);
}
-function findAndRemoveMap(type, id) {
- const byType = _identityMap[type];
- if (byType && byType.hasOwnProperty(id)) {
- const result = byType[id];
- delete byType[id];
- return result;
- }
-}
-
-flushMap();
-
export default class StoreService extends Service {
_plurals = {
category: "categories",
@@ -222,7 +216,8 @@ export default class StoreService extends Service {
const adapter = this.adapterFor(type);
return adapter.update(this, type, id, attrs, function (result) {
if (result && result[type] && result[type][adapter.primaryKey]) {
- const oldRecord = findAndRemoveMap(type, id);
+ const oldRecord = fromMap(type, id);
+ removeMap(type, id);
storeMap(type, result[type][adapter.primaryKey], oldRecord);
}
return result;
diff --git a/frontend/discourse/tests/acceptance/topic-list-tracker-test.js b/frontend/discourse/tests/acceptance/topic-list-tracker-test.js
index 4845267c6f3..61c8c8de08b 100644
--- a/frontend/discourse/tests/acceptance/topic-list-tracker-test.js
+++ b/frontend/discourse/tests/acceptance/topic-list-tracker-test.js
@@ -28,6 +28,7 @@ acceptance("Topic list tracking", function (needs) {
fixture["topic_list"]["topics"].find((t) => {
if (t.id === 11557) {
t.notification_level = notificationLevel;
+ t.last_read_post_number = 1;
}
});
}
@@ -35,11 +36,14 @@ acceptance("Topic list tracking", function (needs) {
return helper.response(cloneJSON(fixture));
});
- server.get("/t/11557.json", () => {
+ const responseTopic11557 = () => {
const topicFixture = cloneJSON(topicFixtures["/t/130.json"]);
topicFixture.id = 11557;
return helper.response(topicFixture);
- });
+ };
+
+ server.get("/t/11557.json", responseTopic11557);
+ server.get("/t/11557/:post_number.json", responseTopic11557);
});
test("Navigation", async function (assert) {
diff --git a/frontend/discourse/tests/unit/lib/weak-value-map-test.js b/frontend/discourse/tests/unit/lib/weak-value-map-test.js
new file mode 100644
index 00000000000..0bd3e80d93e
--- /dev/null
+++ b/frontend/discourse/tests/unit/lib/weak-value-map-test.js
@@ -0,0 +1,211 @@
+import { module, test } from "qunit";
+import WeakValueMap from "discourse/lib/weak-value-map";
+
+/*
+ * NOTE: Garbage collection behavior (WeakRef/FinalizationRegistry) cannot
+ * be reliably tested since GC timing is non-deterministic. These tests
+ * cover the synchronous Map-like API behavior only.
+ */
+module("Unit | Lib | weak-value-map", function () {
+ test("set and get", function (assert) {
+ const map = new WeakValueMap();
+ const value = { id: 1 };
+
+ map.set("key1", value);
+
+ assert.strictEqual(map.get("key1"), value);
+ });
+
+ test("get returns undefined for missing keys", function (assert) {
+ const map = new WeakValueMap();
+
+ assert.strictEqual(map.get("nonexistent"), undefined);
+ });
+
+ test("has returns true for existing keys", function (assert) {
+ const map = new WeakValueMap();
+ const value = { id: 1 };
+
+ map.set("key1", value);
+
+ assert.true(map.has("key1"));
+ });
+
+ test("has returns false for missing keys", function (assert) {
+ const map = new WeakValueMap();
+
+ assert.false(map.has("nonexistent"));
+ });
+
+ test("delete removes entries", function (assert) {
+ const map = new WeakValueMap();
+ const value = { id: 1 };
+
+ map.set("key1", value);
+ const result = map.delete("key1");
+
+ assert.true(result);
+ assert.strictEqual(map.get("key1"), undefined);
+ assert.false(map.has("key1"));
+ });
+
+ test("delete returns false for missing keys", function (assert) {
+ const map = new WeakValueMap();
+
+ assert.false(map.delete("nonexistent"));
+ });
+
+ test("clear removes all entries", function (assert) {
+ const map = new WeakValueMap();
+ const value1 = { id: 1 };
+ const value2 = { id: 2 };
+
+ map.set("key1", value1);
+ map.set("key2", value2);
+ map.clear();
+
+ assert.strictEqual(map.size, 0);
+ assert.false(map.has("key1"));
+ assert.false(map.has("key2"));
+ });
+
+ test("size reflects entry count", function (assert) {
+ const map = new WeakValueMap();
+ const value1 = { id: 1 };
+ const value2 = { id: 2 };
+
+ assert.strictEqual(map.size, 0);
+
+ map.set("key1", value1);
+ assert.strictEqual(map.size, 1);
+
+ map.set("key2", value2);
+ assert.strictEqual(map.size, 2);
+
+ map.delete("key1");
+ assert.strictEqual(map.size, 1);
+ });
+
+ test("keys iterator yields all keys", function (assert) {
+ const map = new WeakValueMap();
+ const value1 = { id: 1 };
+ const value2 = { id: 2 };
+
+ map.set("key1", value1);
+ map.set("key2", value2);
+
+ const keys = [...map.keys()];
+
+ assert.deepEqual(keys.sort(), ["key1", "key2"]);
+ });
+
+ test("values iterator yields all values", function (assert) {
+ const map = new WeakValueMap();
+ const value1 = { id: 1 };
+ const value2 = { id: 2 };
+
+ map.set("key1", value1);
+ map.set("key2", value2);
+
+ const values = [...map.values()];
+
+ assert.strictEqual(values.length, 2);
+ assert.true(values.includes(value1));
+ assert.true(values.includes(value2));
+ });
+
+ test("entries iterator yields [key, value] pairs", function (assert) {
+ const map = new WeakValueMap();
+ const value1 = { id: 1 };
+ const value2 = { id: 2 };
+
+ map.set("key1", value1);
+ map.set("key2", value2);
+
+ const entries = [...map.entries()];
+
+ assert.strictEqual(entries.length, 2);
+
+ const entriesMap = new Map(entries);
+ assert.strictEqual(entriesMap.get("key1"), value1);
+ assert.strictEqual(entriesMap.get("key2"), value2);
+ });
+
+ test("forEach calls callback for each entry", function (assert) {
+ const map = new WeakValueMap();
+ const value1 = { id: 1 };
+ const value2 = { id: 2 };
+
+ map.set("key1", value1);
+ map.set("key2", value2);
+
+ const collected = [];
+ map.forEach((value, key, mapRef) => {
+ collected.push({ value, key });
+ assert.strictEqual(mapRef, map);
+ });
+
+ assert.strictEqual(collected.length, 2);
+ });
+
+ test("forEach respects thisArg", function (assert) {
+ const map = new WeakValueMap();
+ const value = { id: 1 };
+ const context = { name: "test-context" };
+
+ map.set("key1", value);
+
+ map.forEach(function () {
+ assert.strictEqual(this, context);
+ }, context);
+ });
+
+ test("Symbol.iterator works with for...of", function (assert) {
+ const map = new WeakValueMap();
+ const value1 = { id: 1 };
+ const value2 = { id: 2 };
+
+ map.set("key1", value1);
+ map.set("key2", value2);
+
+ const collected = [];
+ for (const [key, value] of map) {
+ collected.push({ key, value });
+ }
+
+ assert.strictEqual(collected.length, 2);
+ });
+
+ test("Symbol.toStringTag returns 'WeakValueMap'", function (assert) {
+ const map = new WeakValueMap();
+
+ assert.strictEqual(map[Symbol.toStringTag], "WeakValueMap");
+ assert.strictEqual(
+ Object.prototype.toString.call(map),
+ "[object WeakValueMap]"
+ );
+ });
+
+ test("set overwrites existing values", function (assert) {
+ const map = new WeakValueMap();
+ const value1 = { id: 1 };
+ const value2 = { id: 2 };
+
+ map.set("key1", value1);
+ map.set("key1", value2);
+
+ assert.strictEqual(map.get("key1"), value2);
+ assert.strictEqual(map.size, 1);
+ });
+
+ test("set returns this for chaining", function (assert) {
+ const map = new WeakValueMap();
+ const value1 = { id: 1 };
+ const value2 = { id: 2 };
+
+ const result = map.set("key1", value1).set("key2", value2);
+
+ assert.strictEqual(result, map);
+ assert.strictEqual(map.size, 2);
+ });
+});
diff --git a/package.json b/package.json
index a5bcc00320a..626e9595fc1 100644
--- a/package.json
+++ b/package.json
@@ -5,7 +5,7 @@
"license": "GPL-2.0-only",
"devDependencies": {
"@babel/plugin-proposal-decorators": "^7.28.0",
- "@discourse/lint-configs": "^2.37.0",
+ "@discourse/lint-configs": "^2.37.1",
"@discourse/moment-timezone-names-translations": "^1.0.0",
"@fortawesome/fontawesome-free": "7.1.0",
"@glint/ember-tsc": "^1.0.8",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 69c5fa282cf..66a9715511f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -35,8 +35,8 @@ importers:
specifier: ^7.28.0
version: 7.28.6(@babel/[email protected])
'@discourse/lint-configs':
- specifier: ^2.37.0
+ specifier: ^2.37.1
'@discourse/moment-timezone-names-translations':
specifier: ^1.0.0
version: 1.0.0
@@ -1720,8 +1720,8 @@ packages:
'@discourse/[email protected]':
resolution: {integrity: sha512-Jn1gdiyHMGUsmUfLFf4Q7VnTAv0l7NePbegU6pKhKHEmbzV3FosGxq30fTOYgVyTS1bxqGjlA6LvQttJpv3ROw==}
- '@discourse/[email protected]':
- resolution: {integrity: sha512-pxN22hR0VOd3TeZWvgbFDMWIKTxpLqsoUqyesCCUkrd6klZCxzgmQdDrSxojVvJOMk3VXLQM+eQ8mc1ePr2Deg==}
+ '@discourse/[email protected]':
+ resolution: {integrity: sha512-lQHRZrbLsS35T7zB7NfIPfYz9xkfDwycNADDfViygpYnUT4h8nr9Sdf6Xs+x0abD0yXTJWkrHq72d2XvwA40YA==}
peerDependencies:
ember-template-lint: 7.9.3
eslint: 9.39.2
@@ -10277,7 +10277,7 @@ snapshots:
'@discourse/[email protected]': {}
dependencies:
'@babel/core': 7.28.6([email protected])
'@babel/eslint-parser': 7.28.6(@babel/[email protected])([email protected]([email protected]))