masterrecord 1.32.1 → 1.32.2

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.
package/CHANGES.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # MasterRecord Changelog
2
2
 
3
+ ## v1.32.2 — re-reads return current data again
4
+
5
+ **Fix: since 1.32.0 a tracked re-read could answer with an old row.** 1.32.0 returned the
6
+ instance the context already tracked and didn't refresh it, so `UPDATE ... WHERE` through
7
+ `executeUpdate` followed by a read of that row, or a write from another context or process
8
+ followed by a read, answered with the values from the first read. Applications written against
9
+ 1.31 rely on that read being current: CodeBook's run claims returned the lease as it was before
10
+ the update. **Don't use 1.32.0 or 1.32.1.**
11
+
12
+ - A tracked query returns the row as the database has it now, as a new object, as it did up to
13
+ 1.31. `a === b` for two reads of one row is no longer true.
14
+ - The memory fix from 1.32.0 stays: the read releases the clean copy of that row, so a long-lived
15
+ context holds one clean copy per row, not one per read.
16
+ - An object read earlier keeps its values and still works: editing it tracks it again. An instance
17
+ with pending changes stays tracked, and a re-read doesn't touch it.
18
+
3
19
  ## v1.32.1 — batched inserts keep add order on MySQL and Postgres
4
20
 
5
21
  **Fix: `saveChanges()` could assign ids out of add order on MySQL and Postgres.** A
@@ -194,8 +194,8 @@ class EntityTrackerModel {
194
194
 
195
195
  // Fetch fresh from database
196
196
  const EntityClass = this.__context[this.__name];
197
- // No tracking: a tracked findById would return THIS instance
198
- // (identity resolution), not the database values.
197
+ // No tracking: reading the values for THIS instance must not release it
198
+ // or track a second copy.
199
199
  const fresh = await EntityClass.asNoTracking().findById(...keyValues);
200
200
  if (!fresh) {
201
201
  throw new Error(
@@ -325,10 +325,10 @@ class queryMethods{
325
325
  }
326
326
 
327
327
  /**
328
- * Can this query's rows be identity-resolved? Only when each row is a whole
329
- * entity row: not raw() SQL, not a select() projection (a partial row must
330
- * not stand in for the entity later), and not a full-text search (each row
331
- * carries a per-query __rank).
328
+ * Do this query's rows replace the context's clean copy of the row? Only when
329
+ * each row is a whole entity row: not raw() SQL, not a select() projection (a
330
+ * partial row must not replace the entity), and not a full-text search (each
331
+ * row carries a per-query __rank).
332
332
  */
333
333
  __identityResolvable(){
334
334
  const s = this.__queryObject.script;
@@ -347,13 +347,11 @@ class queryMethods{
347
347
  const derived = tph.derived.get(String(dataModel[tph.column]));
348
348
  if (derived) def = derived;
349
349
  }
350
- // Identity resolution (EF Core): if this context already tracks the
351
- // row, return that instance. It is NOT refreshed from the row, so
352
- // pending changes on it are kept.
353
- if (resolvable) {
354
- const tracked = $that.__context.__trackedForRow(def, dataModel);
355
- if (tracked) return tracked;
356
- }
350
+ // A query returns the row as the database has it now, as a new object.
351
+ // The clean copy this read replaces is released, so a context holds one
352
+ // clean copy per row however often it re-reads (memory follows the rows,
353
+ // not the reads). An instance with pending changes stays tracked.
354
+ if (resolvable) $that.__context.__releaseCleanCopy(def, dataModel);
357
355
  const ent = new entityTrackerModel();
358
356
  const mod = ent.build(dataModel, def, $that.__context);
359
357
  mod.__state = "track";
@@ -1424,8 +1422,8 @@ class queryMethods{
1424
1422
 
1425
1423
  // Fetch fresh from database
1426
1424
  const EntityClass = this.__context[this.__name];
1427
- // No tracking: a tracked findById would return THIS instance
1428
- // (identity resolution), not the database values.
1425
+ // No tracking: reading the values for THIS instance must not release it
1426
+ // or track a second copy.
1429
1427
  const fresh = await EntityClass.asNoTracking().findById(primaryKeyValue);
1430
1428
  if (!fresh) {
1431
1429
  throw new Error(
package/context.js CHANGED
@@ -138,13 +138,13 @@ function _poolKey(type, cfg) {
138
138
  }
139
139
 
140
140
  // ----------------------------------------------------------------------------
141
- // Identity resolution (EF Core's identity map keyed by primary key)
141
+ // One clean copy per row
142
142
  // ----------------------------------------------------------------------------
143
- // A tracked query that reads a row this context already tracks returns the
144
- // tracked instance instead of building a second copy. The key is
145
- // "<table>\0<primary key>". Without it a long-lived context that re-reads the
146
- // same rows kept a new tracked copy per read, so memory grew with the number of
147
- // reads instead of the number of distinct rows.
143
+ // A tracked query returns the row as the database has it now, as a new object,
144
+ // and releases the clean copy of that row this context already holds. Without
145
+ // this a long-lived context that re-reads the same rows kept a new tracked copy
146
+ // per read, so memory grew with the number of reads instead of the number of
147
+ // distinct rows. The key is "<table>\0<primary key>".
148
148
 
149
149
  // Entity definition -> its primary-key column names, or null when the type
150
150
  // cannot be keyed (no key, or a key column that is a navigation).
@@ -325,13 +325,15 @@ class context {
325
325
  // writes whenever the two disagreed (a stale/colliding id in one but not the
326
326
  // other). All mutations go through __track / __untrack / __clearTracked.
327
327
  __trackedEntitiesMap = new Map(); // __ID -> entity; the authority
328
- // Identity index beside the map: "<table>\0<primary key>" -> the one tracked
329
- // instance of that row, so a tracked query returns it instead of a new copy.
328
+ // Identity index beside the map: "<table>\0<primary key>" -> the tracked
329
+ // instance of that row a query's read replaces, or which has pending changes.
330
+ // __identityCopies holds the row's clean copy while an instance with pending
331
+ // changes holds the key, so that copy is released by the next read as well.
330
332
  // __identityKeys remembers which key each entity was indexed under, so it can
331
- // be removed even after its key value changed. Both are kept in step by
332
- // __track / __untrack / __clearTracked; a stale entry is also dropped when a
333
- // lookup finds it (see __trackedForRow).
333
+ // be removed even after its key value changed. All three are kept in step by
334
+ // __track / __untrack / __clearTracked.
334
335
  __identityIndex = new Map();
336
+ __identityCopies = new Map();
335
337
  __identityKeys = new WeakMap();
336
338
  // One-time "tracked set is large" warning (see __checkTrackedSize).
337
339
  __trackedWarnThreshold = undefined; // undefined = not resolved yet
@@ -2022,9 +2024,9 @@ class context {
2022
2024
  const loadedOut = [];
2023
2025
  const pending = [];
2024
2026
  // opts.run (one per query): the parents whose `nav` this query has
2025
- // already loaded. With identity resolution a query can return an
2026
- // instance whose navigation an EARLIER query loaded (with other filters);
2027
- // an explicit include() reloads it, so the result reflects this query.
2027
+ // already loaded. A query can reach an instance whose navigation an
2028
+ // EARLIER query loaded (with other filters); an explicit include()
2029
+ // reloads it, so the result reflects this query.
2028
2030
  let loadedThisRun = null;
2029
2031
  if (opts.run instanceof Map) {
2030
2032
  const runKey = `${ownerDef.__name}.${nav}`;
@@ -4372,23 +4374,22 @@ class context {
4372
4374
  this.__trackedEntitiesMap.clear(); // sole registry; the list view follows
4373
4375
  this.__dirtyEntities.clear();
4374
4376
  this.__identityIndex.clear();
4377
+ this.__identityCopies.clear();
4375
4378
  this.__identityKeys = new WeakMap();
4376
4379
  }
4377
4380
 
4378
- // ---- Identity resolution ------------------------------------------------
4381
+ // ---- One clean copy per row ----------------------------------------------
4379
4382
 
4380
4383
  /**
4381
- * Index a tracked entity under its type + primary key, so a later tracked
4382
- * query that reads the same row returns this instance. Called from
4383
- * __track(). An entity with no usable key yet (a pending insert with an
4384
- * auto key) is skipped, and indexed once its key is assigned.
4384
+ * Index a tracked entity under its type + primary key, so the next tracked
4385
+ * query that reads the same row can release it. Called from __track(). An
4386
+ * entity with no usable key yet (a pending insert with an auto key) is
4387
+ * skipped, and indexed once its key is assigned.
4385
4388
  *
4386
- * A context can still end up tracking two instances of one row: saved
4387
- * entities are detached, and a later edit re-tracks the old instance while a
4388
- * newer query copy is tracked. Then the instance with pending changes takes
4389
- * the key from a clean holder, so once it is saved (and detached) the next
4390
- * query reads the row afresh instead of returning the stale clean copy.
4391
- * Otherwise the instance that already holds the key keeps it.
4389
+ * A context can track two instances of one row: an instance a read replaced
4390
+ * or a save detached re-tracks itself when it is edited. Then the instance
4391
+ * with pending changes holds the key and the clean copy moves to
4392
+ * __identityCopies. Neither is lost, and the next read releases the clean one.
4392
4393
  * @private
4393
4394
  */
4394
4395
  __indexIdentity(model) {
@@ -4402,9 +4403,16 @@ class context {
4402
4403
  const holder = this.__identityIndex.get(key);
4403
4404
  if (holder !== undefined && holder !== model && this.__isLiveIdentity(holder, key)) {
4404
4405
  const modelDirty = context._isEntityDirty(model);
4405
- if (!modelDirty || context._isEntityDirty(holder)) return;
4406
- this.__identityKeys.delete(holder); // the clean copy stays tracked, unindexed
4406
+ if (!modelDirty) {
4407
+ if (!context._isEntityDirty(holder)) return;
4408
+ this.__identityCopies.set(key, model); // a clean copy beside pending changes
4409
+ this.__identityKeys.set(model, key);
4410
+ return;
4411
+ }
4412
+ if (context._isEntityDirty(holder)) return;
4413
+ this.__identityCopies.set(key, holder); // the clean copy stays tracked
4407
4414
  }
4415
+ if (this.__identityCopies.get(key) === model) this.__identityCopies.delete(key);
4408
4416
  this.__identityIndex.set(key, model);
4409
4417
  this.__identityKeys.set(model, key);
4410
4418
  }
@@ -4414,8 +4422,16 @@ class context {
4414
4422
  if (!model || typeof model !== 'object') return;
4415
4423
  const key = this.__identityKeys.get(model);
4416
4424
  if (key === undefined) return;
4417
- if (this.__identityIndex.get(key) === model) this.__identityIndex.delete(key);
4418
4425
  this.__identityKeys.delete(model);
4426
+ if (this.__identityCopies.get(key) === model) this.__identityCopies.delete(key);
4427
+ if (this.__identityIndex.get(key) === model) {
4428
+ this.__identityIndex.delete(key);
4429
+ // The clean copy beside it went stale when this instance was saved or
4430
+ // detached; nothing would ever read it from here (a deleted row is
4431
+ // never read again), so it goes too.
4432
+ const copy = this.__identityCopies.get(key);
4433
+ if (copy !== undefined && !context._isEntityDirty(copy)) this.__untrack([copy]);
4434
+ }
4419
4435
  }
4420
4436
 
4421
4437
  /** Is `e` still tracked here and does its current key still equal `key`? @private */
@@ -4427,28 +4443,29 @@ class context {
4427
4443
  }
4428
4444
 
4429
4445
  /**
4430
- * The tracked instance of the row `row` (a raw database row of `def`), or
4431
- * null. Used by tracked queries before they build a new entity. The tracked
4432
- * instance is returned as is: database values do not overwrite it, and a
4433
- * modified instance keeps its pending changes (EF Core identity resolution).
4446
+ * A tracked query is about to build a new entity from `row` (a raw database row
4447
+ * of `def`): stop tracking the clean copies of that row. An older instance a
4448
+ * caller still holds keeps working: editing it tracks it again. An instance
4449
+ * with pending changes (modified, pending delete or insert) stays tracked and
4450
+ * is saved as usual.
4434
4451
  * @private
4435
4452
  */
4436
- __trackedForRow(def, row) {
4437
- if (this.__identityIndex.size === 0 || !row) return null;
4453
+ __releaseCleanCopy(def, row) {
4454
+ if (!row || (this.__identityIndex.size === 0 && this.__identityCopies.size === 0)) return;
4438
4455
  let key;
4439
4456
  try {
4440
4457
  key = _identityKey(def, (c) => FieldTransformer.fromDatabase(row[c], def[c], def.__name, c));
4441
4458
  } catch (_) {
4442
- return null; // a failing transformer: let the normal build path report it
4443
- }
4444
- if (key === null) return null;
4445
- const e = this.__identityIndex.get(key);
4446
- if (e === undefined) return null;
4447
- if (this.__isLiveIdentity(e, key)) return e;
4448
- // Stale entry (detached elsewhere, or its key changed): drop it.
4449
- this.__identityIndex.delete(key);
4450
- this.__identityKeys.delete(e);
4451
- return null;
4459
+ return; // a failing transformer: let the normal build path report it
4460
+ }
4461
+ if (key === null) return;
4462
+ const holder = this.__identityIndex.get(key);
4463
+ const copy = this.__identityCopies.get(key);
4464
+ for (const e of [holder, copy]) {
4465
+ if (e === undefined) continue;
4466
+ if (!this.__isLiveIdentity(e, key)) this.__unindexIdentity(e); // detached elsewhere, or its key changed
4467
+ else if (!context._isEntityDirty(e)) this.__untrack([e]);
4468
+ }
4452
4469
  }
4453
4470
 
4454
4471
  /**
@@ -4502,8 +4519,8 @@ class context {
4502
4519
  *
4503
4520
  * A context is a unit of work and is safest scoped per request. If you must
4504
4521
  * reuse a long-lived (e.g. singleton) context, read-only queries still
4505
- * auto-track their results: one instance per distinct row (identity
4506
- * resolution), which still grows with every new row read — call this
4522
+ * auto-track their results: one clean copy per distinct row, which still
4523
+ * grows with every new row read — call this
4507
4524
  * after a read-only operation to release them and keep the tracked set
4508
4525
  * bounded. It drops PENDING changes too, so only call it when there is
4509
4526
  * nothing dirty you still intend to save.
@@ -19,24 +19,27 @@ user.blocked = 1; // dirty
19
19
  await db.saveChanges(); // one UPDATE
20
20
  ```
21
21
 
22
- ### Identity resolution (since 1.32.0)
22
+ ### Re-reads: current data, one clean copy per row (since 1.32.2)
23
23
 
24
- A context tracks **one instance per row**. When a tracked query reads a row the context already tracks (same entity type and primary key, composite keys included), it returns the tracked instance instead of building a new one, as EF Core does:
24
+ A tracked query returns the row **as the database has it now, as a new object**. It releases the clean copy of that row the context already holds (same entity type and primary key, composite keys included).
25
25
 
26
- - The tracked instance is **not** overwritten with the database values. Pending changes on it survive a re-read; unchanged columns keep the values they had when the row was first loaded. Use `asNoTracking()`, `entry(e).getDatabaseValues()` or `reload()` to see the current row.
26
+ - A read sees writes made any other way: `executeUpdate`, another context, another process.
27
27
  - A long-lived context's memory is bounded by the number of **distinct** rows it has loaded, not by how many times it re-reads them.
28
- - An explicit `include()` still loads the navigation for every row the query returns, including instances an earlier query loaded.
29
- - `select()` projections, `raw()` SQL and full-text `search()` rows are tracked as before but never identity-resolved: a partial row never stands in for the whole entity.
28
+ - An object you read earlier keeps the values it read. It still works: editing it tracks it again, and `saveChanges()` writes the change.
29
+ - An instance with pending changes (modified, or pending delete or insert) stays tracked, and a re-read does not touch it. The read answers with the database row until you save.
30
+ - `select()` projections, `raw()` SQL and full-text `search()` rows are tracked as before and do not replace the whole entity.
30
31
 
31
32
  ```javascript
32
33
  const a = await db.User.findById(1);
33
34
  a.name = 'pending';
34
35
  const b = await db.User.where('u => u.id == $$', 1).single();
35
- b === a; // true
36
- b.name; // 'pending': the re-read did not overwrite it
36
+ b === a; // false
37
+ b.name; // the database value: 'pending' is not saved yet
38
+ a.name; // 'pending'
39
+ await db.saveChanges(); // writes a's change
37
40
  ```
38
41
 
39
- ---
42
+ 1.32.0 and 1.32.1 returned the tracked instance without refreshing it. A read after `executeUpdate` or a write from another context answered with the old row. Don't use those two versions.
40
43
 
41
44
  ## Controlling what gets tracked (EF's `QueryTrackingBehavior`)
42
45
 
@@ -268,7 +271,7 @@ Transient errors (deadlocks, lock timeouts, busy SQLite, dropped connections) ar
268
271
  A singleton context shared across concurrent requests is the root cause of an entire class of bugs (and is unsupported in EF for the same reasons):
269
272
 
270
273
  - **Lost writes** — one request's `saveChanges()` interacting with another's tracked entities.
271
- - **Unbounded memory** — read-only queries track results that are never released. Identity resolution bounds this by the number of distinct rows, but a singleton that reads a large or growing table still keeps every row it has seen.
274
+ - **Unbounded memory** — read-only queries track results that are never released. One clean copy per row bounds this by the number of distinct rows, but a singleton that reads a large or growing table still keeps every row it has seen.
272
275
  - **Undefined behavior** under concurrent access (EF: "application crashes and data corruption").
273
276
 
274
277
  MasterRecord hardens against the worst symptoms (each save commits only its own change set; identities are collision-free; the dirty index is complete), but the correct and supported model is a **per-request context** — pooled if you need to amortize setup.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "masterrecord",
3
- "version": "1.32.1",
3
+ "version": "1.32.2",
4
4
  "description": "An Object-relational mapping for the Master framework. Master Record connects classes to relational database tables to establish a database with almost zero-configuration ",
5
5
  "type": "module",
6
6
  "main": "./MasterRecord.js",