@pretty-chitty/core 2.3.3 → 2.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,5 @@
1
+ import v8 from "node:v8";
2
+ import vm from "node:vm";
1
3
  import { expect, test } from "vitest";
2
4
 
3
5
  import { ChildOutlet, NonEditable } from "../utilities/Annotations";
@@ -155,3 +157,51 @@ test("dirty tracking: array mutation via proxy marks dirty", () => {
155
157
  const serialized = c.serialize();
156
158
  expect(JSON.parse(serialized).items).toEqual([1, 2, 3, 4]);
157
159
  });
160
+
161
+ test("dirty tracking: an object two chits share marks the chit it was written through", () => {
162
+ const shared = { a: 1 };
163
+ class ChitWithShared extends Chit {
164
+ public data = shared;
165
+ }
166
+
167
+ const c1 = new ChitWithShared();
168
+ const c2 = new ChitWithShared();
169
+ c1.serialize();
170
+ c2.serialize();
171
+ expect(c1.data.a).toBe(1); // c1 wraps the shared object first
172
+
173
+ c2.data.a = 2;
174
+ expect(c2._dirty).toBe(true);
175
+ expect(c1._dirty).toBe(false);
176
+ });
177
+
178
+ test("dirty tracking: a chit that read long-lived data can still be collected", async () => {
179
+ // Game data in module scope lives as long as the bundle. Reading it through a chit must not tie
180
+ // the chit (and through its parents, a whole disposed match) to that data.
181
+ const gc = exposeGc();
182
+ const staticData = { nested: { value: 1 } };
183
+ class ChitWithStatic extends Chit {
184
+ public data = staticData;
185
+ }
186
+
187
+ let ref: WeakRef<Chit> | undefined;
188
+ (() => {
189
+ const c = new ChitWithStatic();
190
+ c.serialize();
191
+ expect(c.data.nested.value).toBe(1);
192
+ ref = new WeakRef(c);
193
+ })();
194
+
195
+ // WeakRef targets stay alive until the current job ends
196
+ for (let i = 0; i < 5; i++) {
197
+ await new Promise((resolve) => setTimeout(resolve, 10));
198
+ gc();
199
+ }
200
+ expect(ref?.deref()).toBeUndefined();
201
+ });
202
+
203
+ /** V8's gc(), without needing --expose-gc on the command line. */
204
+ function exposeGc(): () => void {
205
+ v8.setFlagsFromString("--expose-gc");
206
+ return vm.runInNewContext("gc") as () => void;
207
+ }
@@ -18,14 +18,24 @@ const EXTRA_SERIALIZATION_PROPS_ARRAY = ["id", "_parent", "_parentOutlet", "_par
18
18
  const EXTRA_SERIALIZATION_PROPS_SET = new Set(EXTRA_SERIALIZATION_PROPS_ARRAY);
19
19
  const DELETED_SERIALIZED = JSON.stringify({ ____deleted: true });
20
20
 
21
- const dirtyProxyCache = new WeakMap<object, object>();
21
+ // Per chit: value -> the proxy that marks that chit dirty. A proxy is bound to one chit, so the cache
22
+ // must be too. Keyed by value alone, an object several chits share (often static game data, which
23
+ // lives as long as the bundle) got the first chit's proxy for good: writes through it marked the
24
+ // wrong chit dirty, and the entry, whose key never dies, kept that chit and its whole match alive
25
+ // after the match was disposed. Keyed by chit, a chit's proxies go when the chit does.
26
+ const dirtyProxyCache = new WeakMap<Chit, WeakMap<object, object>>();
22
27
 
23
28
  function wrapWithDirtyProxy(value: any, chit: Chit): any {
24
29
  if (value === null || value === undefined) return value;
25
30
  if (typeof value !== "object") return value;
26
31
  if (value instanceof Chit || value instanceof OrderedOutlet) return value;
27
32
 
28
- const existing = dirtyProxyCache.get(value);
33
+ let chitProxies = dirtyProxyCache.get(chit);
34
+ if (!chitProxies) {
35
+ chitProxies = new WeakMap();
36
+ dirtyProxyCache.set(chit, chitProxies);
37
+ }
38
+ const existing = chitProxies.get(value);
29
39
  if (existing) return existing;
30
40
 
31
41
  const proxy = new Proxy(value, {
@@ -53,7 +63,7 @@ function wrapWithDirtyProxy(value: any, chit: Chit): any {
53
63
  },
54
64
  });
55
65
 
56
- dirtyProxyCache.set(value, proxy);
66
+ chitProxies.set(value, proxy);
57
67
  return proxy;
58
68
  }
59
69
 
@@ -233,8 +233,20 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
233
233
  return p.id;
234
234
  });
235
235
 
236
- // now serialize all chits in their "locked" state. createTurn flushes the parent right before
237
- // building us, so a clean chit's state there is already current and interned.
236
+ this.captureLockedStates();
237
+ }
238
+
239
+ /**
240
+ * Serializes every locked chit in its "locked" state. createTurn flushes the parent right before
241
+ * building us, so a clean chit's state there is already current and interned.
242
+ *
243
+ * This must stay out of the constructor. A local captured by a callback there lives in the
244
+ * constructor's closure context, which every closure made in the constructor shares, including
245
+ * the `findChit` field. `findChit` outlives the turn's absorption, so the parent's full chit-state
246
+ * map (a fresh copy per absorbed sub-turn) would stay pinned by every finished turn: tens of MB
247
+ * in a long game, out of reach of releasePostAbsorptionRefs.
248
+ */
249
+ private captureLockedStates() {
238
250
  const parentStates = this.parent?.lastChitStates;
239
251
  Object.values(this.chitLookup).forEach((c) => {
240
252
  if (!c.id) {
@@ -1,3 +1,5 @@
1
+ import v8 from "node:v8";
2
+ import vm from "node:vm";
1
3
  import { describe, expect, test } from "vitest";
2
4
 
3
5
  import { Chit } from "./Chit";
@@ -100,6 +102,7 @@ type AnyTurn = {
100
102
  clockSteps: { turns?: AnyTurn[]; absorbed?: AnyTurn[] }[];
101
103
  _checkpoints: { nextIndex: number }[];
102
104
  lockedChitStates: Record<string, string>;
105
+ lastChitStates: Record<string, string>;
103
106
  absorbed: boolean;
104
107
  serialize: (playerId: string, clock: number) => { chits: Record<string, string> };
105
108
  chitsHistory: (playerId: string, ids: string[]) => unknown;
@@ -272,4 +275,40 @@ describe("Turn.serialize", () => {
272
275
  expect(finished.filter((t) => t._checkpoints.length > 0)).toEqual([]);
273
276
  expect(Object.keys(root.lockedChitStates).length).toBeGreaterThan(0);
274
277
  });
278
+
279
+ test("finished turns do not keep old chit-state maps alive", async () => {
280
+ // A turn absorbing a sub-turn replaces its lastChitStates with a fresh full copy, so a long game
281
+ // makes hundreds of them. Once replaced, nothing should hold one: in particular not a closure
282
+ // made in the Turn constructor (findChit), which every finished turn keeps for the whole game.
283
+ const gc = exposeGc();
284
+ const seen = new WeakSet<object>();
285
+ const maps: WeakRef<object>[] = [];
286
+ const root = await play((root) => {
287
+ for (const t of allTurns(root)) {
288
+ if (!seen.has(t.lastChitStates)) {
289
+ seen.add(t.lastChitStates);
290
+ maps.push(new WeakRef(t.lastChitStates));
291
+ }
292
+ }
293
+ });
294
+ expect(maps.length).toBeGreaterThan(10);
295
+
296
+ // WeakRef targets stay alive until the current job ends, and the finished match may still have
297
+ // a notify or two queued: let those run, then collect, a few times over
298
+ for (let i = 0; i < 5; i++) {
299
+ await new Promise((resolve) => setTimeout(resolve, 10));
300
+ gc();
301
+ }
302
+
303
+ // The root (and through it every finished turn) is still alive, as in a running match
304
+ const current = new Set<object>(allTurns(root).map((t) => t.lastChitStates));
305
+ const leaked = maps.map((r) => r.deref()).filter((m) => m !== undefined && !current.has(m));
306
+ expect(`${leaked.length} of ${maps.length} replaced maps still alive`).toBe(`0 of ${maps.length} replaced maps still alive`);
307
+ });
275
308
  });
309
+
310
+ /** V8's gc(), without needing --expose-gc on the command line. */
311
+ function exposeGc(): () => void {
312
+ v8.setFlagsFromString("--expose-gc");
313
+ return vm.runInNewContext("gc") as () => void;
314
+ }
@@ -84,6 +84,7 @@ export class CanvasStack implements IUpdatingCanvas {
84
84
  }
85
85
 
86
86
  this._outlets = {};
87
+ this._fontsUsed.clear();
87
88
  this.context.clearRect(0, 0, this.width, this.height);
88
89
  this.operation.render(
89
90
  this.context,
@@ -93,6 +94,7 @@ export class CanvasStack implements IUpdatingCanvas {
93
94
  this._outlets[id] = coords;
94
95
  },
95
96
  );
97
+ this._noteUnloadedFonts();
96
98
  this._renderMipCanvases();
97
99
  this.cbs.forEach((cb) => cb());
98
100
  }
@@ -132,6 +134,7 @@ export class CanvasStack implements IUpdatingCanvas {
132
134
  throw "Invalid Context";
133
135
  }
134
136
  this.context = context;
137
+ this._trackFonts(context);
135
138
 
136
139
  CanvasStack._liveStacks.add(this);
137
140
  CanvasStack.ensureContextRestoreSubscription();
@@ -145,6 +148,81 @@ export class CanvasStack implements IUpdatingCanvas {
145
148
  return this.operation.benefitsFromMipMap() ? 2 : 0;
146
149
  }
147
150
 
151
+ // Webfonts load lazily, so a face drawn before its font arrives is rasterised in the fallback font, and nothing
152
+ // redrew it. Its custom mips, built a second or more later, came out in the real font, and trilinear filtering
153
+ // blended the two layouts into doubled, ghosted text. So each stack records the fonts it measured or drew with;
154
+ // any not loaded yet get loaded, and when one arrives every stack that used it redraws (base and custom mips) and
155
+ // re-uploads its texture, a few per frame.
156
+ private _fontsUsed = new Set<string>();
157
+ private _unloadedFonts = new Set<string>();
158
+ private static _fontLoads = new Set<string>();
159
+ private static _pendingFontRedraws = new Set<CanvasStack>();
160
+ private static _fontRedrawScheduled = false;
161
+
162
+ private _trackFonts(ctx: CanvasRenderingContext2D) {
163
+ for (const name of ["fillText", "strokeText", "measureText"] as const) {
164
+ const original = ctx[name] as (...args: unknown[]) => unknown;
165
+ (ctx as any)[name] = (...args: unknown[]) => {
166
+ this._fontsUsed.add(ctx.font);
167
+ return original.apply(ctx, args);
168
+ };
169
+ }
170
+ }
171
+
172
+ private _noteUnloadedFonts() {
173
+ this._unloadedFonts.clear();
174
+ const fonts = typeof document !== "undefined" ? document.fonts : undefined;
175
+ if (!fonts) return;
176
+ for (const font of this._fontsUsed) {
177
+ if (fonts.check(font)) continue;
178
+ this._unloadedFonts.add(font);
179
+ CanvasStack.whenFontLoads(font);
180
+ }
181
+ }
182
+
183
+ /** A font this stack drew with before it loaded has loaded since: its pixels are stale. */
184
+ private _fontsArrived(): boolean {
185
+ for (const font of this._unloadedFonts) if (document.fonts.check(font)) return true;
186
+ return false;
187
+ }
188
+
189
+ private static whenFontLoads(font: string) {
190
+ if (CanvasStack._fontLoads.has(font)) return; // once per font: a font that never loads doesn't loop
191
+ CanvasStack._fontLoads.add(font);
192
+ document.fonts.load(font).then(
193
+ () => {
194
+ for (const stack of CanvasStack._liveStacks) {
195
+ if (stack._unloadedFonts.has(font)) CanvasStack._pendingFontRedraws.add(stack);
196
+ }
197
+ if (CanvasStack._pendingFontRedraws.size > 0 && !CanvasStack._fontRedrawScheduled) {
198
+ CanvasStack._fontRedrawScheduled = true;
199
+ requestAnimationFrame(CanvasStack.redrawPendingFonts);
200
+ }
201
+ },
202
+ () => {},
203
+ );
204
+ }
205
+
206
+ private static redrawPendingFonts = () => {
207
+ const start = performance.now();
208
+ for (const stack of CanvasStack._pendingFontRedraws) {
209
+ CanvasStack._pendingFontRedraws.delete(stack);
210
+ stack._redrawForFonts();
211
+ if (performance.now() - start > CanvasStack.MIP_FRAME_BUDGET_MS) break;
212
+ }
213
+ if (CanvasStack._pendingFontRedraws.size > 0) requestAnimationFrame(CanvasStack.redrawPendingFonts);
214
+ else CanvasStack._fontRedrawScheduled = false;
215
+ };
216
+
217
+ private _redrawForFonts() {
218
+ if (!this.context) return;
219
+ this.render(); // redraws the custom mips too, when they're built
220
+ if (this._texture) {
221
+ this._texture.needsUpdate = true;
222
+ CanvasStack.disposer.notifyChange(this._texture.uuid);
223
+ }
224
+ }
225
+
148
226
  // Faces with text get hand-drawn mip levels: text rasterised at the small size is sharper than GPU box-filtering.
149
227
  // Building that chain (a canvas per level, down to 1×1) for every face while the table loads is what stalled
150
228
  // phones — Safari queues 2D drawing in its GPU process and the first texture upload waits for all of it (8 s on an
@@ -182,6 +260,9 @@ export class CanvasStack implements IUpdatingCanvas {
182
260
 
183
261
  private _buildMips() {
184
262
  this._initMipCanvases();
263
+ // the base was drawn in a fallback font that has loaded since: redraw it (and these mips) in the real one,
264
+ // or the chain would hold two different layouts
265
+ if (this._fontsArrived()) this.render();
185
266
  if (this._texture) {
186
267
  this._applyMipmaps(this._texture);
187
268
  this._texture.needsUpdate = true;
@@ -290,6 +371,10 @@ export class CanvasStack implements IUpdatingCanvas {
290
371
  }
291
372
 
292
373
  if (!this._texture) {
374
+ // Rebuilt after the disposer reclaimed it: the disposer also dropped the stack from the live set, so a font
375
+ // that arrived meanwhile never redrew it. Redraw now, and rejoin the live set for later fonts and context loss.
376
+ if (this._fontsArrived()) this.render();
377
+ CanvasStack._liveStacks.add(this);
293
378
  const wrapper = getWebGlRendererInstance();
294
379
  this._texture = new Texture(
295
380
  this.canvas,