masterrecord 1.5.12 → 1.5.14

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.14 — context-level query tracking behavior (EF's QueryTrackingBehavior) + asTracking()
4
+
5
+ The remaining memory issue: on a long-lived/singleton context, tracked entities are held with **strong references** for the life of the context, so read-only queries that track their results grow the tracked set without bound. `asNoTracking()` (1.5.13) bounds it only per call site.
6
+
7
+ This is exactly EF Core's situation, so this release adds EF's context-level control:
8
+ - **`context.setQueryTrackingBehavior('no-track')`** — the default tracking behavior for the whole context (EF's `ChangeTracker.QueryTrackingBehavior = NoTracking`). All queries become no-tracking by default — a read-heavy context then retains nothing from reads — and you opt back in per query with...
9
+ - **`query.asTracking()`** (EF's `AsTracking()`) — track this query's results despite a no-track default, for the queries whose entities you modify and save.
10
+
11
+ Together with `asNoTracking()` and `clearChangeTracker()` (EF's `ChangeTracker.Clear()`), this is EF's full toolkit for bounding tracking.
12
+
13
+ **Honest note on memory (this matters):** EF Core does **not** hold tracked entities weakly — it uses strong references, and its memory bound is **context lifetime**: the `DbContext` is meant to be short-lived (scoped per request) and disposed, releasing the whole change tracker. masterrecord follows the same model. So the definitive fix for unbounded growth is a **request-scoped context**. If a context must be long-lived, set `setQueryTrackingBehavior('no-track')` and use `asTracking()` on write paths. (A `WeakRef`-based identity map would bound a long-lived context transparently, but that is a deliberate departure from EF's design, not what EF does — so it is not adopted here.)
14
+
15
+ New tests in `test/no-tracking-and-dirty-index.test.js`: a `no-track` default retains nothing while `asTracking()` still tracks and persists; the setter validates its argument. Full suite green (0 fail, 309 pass, 20 gated skipped); 0 lint errors.
16
+
17
+ ## v1.5.13 — EF-Core-style change tracking: O(changes) saves (dirty index) + asNoTracking()
18
+
19
+ 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.
20
+
21
+ **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.
22
+
23
+ **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.
24
+
25
+ **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.
26
+
27
+ 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.
28
+
3
29
  ## v1.5.12 — collision-free tracking identity + single source of truth (THE write-loss root cause)
4
30
 
5
31
  **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.
@@ -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];
@@ -531,7 +534,11 @@ class EntityTrackerModel {
531
534
  modelClass.__state = "modified";
532
535
  modelClass.__version = (modelClass.__version || 0) + 1;
533
536
  modelClass.__dirtyFields.push(entityField);
534
- modelClass.__context.__track(modelClass);
537
+ if (typeof modelClass.__context.__markDirty === 'function') {
538
+ modelClass.__context.__markDirty(modelClass);
539
+ } else {
540
+ modelClass.__context.__track(modelClass);
541
+ }
535
542
  }
536
543
  this["__proto__"]["_" + entityField] = value;
537
544
  },
@@ -28,6 +28,34 @@ 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
+ // Tracking follows the context's default (EF's QueryTrackingBehavior);
32
+ // override per query with .asNoTracking() / .asTracking().
33
+ this.__noTracking = (context && context.__queryTrackingBehavior === 'no-track');
34
+ }
35
+
36
+ /**
37
+ * Read-only query: do NOT enter results into the change tracker (like EF
38
+ * Core's AsNoTracking). Nothing is retained, so a read-heavy endpoint that
39
+ * `.toList()`s a large table no longer grows the tracked set. Mutations on
40
+ * the returned entities are not persisted (they are detached), matching EF.
41
+ *
42
+ * @example db.Users.asNoTracking().toList();
43
+ */
44
+ asNoTracking(){
45
+ this.__noTracking = true;
46
+ return this;
47
+ }
48
+
49
+ /**
50
+ * Track this query's results even when the context defaults to no-tracking
51
+ * (EF Core's AsTracking). Use it on the queries whose entities you intend to
52
+ * modify and save, after setting the context to `setQueryTrackingBehavior('no-track')`.
53
+ *
54
+ * @example db.Users.asTracking().where(...).single(); // then edit + saveChanges()
55
+ */
56
+ asTracking(){
57
+ this.__noTracking = false;
58
+ return this;
31
59
  }
32
60
 
33
61
  // build a single entity
@@ -37,7 +65,13 @@ class queryMethods{
37
65
  const ent = new entityTrackerModel();
38
66
  const mod = ent.build(dataModel, $that.__entity, $that.__context);
39
67
  mod.__state = "track";
40
- $that.__context.__track(mod);
68
+ if ($that.__noTracking) {
69
+ // AsNoTracking: flag it so a later mutation won't enqueue a write
70
+ // (__markDirty ignores no-tracking entities) and never track it.
71
+ mod.__noTracking = true;
72
+ } else {
73
+ $that.__context.__track(mod);
74
+ }
41
75
  return mod;
42
76
  }else{
43
77
  return null;
@@ -714,7 +748,9 @@ class queryMethods{
714
748
  if (this.__state === 'track') {
715
749
  this.__state = 'modified';
716
750
  }
717
- if (this.__context && typeof this.__context.__track === 'function') {
751
+ if (this.__context && typeof this.__context.__markDirty === 'function') {
752
+ this.__context.__markDirty(this);
753
+ } else if (this.__context && typeof this.__context.__track === 'function') {
718
754
  this.__context.__track(this);
719
755
  }
720
756
  },
@@ -762,7 +798,9 @@ class queryMethods{
762
798
  if (this.__state === 'track') {
763
799
  this.__state = 'modified';
764
800
  }
765
- if (this.__context && typeof this.__context.__track === 'function') {
801
+ if (this.__context && typeof this.__context.__markDirty === 'function') {
802
+ this.__context.__markDirty(this);
803
+ } else if (this.__context && typeof this.__context.__track === 'function') {
766
804
  this.__context.__track(this);
767
805
  }
768
806
  },
@@ -882,11 +920,11 @@ class queryMethods{
882
920
  throw new Error('Cannot delete: entity is not attached to a context');
883
921
  }
884
922
 
885
- // Mark entity for deletion
923
+ // Mark entity for deletion — dirty, so register it in the dirty index.
886
924
  this.__state = 'delete';
887
-
888
- // Ensure entity is tracked
889
- if (!this.__context.__trackedEntitiesMap.has(this.__ID)) {
925
+ if (typeof this.__context.__markDirty === 'function') {
926
+ this.__context.__markDirty(this);
927
+ } else if (!this.__context.__trackedEntitiesMap.has(this.__ID)) {
890
928
  this.__context.__track(this);
891
929
  }
892
930
 
@@ -1032,14 +1070,14 @@ class queryMethods{
1032
1070
  entityValue[f] = undefined;
1033
1071
  }
1034
1072
  }
1035
- this.__context.__track(entityValue);
1073
+ this.__context.__markDirty(entityValue); // insert is dirty
1036
1074
  }
1037
-
1075
+
1038
1076
  remove(entityValue){
1039
1077
  entityValue.__state = "delete";
1040
1078
  entityValue.__entity = this.__entity;
1041
1079
  entityValue.__context = this.__context;
1042
- this.__context.__track(entityValue);
1080
+ this.__context.__markDirty(entityValue); // delete is dirty
1043
1081
  }
1044
1082
 
1045
1083
  removeRange(entityValues){
@@ -1048,7 +1086,7 @@ class queryMethods{
1048
1086
  entityValue.__state = "delete";
1049
1087
  entityValue.__entity = this.__entity;
1050
1088
  entityValue.__context = this.__context;
1051
- this.__context.__track(entityValue);
1089
+ this.__context.__markDirty(entityValue); // delete is dirty
1052
1090
  }
1053
1091
  }
1054
1092
 
package/context.js CHANGED
@@ -221,7 +221,19 @@ class context {
221
221
  // the two can never desynchronise — a dual array+map registry silently lost
222
222
  // writes whenever the two disagreed (a stale/colliding id in one but not the
223
223
  // other). All mutations go through __track / __untrack / __clearTracked.
224
- __trackedEntitiesMap = new Map(); // O(1) identity lookup; the authority
224
+ __trackedEntitiesMap = new Map(); // __ID -> entity; the authority
225
+ // Default query tracking behavior, EF-style (QueryTrackingBehavior).
226
+ // 'track' — queries track their results (edits persist); the default.
227
+ // 'no-track' — queries do NOT track (read-only; nothing retained). Set once
228
+ // on a long-lived/singleton context so read endpoints don't grow the
229
+ // tracked set; opt back in per query with .asTracking() where you update.
230
+ __queryTrackingBehavior = 'track';
231
+ // Dirty index (like EF Core's StateManager): the subset of tracked entities
232
+ // that are insert/modified/delete. Entities enter it the moment a setter /
233
+ // add() / remove() makes them dirty, and leave it when flushed or detached.
234
+ // saveChanges() reads ONLY this set, so a flush is O(changes) — not O(total
235
+ // tracked) — and an empty save is O(1), even with tens of thousands tracked.
236
+ __dirtyEntities = new Set();
225
237
  __relationshipModels = [];
226
238
  __contextSeedData = {}; // Store seed data by table name
227
239
  __contextSeedConfig = { // Seed data configuration
@@ -2189,16 +2201,18 @@ class context {
2189
2201
  // silently lose the UPDATE (returning true). Committing only the
2190
2202
  // change set makes an empty save a true no-op that never touches
2191
2203
  // another unit of work's entities.
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.
2204
+ // Read ONLY the dirty index — the change set is O(changes), never
2205
+ // O(total tracked). A read-heavy context can track tens of thousands of
2206
+ // clean rows; none of them are scanned here. (Self-heals if a clean
2207
+ // entity ever lingers in the index.)
2195
2208
  const changeSet = [];
2196
- for (const e of this.__trackedEntitiesMap.values()) {
2209
+ for (const e of this.__dirtyEntities) {
2197
2210
  if (e && e.__state && e.__state !== 'track') changeSet.push(e);
2211
+ else this.__dirtyEntities.delete(e);
2198
2212
  }
2199
2213
 
2200
2214
  if (changeSet.length === 0) {
2201
- // Nothing dirty — do NOT touch the shared tracked set.
2215
+ // Nothing dirty — O(1) no-op; do NOT touch the tracked set.
2202
2216
  return true;
2203
2217
  }
2204
2218
 
@@ -2299,7 +2313,9 @@ class context {
2299
2313
  // that were not re-mutated in flight, so no state test is applied here (a
2300
2314
  // state test is what stranded deletes, whose state stays 'delete').
2301
2315
  for (const e of batch) {
2302
- if (e && e.__ID != null) this.__trackedEntitiesMap.delete(e.__ID);
2316
+ if (!e) continue;
2317
+ if (e.__ID != null) this.__trackedEntitiesMap.delete(e.__ID);
2318
+ this.__dirtyEntities.delete(e); // keep the dirty index in lockstep
2303
2319
  }
2304
2320
  }
2305
2321
 
@@ -2793,8 +2809,9 @@ class context {
2793
2809
  // Ensure context reference
2794
2810
  entity.__context = this;
2795
2811
 
2796
- // Track the entity
2797
- this.__track(entity);
2812
+ // Attach() marks the entity modified, so it is dirty — register it in the
2813
+ // dirty index so saveChanges() actually flushes it.
2814
+ this.__markDirty(entity);
2798
2815
 
2799
2816
  return entity;
2800
2817
  }
@@ -2897,6 +2914,31 @@ class context {
2897
2914
  // a no-op and distinct objects never collide. Map is the sole registry;
2898
2915
  // the list view derives from it, so they cannot desynchronise.
2899
2916
  this.__trackedEntitiesMap.set(model.__ID, model);
2917
+ // Robustness: if the entity being tracked is ALREADY dirty, enqueue it in
2918
+ // the dirty index too. This guarantees the index is complete no matter
2919
+ // how an entity gets tracked (setter, add/remove, or a direct __track
2920
+ // after a state change) — a dirty entity can never be tracked yet missed
2921
+ // by the change set.
2922
+ if (model.__state && model.__state !== 'track' && !model.__noTracking) {
2923
+ this.__dirtyEntities.add(model);
2924
+ }
2925
+ return model;
2926
+ }
2927
+
2928
+ /**
2929
+ * Mark an entity dirty (insert/modified/delete): track it in the identity map
2930
+ * AND add it to the dirty index that saveChanges() reads. EVERY dirty-state
2931
+ * transition (setters, add(), remove(), delete(), attach()) funnels through
2932
+ * here, so the dirty index is complete — an entity that is dirty is always in
2933
+ * the change set and therefore always flushed.
2934
+ *
2935
+ * No-tracking entities (AsNoTracking query results) are intentionally ignored
2936
+ * — like EF, mutating a no-tracking entity does not enqueue a write.
2937
+ */
2938
+ __markDirty(model) {
2939
+ if (!model || model.__noTracking) return model;
2940
+ this.__track(model);
2941
+ this.__dirtyEntities.add(model);
2900
2942
  return model;
2901
2943
  }
2902
2944
 
@@ -2922,6 +2964,7 @@ class context {
2922
2964
  */
2923
2965
  __clearTracked() {
2924
2966
  this.__trackedEntitiesMap.clear(); // sole registry; the list view follows
2967
+ this.__dirtyEntities.clear();
2925
2968
  }
2926
2969
 
2927
2970
  /**
@@ -2940,6 +2983,28 @@ class context {
2940
2983
  return this;
2941
2984
  }
2942
2985
 
2986
+ /**
2987
+ * Set the DEFAULT query tracking behavior for this context (EF Core's
2988
+ * `ChangeTracker.QueryTrackingBehavior`).
2989
+ *
2990
+ * 'no-track' — queries do NOT track their results by default, so a
2991
+ * read-heavy / long-lived (singleton) context retains nothing from
2992
+ * reads. Opt back into tracking per query with `.asTracking()` on the
2993
+ * ones whose results you intend to modify and save.
2994
+ * 'track' — the default: queries track their results so edits persist.
2995
+ *
2996
+ * This is the "not per-call-site" bound: set it once instead of adding
2997
+ * `.asNoTracking()` to every read. The definitive fix for unbounded growth
2998
+ * is still a request-scoped context; this is how to run a longer-lived one.
2999
+ */
3000
+ setQueryTrackingBehavior(behavior) {
3001
+ if (behavior !== 'track' && behavior !== 'no-track') {
3002
+ throw new Error(`masterrecord: setQueryTrackingBehavior expects 'track' or 'no-track', got ${JSON.stringify(behavior)}`);
3003
+ }
3004
+ this.__queryTrackingBehavior = behavior;
3005
+ return this;
3006
+ }
3007
+
2943
3008
  /**
2944
3009
  * Detach a single entity from change tracking. Pending changes on it are
2945
3010
  * dropped and it is no longer part of any future saveChanges().
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "masterrecord",
3
- "version": "1.5.12",
3
+ "version": "1.5.14",
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",