masterrecord 1.5.9 → 1.5.10
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 +17 -0
- package/Entity/entityTrackerModel.js +8 -0
- package/context.js +111 -51
- package/package.json +1 -1
package/CHANGES.md
CHANGED
|
@@ -1,5 +1,22 @@
|
|
|
1
1
|
# MasterRecord Changelog
|
|
2
2
|
|
|
3
|
+
## v1.5.10 — saveChanges() is a proper unit of work: commits only its change set (real shared-context lost-write fix)
|
|
4
|
+
|
|
5
|
+
**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.
|
|
6
|
+
|
|
7
|
+
**Fix (unit-of-work model, like EF Core / Hibernate):**
|
|
8
|
+
- `saveChanges()` now builds a **change set of only the dirty entities** (insert/modified/delete) and commits **just that**. It never snapshots, processes, or untracks the rest of the tracked list. **An empty save is a true no-op** that touches no other unit of work's entities.
|
|
9
|
+
- It **releases only the rows it actually wrote**, and only those; unrelated tracked (clean) entities are left alone.
|
|
10
|
+
- Every setter bumps a per-entity **mutation version**; the version is captured before the async write and the post-write reset **skips any entity re-mutated in flight**, so a mutation that lands during the write stays dirty and its UPDATE still fires (no clobber).
|
|
11
|
+
- On failure the change set is **left tracked and dirty** (the caller gets the rejection) — never silently dropped.
|
|
12
|
+
- This upholds the invariant: *an entity tracked and dirty when `saveChanges()` is called is always written or the call rejects; it never resolves `true` leaving the entity unwritten.*
|
|
13
|
+
|
|
14
|
+
**New — lifetime control for long-lived contexts:** `context.clearChangeTracker()` (detach all, à la `session.clear()` / `ChangeTracker.Clear()`) and `context.detach(entity)`. Because saves no longer sweep the whole list, a reused/singleton context's read-only query results stay tracked — call `clearChangeTracker()` after read-only work to keep the tracked set bounded.
|
|
15
|
+
|
|
16
|
+
**Strongly recommended:** scope a context **per request/unit of work**, not as a process singleton. This fix removes the silent lost write and the cross-caller corruption, but a context is a unit of work; a scoped/transient context per request is the robust pattern and avoids the tracked-set growth entirely.
|
|
17
|
+
|
|
18
|
+
New/expanded tests in `test/shared-context-untrack-preserves-dirty.test.js`: an empty save drops nothing; a save commits only its change set and leaves unrelated tracked rows alone; a mutation during the async write still persists. Full suite green (0 fail, 299 pass, 20 gated skipped); 0 lint errors.
|
|
19
|
+
|
|
3
20
|
## v1.5.9 — saveChanges() no longer sweeps away a concurrently-mutated entity (shared/singleton context lost write)
|
|
4
21
|
|
|
5
22
|
**Bug (silent lost write on a shared context):** queried rows are auto-tracked into the context's tracked-entity list, and `saveChanges()` snapshots that whole list, writes the dirty rows, and `__untrack()`s the entire snapshot. When one context instance is shared across concurrent units of work (e.g. a **singleton context** serving many requests), request A's save snapshots a row that request B loaded (clean), B mutates it while A's save is in flight, and A then untracks the snapshot — removing B's now-dirty row from tracking. B's own `saveChanges()` then finds it untracked and **silently issues no UPDATE**. The batch wasn't empty, so the "no tracked entities" warning never fired and the handler returned success (observed as an admin plan change round-tripping back to `free`, and other vanished updates).
|
|
@@ -368,6 +368,13 @@ class EntityTrackerModel {
|
|
|
368
368
|
}
|
|
369
369
|
|
|
370
370
|
this.__state = "modified";
|
|
371
|
+
// Bump a monotonic mutation version on every write. saveChanges()
|
|
372
|
+
// captures this before its async DB write and, afterwards, only
|
|
373
|
+
// resets the entity to clean if the version is unchanged — so a
|
|
374
|
+
// mutation that lands DURING the write (a shared/singleton context
|
|
375
|
+
// serving concurrent requests) keeps the entity dirty and its own
|
|
376
|
+
// save still issues the UPDATE, instead of being silently reset.
|
|
377
|
+
this.__version = (this.__version || 0) + 1;
|
|
371
378
|
|
|
372
379
|
// belongsTo FK columns appear in the DB row but not as a
|
|
373
380
|
// top-level key in `__entity`; translate the dirty field to the
|
|
@@ -516,6 +523,7 @@ class EntityTrackerModel {
|
|
|
516
523
|
set: function(value) {
|
|
517
524
|
if(typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" ){
|
|
518
525
|
modelClass.__state = "modified";
|
|
526
|
+
modelClass.__version = (modelClass.__version || 0) + 1;
|
|
519
527
|
modelClass.__dirtyFields.push(entityField);
|
|
520
528
|
modelClass.__context.__track(modelClass);
|
|
521
529
|
}
|
package/context.js
CHANGED
|
@@ -1868,6 +1868,11 @@ class context {
|
|
|
1868
1868
|
}
|
|
1869
1869
|
}
|
|
1870
1870
|
|
|
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
|
+
|
|
1871
1876
|
if (entities.length === 1) {
|
|
1872
1877
|
// Single insert - use existing insertManager (already sets ID)
|
|
1873
1878
|
const insert = new insertManager(this._SQLEngine, this._isModelValid, this.__entities);
|
|
@@ -1959,8 +1964,14 @@ class context {
|
|
|
1959
1964
|
// from the database.
|
|
1960
1965
|
const tracker = new EntityTrackerModel();
|
|
1961
1966
|
for (const entity of entities) {
|
|
1962
|
-
entity
|
|
1963
|
-
|
|
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
|
+
}
|
|
1964
1975
|
try {
|
|
1965
1976
|
tracker.attachTrackingTo(entity);
|
|
1966
1977
|
} catch (attachErr) {
|
|
@@ -1983,6 +1994,13 @@ class context {
|
|
|
1983
1994
|
}
|
|
1984
1995
|
}
|
|
1985
1996
|
|
|
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
|
+
|
|
1986
2004
|
if (entities.length === 1) {
|
|
1987
2005
|
// Single update - use existing logic.
|
|
1988
2006
|
// NOTE: the second argument must be `__entity` (double underscore).
|
|
@@ -2046,13 +2064,14 @@ class context {
|
|
|
2046
2064
|
}
|
|
2047
2065
|
|
|
2048
2066
|
// Reset tracker state on the entity itself so a subsequent
|
|
2049
|
-
// saveChanges() doesn't re-emit the same UPDATE for the same fields
|
|
2050
|
-
//
|
|
2051
|
-
//
|
|
2052
|
-
//
|
|
2053
|
-
// be
|
|
2054
|
-
//
|
|
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.
|
|
2055
2073
|
for (const entity of entities) {
|
|
2074
|
+
if ((entity.__version || 0) !== __preWriteVersion.get(entity)) continue;
|
|
2056
2075
|
entity.__state = 'track';
|
|
2057
2076
|
entity.__dirtyFields = [];
|
|
2058
2077
|
}
|
|
@@ -2177,38 +2196,50 @@ class context {
|
|
|
2177
2196
|
|
|
2178
2197
|
async _saveChangesExclusive() {
|
|
2179
2198
|
await this._ensureReady();
|
|
2180
|
-
// Snapshot the batch: entities add()ed while this save is in flight
|
|
2181
|
-
// belong to the NEXT queued save, and must not be cleared by this one.
|
|
2182
|
-
const tracked = this.__trackedEntities.slice();
|
|
2183
|
-
try {
|
|
2184
|
-
// Loud guard against silent data loss: if entities with unsaved
|
|
2185
|
-
// changes are tracked by a DIFFERENT context instance, THIS
|
|
2186
|
-
// saveChanges() will not write them. Warn loudly (this is the #1
|
|
2187
|
-
// cause of "saveChanges succeeded but nothing was written").
|
|
2188
|
-
this._warnForeignDirty('saveChanges()');
|
|
2189
|
-
|
|
2190
|
-
if (tracked.length === 0) {
|
|
2191
|
-
console.log('[Context] No tracked entities to save');
|
|
2192
|
-
return true;
|
|
2193
|
-
}
|
|
2194
|
-
|
|
2195
|
-
// Performance: Collect affected tables for cache invalidation (single pass)
|
|
2196
|
-
const affectedTables = new Set();
|
|
2197
|
-
for (const entity of tracked) {
|
|
2198
|
-
if (entity.__name) {
|
|
2199
|
-
affectedTables.add(entity.__name);
|
|
2200
|
-
}
|
|
2201
|
-
}
|
|
2202
2199
|
|
|
2203
|
-
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
|
|
2207
|
-
|
|
2200
|
+
// Loud guard against silent data loss across DIFFERENT context instances.
|
|
2201
|
+
this._warnForeignDirty('saveChanges()');
|
|
2202
|
+
|
|
2203
|
+
// A save commits ONLY its own CHANGE SET — the entities that are dirty
|
|
2204
|
+
// (insert/modified/delete) right now — and must NEVER snapshot, process,
|
|
2205
|
+
// or untrack the rest of the tracked list. This is the unit-of-work
|
|
2206
|
+
// model real ORMs use, and it is essential on a shared/singleton context
|
|
2207
|
+
// serving concurrent requests:
|
|
2208
|
+
// 1. Read-only queries auto-track their results, so a handler that just
|
|
2209
|
+
// `.toList()`s a table leaves thousands of clean entities tracked.
|
|
2210
|
+
// Sweeping the whole list would do O(N) work over unrelated rows on
|
|
2211
|
+
// every save.
|
|
2212
|
+
// 2. If a save untracked the whole list, one caller's save — even an
|
|
2213
|
+
// EMPTY one with nothing dirty — would drop another in-flight
|
|
2214
|
+
// caller's freshly loaded/mutated entity from tracking, and that
|
|
2215
|
+
// caller's own saveChanges() would then find nothing to write and
|
|
2216
|
+
// silently lose the UPDATE (returning true). Committing only the
|
|
2217
|
+
// change set makes an empty save a true no-op that never touches
|
|
2218
|
+
// another unit of work's entities.
|
|
2219
|
+
const changeSet = this.__trackedEntities.filter(
|
|
2220
|
+
e => e && e.__state && e.__state !== 'track'
|
|
2221
|
+
);
|
|
2222
|
+
|
|
2223
|
+
if (changeSet.length === 0) {
|
|
2224
|
+
// Nothing dirty — do NOT touch the shared tracked list.
|
|
2225
|
+
return true;
|
|
2226
|
+
}
|
|
2227
|
+
|
|
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); }
|
|
2232
|
+
|
|
2233
|
+
const affectedTables = new Set();
|
|
2234
|
+
for (const e of changeSet) { if (e.__name) affectedTables.add(e.__name); }
|
|
2235
|
+
|
|
2236
|
+
try {
|
|
2237
|
+
// Atomicity: wrap the change set in a single transaction so a partial
|
|
2238
|
+
// failure rolls it back.
|
|
2208
2239
|
if (this.isSQLite || this.isMySQL || this.isPostgres) {
|
|
2209
2240
|
await this._SQLEngine.startTransaction();
|
|
2210
2241
|
try {
|
|
2211
|
-
await this._processTrackedEntities(
|
|
2242
|
+
await this._processTrackedEntities(changeSet);
|
|
2212
2243
|
this.__clearErrorHandler();
|
|
2213
2244
|
await this._SQLEngine.endTransaction();
|
|
2214
2245
|
} catch (error) {
|
|
@@ -2217,19 +2248,25 @@ class context {
|
|
|
2217
2248
|
}
|
|
2218
2249
|
}
|
|
2219
2250
|
|
|
2220
|
-
// Invalidate query cache for affected tables
|
|
2221
2251
|
for (const tableName of affectedTables) {
|
|
2222
2252
|
this._queryCache.invalidateTable(tableName);
|
|
2223
2253
|
}
|
|
2224
2254
|
|
|
2225
|
-
//
|
|
2226
|
-
|
|
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);
|
|
2227
2264
|
return true;
|
|
2228
2265
|
} catch (error) {
|
|
2229
|
-
// Clean up on error (this batch only)
|
|
2230
2266
|
this.__clearErrorHandler();
|
|
2231
|
-
|
|
2232
|
-
|
|
2267
|
+
// The transaction rolled back, so nothing was committed. Leave the
|
|
2268
|
+
// change set tracked and dirty so a retry can persist it — never
|
|
2269
|
+
// silently drop a pending write (the caller sees the rejection).
|
|
2233
2270
|
console.error('[Context] Failed to save changes:', error);
|
|
2234
2271
|
throw error;
|
|
2235
2272
|
}
|
|
@@ -2259,16 +2296,14 @@ class context {
|
|
|
2259
2296
|
*/
|
|
2260
2297
|
__untrack(batch) {
|
|
2261
2298
|
if (!batch || !batch.length) return;
|
|
2262
|
-
|
|
2263
|
-
|
|
2264
|
-
|
|
2265
|
-
|
|
2266
|
-
|
|
2267
|
-
}
|
|
2268
|
-
if (drop.size === 0) 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);
|
|
2269
2304
|
this.__trackedEntities = this.__trackedEntities.filter(e => !drop.has(e));
|
|
2270
|
-
for (const e of
|
|
2271
|
-
if (e.__ID !== undefined) this.__trackedEntitiesMap.delete(e.__ID);
|
|
2305
|
+
for (const e of batch) {
|
|
2306
|
+
if (e && e.__ID !== undefined) this.__trackedEntitiesMap.delete(e.__ID);
|
|
2272
2307
|
}
|
|
2273
2308
|
}
|
|
2274
2309
|
|
|
@@ -2887,6 +2922,31 @@ class context {
|
|
|
2887
2922
|
this.__trackedEntitiesMap.clear(); // Clear Map for proper garbage collection
|
|
2888
2923
|
}
|
|
2889
2924
|
|
|
2925
|
+
/**
|
|
2926
|
+
* Detach ALL entities from change tracking (like Hibernate's
|
|
2927
|
+
* `session.clear()` / EF Core's `ChangeTracker.Clear()`).
|
|
2928
|
+
*
|
|
2929
|
+
* A context is a unit of work and is safest scoped per request. If you must
|
|
2930
|
+
* reuse a long-lived (e.g. singleton) context, read-only queries still
|
|
2931
|
+
* auto-track their results, and those clean entities accumulate — call this
|
|
2932
|
+
* after a read-only operation to release them and keep the tracked set
|
|
2933
|
+
* bounded. It drops PENDING changes too, so only call it when there is
|
|
2934
|
+
* nothing dirty you still intend to save.
|
|
2935
|
+
*/
|
|
2936
|
+
clearChangeTracker() {
|
|
2937
|
+
this.__clearTracked();
|
|
2938
|
+
return this;
|
|
2939
|
+
}
|
|
2940
|
+
|
|
2941
|
+
/**
|
|
2942
|
+
* Detach a single entity from change tracking. Pending changes on it are
|
|
2943
|
+
* dropped and it is no longer part of any future saveChanges().
|
|
2944
|
+
*/
|
|
2945
|
+
detach(entity) {
|
|
2946
|
+
if (entity) this.__untrack([entity]);
|
|
2947
|
+
return this;
|
|
2948
|
+
}
|
|
2949
|
+
|
|
2890
2950
|
// ------------------------------------------------------------------
|
|
2891
2951
|
// Cross-context change-tracking guards (silent-data-loss prevention)
|
|
2892
2952
|
// ------------------------------------------------------------------
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "masterrecord",
|
|
3
|
-
"version": "1.5.
|
|
3
|
+
"version": "1.5.10",
|
|
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",
|