@memberjunction/integration-engine 6.2.0-edge.5 → 6.2.0-edge.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/BaseIntegrationConnector.d.ts.map +1 -1
- package/dist/BaseIntegrationConnector.js +22 -4
- package/dist/BaseIntegrationConnector.js.map +1 -1
- package/dist/BaseRESTIntegrationConnector.d.ts +2 -2
- package/dist/BaseRESTIntegrationConnector.d.ts.map +1 -1
- package/dist/BaseRESTIntegrationConnector.js +34 -4
- package/dist/BaseRESTIntegrationConnector.js.map +1 -1
- package/dist/CatalogScope.d.ts +152 -0
- package/dist/CatalogScope.d.ts.map +1 -0
- package/dist/CatalogScope.js +399 -0
- package/dist/CatalogScope.js.map +1 -0
- package/dist/CatalogSource.d.ts +53 -0
- package/dist/CatalogSource.d.ts.map +1 -0
- package/dist/CatalogSource.js +82 -0
- package/dist/CatalogSource.js.map +1 -0
- package/dist/CatalogWriter.d.ts +216 -0
- package/dist/CatalogWriter.d.ts.map +1 -0
- package/dist/CatalogWriter.js +457 -0
- package/dist/CatalogWriter.js.map +1 -0
- package/dist/CompanyIntegrationCatalogStore.d.ts +109 -0
- package/dist/CompanyIntegrationCatalogStore.d.ts.map +1 -0
- package/dist/CompanyIntegrationCatalogStore.js +229 -0
- package/dist/CompanyIntegrationCatalogStore.js.map +1 -0
- package/dist/DiscoveryWatchdog.d.ts +38 -1
- package/dist/DiscoveryWatchdog.d.ts.map +1 -1
- package/dist/DiscoveryWatchdog.js +56 -1
- package/dist/DiscoveryWatchdog.js.map +1 -1
- package/dist/IntegrationActionGenerator.d.ts.map +1 -1
- package/dist/IntegrationActionGenerator.js +33 -26
- package/dist/IntegrationActionGenerator.js.map +1 -1
- package/dist/IntegrationConnectorCreationPipeline.d.ts +141 -4
- package/dist/IntegrationConnectorCreationPipeline.d.ts.map +1 -1
- package/dist/IntegrationConnectorCreationPipeline.js +521 -64
- package/dist/IntegrationConnectorCreationPipeline.js.map +1 -1
- package/dist/IntegrationEngine.d.ts +13 -0
- package/dist/IntegrationEngine.d.ts.map +1 -1
- package/dist/IntegrationEngine.js +250 -164
- package/dist/IntegrationEngine.js.map +1 -1
- package/dist/IntegrationSchemaSync.d.ts +97 -0
- package/dist/IntegrationSchemaSync.d.ts.map +1 -1
- package/dist/IntegrationSchemaSync.js +300 -49
- package/dist/IntegrationSchemaSync.js.map +1 -1
- package/dist/MatchEngine.d.ts.map +1 -1
- package/dist/MatchEngine.js +6 -0
- package/dist/MatchEngine.js.map +1 -1
- package/dist/index.d.ts +8 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -1
- package/dist/types.d.ts +21 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +7 -7
|
@@ -1,9 +1,124 @@
|
|
|
1
1
|
import { LogError, Metadata } from '@memberjunction/core';
|
|
2
2
|
import { IntegrationProgressEmitter, } from '@memberjunction/integration-progress-artifacts';
|
|
3
3
|
import { SoftPKClassifier, } from '@memberjunction/integration-pk-classifier';
|
|
4
|
-
import {
|
|
4
|
+
import { BuildCatalogWriter, ResolveCatalogSource } from './CatalogSource.js';
|
|
5
|
+
import { LoadCatalogScope, RunInCatalogScope } from './CatalogScope.js';
|
|
5
6
|
import { IntegrationSchemaSync } from './IntegrationSchemaSync.js';
|
|
6
7
|
import { MergeDeclaredWithSample } from './DeclaredSampleMerge.js';
|
|
8
|
+
import { getHeapStatistics } from 'node:v8';
|
|
9
|
+
import { totalmem } from 'node:os';
|
|
10
|
+
/**
|
|
11
|
+
* Has the heap reached the point where a long stage must stop taking on new work?
|
|
12
|
+
*
|
|
13
|
+
* Pure, so the boundary is testable without arranging real memory pressure — the same reason the
|
|
14
|
+
* overlay deciders in IntegrationSchemaSync are pure.
|
|
15
|
+
*
|
|
16
|
+
* A limit of zero means V8 did not report a ceiling. That must read as "do not stop": a missing
|
|
17
|
+
* reading is not evidence of pressure, and treating it as pressure would halt sampling everywhere
|
|
18
|
+
* the statistic is unavailable.
|
|
19
|
+
*
|
|
20
|
+
* `minHeadroomBytes` (default 0 = off) also stops when no more than that many bytes remain below
|
|
21
|
+
* the limit. A heap caller needs it; see {@link HEAP_STOP_MIN_HEADROOM_BYTES}. An RSS caller (limit
|
|
22
|
+
* = the box) does not pass it.
|
|
23
|
+
*/
|
|
24
|
+
export function ShouldStopSamplingForHeap(usedBytes, limitBytes, stopFraction, minHeadroomBytes = 0) {
|
|
25
|
+
if (!(limitBytes > 0) || !(stopFraction > 0))
|
|
26
|
+
return false;
|
|
27
|
+
if (usedBytes / limitBytes >= stopFraction)
|
|
28
|
+
return true;
|
|
29
|
+
return minHeadroomBytes > 0 && limitBytes - usedBytes <= minHeadroomBytes;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* The absolute headroom a HEAP reading must keep, beside its fraction.
|
|
33
|
+
*
|
|
34
|
+
* A fraction of `heap_size_limit` alone cannot fire on a small heap. That limit includes a fixed
|
|
35
|
+
* young-generation reserve (192 MB on Node 20-24, constant across `--max-old-space-size` values)
|
|
36
|
+
* which live data can never occupy: V8 aborts when the OLD space fills, i.e. at
|
|
37
|
+
* `heap_size_limit - reserve`. At 0.92 the fractional stop sits ABOVE that line for every old space
|
|
38
|
+
* 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
|
|
39
|
+
* above), so on such a box the gate could not fire before the abort it exists to prevent. Measured
|
|
40
|
+
* 2026-09-24 on 888 objects / 97k fields: with the heap pre-filled to 92% of a 4 GB limit the gate
|
|
41
|
+
* stopped after 25 objects; the same fill at a 1 GB limit aborted V8 before the stage ran.
|
|
42
|
+
*
|
|
43
|
+
* 320 MB is the reserve plus 128 MB of old space. Above ~4 GB the 8% margin already exceeds it, so
|
|
44
|
+
* large workspaces are unaffected.
|
|
45
|
+
*/
|
|
46
|
+
export const HEAP_STOP_MIN_HEADROOM_BYTES = 320 * 1024 * 1024;
|
|
47
|
+
/** The live reading. Cheap enough per object: counters V8 and the OS already maintain. */
|
|
48
|
+
export function ReadMemorySample() {
|
|
49
|
+
const heap = getHeapStatistics();
|
|
50
|
+
return {
|
|
51
|
+
HeapUsed: heap.used_heap_size,
|
|
52
|
+
HeapLimit: heap.heap_size_limit,
|
|
53
|
+
RSS: process.memoryUsage().rss,
|
|
54
|
+
TotalMemory: totalmem(),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Stop when EITHER ceiling is close. The heap gate alone cannot save a process the kernel kills:
|
|
59
|
+
* the kernel measures resident memory against the box, V8 measures the heap against its own
|
|
60
|
+
* limit, and the two diverge — parsed response bodies, driver buffers and heap fragmentation all
|
|
61
|
+
* sit in RSS outside the live heap, so RSS runs well above it under load. Observed 2026-09-18 and
|
|
62
|
+
* 2026-09-21 on a 15.7 GB box: node killed at 15.3 GB and 15.6 GB anon-RSS mid-discovery while
|
|
63
|
+
* the heap was still under its ceiling, so the heap gate never fired. An unknown reading (a
|
|
64
|
+
* limit or a box size of 0) is not evidence of pressure, as for the heap.
|
|
65
|
+
*
|
|
66
|
+
* `heapMinHeadroomBytes` applies to the HEAP reading only (see
|
|
67
|
+
* {@link HEAP_STOP_MIN_HEADROOM_BYTES}); resident memory is judged against the whole box, where a
|
|
68
|
+
* fraction is the right measure.
|
|
69
|
+
*/
|
|
70
|
+
export function ShouldStopForMemory(sample, heapStopFraction, rssStopFraction, heapMinHeadroomBytes = 0) {
|
|
71
|
+
return ShouldStopSamplingForHeap(sample.HeapUsed, sample.HeapLimit, heapStopFraction, heapMinHeadroomBytes)
|
|
72
|
+
|| ShouldStopSamplingForHeap(sample.RSS, sample.TotalMemory, rssStopFraction);
|
|
73
|
+
}
|
|
74
|
+
/** A persist result with nothing in it yet — the accumulator a streaming persist sums into. */
|
|
75
|
+
function emptyPersistResult() {
|
|
76
|
+
return {
|
|
77
|
+
ObjectsCreated: 0,
|
|
78
|
+
ObjectsUpdated: 0,
|
|
79
|
+
FieldsCreated: 0,
|
|
80
|
+
FieldsUpdated: 0,
|
|
81
|
+
ObjectMergeLog: [],
|
|
82
|
+
FieldMergeLog: [],
|
|
83
|
+
ObjectsDeactivated: [],
|
|
84
|
+
FieldsDeactivated: [],
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
/** Folds one per-object persist into the streaming total. */
|
|
88
|
+
function addPersistResult(total, part) {
|
|
89
|
+
total.ObjectsCreated += part.ObjectsCreated;
|
|
90
|
+
total.ObjectsUpdated += part.ObjectsUpdated;
|
|
91
|
+
total.FieldsCreated += part.FieldsCreated;
|
|
92
|
+
total.FieldsUpdated += part.FieldsUpdated;
|
|
93
|
+
total.ObjectMergeLog.push(...part.ObjectMergeLog);
|
|
94
|
+
total.FieldMergeLog.push(...part.FieldMergeLog);
|
|
95
|
+
total.ObjectsDeactivated.push(...part.ObjectsDeactivated);
|
|
96
|
+
total.FieldsDeactivated.push(...part.FieldsDeactivated);
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* A name-only object for the final pass of a streamed persist, which exists to tell the absent-
|
|
100
|
+
* object retirement which objects the source still has. It must carry NO opinion: the persist
|
|
101
|
+
* overlay treats any non-empty label or description as the source's, so a stub labelled with its
|
|
102
|
+
* own name would overwrite every stored DisplayName with the raw object name. An empty label is
|
|
103
|
+
* silence to the overlay, and a row that is somehow new still gets its name as display name.
|
|
104
|
+
*/
|
|
105
|
+
function nameStub(externalName) {
|
|
106
|
+
return { ExternalName: externalName, ExternalLabel: '', Fields: [], PrimaryKeyFields: [], Relationships: [] };
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Runs the work it is handed one item at a time, in arrival order, however many callers hand work
|
|
110
|
+
* in at once. A failure belongs to the caller that handed it in; it never stalls the next one.
|
|
111
|
+
*/
|
|
112
|
+
function serialQueue() {
|
|
113
|
+
let tail = Promise.resolve();
|
|
114
|
+
return (work) => {
|
|
115
|
+
const run = tail.then(work);
|
|
116
|
+
tail = run.then(() => undefined, () => undefined);
|
|
117
|
+
return run;
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
/** How many field names a `pk.classifier.result` event carries — enough to read, bounded for a wide object. */
|
|
121
|
+
const PK_VERDICT_FIELD_NAMES = 12;
|
|
7
122
|
/**
|
|
8
123
|
* The unified pipeline that drives connector creation / refresh end-to-end:
|
|
9
124
|
*
|
|
@@ -52,11 +167,58 @@ export class IntegrationConnectorCreationPipeline {
|
|
|
52
167
|
*/
|
|
53
168
|
static { this.IN_FLIGHT_MAX_AGE_MS = 20 * 60_000; }
|
|
54
169
|
/**
|
|
55
|
-
* Default whole-run ceiling
|
|
56
|
-
*
|
|
57
|
-
*
|
|
170
|
+
* Default whole-run ceiling, deliberately enormous: it exists ONLY to release a run that has hung
|
|
171
|
+
* forever, never to bound work that is merely big. At 45 minutes it did the latter — an 888-object
|
|
172
|
+
* catalog was failed at object 336, and because the failure precedes Persist, everything
|
|
173
|
+
* introspected up to then was discarded. A connection that wants a tighter bound sets
|
|
174
|
+
* `Configuration.runDeadlineMs`; the environment can set `MJ_INTEGRATION_RUN_DEADLINE_MS`.
|
|
175
|
+
*/
|
|
176
|
+
static { this.DEFAULT_RUN_DEADLINE_MS = 12 * 60 * 60_000; }
|
|
177
|
+
/**
|
|
178
|
+
* Resolves the whole-run ceiling: explicit argument → the connection's `Configuration.runDeadlineMs`
|
|
179
|
+
* → `MJ_INTEGRATION_RUN_DEADLINE_MS` → {@link DEFAULT_RUN_DEADLINE_MS}.
|
|
180
|
+
*
|
|
181
|
+
* `0` is a MEANINGFUL value here (it disables the ceiling), which is why this does not reuse the
|
|
182
|
+
* positive-only reader the inner discovery knobs share — that one treats 0 as absent and would make
|
|
183
|
+
* "no ceiling" unexpressible. Negatives and non-numerics are rejected rather than honoured, so a
|
|
184
|
+
* malformed Configuration falls through to the next source instead of disabling the one mechanism
|
|
185
|
+
* that rescues a run stuck in-flight forever.
|
|
186
|
+
*/
|
|
187
|
+
static resolveRunDeadlineMs(opts) {
|
|
188
|
+
const valid = (v) => typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.floor(v) : undefined;
|
|
189
|
+
const explicit = valid(opts.RunDeadlineMs);
|
|
190
|
+
if (explicit != null)
|
|
191
|
+
return explicit;
|
|
192
|
+
let fromConfig;
|
|
193
|
+
try {
|
|
194
|
+
const raw = opts.CompanyIntegration?.Configuration;
|
|
195
|
+
if (raw)
|
|
196
|
+
fromConfig = valid(JSON.parse(raw).runDeadlineMs);
|
|
197
|
+
}
|
|
198
|
+
catch { /* malformed Configuration → fall through to env/default */ }
|
|
199
|
+
if (fromConfig != null)
|
|
200
|
+
return fromConfig;
|
|
201
|
+
const fromEnv = Number.parseInt(process.env.MJ_INTEGRATION_RUN_DEADLINE_MS ?? '', 10);
|
|
202
|
+
if (Number.isFinite(fromEnv) && fromEnv >= 0)
|
|
203
|
+
return fromEnv;
|
|
204
|
+
return IntegrationConnectorCreationPipeline.DEFAULT_RUN_DEADLINE_MS;
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Heap fraction past which Introspect stops taking on NEW sampling work.
|
|
208
|
+
*
|
|
209
|
+
* Higher than a warning threshold on purpose. A warning exists to fire while there is still
|
|
210
|
+
* room to act; this is the last exit before V8 gives up, and past it the next large allocation
|
|
211
|
+
* is as likely to abort the process as to succeed. 0.92 leaves roughly the cost of one more
|
|
212
|
+
* object's sample plus the persist that follows — enough to land what has already been
|
|
213
|
+
* gathered, which is the entire point of stopping rather than being stopped.
|
|
58
214
|
*/
|
|
59
|
-
static { this.
|
|
215
|
+
static { this.HEAP_STOP_FRACTION = 0.92; }
|
|
216
|
+
/**
|
|
217
|
+
* Resident-set fraction of the box's memory past which the two long stages stop. Lower than
|
|
218
|
+
* the heap fraction on purpose: the box is shared with everything else that runs on it, and
|
|
219
|
+
* the kernel does not warn first. See ShouldStopForMemory.
|
|
220
|
+
*/
|
|
221
|
+
static { this.RSS_STOP_FRACTION = 0.80; }
|
|
60
222
|
/** Just-completed runs by CompanyIntegrationID — coalesces a *sequential* duplicate within the window. */
|
|
61
223
|
static { this.recentRuns = new Map(); }
|
|
62
224
|
/** Default coalesce window (ms) when the env override is unset/invalid. */
|
|
@@ -89,8 +251,22 @@ export class IntegrationConnectorCreationPipeline {
|
|
|
89
251
|
* is indistinguishable from "the run hasn't opened its stream yet". So whenever a caller supplied
|
|
90
252
|
* a `RunID` and coalescing served a different run, we publish a terminal ALIAS run under the
|
|
91
253
|
* requested ID pointing at the run that actually did the work. See {@link honourRequestedRunID}.
|
|
254
|
+
*
|
|
255
|
+
* CATALOG SCOPE. Every read a discovery makes — the connector's GetCachedObject/GetCachedFields during
|
|
256
|
+
* sampling, the dependency graph, the excluded-field resolution — happens with THIS connection
|
|
257
|
+
* in catalog scope. Scope-aware getters answer from the connection's own rows once it has any
|
|
258
|
+
* and fall back to the shared declared rows until then, so a first discovery still sees the
|
|
259
|
+
* connector's declared floor and a re-discovery sees what this connection found last time,
|
|
260
|
+
* not what some other connection of the same connector found.
|
|
92
261
|
*/
|
|
93
262
|
async Run(opts) {
|
|
263
|
+
// Entered SYNCHRONOUSLY. The de-dup below registers this run before the caller's next
|
|
264
|
+
// statement, which is what lets a concurrent duplicate find it; awaiting the catalog load
|
|
265
|
+
// first would open a window in which both callers start a run. The connection's catalog is
|
|
266
|
+
// loaded inside the run instead (runInternal), where a failed read is a failed run.
|
|
267
|
+
return RunInCatalogScope(opts.CompanyIntegration?.ID ?? '', () => this.runWithDedup(opts));
|
|
268
|
+
}
|
|
269
|
+
async runWithDedup(opts) {
|
|
94
270
|
const ciID = opts.CompanyIntegration?.ID;
|
|
95
271
|
if (!ciID)
|
|
96
272
|
return this.runInternal(opts); // no key to de-dup on — run directly
|
|
@@ -234,8 +410,8 @@ export class IntegrationConnectorCreationPipeline {
|
|
|
234
410
|
// THE RUN MUST END. Raced rather than awaited: a stage that never settles cannot be cancelled,
|
|
235
411
|
// but it can be stopped being waited on — which is the difference between a run that fails and
|
|
236
412
|
// one that is in-flight forever. See RunDeadlineMs.
|
|
237
|
-
const deadlineMs =
|
|
238
|
-
// The
|
|
413
|
+
const deadlineMs = IntegrationConnectorCreationPipeline.resolveRunDeadlineMs(opts);
|
|
414
|
+
// The ceiling is configurable and a caller (or a connection) may set seconds — in
|
|
239
415
|
// which case rounding to minutes reported the failure as a "deadline of 0min", which reads as
|
|
240
416
|
// a bug in the pipeline rather than the limit the caller actually asked for.
|
|
241
417
|
const deadlineLabel = deadlineMs >= 60_000
|
|
@@ -263,9 +439,13 @@ export class IntegrationConnectorCreationPipeline {
|
|
|
263
439
|
clearTimeout(deadlineTimer); });
|
|
264
440
|
};
|
|
265
441
|
try {
|
|
442
|
+
// The connection's own catalog is no longer resident (MJ-RUN-43): load its objects and
|
|
443
|
+
// dependency edges into the scope before any stage reads them synchronously.
|
|
444
|
+
await LoadCatalogScope(opts.CompanyIntegration.ID, opts.ContextUser);
|
|
266
445
|
await withDeadline('ConnectionTest', this.stageConnectionTest(emitter, opts));
|
|
267
|
-
|
|
268
|
-
|
|
446
|
+
// Introspect + Persist as ONE traversal of the source when the connector can stream;
|
|
447
|
+
// the old whole-schema persist when it cannot. See streamIntrospectAndPersist.
|
|
448
|
+
const persistResult = await this.streamIntrospectAndPersist(emitter, opts, withDeadline);
|
|
269
449
|
const { verdicts, unresolved } = await withDeadline('PKClassify', this.stagePKClassify(emitter, opts));
|
|
270
450
|
emitter.stageComplete('Pipeline', {
|
|
271
451
|
processed: persistResult.ObjectsCreated + persistResult.ObjectsUpdated,
|
|
@@ -311,7 +491,7 @@ export class IntegrationConnectorCreationPipeline {
|
|
|
311
491
|
emitter.checkpoint('ConnectionTest', { completedAt: new Date().toISOString(), durationMs: Date.now() - startMs });
|
|
312
492
|
}
|
|
313
493
|
// ── Stage 2: introspect ──────────────────────────────────────────────
|
|
314
|
-
async stageIntrospect(emitter, opts) {
|
|
494
|
+
async stageIntrospect(emitter, opts, onObject) {
|
|
315
495
|
emitter.stageStart('Introspect', 'Discovering objects and fields via connector');
|
|
316
496
|
const startMs = Date.now();
|
|
317
497
|
// Sampling is now per OBJECT, so this stage's cost scales with the catalog — and on a large
|
|
@@ -324,8 +504,28 @@ export class IntegrationConnectorCreationPipeline {
|
|
|
324
504
|
// it, so the two differ by one connectivity probe. The approximation can only ever stop
|
|
325
505
|
// work LATER than the race — never earlier — so it cannot truncate a run that would
|
|
326
506
|
// otherwise have completed.
|
|
327
|
-
const budgetMs =
|
|
507
|
+
const budgetMs = IntegrationConnectorCreationPipeline.resolveRunDeadlineMs(opts);
|
|
328
508
|
const outOfTime = () => budgetMs > 0 && Date.now() - startMs >= budgetMs;
|
|
509
|
+
// THE OTHER BUDGET. Introspect accumulates: `schema.Objects` holds every object with every
|
|
510
|
+
// field for the whole stage and is handed to the persist stage only at the end, so memory
|
|
511
|
+
// climbs monotonically with the size of the source and is never released mid-stage. On a
|
|
512
|
+
// large catalog that reaches V8's ceiling before the time budget is anywhere near spent —
|
|
513
|
+
// 888 objects, some with thousands of columns, is ~97k field descriptors held at once, and
|
|
514
|
+
// a first discovery samples the whole set TWICE.
|
|
515
|
+
//
|
|
516
|
+
// Running out of memory here is not like running out of time. Time ends the stage with
|
|
517
|
+
// everything gathered so far intact; the heap ceiling ends the PROCESS, so the run loses
|
|
518
|
+
// every object it had already sampled, writes no result, and stays in flight forever.
|
|
519
|
+
// Observed 2026-09-19: two hours of sampling discarded by
|
|
520
|
+
// `FATAL ERROR: Ineffective mark-compacts near heap limit`.
|
|
521
|
+
//
|
|
522
|
+
// So memory gets the same treatment time already has — stop taking on new sampling, keep
|
|
523
|
+
// what is gathered, let the stage finish and persist. A smaller catalog beats no catalog.
|
|
524
|
+
// Read synchronously and per object: `used_heap_size` is a counter V8 already maintains,
|
|
525
|
+
// and the alternative (the async whole-machine reading) cannot be afforded per item.
|
|
526
|
+
// The heap side also keeps an absolute floor: on a small heap the fraction alone sits above
|
|
527
|
+
// V8's real abort line (see HEAP_STOP_MIN_HEADROOM_BYTES).
|
|
528
|
+
const outOfMemory = () => ShouldStopForMemory(ReadMemorySample(), IntegrationConnectorCreationPipeline.HEAP_STOP_FRACTION, IntegrationConnectorCreationPipeline.RSS_STOP_FRACTION, HEAP_STOP_MIN_HEADROOM_BYTES);
|
|
329
529
|
try {
|
|
330
530
|
// U11 — determinate discovery progress: surface scanned/total on the structured
|
|
331
531
|
// stream (IntegrationTailRunEvents carries counts) so a client can render a real
|
|
@@ -338,7 +538,99 @@ export class IntegrationConnectorCreationPipeline {
|
|
|
338
538
|
lastEmitted = scanned;
|
|
339
539
|
emitter.heartbeat('Introspect', `scanned ${scanned}/${total} objects`, { processed: scanned, totalKnown: total });
|
|
340
540
|
};
|
|
341
|
-
|
|
541
|
+
// §7 — a SCOPED introspection asked about a named subset. IntrospectSchema already
|
|
542
|
+
// honours the filter; DiscoverObjects does not take it, so without this the scoped run
|
|
543
|
+
// pulled and sampled the whole runtime catalog anyway.
|
|
544
|
+
const wantedNames = opts.IntrospectOptions?.ObjectNames;
|
|
545
|
+
const wanted = wantedNames && wantedNames.length > 0
|
|
546
|
+
? new Set(wantedNames.map(n => n.toLowerCase()))
|
|
547
|
+
: null;
|
|
548
|
+
const inScope = (name) => !wanted || wanted.has(name.toLowerCase());
|
|
549
|
+
const declaredNames = [];
|
|
550
|
+
const seen = new Set();
|
|
551
|
+
const sampledDeclared = new Set();
|
|
552
|
+
let runtimeAdded = 0;
|
|
553
|
+
let unsampledForTime = 0;
|
|
554
|
+
let unsampledForMemory = 0;
|
|
555
|
+
// Per-object progress. Everything below this point is the expensive half of discovery —
|
|
556
|
+
// one read-path sample per object — and it emitted nothing, so a consumer watching a
|
|
557
|
+
// 23-object source saw the same silence as a 5-object one for however long it ran.
|
|
558
|
+
// The denominator is the union BOTH passes will sample (in-scope runtime objects plus
|
|
559
|
+
// in-scope declared ones) rather than either loop's own length, so the total is fixed
|
|
560
|
+
// before the first sample instead of revising upward when the second pass starts. (A
|
|
561
|
+
// STREAMED declared catalog is the exception: its size is unknown until the stream
|
|
562
|
+
// ends, so the denominator grows as it arrives.)
|
|
563
|
+
const sampleUniverse = new Set();
|
|
564
|
+
// Keyed, not counted: a name the connector surfaces twice is sampled twice by the loop
|
|
565
|
+
// below, and a bare counter would then report "24 of 23".
|
|
566
|
+
const announced = new Set();
|
|
567
|
+
const announceSample = (name) => {
|
|
568
|
+
const k = name.toLowerCase();
|
|
569
|
+
if (announced.has(k))
|
|
570
|
+
return;
|
|
571
|
+
announced.add(k);
|
|
572
|
+
emitter.heartbeat('Introspect', `Sampling "${name}" (${announced.size} of ${sampleUniverse.size})`, {
|
|
573
|
+
processed: announced.size,
|
|
574
|
+
totalKnown: sampleUniverse.size,
|
|
575
|
+
skipped: unsampledForTime,
|
|
576
|
+
});
|
|
577
|
+
};
|
|
578
|
+
// STREAMING. When the caller persists per object (onObject), each declared object is
|
|
579
|
+
// sampled HERE, as the connector hands it over, and then handed on — never collected.
|
|
580
|
+
// Everything after IntrospectSchema reads `schema.Objects`, which is empty by design
|
|
581
|
+
// when the connector streamed, so without this nothing streamed would be sampled and
|
|
582
|
+
// every runtime object would look brand new. Sampling stays serial, as it is when the
|
|
583
|
+
// catalog is accumulated, even when the connector describes several objects at once.
|
|
584
|
+
const streamedNames = [];
|
|
585
|
+
let streamedFields = 0;
|
|
586
|
+
const handOff = async (obj) => {
|
|
587
|
+
streamedNames.push(obj.ExternalName);
|
|
588
|
+
streamedFields += obj.Fields.length;
|
|
589
|
+
await onObject(obj);
|
|
590
|
+
};
|
|
591
|
+
const serially = serialQueue();
|
|
592
|
+
const streamDeclared = async (obj) => {
|
|
593
|
+
const key = obj.ExternalName.toLowerCase();
|
|
594
|
+
declaredNames.push(obj.ExternalName);
|
|
595
|
+
seen.add(key);
|
|
596
|
+
if (inScope(obj.ExternalName)) {
|
|
597
|
+
sampleUniverse.add(key);
|
|
598
|
+
await serially(async () => {
|
|
599
|
+
// Two declared entries differing only by case are ONE object: sample it once.
|
|
600
|
+
if (sampledDeclared.has(key))
|
|
601
|
+
return;
|
|
602
|
+
announceSample(obj.ExternalName);
|
|
603
|
+
if (outOfTime()) {
|
|
604
|
+
unsampledForTime++;
|
|
605
|
+
return;
|
|
606
|
+
}
|
|
607
|
+
if (outOfMemory()) {
|
|
608
|
+
unsampledForMemory++;
|
|
609
|
+
return;
|
|
610
|
+
}
|
|
611
|
+
sampledDeclared.add(key);
|
|
612
|
+
await this.sampleDeclaredObjectInPlace(obj, obj.ExternalName, opts, emitter);
|
|
613
|
+
});
|
|
614
|
+
}
|
|
615
|
+
await handOff(obj);
|
|
616
|
+
};
|
|
617
|
+
const schema = await opts.Connector.IntrospectSchema(opts.CompanyIntegration, opts.ContextUser, { ...(opts.IntrospectOptions ?? {}), OnProgress: onProgress, OnObject: onObject ? streamDeclared : undefined });
|
|
618
|
+
// Streamed if the connector says so — or if it called the handler at all: an override
|
|
619
|
+
// that forwards OnObject but rebuilds its result without the flag would otherwise get a
|
|
620
|
+
// whole-schema persist of an EMPTY schema, which on an authoritative comprehensive
|
|
621
|
+
// refresh finds every stored object absent and retires all of them.
|
|
622
|
+
const streamed = !!onObject && (schema.Streamed === true || streamedNames.length > 0);
|
|
623
|
+
if (streamed) {
|
|
624
|
+
// Anything the connector returned rather than streamed goes through the same door.
|
|
625
|
+
for (const leftover of schema.Objects.splice(0))
|
|
626
|
+
await streamDeclared(leftover);
|
|
627
|
+
}
|
|
628
|
+
else {
|
|
629
|
+
for (const o of schema.Objects) {
|
|
630
|
+
declaredNames.push(o.ExternalName);
|
|
631
|
+
seen.add(o.ExternalName.toLowerCase());
|
|
632
|
+
}
|
|
633
|
+
}
|
|
342
634
|
// UNIVERSAL additive runtime-object discovery — the single chokepoint EVERY connector
|
|
343
635
|
// funnels through, regardless of which base it extends or whether that base's
|
|
344
636
|
// IntrospectSchema only reflects already-declared metadata. IntrospectSchema gives the
|
|
@@ -348,8 +640,6 @@ export class IntegrationConnectorCreationPipeline {
|
|
|
348
640
|
// can't silently lose runtime discovery). PersistDiscoveredSchema is additive, so
|
|
349
641
|
// declared objects are preserved and runtime-only objects (e.g. an auth-gated file
|
|
350
642
|
// 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
643
|
let runtimeObjects = [];
|
|
354
644
|
// A DiscoverObjects failure used to end sampling for the ENTIRE run: the loop below was
|
|
355
645
|
// the only thing that sampled, and it iterated this (now empty) list. The declared
|
|
@@ -366,49 +656,20 @@ export class IntegrationConnectorCreationPipeline {
|
|
|
366
656
|
emitter.stageError('Introspect', `DiscoverObjects failed: ${msg}`, { code: 'discover-objects-failed' });
|
|
367
657
|
console.error(`[IntrospectPipeline] DiscoverObjects failed: ${msg}`);
|
|
368
658
|
}
|
|
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
659
|
for (const d of runtimeObjects)
|
|
388
660
|
if (inScope(d.Name))
|
|
389
661
|
sampleUniverse.add(d.Name.toLowerCase());
|
|
390
662
|
for (const n of declaredNames)
|
|
391
663
|
if (inScope(n))
|
|
392
664
|
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
665
|
for (const d of runtimeObjects) {
|
|
409
666
|
const key = d.Name.toLowerCase();
|
|
410
667
|
if (!inScope(d.Name))
|
|
411
668
|
continue;
|
|
669
|
+
// Streamed: a declared object was already sampled (or budget-skipped) and handed on
|
|
670
|
+
// as it arrived — counting it again here would report it twice.
|
|
671
|
+
if (streamed && seen.has(key))
|
|
672
|
+
continue;
|
|
412
673
|
// Announced BEFORE the budget check so an exhausted budget reads as a run that
|
|
413
674
|
// reached the end of its object list, not one that stalled partway through it.
|
|
414
675
|
announceSample(d.Name);
|
|
@@ -416,6 +677,10 @@ export class IntegrationConnectorCreationPipeline {
|
|
|
416
677
|
unsampledForTime++;
|
|
417
678
|
continue;
|
|
418
679
|
}
|
|
680
|
+
if (outOfMemory()) {
|
|
681
|
+
unsampledForMemory++;
|
|
682
|
+
continue;
|
|
683
|
+
}
|
|
419
684
|
if (seen.has(key)) {
|
|
420
685
|
// §case-3 (data-only-discoverable): a DECLARED object the connector ALSO surfaces at
|
|
421
686
|
// runtime. Sampling populates it IN PLACE so a name-only declaration becomes syncable
|
|
@@ -441,7 +706,13 @@ export class IntegrationConnectorCreationPipeline {
|
|
|
441
706
|
emitter.stageError('Introspect', `DiscoverFieldsViaFetch failed for "${d.Name}": ${msg}`, { code: 'discover-fields-failed' });
|
|
442
707
|
console.error(`[IntrospectPipeline] DiscoverFieldsViaFetch failed for "${d.Name}": ${msg}`);
|
|
443
708
|
}
|
|
444
|
-
|
|
709
|
+
if (fields.length === 0) {
|
|
710
|
+
// A RUNTIME-DISCOVERED object has no declaration behind it, so the sample is the
|
|
711
|
+
// only source of fields there is — an empty one is persisted verbatim as a
|
|
712
|
+
// fieldless object. Ask the connector's describe surface before accepting that.
|
|
713
|
+
fields = await this.describeAsLastResort(d.Name, opts, emitter);
|
|
714
|
+
}
|
|
715
|
+
const built = {
|
|
445
716
|
ExternalName: d.Name,
|
|
446
717
|
ExternalLabel: d.Label,
|
|
447
718
|
Description: d.Description,
|
|
@@ -467,7 +738,12 @@ export class IntegrationConnectorCreationPipeline {
|
|
|
467
738
|
Relationships: fields
|
|
468
739
|
.filter(f => (f.IsForeignKey ?? false) && f.ForeignKeyTarget)
|
|
469
740
|
.map(f => ({ FieldName: f.Name, TargetObject: f.ForeignKeyTarget, TargetField: 'ID' })),
|
|
470
|
-
}
|
|
741
|
+
};
|
|
742
|
+
// Streamed: persisted now and released, like every other object of a streamed run.
|
|
743
|
+
if (streamed)
|
|
744
|
+
await handOff(built);
|
|
745
|
+
else
|
|
746
|
+
schema.Objects.push(built);
|
|
471
747
|
runtimeAdded++;
|
|
472
748
|
}
|
|
473
749
|
// The union's second half: DECLARED objects the runtime pass never reached. Sampling used
|
|
@@ -476,8 +752,9 @@ export class IntegrationConnectorCreationPipeline {
|
|
|
476
752
|
// for every object when DiscoverObjects fails — was never sampled at all. It kept whatever
|
|
477
753
|
// widths the catalog guessed (a truncation waiting to happen) and could only ever gain its
|
|
478
754
|
// undeclared columns later, one sync at a time, through the overflow path.
|
|
755
|
+
// (Streamed: every declared object went through streamDeclared, which already sampled it.)
|
|
479
756
|
let declaredOnlySampled = 0;
|
|
480
|
-
for (const name of declaredNames) {
|
|
757
|
+
for (const name of streamed ? [] : declaredNames) {
|
|
481
758
|
const key = name.toLowerCase();
|
|
482
759
|
if (sampledDeclared.has(key) || !inScope(name))
|
|
483
760
|
continue;
|
|
@@ -486,6 +763,10 @@ export class IntegrationConnectorCreationPipeline {
|
|
|
486
763
|
unsampledForTime++;
|
|
487
764
|
continue;
|
|
488
765
|
}
|
|
766
|
+
if (outOfMemory()) {
|
|
767
|
+
unsampledForMemory++;
|
|
768
|
+
continue;
|
|
769
|
+
}
|
|
489
770
|
const existing = schema.Objects.find(o => o.ExternalName.toLowerCase() === key);
|
|
490
771
|
if (!existing)
|
|
491
772
|
continue;
|
|
@@ -506,21 +787,37 @@ export class IntegrationConnectorCreationPipeline {
|
|
|
506
787
|
emitter.stageError('Introspect', msg, { code: 'sample-budget-exhausted' });
|
|
507
788
|
console.warn(`[IntrospectPipeline] ${msg}`);
|
|
508
789
|
}
|
|
509
|
-
|
|
510
|
-
|
|
790
|
+
if (unsampledForMemory > 0) {
|
|
791
|
+
// Deliberately the code the sync path already emits and the UI already renders,
|
|
792
|
+
// rather than a second vocabulary for the same condition.
|
|
793
|
+
const msg = `This workspace ran short of memory partway through reading your source, so ` +
|
|
794
|
+
`${unsampledForMemory} object(s) were not sampled and keep their declared fields ` +
|
|
795
|
+
`and catalog widths. Everything sampled before that point was kept. Re-run to ` +
|
|
796
|
+
`finish the rest, or give the workspace more memory for a source this size.`;
|
|
797
|
+
emitter.warning('Introspect', 'HOST_MEMORY_PRESSURE', msg, {
|
|
798
|
+
unsampledForMemory,
|
|
799
|
+
sampled: announced.size - unsampledForMemory - unsampledForTime,
|
|
800
|
+
});
|
|
801
|
+
console.warn(`[IntrospectPipeline] ${msg}`);
|
|
802
|
+
}
|
|
803
|
+
// A streamed run handed its objects on instead of keeping them, so count what it handed.
|
|
804
|
+
const discovered = streamedNames.length + schema.Objects.length;
|
|
805
|
+
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}`);
|
|
806
|
+
const fieldCount = streamedFields + schema.Objects.reduce((acc, o) => acc + o.Fields.length, 0);
|
|
511
807
|
emitter.stageComplete('Introspect', {
|
|
512
|
-
processed:
|
|
513
|
-
succeeded:
|
|
514
|
-
totalKnown:
|
|
808
|
+
processed: discovered,
|
|
809
|
+
succeeded: discovered,
|
|
810
|
+
totalKnown: discovered,
|
|
515
811
|
});
|
|
516
812
|
emitter.checkpoint('Introspect', {
|
|
517
|
-
objectsDiscovered:
|
|
813
|
+
objectsDiscovered: discovered,
|
|
518
814
|
fieldsDiscovered: fieldCount,
|
|
519
815
|
durationMs: Date.now() - startMs,
|
|
520
816
|
discoverObjectsFailed,
|
|
521
817
|
unsampledForTime,
|
|
818
|
+
unsampledForMemory,
|
|
522
819
|
});
|
|
523
|
-
return schema;
|
|
820
|
+
return streamed ? { ...schema, Objects: [], Streamed: true } : schema;
|
|
524
821
|
}
|
|
525
822
|
catch (err) {
|
|
526
823
|
const msg = err instanceof Error ? err.message : String(err);
|
|
@@ -553,9 +850,46 @@ export class IntegrationConnectorCreationPipeline {
|
|
|
553
850
|
`undeclared columns are unknown for this run: ${msg}`, { code: 'discover-fields-fallback' });
|
|
554
851
|
console.warn(`[IntrospectPipeline] sample fallback for "${objectName}": ${msg}`);
|
|
555
852
|
}
|
|
853
|
+
/**
|
|
854
|
+
* LAST RESORT before an object is persisted with NO FIELDS AT ALL.
|
|
855
|
+
*
|
|
856
|
+
* A sample returns zero fields whenever it saw zero records, and an empty source table is an
|
|
857
|
+
* ordinary state rather than a malfunction — so it never throws, never takes the failure
|
|
858
|
+
* fallback, and the empty result was written out as the object's schema. The object then maps
|
|
859
|
+
* to nothing and syncs nothing, and because discovery does not re-run on its own, the emptiness
|
|
860
|
+
* of a table at one moment becomes a permanent property of the schema. All while the connector's
|
|
861
|
+
* own describe surface knew the columns the entire time.
|
|
862
|
+
*
|
|
863
|
+
* Only ever consulted when nothing else can supply fields. An object whose declaration already
|
|
864
|
+
* names fields keeps them and merges normally — which is also what preserves the sampler's
|
|
865
|
+
* deliberate "adjourn to declared-only fields" outcome for a composition child whose parent
|
|
866
|
+
* tuple is unknowable: that returns zero fields ON PURPOSE, and it must stay a no-op rather
|
|
867
|
+
* than become a fallback.
|
|
868
|
+
*/
|
|
869
|
+
async describeAsLastResort(objectName, opts, emitter) {
|
|
870
|
+
// Announce it either way. The condition being reported is "this discovery learned nothing",
|
|
871
|
+
// which is true whether or not the catalog can rescue it — and a fieldless object that
|
|
872
|
+
// nobody was told about is exactly how this stayed invisible.
|
|
873
|
+
this.reportSampleFallback(objectName, new Error('the sample returned no fields (the source produced no records)'), emitter);
|
|
874
|
+
try {
|
|
875
|
+
return await opts.Connector.DiscoverFields(opts.CompanyIntegration, objectName, opts.ContextUser);
|
|
876
|
+
}
|
|
877
|
+
catch (err) {
|
|
878
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
879
|
+
console.warn(`[IntrospectPipeline] catalog backstop also failed for "${objectName}": ${msg}`);
|
|
880
|
+
return [];
|
|
881
|
+
}
|
|
882
|
+
}
|
|
556
883
|
async sampleDeclaredObjectInPlace(existing, objectName, opts, emitter) {
|
|
557
884
|
try {
|
|
558
|
-
|
|
885
|
+
let dfields = await opts.Connector.DiscoverFieldsViaFetch(opts.CompanyIntegration, objectName, opts.ContextUser, { OnFallback: (err) => this.reportSampleFallback(objectName, err, emitter) });
|
|
886
|
+
if (dfields.length === 0 && existing.Fields.length === 0) {
|
|
887
|
+
// A name-only declaration plus a sample that saw nothing leaves NOTHING to persist,
|
|
888
|
+
// and the branch below would assign that emptiness as the object's whole schema.
|
|
889
|
+
// Gated on the declaration being empty too: an object that declared fields keeps
|
|
890
|
+
// them and merges, so the sampler's deliberate zero-field "adjourn" stays a no-op.
|
|
891
|
+
dfields = await this.describeAsLastResort(objectName, opts, emitter);
|
|
892
|
+
}
|
|
559
893
|
const sampled = dfields.map(f => ({
|
|
560
894
|
Name: f.Name, Label: f.Label, Description: f.Description, SourceType: f.DataType,
|
|
561
895
|
IsRequired: f.IsRequired, AllowsNull: f.AllowsNull, MaxLength: f.MaxLength ?? null,
|
|
@@ -605,17 +939,66 @@ export class IntegrationConnectorCreationPipeline {
|
|
|
605
939
|
console.error(`[IntrospectPipeline] DiscoverFieldsViaFetch failed for declared "${objectName}" — ${lost}: ${msg}`);
|
|
606
940
|
}
|
|
607
941
|
}
|
|
608
|
-
|
|
942
|
+
/**
|
|
943
|
+
* One traversal of the source, persisted object by object.
|
|
944
|
+
*
|
|
945
|
+
* Peak memory becomes one object's fields instead of the whole catalog. Only object NAMES are
|
|
946
|
+
* carried to the end, because that is all absent-object retirement needs.
|
|
947
|
+
*
|
|
948
|
+
* Retirement is split across the two moments deliberately (see IntegrationSchemaSync):
|
|
949
|
+
* per object — its own field list is complete, so absent FIELDS may retire; absent OBJECTS may
|
|
950
|
+
* not, because from one object's vantage every other object looks absent.
|
|
951
|
+
* final pass — the complete name set is known, so absent OBJECTS may retire; absent FIELDS may
|
|
952
|
+
* not, because name stubs carry no fields and would retire every column.
|
|
953
|
+
*
|
|
954
|
+
* A connector whose IntrospectSchema override ignores OnObject simply returns a populated schema
|
|
955
|
+
* with `Streamed` falsy, and the old whole-schema persist runs unchanged — which is what keeps
|
|
956
|
+
* connector overrides in other repositories working untouched.
|
|
957
|
+
*/
|
|
958
|
+
async streamIntrospectAndPersist(emitter, opts, withDeadline) {
|
|
959
|
+
const names = [];
|
|
960
|
+
const agg = emptyPersistResult();
|
|
961
|
+
const onObject = async (obj) => {
|
|
962
|
+
names.push(obj.ExternalName);
|
|
963
|
+
// Not authoritative: the source's claim is only known once the stream ends, so the
|
|
964
|
+
// per-object persist cannot retire anything yet. Field retirement is requested here so
|
|
965
|
+
// the intent is in one place, but it stays gated on that claim inside PersistDiscoveredSchema.
|
|
966
|
+
const r = await this.stagePersist(emitter, opts, { Objects: [obj], IsAuthoritative: false }, { DeactivateAbsentObjects: false, DeactivateAbsentFields: opts.DeactivateAbsent ?? false });
|
|
967
|
+
addPersistResult(agg, r);
|
|
968
|
+
};
|
|
969
|
+
const sourceSchema = await withDeadline('Introspect', this.stageIntrospect(emitter, opts, onObject));
|
|
970
|
+
if (!sourceSchema.Streamed) {
|
|
971
|
+
// The connector did not stream — persist the whole schema exactly as before.
|
|
972
|
+
return withDeadline('Persist', this.stagePersist(emitter, opts, sourceSchema));
|
|
973
|
+
}
|
|
974
|
+
// The final name pass exists only to retire absent OBJECTS; with nothing to retire it would
|
|
975
|
+
// be one no-op upsert per object.
|
|
976
|
+
if (!opts.DeactivateAbsent)
|
|
977
|
+
return agg;
|
|
978
|
+
const tail = await this.stagePersist(emitter, opts, { Objects: names.map(n => nameStub(n)), IsAuthoritative: sourceSchema.IsAuthoritative }, { DeactivateAbsentObjects: true, DeactivateAbsentFields: false });
|
|
979
|
+
agg.ObjectsDeactivated.push(...tail.ObjectsDeactivated);
|
|
980
|
+
return agg;
|
|
981
|
+
}
|
|
982
|
+
async stagePersist(emitter, opts, sourceSchema, retirement) {
|
|
609
983
|
emitter.stageStart('Persist', 'Upserting IntegrationObject/Field rows with overlay precedence');
|
|
610
984
|
const startMs = Date.now();
|
|
611
985
|
const persistResult = await IntegrationSchemaSync.PersistDiscoveredSchema({
|
|
612
986
|
IntegrationID: opts.CompanyIntegration.IntegrationID,
|
|
987
|
+
// The connection this discovery belongs to, and which catalog it writes into. Resolved
|
|
988
|
+
// in ONE place (CatalogSource.ts) so the read side and the write side of the same run
|
|
989
|
+
// can never disagree about which catalog they are on.
|
|
990
|
+
CompanyIntegrationID: opts.CompanyIntegration.ID,
|
|
991
|
+
CatalogSource: ResolveCatalogSource(opts.CompanyIntegration),
|
|
613
992
|
SourceSchema: sourceSchema,
|
|
614
993
|
ContextUser: opts.ContextUser,
|
|
615
994
|
Provider: opts.Provider,
|
|
616
995
|
UseTransactionGroup: true,
|
|
617
996
|
// §7 comprehensive-refresh deactivation (objects + fields absent from this discovery).
|
|
618
997
|
DeactivateAbsent: opts.DeactivateAbsent ?? false,
|
|
998
|
+
// The streaming path drives the two halves separately (see streamIntrospectAndPersist);
|
|
999
|
+
// every other caller leaves them undefined and inherits DeactivateAbsent exactly as before.
|
|
1000
|
+
DeactivateAbsentObjects: retirement?.DeactivateAbsentObjects,
|
|
1001
|
+
DeactivateAbsentFields: retirement?.DeactivateAbsentFields,
|
|
619
1002
|
});
|
|
620
1003
|
// Emit per-object + per-field structural-transparency events so the UI/audit
|
|
621
1004
|
// trail captures WHO won each attribute.
|
|
@@ -655,15 +1038,69 @@ export class IntegrationConnectorCreationPipeline {
|
|
|
655
1038
|
async stagePKClassify(emitter, opts) {
|
|
656
1039
|
emitter.stageStart('PKClassify', 'Soft PK classifier for objects still missing a PK');
|
|
657
1040
|
const md = opts.Provider ?? Metadata.Provider;
|
|
658
|
-
|
|
659
|
-
//
|
|
660
|
-
|
|
661
|
-
|
|
1041
|
+
// NO engine reload here (MJ-RUN-42). This stage used to open with
|
|
1042
|
+
// await IntegrationEngineBase.Instance.Config(true, opts.ContextUser, md);
|
|
1043
|
+
// to "see what Persist just wrote". Config(true) reloads ALL EIGHT engine datasets,
|
|
1044
|
+
// including every IntegrationObject and IntegrationObjectField row Persist has just written,
|
|
1045
|
+
// and then this stage reads none of them: every read below goes through the catalog writer,
|
|
1046
|
+
// which queries per call. So it bought nothing and cost a full second copy of the catalog in
|
|
1047
|
+
// process memory at the exact moment memory peaks, immediately after the run's largest write.
|
|
1048
|
+
// Observed 2026-09-19 (888 objects / 97,414 fields): the run persisted both passes and then
|
|
1049
|
+
// died here with `Ineffective mark-compacts near heap limit`, taking classification with it —
|
|
1050
|
+
// 412 keys instead of the 797 the same catalog produced the day before.
|
|
1051
|
+
//
|
|
1052
|
+
// Safe by ORDERING: this is the LAST stage of Run(), so no later stage can observe a staler
|
|
1053
|
+
// cache; the discovery heal opens its second pass with its own refresh; and the callers that
|
|
1054
|
+
// run this pipeline reload the engine once it returns. RefreshCatalog is no cheaper
|
|
1055
|
+
// substitute: the two arrays it reloads ARE the cost. Do not reintroduce a reload here.
|
|
1056
|
+
//
|
|
1057
|
+
// Read through the writer rather than the cache. On the per-connection catalog the cached
|
|
1058
|
+
// rows are read-only projections with no Save(), so the classifier's one write — promoting
|
|
1059
|
+
// its nominee to primary key — would have had nothing to write to.
|
|
1060
|
+
const writer = BuildCatalogWriter(md, opts.CompanyIntegration, opts.ContextUser);
|
|
1061
|
+
const objects = (await writer.ObjectsInScope()).filter(o => o.Status === 'Active');
|
|
1062
|
+
// Ask ONCE which objects already have a key. The loop below used to load every object's
|
|
1063
|
+
// fields as entity objects just to test `some(IsPrimaryKey)` — 97,414 BaseEntity instances
|
|
1064
|
+
// on an 888-object catalog, right after the run's largest write. The keyed majority needs
|
|
1065
|
+
// nothing else and is settled from one scan; the entity read is kept for the keyless
|
|
1066
|
+
// minority, whose nominee must be Saved.
|
|
1067
|
+
const keyedObjectIDs = await writer.KeyedObjectIDs(objects.map(o => String(o.ID)));
|
|
662
1068
|
const classifier = new SoftPKClassifier();
|
|
663
1069
|
const verdicts = [];
|
|
664
1070
|
const unresolved = [];
|
|
1071
|
+
// The same reading, thresholds and heap floor Introspect uses, so the two long stages agree
|
|
1072
|
+
// about what "out of room" means.
|
|
1073
|
+
const outOfMemoryPK = () => ShouldStopForMemory(ReadMemorySample(), IntegrationConnectorCreationPipeline.HEAP_STOP_FRACTION, IntegrationConnectorCreationPipeline.RSS_STOP_FRACTION, HEAP_STOP_MIN_HEADROOM_BYTES);
|
|
1074
|
+
// This stage runs right after the run's largest write, so it starts wherever Introspect
|
|
1075
|
+
// left the heap, and then works a tight loop: a classifier verdict per object and a Save()
|
|
1076
|
+
// for each nominee. Two things keep it from being the stage that dies where Introspect
|
|
1077
|
+
// learned to stop:
|
|
1078
|
+
// 1. YIELD. Every YIELD_EVERY objects, hand the loop back to the event loop so the
|
|
1079
|
+
// collector can run — a loop with no await between allocations never lets it.
|
|
1080
|
+
// 2. GATE, and STOP rather than die. Past the memory fraction, stop classifying. The
|
|
1081
|
+
// objects not reached come back unresolved, are emitted as skipped, and ONE warning
|
|
1082
|
+
// says how many and why. A short key list is the symptom a customer sees, and
|
|
1083
|
+
// "we stopped early under memory pressure" is the only honest explanation for it.
|
|
1084
|
+
// Observed 2026-09-22 on an 888-object catalog: Persist completed, this stage started the
|
|
1085
|
+
// same second, and 44 s later V8 aborted with `Ineffective mark-compacts near heap limit`
|
|
1086
|
+
// — 830 objects kept their fields, 46 kept a key, and the run was marked killed.
|
|
1087
|
+
const YIELD_EVERY = 25;
|
|
1088
|
+
let classifiedCount = 0;
|
|
1089
|
+
let shedForMemory = 0;
|
|
665
1090
|
for (const obj of objects) {
|
|
666
|
-
|
|
1091
|
+
if (classifiedCount > 0 && classifiedCount % YIELD_EVERY === 0) {
|
|
1092
|
+
await new Promise(resolve => setImmediate(resolve));
|
|
1093
|
+
if (outOfMemoryPK()) {
|
|
1094
|
+
shedForMemory = objects.length - classifiedCount;
|
|
1095
|
+
break;
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
classifiedCount++;
|
|
1099
|
+
if (keyedObjectIDs.has(String(obj.ID).toLowerCase())) {
|
|
1100
|
+
emitter.entityGenerated(obj.Name, obj.Name);
|
|
1101
|
+
continue;
|
|
1102
|
+
}
|
|
1103
|
+
const fields = await writer.FieldsForObject(obj.ID);
|
|
667
1104
|
const hasPK = fields.some(f => f.IsPrimaryKey);
|
|
668
1105
|
if (hasPK) {
|
|
669
1106
|
emitter.entityGenerated(obj.Name, obj.Name);
|
|
@@ -678,6 +1115,16 @@ export class IntegrationConnectorCreationPipeline {
|
|
|
678
1115
|
llmInference: opts.LLMInference,
|
|
679
1116
|
});
|
|
680
1117
|
emitter.pkClassifierResult(obj.Name, {
|
|
1118
|
+
// How many fields the classifier was actually shown, the names of the first few, and
|
|
1119
|
+
// the object id they were read against. Zero names a defect (an empty or failed
|
|
1120
|
+
// catalog read); a non-zero count with no nominee is an honest "no signal". The names
|
|
1121
|
+
// settle what the count cannot: on 2026-09-27 a connector reported all 34 objects
|
|
1122
|
+
// keyless while 30 carried a primary key in the catalog, and the classifier claimed
|
|
1123
|
+
// its naming strategy found nothing for objects whose field list contains a column
|
|
1124
|
+
// literally named "id" — four theories were argued from that one ambiguous verdict.
|
|
1125
|
+
FieldCount: fields.length,
|
|
1126
|
+
FieldNames: fields.slice(0, PK_VERDICT_FIELD_NAMES).map(f => f.Name),
|
|
1127
|
+
ObjectID: String(obj.ID),
|
|
681
1128
|
Confident: verdict.Confident,
|
|
682
1129
|
Nominee: verdict.Nominee,
|
|
683
1130
|
Confidence: verdict.Confidence,
|
|
@@ -715,6 +1162,16 @@ export class IntegrationConnectorCreationPipeline {
|
|
|
715
1162
|
emitter.entitySkippedNoPK(obj.Name);
|
|
716
1163
|
}
|
|
717
1164
|
}
|
|
1165
|
+
if (shedForMemory > 0) {
|
|
1166
|
+
// Loud, and on the run stream rather than a server console.
|
|
1167
|
+
for (const skipped of objects.slice(objects.length - shedForMemory)) {
|
|
1168
|
+
unresolved.push(skipped.Name);
|
|
1169
|
+
emitter.entitySkippedNoPK(skipped.Name);
|
|
1170
|
+
}
|
|
1171
|
+
emitter.warning('PKClassify', 'HOST_MEMORY_PRESSURE', `Stopped classifying primary keys after ${classifiedCount} of ${objects.length} objects — the ` +
|
|
1172
|
+
`process was at its memory ceiling. The ${shedForMemory} object(s) not reached are reported ` +
|
|
1173
|
+
`without a key; re-run discovery with more memory, or a smaller selection, to classify them.`, { classified: classifiedCount, total: objects.length, shed: shedForMemory });
|
|
1174
|
+
}
|
|
718
1175
|
emitter.stageComplete('PKClassify', {
|
|
719
1176
|
processed: verdicts.length,
|
|
720
1177
|
succeeded: verdicts.filter(v => v.Confident).length,
|