@memberjunction/integration-engine 6.2.0-edge.5 → 6.2.0-edge.7

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 (88) hide show
  1. package/dist/ActionMetadataGenerator.d.ts +45 -0
  2. package/dist/ActionMetadataGenerator.d.ts.map +1 -1
  3. package/dist/ActionMetadataGenerator.js +75 -5
  4. package/dist/ActionMetadataGenerator.js.map +1 -1
  5. package/dist/AdaptiveConcurrency.d.ts +15 -0
  6. package/dist/AdaptiveConcurrency.d.ts.map +1 -1
  7. package/dist/AdaptiveConcurrency.js +21 -0
  8. package/dist/AdaptiveConcurrency.js.map +1 -1
  9. package/dist/BaseIntegrationConnector.d.ts +70 -0
  10. package/dist/BaseIntegrationConnector.d.ts.map +1 -1
  11. package/dist/BaseIntegrationConnector.js +112 -9
  12. package/dist/BaseIntegrationConnector.js.map +1 -1
  13. package/dist/BaseRESTIntegrationConnector.d.ts +2 -2
  14. package/dist/BaseRESTIntegrationConnector.d.ts.map +1 -1
  15. package/dist/BaseRESTIntegrationConnector.js +43 -4
  16. package/dist/BaseRESTIntegrationConnector.js.map +1 -1
  17. package/dist/CatalogScope.d.ts +152 -0
  18. package/dist/CatalogScope.d.ts.map +1 -0
  19. package/dist/CatalogScope.js +399 -0
  20. package/dist/CatalogScope.js.map +1 -0
  21. package/dist/CatalogSource.d.ts +53 -0
  22. package/dist/CatalogSource.d.ts.map +1 -0
  23. package/dist/CatalogSource.js +82 -0
  24. package/dist/CatalogSource.js.map +1 -0
  25. package/dist/CatalogWriter.d.ts +216 -0
  26. package/dist/CatalogWriter.d.ts.map +1 -0
  27. package/dist/CatalogWriter.js +457 -0
  28. package/dist/CatalogWriter.js.map +1 -0
  29. package/dist/CompanyIntegrationCatalogStore.d.ts +109 -0
  30. package/dist/CompanyIntegrationCatalogStore.d.ts.map +1 -0
  31. package/dist/CompanyIntegrationCatalogStore.js +229 -0
  32. package/dist/CompanyIntegrationCatalogStore.js.map +1 -0
  33. package/dist/DeclaredSampleMerge.d.ts +10 -4
  34. package/dist/DeclaredSampleMerge.d.ts.map +1 -1
  35. package/dist/DeclaredSampleMerge.js +17 -6
  36. package/dist/DeclaredSampleMerge.js.map +1 -1
  37. package/dist/DiscoveryWatchdog.d.ts +38 -1
  38. package/dist/DiscoveryWatchdog.d.ts.map +1 -1
  39. package/dist/DiscoveryWatchdog.js +56 -1
  40. package/dist/DiscoveryWatchdog.js.map +1 -1
  41. package/dist/IntegrationActionGenerator.d.ts.map +1 -1
  42. package/dist/IntegrationActionGenerator.js +36 -26
  43. package/dist/IntegrationActionGenerator.js.map +1 -1
  44. package/dist/IntegrationConnectorCreationPipeline.d.ts +181 -4
  45. package/dist/IntegrationConnectorCreationPipeline.d.ts.map +1 -1
  46. package/dist/IntegrationConnectorCreationPipeline.js +646 -68
  47. package/dist/IntegrationConnectorCreationPipeline.js.map +1 -1
  48. package/dist/IntegrationEngine.d.ts +86 -2
  49. package/dist/IntegrationEngine.d.ts.map +1 -1
  50. package/dist/IntegrationEngine.js +760 -209
  51. package/dist/IntegrationEngine.js.map +1 -1
  52. package/dist/IntegrationSchemaSync.d.ts +97 -0
  53. package/dist/IntegrationSchemaSync.d.ts.map +1 -1
  54. package/dist/IntegrationSchemaSync.js +302 -49
  55. package/dist/IntegrationSchemaSync.js.map +1 -1
  56. package/dist/MatchEngine.d.ts.map +1 -1
  57. package/dist/MatchEngine.js +6 -0
  58. package/dist/MatchEngine.js.map +1 -1
  59. package/dist/MemoryGovernor.d.ts +183 -0
  60. package/dist/MemoryGovernor.d.ts.map +1 -0
  61. package/dist/MemoryGovernor.js +225 -0
  62. package/dist/MemoryGovernor.js.map +1 -0
  63. package/dist/ResourcePressure.d.ts +80 -0
  64. package/dist/ResourcePressure.d.ts.map +1 -0
  65. package/dist/ResourcePressure.js +143 -0
  66. package/dist/ResourcePressure.js.map +1 -0
  67. package/dist/RunMemoryControl.d.ts +122 -0
  68. package/dist/RunMemoryControl.d.ts.map +1 -0
  69. package/dist/RunMemoryControl.js +237 -0
  70. package/dist/RunMemoryControl.js.map +1 -0
  71. package/dist/SchemaPersistCounts.d.ts +29 -0
  72. package/dist/SchemaPersistCounts.d.ts.map +1 -0
  73. package/dist/SchemaPersistCounts.js +27 -0
  74. package/dist/SchemaPersistCounts.js.map +1 -0
  75. package/dist/SyncLogger.d.ts +21 -0
  76. package/dist/SyncLogger.d.ts.map +1 -1
  77. package/dist/SyncLogger.js +92 -1
  78. package/dist/SyncLogger.js.map +1 -1
  79. package/dist/WatermarkService.d.ts.map +1 -1
  80. package/dist/WatermarkService.js +1 -0
  81. package/dist/WatermarkService.js.map +1 -1
  82. package/dist/index.d.ts +12 -0
  83. package/dist/index.d.ts.map +1 -1
  84. package/dist/index.js +8 -0
  85. package/dist/index.js.map +1 -1
  86. package/dist/types.d.ts +46 -0
  87. package/dist/types.d.ts.map +1 -1
  88. package/package.json +7 -7
@@ -1,9 +1,145 @@
1
- import { LogError, Metadata } from '@memberjunction/core';
1
+ import { LogError, Metadata, RunView } from '@memberjunction/core';
2
+ import { EscapeSQLString } from '@memberjunction/global';
2
3
  import { IntegrationProgressEmitter, } from '@memberjunction/integration-progress-artifacts';
3
4
  import { SoftPKClassifier, } from '@memberjunction/integration-pk-classifier';
4
5
  import { IntegrationEngineBase } from '@memberjunction/integration-engine-base';
6
+ import { BuildCatalogWriter, ResolveCatalogSource } from './CatalogSource.js';
7
+ import { LoadCatalogScope, RefreshCatalogScope, RunInCatalogScope } from './CatalogScope.js';
5
8
  import { IntegrationSchemaSync } from './IntegrationSchemaSync.js';
6
9
  import { MergeDeclaredWithSample } from './DeclaredSampleMerge.js';
10
+ import { DescribePersistCounts } from './SchemaPersistCounts.js';
11
+ import { getHeapStatistics } from 'node:v8';
12
+ import { totalmem } from 'node:os';
13
+ /**
14
+ * Has the heap reached the point where a long stage must stop taking on new work?
15
+ *
16
+ * Pure, so the boundary is testable without arranging real memory pressure — the same reason the
17
+ * overlay deciders in IntegrationSchemaSync are pure.
18
+ *
19
+ * A limit of zero means V8 did not report a ceiling. That must read as "do not stop": a missing
20
+ * reading is not evidence of pressure, and treating it as pressure would halt sampling everywhere
21
+ * the statistic is unavailable.
22
+ *
23
+ * `minHeadroomBytes` (default 0 = off) also stops when no more than that many bytes remain below
24
+ * the limit. A heap caller needs it; see {@link HEAP_STOP_MIN_HEADROOM_BYTES}. An RSS caller (limit
25
+ * = the box) does not pass it.
26
+ */
27
+ export function ShouldStopSamplingForHeap(usedBytes, limitBytes, stopFraction, minHeadroomBytes = 0) {
28
+ if (!(limitBytes > 0) || !(stopFraction > 0))
29
+ return false;
30
+ if (usedBytes / limitBytes >= stopFraction)
31
+ return true;
32
+ return minHeadroomBytes > 0 && limitBytes - usedBytes <= minHeadroomBytes;
33
+ }
34
+ /**
35
+ * The absolute headroom a HEAP reading must keep, beside its fraction.
36
+ *
37
+ * A fraction of `heap_size_limit` alone cannot fire on a small heap. That limit includes a fixed
38
+ * young-generation reserve (192 MB on Node 20-24, constant across `--max-old-space-size` values)
39
+ * which live data can never occupy: V8 aborts when the OLD space fills, i.e. at
40
+ * `heap_size_limit - reserve`. At 0.92 the fractional stop sits ABOVE that line for every old space
41
+ * under ~2.4 GB (1 GB: 95 MB above; 2 GB: 13 MB above; the ~2 GB ceiling a 4 GB box gets: 16 MB
42
+ * above), so on such a box the gate could not fire before the abort it exists to prevent. Measured
43
+ * 2026-09-24 on 888 objects / 97k fields: with the heap pre-filled to 92% of a 4 GB limit the gate
44
+ * stopped after 25 objects; the same fill at a 1 GB limit aborted V8 before the stage ran.
45
+ *
46
+ * 320 MB is the reserve plus 128 MB of old space. Above ~4 GB the 8% margin already exceeds it, so
47
+ * large workspaces are unaffected.
48
+ */
49
+ export const HEAP_STOP_MIN_HEADROOM_BYTES = 320 * 1024 * 1024;
50
+ /** The live reading. Cheap enough per object: counters V8 and the OS already maintain. */
51
+ export function ReadMemorySample() {
52
+ const heap = getHeapStatistics();
53
+ return {
54
+ HeapUsed: heap.used_heap_size,
55
+ HeapLimit: heap.heap_size_limit,
56
+ RSS: process.memoryUsage().rss,
57
+ TotalMemory: totalmem(),
58
+ };
59
+ }
60
+ /**
61
+ * Stop when EITHER ceiling is close. The heap gate alone cannot save a process the kernel kills:
62
+ * the kernel measures resident memory against the box, V8 measures the heap against its own
63
+ * limit, and the two diverge — parsed response bodies, driver buffers and heap fragmentation all
64
+ * sit in RSS outside the live heap, so RSS runs well above it under load. Observed 2026-09-18 and
65
+ * 2026-09-21 on a 15.7 GB box: node killed at 15.3 GB and 15.6 GB anon-RSS mid-discovery while
66
+ * the heap was still under its ceiling, so the heap gate never fired. An unknown reading (a
67
+ * limit or a box size of 0) is not evidence of pressure, as for the heap.
68
+ *
69
+ * `heapMinHeadroomBytes` applies to the HEAP reading only (see
70
+ * {@link HEAP_STOP_MIN_HEADROOM_BYTES}); resident memory is judged against the whole box, where a
71
+ * fraction is the right measure.
72
+ */
73
+ export function ShouldStopForMemory(sample, heapStopFraction, rssStopFraction, heapMinHeadroomBytes = 0) {
74
+ return ShouldStopSamplingForHeap(sample.HeapUsed, sample.HeapLimit, heapStopFraction, heapMinHeadroomBytes)
75
+ || ShouldStopSamplingForHeap(sample.RSS, sample.TotalMemory, rssStopFraction);
76
+ }
77
+ /** A persist result with nothing in it yet — the accumulator a streaming persist sums into. */
78
+ function emptyPersistResult() {
79
+ return {
80
+ ObjectsCreated: 0,
81
+ ObjectsUpdated: 0,
82
+ FieldsCreated: 0,
83
+ FieldsUpdated: 0,
84
+ ObjectMergeLog: [],
85
+ FieldMergeLog: [],
86
+ ObjectsDeactivated: [],
87
+ FieldsDeactivated: [],
88
+ };
89
+ }
90
+ /**
91
+ * The first-discovery result once the healing pass has re-persisted the objects it sampled.
92
+ *
93
+ * Not a sum: the heal re-persists objects the first pass CREATED, so adding its counts would report
94
+ * them a second time, as updates. The first pass's object and field counts stand; what the heal adds
95
+ * is its provenance (the merge logs, now carrying the sampled evidence) and any field that sampling
96
+ * found and the declaration did not. It is scoped and never authoritative, so it retires nothing.
97
+ */
98
+ export function MergeHealedPersistResult(first, heal) {
99
+ return {
100
+ ...first,
101
+ FieldsCreated: first.FieldsCreated + heal.FieldsCreated,
102
+ ObjectMergeLog: [...first.ObjectMergeLog, ...heal.ObjectMergeLog],
103
+ FieldMergeLog: [...first.FieldMergeLog, ...heal.FieldMergeLog],
104
+ ObjectsDeactivated: [...first.ObjectsDeactivated],
105
+ FieldsDeactivated: [...first.FieldsDeactivated],
106
+ };
107
+ }
108
+ /** Folds one per-object persist into the streaming total. */
109
+ function addPersistResult(total, part) {
110
+ total.ObjectsCreated += part.ObjectsCreated;
111
+ total.ObjectsUpdated += part.ObjectsUpdated;
112
+ total.FieldsCreated += part.FieldsCreated;
113
+ total.FieldsUpdated += part.FieldsUpdated;
114
+ total.ObjectMergeLog.push(...part.ObjectMergeLog);
115
+ total.FieldMergeLog.push(...part.FieldMergeLog);
116
+ total.ObjectsDeactivated.push(...part.ObjectsDeactivated);
117
+ total.FieldsDeactivated.push(...part.FieldsDeactivated);
118
+ }
119
+ /**
120
+ * A name-only object for the final pass of a streamed persist, which exists to tell the absent-
121
+ * object retirement which objects the source still has. It must carry NO opinion: the persist
122
+ * overlay treats any non-empty label or description as the source's, so a stub labelled with its
123
+ * own name would overwrite every stored DisplayName with the raw object name. An empty label is
124
+ * silence to the overlay, and a row that is somehow new still gets its name as display name.
125
+ */
126
+ function nameStub(externalName) {
127
+ return { ExternalName: externalName, ExternalLabel: '', Fields: [], PrimaryKeyFields: [], Relationships: [] };
128
+ }
129
+ /**
130
+ * Runs the work it is handed one item at a time, in arrival order, however many callers hand work
131
+ * in at once. A failure belongs to the caller that handed it in; it never stalls the next one.
132
+ */
133
+ function serialQueue() {
134
+ let tail = Promise.resolve();
135
+ return (work) => {
136
+ const run = tail.then(work);
137
+ tail = run.then(() => undefined, () => undefined);
138
+ return run;
139
+ };
140
+ }
141
+ /** How many field names a `pk.classifier.result` event carries — enough to read, bounded for a wide object. */
142
+ const PK_VERDICT_FIELD_NAMES = 12;
7
143
  /**
8
144
  * The unified pipeline that drives connector creation / refresh end-to-end:
9
145
  *
@@ -52,11 +188,58 @@ export class IntegrationConnectorCreationPipeline {
52
188
  */
53
189
  static { this.IN_FLIGHT_MAX_AGE_MS = 20 * 60_000; }
54
190
  /**
55
- * Default whole-run ceiling. Deliberately far above any healthy run — the reference Totara run
56
- * completes in under four minutes and a large Salesforce-backed catalog in tens — so this only ever
57
- * fires on work that has genuinely stopped, never on work that is merely big.
191
+ * Default whole-run ceiling, deliberately enormous: it exists ONLY to release a run that has hung
192
+ * forever, never to bound work that is merely big. At 45 minutes it did the latter — an 888-object
193
+ * catalog was failed at object 336, and because the failure precedes Persist, everything
194
+ * introspected up to then was discarded. A connection that wants a tighter bound sets
195
+ * `Configuration.runDeadlineMs`; the environment can set `MJ_INTEGRATION_RUN_DEADLINE_MS`.
196
+ */
197
+ static { this.DEFAULT_RUN_DEADLINE_MS = 12 * 60 * 60_000; }
198
+ /**
199
+ * Resolves the whole-run ceiling: explicit argument → the connection's `Configuration.runDeadlineMs`
200
+ * → `MJ_INTEGRATION_RUN_DEADLINE_MS` → {@link DEFAULT_RUN_DEADLINE_MS}.
201
+ *
202
+ * `0` is a MEANINGFUL value here (it disables the ceiling), which is why this does not reuse the
203
+ * positive-only reader the inner discovery knobs share — that one treats 0 as absent and would make
204
+ * "no ceiling" unexpressible. Negatives and non-numerics are rejected rather than honoured, so a
205
+ * malformed Configuration falls through to the next source instead of disabling the one mechanism
206
+ * that rescues a run stuck in-flight forever.
207
+ */
208
+ static resolveRunDeadlineMs(opts) {
209
+ const valid = (v) => typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.floor(v) : undefined;
210
+ const explicit = valid(opts.RunDeadlineMs);
211
+ if (explicit != null)
212
+ return explicit;
213
+ let fromConfig;
214
+ try {
215
+ const raw = opts.CompanyIntegration?.Configuration;
216
+ if (raw)
217
+ fromConfig = valid(JSON.parse(raw).runDeadlineMs);
218
+ }
219
+ catch { /* malformed Configuration → fall through to env/default */ }
220
+ if (fromConfig != null)
221
+ return fromConfig;
222
+ const fromEnv = Number.parseInt(process.env.MJ_INTEGRATION_RUN_DEADLINE_MS ?? '', 10);
223
+ if (Number.isFinite(fromEnv) && fromEnv >= 0)
224
+ return fromEnv;
225
+ return IntegrationConnectorCreationPipeline.DEFAULT_RUN_DEADLINE_MS;
226
+ }
227
+ /**
228
+ * Heap fraction past which Introspect stops taking on NEW sampling work.
229
+ *
230
+ * Higher than a warning threshold on purpose. A warning exists to fire while there is still
231
+ * room to act; this is the last exit before V8 gives up, and past it the next large allocation
232
+ * is as likely to abort the process as to succeed. 0.92 leaves roughly the cost of one more
233
+ * object's sample plus the persist that follows — enough to land what has already been
234
+ * gathered, which is the entire point of stopping rather than being stopped.
235
+ */
236
+ static { this.HEAP_STOP_FRACTION = 0.92; }
237
+ /**
238
+ * Resident-set fraction of the box's memory past which the two long stages stop. Lower than
239
+ * the heap fraction on purpose: the box is shared with everything else that runs on it, and
240
+ * the kernel does not warn first. See ShouldStopForMemory.
58
241
  */
59
- static { this.DEFAULT_RUN_DEADLINE_MS = 45 * 60_000; }
242
+ static { this.RSS_STOP_FRACTION = 0.80; }
60
243
  /** Just-completed runs by CompanyIntegrationID — coalesces a *sequential* duplicate within the window. */
61
244
  static { this.recentRuns = new Map(); }
62
245
  /** Default coalesce window (ms) when the env override is unset/invalid. */
@@ -89,8 +272,22 @@ export class IntegrationConnectorCreationPipeline {
89
272
  * is indistinguishable from "the run hasn't opened its stream yet". So whenever a caller supplied
90
273
  * a `RunID` and coalescing served a different run, we publish a terminal ALIAS run under the
91
274
  * requested ID pointing at the run that actually did the work. See {@link honourRequestedRunID}.
275
+ *
276
+ * CATALOG SCOPE. Every read a discovery makes — the connector's GetCachedObject/GetCachedFields during
277
+ * sampling, the dependency graph, the excluded-field resolution — happens with THIS connection
278
+ * in catalog scope. Scope-aware getters answer from the connection's own rows once it has any
279
+ * and fall back to the shared declared rows until then, so a first discovery still sees the
280
+ * connector's declared floor and a re-discovery sees what this connection found last time,
281
+ * not what some other connection of the same connector found.
92
282
  */
93
283
  async Run(opts) {
284
+ // Entered SYNCHRONOUSLY. The de-dup below registers this run before the caller's next
285
+ // statement, which is what lets a concurrent duplicate find it; awaiting the catalog load
286
+ // first would open a window in which both callers start a run. The connection's catalog is
287
+ // loaded inside the run instead (runInternal), where a failed read is a failed run.
288
+ return RunInCatalogScope(opts.CompanyIntegration?.ID ?? '', () => this.runWithDedup(opts));
289
+ }
290
+ async runWithDedup(opts) {
94
291
  const ciID = opts.CompanyIntegration?.ID;
95
292
  if (!ciID)
96
293
  return this.runInternal(opts); // no key to de-dup on — run directly
@@ -184,8 +381,8 @@ export class IntegrationConnectorCreationPipeline {
184
381
  emitter.stageComplete('Coalesced', { processed: 1, succeeded: served.Success ? 1 : 0 });
185
382
  if (served.Success) {
186
383
  const p = served.PersistResult;
187
- await emitter.complete(`${pointer} Outcome: ${p?.ObjectsCreated ?? 0} objects created, ` +
188
- `${p?.ObjectsUpdated ?? 0} updated, ${served.UnresolvedObjects.length} unresolved PKs.`);
384
+ await emitter.complete(`${pointer} Outcome: ${DescribePersistCounts(p)}, ` +
385
+ `${served.UnresolvedObjects.length} unresolved PKs.`);
189
386
  }
190
387
  else {
191
388
  emitter.stageError('Coalesced', served.FailureMessage ?? 'no reason reported', {
@@ -234,8 +431,8 @@ export class IntegrationConnectorCreationPipeline {
234
431
  // THE RUN MUST END. Raced rather than awaited: a stage that never settles cannot be cancelled,
235
432
  // but it can be stopped being waited on — which is the difference between a run that fails and
236
433
  // one that is in-flight forever. See RunDeadlineMs.
237
- const deadlineMs = opts.RunDeadlineMs ?? IntegrationConnectorCreationPipeline.DEFAULT_RUN_DEADLINE_MS;
238
- // The default is 45min, but RunDeadlineMs is a public knob and a caller may set seconds — in
434
+ const deadlineMs = IntegrationConnectorCreationPipeline.resolveRunDeadlineMs(opts);
435
+ // The ceiling is configurable and a caller (or a connection) may set seconds — in
239
436
  // which case rounding to minutes reported the failure as a "deadline of 0min", which reads as
240
437
  // a bug in the pipeline rather than the limit the caller actually asked for.
241
438
  const deadlineLabel = deadlineMs >= 60_000
@@ -263,16 +460,63 @@ export class IntegrationConnectorCreationPipeline {
263
460
  clearTimeout(deadlineTimer); });
264
461
  };
265
462
  try {
463
+ // The connection's own catalog is no longer resident (MJ-RUN-43): load its objects and
464
+ // dependency edges into the scope before any stage reads them synchronously.
465
+ await LoadCatalogScope(opts.CompanyIntegration.ID, opts.ContextUser);
266
466
  await withDeadline('ConnectionTest', this.stageConnectionTest(emitter, opts));
267
- const sourceSchema = await withDeadline('Introspect', this.stageIntrospect(emitter, opts));
268
- const persistResult = await withDeadline('Persist', this.stagePersist(emitter, opts, sourceSchema));
467
+ // Introspect + Persist as ONE traversal of the source when the connector can stream;
468
+ // the old whole-schema persist when it cannot. See streamIntrospectAndPersist.
469
+ let persistResult = await this.streamIntrospectAndPersist(emitter, opts, withDeadline);
470
+ // MJ-DISC-16 — heal first-discovery sampling in the SAME run.
471
+ //
472
+ // The Introspect above could not sample any net-new object: sampling reads the catalog,
473
+ // and those rows only came into existence in the Persist that follows it. So a
474
+ // brand-new object lands with the widths its catalog DESCRIPTION claims and no evidence
475
+ // from actual records — and at sync, values longer than the guess are dropped. From the
476
+ // outside that is indistinguishable from a clean discovery.
477
+ //
478
+ // Their rows exist now. Refresh the engine's catalog cache and run one more
479
+ // Introspect+Persist, which this time can sample them. Verified live 2026-09-07: a
480
+ // manual second refresh sampled all 258 custom types cleanly.
481
+ //
482
+ // Scoped to the objects that went unsampled. Re-running the whole source would double a
483
+ // large connector's time and API calls for a handful of objects, inside the same run
484
+ // deadline PKClassify still needs. A scoped introspection is never authoritative, and
485
+ // DeactivateAbsent is off, so the heal cannot retire anything the first pass kept.
486
+ //
487
+ // Non-fatal by design — a failed heal leaves exactly the state we already had, and
488
+ // failing the whole discovery over it would be worse than the guessed widths. So it is
489
+ // a warning, which never fails the run, not a stage error.
490
+ const unsampled = [...(this._firstDiscoveryFallbacks ?? [])];
491
+ if (unsampled.length > 0) {
492
+ try {
493
+ emitter.stageStart('Introspect', `${unsampled.length} first-discovered object(s) were persisted without sampling — sampling them now`);
494
+ await IntegrationEngineBase.Instance.RefreshCatalog(opts.ContextUser);
495
+ // The new rows are this connection's own, and those live in the catalog scope, not
496
+ // in the engine's shared arrays (MJ-RUN-43). The scope was loaded before Persist
497
+ // wrote them, so re-read it too, or the second pass samples the same empty
498
+ // catalog as the first (MJ-RUN-46; see RefreshCatalog).
499
+ await RefreshCatalogScope(opts.CompanyIntegration.ID, opts.ContextUser);
500
+ const healOpts = {
501
+ ...opts,
502
+ IntrospectOptions: { ...(opts.IntrospectOptions ?? {}), ObjectNames: unsampled },
503
+ DeactivateAbsent: false,
504
+ };
505
+ const healed = await this.streamIntrospectAndPersist(emitter, healOpts, withDeadline);
506
+ persistResult = MergeHealedPersistResult(persistResult, healed);
507
+ }
508
+ catch (healErr) {
509
+ const hm = healErr instanceof Error ? healErr.message : String(healErr);
510
+ emitter.Warning('Introspect', 'first-discovery-heal-failed', `First-discovery healing pass failed (run schema refresh once more to complete sampling evidence): ${hm}`);
511
+ }
512
+ }
269
513
  const { verdicts, unresolved } = await withDeadline('PKClassify', this.stagePKClassify(emitter, opts));
270
514
  emitter.stageComplete('Pipeline', {
271
515
  processed: persistResult.ObjectsCreated + persistResult.ObjectsUpdated,
272
516
  succeeded: verdicts.filter(v => v.Confident).length,
273
517
  skipped: unresolved.length,
274
518
  });
275
- await emitter.complete(`Pipeline complete. ${persistResult.ObjectsCreated} objects created, ${persistResult.ObjectsUpdated} updated, ${unresolved.length} unresolved PKs.`);
519
+ await emitter.complete(`Pipeline complete. ${DescribePersistCounts(persistResult)}, ${unresolved.length} unresolved PKs.`);
276
520
  return {
277
521
  RunID: runID,
278
522
  Success: true,
@@ -310,8 +554,8 @@ export class IntegrationConnectorCreationPipeline {
310
554
  emitter.stageComplete('ConnectionTest', { processed: 1, succeeded: 1 });
311
555
  emitter.checkpoint('ConnectionTest', { completedAt: new Date().toISOString(), durationMs: Date.now() - startMs });
312
556
  }
313
- // ── Stage 2: introspect ──────────────────────────────────────────────
314
- async stageIntrospect(emitter, opts) {
557
+ async stageIntrospect(emitter, opts, onObject) {
558
+ this._firstDiscoveryFallbacks = new Set();
315
559
  emitter.stageStart('Introspect', 'Discovering objects and fields via connector');
316
560
  const startMs = Date.now();
317
561
  // Sampling is now per OBJECT, so this stage's cost scales with the catalog — and on a large
@@ -324,8 +568,28 @@ export class IntegrationConnectorCreationPipeline {
324
568
  // it, so the two differ by one connectivity probe. The approximation can only ever stop
325
569
  // work LATER than the race — never earlier — so it cannot truncate a run that would
326
570
  // otherwise have completed.
327
- const budgetMs = opts.RunDeadlineMs ?? IntegrationConnectorCreationPipeline.DEFAULT_RUN_DEADLINE_MS;
571
+ const budgetMs = IntegrationConnectorCreationPipeline.resolveRunDeadlineMs(opts);
328
572
  const outOfTime = () => budgetMs > 0 && Date.now() - startMs >= budgetMs;
573
+ // THE OTHER BUDGET. Introspect accumulates: `schema.Objects` holds every object with every
574
+ // field for the whole stage and is handed to the persist stage only at the end, so memory
575
+ // climbs monotonically with the size of the source and is never released mid-stage. On a
576
+ // large catalog that reaches V8's ceiling before the time budget is anywhere near spent —
577
+ // 888 objects, some with thousands of columns, is ~97k field descriptors held at once, and
578
+ // a first discovery samples the whole set TWICE.
579
+ //
580
+ // Running out of memory here is not like running out of time. Time ends the stage with
581
+ // everything gathered so far intact; the heap ceiling ends the PROCESS, so the run loses
582
+ // every object it had already sampled, writes no result, and stays in flight forever.
583
+ // Observed 2026-09-19: two hours of sampling discarded by
584
+ // `FATAL ERROR: Ineffective mark-compacts near heap limit`.
585
+ //
586
+ // So memory gets the same treatment time already has — stop taking on new sampling, keep
587
+ // what is gathered, let the stage finish and persist. A smaller catalog beats no catalog.
588
+ // Read synchronously and per object: `used_heap_size` is a counter V8 already maintains,
589
+ // and the alternative (the async whole-machine reading) cannot be afforded per item.
590
+ // The heap side also keeps an absolute floor: on a small heap the fraction alone sits above
591
+ // V8's real abort line (see HEAP_STOP_MIN_HEADROOM_BYTES).
592
+ const outOfMemory = () => ShouldStopForMemory(ReadMemorySample(), IntegrationConnectorCreationPipeline.HEAP_STOP_FRACTION, IntegrationConnectorCreationPipeline.RSS_STOP_FRACTION, HEAP_STOP_MIN_HEADROOM_BYTES);
329
593
  try {
330
594
  // U11 — determinate discovery progress: surface scanned/total on the structured
331
595
  // stream (IntegrationTailRunEvents carries counts) so a client can render a real
@@ -338,7 +602,99 @@ export class IntegrationConnectorCreationPipeline {
338
602
  lastEmitted = scanned;
339
603
  emitter.heartbeat('Introspect', `scanned ${scanned}/${total} objects`, { processed: scanned, totalKnown: total });
340
604
  };
341
- const schema = await opts.Connector.IntrospectSchema(opts.CompanyIntegration, opts.ContextUser, { ...(opts.IntrospectOptions ?? {}), OnProgress: onProgress });
605
+ // §7 — a SCOPED introspection asked about a named subset. IntrospectSchema already
606
+ // honours the filter; DiscoverObjects does not take it, so without this the scoped run
607
+ // pulled and sampled the whole runtime catalog anyway.
608
+ const wantedNames = opts.IntrospectOptions?.ObjectNames;
609
+ const wanted = wantedNames && wantedNames.length > 0
610
+ ? new Set(wantedNames.map(n => n.toLowerCase()))
611
+ : null;
612
+ const inScope = (name) => !wanted || wanted.has(name.toLowerCase());
613
+ const declaredNames = [];
614
+ const seen = new Set();
615
+ const sampledDeclared = new Set();
616
+ let runtimeAdded = 0;
617
+ let unsampledForTime = 0;
618
+ let unsampledForMemory = 0;
619
+ // Per-object progress. Everything below this point is the expensive half of discovery —
620
+ // one read-path sample per object — and it emitted nothing, so a consumer watching a
621
+ // 23-object source saw the same silence as a 5-object one for however long it ran.
622
+ // The denominator is the union BOTH passes will sample (in-scope runtime objects plus
623
+ // in-scope declared ones) rather than either loop's own length, so the total is fixed
624
+ // before the first sample instead of revising upward when the second pass starts. (A
625
+ // STREAMED declared catalog is the exception: its size is unknown until the stream
626
+ // ends, so the denominator grows as it arrives.)
627
+ const sampleUniverse = new Set();
628
+ // Keyed, not counted: a name the connector surfaces twice is sampled twice by the loop
629
+ // below, and a bare counter would then report "24 of 23".
630
+ const announced = new Set();
631
+ const announceSample = (name) => {
632
+ const k = name.toLowerCase();
633
+ if (announced.has(k))
634
+ return;
635
+ announced.add(k);
636
+ emitter.heartbeat('Introspect', `Sampling "${name}" (${announced.size} of ${sampleUniverse.size})`, {
637
+ processed: announced.size,
638
+ totalKnown: sampleUniverse.size,
639
+ skipped: unsampledForTime,
640
+ });
641
+ };
642
+ // STREAMING. When the caller persists per object (onObject), each declared object is
643
+ // sampled HERE, as the connector hands it over, and then handed on — never collected.
644
+ // Everything after IntrospectSchema reads `schema.Objects`, which is empty by design
645
+ // when the connector streamed, so without this nothing streamed would be sampled and
646
+ // every runtime object would look brand new. Sampling stays serial, as it is when the
647
+ // catalog is accumulated, even when the connector describes several objects at once.
648
+ const streamedNames = [];
649
+ let streamedFields = 0;
650
+ const handOff = async (obj) => {
651
+ streamedNames.push(obj.ExternalName);
652
+ streamedFields += obj.Fields.length;
653
+ await onObject(obj);
654
+ };
655
+ const serially = serialQueue();
656
+ const streamDeclared = async (obj) => {
657
+ const key = obj.ExternalName.toLowerCase();
658
+ declaredNames.push(obj.ExternalName);
659
+ seen.add(key);
660
+ if (inScope(obj.ExternalName)) {
661
+ sampleUniverse.add(key);
662
+ await serially(async () => {
663
+ // Two declared entries differing only by case are ONE object: sample it once.
664
+ if (sampledDeclared.has(key))
665
+ return;
666
+ announceSample(obj.ExternalName);
667
+ if (outOfTime()) {
668
+ unsampledForTime++;
669
+ return;
670
+ }
671
+ if (outOfMemory()) {
672
+ unsampledForMemory++;
673
+ return;
674
+ }
675
+ sampledDeclared.add(key);
676
+ await this.sampleDeclaredObjectInPlace(obj, obj.ExternalName, opts, emitter);
677
+ });
678
+ }
679
+ await handOff(obj);
680
+ };
681
+ const schema = await opts.Connector.IntrospectSchema(opts.CompanyIntegration, opts.ContextUser, { ...(opts.IntrospectOptions ?? {}), OnProgress: onProgress, OnObject: onObject ? streamDeclared : undefined });
682
+ // Streamed if the connector says so — or if it called the handler at all: an override
683
+ // that forwards OnObject but rebuilds its result without the flag would otherwise get a
684
+ // whole-schema persist of an EMPTY schema, which on an authoritative comprehensive
685
+ // refresh finds every stored object absent and retires all of them.
686
+ const streamed = !!onObject && (schema.Streamed === true || streamedNames.length > 0);
687
+ if (streamed) {
688
+ // Anything the connector returned rather than streamed goes through the same door.
689
+ for (const leftover of schema.Objects.splice(0))
690
+ await streamDeclared(leftover);
691
+ }
692
+ else {
693
+ for (const o of schema.Objects) {
694
+ declaredNames.push(o.ExternalName);
695
+ seen.add(o.ExternalName.toLowerCase());
696
+ }
697
+ }
342
698
  // UNIVERSAL additive runtime-object discovery — the single chokepoint EVERY connector
343
699
  // funnels through, regardless of which base it extends or whether that base's
344
700
  // IntrospectSchema only reflects already-declared metadata. IntrospectSchema gives the
@@ -348,8 +704,6 @@ export class IntegrationConnectorCreationPipeline {
348
704
  // can't silently lose runtime discovery). PersistDiscoveredSchema is additive, so
349
705
  // declared objects are preserved and runtime-only objects (e.g. an auth-gated file
350
706
  // feed's streams) get created as Discovered. Errors are SURFACED, never swallowed.
351
- const declaredNames = schema.Objects.map(o => o.ExternalName);
352
- const seen = new Set(declaredNames.map(n => n.toLowerCase()));
353
707
  let runtimeObjects = [];
354
708
  // A DiscoverObjects failure used to end sampling for the ENTIRE run: the loop below was
355
709
  // the only thing that sampled, and it iterated this (now empty) list. The declared
@@ -366,49 +720,20 @@ export class IntegrationConnectorCreationPipeline {
366
720
  emitter.stageError('Introspect', `DiscoverObjects failed: ${msg}`, { code: 'discover-objects-failed' });
367
721
  console.error(`[IntrospectPipeline] DiscoverObjects failed: ${msg}`);
368
722
  }
369
- // §7 — a SCOPED introspection asked about a named subset. IntrospectSchema already
370
- // honours the filter; DiscoverObjects does not take it, so without this the scoped run
371
- // pulled and sampled the whole runtime catalog anyway.
372
- const wantedNames = opts.IntrospectOptions?.ObjectNames;
373
- const wanted = wantedNames && wantedNames.length > 0
374
- ? new Set(wantedNames.map(n => n.toLowerCase()))
375
- : null;
376
- const inScope = (name) => !wanted || wanted.has(name.toLowerCase());
377
- const sampledDeclared = new Set();
378
- let runtimeAdded = 0;
379
- let unsampledForTime = 0;
380
- // Per-object progress. Everything below this point is the expensive half of discovery —
381
- // one read-path sample per object — and it emitted nothing, so a consumer watching a
382
- // 23-object source saw the same silence as a 5-object one for however long it ran.
383
- // The denominator is the union BOTH passes will sample (in-scope runtime objects plus
384
- // in-scope declared ones) rather than either loop's own length, so the total is fixed
385
- // before the first sample instead of revising upward when the second pass starts.
386
- const sampleUniverse = new Set();
387
723
  for (const d of runtimeObjects)
388
724
  if (inScope(d.Name))
389
725
  sampleUniverse.add(d.Name.toLowerCase());
390
726
  for (const n of declaredNames)
391
727
  if (inScope(n))
392
728
  sampleUniverse.add(n.toLowerCase());
393
- const sampleTotal = sampleUniverse.size;
394
- // Keyed, not counted: a name the connector surfaces twice is sampled twice by the loop
395
- // below, and a bare counter would then report "24 of 23".
396
- const announced = new Set();
397
- const announceSample = (name) => {
398
- const k = name.toLowerCase();
399
- if (announced.has(k))
400
- return;
401
- announced.add(k);
402
- emitter.heartbeat('Introspect', `Sampling "${name}" (${announced.size} of ${sampleTotal})`, {
403
- processed: announced.size,
404
- totalKnown: sampleTotal,
405
- skipped: unsampledForTime,
406
- });
407
- };
408
729
  for (const d of runtimeObjects) {
409
730
  const key = d.Name.toLowerCase();
410
731
  if (!inScope(d.Name))
411
732
  continue;
733
+ // Streamed: a declared object was already sampled (or budget-skipped) and handed on
734
+ // as it arrived — counting it again here would report it twice.
735
+ if (streamed && seen.has(key))
736
+ continue;
412
737
  // Announced BEFORE the budget check so an exhausted budget reads as a run that
413
738
  // reached the end of its object list, not one that stalled partway through it.
414
739
  announceSample(d.Name);
@@ -416,6 +741,10 @@ export class IntegrationConnectorCreationPipeline {
416
741
  unsampledForTime++;
417
742
  continue;
418
743
  }
744
+ if (outOfMemory()) {
745
+ unsampledForMemory++;
746
+ continue;
747
+ }
419
748
  if (seen.has(key)) {
420
749
  // §case-3 (data-only-discoverable): a DECLARED object the connector ALSO surfaces at
421
750
  // runtime. Sampling populates it IN PLACE so a name-only declaration becomes syncable
@@ -441,7 +770,13 @@ export class IntegrationConnectorCreationPipeline {
441
770
  emitter.stageError('Introspect', `DiscoverFieldsViaFetch failed for "${d.Name}": ${msg}`, { code: 'discover-fields-failed' });
442
771
  console.error(`[IntrospectPipeline] DiscoverFieldsViaFetch failed for "${d.Name}": ${msg}`);
443
772
  }
444
- schema.Objects.push({
773
+ if (fields.length === 0) {
774
+ // A RUNTIME-DISCOVERED object has no declaration behind it, so the sample is the
775
+ // only source of fields there is — an empty one is persisted verbatim as a
776
+ // fieldless object. Ask the connector's describe surface before accepting that.
777
+ fields = await this.describeAsLastResort(d.Name, opts, emitter);
778
+ }
779
+ const built = {
445
780
  ExternalName: d.Name,
446
781
  ExternalLabel: d.Label,
447
782
  Description: d.Description,
@@ -467,7 +802,12 @@ export class IntegrationConnectorCreationPipeline {
467
802
  Relationships: fields
468
803
  .filter(f => (f.IsForeignKey ?? false) && f.ForeignKeyTarget)
469
804
  .map(f => ({ FieldName: f.Name, TargetObject: f.ForeignKeyTarget, TargetField: 'ID' })),
470
- });
805
+ };
806
+ // Streamed: persisted now and released, like every other object of a streamed run.
807
+ if (streamed)
808
+ await handOff(built);
809
+ else
810
+ schema.Objects.push(built);
471
811
  runtimeAdded++;
472
812
  }
473
813
  // The union's second half: DECLARED objects the runtime pass never reached. Sampling used
@@ -476,8 +816,9 @@ export class IntegrationConnectorCreationPipeline {
476
816
  // for every object when DiscoverObjects fails — was never sampled at all. It kept whatever
477
817
  // widths the catalog guessed (a truncation waiting to happen) and could only ever gain its
478
818
  // undeclared columns later, one sync at a time, through the overflow path.
819
+ // (Streamed: every declared object went through streamDeclared, which already sampled it.)
479
820
  let declaredOnlySampled = 0;
480
- for (const name of declaredNames) {
821
+ for (const name of streamed ? [] : declaredNames) {
481
822
  const key = name.toLowerCase();
482
823
  if (sampledDeclared.has(key) || !inScope(name))
483
824
  continue;
@@ -486,6 +827,10 @@ export class IntegrationConnectorCreationPipeline {
486
827
  unsampledForTime++;
487
828
  continue;
488
829
  }
830
+ if (outOfMemory()) {
831
+ unsampledForMemory++;
832
+ continue;
833
+ }
489
834
  const existing = schema.Objects.find(o => o.ExternalName.toLowerCase() === key);
490
835
  if (!existing)
491
836
  continue;
@@ -506,21 +851,37 @@ export class IntegrationConnectorCreationPipeline {
506
851
  emitter.stageError('Introspect', msg, { code: 'sample-budget-exhausted' });
507
852
  console.warn(`[IntrospectPipeline] ${msg}`);
508
853
  }
509
- console.log(`[IntrospectPipeline] declared=${declaredNames.length} runtime-added=${runtimeAdded} declared-only-sampled=${declaredOnlySampled} unsampled-for-time=${unsampledForTime} total=${schema.Objects.length}`);
510
- const fieldCount = schema.Objects.reduce((acc, o) => acc + o.Fields.length, 0);
854
+ if (unsampledForMemory > 0) {
855
+ // Deliberately the code the sync path already emits and the UI already renders,
856
+ // rather than a second vocabulary for the same condition.
857
+ const msg = `This workspace ran short of memory partway through reading your source, so ` +
858
+ `${unsampledForMemory} object(s) were not sampled and keep their declared fields ` +
859
+ `and catalog widths. Everything sampled before that point was kept. Re-run to ` +
860
+ `finish the rest, or give the workspace more memory for a source this size.`;
861
+ emitter.warning('Introspect', 'HOST_MEMORY_PRESSURE', msg, {
862
+ unsampledForMemory,
863
+ sampled: announced.size - unsampledForMemory - unsampledForTime,
864
+ });
865
+ console.warn(`[IntrospectPipeline] ${msg}`);
866
+ }
867
+ // A streamed run handed its objects on instead of keeping them, so count what it handed.
868
+ const discovered = streamedNames.length + schema.Objects.length;
869
+ console.log(`[IntrospectPipeline] declared=${declaredNames.length} runtime-added=${runtimeAdded} declared-only-sampled=${declaredOnlySampled} unsampled-for-time=${unsampledForTime} unsampled-for-memory=${unsampledForMemory} streamed=${streamed} total=${discovered}`);
870
+ const fieldCount = streamedFields + schema.Objects.reduce((acc, o) => acc + o.Fields.length, 0);
511
871
  emitter.stageComplete('Introspect', {
512
- processed: schema.Objects.length,
513
- succeeded: schema.Objects.length,
514
- totalKnown: schema.Objects.length,
872
+ processed: discovered,
873
+ succeeded: discovered,
874
+ totalKnown: discovered,
515
875
  });
516
876
  emitter.checkpoint('Introspect', {
517
- objectsDiscovered: schema.Objects.length,
877
+ objectsDiscovered: discovered,
518
878
  fieldsDiscovered: fieldCount,
519
879
  durationMs: Date.now() - startMs,
520
880
  discoverObjectsFailed,
521
881
  unsampledForTime,
882
+ unsampledForMemory,
522
883
  });
523
- return schema;
884
+ return streamed ? { ...schema, Objects: [], Streamed: true } : schema;
524
885
  }
525
886
  catch (err) {
526
887
  const msg = err instanceof Error ? err.message : String(err);
@@ -549,13 +910,57 @@ export class IntegrationConnectorCreationPipeline {
549
910
  */
550
911
  reportSampleFallback(objectName, err, emitter) {
551
912
  const msg = err instanceof Error ? err.message : String(err);
913
+ // MJ-DISC-16: an object discovered for the FIRST time cannot be sampled in the run that
914
+ // discovers it — sampling reads through the catalog, and its row only exists after Persist.
915
+ // Remember exactly those, so the pipeline can heal them in the same run rather than leaving
916
+ // a brand-new object with catalog-guessed widths until someone happens to refresh again.
917
+ if (/IntegrationObject not found/i.test(msg)) {
918
+ (this._firstDiscoveryFallbacks ??= new Set()).add(objectName);
919
+ }
552
920
  emitter.stageError('Introspect', `Sampling fell back to the catalog description for "${objectName}" — real widths and ` +
553
921
  `undeclared columns are unknown for this run: ${msg}`, { code: 'discover-fields-fallback' });
554
922
  console.warn(`[IntrospectPipeline] sample fallback for "${objectName}": ${msg}`);
555
923
  }
924
+ /**
925
+ * LAST RESORT before an object is persisted with NO FIELDS AT ALL.
926
+ *
927
+ * A sample returns zero fields whenever it saw zero records, and an empty source table is an
928
+ * ordinary state rather than a malfunction — so it never throws, never takes the failure
929
+ * fallback, and the empty result was written out as the object's schema. The object then maps
930
+ * to nothing and syncs nothing, and because discovery does not re-run on its own, the emptiness
931
+ * of a table at one moment becomes a permanent property of the schema. All while the connector's
932
+ * own describe surface knew the columns the entire time.
933
+ *
934
+ * Only ever consulted when nothing else can supply fields. An object whose declaration already
935
+ * names fields keeps them and merges normally — which is also what preserves the sampler's
936
+ * deliberate "adjourn to declared-only fields" outcome for a composition child whose parent
937
+ * tuple is unknowable: that returns zero fields ON PURPOSE, and it must stay a no-op rather
938
+ * than become a fallback.
939
+ */
940
+ async describeAsLastResort(objectName, opts, emitter) {
941
+ // Announce it either way. The condition being reported is "this discovery learned nothing",
942
+ // which is true whether or not the catalog can rescue it — and a fieldless object that
943
+ // nobody was told about is exactly how this stayed invisible.
944
+ this.reportSampleFallback(objectName, new Error('the sample returned no fields (the source produced no records)'), emitter);
945
+ try {
946
+ return await opts.Connector.DiscoverFields(opts.CompanyIntegration, objectName, opts.ContextUser);
947
+ }
948
+ catch (err) {
949
+ const msg = err instanceof Error ? err.message : String(err);
950
+ console.warn(`[IntrospectPipeline] catalog backstop also failed for "${objectName}": ${msg}`);
951
+ return [];
952
+ }
953
+ }
556
954
  async sampleDeclaredObjectInPlace(existing, objectName, opts, emitter) {
557
955
  try {
558
- const dfields = await opts.Connector.DiscoverFieldsViaFetch(opts.CompanyIntegration, objectName, opts.ContextUser, { OnFallback: (err) => this.reportSampleFallback(objectName, err, emitter) });
956
+ let dfields = await opts.Connector.DiscoverFieldsViaFetch(opts.CompanyIntegration, objectName, opts.ContextUser, { OnFallback: (err) => this.reportSampleFallback(objectName, err, emitter) });
957
+ if (dfields.length === 0 && existing.Fields.length === 0) {
958
+ // A name-only declaration plus a sample that saw nothing leaves NOTHING to persist,
959
+ // and the branch below would assign that emptiness as the object's whole schema.
960
+ // Gated on the declaration being empty too: an object that declared fields keeps
961
+ // them and merges, so the sampler's deliberate zero-field "adjourn" stays a no-op.
962
+ dfields = await this.describeAsLastResort(objectName, opts, emitter);
963
+ }
559
964
  const sampled = dfields.map(f => ({
560
965
  Name: f.Name, Label: f.Label, Description: f.Description, SourceType: f.DataType,
561
966
  IsRequired: f.IsRequired, AllowsNull: f.AllowsNull, MaxLength: f.MaxLength ?? null,
@@ -605,17 +1010,116 @@ export class IntegrationConnectorCreationPipeline {
605
1010
  console.error(`[IntrospectPipeline] DiscoverFieldsViaFetch failed for declared "${objectName}" — ${lost}: ${msg}`);
606
1011
  }
607
1012
  }
608
- async stagePersist(emitter, opts, sourceSchema) {
1013
+ /**
1014
+ * Is the connection this run belongs to still THERE?
1015
+ *
1016
+ * The run holds an in-memory `CompanyIntegration`; a delete that lands mid-run removes its row and
1017
+ * nothing tells the pipeline. `startSchemaRefreshPipelineDetached` is fire-and-forget, nothing
1018
+ * cancels it, and ConnectionTest passed before the delete — so the run carries on, the per-object
1019
+ * credential lookups fail (the credential went with the connection), each failure is handled as a
1020
+ * legitimate SAMPLING fallback, and Persist then writes 27 description-only object shapes for a
1021
+ * connection that no longer exists. Observed live on the sandbox 2026-09-11: one full pass wrote
1022
+ * 27 objects while the connection list reported zero connections.
1023
+ *
1024
+ * Whether that is loud or silent depends entirely on which catalog is the target, which is why the
1025
+ * check belongs HERE and not in a writer. Per-connection, every row carries
1026
+ * `CompanyIntegrationID` and the FK rejects all 27 — noisy, atomic, nothing lands. SHARED, every
1027
+ * row is keyed by `IntegrationID`, which never goes away: the identical run SUCCEEDS and
1028
+ * overwrites the declared floor with description-only shapes, for this connector's every other
1029
+ * connection. That is the mechanism that corrupted a tenant's declared catalog earlier in this
1030
+ * programme; the FK is all that turned it from invisible damage into clean rollbacks.
1031
+ *
1032
+ * Read with BypassCache — a cached row is exactly the stale answer this question cannot accept.
1033
+ * A failed READ is NOT treated as a deleted connection: refusing a run because a SELECT failed
1034
+ * would turn a transient DB blip into a failed discovery, so only a definitive empty result stops
1035
+ * the write.
1036
+ */
1037
+ async connectionStillExists(opts) {
1038
+ // The run's own provider, as every other read in this run uses.
1039
+ const rv = new RunView(opts.Provider);
1040
+ const result = await rv.RunView({
1041
+ EntityName: 'MJ: Company Integrations',
1042
+ ExtraFilter: `ID='${EscapeSQLString(String(opts.CompanyIntegration.ID))}'`,
1043
+ Fields: ['ID'],
1044
+ MaxRows: 1,
1045
+ ResultType: 'simple',
1046
+ BypassCache: true,
1047
+ }, opts.ContextUser);
1048
+ if (!result.Success)
1049
+ return true; // could not ask ⇒ do not invent an answer
1050
+ return result.Results.length > 0;
1051
+ }
1052
+ /**
1053
+ * One traversal of the source, persisted object by object.
1054
+ *
1055
+ * Peak memory becomes one object's fields instead of the whole catalog. Only object NAMES are
1056
+ * carried to the end, because that is all absent-object retirement needs.
1057
+ *
1058
+ * Retirement is split across the two moments deliberately (see IntegrationSchemaSync):
1059
+ * per object — its own field list is complete, so absent FIELDS may retire; absent OBJECTS may
1060
+ * not, because from one object's vantage every other object looks absent.
1061
+ * final pass — the complete name set is known, so absent OBJECTS may retire; absent FIELDS may
1062
+ * not, because name stubs carry no fields and would retire every column.
1063
+ *
1064
+ * A connector whose IntrospectSchema override ignores OnObject simply returns a populated schema
1065
+ * with `Streamed` falsy, and the old whole-schema persist runs unchanged — which is what keeps
1066
+ * connector overrides in other repositories working untouched.
1067
+ */
1068
+ async streamIntrospectAndPersist(emitter, opts, withDeadline) {
1069
+ const names = [];
1070
+ const agg = emptyPersistResult();
1071
+ const onObject = async (obj) => {
1072
+ names.push(obj.ExternalName);
1073
+ // Not authoritative: the source's claim is only known once the stream ends, so the
1074
+ // per-object persist cannot retire anything yet. Field retirement is requested here so
1075
+ // the intent is in one place, but it stays gated on that claim inside PersistDiscoveredSchema.
1076
+ const r = await this.stagePersist(emitter, opts, { Objects: [obj], IsAuthoritative: false }, { DeactivateAbsentObjects: false, DeactivateAbsentFields: opts.DeactivateAbsent ?? false });
1077
+ addPersistResult(agg, r);
1078
+ };
1079
+ const sourceSchema = await withDeadline('Introspect', this.stageIntrospect(emitter, opts, onObject));
1080
+ if (!sourceSchema.Streamed) {
1081
+ // The connector did not stream — persist the whole schema exactly as before.
1082
+ return withDeadline('Persist', this.stagePersist(emitter, opts, sourceSchema));
1083
+ }
1084
+ // The final name pass exists only to retire absent OBJECTS; with nothing to retire it would
1085
+ // be one no-op upsert per object.
1086
+ if (!opts.DeactivateAbsent)
1087
+ return agg;
1088
+ const tail = await this.stagePersist(emitter, opts, { Objects: names.map(n => nameStub(n)), IsAuthoritative: sourceSchema.IsAuthoritative }, { DeactivateAbsentObjects: true, DeactivateAbsentFields: false });
1089
+ agg.ObjectsDeactivated.push(...tail.ObjectsDeactivated);
1090
+ return agg;
1091
+ }
1092
+ async stagePersist(emitter, opts, sourceSchema, retirement) {
609
1093
  emitter.stageStart('Persist', 'Upserting IntegrationObject/Field rows with overlay precedence');
610
1094
  const startMs = Date.now();
1095
+ // Liveness, re-checked at the WRITE — not only at the start of the run. See
1096
+ // connectionStillExists: the whole harm of a detached run outliving its connection lands in
1097
+ // this stage, and on a shared catalog it lands as a SUCCESS.
1098
+ if (!await this.connectionStillExists(opts)) {
1099
+ const msg = `Connection ${opts.CompanyIntegration.ID} was deleted while this discovery was running, so ` +
1100
+ `nothing was persisted. The objects introspected by this run describe a connection that no ` +
1101
+ `longer exists; writing them would overwrite the declared catalog every other connection of ` +
1102
+ `this connector rebases from.`;
1103
+ emitter.stageError('Persist', msg, { code: 'connection-deleted' });
1104
+ throw new Error(msg);
1105
+ }
611
1106
  const persistResult = await IntegrationSchemaSync.PersistDiscoveredSchema({
612
1107
  IntegrationID: opts.CompanyIntegration.IntegrationID,
1108
+ // The connection this discovery belongs to, and which catalog it writes into. Resolved
1109
+ // in ONE place (CatalogSource.ts) so the read side and the write side of the same run
1110
+ // can never disagree about which catalog they are on.
1111
+ CompanyIntegrationID: opts.CompanyIntegration.ID,
1112
+ CatalogSource: ResolveCatalogSource(opts.CompanyIntegration),
613
1113
  SourceSchema: sourceSchema,
614
1114
  ContextUser: opts.ContextUser,
615
1115
  Provider: opts.Provider,
616
1116
  UseTransactionGroup: true,
617
1117
  // §7 comprehensive-refresh deactivation (objects + fields absent from this discovery).
618
1118
  DeactivateAbsent: opts.DeactivateAbsent ?? false,
1119
+ // The streaming path drives the two halves separately (see streamIntrospectAndPersist);
1120
+ // every other caller leaves them undefined and inherits DeactivateAbsent exactly as before.
1121
+ DeactivateAbsentObjects: retirement?.DeactivateAbsentObjects,
1122
+ DeactivateAbsentFields: retirement?.DeactivateAbsentFields,
619
1123
  });
620
1124
  // Emit per-object + per-field structural-transparency events so the UI/audit
621
1125
  // trail captures WHO won each attribute.
@@ -655,15 +1159,69 @@ export class IntegrationConnectorCreationPipeline {
655
1159
  async stagePKClassify(emitter, opts) {
656
1160
  emitter.stageStart('PKClassify', 'Soft PK classifier for objects still missing a PK');
657
1161
  const md = opts.Provider ?? Metadata.Provider;
658
- const engine = IntegrationEngineBase.Instance;
659
- // Refresh from DB so we see what Persist just wrote
660
- await engine.Config(true, opts.ContextUser, md);
661
- const objects = engine.GetIntegrationObjectsByIntegrationID(opts.CompanyIntegration.IntegrationID);
1162
+ // NO engine reload here (MJ-RUN-42). This stage used to open with
1163
+ // await IntegrationEngineBase.Instance.Config(true, opts.ContextUser, md);
1164
+ // to "see what Persist just wrote". Config(true) reloads ALL EIGHT engine datasets,
1165
+ // including every IntegrationObject and IntegrationObjectField row Persist has just written,
1166
+ // and then this stage reads none of them: every read below goes through the catalog writer,
1167
+ // which queries per call. So it bought nothing and cost a full second copy of the catalog in
1168
+ // process memory at the exact moment memory peaks, immediately after the run's largest write.
1169
+ // Observed 2026-09-19 (888 objects / 97,414 fields): the run persisted both passes and then
1170
+ // died here with `Ineffective mark-compacts near heap limit`, taking classification with it —
1171
+ // 412 keys instead of the 797 the same catalog produced the day before.
1172
+ //
1173
+ // Safe by ORDERING: this is the LAST stage of Run(), so no later stage can observe a staler
1174
+ // cache; the discovery heal opens its second pass with its own refresh; and the callers that
1175
+ // run this pipeline reload the engine once it returns. RefreshCatalog is no cheaper
1176
+ // substitute: the two arrays it reloads ARE the cost. Do not reintroduce a reload here.
1177
+ //
1178
+ // Read through the writer rather than the cache. On the per-connection catalog the cached
1179
+ // rows are read-only projections with no Save(), so the classifier's one write — promoting
1180
+ // its nominee to primary key — would have had nothing to write to.
1181
+ const writer = BuildCatalogWriter(md, opts.CompanyIntegration, opts.ContextUser);
1182
+ const objects = (await writer.ObjectsInScope()).filter(o => o.Status === 'Active');
1183
+ // Ask ONCE which objects already have a key. The loop below used to load every object's
1184
+ // fields as entity objects just to test `some(IsPrimaryKey)` — 97,414 BaseEntity instances
1185
+ // on an 888-object catalog, right after the run's largest write. The keyed majority needs
1186
+ // nothing else and is settled from one scan; the entity read is kept for the keyless
1187
+ // minority, whose nominee must be Saved.
1188
+ const keyedObjectIDs = await writer.KeyedObjectIDs(objects.map(o => String(o.ID)));
662
1189
  const classifier = new SoftPKClassifier();
663
1190
  const verdicts = [];
664
1191
  const unresolved = [];
1192
+ // The same reading, thresholds and heap floor Introspect uses, so the two long stages agree
1193
+ // about what "out of room" means.
1194
+ const outOfMemoryPK = () => ShouldStopForMemory(ReadMemorySample(), IntegrationConnectorCreationPipeline.HEAP_STOP_FRACTION, IntegrationConnectorCreationPipeline.RSS_STOP_FRACTION, HEAP_STOP_MIN_HEADROOM_BYTES);
1195
+ // This stage runs right after the run's largest write, so it starts wherever Introspect
1196
+ // left the heap, and then works a tight loop: a classifier verdict per object and a Save()
1197
+ // for each nominee. Two things keep it from being the stage that dies where Introspect
1198
+ // learned to stop:
1199
+ // 1. YIELD. Every YIELD_EVERY objects, hand the loop back to the event loop so the
1200
+ // collector can run — a loop with no await between allocations never lets it.
1201
+ // 2. GATE, and STOP rather than die. Past the memory fraction, stop classifying. The
1202
+ // objects not reached come back unresolved, are emitted as skipped, and ONE warning
1203
+ // says how many and why. A short key list is the symptom a customer sees, and
1204
+ // "we stopped early under memory pressure" is the only honest explanation for it.
1205
+ // Observed 2026-09-22 on an 888-object catalog: Persist completed, this stage started the
1206
+ // same second, and 44 s later V8 aborted with `Ineffective mark-compacts near heap limit`
1207
+ // — 830 objects kept their fields, 46 kept a key, and the run was marked killed.
1208
+ const YIELD_EVERY = 25;
1209
+ let classifiedCount = 0;
1210
+ let shedForMemory = 0;
665
1211
  for (const obj of objects) {
666
- const fields = engine.GetIntegrationObjectFields(obj.ID);
1212
+ if (classifiedCount > 0 && classifiedCount % YIELD_EVERY === 0) {
1213
+ await new Promise(resolve => setImmediate(resolve));
1214
+ if (outOfMemoryPK()) {
1215
+ shedForMemory = objects.length - classifiedCount;
1216
+ break;
1217
+ }
1218
+ }
1219
+ classifiedCount++;
1220
+ if (keyedObjectIDs.has(String(obj.ID).toLowerCase())) {
1221
+ emitter.entityGenerated(obj.Name, obj.Name);
1222
+ continue;
1223
+ }
1224
+ const fields = await writer.FieldsForObject(obj.ID);
667
1225
  const hasPK = fields.some(f => f.IsPrimaryKey);
668
1226
  if (hasPK) {
669
1227
  emitter.entityGenerated(obj.Name, obj.Name);
@@ -678,6 +1236,16 @@ export class IntegrationConnectorCreationPipeline {
678
1236
  llmInference: opts.LLMInference,
679
1237
  });
680
1238
  emitter.pkClassifierResult(obj.Name, {
1239
+ // How many fields the classifier was actually shown, the names of the first few, and
1240
+ // the object id they were read against. Zero names a defect (an empty or failed
1241
+ // catalog read); a non-zero count with no nominee is an honest "no signal". The names
1242
+ // settle what the count cannot: on 2026-09-27 a connector reported all 34 objects
1243
+ // keyless while 30 carried a primary key in the catalog, and the classifier claimed
1244
+ // its naming strategy found nothing for objects whose field list contains a column
1245
+ // literally named "id" — four theories were argued from that one ambiguous verdict.
1246
+ FieldCount: fields.length,
1247
+ FieldNames: fields.slice(0, PK_VERDICT_FIELD_NAMES).map(f => f.Name),
1248
+ ObjectID: String(obj.ID),
681
1249
  Confident: verdict.Confident,
682
1250
  Nominee: verdict.Nominee,
683
1251
  Confidence: verdict.Confidence,
@@ -715,6 +1283,16 @@ export class IntegrationConnectorCreationPipeline {
715
1283
  emitter.entitySkippedNoPK(obj.Name);
716
1284
  }
717
1285
  }
1286
+ if (shedForMemory > 0) {
1287
+ // Loud, and on the run stream rather than a server console.
1288
+ for (const skipped of objects.slice(objects.length - shedForMemory)) {
1289
+ unresolved.push(skipped.Name);
1290
+ emitter.entitySkippedNoPK(skipped.Name);
1291
+ }
1292
+ emitter.warning('PKClassify', 'HOST_MEMORY_PRESSURE', `Stopped classifying primary keys after ${classifiedCount} of ${objects.length} objects — the ` +
1293
+ `process was at its memory ceiling. The ${shedForMemory} object(s) not reached are reported ` +
1294
+ `without a key; re-run discovery with more memory, or a smaller selection, to classify them.`, { classified: classifiedCount, total: objects.length, shed: shedForMemory });
1295
+ }
718
1296
  emitter.stageComplete('PKClassify', {
719
1297
  processed: verdicts.length,
720
1298
  succeeded: verdicts.filter(v => v.Confident).length,