masterrecord 1.5.11 → 1.5.13

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,29 @@
1
1
  # MasterRecord Changelog
2
2
 
3
+ ## v1.5.13 — EF-Core-style change tracking: O(changes) saves (dirty index) + asNoTracking()
4
+
5
+ Fixing the write loss in 1.5.12 exposed two costs of correct retention in a long-lived context — unbounded memory and O(total-tracked) saves. Both are addressed the way EF Core does.
6
+
7
+ **1. Dirty index (EF's `StateManager`) — a flush is O(changes), not O(total tracked).** The context keeps a `__dirtyEntities` set: the subset of tracked entities that are insert/modified/delete. Entities enter it the instant a setter / `add()` / `remove()` / `delete()` / `attach()` makes them dirty (all funnel through a new `__markDirty()`), and leave it when flushed or detached. `saveChanges()` now reads **only** this set, so an empty save is O(1) and a flush is O(changes) even with tens of thousands of clean rows tracked. Belt-and-suspenders for completeness: `__track()` also enqueues any entity that is already dirty when tracked, so no dirty entity can ever be tracked yet missed by the change set.
8
+
9
+ **2. `asNoTracking()` (EF's `AsNoTracking`) — read-only queries retain nothing.** `db.Model.asNoTracking().toList()` returns entities without entering them into the change tracker, so a read-heavy endpoint that lists a whole table no longer grows the tracked set. Mutating a no-tracking entity does not enqueue a write (it is detached), matching EF. This is the fix for the memory growth a process-lifetime singleton context accumulated from read-only `.toList()` calls.
10
+
11
+ **Guidance (also EF's):** a context is a unit of work — prefer a **short-lived, request-scoped** context (EF disposes the DbContext per request). For read-only work on a shared/long-lived context, use `asNoTracking()`. `clearChangeTracker()` remains, but it drops pending changes, so it is not safe as a per-request mitigation on a shared context — scope the context or use `asNoTracking()` instead.
12
+
13
+ New tests: `test/no-tracking-and-dirty-index.test.js` — asNoTracking retains nothing and its mutations don't persist; a normal query tracks and its edits persist; a save over 2000 tracked rows with 3 dirty puts exactly 3 in the change set and flushes only those. Full suite green (0 fail, 307 pass, 20 gated skipped); 0 lint errors.
14
+
15
+ ## v1.5.12 — collision-free tracking identity + single source of truth (THE write-loss root cause)
16
+
17
+ **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.
18
+
19
+ **Fix:**
20
+ 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.
21
+ 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).
22
+
23
+ **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+.
24
+
25
+ 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.
26
+
3
27
  ## v1.5.11 — deletes are released after commit (fix 1.5.10 "zombie delete" latch); lifecycle reconciliation centralized
4
28
 
5
29
  **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.
@@ -150,11 +150,12 @@ class EntityTrackerModel {
150
150
  throw new Error('Cannot delete: entity is not attached to a context');
151
151
  }
152
152
 
153
- // Mark entity for deletion
153
+ // Mark entity for deletion — dirty, so register it in the dirty index
154
+ // (a delete that isn't in the change set would never be issued).
154
155
  this.__state = 'delete';
155
-
156
- // Ensure entity is tracked
157
- if (!this.__context.__trackedEntitiesMap.has(this.__ID)) {
156
+ if (typeof this.__context.__markDirty === 'function') {
157
+ this.__context.__markDirty(this);
158
+ } else if (!this.__context.__trackedEntitiesMap.has(this.__ID)) {
158
159
  this.__context.__track(this);
159
160
  }
160
161
 
@@ -392,7 +393,9 @@ class EntityTrackerModel {
392
393
  // Ensure this entity is tracked on any modification. THIS is the
393
394
  // line that makes a just-inserted, attached entity's later edits
394
395
  // persist instead of being silently dropped.
395
- if (this.__context && typeof this.__context.__track === 'function') {
396
+ if (this.__context && typeof this.__context.__markDirty === 'function') {
397
+ this.__context.__markDirty(this);
398
+ } else if (this.__context && typeof this.__context.__track === 'function') {
396
399
  this.__context.__track(this);
397
400
  }
398
401
  const fieldDefForSet = currentEntity[modelField];
@@ -488,7 +491,13 @@ class EntityTrackerModel {
488
491
 
489
492
  buildObject(){
490
493
  return {
491
- __ID : Math.floor((Math.random() * 100000) + 1),
494
+ // Do NOT assign an identity here. A random __ID in [1,100000] collided
495
+ // catastrophically once the tracked set grew (birthday paradox): a new
496
+ // entity whose random __ID already existed hit __track's dedup guard,
497
+ // was never added to the tracked set, and its writes were silently
498
+ // dropped — the monotonic write-loss decay in long-lived contexts.
499
+ // __track() assigns a process-unique, collision-free sequential id.
500
+ __ID : null,
492
501
  __dirtyFields : [],
493
502
  __state : "track",
494
503
  __entity : null,
@@ -525,7 +534,11 @@ class EntityTrackerModel {
525
534
  modelClass.__state = "modified";
526
535
  modelClass.__version = (modelClass.__version || 0) + 1;
527
536
  modelClass.__dirtyFields.push(entityField);
528
- modelClass.__context.__track(modelClass);
537
+ if (typeof modelClass.__context.__markDirty === 'function') {
538
+ modelClass.__context.__markDirty(modelClass);
539
+ } else {
540
+ modelClass.__context.__track(modelClass);
541
+ }
529
542
  }
530
543
  this["__proto__"]["_" + entityField] = value;
531
544
  },
@@ -28,6 +28,20 @@ class queryMethods{
28
28
  this.__context = context;
29
29
  this.__queryObject = new queryScript();
30
30
  this.__useCache = false; // Disable caching by default (opt-in with .cache())
31
+ this.__noTracking = false; // opt-in with .asNoTracking() for read-only reads
32
+ }
33
+
34
+ /**
35
+ * Read-only query: do NOT enter results into the change tracker (like EF
36
+ * Core's AsNoTracking). Nothing is retained, so a read-heavy endpoint that
37
+ * `.toList()`s a large table no longer grows the tracked set. Mutations on
38
+ * the returned entities are not persisted (they are detached), matching EF.
39
+ *
40
+ * @example db.Users.asNoTracking().toList();
41
+ */
42
+ asNoTracking(){
43
+ this.__noTracking = true;
44
+ return this;
31
45
  }
32
46
 
33
47
  // build a single entity
@@ -37,7 +51,13 @@ class queryMethods{
37
51
  const ent = new entityTrackerModel();
38
52
  const mod = ent.build(dataModel, $that.__entity, $that.__context);
39
53
  mod.__state = "track";
40
- $that.__context.__track(mod);
54
+ if ($that.__noTracking) {
55
+ // AsNoTracking: flag it so a later mutation won't enqueue a write
56
+ // (__markDirty ignores no-tracking entities) and never track it.
57
+ mod.__noTracking = true;
58
+ } else {
59
+ $that.__context.__track(mod);
60
+ }
41
61
  return mod;
42
62
  }else{
43
63
  return null;
@@ -714,7 +734,9 @@ class queryMethods{
714
734
  if (this.__state === 'track') {
715
735
  this.__state = 'modified';
716
736
  }
717
- if (this.__context && typeof this.__context.__track === 'function') {
737
+ if (this.__context && typeof this.__context.__markDirty === 'function') {
738
+ this.__context.__markDirty(this);
739
+ } else if (this.__context && typeof this.__context.__track === 'function') {
718
740
  this.__context.__track(this);
719
741
  }
720
742
  },
@@ -762,7 +784,9 @@ class queryMethods{
762
784
  if (this.__state === 'track') {
763
785
  this.__state = 'modified';
764
786
  }
765
- if (this.__context && typeof this.__context.__track === 'function') {
787
+ if (this.__context && typeof this.__context.__markDirty === 'function') {
788
+ this.__context.__markDirty(this);
789
+ } else if (this.__context && typeof this.__context.__track === 'function') {
766
790
  this.__context.__track(this);
767
791
  }
768
792
  },
@@ -882,11 +906,11 @@ class queryMethods{
882
906
  throw new Error('Cannot delete: entity is not attached to a context');
883
907
  }
884
908
 
885
- // Mark entity for deletion
909
+ // Mark entity for deletion — dirty, so register it in the dirty index.
886
910
  this.__state = 'delete';
887
-
888
- // Ensure entity is tracked
889
- if (!this.__context.__trackedEntitiesMap.has(this.__ID)) {
911
+ if (typeof this.__context.__markDirty === 'function') {
912
+ this.__context.__markDirty(this);
913
+ } else if (!this.__context.__trackedEntitiesMap.has(this.__ID)) {
890
914
  this.__context.__track(this);
891
915
  }
892
916
 
@@ -1032,14 +1056,14 @@ class queryMethods{
1032
1056
  entityValue[f] = undefined;
1033
1057
  }
1034
1058
  }
1035
- this.__context.__track(entityValue);
1059
+ this.__context.__markDirty(entityValue); // insert is dirty
1036
1060
  }
1037
-
1061
+
1038
1062
  remove(entityValue){
1039
1063
  entityValue.__state = "delete";
1040
1064
  entityValue.__entity = this.__entity;
1041
1065
  entityValue.__context = this.__context;
1042
- this.__context.__track(entityValue);
1066
+ this.__context.__markDirty(entityValue); // delete is dirty
1043
1067
  }
1044
1068
 
1045
1069
  removeRange(entityValues){
@@ -1048,7 +1072,7 @@ class queryMethods{
1048
1072
  entityValue.__state = "delete";
1049
1073
  entityValue.__entity = this.__entity;
1050
1074
  entityValue.__context = this.__context;
1051
- this.__context.__track(entityValue);
1075
+ this.__context.__markDirty(entityValue); // delete is dirty
1052
1076
  }
1053
1077
  }
1054
1078
 
package/context.js CHANGED
@@ -216,8 +216,18 @@ 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
225
+ // Dirty index (like EF Core's StateManager): the subset of tracked entities
226
+ // that are insert/modified/delete. Entities enter it the moment a setter /
227
+ // add() / remove() makes them dirty, and leave it when flushed or detached.
228
+ // saveChanges() reads ONLY this set, so a flush is O(changes) — not O(total
229
+ // tracked) — and an empty save is O(1), even with tens of thousands tracked.
230
+ __dirtyEntities = new Set();
221
231
  __relationshipModels = [];
222
232
  __contextSeedData = {}; // Store seed data by table name
223
233
  __contextSeedConfig = { // Seed data configuration
@@ -2185,12 +2195,18 @@ class context {
2185
2195
  // silently lose the UPDATE (returning true). Committing only the
2186
2196
  // change set makes an empty save a true no-op that never touches
2187
2197
  // another unit of work's entities.
2188
- const changeSet = this.__trackedEntities.filter(
2189
- e => e && e.__state && e.__state !== 'track'
2190
- );
2198
+ // Read ONLY the dirty index — the change set is O(changes), never
2199
+ // O(total tracked). A read-heavy context can track tens of thousands of
2200
+ // clean rows; none of them are scanned here. (Self-heals if a clean
2201
+ // entity ever lingers in the index.)
2202
+ const changeSet = [];
2203
+ for (const e of this.__dirtyEntities) {
2204
+ if (e && e.__state && e.__state !== 'track') changeSet.push(e);
2205
+ else this.__dirtyEntities.delete(e);
2206
+ }
2191
2207
 
2192
2208
  if (changeSet.length === 0) {
2193
- // Nothing dirty — do NOT touch the shared tracked list.
2209
+ // Nothing dirty — O(1) no-op; do NOT touch the tracked set.
2194
2210
  return true;
2195
2211
  }
2196
2212
 
@@ -2286,14 +2302,14 @@ class context {
2286
2302
  */
2287
2303
  __untrack(batch) {
2288
2304
  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));
2305
+ // Remove exactly the entities passed in, from the single registry (the
2306
+ // map). The caller (saveChanges) curates this to the rows it flushed and
2307
+ // that were not re-mutated in flight, so no state test is applied here (a
2308
+ // state test is what stranded deletes, whose state stays 'delete').
2295
2309
  for (const e of batch) {
2296
- if (e && e.__ID !== undefined) this.__trackedEntitiesMap.delete(e.__ID);
2310
+ if (!e) continue;
2311
+ if (e.__ID != null) this.__trackedEntitiesMap.delete(e.__ID);
2312
+ this.__dirtyEntities.delete(e); // keep the dirty index in lockstep
2297
2313
  }
2298
2314
  }
2299
2315
 
@@ -2750,8 +2766,7 @@ class context {
2750
2766
  const previous = entity.__context;
2751
2767
  if (previous && previous !== this && entity.__ID &&
2752
2768
  previous.__trackedEntitiesMap && previous.__trackedEntitiesMap.has(entity.__ID)) {
2753
- previous.__trackedEntitiesMap.delete(entity.__ID);
2754
- previous.__trackedEntities = previous.__trackedEntities.filter(e => e.__ID !== entity.__ID);
2769
+ previous.__trackedEntitiesMap.delete(entity.__ID); // list view follows the map
2755
2770
  }
2756
2771
 
2757
2772
  // Mark entity as modified
@@ -2788,8 +2803,9 @@ class context {
2788
2803
  // Ensure context reference
2789
2804
  entity.__context = this;
2790
2805
 
2791
- // Track the entity
2792
- this.__track(entity);
2806
+ // Attach() marks the entity modified, so it is dirty — register it in the
2807
+ // dirty index so saveChanges() actually flushes it.
2808
+ this.__markDirty(entity);
2793
2809
 
2794
2810
  return entity;
2795
2811
  }
@@ -2871,19 +2887,52 @@ class context {
2871
2887
  * @param {object} model - Entity to track
2872
2888
  * @returns {object} The tracked entity
2873
2889
  */
2890
+ /**
2891
+ * The tracked-entity list — a DERIVED view over the identity map, which is
2892
+ * the single source of truth. Rebuilt on read so it always exactly matches
2893
+ * the map (same set, no duplicates, no orphans). Never assign to this.
2894
+ */
2895
+ get __trackedEntities() {
2896
+ return Array.from(this.__trackedEntitiesMap.values());
2897
+ }
2898
+
2874
2899
  __track(model) {
2875
- // Performance: Use Map for O(1) lookup instead of O(n) linear search
2876
2900
  if (!model.__ID) {
2877
- // Generate sequential ID (collision-safe)
2901
+ // Every entity gets a process-unique, collision-free sequential id.
2902
+ // (Queried entities used to arrive with a random __ID from
2903
+ // buildObject, which collided as the tracked set grew and made this
2904
+ // dedup guard silently drop them — the write-loss bug.)
2878
2905
  model.__ID = `entity_${context._nextEntityId++}`;
2879
2906
  }
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);
2907
+ // Idempotent: keyed by the unique __ID, so re-tracking the same object is
2908
+ // a no-op and distinct objects never collide. Map is the sole registry;
2909
+ // the list view derives from it, so they cannot desynchronise.
2910
+ this.__trackedEntitiesMap.set(model.__ID, model);
2911
+ // Robustness: if the entity being tracked is ALREADY dirty, enqueue it in
2912
+ // the dirty index too. This guarantees the index is complete no matter
2913
+ // how an entity gets tracked (setter, add/remove, or a direct __track
2914
+ // after a state change) — a dirty entity can never be tracked yet missed
2915
+ // by the change set.
2916
+ if (model.__state && model.__state !== 'track' && !model.__noTracking) {
2917
+ this.__dirtyEntities.add(model);
2885
2918
  }
2919
+ return model;
2920
+ }
2886
2921
 
2922
+ /**
2923
+ * Mark an entity dirty (insert/modified/delete): track it in the identity map
2924
+ * AND add it to the dirty index that saveChanges() reads. EVERY dirty-state
2925
+ * transition (setters, add(), remove(), delete(), attach()) funnels through
2926
+ * here, so the dirty index is complete — an entity that is dirty is always in
2927
+ * the change set and therefore always flushed.
2928
+ *
2929
+ * No-tracking entities (AsNoTracking query results) are intentionally ignored
2930
+ * — like EF, mutating a no-tracking entity does not enqueue a write.
2931
+ */
2932
+ __markDirty(model) {
2933
+ if (!model || model.__noTracking) return model;
2934
+ this.__track(model);
2935
+ this.__dirtyEntities.add(model);
2887
2936
  return model;
2888
2937
  }
2889
2938
 
@@ -2908,8 +2957,8 @@ class context {
2908
2957
  * @private
2909
2958
  */
2910
2959
  __clearTracked() {
2911
- this.__trackedEntities = [];
2912
- this.__trackedEntitiesMap.clear(); // Clear Map for proper garbage collection
2960
+ this.__trackedEntitiesMap.clear(); // sole registry; the list view follows
2961
+ this.__dirtyEntities.clear();
2913
2962
  }
2914
2963
 
2915
2964
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "masterrecord",
3
- "version": "1.5.11",
3
+ "version": "1.5.13",
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",