@memberjunction/core 6.2.1 → 6.3.0-edge.0

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.
Files changed (126) hide show
  1. package/dist/generic/JSONType-interfaces/IEntityConfiguration.d.ts +94 -0
  2. package/dist/generic/JSONType-interfaces/IEntityConfiguration.d.ts.map +1 -1
  3. package/dist/generic/JSONType-interfaces/IEntitySubtypeSelectorConfig.d.ts +77 -4
  4. package/dist/generic/JSONType-interfaces/IEntitySubtypeSelectorConfig.d.ts.map +1 -1
  5. package/dist/generic/appCapabilityRegistry.d.ts +106 -0
  6. package/dist/generic/appCapabilityRegistry.d.ts.map +1 -0
  7. package/dist/generic/appCapabilityRegistry.js +212 -0
  8. package/dist/generic/appCapabilityRegistry.js.map +1 -0
  9. package/dist/generic/baseEngine.d.ts +108 -3
  10. package/dist/generic/baseEngine.d.ts.map +1 -1
  11. package/dist/generic/baseEngine.js +891 -122
  12. package/dist/generic/baseEngine.js.map +1 -1
  13. package/dist/generic/baseEngineRegistry.d.ts.map +1 -1
  14. package/dist/generic/baseEngineRegistry.js +8 -1
  15. package/dist/generic/baseEngineRegistry.js.map +1 -1
  16. package/dist/generic/baseEntity.d.ts +147 -3
  17. package/dist/generic/baseEntity.d.ts.map +1 -1
  18. package/dist/generic/baseEntity.js +1063 -25
  19. package/dist/generic/baseEntity.js.map +1 -1
  20. package/dist/generic/baseRemotableOperation.d.ts +15 -0
  21. package/dist/generic/baseRemotableOperation.d.ts.map +1 -1
  22. package/dist/generic/baseRemotableOperation.js +11 -0
  23. package/dist/generic/baseRemotableOperation.js.map +1 -1
  24. package/dist/generic/compositeKey.d.ts.map +1 -1
  25. package/dist/generic/compositeKey.js +3 -1
  26. package/dist/generic/compositeKey.js.map +1 -1
  27. package/dist/generic/crossEntityPolicyEngine.d.ts +172 -0
  28. package/dist/generic/crossEntityPolicyEngine.d.ts.map +1 -0
  29. package/dist/generic/crossEntityPolicyEngine.js +667 -0
  30. package/dist/generic/crossEntityPolicyEngine.js.map +1 -0
  31. package/dist/generic/dataHooks.d.ts +14 -1
  32. package/dist/generic/dataHooks.d.ts.map +1 -1
  33. package/dist/generic/dataHooks.js.map +1 -1
  34. package/dist/generic/databaseProviderBase.d.ts +37 -0
  35. package/dist/generic/databaseProviderBase.d.ts.map +1 -1
  36. package/dist/generic/databaseProviderBase.js +220 -24
  37. package/dist/generic/databaseProviderBase.js.map +1 -1
  38. package/dist/generic/documentNumberingEngine.d.ts +190 -0
  39. package/dist/generic/documentNumberingEngine.d.ts.map +1 -0
  40. package/dist/generic/documentNumberingEngine.js +739 -0
  41. package/dist/generic/documentNumberingEngine.js.map +1 -0
  42. package/dist/generic/entityInfo.d.ts +104 -3
  43. package/dist/generic/entityInfo.d.ts.map +1 -1
  44. package/dist/generic/entityInfo.js +326 -22
  45. package/dist/generic/entityInfo.js.map +1 -1
  46. package/dist/generic/entityLifecyclePolicy.d.ts +214 -0
  47. package/dist/generic/entityLifecyclePolicy.d.ts.map +1 -0
  48. package/dist/generic/entityLifecyclePolicy.js +708 -0
  49. package/dist/generic/entityLifecyclePolicy.js.map +1 -0
  50. package/dist/generic/entitySubtypeDriver.d.ts +49 -0
  51. package/dist/generic/entitySubtypeDriver.d.ts.map +1 -0
  52. package/dist/generic/entitySubtypeDriver.js +26 -0
  53. package/dist/generic/entitySubtypeDriver.js.map +1 -0
  54. package/dist/generic/fieldSecuritySQLGate.d.ts +17 -0
  55. package/dist/generic/fieldSecuritySQLGate.d.ts.map +1 -1
  56. package/dist/generic/fieldSecuritySQLGate.js +41 -1
  57. package/dist/generic/fieldSecuritySQLGate.js.map +1 -1
  58. package/dist/generic/filters/compositeFilter.d.ts +5 -1
  59. package/dist/generic/filters/compositeFilter.d.ts.map +1 -1
  60. package/dist/generic/filters/compositeFilter.js +127 -12
  61. package/dist/generic/filters/compositeFilter.js.map +1 -1
  62. package/dist/generic/filters/compositeFilterSQL.d.ts +121 -0
  63. package/dist/generic/filters/compositeFilterSQL.d.ts.map +1 -0
  64. package/dist/generic/filters/compositeFilterSQL.js +489 -0
  65. package/dist/generic/filters/compositeFilterSQL.js.map +1 -0
  66. package/dist/generic/filters/filter.types.d.ts +5 -2
  67. package/dist/generic/filters/filter.types.d.ts.map +1 -1
  68. package/dist/generic/filters/filter.types.js +4 -1
  69. package/dist/generic/filters/filter.types.js.map +1 -1
  70. package/dist/generic/filters/filterBuilder.d.ts +75 -0
  71. package/dist/generic/filters/filterBuilder.d.ts.map +1 -0
  72. package/dist/generic/filters/filterBuilder.js +104 -0
  73. package/dist/generic/filters/filterBuilder.js.map +1 -0
  74. package/dist/generic/filters/index.d.ts +2 -0
  75. package/dist/generic/filters/index.d.ts.map +1 -1
  76. package/dist/generic/filters/index.js +2 -0
  77. package/dist/generic/filters/index.js.map +1 -1
  78. package/dist/generic/interfaces.d.ts +56 -1
  79. package/dist/generic/interfaces.d.ts.map +1 -1
  80. package/dist/generic/interfaces.js +0 -1
  81. package/dist/generic/interfaces.js.map +1 -1
  82. package/dist/generic/localCacheManager.d.ts +46 -3
  83. package/dist/generic/localCacheManager.d.ts.map +1 -1
  84. package/dist/generic/localCacheManager.js +267 -45
  85. package/dist/generic/localCacheManager.js.map +1 -1
  86. package/dist/generic/metadata.d.ts +3 -1
  87. package/dist/generic/metadata.d.ts.map +1 -1
  88. package/dist/generic/metadata.js +25 -6
  89. package/dist/generic/metadata.js.map +1 -1
  90. package/dist/generic/providerBase.d.ts +212 -33
  91. package/dist/generic/providerBase.d.ts.map +1 -1
  92. package/dist/generic/providerBase.js +543 -117
  93. package/dist/generic/providerBase.js.map +1 -1
  94. package/dist/generic/queryInfo.d.ts +5 -0
  95. package/dist/generic/queryInfo.d.ts.map +1 -1
  96. package/dist/generic/queryInfo.js +5 -0
  97. package/dist/generic/queryInfo.js.map +1 -1
  98. package/dist/generic/queryInfoInterfaces.d.ts +5 -0
  99. package/dist/generic/queryInfoInterfaces.d.ts.map +1 -1
  100. package/dist/generic/remoteOperationDispatch.d.ts.map +1 -1
  101. package/dist/generic/remoteOperationDispatch.js +13 -1
  102. package/dist/generic/remoteOperationDispatch.js.map +1 -1
  103. package/dist/generic/saveEntityGraphOperation.d.ts +6 -0
  104. package/dist/generic/saveEntityGraphOperation.d.ts.map +1 -1
  105. package/dist/generic/saveEntityGraphOperation.js +8 -0
  106. package/dist/generic/saveEntityGraphOperation.js.map +1 -1
  107. package/dist/generic/transactionGroup.d.ts +25 -0
  108. package/dist/generic/transactionGroup.d.ts.map +1 -1
  109. package/dist/generic/transactionGroup.js +105 -0
  110. package/dist/generic/transactionGroup.js.map +1 -1
  111. package/dist/generic/typedQuery.d.ts +151 -0
  112. package/dist/generic/typedQuery.d.ts.map +1 -0
  113. package/dist/generic/typedQuery.js +286 -0
  114. package/dist/generic/typedQuery.js.map +1 -0
  115. package/dist/generic/util.d.ts.map +1 -1
  116. package/dist/generic/util.js +9 -3
  117. package/dist/generic/util.js.map +1 -1
  118. package/dist/index.d.ts +6 -0
  119. package/dist/index.d.ts.map +1 -1
  120. package/dist/index.js +6 -0
  121. package/dist/index.js.map +1 -1
  122. package/dist/views/runView.d.ts +53 -0
  123. package/dist/views/runView.d.ts.map +1 -1
  124. package/dist/views/runView.js +134 -0
  125. package/dist/views/runView.js.map +1 -1
  126. package/package.json +3 -3
@@ -17,13 +17,14 @@ import { LibraryInfo } from "./libraryInfo.js";
17
17
  import { CompositeKey } from "./compositeKey.js";
18
18
  import { ExplorerNavigationItem } from "./explorerNavigationItem.js";
19
19
  import { Metadata } from "./metadata.js";
20
- import { RunView, IsMaterializedDataSource } from "../views/runView.js";
20
+ import { RunView, IsMaterializedDataSource, ExtractRunViewParameterNames } from "../views/runView.js";
21
21
  import { IsPlatformSQL } from "./platformSQL.js";
22
22
  import { GetDataHooks } from "./dataHooks.js";
23
23
  import { TransformSimpleObjectToEntityObject } from "./util.js";
24
24
  import { LoadRelatedRecordsBatched } from "./relatedRecordBatchLoader.js";
25
25
  import { GetLocalTimeZone } from "./contextTokens.js";
26
26
  import { FindQueryContextTokens, QueryContextCacheValues } from "./queryTemplateContext.js";
27
+ import { CompositeFilterSQLCompiler } from "./filters/compositeFilterSQL.js";
27
28
  /**
28
29
  * Creates a new instance of AllMetadata from a simple object.
29
30
  * Handles deserialization and proper instantiation of all metadata classes.
@@ -209,6 +210,14 @@ export class ProviderBase {
209
210
  * acts on its answer. Held as the promise (not a flag) so only its owner clears it.
210
211
  */
211
212
  this._refreshCheckInFlight = null;
213
+ /**
214
+ * The remote timestamps stored by the last refresh check whose status read succeeded; null after
215
+ * a check whose read failed. {@link RefreshIfNeeded} reuses the stored remote timestamps for its
216
+ * scoped reload only while they are this array, so a check whose read failed is followed by a
217
+ * fresh read. This prefers fresher stamps; it is not needed for correctness, because any stored
218
+ * stamps were read before the scoped dataset read starts.
219
+ */
220
+ this._checkedRemoteMetadataTimestamps = null;
212
221
  /**
213
222
  * Set when Config() adopts a snapshot it loaded from the server (which fetched the current user
214
223
  * with it); consumed by the next {@link preValidateAndRefresh}, which then has nothing to check.
@@ -221,8 +230,10 @@ export class ProviderBase {
221
230
  * so the caller's promise resolves with only their slice of results.
222
231
  */
223
232
  this._coalesceQueue = [];
224
- /** Timer handle for the coalesce flush */
233
+ /** Timer handle for the coalesce flush (when `CoalesceUseMicrotask === false`) */
225
234
  this._coalesceTimer = null;
235
+ /** True while a microtask-drain coalesce flush is scheduled */
236
+ this._coalesceMicrotaskScheduled = false;
226
237
  /**
227
238
  * In-flight + linger cache keyed by a deterministic fingerprint of
228
239
  * the RunViewParams batch. While a request is in-flight, concurrent
@@ -268,14 +279,19 @@ export class ProviderBase {
268
279
  */
269
280
  this._metadataReadsJoinTransaction = false;
270
281
  /**
271
- * The MJ_Metadata dataset items (code + entity name + row count) as of the last load. The remote
272
- * timestamps ({@link GetLatestMetadataUpdates}) are keyed by entity name while a dataset
273
- * read is scoped by item code, so this is the bridge that lets a staleness check be turned
274
- * into a scoped reload (see {@link PartialRefreshItemCodes}) and lets {@link adoptServerMetadata}
275
- * verify that the received dataset items' row counts match `_latestRemoteMetadataTimestamps`.
282
+ * The MJ_Metadata dataset items (code + entity name + row count) as of the last load, or as
283
+ * stored beside the snapshot a warm boot restored. The remote timestamps
284
+ * ({@link GetLatestMetadataUpdates}) are keyed by entity name while a dataset read is scoped by
285
+ * item code, so this is the bridge that lets a staleness check be turned into a scoped reload
286
+ * (see {@link MetadataRefreshScope}) and lets {@link adoptServerMetadata} verify that the
287
+ * received dataset items' row counts match `_latestRemoteMetadataTimestamps`.
276
288
  */
277
289
  this._metadataDatasetItems = null;
278
- /** Debounce timer for {@link scheduleMetadataMemberRefresh}. */
290
+ /** Failed refresh attempts in a row; picks the next delay from {@link MetadataRefreshRetryDelaysMs}. */
291
+ this._metadataRefreshRetries = 0;
292
+ /** Failed scoped reloads in a row; see {@link MetadataScopedReloadAttempts}. */
293
+ this._metadataScopedReloadFailures = 0;
294
+ /** Debounce timer for {@link scheduleMetadataMemberRefresh}, and for {@link scheduleMetadataRefreshRetry}. */
279
295
  this._metadataMemberRefreshTimer = null;
280
296
  // ── Metadata change notices from other servers ─────────────────────
281
297
  /** When the current run of undebounced peer notices began; caps how long the check is deferred. */
@@ -284,6 +300,17 @@ export class ProviderBase {
284
300
  this._peerMetadataNoticeRetries = 0;
285
301
  /** Debounce timer for {@link HandlePeerMetadataNotice}. */
286
302
  this._peerMetadataNoticeTimer = null;
303
+ /**
304
+ * Set by a write-event refresh that found a reload in flight and queued a follow-up pass; that
305
+ * pass consumes it and applies {@link applyWriteEventRule}. Without it the follow-up would take
306
+ * "no item moved" as "nothing changed", and the writer could miss its own write.
307
+ */
308
+ this._metadataWriteEventPending = false;
309
+ /**
310
+ * Set by an explicit full reload (a `Refresh()`) that found a reload in flight and queued a
311
+ * follow-up pass; that pass consumes it and runs in full, so the promise of a full reload holds.
312
+ */
313
+ this._metadataFullReloadRequested = false;
287
314
  this._metadataMemberRefreshWaits = 0;
288
315
  this._clientFingerprintMemo = new WeakMap();
289
316
  this._requestDeniedReadFields = new WeakMap();
@@ -364,6 +391,17 @@ export class ProviderBase {
364
391
  * all engines that fire in the same tick, without adding perceptible delay.
365
392
  */
366
393
  static { this.CoalesceWindowMs = 10; }
394
+ /**
395
+ * Controls whether `RunViews` coalescing drains via microtasks (`queueMicrotask`) instead
396
+ * of a wall-clock `setTimeout(..., CoalesceWindowMs)` timer when `CoalesceWindowMs > 0`.
397
+ *
398
+ * When `true` (default), concurrent calls in the same synchronous turn or immediate
399
+ * `Promise` / `BaseEngine.Load` microtask hops coalesce into one mega-batch and flush as
400
+ * soon as the microtask queue stabilizes (bounded at 8 hops), eliminating the 10–16ms timer
401
+ * floor (and ~1,000ms background-tab timer throttling) on isolated queries. Set to `false`
402
+ * to use the fixed `setTimeout(..., CoalesceWindowMs)` timer window.
403
+ */
404
+ static { this.CoalesceUseMicrotask = true; }
367
405
  // ── Request Deduplication + Linger Window ──────────────────────────
368
406
  /**
369
407
  * How long (ms) a resolved RunViews result stays available for instant
@@ -636,6 +674,33 @@ export class ProviderBase {
636
674
  static { this._queryFamilyItemCodes = [
637
675
  'QueryCategories', 'Queries', 'QueryFields', 'QueryPermissions', 'QueryEntities', 'QueryParameters', 'QueryDependencies', 'QuerySQLs',
638
676
  ]; }
677
+ /**
678
+ * MJ_Metadata item codes that {@link GetAllMetadata} reads to build the metadata: every
679
+ * {@link AllMetadataArrays} item, plus the items it folds into entities and applications. The
680
+ * shipped dataset also carries items the build never reads (`Dashboards`,
681
+ * `Dashboard_Categories`); a change to one of those cannot change the built metadata, so it
682
+ * needs no reload (see {@link MetadataRefreshScope}).
683
+ */
684
+ static get MetadataBuildItemCodes() {
685
+ return ProviderBase._metadataBuildItemCodes;
686
+ }
687
+ /** The items {@link GetAllMetadata} folds into entities (PostProcessEntityMetadata) and applications. */
688
+ static { this._metadataFoldedItemCodes = [
689
+ 'EntityFields', 'EntityFieldValues', 'EntityPermissions', 'EntityRelationships', 'EntitySettings', 'EntityOrganicKeys',
690
+ 'EntityOrganicKeyRelatedEntities', 'EntityFieldPermissions', 'EntityAlternateBaseViews', 'EntityUniqueKeys',
691
+ 'ApplicationEntities', 'ApplicationSettings',
692
+ ]; }
693
+ static { this._metadataBuildItemCodes = new Set([...AllMetadataArrays.map(m => m.key.substring(3)), ...ProviderBase._metadataFoldedItemCodes]); }
694
+ /**
695
+ * Delays, in milliseconds, before each retry of a metadata refresh that failed; the last one
696
+ * repeats. A failed timestamp read, a failed scoped reload and a failed full reload all keep
697
+ * the metadata already loaded and try again later. None of them escalates to a full reload:
698
+ * that is the most expensive read the provider makes, and these failures come when the server
699
+ * is busiest (an exhausted connection pool, a timed-out status query).
700
+ */
701
+ static { this.MetadataRefreshRetryDelaysMs = [15000, 30000, 60000, 120000, 300000]; }
702
+ /** Failed scoped reloads in a row before the full reload is used instead. */
703
+ static { this.MetadataScopedReloadAttempts = 3; }
639
704
  /** The synthetic roll-up row {@link GetLatestMetadataUpdates} appends to the per-entity timestamps. */
640
705
  static { this._allMetadataTypeName = 'All Entity Metadata'; }
641
706
  /**
@@ -955,12 +1020,27 @@ export class ProviderBase {
955
1020
  this._peerMetadataNoticeTimer = timer;
956
1021
  }
957
1022
  /**
958
- * How this provider refreshes after a metadata member entity changed. The base behavior is a
959
- * hard {@link Refresh} — correct for database providers, where the process that PERFORMED the
960
- * write is the one refreshing, so re-checking staleness first is wasted work and the re-read
961
- * must bypass every cache layer. Transport providers (GraphQL) override this with a staleness
962
- * check so a browser doesn't re-pull the full metadata graph for a change the server-side
963
- * timestamp comparison can disconfirm.
1023
+ * How this provider refreshes after a metadata member entity changed. The base behavior
1024
+ * re-reads the authoritative timestamps once (the status query is read from the database
1025
+ * every time, never from a cache layer) and reloads only what they show changed — see
1026
+ * {@link MetadataRefreshScope}: nothing, the saved-query family (through
1027
+ * {@link ReloadMetadata}, which reuses that read instead of reading the timestamps again), or
1028
+ * everything (a hard {@link Refresh}, which bypasses every cache layer).
1029
+ *
1030
+ * The caller holds positive evidence that a member entity was written, so "no item moved" is
1031
+ * NOT taken as "nothing changed" here: a write committed with a stamp older than the item's
1032
+ * current max — on PostgreSQL `NOW()` is the transaction start, so any in-place edit inside a
1033
+ * transaction that outlived a peer's later write; on SQL Server the statement-to-commit
1034
+ * window — leaves both the max stamp and the row count where they were. Only a change the
1035
+ * timestamps positively attribute to items the metadata build never reads (`Dashboards`) is
1036
+ * answered without a reload. The same rule governs the follow-up pass that a write arriving
1037
+ * mid-reload queues (see `_metadataWriteEventPending`).
1038
+ *
1039
+ * A timestamp read that fails while metadata is loaded is retried on
1040
+ * {@link MetadataRefreshRetryDelaysMs}; it is not a reason for a full reload. With nothing
1041
+ * loaded there is nothing to keep serving, so the full load runs. Transport providers
1042
+ * (GraphQL) override this with a staleness check so a browser doesn't re-pull the full
1043
+ * metadata graph for a change the server-side timestamp comparison can disconfirm.
964
1044
  */
965
1045
  async RefreshAfterMetadataMemberChange() {
966
1046
  if (this.MetadataMemberRefreshMustWait) {
@@ -984,26 +1064,99 @@ export class ProviderBase {
984
1064
  // concurrently here, because that mutates _latestRemoteMetadataTimestamps out from under
985
1065
  // the in-flight pass before it runs adoptServerMetadata(). Instead, delegate directly to
986
1066
  // ReloadMetadata, which sets _metadataReloadQueued = true and re-reads authoritative
987
- // remote timestamps at the start of the queued follow-up pass.
1067
+ // remote timestamps at the start of the queued follow-up pass. That pass must apply the
1068
+ // write-event rule (no item moved ⇒ full reload), so the evidence is handed to it.
1069
+ this._metadataWriteEventPending = true;
988
1070
  return this.ReloadMetadata(true, undefined, true);
989
1071
  }
1072
+ if (!this.AllowRefresh) {
1073
+ return this.Refresh();
1074
+ }
990
1075
  // The writer holds positive evidence, so the timestamps are re-read from the authoritative
991
- // status query. When they attribute the change entirely to the saved-query family (see
992
- // PartialRefreshMetadataItemCodes) only that family is reloaded, cache layers bypassed as a
993
- // hard refresh would. Anything that cannot be attributed — another item moved, the status
994
- // read failed, or it claims nothing changed — keeps the base policy: a HARD Refresh().
995
- let scoped = false;
1076
+ // status query, and only what they show changed is reloaded (see MetadataRefreshScope). A
1077
+ // change only to items the build never reads needs no reload. But "no item moved at all"
1078
+ // is not trusted here: a committed write can leave the max stamp and the row count where
1079
+ // they were (see the method doc), and the writer must see its own write.
1080
+ let timestampsRead = false;
996
1081
  try {
997
- scoped = this.AllowRefresh && await this.RefreshRemoteMetadataTimestamps() && this.PartialRefreshItemCodes() !== null;
1082
+ timestampsRead = await this.RefreshRemoteMetadataTimestamps();
998
1083
  }
999
1084
  catch (e) {
1000
- LogError(`Metadata refresh after a member-entity change could not read the timestamps; running a full refresh: ${e instanceof Error ? e.message : String(e)}`);
1085
+ LogError(`[Metadata] A refresh after a metadata change could not read the timestamps: ${e instanceof Error ? e.message : String(e)}`);
1001
1086
  }
1002
- if (scoped) {
1003
- return this.ReloadMetadata(true, undefined, true);
1087
+ if (!timestampsRead) {
1088
+ if (this.holdsMetadata) {
1089
+ this.scheduleMetadataRefreshRetry('the metadata timestamps could not be read');
1090
+ return true;
1091
+ }
1092
+ return this.Refresh(); // nothing loaded to keep serving
1093
+ }
1094
+ const scope = ProviderBase.applyWriteEventRule(this.MetadataRefreshScope());
1095
+ if (scope.Kind === 'none') {
1096
+ this.markMetadataCurrent();
1097
+ return true;
1004
1098
  }
1099
+ if (scope.Kind === 'scoped') {
1100
+ return this.ReloadMetadata(true, undefined, true, true);
1101
+ }
1102
+ LogStatus(`[Metadata] Full reload needed: ${scope.Reason}`);
1005
1103
  return this.Refresh();
1006
1104
  }
1105
+ /**
1106
+ * The write-event rule: a refresh prompted by a member-entity write knows something changed, so
1107
+ * a `none` scope in which no item moved at all becomes a full reload. A `none` in which only
1108
+ * items the build never reads moved stands — the timestamps positively attribute the change.
1109
+ */
1110
+ static applyWriteEventRule(scope) {
1111
+ if (scope.Kind === 'none' && !scope.AnyItemMoved) {
1112
+ return { Kind: 'full', Reason: 'a metadata member entity was written, but no item timestamp moved' };
1113
+ }
1114
+ return scope;
1115
+ }
1116
+ /** True when this provider holds metadata it can keep serving while a refresh is retried. */
1117
+ get holdsMetadata() {
1118
+ return (this._localMetadata?.AllEntities?.length ?? 0) > 0;
1119
+ }
1120
+ /**
1121
+ * Runs {@link RefreshAfterMetadataMemberChange} again after the next delay in
1122
+ * {@link MetadataRefreshRetryDelaysMs}. The retry shares the member-change timer: a refresh
1123
+ * that is already pending covers it, a new write re-arms it with the short debounce, and
1124
+ * {@link CancelPendingMetadataMemberRefresh} cancels it. The timer does not keep a Node
1125
+ * process alive.
1126
+ */
1127
+ scheduleMetadataRefreshRetry(reason) {
1128
+ if (this._metadataMemberRefreshTimer) {
1129
+ return;
1130
+ }
1131
+ const delays = ProviderBase.MetadataRefreshRetryDelaysMs;
1132
+ const delay = delays.length > 0 ? delays[Math.min(this._metadataRefreshRetries, delays.length - 1)] : 0;
1133
+ this._metadataRefreshRetries++;
1134
+ LogStatus(`[Metadata] Refresh postponed (${reason}); trying again in ${Math.round(delay / 1000)} s`);
1135
+ const timer = setTimeout(() => {
1136
+ this._metadataMemberRefreshTimer = null;
1137
+ this.RefreshAfterMetadataMemberChange().catch((e) => {
1138
+ LogError(`Metadata refresh retry failed: ${e instanceof Error ? e.message : String(e)}`);
1139
+ });
1140
+ }, delay);
1141
+ if (typeof timer === 'object' && timer !== null && 'unref' in timer) {
1142
+ timer.unref();
1143
+ }
1144
+ this._metadataMemberRefreshTimer = timer;
1145
+ }
1146
+ /**
1147
+ * The timestamps show nothing the metadata build reads has changed: stamp the held snapshot
1148
+ * with them, so the next check agrees. Only the in-memory stamp moves; re-saving the snapshot
1149
+ * would serialize the whole graph for a change it does not contain.
1150
+ */
1151
+ markMetadataCurrent() {
1152
+ this._latestLocalMetadataTimestamps = this._latestRemoteMetadataTimestamps;
1153
+ this.resetMetadataRefreshFailures();
1154
+ }
1155
+ /** The metadata is current again: the next failure starts at the first retry delay. */
1156
+ resetMetadataRefreshFailures() {
1157
+ this._metadataRefreshRetries = 0;
1158
+ this._metadataScopedReloadFailures = 0;
1159
+ }
1007
1160
  /**
1008
1161
  * How many consecutive windows a member-change refresh may wait on
1009
1162
  * {@link MetadataMemberRefreshMustWait} before it is dropped. At the default 500ms window
@@ -1428,18 +1581,46 @@ export class ProviderBase {
1428
1581
  resolve: resolve,
1429
1582
  reject
1430
1583
  });
1431
- // Start the coalesce timer if not already running
1432
- if (!this._coalesceTimer) {
1584
+ if (ProviderBase.CoalesceUseMicrotask) {
1585
+ if (!this._coalesceMicrotaskScheduled && !this._coalesceTimer) {
1586
+ this._coalesceMicrotaskScheduled = true;
1587
+ this.scheduleMicrotaskCoalesceDrain(this._coalesceQueue.length, 0);
1588
+ }
1589
+ }
1590
+ else if (!this._coalesceTimer && !this._coalesceMicrotaskScheduled) {
1591
+ // Start the coalesce timer if not already running
1433
1592
  this._coalesceTimer = setTimeout(() => this.flushCoalesceQueue(), ProviderBase.CoalesceWindowMs);
1434
1593
  }
1435
1594
  });
1436
1595
  }
1596
+ /**
1597
+ * Drains the coalesce queue via `queueMicrotask`. Yields a minimum of 6 microtask hops
1598
+ * (~4µs) so sibling `StartupManager` engines finishing their initial `ResolveContextUser`
1599
+ * and `PreRunViews` awaits reach the queue, and continues yielding (bounded at 16 hops)
1600
+ * while queue length is still growing; flushes immediately once queue growth settles.
1601
+ */
1602
+ scheduleMicrotaskCoalesceDrain(seenLength, hop) {
1603
+ queueMicrotask(() => {
1604
+ const currentLength = this._coalesceQueue.length;
1605
+ if (currentLength === 0) {
1606
+ this._coalesceMicrotaskScheduled = false;
1607
+ return;
1608
+ }
1609
+ if (hop < 6 || (currentLength > seenLength && hop < 16)) {
1610
+ this.scheduleMicrotaskCoalesceDrain(currentLength, hop + 1);
1611
+ return;
1612
+ }
1613
+ this._coalesceMicrotaskScheduled = false;
1614
+ void this.flushCoalesceQueue();
1615
+ });
1616
+ }
1437
1617
  /**
1438
1618
  * Flushes the coalesce queue: merges all pending RunViews params into one
1439
1619
  * mega-batch, executes it, then splits results back to each original caller.
1440
1620
  */
1441
1621
  async flushCoalesceQueue() {
1442
1622
  this._coalesceTimer = null;
1623
+ this._coalesceMicrotaskScheduled = false;
1443
1624
  // Grab and clear the queue atomically
1444
1625
  const queue = this._coalesceQueue.splice(0);
1445
1626
  if (queue.length === 0)
@@ -1737,7 +1918,24 @@ export class ProviderBase {
1737
1918
  * widens and caches.
1738
1919
  */
1739
1920
  shouldWidenAndPopulateCache(param) {
1740
- return this.runViewCacheEligible(param);
1921
+ if (!this.runViewCacheEligible(param)) {
1922
+ return false;
1923
+ }
1924
+ // On the server, when the caller requested a narrow `Fields` projection without
1925
+ // explicitly asking for `CacheLocal: true`, do not widen to `SELECT *` when:
1926
+ // 1. `UserSearchString` is populated (ad-hoc search-as-you-type queries would otherwise
1927
+ // pull every wide NVARCHAR(MAX) column and allocate per-keystroke cache slots), or
1928
+ // 2. `LocalCacheManager` is currently batching writes for this provider (`SetRunViewResult`
1929
+ // drops cache writes while a write batch is open, so widening would be pure waste).
1930
+ if (this.TrustLocalCacheCompletely && param.CacheLocal !== true && this.hasNarrowFieldsOverride(param)) {
1931
+ if ((param.UserSearchString ?? '').trim().length > 0) {
1932
+ return false;
1933
+ }
1934
+ if (LocalCacheManager.Instance.IsInitialized && LocalCacheManager.Instance.IsBatchingEntityEvents(this)) {
1935
+ return false;
1936
+ }
1937
+ }
1938
+ return true;
1741
1939
  }
1742
1940
  /**
1743
1941
  * True when the request targets an `AlternateBaseView` (explicitly on `param.AlternateBaseView`
@@ -2950,9 +3148,16 @@ export class ProviderBase {
2950
3148
  if (!entity) {
2951
3149
  return;
2952
3150
  }
3151
+ if (params.Filter) {
3152
+ CompositeFilterSQLCompiler.AssertFieldsAllowed(params.Filter, entity, contextUser);
3153
+ }
2953
3154
  const view = params.ViewEntity;
3155
+ const parameterNames = ExtractRunViewParameterNames(params.Parameters);
3156
+ if (parameterNames.size > 0) {
3157
+ this.AssertClausesRespectFieldSecurityForEntity(entity, [params.ExtraFilter], contextUser, parameterNames);
3158
+ }
2954
3159
  this.AssertClausesRespectFieldSecurityForEntity(entity, [
2955
- params.ExtraFilter,
3160
+ ...(parameterNames.size > 0 ? [] : [params.ExtraFilter]),
2956
3161
  params.OverrideExcludeFilter,
2957
3162
  ...(params.Aggregates ?? []).map(a => a?.expression),
2958
3163
  view ? view.Get('WhereClause') : undefined,
@@ -2971,8 +3176,8 @@ export class ProviderBase {
2971
3176
  * The shared entry point for every clause slot a provider runs: RunView parameters, a saved
2972
3177
  * view's stored clauses, dataset item filters, user-search text spliced as SQL.
2973
3178
  */
2974
- AssertClausesRespectFieldSecurityForEntity(entity, clauses, user) {
2975
- this.assertFragmentsAllowed(entity, clauses, user, (sql, context) => FieldSecuritySQLGate.FindViolation(sql, context));
3179
+ AssertClausesRespectFieldSecurityForEntity(entity, clauses, user, parameterNames) {
3180
+ this.assertFragmentsAllowed(entity, clauses, user, (sql, context) => FieldSecuritySQLGate.FindViolation(sql, context), parameterNames);
2976
3181
  }
2977
3182
  /**
2978
3183
  * {@link AssertClausesRespectFieldSecurityForEntity} for ORDER BY fragments, which also refuses
@@ -2983,8 +3188,14 @@ export class ProviderBase {
2983
3188
  this.assertFragmentsAllowed(entity, orderBys, user, (sql, context) => FieldSecuritySQLGate.FindSortViolation(sql, context));
2984
3189
  }
2985
3190
  /** Throws the field-security error for the first of `fragments` that `find` refuses. */
2986
- assertFragmentsAllowed(entity, fragments, user, find) {
2987
- const context = { User: user, Dialect: this.PlatformKey, Catalog: this.Entities, TargetEntity: entity };
3191
+ assertFragmentsAllowed(entity, fragments, user, find, parameterNames) {
3192
+ const context = {
3193
+ User: user,
3194
+ Dialect: this.PlatformKey,
3195
+ Catalog: this.Entities,
3196
+ TargetEntity: entity,
3197
+ ParameterNames: parameterNames,
3198
+ };
2988
3199
  for (const clause of fragments) {
2989
3200
  if (typeof clause !== 'string' || clause.trim().length === 0) {
2990
3201
  continue;
@@ -4322,6 +4533,12 @@ export class ProviderBase {
4322
4533
  // bypass in runViewCacheEligible; this covers the query-materialization Live-read path.)
4323
4534
  if (entity.VirtualEntity && entity.BaseView && entity.BaseView.toLowerCase().startsWith('materialized_vw'))
4324
4535
  return false;
4536
+ // External data-source entities (federated REST/SQL connectors) are never event-invalidated
4537
+ // and `LocalCacheManager.SetRunViewResult` skips them unless an explicit `ttlMs` is passed
4538
+ // (`PostRunView` never passes `ttlMs`), so treating them as server-cacheable only forces
4539
+ // wasted `Fields` widening and futile cache lookups.
4540
+ if (entity.ExternalDataSourceID)
4541
+ return false;
4325
4542
  return entity.TrustServerCacheCompletely !== false;
4326
4543
  }
4327
4544
  shouldAutoCache(params, result, contextUser) {
@@ -4908,12 +5125,18 @@ export class ProviderBase {
4908
5125
  /**
4909
5126
  * Reloads this provider's metadata. Single-flight: at most one reload runs at a time, and a
4910
5127
  * request arriving mid-reload queues exactly one follow-up pass.
4911
- * @param hardRefresh - re-read the remote timestamps first and bypass every cache layer
4912
- * @param scopedFirst - try the scoped reload of the saved-query family (see
4913
- * {@link PartialRefreshMetadataItemCodes}) before the full one. Defaults to true unless
4914
- * hardRefresh: an explicit Refresh() is always a full reload.
4915
- */
4916
- async ReloadMetadata(hardRefresh, providerToUse, scopedFirst = !hardRefresh) {
5128
+ * @param hardRefresh - re-read the remote timestamps first (unless `stampsFresh`) and bypass
5129
+ * every cache layer
5130
+ * @param scopedFirst - reload only what the timestamps show changed (see
5131
+ * {@link MetadataRefreshScope}): nothing, the saved-query family (see
5132
+ * {@link PartialRefreshMetadataItemCodes}), or everything. Defaults to true unless
5133
+ * hardRefresh: an explicit Refresh() is always a full reload, and so is one that joins a
5134
+ * reload already in flight — the follow-up pass it queues runs in full. A pass that may be
5135
+ * scoped but cannot read the timestamps keeps the metadata loaded and is retried later.
5136
+ * @param stampsFresh - the caller read the remote timestamps just before this call. The first
5137
+ * hard pass then uses them instead of reading them again; a queued follow-up pass still reads.
5138
+ */
5139
+ async ReloadMetadata(hardRefresh, providerToUse, scopedFirst = !hardRefresh, stampsFresh = false) {
4917
5140
  // first, make sure we reset the flag to false so that if another call to this function happens
4918
5141
  // while we are waiting for the async call to finish, we dont do it again
4919
5142
  this._refresh = false;
@@ -4926,6 +5149,10 @@ export class ProviderBase {
4926
5149
  // guaranteeing the final swap comes from a read that started after the last request.
4927
5150
  if (this._metadataReloadInFlight) {
4928
5151
  this._metadataReloadQueued = true;
5152
+ if (!scopedFirst) {
5153
+ // An explicit Refresh() promises a full reload; the follow-up pass keeps that promise.
5154
+ this._metadataFullReloadRequested = true;
5155
+ }
4929
5156
  if (this._metadataReadsJoinTransaction) {
4930
5157
  // Caller owns an open database transaction (RefreshWithinTransaction) and is
4931
5158
  // waiting for this reload before it can COMMIT or ROLLBACK. An in-flight pool
@@ -4948,6 +5175,7 @@ export class ProviderBase {
4948
5175
  this._metadataReloadInFlight = (async () => {
4949
5176
  let effectiveHardRefresh = hardRefresh;
4950
5177
  let tryScoped = scopedFirst;
5178
+ let timestampsFresh = stampsFresh;
4951
5179
  do {
4952
5180
  this._metadataReloadQueued = false;
4953
5181
  // The local timestamps must describe the snapshot about to be loaded. On the
@@ -4957,29 +5185,34 @@ export class ProviderBase {
4957
5185
  // them (one cheap status query, authoritative) BEFORE the load, not after:
4958
5186
  // a write landing DURING the load then leaves the stamped timestamps looking
4959
5187
  // stale and the next tick reloads — the safe direction. Reading after could
4960
- // stamp the snapshot as containing a write it does not.
4961
- if (effectiveHardRefresh) {
4962
- await this.RefreshRemoteMetadataTimestamps(providerToUse);
5188
+ // stamp the snapshot as containing a write it does not. When the caller has just
5189
+ // read them (stampsFresh), the first pass uses that read.
5190
+ let timestampsRead = true;
5191
+ if (effectiveHardRefresh && !timestampsFresh) {
5192
+ timestampsRead = await this.RefreshRemoteMetadataTimestamps(providerToUse);
4963
5193
  }
4964
- // SCOPED FIRST: when the staleness is attributable entirely to the saved-query family
4965
- // (see PartialRefreshMetadataItemCodes), reload just that family and keep every other
4966
- // array as is. Anything else — or a failed scoped read — takes the full reload below.
4967
- const scopedDone = tryScoped && await this.TryPartialMetadataReload(providerToUse);
4968
- if (!scopedDone) {
4969
- // Fetch new metadata without clearing current metadata
4970
- // This ensures readers always see valid data (old until new is ready)
4971
- const start = new Date().getTime();
4972
- const res = await this.GetAllMetadata(providerToUse, effectiveHardRefresh);
4973
- const end = new Date().getTime();
4974
- LogStatus(`GetAllMetadata() took ${end - start} ms`);
4975
- if (res) {
4976
- await this.adoptServerMetadata(res);
4977
- this._configLoadedFromServer = true;
4978
- }
4979
- else {
4980
- // GetAllMetadata failed - log error but keep existing metadata
4981
- LogError('GetAllMetadata() returned undefined - metadata not updated');
4982
- }
5194
+ // SCOPED FIRST: reload only what the timestamps show changed (see
5195
+ // MetadataRefreshScope) — nothing, the saved-query family with every other array kept
5196
+ // as is, or everything. A pass that may be scoped but could not read the timestamps
5197
+ // has no basis for choosing, so it keeps what is loaded and is retried later. A pass
5198
+ // that stands in for a write-event refresh applies the write-event rule (see
5199
+ // RefreshAfterMetadataMemberChange); one that stands in for an explicit Refresh()
5200
+ // runs in full.
5201
+ const fullRequested = this._metadataFullReloadRequested;
5202
+ this._metadataFullReloadRequested = false;
5203
+ const writeEvent = this._metadataWriteEventPending;
5204
+ this._metadataWriteEventPending = false;
5205
+ let scope = (!tryScoped || fullRequested)
5206
+ ? { Kind: 'full', Reason: 'a full reload was requested' }
5207
+ : (timestampsRead || !this.holdsMetadata) ? this.MetadataRefreshScope() : null;
5208
+ if (scope && writeEvent) {
5209
+ scope = ProviderBase.applyWriteEventRule(scope);
5210
+ }
5211
+ if (!scope) {
5212
+ this.scheduleMetadataRefreshRetry('the metadata timestamps could not be read');
5213
+ }
5214
+ else if (await this.applyMetadataRefreshScope(scope, providerToUse, effectiveHardRefresh)) {
5215
+ this._configLoadedFromServer = true;
4983
5216
  }
4984
5217
  // A queued follow-up exists only because another refresh request arrived
4985
5218
  // mid-reload; rerun hard so the re-read cannot be served by any cache layer.
@@ -4987,6 +5220,7 @@ export class ProviderBase {
4987
5220
  // The follow-up re-reads the timestamps first, so it may still be attributed to the
4988
5221
  // saved-query family — and a scoped read never trusts a cache layer either.
4989
5222
  tryScoped = true;
5223
+ timestampsFresh = false;
4990
5224
  } while (this._metadataReloadQueued);
4991
5225
  })();
4992
5226
  try {
@@ -4997,6 +5231,55 @@ export class ProviderBase {
4997
5231
  }
4998
5232
  return true;
4999
5233
  }
5234
+ /**
5235
+ * Carries out one reload pass for `scope`. A failed scoped reload is retried later; only the
5236
+ * {@link MetadataScopedReloadAttempts}-th failure in a row runs the full reload instead.
5237
+ * @returns true when a full snapshot was loaded from the server and adopted
5238
+ */
5239
+ async applyMetadataRefreshScope(scope, providerToUse, forceRefresh) {
5240
+ if (scope.Kind === 'none') {
5241
+ this.markMetadataCurrent();
5242
+ return false;
5243
+ }
5244
+ if (scope.Kind === 'full') {
5245
+ return this.reloadAllMetadata(providerToUse, forceRefresh, scope.Reason);
5246
+ }
5247
+ if (await this.TryPartialMetadataReload(providerToUse)) {
5248
+ this.resetMetadataRefreshFailures();
5249
+ return false;
5250
+ }
5251
+ const failures = ++this._metadataScopedReloadFailures;
5252
+ const limit = ProviderBase.MetadataScopedReloadAttempts;
5253
+ if (failures < limit) {
5254
+ this.scheduleMetadataRefreshRetry(`the scoped reload failed, ${failures} of ${limit}`);
5255
+ return false;
5256
+ }
5257
+ this._metadataScopedReloadFailures = 0;
5258
+ // A scoped read never trusts a cache layer, so neither does the reload that replaces it.
5259
+ return this.reloadAllMetadata(providerToUse, true, `the scoped reload failed ${limit} times in a row`);
5260
+ }
5261
+ /**
5262
+ * The full reload: fetches all metadata and adopts it. Readers keep the current metadata until
5263
+ * the new snapshot is ready, and keep it if the fetch fails; a failure while metadata is loaded
5264
+ * is retried later. Every full reload is logged with its reason and duration.
5265
+ * @returns true when the snapshot was loaded and adopted
5266
+ */
5267
+ async reloadAllMetadata(providerToUse, forceRefresh, reason) {
5268
+ const start = Date.now();
5269
+ const res = await this.GetAllMetadata(providerToUse, forceRefresh);
5270
+ if (!res) {
5271
+ // GetAllMetadata failed - log error but keep existing metadata
5272
+ LogError('GetAllMetadata() returned undefined - metadata not updated');
5273
+ if (this.holdsMetadata) {
5274
+ this.scheduleMetadataRefreshRetry('the full reload failed');
5275
+ }
5276
+ return false;
5277
+ }
5278
+ await this.adoptServerMetadata(res);
5279
+ this.resetMetadataRefreshFailures();
5280
+ LogStatus(`[Metadata] Full reload (${reason}) took ${Date.now() - start} ms`);
5281
+ return true;
5282
+ }
5000
5283
  /**
5001
5284
  * Adopts a metadata snapshot just loaded from the server: swaps it in, records that the
5002
5285
  * local copy now matches the server's timestamps (verified per item against the received
@@ -5028,6 +5311,7 @@ export class ProviderBase {
5028
5311
  const rollup = norm(ProviderBase._allMetadataTypeName);
5029
5312
  const prevLocal = this._latestLocalMetadataTimestamps ?? [];
5030
5313
  const datasetItems = this._metadataDatasetItems;
5314
+ const built = ProviderBase.MetadataBuildItemCodes;
5031
5315
  const resRecord = res;
5032
5316
  let hasMismatch = false;
5033
5317
  const reconciled = [];
@@ -5052,7 +5336,10 @@ export class ProviderBase {
5052
5336
  if (datasetItems && datasetItems.length > 0) {
5053
5337
  const match = (remoteEntry.ID ? datasetItemsByEntityID?.Get(remoteEntry.ID) : undefined)
5054
5338
  ?? datasetItemsByNameOrCode.get(norm(remoteEntry.Type));
5055
- if (match && match.RowCount !== undefined) {
5339
+ // Only items the build reads have a received count to check. The others (Dashboards)
5340
+ // are never read, so their recorded count is whatever the last full load saw; after a
5341
+ // scoped reload it would be stale and would report a mismatch that is not one.
5342
+ if (match && match.RowCount !== undefined && built.has(match.Code)) {
5056
5343
  receivedRowCount = match.RowCount;
5057
5344
  receivedUpdateDate = match.LatestUpdateDate;
5058
5345
  }
@@ -5123,24 +5410,38 @@ export class ProviderBase {
5123
5410
  return reconciled;
5124
5411
  }
5125
5412
  /**
5126
- * Decides whether the current staleness can be served by a scoped reload of the saved-query
5127
- * family. Compares local and remote timestamps item by item (the same test as
5128
- * {@link LocalMetadataObsolete}) and maps each stale entity back to its MJ_Metadata item code.
5129
- * @returns the family's item codes (the whole family — the query classes are swapped as a set)
5130
- * when every stale item belongs to it; null when anything else is stale, nothing is, or the
5131
- * inputs needed to attribute the change are missing — the full reload is then the answer.
5132
- */
5133
- PartialRefreshItemCodes() {
5413
+ * What a metadata refresh must reload, from the local and remote timestamps. Compares them
5414
+ * item by item (the same test as {@link LocalMetadataObsolete}) and maps each stale entity
5415
+ * back to its MJ_Metadata item code:
5416
+ *
5417
+ * - `none` — nothing {@link MetadataBuildItemCodes} names has changed. Either nothing moved,
5418
+ * or only items the metadata build never reads did (`Dashboards`).
5419
+ * - `scoped` — every change the build reads is in the saved-query family (see
5420
+ * {@link PartialRefreshMetadataItemCodes}); `Codes` is the whole family, since the query
5421
+ * classes are swapped as a set.
5422
+ * - `full` — anything else changed, or the change cannot be attributed (an unknown item, an
5423
+ * item that left the dataset, the roll-up moving with no item, or the inputs to compare are
5424
+ * missing). `Reason` says which, for the log.
5425
+ */
5426
+ MetadataRefreshScope() {
5134
5427
  const items = this._metadataDatasetItems;
5135
5428
  const local = this.LatestLocalMetadata;
5136
5429
  const remote = this.LatestRemoteMetadata;
5137
- if (!items?.length || !this._localMetadata?.AllEntities?.length || !local?.length || !remote?.length) {
5138
- return null;
5430
+ if (!this.holdsMetadata) {
5431
+ return { Kind: 'full', Reason: 'no metadata is loaded yet' };
5432
+ }
5433
+ if (!items?.length) {
5434
+ return { Kind: 'full', Reason: 'the metadata dataset items are not known' };
5435
+ }
5436
+ if (!local?.length || !remote?.length) {
5437
+ return { Kind: 'full', Reason: 'the metadata timestamps are not known' };
5139
5438
  }
5140
5439
  const family = new Set(ProviderBase.PartialRefreshMetadataItemCodes);
5440
+ const built = ProviderBase.MetadataBuildItemCodes;
5141
5441
  const norm = (v) => (v ?? '').trim().toLowerCase();
5142
5442
  const rollup = norm(ProviderBase._allMetadataTypeName);
5143
- let stale = 0;
5443
+ let anyItemChanged = false;
5444
+ let familyChanged = false;
5144
5445
  for (const r of remote) {
5145
5446
  if (norm(r.Type) === rollup) {
5146
5447
  continue; // the roll-up moves with any item; the per-item rows decide
@@ -5149,20 +5450,45 @@ export class ProviderBase {
5149
5450
  if (l && !ProviderBase.metadataStampChanged(l, r)) {
5150
5451
  continue;
5151
5452
  }
5453
+ anyItemChanged = true;
5152
5454
  const owners = items.filter(i => norm(i.EntityName) === norm(r.Type));
5153
- if (owners.length === 0 || owners.some(o => !family.has(o.Code))) {
5154
- return null; // something outside the family moved, or a new item appeared
5455
+ if (owners.length === 0) {
5456
+ return { Kind: 'full', Reason: `${r.Type} changed and is not a known metadata dataset item` };
5457
+ }
5458
+ const read = owners.filter(o => built.has(o.Code));
5459
+ if (read.length === 0) {
5460
+ continue; // an item the metadata build never reads
5155
5461
  }
5156
- stale++;
5462
+ if (read.some(o => !family.has(o.Code))) {
5463
+ return { Kind: 'full', Reason: `${r.Type} changed` };
5464
+ }
5465
+ familyChanged = true;
5466
+ }
5467
+ const removed = local.find(l => norm(l.Type) !== rollup && !remote.some(r => norm(r.Type) === norm(l.Type)));
5468
+ if (removed) {
5469
+ return { Kind: 'full', Reason: `${removed.Type} is no longer in the metadata dataset` };
5157
5470
  }
5158
- if (local.some(l => norm(l.Type) !== rollup && !remote.some(r => norm(r.Type) === norm(l.Type)))) {
5159
- return null; // an item left the dataset
5471
+ if (familyChanged) {
5472
+ const codes = [...new Set(items.map(i => i.Code).filter(c => family.has(c)))];
5473
+ return { Kind: 'scoped', Codes: codes };
5160
5474
  }
5161
- if (stale === 0) {
5162
- return null; // nothing attributable — the caller's own policy decides
5475
+ if (!anyItemChanged) {
5476
+ const localRollup = local.find(m => norm(m.Type) === rollup);
5477
+ const remoteRollup = remote.find(m => norm(m.Type) === rollup);
5478
+ if (remoteRollup && (!localRollup || ProviderBase.metadataStampChanged(localRollup, remoteRollup))) {
5479
+ return { Kind: 'full', Reason: 'the metadata timestamp moved, but no item did' };
5480
+ }
5163
5481
  }
5164
- const codes = [...new Set(items.map(i => i.Code).filter(c => family.has(c)))];
5165
- return codes.length > 0 ? codes : null;
5482
+ return { Kind: 'none', AnyItemMoved: anyItemChanged };
5483
+ }
5484
+ /**
5485
+ * The saved-query family's item codes when the current staleness can be served by a scoped
5486
+ * reload; null otherwise.
5487
+ * @deprecated Use {@link MetadataRefreshScope}, which also says when nothing needs reloading.
5488
+ */
5489
+ PartialRefreshItemCodes() {
5490
+ const scope = this.MetadataRefreshScope();
5491
+ return scope.Kind === 'scoped' ? [...scope.Codes] : null;
5166
5492
  }
5167
5493
  static metadataStampChanged(local, remote) {
5168
5494
  if (!local.UpdatedAt && !remote.UpdatedAt) {
@@ -5180,10 +5506,13 @@ export class ProviderBase {
5180
5506
  * requested with a `1=0` filter, so it reads nothing. Always bypasses cache layers — the read
5181
5507
  * is small, and a cached answer is exactly what a staleness check cannot trust.
5182
5508
  * @returns true when the scoped reload was applied; false when it does not apply or any part
5183
- * of it failed — the caller then runs the full reload, so a failure never leaves stale queries.
5509
+ * of it failed — the caller then retries it later, and after
5510
+ * {@link MetadataScopedReloadAttempts} failures in a row runs the full reload, so a failure
5511
+ * never leaves stale queries for good.
5184
5512
  */
5185
5513
  async TryPartialMetadataReload(providerToUse) {
5186
- const codes = this.PartialRefreshItemCodes();
5514
+ const scope = this.MetadataRefreshScope();
5515
+ const codes = scope.Kind === 'scoped' ? scope.Codes : null;
5187
5516
  const current = this._localMetadata;
5188
5517
  const items = this._metadataDatasetItems;
5189
5518
  if (!codes || !current || !items) {
@@ -5197,14 +5526,14 @@ export class ProviderBase {
5197
5526
  const start = Date.now();
5198
5527
  const d = await this.GetDatasetByName(ProviderBase._mjMetadataDatasetName, skipOthers, this.CurrentUser, providerToUse, true);
5199
5528
  if (!d?.Success) {
5200
- LogStatusEx({ message: `[Metadata] Scoped reload of ${codes.join(', ')} failed (${d?.Status ?? 'no result'}); running the full reload`, verboseOnly: true });
5529
+ LogStatus(`[Metadata] Scoped reload of ${codes.join(', ')} failed (${d?.Status ?? 'no result'})`);
5201
5530
  return false;
5202
5531
  }
5203
5532
  const simple = {};
5204
5533
  for (const code of codes) {
5205
5534
  const item = d.Results?.find(r => r.Code === code);
5206
5535
  if (!item || item.Success === false || !Array.isArray(item.Results)) {
5207
- LogStatusEx({ message: `[Metadata] Scoped reload: item ${code} ${item ? `failed (${item.Status ?? 'no rows'})` : 'missing'}; running the full reload`, verboseOnly: true });
5536
+ LogStatus(`[Metadata] Scoped reload: item ${code} ${item ? `failed (${item.Status ?? 'no rows'})` : 'missing'}`);
5208
5537
  return false;
5209
5538
  }
5210
5539
  simple[code] = item.Results;
@@ -5242,15 +5571,15 @@ export class ProviderBase {
5242
5571
  return true;
5243
5572
  }
5244
5573
  catch (e) {
5245
- LogError(`[Metadata] Scoped reload failed; running the full reload: ${e instanceof Error ? e.message : String(e)}`);
5574
+ LogError(`[Metadata] Scoped reload failed: ${e instanceof Error ? e.message : String(e)}`);
5246
5575
  return false;
5247
5576
  }
5248
5577
  }
5249
5578
  /**
5250
5579
  * Background validation for the stale-while-revalidate fast-start pattern.
5251
- * Checks if local metadata is still current; if stale, fetches fresh metadata
5252
- * and atomically swaps it in. The app continues operating on cached data
5253
- * during this process — no blocking.
5580
+ * Checks if local metadata is still current; if stale, reloads only what changed (see
5581
+ * {@link MetadataRefreshScope}) and atomically swaps it in. The app continues operating on
5582
+ * cached data during this process — no blocking.
5254
5583
  */
5255
5584
  async backgroundValidateAndRefresh(providerToUse) {
5256
5585
  try {
@@ -5258,12 +5587,8 @@ export class ProviderBase {
5258
5587
  if (needsRefresh) {
5259
5588
  LogStatusEx({ message: `⚡ [Metadata Cache] Background check: metadata is stale — refreshing...`, verboseOnly: true });
5260
5589
  const start = Date.now();
5261
- const res = await this.GetAllMetadata(providerToUse, false);
5262
- const elapsed = Date.now() - start;
5263
- if (res) {
5264
- await this.adoptServerMetadata(res);
5265
- LogStatusEx({ message: `⚡ [Metadata Cache] Background refresh complete (${elapsed}ms) — metadata updated in place`, verboseOnly: true });
5266
- }
5590
+ await this.reloadStaleCachedMetadata(providerToUse, true);
5591
+ LogStatusEx({ message: `⚡ [Metadata Cache] Background refresh complete (${Date.now() - start}ms) — metadata updated in place`, verboseOnly: true });
5267
5592
  }
5268
5593
  else {
5269
5594
  LogStatusEx({ message: `⚡ [Metadata Cache] Background check: metadata is current — no refresh needed`, verboseOnly: true });
@@ -5289,8 +5614,9 @@ export class ProviderBase {
5289
5614
  * engines start, then proceed normally.
5290
5615
  *
5291
5616
  * Cost on the warm-current path is one batched timestamp fetch (~50–200 ms depending
5292
- * on RTT). On the warm-stale path we additionally pay the full metadata fetch but
5293
- * avoid serving stale data to the UI in the first place.
5617
+ * on RTT). On the warm-stale path we additionally reload what changed — the saved-query
5618
+ * family alone when only saved queries moved, everything otherwise — but avoid serving
5619
+ * stale data to the UI in the first place.
5294
5620
  *
5295
5621
  * On a cold boot, where Config() just loaded the graph (and the current user) from the
5296
5622
  * server, the first call after that load returns immediately — no check, no current-user
@@ -5318,12 +5644,9 @@ export class ProviderBase {
5318
5644
  if (needsRefresh) {
5319
5645
  LogStatus(`⚡ [Metadata Cache] Pre-validation: metadata is stale — refreshing before engine startup`);
5320
5646
  const start = Date.now();
5321
- const res = await this.GetAllMetadata(providerToUse, false);
5322
- const elapsed = Date.now() - start;
5323
- if (res) {
5324
- await this.adoptServerMetadata(res);
5325
- LogStatus(`⚡ [Metadata Cache] Pre-validation refresh complete (${elapsed}ms)`);
5326
- }
5647
+ // The current user was refreshed beside the check above.
5648
+ await this.reloadStaleCachedMetadata(providerToUse, false);
5649
+ LogStatus(`⚡ [Metadata Cache] Pre-validation refresh complete (${Date.now() - start}ms)`);
5327
5650
  }
5328
5651
  else {
5329
5652
  LogStatus(`⚡ [Metadata Cache] Pre-validation: metadata is current`);
@@ -5333,6 +5656,25 @@ export class ProviderBase {
5333
5656
  LogError(`[Metadata Cache] Pre-validation failed: ${e instanceof Error ? e.message : String(e)} — engines will smart-cache-check`);
5334
5657
  }
5335
5658
  }
5659
+ /**
5660
+ * Brings cached metadata that a staleness check just found stale up to date, reloading only
5661
+ * what changed (see {@link MetadataRefreshScope}). The full reload replaces the snapshot
5662
+ * wholesale and fetches the current user with it; it is not {@link Config}'s load, so it does
5663
+ * not claim the cold-boot pre-validation skip. A scoped reload merges into the current
5664
+ * snapshot, so it runs inside {@link ReloadMetadata}'s single flight, where no other reload can
5665
+ * swap the snapshot out from under it; it fetches no user, so `refreshCurrentUser` asks for one.
5666
+ */
5667
+ async reloadStaleCachedMetadata(providerToUse, refreshCurrentUser) {
5668
+ const scope = this.MetadataRefreshScope();
5669
+ if (scope.Kind === 'full') {
5670
+ await this.reloadAllMetadata(providerToUse, false, scope.Reason);
5671
+ return;
5672
+ }
5673
+ await this.ReloadMetadata(false, providerToUse, true);
5674
+ if (refreshCurrentUser) {
5675
+ await this.RefreshCurrentUser();
5676
+ }
5677
+ }
5336
5678
  /**
5337
5679
  * @deprecated The reuse-global fast path now builds a shared shell instead — see
5338
5680
  * {@link CreateSharedMetadataShell}. The metadata graph is immutable after Config,
@@ -5578,7 +5920,7 @@ export class ProviderBase {
5578
5920
  simpleMetadata[r.Code] = r.Results;
5579
5921
  }
5580
5922
  // Post Process Entities because there's some special handling of the sub-objects
5581
- simpleMetadata.AllEntities = this.PostProcessEntityMetadata(simpleMetadata.Entities, simpleMetadata.EntityFields, simpleMetadata.EntityFieldValues, simpleMetadata.EntityPermissions, simpleMetadata.EntityRelationships, simpleMetadata.EntitySettings, simpleMetadata.EntityOrganicKeys, simpleMetadata.EntityOrganicKeyRelatedEntities, simpleMetadata.EntityFieldPermissions, simpleMetadata.EntityAlternateBaseViews);
5923
+ simpleMetadata.AllEntities = this.PostProcessEntityMetadata(simpleMetadata.Entities, simpleMetadata.EntityFields, simpleMetadata.EntityFieldValues, simpleMetadata.EntityPermissions, simpleMetadata.EntityRelationships, simpleMetadata.EntitySettings, simpleMetadata.EntityOrganicKeys, simpleMetadata.EntityOrganicKeyRelatedEntities, simpleMetadata.EntityFieldPermissions, simpleMetadata.EntityAlternateBaseViews, simpleMetadata.EntityUniqueKeys);
5582
5924
  // Post Process the Applications, because we want to handle the sub-objects properly.
5583
5925
  simpleMetadata.AllApplications = simpleMetadata.Applications.map((a) => {
5584
5926
  a.ApplicationEntities = simpleMetadata.ApplicationEntities.filter((ae) => UUIDsEqual(ae.ApplicationID, a.ID));
@@ -5665,7 +6007,7 @@ export class ProviderBase {
5665
6007
  }
5666
6008
  return map;
5667
6009
  }
5668
- PostProcessEntityMetadata(entities, fields, fieldValues, permissions, relationships, settings, organicKeys, organicKeyRelatedEntities, fieldPermissions, alternateBaseViews) {
6010
+ PostProcessEntityMetadata(entities, fields, fieldValues, permissions, relationships, settings, organicKeys, organicKeyRelatedEntities, fieldPermissions, alternateBaseViews, uniqueKeys) {
5669
6011
  const result = [];
5670
6012
  // Sort entities alphabetically by name to ensure deterministic ordering
5671
6013
  // This prevents non-deterministic output in CodeGen and other metadata consumers
@@ -5706,6 +6048,9 @@ export class ProviderBase {
5706
6048
  const alternateBaseViewsByEntityId = alternateBaseViews && alternateBaseViews.length > 0
5707
6049
  ? this.groupByNormalizedUUID(alternateBaseViews, abv => abv.EntityID)
5708
6050
  : new Map();
6051
+ const uniqueKeysByEntityId = uniqueKeys && uniqueKeys.length > 0
6052
+ ? this.groupByNormalizedUUID(uniqueKeys, uk => uk.EntityID)
6053
+ : new Map();
5709
6054
  for (const e of sortedEntities) {
5710
6055
  const entityIdKey = NormalizeUUID(e.ID);
5711
6056
  const entityFields = fieldsByEntityId.get(entityIdKey) || [];
@@ -5720,6 +6065,9 @@ export class ProviderBase {
5720
6065
  if (alternateBaseViews) {
5721
6066
  e.EntityAlternateBaseViews = alternateBaseViewsByEntityId.get(entityIdKey) || [];
5722
6067
  }
6068
+ if (uniqueKeys) {
6069
+ e.EntityUniqueKeys = uniqueKeysByEntityId.get(entityIdKey) || [];
6070
+ }
5723
6071
  result.push(new EntityInfo(e, this));
5724
6072
  }
5725
6073
  // Check for schema name collision: if both 'MJ' and 'MJCustom' schemas exist,
@@ -5997,6 +6345,7 @@ export class ProviderBase {
5997
6345
  // Read the reachability flag in the SAME synchronous turn the await above resumed in —
5998
6346
  // before the next await can let a concurrent check overwrite it.
5999
6347
  const serverReached = this._lastRemoteTimestampReadReached;
6348
+ this._checkedRemoteMetadataTimestamps = gotTimestamps ? this._latestRemoteMetadataTimestamps : null;
6000
6349
  if (gotTimestamps) {
6001
6350
  this._lastRefreshCheckAt = Date.now();
6002
6351
  }
@@ -6055,33 +6404,58 @@ export class ProviderBase {
6055
6404
  */
6056
6405
  async RefreshIfNeeded(providerToUse, bypassMinCheckInterval) {
6057
6406
  if (await this.CheckToSeeIfRefreshNeeded(providerToUse, bypassMinCheckInterval)) {
6058
- // Stale only in the saved-query family → reload just that family (fresh timestamps, no
6059
- // cache layer), falling back to the full hard reload if the scoped read fails.
6060
- if (this.PartialRefreshItemCodes() !== null)
6061
- return this.ReloadMetadata(true, providerToUse, true);
6407
+ // Reload only what changed (see MetadataRefreshScope): nothing, the saved-query family
6408
+ // (fresh timestamps, no cache layer; a failed read is retried), or everything (a hard
6409
+ // Refresh()).
6410
+ const scope = this.MetadataRefreshScope();
6411
+ if (scope.Kind === 'none') {
6412
+ this.markMetadataCurrent();
6413
+ return true;
6414
+ }
6415
+ if (scope.Kind === 'scoped') {
6416
+ // Reuse the stored stamps while they come from the latest successful check; after a
6417
+ // failed check read, or a read stored by another caller, the pass reads them again.
6418
+ const stampsFresh = this._checkedRemoteMetadataTimestamps != null
6419
+ && this._checkedRemoteMetadataTimestamps === this._latestRemoteMetadataTimestamps;
6420
+ return this.ReloadMetadata(true, providerToUse, true, stampsFresh);
6421
+ }
6422
+ LogStatus(`[Metadata] Full reload needed: ${scope.Reason}`);
6062
6423
  return this.Refresh(providerToUse);
6063
6424
  }
6064
6425
  else
6065
6426
  return true;
6066
6427
  }
6067
- async GetEntityObject(entityName, loadKeyOrContextUser, contextUser) {
6428
+ static isGetEntityObjectOptions(value) {
6429
+ return (typeof value === 'object' &&
6430
+ value !== null &&
6431
+ !(value instanceof CompositeKey) &&
6432
+ !(value instanceof UserInfo) &&
6433
+ 'SkipNewRecord' in value);
6434
+ }
6435
+ async GetEntityObject(entityName, loadKeyOrOptionsOrContextUser, contextUser) {
6068
6436
  try {
6069
6437
  // Determine which overload was called
6070
6438
  let actualLoadKey;
6439
+ let actualOptions;
6071
6440
  let actualContextUser;
6072
- if (loadKeyOrContextUser instanceof CompositeKey) {
6073
- // Second overload: entityName, loadKey, contextUser
6074
- actualLoadKey = loadKeyOrContextUser;
6441
+ if (loadKeyOrOptionsOrContextUser instanceof CompositeKey) {
6442
+ // Overload: entityName, loadKey, contextUser
6443
+ actualLoadKey = loadKeyOrOptionsOrContextUser;
6444
+ actualContextUser = contextUser;
6445
+ }
6446
+ else if (ProviderBase.isGetEntityObjectOptions(loadKeyOrOptionsOrContextUser)) {
6447
+ // Overload: entityName, options, contextUser
6448
+ actualOptions = loadKeyOrOptionsOrContextUser;
6075
6449
  actualContextUser = contextUser;
6076
6450
  }
6077
6451
  else if (contextUser !== undefined) {
6078
- // Second overload with null/undefined loadKey: entityName, null/undefined, contextUser
6452
+ // Overload with null/undefined loadKey: entityName, null/undefined, contextUser
6079
6453
  actualLoadKey = undefined;
6080
6454
  actualContextUser = contextUser;
6081
6455
  }
6082
6456
  else {
6083
6457
  // First overload: entityName, contextUser
6084
- actualContextUser = loadKeyOrContextUser;
6458
+ actualContextUser = loadKeyOrOptionsOrContextUser;
6085
6459
  }
6086
6460
  const entity = this.EntityByName(entityName);
6087
6461
  if (entity) {
@@ -6129,7 +6503,7 @@ export class ProviderBase {
6129
6503
  throw new Error(`Failed to load ${entityName} with key: ${actualLoadKey.ToString()}`);
6130
6504
  }
6131
6505
  }
6132
- else {
6506
+ else if (!actualOptions?.SkipNewRecord) {
6133
6507
  // whenever we create a new object we want it to start
6134
6508
  // out as a new record, so we call NewRecord() on it
6135
6509
  newObject.NewRecord();
@@ -6149,6 +6523,13 @@ export class ProviderBase {
6149
6523
  return null;
6150
6524
  }
6151
6525
  }
6526
+ /**
6527
+ * Instantiates a `BaseEntity` subclass using explicit {@link GetEntityObjectOptions}
6528
+ * (for example `{ SkipNewRecord: true }` prior to `LoadFromData`).
6529
+ */
6530
+ GetEntityObjectWithOptions(entityName, options, contextUser) {
6531
+ return this.GetEntityObject(entityName, options, contextUser);
6532
+ }
6152
6533
  /**
6153
6534
  * Returns a list of entity dependencies, basically metadata that tells you the links to this entity from all other entities.
6154
6535
  * @param entityName
@@ -6701,13 +7082,15 @@ export class ProviderBase {
6701
7082
  const fmtKey = this.LocalStoragePrefix + ProviderBase.localStorageFormatKey;
6702
7083
  const dataKey = this.LocalStoragePrefix + ProviderBase.localStorageAllMetadataKey;
6703
7084
  const membershipKey = this.LocalStoragePrefix + ProviderBase.localStorageDatasetMembershipKey;
7085
+ const itemsKey = this.LocalStoragePrefix + ProviderBase.localStorageDatasetItemsKey;
6704
7086
  const readStart = Date.now();
6705
- const all = await ls.GetItems([tsKey, fmtKey, dataKey, membershipKey]);
7087
+ const all = await ls.GetItems([tsKey, fmtKey, dataKey, membershipKey, itemsKey]);
6706
7088
  const readMs = Date.now() - readStart;
6707
7089
  const tsRaw = all.get(tsKey) ?? null;
6708
7090
  const format = all.get(fmtKey) ?? null;
6709
7091
  const raw = all.get(dataKey) ?? null;
6710
7092
  const membershipRaw = all.get(membershipKey) ?? null;
7093
+ const itemsRaw = all.get(itemsKey) ?? null;
6711
7094
  // The timestamps are a freshness claim FOR THE PAYLOAD, so they are only adopted when the
6712
7095
  // payload is there to adopt with them. Timestamps without a payload happen whenever the
6713
7096
  // two keys do not disappear together: the timestamps key is written last (and removed
@@ -6745,6 +7128,12 @@ export class ProviderBase {
6745
7128
  LogError(`[Metadata Cache] Failed to restore dataset membership: ${membershipErr instanceof Error ? membershipErr.message : String(membershipErr)}`);
6746
7129
  }
6747
7130
  }
7131
+ // Restore the dataset item list the same way, so a warm boot can attribute a change to
7132
+ // its item and reload only what changed (see MetadataRefreshScope). Without it, every
7133
+ // change seen by a process that started from the snapshot was a full reload.
7134
+ if (itemsRaw) {
7135
+ this.restoreMetadataDatasetItems(itemsRaw);
7136
+ }
6748
7137
  if (!raw)
6749
7138
  return;
6750
7139
  // Decompress if stored in compressed format, otherwise parse directly
@@ -6791,12 +7180,45 @@ export class ProviderBase {
6791
7180
  static { this.localStorageAllMetadataKey = this.localStorageRootKey + '_AllMetadata'; }
6792
7181
  static { this.localStorageFormatKey = this.localStorageRootKey + '_Format'; }
6793
7182
  static { this.localStorageDatasetMembershipKey = this.localStorageRootKey + '_DatasetMembership'; }
7183
+ /** The MJ_Metadata dataset items (see `_metadataDatasetItems`) of the stored snapshot. */
7184
+ static { this.localStorageDatasetItemsKey = this.localStorageRootKey + '_DatasetItems'; }
6794
7185
  static { this.localStorageKeys = [
6795
7186
  ProviderBase.localStorageTimestampsKey,
6796
7187
  ProviderBase.localStorageAllMetadataKey,
6797
7188
  ProviderBase.localStorageFormatKey,
6798
7189
  ProviderBase.localStorageDatasetMembershipKey,
7190
+ ProviderBase.localStorageDatasetItemsKey,
6799
7191
  ]; }
7192
+ /**
7193
+ * Adopts a stored dataset item list. Only a well-formed list replaces the one held: a damaged or
7194
+ * empty value must not erase the list a load already recorded.
7195
+ */
7196
+ restoreMetadataDatasetItems(itemsRaw) {
7197
+ try {
7198
+ const parsed = JSON.parse(itemsRaw);
7199
+ if (!Array.isArray(parsed) || parsed.length === 0) {
7200
+ return;
7201
+ }
7202
+ const restored = [];
7203
+ for (const entry of parsed) {
7204
+ if (typeof entry?.Code !== 'string' || typeof entry.EntityName !== 'string' || !entry.Code || !entry.EntityName) {
7205
+ return;
7206
+ }
7207
+ const latest = typeof entry.LatestUpdateDate === 'string' ? new Date(entry.LatestUpdateDate) : undefined;
7208
+ restored.push({
7209
+ Code: entry.Code,
7210
+ EntityName: entry.EntityName,
7211
+ EntityID: typeof entry.EntityID === 'string' ? entry.EntityID : undefined,
7212
+ RowCount: typeof entry.RowCount === 'number' ? entry.RowCount : undefined,
7213
+ LatestUpdateDate: latest && !isNaN(latest.getTime()) ? latest : undefined,
7214
+ });
7215
+ }
7216
+ this._metadataDatasetItems = restored;
7217
+ }
7218
+ catch (itemsErr) {
7219
+ LogError(`[Metadata Cache] Failed to restore the dataset item list: ${itemsErr instanceof Error ? itemsErr.message : String(itemsErr)}`);
7220
+ }
7221
+ }
6800
7222
  /**
6801
7223
  * Converts a base64-encoded string to an ArrayBuffer.
6802
7224
  * Used for compressed metadata storage/retrieval.
@@ -6912,6 +7334,10 @@ export class ProviderBase {
6912
7334
  if (this._metadataDatasetEntityNames?.size) {
6913
7335
  await ls.SetItem(this.LocalStoragePrefix + ProviderBase.localStorageDatasetMembershipKey, JSON.stringify([...this._metadataDatasetEntityNames]));
6914
7336
  }
7337
+ // And the dataset item list, so a warm boot can reload only what changed.
7338
+ if (this._metadataDatasetItems?.length) {
7339
+ await ls.SetItem(this.LocalStoragePrefix + ProviderBase.localStorageDatasetItemsKey, JSON.stringify(this._metadataDatasetItems));
7340
+ }
6915
7341
  // Timestamps LAST: they are the freshness claim for everything written above, so they
6916
7342
  // must be the final thing to land.
6917
7343
  const timestampsRaw = JSON.stringify(this._latestLocalMetadataTimestamps);