masterrecord 1.5.9 → 1.5.11

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,36 @@
1
1
  # MasterRecord Changelog
2
2
 
3
+ ## v1.5.11 — deletes are released after commit (fix 1.5.10 "zombie delete" latch); lifecycle reconciliation centralized
4
+
5
+ **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.
6
+
7
+ **Root cause (design):** entity-lifecycle transitions were **scattered** across three batch processors plus a release filter, and the delete path had no reset — an asymmetry that made the gap inevitable.
8
+
9
+ **Fix (Unit-of-Work reconciliation, one place, one rule):** `saveChanges()` now captures each committed entity's mutation **generation** at flush time and, after the transaction commits, runs a single `_reconcileFlushed()` step with one uniform rule for insert/update/delete:
10
+ - **re-mutated in flight** (generation changed) → leave it in its new pending state so the next save persists it;
11
+ - **otherwise committed cleanly** → insert/modified reset to `'track'` then **detached**; delete **detached** (the row is gone).
12
+
13
+ The per-processor state resets were removed, so there is no longer any state-specific branch that can strand an entity. This also fixes the falsy-`__state` edge and corrects the stale `__untrack` doc comment.
14
+
15
+ New tests: `test/delete-release-no-zombie.test.js` — a committed delete is detached (no replay); repeated update-then-delete does not latch (UPDATEs keep persisting); a mixed insert+update+delete change set reconciles all three. Full suite green (0 fail, 302 pass, 20 gated skipped); 0 lint errors.
16
+
17
+ ## v1.5.10 — saveChanges() is a proper unit of work: commits only its change set (real shared-context lost-write fix)
18
+
19
+ **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.
20
+
21
+ **Fix (unit-of-work model, like EF Core / Hibernate):**
22
+ - `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.
23
+ - It **releases only the rows it actually wrote**, and only those; unrelated tracked (clean) entities are left alone.
24
+ - 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).
25
+ - On failure the change set is **left tracked and dirty** (the caller gets the rejection) — never silently dropped.
26
+ - 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.*
27
+
28
+ **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.
29
+
30
+ **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.
31
+
32
+ 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.
33
+
3
34
  ## v1.5.9 — saveChanges() no longer sweeps away a concurrently-mutated entity (shared/singleton context lost write)
4
35
 
5
36
  **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
@@ -1947,20 +1947,14 @@ class context {
1947
1947
  }
1948
1948
  }
1949
1949
 
1950
- // Transition inserted entities to tracked state so subsequent
1951
- // property changes trigger UPDATE instead of a second INSERT.
1952
- //
1953
- // A plain `new Model()` passed to add() has ordinary own-property
1954
- // fields, NOT the change-tracking accessors a queried entity has — so
1955
- // without this a later edit (`row.name = 'x'`) is a silent write that
1956
- // never marks the entity modified, and the change is dropped on the next
1957
- // saveChanges(). attachTrackingTo() installs those accessors in place so
1958
- // the just-inserted entity is update-trackable, exactly like one loaded
1959
- // from the database.
1950
+ // Install change-tracking accessors on each inserted entity so later
1951
+ // edits are tracked: a plain `new Model()` passed to add() has ordinary
1952
+ // own-property fields, NOT the accessors a queried entity has, so without
1953
+ // this a later `row.name = 'x'` would be a silent write. Lifecycle state
1954
+ // (insert -> clean, then detached) is transitioned centrally in
1955
+ // _reconcileFlushed after the transaction commits — not here.
1960
1956
  const tracker = new EntityTrackerModel();
1961
1957
  for (const entity of entities) {
1962
- entity.__state = 'track';
1963
- entity.__dirtyFields = [];
1964
1958
  try {
1965
1959
  tracker.attachTrackingTo(entity);
1966
1960
  } catch (attachErr) {
@@ -2045,17 +2039,11 @@ class context {
2045
2039
  }
2046
2040
  }
2047
2041
 
2048
- // Reset tracker state on the entity itself so a subsequent
2049
- // saveChanges() doesn't re-emit the same UPDATE for the same fields.
2050
- // Previously only _processBatchInserts did this, not updates —
2051
- // leaving __state="modified" and __dirtyFields populated. On the
2052
- // next modification of a different field, the stale fields would
2053
- // be re-written, silently overwriting any concurrent external
2054
- // changes to those columns.
2055
- for (const entity of entities) {
2056
- entity.__state = 'track';
2057
- entity.__dirtyFields = [];
2058
- }
2042
+ // Lifecycle state (modified -> clean, then detached) is transitioned
2043
+ // centrally in _reconcileFlushed after the transaction commits — not
2044
+ // here. Keeping it in one place, applied uniformly to inserts, updates
2045
+ // and deletes, is what prevents state-specific gaps (a delete never
2046
+ // becomes 'track', so a per-processor reset here would strand it).
2059
2047
  }
2060
2048
 
2061
2049
  /**
@@ -2177,38 +2165,58 @@ class context {
2177
2165
 
2178
2166
  async _saveChangesExclusive() {
2179
2167
  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
2168
 
2203
- // Atomicity: wrap every write in a single transaction so a partial
2204
- // failure rolls the whole batch back. All three engines now expose
2205
- // startTransaction/endTransaction/errorTransaction (MySQL/Postgres
2206
- // gained them in 1.4.0; previously their writes were autocommitted
2207
- // per statement, leaving partial data on a mid-batch error).
2169
+ // Loud guard against silent data loss across DIFFERENT context instances.
2170
+ this._warnForeignDirty('saveChanges()');
2171
+
2172
+ // A save commits ONLY its own CHANGE SET — the entities that are dirty
2173
+ // (insert/modified/delete) right now — and must NEVER snapshot, process,
2174
+ // or untrack the rest of the tracked list. This is the unit-of-work
2175
+ // model real ORMs use, and it is essential on a shared/singleton context
2176
+ // serving concurrent requests:
2177
+ // 1. Read-only queries auto-track their results, so a handler that just
2178
+ // `.toList()`s a table leaves thousands of clean entities tracked.
2179
+ // Sweeping the whole list would do O(N) work over unrelated rows on
2180
+ // every save.
2181
+ // 2. If a save untracked the whole list, one caller's save — even an
2182
+ // EMPTY one with nothing dirty — would drop another in-flight
2183
+ // caller's freshly loaded/mutated entity from tracking, and that
2184
+ // caller's own saveChanges() would then find nothing to write and
2185
+ // silently lose the UPDATE (returning true). Committing only the
2186
+ // change set makes an empty save a true no-op that never touches
2187
+ // another unit of work's entities.
2188
+ const changeSet = this.__trackedEntities.filter(
2189
+ e => e && e.__state && e.__state !== 'track'
2190
+ );
2191
+
2192
+ if (changeSet.length === 0) {
2193
+ // Nothing dirty — do NOT touch the shared tracked list.
2194
+ return true;
2195
+ }
2196
+
2197
+ // Snapshot the committed unit of work: for each entity in the change set,
2198
+ // capture the exact pending change we are about to flush — its mutation
2199
+ // GENERATION (version) and whether it was a delete. All post-commit
2200
+ // lifecycle transitions are driven from this snapshot in ONE place
2201
+ // (_reconcileFlushed), by ONE uniform rule, rather than being scattered
2202
+ // across the per-state batch processors — which is how a delete (never
2203
+ // reset to 'track') used to be stranded forever.
2204
+ const captured = changeSet.map(e => ({
2205
+ entity: e,
2206
+ generation: e.__version || 0,
2207
+ wasDelete: e.__state === 'delete',
2208
+ }));
2209
+
2210
+ const affectedTables = new Set();
2211
+ for (const e of changeSet) { if (e.__name) affectedTables.add(e.__name); }
2212
+
2213
+ try {
2214
+ // Atomicity: wrap the change set in a single transaction so a partial
2215
+ // failure rolls it back.
2208
2216
  if (this.isSQLite || this.isMySQL || this.isPostgres) {
2209
2217
  await this._SQLEngine.startTransaction();
2210
2218
  try {
2211
- await this._processTrackedEntities(tracked);
2219
+ await this._processTrackedEntities(changeSet);
2212
2220
  this.__clearErrorHandler();
2213
2221
  await this._SQLEngine.endTransaction();
2214
2222
  } catch (error) {
@@ -2217,58 +2225,75 @@ class context {
2217
2225
  }
2218
2226
  }
2219
2227
 
2220
- // Invalidate query cache for affected tables
2221
2228
  for (const tableName of affectedTables) {
2222
2229
  this._queryCache.invalidateTable(tableName);
2223
2230
  }
2224
2231
 
2225
- // Clear only THIS batch — entities tracked mid-save stay queued.
2226
- this.__untrack(tracked);
2232
+ this._reconcileFlushed(captured);
2227
2233
  return true;
2228
2234
  } catch (error) {
2229
- // Clean up on error (this batch only)
2230
2235
  this.__clearErrorHandler();
2231
- this.__untrack(tracked);
2232
-
2236
+ // The transaction rolled back, so nothing was committed. Leave the
2237
+ // change set tracked and dirty so a retry can persist it — never
2238
+ // silently drop a pending write (the caller sees the rejection).
2233
2239
  console.error('[Context] Failed to save changes:', error);
2234
2240
  throw error;
2235
2241
  }
2236
2242
  }
2237
2243
 
2238
2244
  /**
2239
- * Remove a batch of entities from change tracking after a save — but ONLY
2240
- * entities that are currently CLEAN (state 'track').
2241
- *
2242
- * saveChanges() snapshots the tracked list, writes the dirty rows (which are
2243
- * then reset to 'track'), and calls this to drop the batch. A batched entity
2244
- * that is STILL dirty at this point (insert/modified/delete) was NOT written
2245
- * by this save — it became dirty AFTER the snapshot. That happens when a
2246
- * context instance is shared across concurrent units of work (e.g. a
2247
- * singleton context serving many requests): request A's save snapshots a row
2248
- * that request B loaded, B mutates it while A's save is in flight, and if A
2249
- * then untracked it unconditionally, B's own saveChanges() would find it
2250
- * untracked and silently drop the UPDATE. Skipping dirty entities keeps
2251
- * B's pending change tracked so B's save still writes it. (In the normal
2252
- * per-request context the whole batch is clean here, so behavior is
2253
- * unchanged.)
2254
- *
2255
- * NOTE: a context is a unit of work and is safest scoped per request.
2256
- * Sharing one instance across requests still risks cross-request
2257
- * transaction conflation; this guard removes the silent-lost-write, not the
2258
- * need for request-scoped contexts.
2245
+ * Post-commit reconciliation for a flushed unit of work — the SINGLE place
2246
+ * that transitions entity lifecycle state after a successful save. Driven by
2247
+ * the generation snapshot captured at flush time, with one uniform rule for
2248
+ * inserts, updates and deletes (no per-state special cases — that asymmetry
2249
+ * is what stranded deletes as replaying "zombies").
2250
+ *
2251
+ * For each committed entity:
2252
+ * - Re-mutated in flight (generation changed): a NEW change arrived during
2253
+ * the async write. Leave the entity in its current pending state so the
2254
+ * next saveChanges() persists it — never reset it, or that change is lost.
2255
+ * - Otherwise it was fully persisted with no newer change:
2256
+ * * insert / modified -> reset to the clean 'track' state, then detach
2257
+ * from the unit of work (remove from tracking).
2258
+ * * delete -> detach from the unit of work (the row is gone;
2259
+ * it never becomes 'track', so it is released on the delete branch).
2260
+ *
2261
+ * @param {Array<{entity:object, generation:number, wasDelete:boolean}>} captured
2262
+ */
2263
+ _reconcileFlushed(captured) {
2264
+ const detach = [];
2265
+ for (const { entity, generation, wasDelete } of captured) {
2266
+ if ((entity.__version || 0) !== generation) {
2267
+ // A mutation landed during the flush; keep the new pending change.
2268
+ continue;
2269
+ }
2270
+ if (!wasDelete) {
2271
+ entity.__state = 'track';
2272
+ entity.__dirtyFields = [];
2273
+ }
2274
+ detach.push(entity);
2275
+ }
2276
+ this.__untrack(detach);
2277
+ }
2278
+
2279
+ /**
2280
+ * Remove an exact set of entities from change tracking (identity map +
2281
+ * tracked list). The caller curates the set — saveChanges passes only the
2282
+ * entities it fully flushed and that were not re-mutated in flight — so this
2283
+ * removes precisely what it is given and applies NO state test of its own
2284
+ * (a state test here is what stranded deletes, whose state stays 'delete').
2285
+ * Also used by detach()/clearChangeTracker() and attach()'s re-home path.
2259
2286
  */
2260
2287
  __untrack(batch) {
2261
2288
  if (!batch || !batch.length) return;
2262
- const drop = new Set();
2263
- for (const e of batch) {
2264
- if (!e) continue;
2265
- if (e.__state && e.__state !== 'track') continue; // keep still-dirty entities
2266
- drop.add(e);
2267
- }
2268
- if (drop.size === 0) 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);
2269
2294
  this.__trackedEntities = this.__trackedEntities.filter(e => !drop.has(e));
2270
- for (const e of drop) {
2271
- if (e.__ID !== undefined) this.__trackedEntitiesMap.delete(e.__ID);
2295
+ for (const e of batch) {
2296
+ if (e && e.__ID !== undefined) this.__trackedEntitiesMap.delete(e.__ID);
2272
2297
  }
2273
2298
  }
2274
2299
 
@@ -2887,6 +2912,31 @@ class context {
2887
2912
  this.__trackedEntitiesMap.clear(); // Clear Map for proper garbage collection
2888
2913
  }
2889
2914
 
2915
+ /**
2916
+ * Detach ALL entities from change tracking (like Hibernate's
2917
+ * `session.clear()` / EF Core's `ChangeTracker.Clear()`).
2918
+ *
2919
+ * A context is a unit of work and is safest scoped per request. If you must
2920
+ * reuse a long-lived (e.g. singleton) context, read-only queries still
2921
+ * auto-track their results, and those clean entities accumulate — call this
2922
+ * after a read-only operation to release them and keep the tracked set
2923
+ * bounded. It drops PENDING changes too, so only call it when there is
2924
+ * nothing dirty you still intend to save.
2925
+ */
2926
+ clearChangeTracker() {
2927
+ this.__clearTracked();
2928
+ return this;
2929
+ }
2930
+
2931
+ /**
2932
+ * Detach a single entity from change tracking. Pending changes on it are
2933
+ * dropped and it is no longer part of any future saveChanges().
2934
+ */
2935
+ detach(entity) {
2936
+ if (entity) this.__untrack([entity]);
2937
+ return this;
2938
+ }
2939
+
2890
2940
  // ------------------------------------------------------------------
2891
2941
  // Cross-context change-tracking guards (silent-data-loss prevention)
2892
2942
  // ------------------------------------------------------------------
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "masterrecord",
3
- "version": "1.5.9",
3
+ "version": "1.5.11",
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",