masterrecord 1.5.11 → 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,17 @@
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
+
3
15
  ## v1.5.11 — deletes are released after commit (fix 1.5.10 "zombie delete" latch); lifecycle reconciliation centralized
4
16
 
5
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.
@@ -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
@@ -2185,12 +2189,16 @@ class context {
2185
2189
  // silently lose the UPDATE (returning true). Committing only the
2186
2190
  // change set makes an empty save a true no-op that never touches
2187
2191
  // another unit of work's entities.
2188
- const changeSet = this.__trackedEntities.filter(
2189
- e => e && e.__state && e.__state !== 'track'
2190
- );
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
+ }
2191
2199
 
2192
2200
  if (changeSet.length === 0) {
2193
- // Nothing dirty — do NOT touch the shared tracked list.
2201
+ // Nothing dirty — do NOT touch the shared tracked set.
2194
2202
  return true;
2195
2203
  }
2196
2204
 
@@ -2286,14 +2294,12 @@ class context {
2286
2294
  */
2287
2295
  __untrack(batch) {
2288
2296
  if (!batch || !batch.length) return;
2289
- // Remove exactly the entities passed in. The caller (saveChanges) curates
2290
- // this to the rows it actually wrote and that were not re-mutated in
2291
- // flight, so no state test is needed here — and none should be applied,
2292
- // or an entity with a falsy __state could be dropped or kept wrongly.
2293
- const drop = new Set(batch);
2294
- 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').
2295
2301
  for (const e of batch) {
2296
- if (e && e.__ID !== undefined) this.__trackedEntitiesMap.delete(e.__ID);
2302
+ if (e && e.__ID != null) this.__trackedEntitiesMap.delete(e.__ID);
2297
2303
  }
2298
2304
  }
2299
2305
 
@@ -2750,8 +2756,7 @@ class context {
2750
2756
  const previous = entity.__context;
2751
2757
  if (previous && previous !== this && entity.__ID &&
2752
2758
  previous.__trackedEntitiesMap && previous.__trackedEntitiesMap.has(entity.__ID)) {
2753
- previous.__trackedEntitiesMap.delete(entity.__ID);
2754
- previous.__trackedEntities = previous.__trackedEntities.filter(e => e.__ID !== entity.__ID);
2759
+ previous.__trackedEntitiesMap.delete(entity.__ID); // list view follows the map
2755
2760
  }
2756
2761
 
2757
2762
  // Mark entity as modified
@@ -2871,19 +2876,27 @@ class context {
2871
2876
  * @param {object} model - Entity to track
2872
2877
  * @returns {object} The tracked entity
2873
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
+
2874
2888
  __track(model) {
2875
- // Performance: Use Map for O(1) lookup instead of O(n) linear search
2876
2889
  if (!model.__ID) {
2877
- // 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.)
2878
2894
  model.__ID = `entity_${context._nextEntityId++}`;
2879
2895
  }
2880
-
2881
- // O(1) check if already tracked
2882
- if (!this.__trackedEntitiesMap.has(model.__ID)) {
2883
- this.__trackedEntities.push(model);
2884
- this.__trackedEntitiesMap.set(model.__ID, model);
2885
- }
2886
-
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);
2887
2900
  return model;
2888
2901
  }
2889
2902
 
@@ -2908,8 +2921,7 @@ class context {
2908
2921
  * @private
2909
2922
  */
2910
2923
  __clearTracked() {
2911
- this.__trackedEntities = [];
2912
- this.__trackedEntitiesMap.clear(); // Clear Map for proper garbage collection
2924
+ this.__trackedEntitiesMap.clear(); // sole registry; the list view follows
2913
2925
  }
2914
2926
 
2915
2927
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "masterrecord",
3
- "version": "1.5.11",
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",