masterrecord 1.5.10 → 1.5.12

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,31 @@
1
1
  # MasterRecord Changelog
2
2
 
3
+ ## v1.5.12 — collision-free tracking identity + single source of truth (THE write-loss root cause)
4
+
5
+ **Bug (silent write loss with monotonic decay — the one behind 1.5.8→1.5.11):** queried entities were assigned a **random `__ID` in `[1, 100000]`** (`entityTrackerModel.buildObject`). Added entities used a collision-free sequential id, but read-only `.toList()` results used random ones. In a long-lived, read-heavy singleton context the tracked set grows toward tens of thousands, and by the birthday paradox a new entity's random `__ID` increasingly collides with one already in the identity map. `__track()` dedups by id (`if (!map.has(id))`), so the colliding entity was **never added to the tracked set** — `changeSet` never saw it, its INSERT/UPDATE was never issued, and `saveChanges()` still returned `true`. This is exactly why the library **passed in isolation** (small set, no collisions) but **decayed over a server's lifetime** (22/22 fresh → 16/22 → 14/22 as the set filled), with no exception, no rollback, and nothing between the SELECT and the missing UPDATE in the SQL log. Proven: 3000 queried rows → 52 dropped by collision, and a dropped entity's write is lost.
6
+
7
+ **Fix:**
8
+ 1. **Collision-free identity** — `buildObject` no longer assigns a random id; every entity (queried or added) gets a process-unique sequential id in `__track`. No collisions, so no entity is ever silently dropped from tracking.
9
+ 2. **Single source of truth** — the identity map (`__ID → entity`) is now the sole registry; `__trackedEntities` is a **derived read-only view** over it (`get __trackedEntities()`), so the list and the map can never desynchronise. `__track`/`__untrack`/`__clearTracked`/`attach` mutate only the map. This structurally guarantees the invariant "the tracked list and the map are the same set at all times," and `changeSet` iterates the map directly (no O(N) list materialization for read-heavy contexts).
10
+
11
+ **Also:** relaxed `engines.node` from `>=22.12.0` back to `>=20.0.0`. The `better-sqlite3` dependency range already allows 12.x (Node-20 compatible), so the hard 22.12 floor only produced spurious `EBADENGINE` warnings on Node 20; the library code runs on Node 20+.
12
+
13
+ New tests: `test/tracking-identity-unique.test.js` — 3000 queried entities get unique ids with zero collisions and the derived list equals the map; and 40 load→mutate→save cycles against a large tracked set lose zero writes (no decay). Full suite green (0 fail, 304 pass, 20 gated skipped); 0 lint errors.
14
+
15
+ ## v1.5.11 — deletes are released after commit (fix 1.5.10 "zombie delete" latch); lifecycle reconciliation centralized
16
+
17
+ **Regression fixed (introduced in 1.5.10):** 1.5.10 released a flushed entity only if its state was back to `'track'`. Inserts and updates are reset to `'track'` by the batch processors, but a **delete stays in state `'delete'`** after `_processBatchDeletes`, so it failed the release check and was **never untracked**. Each deleted entity then became a permanent "zombie" in the change set: every later `saveChanges()` re-included it and **re-issued its DELETE** (hundreds of redundant deletes), the cross-context "unsaved changes" warning fired forever and grew, and — because the unit of work was permanently non-empty and stuck — **real writes stopped persisting after a round or two** (an admin block/unblock UPDATE and session revocation both silently failed). No exception, no rollback.
18
+
19
+ **Root cause (design):** entity-lifecycle transitions were **scattered** across three batch processors plus a release filter, and the delete path had no reset — an asymmetry that made the gap inevitable.
20
+
21
+ **Fix (Unit-of-Work reconciliation, one place, one rule):** `saveChanges()` now captures each committed entity's mutation **generation** at flush time and, after the transaction commits, runs a single `_reconcileFlushed()` step with one uniform rule for insert/update/delete:
22
+ - **re-mutated in flight** (generation changed) → leave it in its new pending state so the next save persists it;
23
+ - **otherwise committed cleanly** → insert/modified reset to `'track'` then **detached**; delete **detached** (the row is gone).
24
+
25
+ The per-processor state resets were removed, so there is no longer any state-specific branch that can strand an entity. This also fixes the falsy-`__state` edge and corrects the stale `__untrack` doc comment.
26
+
27
+ New tests: `test/delete-release-no-zombie.test.js` — a committed delete is detached (no replay); repeated update-then-delete does not latch (UPDATEs keep persisting); a mixed insert+update+delete change set reconciles all three. Full suite green (0 fail, 302 pass, 20 gated skipped); 0 lint errors.
28
+
3
29
  ## v1.5.10 — saveChanges() is a proper unit of work: commits only its change set (real shared-context lost-write fix)
4
30
 
5
31
  **Bug (silent lost write, 60–75% under load):** `saveChanges()` snapshotted the **entire tracked-entity list**, and after writing untracked **all of it**. On a shared/singleton context (one instance serving many requests) this is corrupting, because queried rows are auto-tracked and read-only `.toList()` handlers leave thousands of clean entities tracked forever. So one caller's `saveChanges()` — **even an empty one with nothing dirty** — snapshotted and untracked another in-flight caller's freshly loaded/mutated row, and that caller's own `saveChanges()` then found nothing tracked and **issued no UPDATE while resolving `true`**. Frequency scaled with the size of the shared list (~43k tracked entities → 60–75% loss; ~4 entities → never). The 1.5.9 `__untrack` guard didn't catch it: the interfering save evaluated the victim's state before the pending mutation, and an empty save still snapshotted/untracked everything. Emitted no SQL of its own, so nothing appeared in the log between the SELECT and the missing UPDATE.
@@ -488,7 +488,13 @@ class EntityTrackerModel {
488
488
 
489
489
  buildObject(){
490
490
  return {
491
- __ID : Math.floor((Math.random() * 100000) + 1),
491
+ // Do NOT assign an identity here. A random __ID in [1,100000] collided
492
+ // catastrophically once the tracked set grew (birthday paradox): a new
493
+ // entity whose random __ID already existed hit __track's dedup guard,
494
+ // was never added to the tracked set, and its writes were silently
495
+ // dropped — the monotonic write-loss decay in long-lived contexts.
496
+ // __track() assigns a process-unique, collision-free sequential id.
497
+ __ID : null,
492
498
  __dirtyFields : [],
493
499
  __state : "track",
494
500
  __entity : null,
package/context.js CHANGED
@@ -216,8 +216,12 @@ class context {
216
216
  // Entity collections
217
217
  __entities = [];
218
218
  __builderEntities = [];
219
- __trackedEntities = [];
220
- __trackedEntitiesMap = new Map(); // Performance: O(1) entity lookup instead of O(n) linear search
219
+ // Change tracking has a SINGLE source of truth: the identity map
220
+ // (__ID -> entity). The tracked-entity LIST is a derived read-only view, so
221
+ // the two can never desynchronise — a dual array+map registry silently lost
222
+ // writes whenever the two disagreed (a stale/colliding id in one but not the
223
+ // other). All mutations go through __track / __untrack / __clearTracked.
224
+ __trackedEntitiesMap = new Map(); // O(1) identity lookup; the authority
221
225
  __relationshipModels = [];
222
226
  __contextSeedData = {}; // Store seed data by table name
223
227
  __contextSeedConfig = { // Seed data configuration
@@ -1868,11 +1872,6 @@ class context {
1868
1872
  }
1869
1873
  }
1870
1874
 
1871
- // Capture mutation versions before the async write so the state reset
1872
- // below skips any entity a concurrent request re-mutated in flight.
1873
- const __preWriteVersion = new Map();
1874
- for (const entity of entities) { __preWriteVersion.set(entity, entity.__version || 0); }
1875
-
1876
1875
  if (entities.length === 1) {
1877
1876
  // Single insert - use existing insertManager (already sets ID)
1878
1877
  const insert = new insertManager(this._SQLEngine, this._isModelValid, this.__entities);
@@ -1952,26 +1951,14 @@ class context {
1952
1951
  }
1953
1952
  }
1954
1953
 
1955
- // Transition inserted entities to tracked state so subsequent
1956
- // property changes trigger UPDATE instead of a second INSERT.
1957
- //
1958
- // A plain `new Model()` passed to add() has ordinary own-property
1959
- // fields, NOT the change-tracking accessors a queried entity has — so
1960
- // without this a later edit (`row.name = 'x'`) is a silent write that
1961
- // never marks the entity modified, and the change is dropped on the next
1962
- // saveChanges(). attachTrackingTo() installs those accessors in place so
1963
- // the just-inserted entity is update-trackable, exactly like one loaded
1964
- // from the database.
1954
+ // Install change-tracking accessors on each inserted entity so later
1955
+ // edits are tracked: a plain `new Model()` passed to add() has ordinary
1956
+ // own-property fields, NOT the accessors a queried entity has, so without
1957
+ // this a later `row.name = 'x'` would be a silent write. Lifecycle state
1958
+ // (insert -> clean, then detached) is transitioned centrally in
1959
+ // _reconcileFlushed after the transaction commits — not here.
1965
1960
  const tracker = new EntityTrackerModel();
1966
1961
  for (const entity of entities) {
1967
- // Only mark the just-inserted entity clean if it was not re-mutated
1968
- // during the async insert. If a concurrent request changed a field in
1969
- // flight, leave it dirty so that change is persisted as an UPDATE on
1970
- // the next save instead of being silently reset away.
1971
- if ((entity.__version || 0) === __preWriteVersion.get(entity)) {
1972
- entity.__state = 'track';
1973
- entity.__dirtyFields = [];
1974
- }
1975
1962
  try {
1976
1963
  tracker.attachTrackingTo(entity);
1977
1964
  } catch (attachErr) {
@@ -1994,13 +1981,6 @@ class context {
1994
1981
  }
1995
1982
  }
1996
1983
 
1997
- // Capture each entity's mutation version AFTER beforeSave and BEFORE the
1998
- // async write. The reset at the end uses it to skip any entity a
1999
- // concurrent request re-mutated during the write — resetting such an
2000
- // entity would clear the new dirty state and silently drop that update.
2001
- const __preWriteVersion = new Map();
2002
- for (const entity of entities) { __preWriteVersion.set(entity, entity.__version || 0); }
2003
-
2004
1984
  if (entities.length === 1) {
2005
1985
  // Single update - use existing logic.
2006
1986
  // NOTE: the second argument must be `__entity` (double underscore).
@@ -2063,18 +2043,11 @@ class context {
2063
2043
  }
2064
2044
  }
2065
2045
 
2066
- // Reset tracker state on the entity itself so a subsequent
2067
- // saveChanges() doesn't re-emit the same UPDATE for the same fields —
2068
- // but ONLY for entities that were not re-mutated during the async write.
2069
- // If a concurrent request mutated an entity after we captured its
2070
- // version, resetting it here would clear the new dirty state and its
2071
- // UPDATE would never be issued (a silent lost write on a shared context).
2072
- // Leaving it dirty lets its own saveChanges() persist the newer value.
2073
- for (const entity of entities) {
2074
- if ((entity.__version || 0) !== __preWriteVersion.get(entity)) continue;
2075
- entity.__state = 'track';
2076
- entity.__dirtyFields = [];
2077
- }
2046
+ // Lifecycle state (modified -> clean, then detached) is transitioned
2047
+ // centrally in _reconcileFlushed after the transaction commits — not
2048
+ // here. Keeping it in one place, applied uniformly to inserts, updates
2049
+ // and deletes, is what prevents state-specific gaps (a delete never
2050
+ // becomes 'track', so a per-processor reset here would strand it).
2078
2051
  }
2079
2052
 
2080
2053
  /**
@@ -2216,19 +2189,31 @@ class context {
2216
2189
  // silently lose the UPDATE (returning true). Committing only the
2217
2190
  // change set makes an empty save a true no-op that never touches
2218
2191
  // another unit of work's entities.
2219
- const changeSet = this.__trackedEntities.filter(
2220
- e => e && e.__state && e.__state !== 'track'
2221
- );
2192
+ // Iterate the identity map directly rather than materializing the whole
2193
+ // tracked list — a read-heavy context can track tens of thousands of
2194
+ // clean rows, and only the dirty ones are the unit of work.
2195
+ const changeSet = [];
2196
+ for (const e of this.__trackedEntitiesMap.values()) {
2197
+ if (e && e.__state && e.__state !== 'track') changeSet.push(e);
2198
+ }
2222
2199
 
2223
2200
  if (changeSet.length === 0) {
2224
- // Nothing dirty — do NOT touch the shared tracked list.
2201
+ // Nothing dirty — do NOT touch the shared tracked set.
2225
2202
  return true;
2226
2203
  }
2227
2204
 
2228
- // Capture each entity's mutation version so that, after the async write,
2229
- // we can tell whether it was re-mutated in flight and keep it tracked.
2230
- const versions = new Map();
2231
- for (const e of changeSet) { versions.set(e, e.__version || 0); }
2205
+ // Snapshot the committed unit of work: for each entity in the change set,
2206
+ // capture the exact pending change we are about to flush — its mutation
2207
+ // GENERATION (version) and whether it was a delete. All post-commit
2208
+ // lifecycle transitions are driven from this snapshot in ONE place
2209
+ // (_reconcileFlushed), by ONE uniform rule, rather than being scattered
2210
+ // across the per-state batch processors — which is how a delete (never
2211
+ // reset to 'track') used to be stranded forever.
2212
+ const captured = changeSet.map(e => ({
2213
+ entity: e,
2214
+ generation: e.__version || 0,
2215
+ wasDelete: e.__state === 'delete',
2216
+ }));
2232
2217
 
2233
2218
  const affectedTables = new Set();
2234
2219
  for (const e of changeSet) { if (e.__name) affectedTables.add(e.__name); }
@@ -2252,15 +2237,7 @@ class context {
2252
2237
  this._queryCache.invalidateTable(tableName);
2253
2238
  }
2254
2239
 
2255
- // Release ONLY the entities we actually wrote and that were not
2256
- // re-mutated during the write (state back to 'track' AND version
2257
- // unchanged). An entity re-mutated in flight has a bumped __version
2258
- // (and the batch processors leave it dirty) — keep it tracked so its
2259
- // own saveChanges() still persists the newer change.
2260
- const done = changeSet.filter(
2261
- e => e.__state === 'track' && (e.__version || 0) === versions.get(e)
2262
- );
2263
- this.__untrack(done);
2240
+ this._reconcileFlushed(captured);
2264
2241
  return true;
2265
2242
  } catch (error) {
2266
2243
  this.__clearErrorHandler();
@@ -2273,37 +2250,56 @@ class context {
2273
2250
  }
2274
2251
 
2275
2252
  /**
2276
- * Remove a batch of entities from change tracking after a save — but ONLY
2277
- * entities that are currently CLEAN (state 'track').
2278
- *
2279
- * saveChanges() snapshots the tracked list, writes the dirty rows (which are
2280
- * then reset to 'track'), and calls this to drop the batch. A batched entity
2281
- * that is STILL dirty at this point (insert/modified/delete) was NOT written
2282
- * by this save — it became dirty AFTER the snapshot. That happens when a
2283
- * context instance is shared across concurrent units of work (e.g. a
2284
- * singleton context serving many requests): request A's save snapshots a row
2285
- * that request B loaded, B mutates it while A's save is in flight, and if A
2286
- * then untracked it unconditionally, B's own saveChanges() would find it
2287
- * untracked and silently drop the UPDATE. Skipping dirty entities keeps
2288
- * B's pending change tracked so B's save still writes it. (In the normal
2289
- * per-request context the whole batch is clean here, so behavior is
2290
- * unchanged.)
2291
- *
2292
- * NOTE: a context is a unit of work and is safest scoped per request.
2293
- * Sharing one instance across requests still risks cross-request
2294
- * transaction conflation; this guard removes the silent-lost-write, not the
2295
- * need for request-scoped contexts.
2253
+ * Post-commit reconciliation for a flushed unit of work — the SINGLE place
2254
+ * that transitions entity lifecycle state after a successful save. Driven by
2255
+ * the generation snapshot captured at flush time, with one uniform rule for
2256
+ * inserts, updates and deletes (no per-state special cases — that asymmetry
2257
+ * is what stranded deletes as replaying "zombies").
2258
+ *
2259
+ * For each committed entity:
2260
+ * - Re-mutated in flight (generation changed): a NEW change arrived during
2261
+ * the async write. Leave the entity in its current pending state so the
2262
+ * next saveChanges() persists it — never reset it, or that change is lost.
2263
+ * - Otherwise it was fully persisted with no newer change:
2264
+ * * insert / modified -> reset to the clean 'track' state, then detach
2265
+ * from the unit of work (remove from tracking).
2266
+ * * delete -> detach from the unit of work (the row is gone;
2267
+ * it never becomes 'track', so it is released on the delete branch).
2268
+ *
2269
+ * @param {Array<{entity:object, generation:number, wasDelete:boolean}>} captured
2270
+ */
2271
+ _reconcileFlushed(captured) {
2272
+ const detach = [];
2273
+ for (const { entity, generation, wasDelete } of captured) {
2274
+ if ((entity.__version || 0) !== generation) {
2275
+ // A mutation landed during the flush; keep the new pending change.
2276
+ continue;
2277
+ }
2278
+ if (!wasDelete) {
2279
+ entity.__state = 'track';
2280
+ entity.__dirtyFields = [];
2281
+ }
2282
+ detach.push(entity);
2283
+ }
2284
+ this.__untrack(detach);
2285
+ }
2286
+
2287
+ /**
2288
+ * Remove an exact set of entities from change tracking (identity map +
2289
+ * tracked list). The caller curates the set — saveChanges passes only the
2290
+ * entities it fully flushed and that were not re-mutated in flight — so this
2291
+ * removes precisely what it is given and applies NO state test of its own
2292
+ * (a state test here is what stranded deletes, whose state stays 'delete').
2293
+ * Also used by detach()/clearChangeTracker() and attach()'s re-home path.
2296
2294
  */
2297
2295
  __untrack(batch) {
2298
2296
  if (!batch || !batch.length) return;
2299
- // Remove exactly the entities passed in. The caller (saveChanges) curates
2300
- // this to the rows it actually wrote and that were not re-mutated in
2301
- // flight, so no state test is needed here — and none should be applied,
2302
- // or an entity with a falsy __state could be dropped or kept wrongly.
2303
- const drop = new Set(batch);
2304
- this.__trackedEntities = this.__trackedEntities.filter(e => !drop.has(e));
2297
+ // Remove exactly the entities passed in, from the single registry (the
2298
+ // map). The caller (saveChanges) curates this to the rows it flushed and
2299
+ // that were not re-mutated in flight, so no state test is applied here (a
2300
+ // state test is what stranded deletes, whose state stays 'delete').
2305
2301
  for (const e of batch) {
2306
- if (e && e.__ID !== undefined) this.__trackedEntitiesMap.delete(e.__ID);
2302
+ if (e && e.__ID != null) this.__trackedEntitiesMap.delete(e.__ID);
2307
2303
  }
2308
2304
  }
2309
2305
 
@@ -2760,8 +2756,7 @@ class context {
2760
2756
  const previous = entity.__context;
2761
2757
  if (previous && previous !== this && entity.__ID &&
2762
2758
  previous.__trackedEntitiesMap && previous.__trackedEntitiesMap.has(entity.__ID)) {
2763
- previous.__trackedEntitiesMap.delete(entity.__ID);
2764
- previous.__trackedEntities = previous.__trackedEntities.filter(e => e.__ID !== entity.__ID);
2759
+ previous.__trackedEntitiesMap.delete(entity.__ID); // list view follows the map
2765
2760
  }
2766
2761
 
2767
2762
  // Mark entity as modified
@@ -2881,19 +2876,27 @@ class context {
2881
2876
  * @param {object} model - Entity to track
2882
2877
  * @returns {object} The tracked entity
2883
2878
  */
2879
+ /**
2880
+ * The tracked-entity list — a DERIVED view over the identity map, which is
2881
+ * the single source of truth. Rebuilt on read so it always exactly matches
2882
+ * the map (same set, no duplicates, no orphans). Never assign to this.
2883
+ */
2884
+ get __trackedEntities() {
2885
+ return Array.from(this.__trackedEntitiesMap.values());
2886
+ }
2887
+
2884
2888
  __track(model) {
2885
- // Performance: Use Map for O(1) lookup instead of O(n) linear search
2886
2889
  if (!model.__ID) {
2887
- // Generate sequential ID (collision-safe)
2890
+ // Every entity gets a process-unique, collision-free sequential id.
2891
+ // (Queried entities used to arrive with a random __ID from
2892
+ // buildObject, which collided as the tracked set grew and made this
2893
+ // dedup guard silently drop them — the write-loss bug.)
2888
2894
  model.__ID = `entity_${context._nextEntityId++}`;
2889
2895
  }
2890
-
2891
- // O(1) check if already tracked
2892
- if (!this.__trackedEntitiesMap.has(model.__ID)) {
2893
- this.__trackedEntities.push(model);
2894
- this.__trackedEntitiesMap.set(model.__ID, model);
2895
- }
2896
-
2896
+ // Idempotent: keyed by the unique __ID, so re-tracking the same object is
2897
+ // a no-op and distinct objects never collide. Map is the sole registry;
2898
+ // the list view derives from it, so they cannot desynchronise.
2899
+ this.__trackedEntitiesMap.set(model.__ID, model);
2897
2900
  return model;
2898
2901
  }
2899
2902
 
@@ -2918,8 +2921,7 @@ class context {
2918
2921
  * @private
2919
2922
  */
2920
2923
  __clearTracked() {
2921
- this.__trackedEntities = [];
2922
- this.__trackedEntitiesMap.clear(); // Clear Map for proper garbage collection
2924
+ this.__trackedEntitiesMap.clear(); // sole registry; the list view follows
2923
2925
  }
2924
2926
 
2925
2927
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "masterrecord",
3
- "version": "1.5.10",
3
+ "version": "1.5.12",
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",
@@ -46,7 +46,7 @@
46
46
  "LICENSE"
47
47
  ],
48
48
  "engines": {
49
- "node": ">=22.12.0"
49
+ "node": ">=20.0.0"
50
50
  },
51
51
  "scripts": {
52
52
  "test": "node --test test/*.test.js test/integration/*.test.js Migrations/pathUtils.test.js",