@memberjunction/generic-database-provider 6.2.0-edge.3 → 6.2.0-edge.4

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.
@@ -23,7 +23,7 @@ import { createHash } from 'node:crypto';
23
23
  import { v4 as uuidv4 } from 'uuid';
24
24
  import { SqlLoggingSessionImpl } from './SqlLogger.js';
25
25
  import { GetDialect } from '@memberjunction/sql-dialect';
26
- import { SQLParser, IsReadOnlyQuery } from '@memberjunction/sql-parser';
26
+ import { SQLParser, IsReadOnlyQuery, CheckAggregateExpression } from '@memberjunction/sql-parser';
27
27
  // QueryCompositionEngine is now owned by RenderPipeline
28
28
  import { RenderPipeline } from './renderPipeline.js';
29
29
  import { UseJsonArgShape } from './crudSprocFieldRules.js';
@@ -34,8 +34,9 @@ import { QueueManager } from '@memberjunction/queue';
34
34
  import { BuildEntityActionDispatchKey, EntityActionDispatchGuard, EntityActionEngineServer } from '@memberjunction/actions';
35
35
  import { BuildEntityChangeContext } from '@memberjunction/actions-base';
36
36
  import { TransactionFrameTracker } from './TransactionFrameTracker.js';
37
+ import { TransactionAffinity } from './TransactionAffinity.js';
37
38
  import { CountOnlyBatchCoalescer, IsCoalescibleCountBatch } from './countOnlyBatch.js';
38
- import { EncryptionEngine } from '@memberjunction/encryption';
39
+ import { EncryptionEngine, IsEncryptionKeyUnavailable, ReportEncryptionKeyUnavailable } from '@memberjunction/encryption';
39
40
  import { GeoCodeSyncService } from '@memberjunction/geo-core';
40
41
  /**
41
42
  * Execution options for SQL a caller supplied rather than a saved query (ad-hoc SQL, transient test
@@ -95,16 +96,25 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
95
96
  * release hands them to the enclosing frame.
96
97
  */
97
98
  this._postCommitTasks = [];
98
- /**
99
- * Tasks whose own transaction already settled, held back because an UNRELATED transaction is
100
- * open on this instance. Running them now would enlist their writes in it — on one connection,
101
- * that means a rollback of work that has nothing to do with them. Drained when this provider
102
- * goes idle, whichever way that transaction ends.
103
- */
104
- this._idlePostCommitTasks = [];
105
99
  /** Identity of each open frame and the fate of recent transactions, for {@link PostCommitToken}s. */
106
100
  this._frameTracker = new TransactionFrameTracker();
101
+ /** Which async scope the open transaction belongs to (#4786). See {@link IsCallerInAmbientTransaction}. */
102
+ this._affinity = new TransactionAffinity();
103
+ /** Epoch whose foreign join was already reported, so a transaction reports at most one (#4786). */
104
+ this._foreignJoinReportedEpoch = null;
107
105
  this._txMutex = Promise.resolve();
106
+ /**
107
+ * Batch levels this provider has opened and not yet closed.
108
+ *
109
+ * The open happens only after a begin SUCCEEDS, while a commit or rollback closes in a
110
+ * `finally` — so a rollback issued for a begin that threw would close a level it never opened.
111
+ * That happens for real: a nested begin whose savepoint creation fails leaves the caller's
112
+ * catch to roll back, and the seventeen generated cascade-delete overrides are written exactly
113
+ * that way. Closing an outer unit of work's batch early un-batches the rest of its saves, which
114
+ * then write to the shared cache one by one — the uncommitted-rows-in-the-fleet failure the
115
+ * batch exists to prevent.
116
+ */
117
+ this._openBatchLevels = 0;
108
118
  }
109
119
  /**
110
120
  * Returns the active local storage provider, lazily creating an
@@ -144,6 +154,19 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
144
154
  SetLocalStorageProvider(provider) {
145
155
  this._localStorageProvider = provider;
146
156
  }
157
+ /**
158
+ * Installs {@link ProviderConfigDataBase.LocalStorageProvider}, when the configuration carries
159
+ * one, before the base configuration loads metadata. A server fleet passes its shared (Redis)
160
+ * store this way so the metadata load and the engines loaded at startup use it from the first
161
+ * read: the first server to start fills the shared cache, and the others read it instead of
162
+ * each querying the database and broadcasting what they loaded.
163
+ */
164
+ async Config(data, providerToUse) {
165
+ if (data?.LocalStorageProvider) {
166
+ this.SetLocalStorageProvider(data.LocalStorageProvider);
167
+ }
168
+ return super.Config(data, providerToUse);
169
+ }
147
170
  /**************************************************************************/
148
171
  // SQL Logging — Session Management & Statement Logging
149
172
  /**************************************************************************/
@@ -674,6 +697,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
674
697
  processedRow[field.Name] = decryptedValue;
675
698
  }
676
699
  catch (decryptError) {
700
+ // A key this install wasn't given (an app's own key) is configuration, not a
701
+ // fault: one warning per key, and the value stays encrypted.
702
+ if (IsEncryptionKeyUnavailable(decryptError)) {
703
+ ReportEncryptionKeyUnavailable(decryptError);
704
+ continue;
705
+ }
677
706
  const message = decryptError instanceof Error ? decryptError.message : String(decryptError);
678
707
  LogError(`Failed to decrypt field "${field.Name}" on entity "${entityInfo.Name}": ${message}. ` +
679
708
  'The encrypted value will be returned unchanged.');
@@ -1023,6 +1052,27 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1023
1052
  RenderReplaySaveSQL(_binding, _entity, _fieldValues) {
1024
1053
  return undefined;
1025
1054
  }
1055
+ /**
1056
+ * Optional replay form of an UPDATE for the SQL log only (never executed). Receives just the
1057
+ * fields this save CHANGED. A recording that carried the whole row would, on replay, overwrite
1058
+ * every column of the target row with the recording database's values — including settings a
1059
+ * deploying application tuned on purpose (an MJ metadata sync that only flipped
1060
+ * `AllowUserSearchAPI` on 'MJ: Content Items' also reset that consumer's
1061
+ * `TrustServerCacheCompletely`). Dialects whose update procs keep unpassed columns override
1062
+ * this. Default: no replay form, the plain save SQL is logged.
1063
+ */
1064
+ RenderReplayUpdateSQL(_binding, _entity, _changedFieldValues) {
1065
+ return undefined;
1066
+ }
1067
+ /** The entries of a save's parameter map whose fields this save actually changed. */
1068
+ changedFieldValues(entity, fieldValues) {
1069
+ const changed = new Map();
1070
+ for (const [f, value] of fieldValues) {
1071
+ if (entity.GetFieldByName(f.Name)?.Dirty)
1072
+ changed.set(f, value);
1073
+ }
1074
+ return changed;
1075
+ }
1026
1076
  /**
1027
1077
  * Concrete implementation of the abstract save-SQL builder defined on
1028
1078
  * `DatabaseProviderBase`. Iterates fields via the single `IsSPParameter`
@@ -1087,9 +1137,16 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1087
1137
  const baseSaveSQL = this.WrapSaveCallForResult(binding, entity, spName);
1088
1138
  let saveSQL = baseSaveSQL;
1089
1139
  // A CREATE's logged form is guarded on the primary key so a migration replay of
1090
- // the recording converges on a database that already holds the row (#4503).
1091
- // Updates and dialects without a replay form log the plain save SQL.
1092
- const replaySQL = isNew ? this.RenderReplaySaveSQL(binding, entity, fieldValueMap) : undefined;
1140
+ // the recording converges on a database that already holds the row (#4503). An
1141
+ // UPDATE's logged form carries only the fields this save changed, so a replay never
1142
+ // resets the target's other columns. A forced save (IgnoreDirtyState, e.g. MetadataSync's
1143
+ // `alwaysPush`) asked to re-impose the whole row, so it keeps the full-row form. Dialects
1144
+ // without a replay form log the plain save SQL.
1145
+ const replaySQL = isNew
1146
+ ? this.RenderReplaySaveSQL(binding, entity, fieldValueMap)
1147
+ : options?.IgnoreDirtyState
1148
+ ? undefined
1149
+ : this.RenderReplayUpdateSQL(binding, entity, this.changedFieldValues(entity, fieldValueMap));
1093
1150
  const simpleSQL = replaySQL ?? baseSaveSQL.sql;
1094
1151
  // 5. Optionally wrap with record-change emission.
1095
1152
  let overlappingChangeData;
@@ -1873,6 +1930,40 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1873
1930
  /**************************************************************************/
1874
1931
  // InternalRunView Helpers
1875
1932
  /**************************************************************************/
1933
+ /**
1934
+ * Builds the aggregate query without running the caller's text. Each expression must be a single
1935
+ * aggregate function call over this entity's columns: the query runs the SQL that
1936
+ * {@link CheckAggregateExpression} rebuilds from the checked parse tree (with this provider's
1937
+ * dialect), once the keyword validator has also accepted that SQL. A refused expression becomes a
1938
+ * per-aggregate error in request order. The accepted ones are aliased `Agg_0`, `Agg_1`, … in
1939
+ * request order, which is how `RunViewCore` reads their values back.
1940
+ */
1941
+ BuildAggregateSQL(aggregates, entityInfo, schemaName, baseView, whereSQL) {
1942
+ const columns = entityInfo.Fields.map((f) => f.Name);
1943
+ const items = [];
1944
+ const validationErrors = [];
1945
+ for (const agg of aggregates ?? []) {
1946
+ const screened = this.screenAggregateExpression(agg.expression, columns);
1947
+ if ('SQL' in screened) {
1948
+ items.push(`${screened.SQL} AS ${this.QuoteIdentifier(`Agg_${items.length}`)}`);
1949
+ }
1950
+ else {
1951
+ validationErrors.push({ expression: agg.expression, alias: agg.alias || agg.expression, value: null, error: screened.Error });
1952
+ }
1953
+ }
1954
+ if (items.length === 0)
1955
+ return { aggregateSQL: null, validationErrors };
1956
+ const where = whereSQL ? ` WHERE ${whereSQL}` : '';
1957
+ return { aggregateSQL: `SELECT ${items.join(', ')} FROM ${this.QuoteSchemaAndView(schemaName, baseView)}${where}`, validationErrors };
1958
+ }
1959
+ /** The SQL to run for one caller aggregate expression, or why it is refused. */
1960
+ screenAggregateExpression(expression, columns) {
1961
+ const check = CheckAggregateExpression(expression, this.Dialect, columns);
1962
+ if (!check.IsAllowed || check.SQL === null)
1963
+ return { Error: `Invalid aggregate expression: ${check.Reason}` };
1964
+ const keywordCheck = SQLExpressionValidator.Instance.validate(check.SQL, { context: 'aggregate', entityFields: columns });
1965
+ return keywordCheck.valid ? { SQL: check.SQL } : { Error: keywordCheck.error || 'Validation failed' };
1966
+ }
1876
1967
  /**
1877
1968
  * Returns the SELECT list for a single-record load: `*` normally, or an explicit list of
1878
1969
  * the columns this user is allowed to read when field security denies them any.
@@ -2309,6 +2400,50 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2309
2400
  /**************************************************************************/
2310
2401
  // RunViewsWithCacheCheck — Shared Implementation
2311
2402
  /**************************************************************************/
2403
+ /**
2404
+ * Row count and newest `__mj_UpdatedAt` for each view, read from the database and never from
2405
+ * a cache. Uses the same WHERE clause (filter, user search, row-level security, pre-run hooks)
2406
+ * and the same batched status query as {@link RunViewsWithCacheCheck}. One entry per param,
2407
+ * in order; a failure is reported per entry.
2408
+ */
2409
+ async GetRunViewsDatabaseStatus(params, contextUser) {
2410
+ const user = contextUser || this.CurrentUser;
2411
+ const statuses = params.map(() => ({ Success: false, ErrorMessage: 'not checked' }));
2412
+ if (!user) {
2413
+ return statuses.map(() => ({ Success: false, ErrorMessage: 'No user context available' }));
2414
+ }
2415
+ const items = await this.buildDatabaseStatusItems(params, user, statuses);
2416
+ const results = await this.getBatchedServerCacheStatus(items, contextUser);
2417
+ for (const { index } of items) {
2418
+ const status = results.get(index);
2419
+ statuses[index] = status?.success
2420
+ ? { Success: true, RowCount: status.rowCount ?? 0, MaxUpdatedAt: status.maxUpdatedAt }
2421
+ : { Success: false, ErrorMessage: status?.errorMessage ?? 'no status returned' };
2422
+ }
2423
+ return statuses;
2424
+ }
2425
+ /** Status-query inputs for {@link GetRunViewsDatabaseStatus}; entries that cannot be built record their error. */
2426
+ async buildDatabaseStatusItems(params, user, statuses) {
2427
+ const items = [];
2428
+ for (let index = 0; index < params.length; index++) {
2429
+ try {
2430
+ const viewParams = { ...params[index] };
2431
+ this.ResolvePlatformSQLInParams(viewParams);
2432
+ const hooked = await this.RunPreRunViewHooks(viewParams, user);
2433
+ const entityInfo = hooked.EntityName ? this.EntityByName(hooked.EntityName) : undefined;
2434
+ if (!entityInfo) {
2435
+ statuses[index] = { Success: false, ErrorMessage: `Entity ${hooked.EntityName ?? '(none)'} not found` };
2436
+ continue;
2437
+ }
2438
+ const whereSQL = await this.buildWhereClauseForCacheCheck(hooked, entityInfo, user);
2439
+ items.push({ index, item: { params: hooked }, entityInfo, whereSQL });
2440
+ }
2441
+ catch (e) {
2442
+ statuses[index] = { Success: false, ErrorMessage: e instanceof Error ? e.message : String(e) };
2443
+ }
2444
+ }
2445
+ return items;
2446
+ }
2312
2447
  /**
2313
2448
  * Smart cache validation for batch RunViews.
2314
2449
  * For each view request, if cacheStatus is provided, checks if the cache is current
@@ -2498,6 +2633,18 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2498
2633
  const noCacheStatusServedFromCache = [];
2499
2634
  const noCacheStatusNeedsDB = [];
2500
2635
  for (const entry of itemsWithoutCacheCheck) {
2636
+ // A param carrying BypassCache lands here because it is ineligible for a cache status,
2637
+ // NOT because the caller has nothing cached — and those two must not be treated alike.
2638
+ // Serving it from the server cache is precisely what it asked not to happen: its
2639
+ // documented contract is "the query always hits the database", and it is the only way a
2640
+ // client can escape a server slot that a missed invalidation left stale. The write side
2641
+ // already refuses to store such a result (runViewCacheEligible starts with
2642
+ // !param.BypassCache); this is the matching read-side gate.
2643
+ if (entry.item.params.BypassCache) {
2644
+ LogStatusEx({ message: ` 🚫 [SmartCache BYPASS] "${entry.item.params.EntityName || 'unknown'}" — BypassCache requested, going to the database`, verboseOnly: true });
2645
+ noCacheStatusNeedsDB.push(entry);
2646
+ continue;
2647
+ }
2501
2648
  if (LocalCacheManager.Instance.IsInitialized) {
2502
2649
  const rlsWhereClause = this.ComputeRunViewRLSWhereClause(entry.item.params, contextUser);
2503
2650
  const flsFieldsKey = this.ComputeRunViewFLSFingerprintKey(entry.item.params);
@@ -2639,6 +2786,22 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2639
2786
  }
2640
2787
  return whereSQL;
2641
2788
  }
2789
+ /**
2790
+ * The freshness probe for one view: a row count, plus the newest `__mj_UpdatedAt` **when the
2791
+ * entity has that column**. Selecting it unconditionally made the probe fail outright for an
2792
+ * entity whose view does not carry it, instead of comparing by count alone the way
2793
+ * `BaseEngine.SweepAgainstDatabase` documents.
2794
+ */
2795
+ BuildCacheStatusSQL(entityInfo, effectiveView, whereSQL) {
2796
+ const from = `FROM ${this.QuoteSchemaAndView(entityInfo.SchemaName, effectiveView)}${whereSQL ? ' WHERE ' + whereSQL : ''}`;
2797
+ const count = `COUNT(*) AS ${this.QuoteIdentifier('TotalRows')}`;
2798
+ // `Fields` absent (a partial EntityInfo) degrades to the count-only probe rather than
2799
+ // throwing: a freshness check must not be the thing that breaks a sweep.
2800
+ if (!entityInfo.Fields?.some(f => f.IsUpdatedAtField)) {
2801
+ return `SELECT ${count} ${from}`;
2802
+ }
2803
+ return `SELECT ${count}, MAX(${this.QuoteIdentifier('__mj_UpdatedAt')}) AS ${this.QuoteIdentifier('MaxUpdatedAt')} ${from}`;
2804
+ }
2642
2805
  /**
2643
2806
  * Executes cache status checks for multiple views.
2644
2807
  * Default: parallel individual queries (works on all platforms).
@@ -2657,7 +2820,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2657
2820
  // (Materialized reads are normally kept out of the client cache by runViewCacheEligible; this
2658
2821
  // matches the SQL Server override and is defense-in-depth on the PG/default path.)
2659
2822
  const effectiveView = await this.resolveEffectiveBaseView(entityInfo, item.params, contextUser);
2660
- const statusSQL = `SELECT COUNT(*) AS ${this.QuoteIdentifier('TotalRows')}, MAX(${this.QuoteIdentifier('__mj_UpdatedAt')}) AS ${this.QuoteIdentifier('MaxUpdatedAt')} FROM ${this.QuoteSchemaAndView(entityInfo.SchemaName, effectiveView)}${whereSQL ? ' WHERE ' + whereSQL : ''}`;
2823
+ const statusSQL = this.BuildCacheStatusSQL(entityInfo, effectiveView, whereSQL);
2661
2824
  const rows = await this.ExecuteSQL(statusSQL, undefined, undefined, contextUser);
2662
2825
  if (rows && rows.length > 0) {
2663
2826
  const row = rows[0];
@@ -5141,12 +5304,6 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5141
5304
  get IsDoomed() {
5142
5305
  return this._doomed;
5143
5306
  }
5144
- /**
5145
- * Throw if a statement would run on the pool while frames are still open
5146
- * after a server abort. Keyed on `_doomed`, not "depth > 0 with no handle"
5147
- * — outermost begin has depth 1 before the handle is published, and
5148
- * concurrent reads on SQL Server legitimately use the pool in that window.
5149
- */
5150
5307
  /**
5151
5308
  * A debounced metadata refresh is timer-driven, so it can fire at any point of a caller's
5152
5309
  * unit of work — including the microtask window while the ambient transaction is being
@@ -5156,21 +5313,45 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5156
5313
  * Metadata reads are not part of anyone's unit of work, so wait for the transaction to end
5157
5314
  * before starting one (#4486).
5158
5315
  *
5159
- * This narrows the window rather than closing it: the check runs when the timer fires, and
5160
- * the batch is issued several round trips later, so a transaction that begins in between
5161
- * is still joined. That case is now harmless to the process — the batch fails, the dataset
5162
- * reports it, and the loaded metadata stays — but the refresh itself is lost until the next
5163
- * member write. Running the metadata batch on the pool regardless of the ambient
5164
- * transaction is #4514 (alongside #4454, the commit-side half of the same window).
5316
+ * Under scope affinity (#4786) the timer inherits the membership of the code that scheduled it
5317
+ * (re-arms included), so the refresh can only ever join the transaction whose scope scheduled
5318
+ * it — and only if that transaction is still open when the batch is issued, several round trips
5319
+ * after this check ran. It never joins a transaction someone else begins later. That remaining
5320
+ * window is harmless to the process — the batch fails, the dataset reports it, and the loaded
5321
+ * metadata stays — but the refresh itself is lost until the next member write. The check is
5322
+ * instance-wide, so an unrelated transaction also defers the refresh. Running the metadata
5323
+ * batch on the pool regardless of the ambient transaction is #4514 (alongside #4454, the
5324
+ * commit-side half of the same window).
5165
5325
  */
5166
5326
  get MetadataMemberRefreshMustWait() {
5167
5327
  return this.CurrentTransactionDepth > 0 || this.HasPhysicalTransaction;
5168
5328
  }
5329
+ /**
5330
+ * Throw if a statement from a member of the ambient transaction would run on the pool while its
5331
+ * frames are still open after a server abort. Keyed on `_doomed`, not "depth > 0 with no handle"
5332
+ * — outermost begin has depth 1 before the handle is published, and concurrent reads on SQL
5333
+ * Server legitimately use the pool in that window. Callers outside the transaction's scope
5334
+ * (see {@link IsCallerInAmbientTransaction}) do not use its handle, so a subclass should apply
5335
+ * this check only to members' statements.
5336
+ */
5169
5337
  AssertAmbientTransactionUsable() {
5170
5338
  if (this._doomed) {
5171
5339
  throw new DoomedTransactionError(`SQL issued at depth ${this._transactionDepth} while the ambient transaction is doomed would autocommit on the pool`);
5172
5340
  }
5173
5341
  }
5342
+ /**
5343
+ * Whether the calling async scope is part of this provider's ambient transaction (#4786). A shared
5344
+ * provider's open transaction belongs to the scope that began it and its descendants; every other
5345
+ * caller must run on the pool, as if no transaction were open. Subclasses consult this — not merely
5346
+ * "is a handle open" — before routing a statement to the transaction handle.
5347
+ */
5348
+ IsCallerInAmbientTransaction() {
5349
+ return this._affinity.IsCallerMember;
5350
+ }
5351
+ /** Members of the open transaction share RunViews only with each other (see {@link ProviderBase.RunViewDedupScope}). */
5352
+ get RunViewDedupScope() {
5353
+ return this.IsCallerInAmbientTransaction() ? `tx:${this._affinity.CurrentEpoch}` : '';
5354
+ }
5174
5355
  /**
5175
5356
  * Drop a dead physical handle without going through public RollbackTransaction.
5176
5357
  * Default is RollbackPhysicalTransaction if one is open. Subclasses override
@@ -5204,8 +5385,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5204
5385
  }
5205
5386
  }
5206
5387
  /**
5207
- * Queue `task` until the outermost commit of the ambient transaction, or start it now when
5208
- * there is none. See {@link DatabaseProviderBase.RunAfterCommit} for the contract.
5388
+ * Queue `task` until the outermost commit of the caller's transaction, or start it now when
5389
+ * there is none. See {@link DatabaseProviderBase.RunAfterCommit} for the contract. Work
5390
+ * registered by a caller outside the open transaction's scope (#4786) is not tied to that
5391
+ * transaction: it starts now, detached, on the pool, whether or not that transaction is open.
5209
5392
  *
5210
5393
  * - Queued tasks run once, in registration order, after the outermost commit succeeds and the
5211
5394
  * transaction lock is released — so a task may begin its own transaction. The committer
@@ -5219,26 +5402,37 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5219
5402
  * token was captured in, rolled back — including a savepoint rolled back inside a transaction
5220
5403
  * that went on to commit — or if the token matches nothing this provider knows; otherwise it
5221
5404
  * is queued at the deepest captured frame that is still open. A token captured outside any
5222
- * transaction always runs. "Runs" means immediately when this provider is idle, and otherwise
5223
- * once it is: a task must never have its own writes rolled back by an unrelated transaction.
5405
+ * transaction always runs.
5406
+ * - "Starts now" means fire-and-forget under {@link TransactionAffinity.RunDetached}: the task is
5407
+ * in no transaction on this provider (its statements run on the pool), the caller never awaits
5408
+ * it, and a `BeginTransaction` in the task's synchronous prefix stays in the task's own scope.
5409
+ * If the task begins a transaction while another is open on this instance, it joins that one as
5410
+ * a savepoint (logged) — a task that needs its own transaction belongs on an independent instance.
5224
5411
  */
5225
5412
  RunAfterCommit(task, description = 'post-commit task', token) {
5226
5413
  if (token) {
5227
5414
  this.registerPostCommitTaskWithToken(task, description, token);
5228
5415
  return;
5229
5416
  }
5230
- if (this._transactionDepth === 0 && !this.HasPhysicalTransaction) {
5231
- super.RunAfterCommit(task, description);
5417
+ if (!this.IsCallerInAmbientTransaction()) {
5418
+ // No transaction open, or not the caller's: either way the task is not tied to one.
5419
+ this.runDetachedTask(task, description);
5232
5420
  return;
5233
5421
  }
5234
5422
  this._postCommitTasks.push({ Task: task, Description: description, Depth: this._transactionDepth });
5235
5423
  }
5236
5424
  /**
5237
- * Snapshot of the open transaction frames. Synchronous, and never `undefined` on this provider:
5238
- * outside a transaction it returns a token whose epoch is `null`, which says the work is already
5239
- * durable rather than saying nothing. See {@link DatabaseProviderBase.CapturePostCommitToken}.
5425
+ * Snapshot of the caller's transaction frames. Synchronous, and never `undefined` on this
5426
+ * provider: outside a transaction it returns a token whose epoch is `null`, which says the work
5427
+ * is already durable rather than saying nothing. See
5428
+ * {@link DatabaseProviderBase.CapturePostCommitToken}. Work registered by a caller outside the
5429
+ * open transaction's scope (#4786) is not tied to that transaction, so such a caller gets the
5430
+ * same `null`-epoch token.
5240
5431
  */
5241
5432
  CapturePostCommitToken() {
5433
+ if (!this.IsCallerInAmbientTransaction()) {
5434
+ return { Epoch: null, FrameIds: [] };
5435
+ }
5242
5436
  return this._frameTracker.Capture();
5243
5437
  }
5244
5438
  registerPostCommitTaskWithToken(task, description, token) {
@@ -5266,33 +5460,22 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5266
5460
  get PendingPostCommitTaskCount() {
5267
5461
  return this._postCommitTasks.length;
5268
5462
  }
5269
- /** Number of tasks waiting only for this provider to go idle. */
5463
+ /**
5464
+ * @deprecated Always 0. Post-commit work not tied to the caller's transaction used to be held
5465
+ * until this provider went idle; with scope affinity (#4786) it starts immediately on the pool, so
5466
+ * there is no idle queue left to count. Kept for one release.
5467
+ */
5270
5468
  get PendingIdlePostCommitTaskCount() {
5271
- return this._idlePostCommitTasks.length;
5469
+ return 0;
5272
5470
  }
5273
5471
  /**
5274
- * Run work whose own transaction has already settled. Immediate when this provider is idle;
5275
- * otherwise held until it is, so the task's writes cannot join — and be rolled back with — a
5276
- * transaction it has nothing to do with.
5472
+ * Start work that is not tied to the caller's transaction now, fire-and-forget; never throws.
5473
+ * Detached so it is in no transaction on this provider — its statements run on the pool, even
5474
+ * while an unrelated transaction is open — and so a begin in its synchronous prefix cannot make
5475
+ * the caller a member (see {@link TransactionAffinity.Claim}).
5277
5476
  */
5278
5477
  runDetachedTask(task, description) {
5279
- if (this._transactionDepth === 0 && !this.HasPhysicalTransaction) {
5280
- super.RunAfterCommit(task, description);
5281
- return;
5282
- }
5283
- this._idlePostCommitTasks.push({ Task: task, Description: description, Depth: 0 });
5284
- }
5285
- /** Run everything that was waiting for this provider to go idle. Never throws. */
5286
- async drainIdlePostCommitTasks() {
5287
- if (this._idlePostCommitTasks.length === 0 || this._transactionDepth > 0 || this.HasPhysicalTransaction) {
5288
- return;
5289
- }
5290
- const tasks = this._idlePostCommitTasks;
5291
- this._idlePostCommitTasks = [];
5292
- LogStatus(`Running ${tasks.length} post-commit task(s) held back by an unrelated transaction`);
5293
- for (const entry of tasks) {
5294
- await this.RunPostCommitTaskSafely(entry.Task, entry.Description);
5295
- }
5478
+ void this._affinity.RunDetached(() => this.RunPostCommitTaskSafely(task, description));
5296
5479
  }
5297
5480
  /** Run tasks detached from a committed transaction, one at a time, in order. Never throws. */
5298
5481
  async runPostCommitTasks(tasks) {
@@ -5301,7 +5484,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5301
5484
  }
5302
5485
  LogStatus(`Running ${tasks.length} post-commit task(s) after transaction commit`);
5303
5486
  for (const entry of tasks) {
5304
- await this.RunPostCommitTaskSafely(entry.Task, entry.Description);
5487
+ // Detached from the committer's (now stale) membership explicitly, not merely by epoch mismatch.
5488
+ await this._affinity.RunDetached(() => this.RunPostCommitTaskSafely(entry.Task, entry.Description));
5305
5489
  }
5306
5490
  }
5307
5491
  /** Detach the whole queue (outermost commit succeeded). */
@@ -5359,29 +5543,79 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5359
5543
  */
5360
5544
  async ResetTransactionState() {
5361
5545
  await this.WithTransactionLock(() => this.abandonDoomedTransaction());
5362
- await this.drainIdlePostCommitTasks();
5546
+ // The frames are gone, so no settle will ever close this instance's batch. Drop it here or
5547
+ // its entities count as pending forever and every cached read of them misses.
5548
+ this._openBatchLevels = 0;
5549
+ await LocalCacheManager.Instance.AbandonEntityEventBatch(this);
5363
5550
  }
5551
+ /**
5552
+ * Cache maintenance for the saves inside a transaction waits for the outermost settle: one
5553
+ * rewrite per cached slot on commit instead of one per save, and nothing written for work that
5554
+ * is rolled back.
5555
+ *
5556
+ * The batch is opened HERE, on the raw primitive, not only in
5557
+ * `DatabaseProviderBase.BeginEntityTransaction` — 41 call sites across the repo use
5558
+ * `BeginTransaction()` directly, including new-user creation on first login, the magic-link
5559
+ * service, the roles/users sync resolver, `MergeRecords` and every generated cascade-delete
5560
+ * override. Those saves each published their own cache write, and a rollback left rows in the
5561
+ * shared cache that were never committed. `BeginEntityTransaction` still opens
5562
+ * its own level on top; the levels are depth-counted, so the batch applies once, at the
5563
+ * outermost settle, either way.
5564
+ */
5364
5565
  async BeginTransaction() {
5365
- return this.WithTransactionLock(() => this.beginTransactionCore());
5566
+ // Claimed before the first await (the lock's): see TransactionAffinity.Claim for why.
5567
+ const membership = this._affinity.Claim();
5568
+ try {
5569
+ await this.WithTransactionLock(() => this.beginTransactionCore(membership));
5570
+ }
5571
+ catch (e) {
5572
+ // Every failure path, including a begin refused while doomed. A no-op for a membership
5573
+ // already bound (a member's failed nested begin): see TransactionAffinity.Release.
5574
+ this._affinity.Release(membership);
5575
+ throw e;
5576
+ }
5577
+ LocalCacheManager.Instance.BeginEntityEventBatch(this);
5578
+ this._openBatchLevels++;
5579
+ }
5580
+ /** Closes one batch level, but only if this provider opened one. @internal */
5581
+ async endBatchLevelIfOpen(succeeded) {
5582
+ if (this._openBatchLevels <= 0) {
5583
+ return;
5584
+ }
5585
+ this._openBatchLevels--;
5586
+ await LocalCacheManager.Instance.EndEntityEventBatch(this, succeeded);
5366
5587
  }
5367
5588
  async CommitTransaction() {
5368
5589
  // null = not the outermost commit, so nothing drains and the subclass hook does not run.
5369
- const committedTasks = await this.WithTransactionLock(async () => {
5370
- const outermost = this._transactionDepth === 1;
5371
- const tasks = await this.commitTransactionCore();
5372
- return outermost ? tasks : null;
5373
- });
5590
+ let committedTasks;
5591
+ try {
5592
+ committedTasks = await this.WithTransactionLock(async () => {
5593
+ const outermost = this._transactionDepth === 1;
5594
+ const tasks = await this.commitTransactionCore();
5595
+ return outermost ? tasks : null;
5596
+ });
5597
+ }
5598
+ catch (e) {
5599
+ // The commit failed: the rows may not be in the database, so the batch settles as a
5600
+ // failure (its slots are invalidated) rather than being left open.
5601
+ await this.endBatchLevelIfOpen(false);
5602
+ throw e;
5603
+ }
5604
+ await this.endBatchLevelIfOpen(true);
5374
5605
  if (committedTasks) {
5375
5606
  await this.runPostCommitTasks(committedTasks);
5376
5607
  await this.AfterPhysicalCommit();
5377
5608
  }
5378
- await this.drainIdlePostCommitTasks();
5379
5609
  }
5380
5610
  async RollbackTransaction() {
5381
- await this.WithTransactionLock(() => this.rollbackTransactionCore());
5382
- await this.drainIdlePostCommitTasks();
5611
+ try {
5612
+ await this.WithTransactionLock(() => this.rollbackTransactionCore());
5613
+ }
5614
+ finally {
5615
+ await this.endBatchLevelIfOpen(false);
5616
+ }
5383
5617
  }
5384
- async beginTransactionCore() {
5618
+ async beginTransactionCore(membership) {
5385
5619
  if (this._doomed) {
5386
5620
  throw new DoomedTransactionError();
5387
5621
  }
@@ -5391,6 +5625,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5391
5625
  if (this._transactionDepth === 1) {
5392
5626
  this._abandonedByFailedCommit = false;
5393
5627
  await this.BeginPhysicalTransaction();
5628
+ this._affinity.OpenEpoch();
5629
+ this._affinity.Bind(membership);
5394
5630
  return;
5395
5631
  }
5396
5632
  if (!this.HasPhysicalTransaction) {
@@ -5406,6 +5642,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5406
5642
  this._savepointCounter--;
5407
5643
  throw savepointError;
5408
5644
  }
5645
+ // Only once the savepoint exists (as the outermost binds only after BEGIN): a begin that
5646
+ // failed to join must not leave its caller's statements routed to the transaction handle.
5647
+ this.bindJoiningMembership(membership);
5409
5648
  }
5410
5649
  catch (e) {
5411
5650
  if (this._transactionDepth > 0) {
@@ -5424,14 +5663,36 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5424
5663
  throw e;
5425
5664
  }
5426
5665
  }
5666
+ /**
5667
+ * A nested begin joins the open transaction as a savepoint. When the caller was not already part of
5668
+ * it, that is an unrelated unit of work entangling itself with someone else's transaction on a shared
5669
+ * instance: its savepoint commits only if the owner commits, and settling out of order corrupts both.
5670
+ * Joining keeps pre-#4786 behaviour — waiting for the owner instead can deadlock when the owner is
5671
+ * itself waiting on this work (a coalesced entity-action rerun) — so it is reported, once per
5672
+ * transaction, instead of silently happening. The joiner stays bound to the owner's transaction
5673
+ * after its own savepoint is released: its later plain statements keep running on that
5674
+ * transaction until the owner ends it.
5675
+ */
5676
+ bindJoiningMembership(membership) {
5677
+ const epoch = this._affinity.CurrentEpoch;
5678
+ if (membership.Epoch !== epoch && this._foreignJoinReportedEpoch !== epoch) {
5679
+ this._foreignJoinReportedEpoch = epoch;
5680
+ LogError(`${this.constructor.name}: a transaction was begun by code outside the async scope of the transaction ` +
5681
+ `already open on this provider instance, so it joins that transaction as a savepoint. Its writes now ` +
5682
+ `commit or roll back with a unit of work it is not part of, and its later statements keep running ` +
5683
+ `in that transaction until its owner ends it. Run independent units of work on ` +
5684
+ `CreateIndependentInstance() or a per-request provider (#4786).`);
5685
+ }
5686
+ this._affinity.Bind(membership);
5687
+ }
5688
+ /** Savepoint SQL is the provider's own bookkeeping: it must reach the handle whichever scope settles the frame. */
5689
+ async executeTransactionControlSQL(sql, description) {
5690
+ await this._affinity.RunAsMember(() => this.ExecuteSQL(sql, undefined, { description, ignoreLogging: true }));
5691
+ }
5427
5692
  async createSavepoint(savepointName) {
5428
5693
  const sql = this.Dialect.CreateSavepointSQL(savepointName);
5429
- const options = {
5430
- description: `Creating savepoint ${savepointName} at depth ${this._transactionDepth}`,
5431
- ignoreLogging: true,
5432
- };
5433
5694
  try {
5434
- await this.ExecuteSQL(sql, undefined, options);
5695
+ await this.executeTransactionControlSQL(sql, `Creating savepoint ${savepointName} at depth ${this._transactionDepth}`);
5435
5696
  }
5436
5697
  catch (savepointError) {
5437
5698
  if (this.HasPhysicalTransaction && this.isDoomedPhysicalTransactionError(savepointError)) {
@@ -5507,10 +5768,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5507
5768
  const releaseSQL = this.Dialect.ReleaseSavepointSQL(savepointName);
5508
5769
  if (releaseSQL) {
5509
5770
  try {
5510
- await this.ExecuteSQL(releaseSQL, undefined, {
5511
- description: `Releasing savepoint ${savepointName}`,
5512
- ignoreLogging: true,
5513
- });
5771
+ await this.executeTransactionControlSQL(releaseSQL, `Releasing savepoint ${savepointName}`);
5514
5772
  }
5515
5773
  catch (e) {
5516
5774
  await this.AbandonPhysicalTransaction();
@@ -5555,16 +5813,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5555
5813
  throw new Error('Savepoint stack mismatch - no savepoint to rollback to');
5556
5814
  }
5557
5815
  try {
5558
- await this.ExecuteSQL(this.Dialect.RollbackToSavepointSQL(savepointName), undefined, {
5559
- description: `Rolling back to savepoint ${savepointName}`,
5560
- ignoreLogging: true,
5561
- });
5816
+ await this.executeTransactionControlSQL(this.Dialect.RollbackToSavepointSQL(savepointName), `Rolling back to savepoint ${savepointName}`);
5562
5817
  const releaseSQL = this.Dialect.ReleaseSavepointSQL(savepointName);
5563
5818
  if (releaseSQL) {
5564
- await this.ExecuteSQL(releaseSQL, undefined, {
5565
- description: `Releasing savepoint ${savepointName} after rollback`,
5566
- ignoreLogging: true,
5567
- });
5819
+ await this.executeTransactionControlSQL(releaseSQL, `Releasing savepoint ${savepointName} after rollback`);
5568
5820
  }
5569
5821
  this.discardPostCommitTasks(this._transactionDepth, `savepoint ${savepointName} was rolled back`);
5570
5822
  this._savepointStack.pop();
@@ -5595,10 +5847,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5595
5847
  this._savepointCounter = 0;
5596
5848
  }
5597
5849
  /**
5598
- * Back to depth 0. A successful commit detaches the post-commit queue first, so anything still
5599
- * queued here belongs to a transaction that rolled back, failed, or was abandoned.
5850
+ * Back to depth 0 — every ending of the transaction goes through here, so it is also where the
5851
+ * transaction's memberships go stale. A successful commit detaches the post-commit queue first, so
5852
+ * anything still queued here belongs to a transaction that rolled back, failed, or was abandoned.
5600
5853
  */
5601
5854
  clearTransactionState() {
5855
+ this._affinity.CloseEpoch();
5602
5856
  this._transactionDepth = 0;
5603
5857
  this._doomed = false;
5604
5858
  this.clearSavepointState();