masterrecord 1.31.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,102 @@
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
+
19
+ ## v1.32.1 — batched inserts keep add order on MySQL and Postgres
20
+
21
+ **Fix: `saveChanges()` could assign ids out of add order on MySQL and Postgres.** A
22
+ multi-row INSERT can only serve rows with the same column list, and since 1.3.1 `bulkInsert`
23
+ pooled every row of a column list into one statement. A batch of `{name,bio}`, `{name}`,
24
+ `{name,bio}` therefore got the ids 1, 3, 2, and `ORDER BY id` returned the rows in a
25
+ different order than they were added. SQLite, the single-insert path and the per-row fallback
26
+ all assign ids in add order, so the result depended on the engine. Each entity still received
27
+ its own row's id, and stored values were correct.
28
+
29
+ - Only consecutive rows with the same columns now share a statement, so ids ascend in add
30
+ order. A batch whose rows all set the same columns is still one statement. One that
31
+ alternates column lists takes one statement per run, up to one per row, inside the same
32
+ transaction. Omitted columns still take their DB-level `DEFAULT`.
33
+ - New `test/bulk-insert-order.test.js` covers both engines without a server, because CI runs
34
+ SQLite only.
35
+
36
+ **Tests: the live MySQL and Postgres suite passes again.** 8 of the 20 tests in
37
+ `test/integration/cross-engine.test.js` failed, and only on a live server. Apart from the
38
+ ordering bug above, the rest were test faults. Since 1.23.0 a new entity's prototype is
39
+ `Object.prototype`, so the suite's `Object.getPrototypeOf(e)._role = …` wrote to every object
40
+ in the process. That emptied the row being tested (`No columns to insert`), and the
41
+ inherited key then surfaced as a column on MySQL (`Unknown column 'ran.operator'`) for any
42
+ later test in the file. The suite now sets the entity's own slot. Its check that a batch does
43
+ not fall back to per-row inserts looked for a log message that no longer exists, so it could
44
+ never fail; it now matches, and the `.set()` batch test makes the same check.
45
+
46
+ ## v1.32.0 — identity resolution: one tracked instance per row
47
+
48
+ **Memory fix for long-lived contexts.** A tracked query built a new entity for every row
49
+ and tracked it, even when the context already tracked that row. Nothing matched a row to
50
+ the instance already tracked, so a context kept alive for the whole process and re-reading
51
+ the same rows grew without limit: about 2 KB per row read. OpenBook's API ran out of heap
52
+ this way: a process-wide context polled a 200-row query every 30 s. Measured on one
53
+ context, 1,000 reads of 200 rows: 614 MB retained and 200,200 tracked entities before;
54
+ 0.5 MB and 200 tracked entities now.
55
+
56
+ Tracked queries now do EF Core's identity resolution. When a row's entity type and primary
57
+ key (every column of a composite key) match an entity this context already tracks, the
58
+ query returns that instance instead of a new one. A long-lived context's memory is bounded
59
+ by the number of distinct rows it has loaded, not by how many times it reads them.
60
+
61
+ **Behaviour changes you may notice:**
62
+
63
+ - **The same instance comes back.** `findById`, `find`, `single`, `toList` and lazy or
64
+ `include()` loading on one context return the same object for the same row
65
+ (`a === b`).
66
+ - **A re-read does not refresh a tracked entity.** As in EF, database values do not
67
+ overwrite the tracked instance: its pending changes are kept, and its unchanged columns
68
+ keep the values from when it was first loaded, even if the row changed since. Before,
69
+ each query returned a new copy with the current row. To see the current row, use
70
+ `asNoTracking()`, `entry(e).getDatabaseValues()`, `reload()`, or a fresh context.
71
+ - **A re-read returns a deleted-but-unsaved entity** in its `delete` state, instead of a
72
+ second clean copy.
73
+ - **`include()` reloads the navigation** on every row the query returns, including
74
+ instances an earlier query loaded (with other filters, for example). It used to skip any
75
+ navigation already loaded on the instance, which only mattered once instances were
76
+ shared.
77
+
78
+ Unchanged: `asNoTracking()` (new instances, database values, nothing tracked). `select()`
79
+ projections, `raw()` SQL and full-text `search()` rows are tracked as before but never
80
+ identity-resolved, so a partial row never stands in for the whole entity. Saved entities
81
+ are still detached after `saveChanges()`. If an edit re-tracks such an older instance while
82
+ a newer clean copy of the row is tracked, the instance with the pending change is the one
83
+ queries return, and after it is saved the next read loads the row again.
84
+
85
+ **New: one-time warning for large tracked sets.** When a context tracks 10,000 entities it
86
+ logs one warning (through `configureLogging`'s logger) that names `asNoTracking()`,
87
+ `setQueryTrackingBehavior('no-track')`, `clearChangeTracker()` and per-request contexts.
88
+ Change the threshold with `context.setTrackedEntityWarningThreshold(n)` or
89
+ `MASTERRECORD_TRACKED_WARN_THRESHOLD=<n>`; `0` turns it off.
90
+
91
+ Internals: an index keyed by table + primary key sits beside `__trackedEntitiesMap` and is
92
+ kept in step by `__track`, `__untrack`, `__clearTracked`, `attach()` re-homing and the insert
93
+ path (once an INSERT assigns the key). A lookup that finds a stale entry drops it. `reload()`
94
+ now reads with `asNoTracking()`, because a tracked `findById` would return the instance
95
+ being reloaded.
96
+
97
+ New test: `test/identity-resolution.test.js`. Full suite: 453 pass, 0 fail, 22 live-DB
98
+ tests skipped (MySQL/Postgres were not run locally).
99
+
3
100
  ## v1.31.1 — better-sqlite3 range back to `>=12.6.2 <14`
4
101
 
5
102
  **Fix for a build break introduced in 1.31.0.** 1.31.0 raised the floor to
@@ -194,7 +194,9 @@ class EntityTrackerModel {
194
194
 
195
195
  // Fetch fresh from database
196
196
  const EntityClass = this.__context[this.__name];
197
- const fresh = await EntityClass.findById(...keyValues);
197
+ // No tracking: reading the values for THIS instance must not release it
198
+ // or track a second copy.
199
+ const fresh = await EntityClass.asNoTracking().findById(...keyValues);
198
200
  if (!fresh) {
199
201
  throw new Error(
200
202
  `Cannot reload: ${this.__name} with ${keys.map((k, i) => `${k}=${keyValues[i]}`).join(', ')} not found`
@@ -225,12 +227,6 @@ class EntityTrackerModel {
225
227
  if (typeof this.__context._refreshOriginalValues === 'function') {
226
228
  this.__context._refreshOriginalValues(this);
227
229
  }
228
- // findById tracked a second instance of this row; drop it so the
229
- // identity map holds only this entity (EF never tracks two copies).
230
- if (typeof this.__context.__untrack === 'function') {
231
- this.__context.__untrack([fresh]);
232
- }
233
-
234
230
  return this;
235
231
  };
236
232
 
@@ -324,11 +324,21 @@ class queryMethods{
324
324
  }
325
325
  }
326
326
 
327
+ /**
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
+ */
333
+ __identityResolvable(){
334
+ const s = this.__queryObject.script;
335
+ return !this.__noTracking && !s.raw && !s.select && !s.search;
336
+ }
337
+
327
338
  // build a single entity
328
- __singleEntityBuilder(dataModel){
339
+ __singleEntityBuilder(dataModel, resolvable = this.__identityResolvable()){
329
340
  const $that = this;
330
341
  if(dataModel){
331
- const ent = new entityTrackerModel();
332
342
  // TPH: materialize the row as its DERIVED type when the discriminator
333
343
  // names one (EF returns Cat/Dog instances from the Animal set).
334
344
  let def = $that.__entity;
@@ -337,6 +347,12 @@ class queryMethods{
337
347
  const derived = tph.derived.get(String(dataModel[tph.column]));
338
348
  if (derived) def = derived;
339
349
  }
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);
355
+ const ent = new entityTrackerModel();
340
356
  const mod = ent.build(dataModel, def, $that.__context);
341
357
  mod.__state = "track";
342
358
  if ($that.__noTracking) {
@@ -344,6 +360,12 @@ class queryMethods{
344
360
  // (__markDirty ignores no-tracking entities) and never track it.
345
361
  mod.__noTracking = true;
346
362
  } else {
363
+ if (!resolvable) {
364
+ // Projection / raw / search row: tracked as before, but kept
365
+ // out of the identity index so it never stands in for the
366
+ // whole entity.
367
+ Object.defineProperty(mod, '__noIdentity', { value: true, enumerable: false, writable: true, configurable: true });
368
+ }
347
369
  $that.__context.__track(mod);
348
370
  }
349
371
  return mod;
@@ -357,8 +379,9 @@ class queryMethods{
357
379
  const $that = this;
358
380
  const listArray = [];
359
381
  if(entityValue){
382
+ const resolvable = $that.__identityResolvable();
360
383
  for(let i = 0; i < entityValue.length; i++){
361
- listArray.push($that.__singleEntityBuilder(entityValue[i]));
384
+ listArray.push($that.__singleEntityBuilder(entityValue[i], resolvable));
362
385
  }
363
386
  return listArray;
364
387
  }else{
@@ -625,10 +648,11 @@ class queryMethods{
625
648
  if (!paths || !paths.length) return;
626
649
  const roots = Array.isArray(result) ? result : (result ? [result] : []);
627
650
  if (!roots.length) return;
651
+ const run = new Map(); // navigations this query has loaded (see __batchLoadNavigation)
628
652
  for (const path of paths) {
629
653
  let level = roots;
630
654
  for (const nav of path) {
631
- level = await this.__context.__batchLoadNavigation(level, nav, { ignoredFilters: this.__ignoredFilters });
655
+ level = await this.__context.__batchLoadNavigation(level, nav, { ignoredFilters: this.__ignoredFilters, run });
632
656
  if (!level.length) break;
633
657
  }
634
658
  }
@@ -1398,7 +1422,9 @@ class queryMethods{
1398
1422
 
1399
1423
  // Fetch fresh from database
1400
1424
  const EntityClass = this.__context[this.__name];
1401
- const fresh = await EntityClass.findById(primaryKeyValue);
1425
+ // No tracking: reading the values for THIS instance must not release it
1426
+ // or track a second copy.
1427
+ const fresh = await EntityClass.asNoTracking().findById(primaryKeyValue);
1402
1428
  if (!fresh) {
1403
1429
  throw new Error(
1404
1430
  `Cannot reload: ${this.__name} with ${primaryKey}=${primaryKeyValue} not found`
@@ -1428,11 +1454,6 @@ class queryMethods{
1428
1454
  if (typeof this.__context._refreshOriginalValues === 'function') {
1429
1455
  this.__context._refreshOriginalValues(this);
1430
1456
  }
1431
- // Drop the duplicate instance findById tracked (one copy per row).
1432
- if (typeof this.__context.__untrack === 'function') {
1433
- this.__context.__untrack([fresh]);
1434
- }
1435
-
1436
1457
  return this;
1437
1458
  };
1438
1459
 
package/context.js CHANGED
@@ -23,6 +23,7 @@ import MySQLEngine from './mySQLEngine.js';
23
23
  import insertManager from './insertManager.js';
24
24
  import deleteManager from './deleteManager.js';
25
25
  import EntityTrackerModel from './Entity/entityTrackerModel.js';
26
+ import FieldTransformer from './Entity/fieldTransformer.js';
26
27
  import { ConcurrencyError } from './errors.js';
27
28
  import { withRetry } from './resilience.js';
28
29
  import { log } from './logging.js';
@@ -136,6 +137,73 @@ function _poolKey(type, cfg) {
136
137
  return key;
137
138
  }
138
139
 
140
+ // ----------------------------------------------------------------------------
141
+ // One clean copy per row
142
+ // ----------------------------------------------------------------------------
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
+
149
+ // Entity definition -> its primary-key column names, or null when the type
150
+ // cannot be keyed (no key, or a key column that is a navigation).
151
+ const _identityColumnsCache = new WeakMap();
152
+
153
+ function _identityColumns(def) {
154
+ let cols = _identityColumnsCache.get(def);
155
+ if (cols !== undefined) return cols;
156
+ cols = tools.primaryKeys(def);
157
+ if (cols.length === 0 || cols.some(k => def[k].relationshipType === 'belongsTo')) cols = null;
158
+ _identityColumnsCache.set(def, cols);
159
+ return cols;
160
+ }
161
+
162
+ // One key column value as a string, or null when it cannot identify a row
163
+ // (unset, or a type with no reliable string form). Numbers and numeric strings
164
+ // map to the same text on purpose: Postgres returns BIGINT as "5" where the app
165
+ // assigned 5, and both name the same row. A column holds one type, so this
166
+ // cannot make two different rows equal.
167
+ function _identityPart(v) {
168
+ switch (typeof v) {
169
+ case 'string': return v === '' ? null : v;
170
+ case 'number': return Number.isFinite(v) ? String(v) : null;
171
+ case 'bigint': return String(v);
172
+ case 'boolean': return v ? 'true' : 'false';
173
+ case 'object':
174
+ if (v === null) return null;
175
+ if (v instanceof Date) { const t = v.getTime(); return Number.isNaN(t) ? null : `\u0001d${t}`; }
176
+ if (ArrayBuffer.isView(v)) return `\u0001x${Buffer.from(v.buffer, v.byteOffset, v.byteLength).toString('hex')}`;
177
+ return null;
178
+ default: return null;
179
+ }
180
+ }
181
+
182
+ // Identity key for one row of `def`. `read(column)` returns that column's value
183
+ // in its in-memory form. null = this row cannot be identity-resolved.
184
+ function _identityKey(def, read) {
185
+ const cols = def ? _identityColumns(def) : null;
186
+ if (!cols) return null;
187
+ if (cols.length === 1) {
188
+ const p = _identityPart(read(cols[0]));
189
+ return p === null ? null : `${def.__name}\u0000${p}`;
190
+ }
191
+ const parts = new Array(cols.length);
192
+ for (let i = 0; i < cols.length; i++) {
193
+ const p = _identityPart(read(cols[i]));
194
+ if (p === null) return null;
195
+ parts[i] = p;
196
+ }
197
+ return `${def.__name}\u0000${JSON.stringify(parts)}`;
198
+ }
199
+
200
+ /**
201
+ * Default size of a context's tracked set at which a one-time warning is
202
+ * logged. Override per context with setTrackedEntityWarningThreshold(n), or
203
+ * process-wide with MASTERRECORD_TRACKED_WARN_THRESHOLD=<n>; 0 turns it off.
204
+ */
205
+ const DEFAULT_TRACKED_WARN_THRESHOLD = 10000;
206
+
139
207
  // ============================================================================
140
208
  // CONSTANTS - Extract all magic numbers for maintainability
141
209
  // ============================================================================
@@ -257,6 +325,19 @@ class context {
257
325
  // writes whenever the two disagreed (a stale/colliding id in one but not the
258
326
  // other). All mutations go through __track / __untrack / __clearTracked.
259
327
  __trackedEntitiesMap = new Map(); // __ID -> entity; the authority
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.
332
+ // __identityKeys remembers which key each entity was indexed under, so it can
333
+ // be removed even after its key value changed. All three are kept in step by
334
+ // __track / __untrack / __clearTracked.
335
+ __identityIndex = new Map();
336
+ __identityCopies = new Map();
337
+ __identityKeys = new WeakMap();
338
+ // One-time "tracked set is large" warning (see __checkTrackedSize).
339
+ __trackedWarnThreshold = undefined; // undefined = not resolved yet
340
+ __trackedWarned = false;
260
341
  // Default query tracking behavior, EF-style (QueryTrackingBehavior).
261
342
  // 'track' — queries track their results (edits persist); the default.
262
343
  // 'no-track' — queries do NOT track (read-only; nothing retained). Set once
@@ -1942,23 +2023,48 @@ class context {
1942
2023
  const uniq = (arr) => [...new Set(arr.filter(v => v !== undefined && v !== null && typeof v !== 'function'))];
1943
2024
  const loadedOut = [];
1944
2025
  const pending = [];
2026
+ // opts.run (one per query): the parents whose `nav` this query has
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.
2030
+ let loadedThisRun = null;
2031
+ if (opts.run instanceof Map) {
2032
+ const runKey = `${ownerDef.__name}.${nav}`;
2033
+ loadedThisRun = opts.run.get(runKey);
2034
+ if (!loadedThisRun) { loadedThisRun = new WeakSet(); opts.run.set(runKey, loadedThisRun); }
2035
+ }
2036
+ const reloading = new Set(); // pending parents whose nav an earlier query loaded
1945
2037
  for (const p of list) {
1946
- if (this.isNavigationLoaded(p, nav)) {
2038
+ const loaded = this.isNavigationLoaded(p, nav);
2039
+ if (loaded && (!loadedThisRun || loadedThisRun.has(p))) {
1947
2040
  const v = slotOf(p)['_' + nav];
1948
2041
  if (Array.isArray(v)) loadedOut.push(...v); else if (v && typeof v === 'object') loadedOut.push(v);
1949
- } else pending.push(p);
2042
+ } else {
2043
+ pending.push(p);
2044
+ if (loaded) reloading.add(p);
2045
+ }
1950
2046
  }
2047
+ if (loadedThisRun) for (const p of pending) loadedThisRun.add(p);
1951
2048
  if (!pending.length) return loadedOut;
1952
2049
 
1953
2050
  if (isBt) {
1954
2051
  const parentSet = this._dbsetByName(def.foreignTable);
1955
2052
  if (!parentSet) throw new Error(`masterrecord: entity '${def.foreignTable}' (referenced by ${ownerDef.__name}.${nav}) is not registered on this context.`);
1956
2053
  const pk = tools.getPrimaryKeyObject(parentSet.__entity) || 'id';
1957
- const keys = uniq(pending.map(p => tools.foreignKeyValue(p, nav)));
2054
+ // On a reload the navigation slot holds the earlier result (null when
2055
+ // that query's filters hid the parent), so read the FK column itself.
2056
+ const fkOf = (p) => {
2057
+ if (reloading.has(p) && def.foreignKey) {
2058
+ const fk = tools.dataValue(p, def.foreignKey);
2059
+ if (fk === null || (fk !== undefined && typeof fk !== 'object' && typeof fk !== 'function')) return fk;
2060
+ }
2061
+ return tools.foreignKeyValue(p, nav);
2062
+ };
2063
+ const keys = uniq(pending.map(fkOf));
1958
2064
  const byKey = new Map();
1959
2065
  for (const c of chunks(keys)) for (const t of await withFilters(parentSet).where(`r => $$.includes(r.${pk})`, c).toList()) byKey.set(String(tools.dataValue(t, pk)), t);
1960
2066
  for (const p of pending) {
1961
- const k = tools.foreignKeyValue(p, nav);
2067
+ const k = fkOf(p);
1962
2068
  const t = (k === undefined || k === null) ? null : (byKey.get(String(k)) || null);
1963
2069
  setSlot(p, t);
1964
2070
  if (t) loadedOut.push(t);
@@ -2865,6 +2971,11 @@ class context {
2865
2971
  } catch (attachErr) {
2866
2972
  console.error(`[Context] Could not attach change-tracking to inserted ${entity.__name || 'entity'}: ${attachErr.message}`);
2867
2973
  }
2974
+ // The INSERT may have just assigned the key (auto-increment, read
2975
+ // back). Index the entity under it while it is still tracked.
2976
+ if (entity.__ID != null && this.__trackedEntitiesMap.get(entity.__ID) === entity) {
2977
+ this.__indexIdentity(entity);
2978
+ }
2868
2979
  }
2869
2980
  }
2870
2981
 
@@ -3566,6 +3677,7 @@ class context {
3566
3677
  if (!e) continue;
3567
3678
  if (e.__ID != null) this.__trackedEntitiesMap.delete(e.__ID);
3568
3679
  this.__dirtyEntities.delete(e); // keep the dirty index in lockstep
3680
+ this.__unindexIdentity(e); // and the identity index
3569
3681
  }
3570
3682
  }
3571
3683
 
@@ -4055,6 +4167,7 @@ class context {
4055
4167
  if (previous && previous !== this && entity.__ID &&
4056
4168
  previous.__trackedEntitiesMap && previous.__trackedEntitiesMap.has(entity.__ID)) {
4057
4169
  previous.__trackedEntitiesMap.delete(entity.__ID); // list view follows the map
4170
+ if (typeof previous.__unindexIdentity === 'function') previous.__unindexIdentity(entity);
4058
4171
  }
4059
4172
 
4060
4173
  // Mark entity as modified
@@ -4197,7 +4310,14 @@ class context {
4197
4310
  // the list view derives from it, so they cannot desynchronise.
4198
4311
  const wasTracked = this.__trackedEntitiesMap.has(model.__ID);
4199
4312
  this.__trackedEntitiesMap.set(model.__ID, model);
4200
- if (!wasTracked) this._emit('tracked', { context: this, entity: model });
4313
+ // Every path that tracks or re-tracks an entity (queries, setters,
4314
+ // add/remove, attach) comes through here, so this also picks up a key
4315
+ // that was assigned after the entity was first tracked.
4316
+ this.__indexIdentity(model);
4317
+ if (!wasTracked) {
4318
+ this._emit('tracked', { context: this, entity: model });
4319
+ this.__checkTrackedSize();
4320
+ }
4201
4321
  // Robustness: if the entity being tracked is ALREADY dirty, enqueue it in
4202
4322
  // the dirty index too. This guarantees the index is complete no matter
4203
4323
  // how an entity gets tracked (setter, add/remove, or a direct __track
@@ -4253,6 +4373,144 @@ class context {
4253
4373
  __clearTracked() {
4254
4374
  this.__trackedEntitiesMap.clear(); // sole registry; the list view follows
4255
4375
  this.__dirtyEntities.clear();
4376
+ this.__identityIndex.clear();
4377
+ this.__identityCopies.clear();
4378
+ this.__identityKeys = new WeakMap();
4379
+ }
4380
+
4381
+ // ---- One clean copy per row ----------------------------------------------
4382
+
4383
+ /**
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.
4388
+ *
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.
4393
+ * @private
4394
+ */
4395
+ __indexIdentity(model) {
4396
+ if (!model || !model.__entity) return;
4397
+ const key = (model.__noTracking || model.__noIdentity)
4398
+ ? null
4399
+ : _identityKey(model.__entity, (c) => tools.dataValue(model, c));
4400
+ const prev = this.__identityKeys.get(model);
4401
+ if (prev !== undefined && prev !== key) this.__unindexIdentity(model);
4402
+ if (key === null) return;
4403
+ const holder = this.__identityIndex.get(key);
4404
+ if (holder !== undefined && holder !== model && this.__isLiveIdentity(holder, key)) {
4405
+ const modelDirty = context._isEntityDirty(model);
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
4414
+ }
4415
+ if (this.__identityCopies.get(key) === model) this.__identityCopies.delete(key);
4416
+ this.__identityIndex.set(key, model);
4417
+ this.__identityKeys.set(model, key);
4418
+ }
4419
+
4420
+ /** Remove an entity from the identity index (it stays tracked). @private */
4421
+ __unindexIdentity(model) {
4422
+ if (!model || typeof model !== 'object') return;
4423
+ const key = this.__identityKeys.get(model);
4424
+ if (key === undefined) return;
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
+ }
4435
+ }
4436
+
4437
+ /** Is `e` still tracked here and does its current key still equal `key`? @private */
4438
+ __isLiveIdentity(e, key) {
4439
+ return e.__ID != null
4440
+ && this.__trackedEntitiesMap.get(e.__ID) === e
4441
+ && !e.__noTracking
4442
+ && _identityKey(e.__entity, (c) => tools.dataValue(e, c)) === key;
4443
+ }
4444
+
4445
+ /**
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.
4451
+ * @private
4452
+ */
4453
+ __releaseCleanCopy(def, row) {
4454
+ if (!row || (this.__identityIndex.size === 0 && this.__identityCopies.size === 0)) return;
4455
+ let key;
4456
+ try {
4457
+ key = _identityKey(def, (c) => FieldTransformer.fromDatabase(row[c], def[c], def.__name, c));
4458
+ } catch (_) {
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
+ }
4469
+ }
4470
+
4471
+ /**
4472
+ * Log a warning, once per context, when the tracked set reaches the
4473
+ * threshold. A context that keeps growing past this is usually a long-lived
4474
+ * context used for reads.
4475
+ * @private
4476
+ */
4477
+ __checkTrackedSize() {
4478
+ if (this.__trackedWarned) return;
4479
+ let threshold = this.__trackedWarnThreshold;
4480
+ if (threshold === undefined) {
4481
+ const env = process.env.MASTERRECORD_TRACKED_WARN_THRESHOLD;
4482
+ const n = env === undefined || env === '' ? NaN : Number(env);
4483
+ threshold = Number.isFinite(n) && n >= 0 ? n : DEFAULT_TRACKED_WARN_THRESHOLD;
4484
+ this.__trackedWarnThreshold = threshold;
4485
+ }
4486
+ if (!threshold || this.__trackedEntitiesMap.size < threshold) return;
4487
+ this.__trackedWarned = true;
4488
+ log('warn',
4489
+ `[masterrecord] WARNING: context '${this.__name}' is tracking ${this.__trackedEntitiesMap.size} entities ` +
4490
+ `(warning threshold ${threshold}). Every entity a tracked query returns stays in memory until it is ` +
4491
+ `saved, detached or the context is closed. If this context lives for the whole process, read with ` +
4492
+ `asNoTracking() (or setQueryTrackingBehavior('no-track') on the context), call clearChangeTracker() ` +
4493
+ `after read-only work, or create a context per request / unit of work (ContextPool). ` +
4494
+ `Change the threshold with setTrackedEntityWarningThreshold(n) or ` +
4495
+ `MASTERRECORD_TRACKED_WARN_THRESHOLD=<n>; 0 turns the warning off.`
4496
+ );
4497
+ }
4498
+
4499
+ /**
4500
+ * Set the tracked-set size at which this context logs its one-time
4501
+ * "tracking many entities" warning (default 10,000, or
4502
+ * MASTERRECORD_TRACKED_WARN_THRESHOLD). 0, null or false turns it off.
4503
+ * Setting it re-arms the warning.
4504
+ */
4505
+ setTrackedEntityWarningThreshold(n) {
4506
+ if (n === null || n === false) n = 0;
4507
+ if (typeof n !== 'number' || !Number.isFinite(n) || n < 0) {
4508
+ throw new TypeError(`masterrecord: setTrackedEntityWarningThreshold expects a non-negative number, got ${JSON.stringify(n)}`);
4509
+ }
4510
+ this.__trackedWarnThreshold = n;
4511
+ this.__trackedWarned = false;
4512
+ this.__checkTrackedSize();
4513
+ return this;
4256
4514
  }
4257
4515
 
4258
4516
  /**
@@ -4261,7 +4519,8 @@ class context {
4261
4519
  *
4262
4520
  * A context is a unit of work and is safest scoped per request. If you must
4263
4521
  * reuse a long-lived (e.g. singleton) context, read-only queries still
4264
- * auto-track their results, and those clean entities accumulate — call this
4522
+ * auto-track their results: one clean copy per distinct row, which still
4523
+ * grows with every new row read — call this
4265
4524
  * after a read-only operation to release them and keep the tracked set
4266
4525
  * bounded. It drops PENDING changes too, so only call it when there is
4267
4526
  * nothing dirty you still intend to save.
@@ -19,7 +19,27 @@ user.blocked = 1; // dirty
19
19
  await db.saveChanges(); // one UPDATE
20
20
  ```
21
21
 
22
- ---
22
+ ### Re-reads: current data, one clean copy per row (since 1.32.2)
23
+
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
+
26
+ - A read sees writes made any other way: `executeUpdate`, another context, another process.
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 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.
31
+
32
+ ```javascript
33
+ const a = await db.User.findById(1);
34
+ a.name = 'pending';
35
+ const b = await db.User.where('u => u.id == $$', 1).single();
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
40
+ ```
41
+
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.
23
43
 
24
44
  ## Controlling what gets tracked (EF's `QueryTrackingBehavior`)
25
45
 
@@ -61,6 +81,8 @@ If you set a `no-track` default on a shared/long-lived context, remember every w
61
81
 
62
82
  `clearChangeTracker()` drops pending changes, so on a shared context it can destroy another in-flight request's writes — it is not a safe per-request mitigation. Use request-scoped contexts or `asNoTracking()` instead.
63
83
 
84
+ **Large tracked sets are reported once.** When a context's tracked set reaches 10,000 entities it logs one warning (through `configureLogging`'s logger) naming `asNoTracking()`, `clearChangeTracker()` and per-request contexts. Change the threshold per context with `context.setTrackedEntityWarningThreshold(n)` or process-wide with `MASTERRECORD_TRACKED_WARN_THRESHOLD=<n>`; `0` turns it off.
85
+
64
86
  ---
65
87
 
66
88
  ## Scoping a context (the memory bound)
@@ -249,7 +271,7 @@ Transient errors (deadlocks, lock timeouts, busy SQLite, dropped connections) ar
249
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):
250
272
 
251
273
  - **Lost writes** — one request's `saveChanges()` interacting with another's tracked entities.
252
- - **Unbounded memory** — read-only queries track results that are never released.
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.
253
275
  - **Undefined behavior** under concurrent access (EF: "application crashes and data corruption").
254
276
 
255
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.
@@ -88,6 +88,7 @@ context.User.where(u => $$.includes(u.id), [1, 2, 3]).toList();
88
88
  | `context.setRetryOnFailure(opts)` | `EnableRetryOnFailure` | Transient-error retry |
89
89
  | `await context.healthCheck()` / `await context.canConnect()` | `Database.CanConnect` / health check | `{ healthy, engine, latencyMs, version, … }`; never throws |
90
90
  | `context.setQueryTrackingBehavior('no-track')` / `clearChangeTracker()` / `reset()` / `close()` | `QueryTrackingBehavior` / `ChangeTracker.Clear` / `Dispose` | Tracker lifetime |
91
+ | `context.setTrackedEntityWarningThreshold(n)` | — | One-time warning when the tracked set reaches `n` (default 10,000; `0` = off; or `MASTERRECORD_TRACKED_WARN_THRESHOLD`) |
91
92
  | `db.rowVersion()` / `db.concurrencyToken()` (model builder) | `IsRowVersion` / `IsConcurrencyToken` | Optimistic concurrency (throws `ConcurrencyError`) |
92
93
  | `db.belongsTo(...).onDelete('cascade'\|'restrict'\|'setNull'\|'noAction')` / `.excludeForeignKeyFromMigrations()` | `OnDelete` / EF 11 | FK constraint behavior |
93
94
  | `db.defaultSql('CURRENT_TIMESTAMP')` | `HasDefaultValueSql` | Database-side default expression (read back after insert) |
package/mySQLEngine.js CHANGED
@@ -195,15 +195,23 @@ class MySQLEngine {
195
195
  // by table + exact column signature and emit one statement per group.
196
196
  // No NULL-padding to a column union — that would override DB-level
197
197
  // column defaults.
198
- const groups = new Map();
198
+ //
199
+ // Only CONSECUTIVE rows share a statement: pooling all rows of a
200
+ // signature would hand out auto-increment ids out of add order, unlike
201
+ // SQLite, the single-insert path and the per-row fallback.
202
+ const groups = [];
203
+ let lastKey;
199
204
  for (const row of rows) {
200
205
  const key = `${row.sql.tableName}\u0000${row.sql.columns}`;
201
- if (!groups.has(key)) groups.set(key, []);
202
- groups.get(key).push(row);
206
+ if (groups.length === 0 || key !== lastKey) {
207
+ groups.push([]);
208
+ lastKey = key;
209
+ }
210
+ groups[groups.length - 1].push(row);
203
211
  }
204
212
 
205
213
  const results = new Array(entities.length);
206
- for (const group of groups.values()) {
214
+ for (const group of groups) {
207
215
  const first = group[0].sql;
208
216
  const valueGroups = [];
209
217
  const allParams = [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "masterrecord",
3
- "version": "1.31.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",
package/postgresEngine.js CHANGED
@@ -248,15 +248,23 @@ class postgresEngine {
248
248
  // by table + exact column signature and emit one statement per group.
249
249
  // No NULL-padding to a column union — that would override DB-level
250
250
  // column defaults.
251
- const groups = new Map();
251
+ //
252
+ // Only CONSECUTIVE rows share a statement: pooling all rows of a
253
+ // signature would hand out auto-increment ids out of add order, unlike
254
+ // SQLite, the single-insert path and the per-row fallback.
255
+ const groups = [];
256
+ let lastKey;
252
257
  for (const row of rows) {
253
258
  const key = `${row.sql.tableName} ${row.sql.columns}`;
254
- if (!groups.has(key)) groups.set(key, []);
255
- groups.get(key).push(row);
259
+ if (groups.length === 0 || key !== lastKey) {
260
+ groups.push([]);
261
+ lastKey = key;
262
+ }
263
+ groups[groups.length - 1].push(row);
256
264
  }
257
265
 
258
266
  const results = new Array(entities.length);
259
- for (const group of groups.values()) {
267
+ for (const group of groups) {
260
268
  const first = group[0].sql;
261
269
  const primaryKey = tools.getPrimaryKeyObject(group[0].entity.__entity);
262
270