@memberjunction/integration-engine 6.2.0-edge.6 → 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 (63) 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 +90 -5
  12. package/dist/BaseIntegrationConnector.js.map +1 -1
  13. package/dist/BaseRESTIntegrationConnector.d.ts.map +1 -1
  14. package/dist/BaseRESTIntegrationConnector.js +9 -0
  15. package/dist/BaseRESTIntegrationConnector.js.map +1 -1
  16. package/dist/DeclaredSampleMerge.d.ts +10 -4
  17. package/dist/DeclaredSampleMerge.d.ts.map +1 -1
  18. package/dist/DeclaredSampleMerge.js +17 -6
  19. package/dist/DeclaredSampleMerge.js.map +1 -1
  20. package/dist/IntegrationActionGenerator.d.ts.map +1 -1
  21. package/dist/IntegrationActionGenerator.js +3 -0
  22. package/dist/IntegrationActionGenerator.js.map +1 -1
  23. package/dist/IntegrationConnectorCreationPipeline.d.ts +40 -0
  24. package/dist/IntegrationConnectorCreationPipeline.d.ts.map +1 -1
  25. package/dist/IntegrationConnectorCreationPipeline.js +128 -7
  26. package/dist/IntegrationConnectorCreationPipeline.js.map +1 -1
  27. package/dist/IntegrationEngine.d.ts +73 -2
  28. package/dist/IntegrationEngine.d.ts.map +1 -1
  29. package/dist/IntegrationEngine.js +510 -45
  30. package/dist/IntegrationEngine.js.map +1 -1
  31. package/dist/IntegrationSchemaSync.d.ts.map +1 -1
  32. package/dist/IntegrationSchemaSync.js +2 -0
  33. package/dist/IntegrationSchemaSync.js.map +1 -1
  34. package/dist/MemoryGovernor.d.ts +183 -0
  35. package/dist/MemoryGovernor.d.ts.map +1 -0
  36. package/dist/MemoryGovernor.js +225 -0
  37. package/dist/MemoryGovernor.js.map +1 -0
  38. package/dist/ResourcePressure.d.ts +80 -0
  39. package/dist/ResourcePressure.d.ts.map +1 -0
  40. package/dist/ResourcePressure.js +143 -0
  41. package/dist/ResourcePressure.js.map +1 -0
  42. package/dist/RunMemoryControl.d.ts +122 -0
  43. package/dist/RunMemoryControl.d.ts.map +1 -0
  44. package/dist/RunMemoryControl.js +237 -0
  45. package/dist/RunMemoryControl.js.map +1 -0
  46. package/dist/SchemaPersistCounts.d.ts +29 -0
  47. package/dist/SchemaPersistCounts.d.ts.map +1 -0
  48. package/dist/SchemaPersistCounts.js +27 -0
  49. package/dist/SchemaPersistCounts.js.map +1 -0
  50. package/dist/SyncLogger.d.ts +21 -0
  51. package/dist/SyncLogger.d.ts.map +1 -1
  52. package/dist/SyncLogger.js +92 -1
  53. package/dist/SyncLogger.js.map +1 -1
  54. package/dist/WatermarkService.d.ts.map +1 -1
  55. package/dist/WatermarkService.js +1 -0
  56. package/dist/WatermarkService.js.map +1 -1
  57. package/dist/index.d.ts +4 -0
  58. package/dist/index.d.ts.map +1 -1
  59. package/dist/index.js +2 -0
  60. package/dist/index.js.map +1 -1
  61. package/dist/types.d.ts +25 -0
  62. package/dist/types.d.ts.map +1 -1
  63. package/package.json +7 -7
@@ -13,6 +13,8 @@ import { FieldMappingEngine } from './FieldMappingEngine.js';
13
13
  import { MatchEngine } from './MatchEngine.js';
14
14
  import { WatermarkService } from './WatermarkService.js';
15
15
  import { SyncLogger } from './SyncLogger.js';
16
+ import { ReadResourcePressure, EvaluatePressure } from './ResourcePressure.js';
17
+ import { RunMemoryControl } from './RunMemoryControl.js';
16
18
  import { CONTENT_HASH_COLUMN, ComputeContentHash } from './ContentHash.js';
17
19
  import { RecordMapBatch } from './RecordMapBatch.js';
18
20
  import { BuildContentHashPrefetchFilter, QuoteTextLiteral } from './prefetchFilter.js';
@@ -435,6 +437,20 @@ export class IntegrationEngine extends BaseSingleton {
435
437
  }
436
438
  /** In-process lock map to prevent concurrent syncs for the same CompanyIntegration */
437
439
  static { this.activeSyncs = new Map(); }
440
+ /**
441
+ * Live progress for runs owned by THIS process, keyed like activeSyncs.
442
+ *
443
+ * Progress moved to the run row's ProgressJSON so any process could read it — but that column
444
+ * arrives in MJ 6.1.x, and the in-process map was deleted at the same time. On every earlier
445
+ * tenant that left NO source at all: the async reader silently finds nothing (RunView drops the
446
+ * unknown field) and the synchronous accessor was left returning undefined by contract. A sync
447
+ * could run for an hour with the UI showing nothing running.
448
+ *
449
+ * This is the floor. GetSyncProgressAsync prefers the durable row and falls back here, so a
450
+ * single-process tenant answers correctly today and a multi-process one still answers from the
451
+ * row once the column exists.
452
+ */
453
+ static { this.liveProgress = new Map(); }
438
454
  /**
439
455
  * Maintenance locks: while a metadata refresh / schema evolution / RSU pipeline is
440
456
  * running for a CompanyIntegration, data syncs MUST NOT start ("locks of sync and scheduled
@@ -457,6 +473,19 @@ export class IntegrationEngine extends BaseSingleton {
457
473
  IntegrationEngine.maintenanceLocks.set(key, { Reason: reason, AcquiredAt: new Date() });
458
474
  return true;
459
475
  }
476
+ /**
477
+ * Whether a sync for this connection is executing IN THIS PROCESS right now.
478
+ *
479
+ * Exists so a caller can tell an operator the truth about a cancel. The durable cancel needs
480
+ * a run-row column that only newer tenants have; where it is absent, the in-process registry
481
+ * is the only signal there is, and "we signalled the sync" versus "a sync is running
482
+ * somewhere we cannot reach" are different things to tell someone who just hit pause.
483
+ *
484
+ * Reads the same map RunSync reserves, so it cannot drift from what is actually running.
485
+ */
486
+ static IsSyncRunningInThisProcess(companyIntegrationID) {
487
+ return IntegrationEngine.activeSyncs.has(companyIntegrationID.toLowerCase());
488
+ }
460
489
  /** Releases the maintenance lock (idempotent — safe in a finally). */
461
490
  static ReleaseMaintenanceLock(companyIntegrationID) {
462
491
  IntegrationEngine.maintenanceLocks.delete(companyIntegrationID.toLowerCase());
@@ -596,22 +625,30 @@ export class IntegrationEngine extends BaseSingleton {
596
625
  EntityName: 'MJ: Company Integration Runs',
597
626
  ExtraFilter: `CompanyIntegrationID='${companyIntegrationID.replace(/'/g, "''")}' AND Status IN ('In Progress','Queued')`,
598
627
  OrderBy: 'StartedAt DESC',
599
- Fields: ['ProgressJSON', 'LeaseExpiresAt', 'StartedAt'],
628
+ Fields: ['ID', 'ProgressJSON', 'LeaseExpiresAt', 'StartedAt'],
600
629
  MaxRows: 1,
630
+ SkipTotalRowCount: true,
601
631
  ResultType: 'simple',
602
632
  BypassCache: true, // live liveness/progress read — must see the current row
603
633
  }, contextUser);
604
634
  const row = result.Success ? result.Results?.[0] : undefined;
635
+ // No readable row is not proof there is no sync: before MJ 6.1.x the run row has no
636
+ // ProgressJSON column at all, and RunView drops the unknown field silently rather than
637
+ // failing. Fall back to this process's own snapshot.
605
638
  if (!row)
606
- return undefined;
639
+ return IntegrationEngine.liveProgress.get(companyIntegrationID.toLowerCase());
607
640
  if (row.LeaseExpiresAt != null && new Date(row.LeaseExpiresAt).getTime() < Date.now()) {
608
641
  return undefined; // owner's lease lapsed — not live progress
609
642
  }
610
- if (!row.ProgressJSON)
611
- return undefined;
643
+ if (!row.ProgressJSON) {
644
+ const local = IntegrationEngine.liveProgress.get(companyIntegrationID.toLowerCase());
645
+ // The row is readable even when the column is not, so the id is known here even on a
646
+ // tenant whose snapshot came from this process rather than the database.
647
+ return local ? { ...local, RunID: local.RunID ?? row.ID } : undefined;
648
+ }
612
649
  try {
613
650
  const snapshot = JSON.parse(row.ProgressJSON);
614
- return { ...snapshot, StartedAt: new Date(snapshot.StartedAt) };
651
+ return { ...snapshot, StartedAt: new Date(snapshot.StartedAt), RunID: snapshot.RunID ?? row.ID };
615
652
  }
616
653
  catch {
617
654
  return undefined; // corrupt snapshot — treat as no progress rather than throwing at a poller
@@ -855,11 +892,15 @@ export class IntegrationEngine extends BaseSingleton {
855
892
  RecordsCreated: 0,
856
893
  RecordsUpdated: 0,
857
894
  RecordsErrored: 0,
895
+ RecordsSkipped: 0,
858
896
  // The run's OWN trigger type, recovered above — not a hardcoded 'Scheduled'. This is
859
897
  // what IntegrationGetSyncProgress reports back ("Sync in progress (Manual)"), so a
860
898
  // hardcoded value mislabels every adopted run.
861
899
  TriggerType: resumeTriggerType,
862
900
  };
901
+ // Same reason as the main path: without this a resumed run reports no progress at all
902
+ // on any tenant whose run row has no ProgressJSON column.
903
+ IntegrationEngine.liveProgress.set(lockKey, progressSnapshot);
863
904
  const runCtx = {
864
905
  provider: prov,
865
906
  ownership,
@@ -911,6 +952,7 @@ export class IntegrationEngine extends BaseSingleton {
911
952
  // `existing`). Resolve with the real result when we have one, else a benign empty result so no
912
953
  // waiter hangs. Promise resolve is idempotent and the early-exit `return`s also land here.
913
954
  IntegrationEngine.activeSyncs.delete(lockKey);
955
+ IntegrationEngine.liveProgress.delete(lockKey);
914
956
  resolveResumeLock(resumeResult ?? {
915
957
  Success: false, ErrorMessage: 'Resume produced no result', RecordsProcessed: 0,
916
958
  RecordsCreated: 0, RecordsUpdated: 0, RecordsDeleted: 0, RecordsErrored: 0,
@@ -1066,6 +1108,7 @@ export class IntegrationEngine extends BaseSingleton {
1066
1108
  RecordsCreated: 0,
1067
1109
  RecordsUpdated: 0,
1068
1110
  RecordsErrored: 0,
1111
+ RecordsSkipped: 0,
1069
1112
  TriggerType: triggerType,
1070
1113
  };
1071
1114
  const runCtx = {
@@ -1090,11 +1133,13 @@ export class IntegrationEngine extends BaseSingleton {
1090
1133
  // ProviderToUse / write chain / ownership from THIS context, isolated per run.
1091
1134
  const syncPromise = IntegrationEngine.runContext.run(runCtx, () => this.executeSyncInternal(companyIntegrationID, contextUser, triggerType, wrappedProgress, onNotification, options, abortController.signal, existingRun));
1092
1135
  IntegrationEngine.activeSyncs.set(lockKey, syncPromise);
1136
+ IntegrationEngine.liveProgress.set(lockKey, progressSnapshot);
1093
1137
  try {
1094
1138
  return await syncPromise;
1095
1139
  }
1096
1140
  finally {
1097
1141
  IntegrationEngine.activeSyncs.delete(lockKey);
1142
+ IntegrationEngine.liveProgress.delete(lockKey);
1098
1143
  runCtx.ownership?.StopHeartbeat();
1099
1144
  }
1100
1145
  }
@@ -1274,6 +1319,9 @@ export class IntegrationEngine extends BaseSingleton {
1274
1319
  }
1275
1320
  }
1276
1321
  const summary = this.buildSyncResultBody(config.companyIntegration.Integration, result);
1322
+ // Repeated warnings are rolled up by code (SyncLogger.warning) and the summary is emitted
1323
+ // HERE — before the terminal event, so it lands inside this run's own artifact stream.
1324
+ logger.FlushWarningRollups();
1277
1325
  logger.emit('sync.run.complete', {
1278
1326
  success: result.Success && result.RecordsErrored === 0,
1279
1327
  durationMs: result.Duration,
@@ -1287,12 +1335,22 @@ export class IntegrationEngine extends BaseSingleton {
1287
1335
  });
1288
1336
  // A cancelled run returns normally (no throw) with abortSignal.aborted set — finalize it as
1289
1337
  // 'cancelled' (exitReason='aborted'), NOT 'completed', so a stopped run is distinguishable.
1290
- await this.finalizeSyncProgress(progress, abortSignal?.aborted ? 'cancelled' : 'completed', result.ErrorMessage);
1338
+ //
1339
+ // MJ-RUN-4: a run that abandoned objects must not read as an unqualified success. It is
1340
+ // still 'completed' — the watermark is held and the unfetched window retries next run,
1341
+ // so this is not a failure — but the message has to name what did not finish, or a
1342
+ // nightly sync that dies on its first page every night looks like an unbroken run of
1343
+ // clean Successes with TotalRecords=0.
1344
+ const completionMessage = BuildRunCompletionMessage(result.IncompleteObjects ?? [], result.ErrorMessage, abortSignal?.aborted === true);
1345
+ await this.finalizeSyncProgress(progress, abortSignal?.aborted ? 'cancelled' : 'completed', completionMessage);
1291
1346
  console.log(`[IntegrationEngine] Sync complete:\n${summary}`);
1292
1347
  return result;
1293
1348
  }
1294
1349
  catch (err) {
1295
1350
  const errMsg = err instanceof Error ? err.message : String(err);
1351
+ // A failing run is exactly where a warning cascade is most likely, so flush the rollups
1352
+ // on this path too — before the terminal fail event.
1353
+ logger.FlushWarningRollups();
1296
1354
  logger.emit('sync.run.fail', { error: errMsg, durationMs: Date.now() - startTime });
1297
1355
  // Ownership lost (fence moved / lease reclaimed): the run row now belongs to
1298
1356
  // ANOTHER process — writing a terminal status to it here would clobber the new
@@ -1390,6 +1448,7 @@ export class IntegrationEngine extends BaseSingleton {
1390
1448
  EntityName: 'MJ: Company Integrations',
1391
1449
  ExtraFilter: `ID='${companyIntegrationID}'`,
1392
1450
  MaxRows: 1,
1451
+ SkipTotalRowCount: true,
1393
1452
  ResultType: 'entity_object',
1394
1453
  BypassCache: true,
1395
1454
  },
@@ -1534,6 +1593,8 @@ export class IntegrationEngine extends BaseSingleton {
1534
1593
  };
1535
1594
  const totalMaps = config.entityMaps.length;
1536
1595
  let globalIndex = 0;
1596
+ /** Pressure codes already reported on this run, so each is said once and not per map. */
1597
+ const pressureWarned = new Set();
1537
1598
  // Per-map processing. Extracted so it can run sequentially OR concurrently within a
1538
1599
  // dependency layer. Aggregate mutations run when each promise resolves — atomic under
1539
1600
  // single-threaded async, so concurrent maps in a layer are safe.
@@ -1560,7 +1621,9 @@ export class IntegrationEngine extends BaseSingleton {
1560
1621
  // the pipelined path below gets the same warm site for free.
1561
1622
  warmed = await this.warmEntityMapCatalog(config, entityMap, depGraph, contextUser);
1562
1623
  const mapResult = await this.processSingleEntityMap(config, entityMap, run, contextUser, i, totalMaps, onProgress, abortSignal, logger);
1624
+ const governorShedding = config.memoryControl?.IsShedding === true;
1563
1625
  this.mergeResult(aggregate, mapResult);
1626
+ const memoryPressure = await this.warnOnResourcePressure(logger, pressureWarned, governorShedding);
1564
1627
  aggregate.EntityMapResults.push(this.buildEntityMapResult(entityMap, mapResult, Date.now() - mapStartTime));
1565
1628
  logger?.emit('sync.entity-map.complete', {
1566
1629
  externalObjectName: entityMap.ExternalObjectName,
@@ -1576,7 +1639,17 @@ export class IntegrationEngine extends BaseSingleton {
1576
1639
  recordsErrored: mapResult.RecordsErrored,
1577
1640
  });
1578
1641
  this.checkSecondLayerEmpty(entityMap, mapResult, depGraph, processedByIoId, ioNameById, ioCategoryById, logger);
1579
- return { ok: mapResult.Success, throttled: mapResult.Throttled === true };
1642
+ // Host memory pressure enters the SAME AIMD signal a source throttle uses, so it
1643
+ // halves the in-flight cap and ramps back only once maps complete cleanly. That is
1644
+ // the whole adaptive answer to OOM: no per-connector tuning, no advance knowledge of
1645
+ // which connector misbehaves - a connector that returns 10x the requested batch
1646
+ // costs 10x the memory, the reading notices, and the cap follows. Floor is 1, so a
1647
+ // sync always makes progress rather than deadlocking on a full box.
1648
+ // Except while the run's governor is shedding: it has already chosen a lever by
1649
+ // cost and escalates itself if the host stays above the line, so halving here too
1650
+ // would override a hold (no throughput cost) with a halve (half of it). This check
1651
+ // remains the answer when the governor has nothing to act on.
1652
+ return { ok: mapResult.Success, throttled: mapResult.Throttled === true || (memoryPressure && !governorShedding) };
1580
1653
  }
1581
1654
  catch (err) {
1582
1655
  // Ownership loss is NOT a per-map failure to record-and-continue: continuing to the
@@ -1638,6 +1711,18 @@ export class IntegrationEngine extends BaseSingleton {
1638
1711
  // Configuration override (IntegrationSetSyncConfig) wins over the connector's MaxConcurrencyHint constant.
1639
1712
  const maxConcurrency = Math.max(concurrency, this.getConfigOverrides(config).maxConcurrency ?? config.connector.MaxConcurrencyHint ?? concurrency);
1640
1713
  const concController = new AdaptiveConcurrencyController({ start: concurrency, min: 1, max: maxConcurrency });
1714
+ // The governor, scoped to THIS run. Created here because this is the only frame that can
1715
+ // see the concurrency controller; handed down on the config because the decision has to be
1716
+ // taken where a batch lands, several frames below.
1717
+ config.memoryControl = new RunMemoryControl({
1718
+ HoldAdmissions: () => concController.Hold(),
1719
+ ReleaseAdmissions: () => concController.Release(),
1720
+ ReduceConcurrency: () => concController.OnThrottleOrError(),
1721
+ CurrentInFlight: () => concController.Cap,
1722
+ Report: plan => logger?.warning('sync', plan.Exhausted ? 'HOST_MEMORY_EXHAUSTED' : 'HOST_MEMORY_PRESSURE', plan.Exhausted
1723
+ ? `This workspace ran short of memory and there was nothing left to slow down — ${plan.Reason}. It needs a larger size for this amount of data.`
1724
+ : `This workspace is short of memory, so the sync is ${plan.Levers.map(l => LEVER_COPY[l.Code] ?? 'easing off').join(' and ')} to keep going — ${plan.Reason}.`, { reason: plan.Reason, levers: plan.Levers.map(l => l.Code), exhausted: plan.Exhausted })
1725
+ }, this.MaxBatchSize);
1641
1726
  // Second-layer silent-empty detection state (see checkSecondLayerEmpty): a per-IO running
1642
1727
  // record count + the FK dependency graph, so an association/dependent object that fetches
1643
1728
  // ZERO records while it HAS parents is surfaced as a structured SyncWarning. Layers run
@@ -2092,7 +2177,19 @@ export class IntegrationEngine extends BaseSingleton {
2092
2177
  let throttleReported = false;
2093
2178
  try {
2094
2179
  await this.rateLimit(config);
2095
- return await this.withFetchGate(config, () => WithRetry(() => WithTimeout(config.connector.FetchChanges(ctx), fetchTimeoutMs, `FetchChanges(${objectName})`), undefined, (err) => !(err instanceof OperationTimeoutError) && IsRetryableError(ClassifyError(err).Code), (attempt, err, delayMs) => {
2180
+ return await this.withFetchGate(config, () => WithRetry(() => WithTimeout(config.connector.FetchChanges(ctx), fetchTimeoutMs, `FetchChanges(${objectName})`), undefined,
2181
+ // A timeout is NOT retryable here, deliberately: WithTimeout abandons the attempt
2182
+ // without CANCELLING it, so a retry stacks a second full page of vendor requests on
2183
+ // a source already too slow to finish the first. A transport error IS retryable — a
2184
+ // reset socket is worth another go.
2185
+ //
2186
+ // The fleet carried a patch (MJ-MEM-2) that inverted this, because the same rule
2187
+ // abandoned sixteen NetSuite objects for a whole run. That inversion must not be
2188
+ // ported here — it contradicts this decision and the two tests that pin it. What
2189
+ // satisfies both is in ProcessPullSync's fetch-error handler: a KEYSET scan whose page
2190
+ // times out is SUSPENDED and resumes from its persisted key next run, where the page
2191
+ // is retried without stacking on the abandoned attempt.
2192
+ (err) => !(err instanceof OperationTimeoutError) && IsRetryableError(ClassifyError(err).Code), (attempt, err, delayMs) => {
2096
2193
  // Report a throttle NOW, not after the retries are spent. ReportThrottle
2097
2194
  // freezes the shared bucket for this CompanyIntegration, so every other
2098
2195
  // object fetching concurrently backs off too. Once per episode; later
@@ -2275,6 +2372,47 @@ export class IntegrationEngine extends BaseSingleton {
2275
2372
  // same run reads the value that is actually stored.
2276
2373
  entityMap.Configuration = configurationJSON;
2277
2374
  }
2375
+ /**
2376
+ * Reports a keyset scan suspended by a page timeout: a warning that says where the next run
2377
+ * resumes, a Warning-severity entry in the run's queryable error log, and the object on the
2378
+ * run's incomplete list (MJ-RUN-4). Warning severity keeps Status='Success' — nothing failed,
2379
+ * and the position is held exactly — but the run must not read as a clean, complete one.
2380
+ */
2381
+ reportKeysetSuspension(entityMap, batchIndex, recordsApplied, resumeAfterKey, errMsg, result, logger) {
2382
+ const objectName = entityMap.ExternalObjectName ?? entityMap.ID;
2383
+ const resumesFrom = resumeAfterKey
2384
+ ? `resumes from ordering key '${resumeAfterKey}'`
2385
+ : 'restarts from the beginning, or from the position an earlier suspended scan saved if one ' +
2386
+ 'is on record (a full sync does not clear it; the rows before it were applied by that scan)';
2387
+ const message = `Fetch for '${objectName}' timed out at batch ${batchIndex} and is suspended for the rest of this ` +
2388
+ `run: the page is not re-requested while the abandoned request may still be running. ` +
2389
+ `${recordsApplied} record(s) were applied before it. The scan ${resumesFrom} next run, where ` +
2390
+ `this page is retried. Error: ${errMsg}`;
2391
+ logger?.warning(objectName, 'FETCH_SUSPENDED_TIMEOUT', message, {
2392
+ batchIndex,
2393
+ recordsAppliedBeforeTimeout: recordsApplied,
2394
+ resumeAfterKey: resumeAfterKey ?? null,
2395
+ error: errMsg,
2396
+ });
2397
+ result.Errors.push({
2398
+ ExternalID: '',
2399
+ ChangeType: 'Skip',
2400
+ ErrorMessage: message,
2401
+ ErrorCode: 'CONNECTOR_ERROR',
2402
+ Severity: 'Warning',
2403
+ });
2404
+ this.markIncomplete(result, objectName);
2405
+ }
2406
+ /**
2407
+ * Puts an object on the result's incomplete list once (MJ-RUN-4). One object can be held
2408
+ * incomplete for more than one reason in the same run — a suspended page and overlapping pages,
2409
+ * say — and the run summary names objects, not reasons.
2410
+ */
2411
+ markIncomplete(result, objectName) {
2412
+ const list = (result.IncompleteObjects ??= []);
2413
+ if (!list.includes(objectName))
2414
+ list.push(objectName);
2415
+ }
2278
2416
  /**
2279
2417
  * Pull sync: fetch from external → map → match → validate → apply to MJ.
2280
2418
  */
@@ -2400,11 +2538,40 @@ export class IntegrationEngine extends BaseSingleton {
2400
2538
  let previousBatchFingerprint;
2401
2539
  let fetchCompletedCleanly = true; // flipped to false if fetch aborted or errored mid-way
2402
2540
  let hadFetchGap = false; // ≥1 page was skipped after a persistent fetch error (offset/page paging)
2541
+ // A HOLE behind the max watermark seen, from a cause other than a skipped page.
2542
+ //
2543
+ // The early-stop branch below persists the max watermark on the reasoning that whole
2544
+ // batches completed, so nothing unwritten lies past it. That reasoning fails when records
2545
+ // were never HANDED to us at all: a shortfall against the source's own total, or pages that
2546
+ // overlapped and therefore skipped. Those missing records can carry timestamps BELOW the max
2547
+ // we saw, so advancing past them skips them permanently — the same reason that branch already
2548
+ // refuses to run when `hadFetchGap`, which its own comment calls 'a HOLE behind this
2549
+ // watermark'. Clearing `fetchCompletedCleanly` alone is NOT enough: it only moves us out of
2550
+ // the clean branch and into this one.
2551
+ let windowHasHole = false;
2403
2552
  let watermarkFloorSaved = null; // §8a durability floor last persisted mid-run (null = none)
2404
2553
  let fetchGapCount = 0; // CONSECUTIVE skipped pages (reset on any clean fetch)
2554
+ // MJ-RUN-35: the total the SOURCE stated for this object, when it states one.
2555
+ let sourceTotalRecords;
2556
+ // MJ-RUN-36: identities a LATER batch repeated from an EARLIER one. Only meaningful for
2557
+ // position-based paging, where it is evidence the page boundaries moved under us.
2558
+ let crossBatchRepeatCount = 0;
2559
+ const crossBatchRepeatSamples = [];
2405
2560
  const MAX_FETCH_GAPS = 25; // give up + hold the watermark if this many pages fail in a row (API down)
2406
2561
  let consecutiveEmptyBatches = 0; // P3-D: detect a connector that pages empty-but-HasMore forever
2407
2562
  let oversizeBatchWarned = false; // pagination rule: warn ONCE per object that the connector ignored BatchSize
2563
+ // Whether this connector respects the page size it is given. Assumed true until a batch
2564
+ // proves otherwise, because that verdict decides whether asking for smaller pages is the
2565
+ // cheapest lever available under memory pressure or a wasted round trip that frees nothing.
2566
+ let honoursBatchSize = true;
2567
+ /**
2568
+ * The page size THIS run asks for, which the governor may shrink between batches.
2569
+ *
2570
+ * Read fresh per fetch, and captured into a local for the duration of that fetch: the
2571
+ * error-skip path advances the offset by what was REQUESTED, so reading it again after the
2572
+ * governor moved it would skip or re-read a page.
2573
+ */
2574
+ const askedBatchSize = () => config.memoryControl?.BatchSize ?? this.MaxBatchSize;
2408
2575
  const MAX_BATCHES_PER_MAP = 5000;
2409
2576
  const EMPTY_BATCH_WARN_THRESHOLD = 5; // warn once after this many empty-but-HasMore batches in a row
2410
2577
  const fetchedExternalIDs = new Set(); // Track all IDs seen during this pull for orphan detection
@@ -2444,6 +2611,10 @@ export class IntegrationEngine extends BaseSingleton {
2444
2611
  fetchCompletedCleanly = false;
2445
2612
  break;
2446
2613
  }
2614
+ // Captured ONCE per iteration. The governor may shrink the run's page size while this
2615
+ // fetch is in flight, and the error-skip path below advances the offset by what was
2616
+ // asked for — re-reading it there would skip or re-read a page.
2617
+ const requestedThisBatch = askedBatchSize();
2447
2618
  const ctx = {
2448
2619
  CompanyIntegration: config.companyIntegration,
2449
2620
  ObjectName: entityMap.ExternalObjectName,
@@ -2457,7 +2628,7 @@ export class IntegrationEngine extends BaseSingleton {
2457
2628
  // to 707 of 23,558 rows — an id-ascending-AND-modstamp-ascending subsequence — with
2458
2629
  // the run still reporting success. `currentWatermark` remains persistence bookkeeping.
2459
2630
  WatermarkValue: initialWatermark,
2460
- BatchSize: this.MaxBatchSize,
2631
+ BatchSize: requestedThisBatch,
2461
2632
  ContextUser: contextUser,
2462
2633
  CurrentPage: currentPage,
2463
2634
  CurrentOffset: currentOffset,
@@ -2478,7 +2649,7 @@ export class IntegrationEngine extends BaseSingleton {
2478
2649
  page: currentPage ?? null,
2479
2650
  offset: currentOffset ?? null,
2480
2651
  cursor: currentCursor ?? null,
2481
- batchSize: this.MaxBatchSize,
2652
+ batchSize: requestedThisBatch,
2482
2653
  });
2483
2654
  let batch;
2484
2655
  const fetchStart = Date.now();
@@ -2497,6 +2668,12 @@ export class IntegrationEngine extends BaseSingleton {
2497
2668
  batch = await this.governedFetch(config, ctx, entityMap.ExternalObjectName, fetchTimeoutMs, batchCount, logger);
2498
2669
  }
2499
2670
  this.reportRateOutcome(config); // clean fetch → ramp the adaptive rate back up
2671
+ // MJ-RUN-35: remember what the source said it holds. Last statement wins — the
2672
+ // freshest page is the most current answer — and a page that says nothing must
2673
+ // never erase a total an earlier page gave.
2674
+ if (typeof batch.SourceTotalRecords === 'number' && batch.SourceTotalRecords >= 0) {
2675
+ sourceTotalRecords = batch.SourceTotalRecords;
2676
+ }
2500
2677
  fetchGapCount = 0; // clean fetch → reset the consecutive fetch-gap counter
2501
2678
  // §10: connector type-driven post-processing hook (default no-op) — enforce/normalize
2502
2679
  // record values to their resolved formats before mapping + write.
@@ -2574,6 +2751,18 @@ export class IntegrationEngine extends BaseSingleton {
2574
2751
  batchIndex: batchCount,
2575
2752
  error: errMsg,
2576
2753
  });
2754
+ // A KEYSET scan whose page hit our own timeout is SUSPENDED, not skipped. The timed-out
2755
+ // attempt is still running (WithTimeout cannot cancel it), so any further request now
2756
+ // stacks on a source already too slow to finish the first — and the page-skip below
2757
+ // would be exactly that: advancing an offset skips nothing in a seek, so the "next"
2758
+ // page re-requests the SAME key. A keyset scan knows its place (the last key whose
2759
+ // batch was applied), so it stops here, the post-loop save persists that key, and the
2760
+ // next run seeks from it: the timed-out page is retried THERE, never stacked.
2761
+ if (fetchErr instanceof OperationTimeoutError && isKeysetConnector) {
2762
+ fetchCompletedCleanly = false;
2763
+ this.reportKeysetSuspension(entityMap, batchCount, recordsInMap, currentAfterKey, errMsg, result, logger);
2764
+ break;
2765
+ }
2577
2766
  // Resilience: a persistent fetch failure on ONE page shouldn't abandon the whole object.
2578
2767
  // POSITION-based paging (offset/page) can step past the failed page and keep going; we mark
2579
2768
  // the fetch incomplete (so the watermark is HELD below + the orphan/partition sweep is skipped)
@@ -2597,7 +2786,7 @@ export class IntegrationEngine extends BaseSingleton {
2597
2786
  `'${entityMap.ExternalObjectName}' (batch ${batchCount}); skipped this page and continued — the ` +
2598
2787
  `watermark is held so the window is re-fetched next run. Error: ${errMsg}`, { offset: currentOffset ?? null, page: currentPage ?? null, batchIndex: batchCount, error: errMsg });
2599
2788
  if (currentOffset != null)
2600
- currentOffset += this.MaxBatchSize;
2789
+ currentOffset += requestedThisBatch;
2601
2790
  else if (currentPage != null)
2602
2791
  currentPage += 1;
2603
2792
  continue;
@@ -2629,6 +2818,11 @@ export class IntegrationEngine extends BaseSingleton {
2629
2818
  ErrorCode: 'CONNECTOR_ERROR',
2630
2819
  Severity: 'Warning',
2631
2820
  });
2821
+ // MJ-RUN-4: an abandoned object must also reach the RUN-level result, not only the
2822
+ // per-object warning above. A caller reading the run summary otherwise sees a clean
2823
+ // completion and has to go mining the event stream to discover that sixteen objects
2824
+ // ended INCOMPLETE.
2825
+ this.markIncomplete(result, entityMap.ExternalObjectName ?? entityMap.ID);
2632
2826
  break;
2633
2827
  }
2634
2828
  logger?.emit('sync.fetch.batch.complete', {
@@ -2656,9 +2850,28 @@ export class IntegrationEngine extends BaseSingleton {
2656
2850
  // run-event stream, not buried in a console.log nobody reads. Warned ONCE per object (the
2657
2851
  // CONSECUTIVE_EMPTY_BATCHES pattern) so a paginating-but-over-size connector doesn't flood
2658
2852
  // the artifact with one warning per page.
2659
- if (batch.Records.length > this.MaxBatchSize && !oversizeBatchWarned) {
2660
- oversizeBatchWarned = true;
2661
- this.warnOversizedBatch(entityMap, batch, batchCount, logger);
2853
+ if (batch.Records.length > requestedThisBatch) {
2854
+ // The verdict the governor needs: a connector that overshoots its page size cannot
2855
+ // be asked to use less memory by asking for a smaller page.
2856
+ honoursBatchSize = false;
2857
+ if (!oversizeBatchWarned) {
2858
+ oversizeBatchWarned = true;
2859
+ this.warnOversizedBatch(entityMap, batch, batchCount, requestedThisBatch, logger);
2860
+ }
2861
+ }
2862
+ // Decide what to give up, HERE — at the batch, not between tables. A table that fetches
2863
+ // twelve consecutive 2,000-record pages allocates all of it without ever reaching a
2864
+ // between-tables checkpoint, which is how the sandbox reached 3,478 MB of 3,830 MB on
2865
+ // 2026-09-14 with the old check never getting a turn. Never awaited for its answer's
2866
+ // sake and never able to throw: a governor that can fail a run trades an occasional
2867
+ // memory problem for a constant availability one.
2868
+ if (config.memoryControl && batch.Records.length > 0) {
2869
+ await config.memoryControl.NoteBatch({
2870
+ EntityMapID: entityMap.ID,
2871
+ ObservedRecords: batch.Records.length,
2872
+ SampleRecord: batch.Records[0],
2873
+ HonoursBatchSize: honoursBatchSize
2874
+ });
2662
2875
  }
2663
2876
  if (batch.Records.length > 0) {
2664
2877
  const fingerprint = batch.Records.map(r => r.ExternalID).join(',');
@@ -2671,6 +2884,47 @@ export class IntegrationEngine extends BaseSingleton {
2671
2884
  previousBatchFingerprint = fingerprint;
2672
2885
  }
2673
2886
  if (!orphanTrackingOverflowed) {
2887
+ // MJ-RUN-36: an identity seen in an EARLIER batch means the pages overlapped.
2888
+ //
2889
+ // `CollapseDuplicateIdentities` below is within-batch only ("already present in the
2890
+ // same batch"), so it cannot see this, and before this check nothing could: a page
2891
+ // that re-served a row another page already gave was written twice, quietly, as an
2892
+ // insert and then an update.
2893
+ //
2894
+ // That matters far beyond the wasted write. Position-based pagination has no
2895
+ // guaranteed order unless the source promises one, so a boundary that moves BACKWARD
2896
+ // to re-serve a row has also moved FORWARD past another — the repeat is the visible
2897
+ // half of an omission. The row count then understates the source while the run
2898
+ // reports success, which is the failure mode with no signal attached to it.
2899
+ //
2900
+ // The set is already accumulated here for orphan detection, so this costs one lookup
2901
+ // per record and no extra memory.
2902
+ // TWO PASSES, and the order is the whole correctness of this check.
2903
+ //
2904
+ // Checking and adding in one loop misattributes a batch's OWN duplicate to page
2905
+ // overlap: by the time the second copy is examined, the first has already been added,
2906
+ // so an in-batch repeat looks exactly like a row an earlier page served. Verified —
2907
+ // page 1 [ext-1, ext-2] then page 2 [ext-3, ext-3] reported BOTH a within-batch
2908
+ // collapse and a page overlap, and only one of them was true.
2909
+ //
2910
+ // So pass one asks only about identities from EARLIER batches, while the set still
2911
+ // holds exactly those. Pass two then adds this batch. No copy of the set is taken —
2912
+ // it can hold hundreds of thousands of ids.
2913
+ //
2914
+ // `positionPaged` is also the batch-1 guard: currentOffset/currentPage are only set
2915
+ // from the PREVIOUS batch's NextOffset/NextPage, so both are null on the first batch
2916
+ // by construction and nothing can be a repeat yet.
2917
+ const positionPaged = currentOffset != null || currentPage != null;
2918
+ if (positionPaged) {
2919
+ for (const rec of batch.Records) {
2920
+ if (fetchedExternalIDs.has(rec.ExternalID)) {
2921
+ crossBatchRepeatCount++;
2922
+ if (crossBatchRepeatSamples.length < 5) {
2923
+ crossBatchRepeatSamples.push(String(rec.ExternalID));
2924
+ }
2925
+ }
2926
+ }
2927
+ }
2674
2928
  for (const rec of batch.Records) {
2675
2929
  fetchedExternalIDs.add(rec.ExternalID);
2676
2930
  }
@@ -2762,9 +3016,19 @@ export class IntegrationEngine extends BaseSingleton {
2762
3016
  `${offsetInfo} — running totals: ${result.RecordsCreated} created, ${result.RecordsUpdated} updated, ` +
2763
3017
  `${result.RecordsSkipped} skipped, ${result.RecordsErrored} errored` +
2764
3018
  (batch.HasMore ? ` | more batches pending` : ` | batch complete`));
2765
- // Update progress on the watermark record so the DB reflects live sync state
3019
+ // Update progress on the watermark record so the DB reflects live sync state.
3020
+ //
3021
+ // RecordsSynced counts RECORDS WRITTEN — created + updated — and nothing else. It used
3022
+ // to be handed `afterApply`, which folds in skipped and errored: an object whose rows
3023
+ // were all content-hash-unchanged reported thousands "synced" while writing nothing,
3024
+ // and an object that errored on every record reported the same number as one that
3025
+ // succeeded on every record. Operators watched that counter climb against a physical
3026
+ // row count that never moved (ACR dev, Vendor Payment: 10,400 "synced" against 3,150
3027
+ // rows). Skipped and errored are still counted — on the run result and the run detail,
3028
+ // where they are named as what they are.
2766
3029
  if (batch.HasMore) {
2767
- await this.runWriteForMap(entityMapID, () => this.watermarkService.UpdateProgress(entityMapID, afterApply, contextUser));
3030
+ const writtenSoFar = result.RecordsCreated + result.RecordsUpdated;
3031
+ await this.runWriteForMap(entityMapID, () => this.watermarkService.UpdateProgress(entityMapID, writtenSoFar, contextUser));
2768
3032
  }
2769
3033
  }
2770
3034
  recordsInMap += batch.Records.length;
@@ -2835,6 +3099,52 @@ export class IntegrationEngine extends BaseSingleton {
2835
3099
  }
2836
3100
  hasMore = batch.HasMore === true; // Explicit boolean check — prevents truthy undefined from looping
2837
3101
  }
3102
+ // MJ-RUN-35 — check our work against the number the source gave us.
3103
+ //
3104
+ // The cheapest self-check available, and it was never wired: the source states its own total
3105
+ // on every page (Django REST returns `count`), connectors parsed it, and it had nowhere to
3106
+ // go. Comparing it to what a CLEAN fetch produced turns a silently short scan into a failed
3107
+ // one, on every connector that states a total, without knowing anything about the vendor.
3108
+ //
3109
+ // Only on a clean fetch: one that already skipped pages or aborted is KNOWN to be short and
3110
+ // has said so. Only when a total was actually stated — absent means "it did not say", never
3111
+ // zero. And deliberately not an equality check: a total that moves while we page is normal,
3112
+ // and fetching MORE than claimed is not a fault. Fetching FEWER is.
3113
+ if (fetchCompletedCleanly &&
3114
+ typeof sourceTotalRecords === 'number' &&
3115
+ recordsInMap < sourceTotalRecords) {
3116
+ const missing = sourceTotalRecords - recordsInMap;
3117
+ fetchCompletedCleanly = false;
3118
+ windowHasHole = true;
3119
+ this.markIncomplete(result, entityMap.ExternalObjectName ?? entityMap.ID);
3120
+ logger?.warning(entityMap.ExternalObjectName ?? entityMap.ID, 'FETCH_SHORT_OF_SOURCE_TOTAL', `'${entityMap.ExternalObjectName}': the source reports ${sourceTotalRecords} record(s) and the scan ` +
3121
+ `finished with ${recordsInMap}, so ${missing} were never returned to us. No request failed, which ` +
3122
+ `means the shortfall is in how the source paged rather than in any one response — most often a page ` +
3123
+ `boundary that moved mid-scan. This result set is INCOMPLETE; the watermark is held so the window is ` +
3124
+ `re-fetched next run.`, { sourceTotal: sourceTotalRecords, fetched: recordsInMap, missing, batches: batchCount });
3125
+ }
3126
+ // MJ-RUN-36 — pages that overlapped also skipped, so this result set is INCOMPLETE.
3127
+ //
3128
+ // Reported and marked incomplete rather than logged as a curiosity: the repeat is the only
3129
+ // visible symptom of an invisible omission, and the run would otherwise finish Success with a
3130
+ // row count that understates the source.
3131
+ //
3132
+ // `fetchCompletedCleanly = false` is what withholds every consequence of "we saw the complete
3133
+ // set" — the watermark is held, orphan detection is skipped (rows absent from an incomplete
3134
+ // fetch are not proof they are gone at the source), and the partition rollup is not
3135
+ // overwritten.
3136
+ if (crossBatchRepeatCount > 0) {
3137
+ fetchCompletedCleanly = false;
3138
+ windowHasHole = true;
3139
+ this.markIncomplete(result, entityMap.ExternalObjectName ?? entityMap.ID);
3140
+ logger?.warning(entityMap.ExternalObjectName ?? entityMap.ID, 'FETCH_PAGES_OVERLAPPED', `'${entityMap.ExternalObjectName}': ${crossBatchRepeatCount} record(s) were served again by a later ` +
3141
+ `page after an earlier page had already returned them, so the page boundaries moved during the scan. ` +
3142
+ `A boundary that moves back to repeat a row has also moved forward past another, which means records ` +
3143
+ `were MISSED — this result set is INCOMPLETE and its row count understates the source. The watermark ` +
3144
+ `is held so the window is re-fetched next run. This object needs a guaranteed sort order from the ` +
3145
+ `source, or a page size large enough that the scan fits one page. ` +
3146
+ `Sample: ${crossBatchRepeatSamples.join(', ')}`, { repeated: crossBatchRepeatCount, sample: crossBatchRepeatSamples, batches: batchCount });
3147
+ }
2838
3148
  // Partition (Merkle) reconcile: the full set is now accumulated — diff it against last sync's
2839
3149
  // rollups and deep-apply ONLY the changed/added partitions; the new rollup snapshot is persisted
2840
3150
  // inside. Runs only on a CLEAN fetch (a partial set would mis-skip partitions and lose updates).
@@ -2903,7 +3213,7 @@ export class IntegrationEngine extends BaseSingleton {
2903
3213
  await this.runWriteForMap(entityMapID, () => this.watermarkService.SaveKeysetPosition(entityMapID, currentAfterKey, contextUser));
2904
3214
  result.WatermarkAfter = currentAfterKey;
2905
3215
  }
2906
- else if (!hadFetchGap && currentWatermark && currentWatermark !== initialWatermark) {
3216
+ else if (!hadFetchGap && !windowHasHole && currentWatermark && currentWatermark !== initialWatermark) {
2907
3217
  // A WATERMARK-based connector stopped early (cancel / safety limit / duplicate batch /
2908
3218
  // schema-not-generated / unskippable fetch error) but whole batches DID complete. Persist the
2909
3219
  // max watermark seen so the next run resumes from there instead of re-fetching everything
@@ -2918,7 +3228,10 @@ export class IntegrationEngine extends BaseSingleton {
2918
3228
  // Deliberately NOT wall-clock "now", even for a full sync: coverage is partial, so advancing
2919
3229
  // past the point actually reached would skip the (reached, now] window permanently. And
2920
3230
  // deliberately NOT when hadFetchGap — a skipped page leaves a HOLE behind this watermark,
2921
- // which is why that path holds it for a full re-fetch next run.
3231
+ // which is why that path holds it for a full re-fetch next run. `windowHasHole` is the
3232
+ // same refusal for the two holes that are not skipped pages: a scan that finished short
3233
+ // of the total the source stated, and one whose pages overlapped (and therefore skipped).
3234
+ // In both, records we never received can sit BELOW this value.
2922
3235
  const partialWatermark = currentWatermark;
2923
3236
  await this.runWriteForMap(entityMapID, () => this.watermarkService.Update(entityMapID, partialWatermark, contextUser, 'Pull'));
2924
3237
  result.WatermarkAfter = partialWatermark;
@@ -2941,6 +3254,7 @@ export class IntegrationEngine extends BaseSingleton {
2941
3254
  // operator knows this object's data is INCOMPLETE this run (the per-page warnings carry the
2942
3255
  // offsets). The watermark was held above, so the skipped window is re-fetched on the next run.
2943
3256
  if (hadFetchGap) {
3257
+ this.markIncomplete(result, entityMap.ExternalObjectName ?? entityMap.ID);
2944
3258
  logger?.warning(entityMap.ExternalObjectName ?? entityMap.ID, 'FETCH_INCOMPLETE_PAGES_SKIPPED', `'${entityMap.ExternalObjectName}' finished with one or more pages skipped after persistent fetch errors — ` +
2945
3259
  `the result set is INCOMPLETE. The watermark was held, so the skipped window is re-fetched next run; ` +
2946
3260
  `records on the reachable pages were synced normally.`, { skipped: true });
@@ -2958,6 +3272,20 @@ export class IntegrationEngine extends BaseSingleton {
2958
3272
  })).sort((a, b) => a.Key.localeCompare(b.Key)),
2959
3273
  };
2960
3274
  }
3275
+ // FINALISE the counter. The mid-loop write above is gated on `batch.HasMore`, so it never
3276
+ // fires for the LAST batch — and an object that finishes in a single page has no such batch
3277
+ // at all, which left its RecordsSynced at whatever the previous run wrote (0, for every
3278
+ // object that has only ever completed in one page). partitionReconcile never entered that
3279
+ // branch either, because its writes all happen after the fetch loop. One write per map per
3280
+ // run closes both cases; it runs after the watermark branches above so the row it updates
3281
+ // exists by now.
3282
+ //
3283
+ // Only for a fetch that completed cleanly. UpdateProgress also stamps LastSyncAt, and a map
3284
+ // that was cancelled, failed mid-fetch or ended INCOMPLETE breaks out of the loop rather than
3285
+ // returning — stamping it would show a run that stopped short as freshly synced.
3286
+ if (fetchCompletedCleanly) {
3287
+ await this.runWriteForMap(entityMapID, () => this.watermarkService.UpdateProgress(entityMapID, result.RecordsCreated + result.RecordsUpdated, contextUser));
3288
+ }
2961
3289
  await this.createRunDetail(run, entityMap, result, contextUser);
2962
3290
  return result;
2963
3291
  }
@@ -3000,15 +3328,22 @@ export class IntegrationEngine extends BaseSingleton {
3000
3328
  * IntegrationTailRunEvents) so the pagination-rule violation is visible instead of console-only.
3001
3329
  * Never truncates and never fails the sync — the over-size batch is written in chunks either way.
3002
3330
  */
3003
- warnOversizedBatch(entityMap, batch, batchIndex, logger) {
3331
+ warnOversizedBatch(entityMap, batch, batchIndex, requestedBatchSize, logger) {
3004
3332
  const objectName = entityMap.ExternalObjectName ?? entityMap.ID;
3005
- const verdict = IntegrationEngine.ClassifyOversizedBatch(objectName, batch.Records.length, this.MaxBatchSize, batchIndex, batch.HasMore);
3333
+ // WHAT WAS ASKED FOR ON THIS PAGE, not `this.MaxBatchSize`. The governor may have shed the
3334
+ // run's page size, and the caller decides a batch is over-size against the shed figure.
3335
+ // Classifying against the un-shed ceiling makes the two disagree in exactly the case the
3336
+ // warning exists for: a 2,000 ceiling shed to 500, a connector returning 800, the caller
3337
+ // marking the connector as not honouring the size — and this returning null, so nothing is
3338
+ // ever reported. `oversizeBatchWarned` latches on that first page, so no later page
3339
+ // reports it either.
3340
+ const verdict = IntegrationEngine.ClassifyOversizedBatch(objectName, batch.Records.length, requestedBatchSize, batchIndex, batch.HasMore);
3006
3341
  if (!verdict)
3007
3342
  return;
3008
3343
  logger?.warning(objectName, verdict.Code, verdict.Message, {
3009
3344
  batchIndex,
3010
3345
  recordCount: batch.Records.length,
3011
- requestedBatchSize: this.MaxBatchSize,
3346
+ requestedBatchSize,
3012
3347
  hasMore: batch.HasMore ?? null,
3013
3348
  unbounded: verdict.Unbounded,
3014
3349
  });
@@ -3225,7 +3560,11 @@ export class IntegrationEngine extends BaseSingleton {
3225
3560
  // Paged: an unpaged read is silently capped at the entity's UserViewMaxRows (1000 by
3226
3561
  // default), and a truncated map here makes already-synced records look brand new — so
3227
3562
  // the push would re-CREATE them externally as duplicates.
3228
- const allMaps = await this.loadAllRecordMaps(companyIntegration.ID, entityMap.EntityID, contextUser);
3563
+ // Streamed per page into the lookup this path actually uses (MJ record id → external id)
3564
+ // rather than materialising every row object first — see loadAllRecordMaps' STREAMING note.
3565
+ const existingMaps = new Map();
3566
+ const allMaps = await this.loadAllRecordMaps(companyIntegration.ID, entityMap.EntityID, contextUser, page => { for (const m of page)
3567
+ existingMaps.set(m.EntityRecordID, m.ExternalSystemRecordID); });
3229
3568
  if (!allMaps.Complete) {
3230
3569
  // Refuse rather than push a partial picture: with an incomplete map, every unmapped
3231
3570
  // record reads as "not yet in the external system" and gets created a second time.
@@ -3233,10 +3572,6 @@ export class IntegrationEngine extends BaseSingleton {
3233
3572
  `(${allMaps.Error ?? 'unknown error'}). Refusing to push — an incomplete map would ` +
3234
3573
  `re-create already-synced records as duplicates in the external system.`);
3235
3574
  }
3236
- const existingMaps = new Map();
3237
- for (const m of allMaps.Rows) {
3238
- existingMaps.set(m.EntityRecordID, m.ExternalSystemRecordID);
3239
- }
3240
3575
  const md = this.ProviderToUse;
3241
3576
  const entityInfo = md.EntityByName(entityMap.Entity);
3242
3577
  if (!entityInfo) {
@@ -3278,6 +3613,7 @@ export class IntegrationEngine extends BaseSingleton {
3278
3613
  ExtraFilter: `EntityRecordID='${change.RecordID}' AND CompanyIntegrationID='${config.companyIntegration.ID}'`,
3279
3614
  Fields: ['ExternalSystemRecordID'],
3280
3615
  MaxRows: 1,
3616
+ SkipTotalRowCount: true,
3281
3617
  ResultType: 'simple',
3282
3618
  BypassCache: true, // write-back targets the committed external-id mapping
3283
3619
  }, contextUser);
@@ -3529,17 +3865,26 @@ export class IntegrationEngine extends BaseSingleton {
3529
3865
  // Paged: an unpaged read is silently capped at the entity's UserViewMaxRows (1000 by
3530
3866
  // default). A tenant with 5,000 orphans would clear 1,000 per run and the operator would
3531
3867
  // see a clean run every time — the truncation was invisible, which is the actual bug.
3532
- const allMaps = await this.loadAllRecordMaps(companyIntegration.ID, entityMap.EntityID, contextUser);
3868
+ //
3869
+ // Streamed: the orphan test is per row and needs nothing from the rows that pass it, so each
3870
+ // page is filtered and dropped. What stays resident is the ORPHANS — normally a handful —
3871
+ // instead of every mapping the entity has (see loadAllRecordMaps' STREAMING note).
3872
+ const orphans = [];
3873
+ const allMaps = await this.loadAllRecordMaps(companyIntegration.ID, entityMap.EntityID, contextUser, page => {
3874
+ for (const m of page) {
3875
+ if (!fetchedExternalIDs.has(m.ExternalSystemRecordID))
3876
+ orphans.push(m);
3877
+ }
3878
+ });
3533
3879
  if (!allMaps.Complete) {
3534
3880
  // Deleting against a partial map is the dangerous direction: rows we simply failed to
3535
3881
  // read are indistinguishable from rows the external system dropped. Skip the sweep and
3536
3882
  // say so, rather than archiving live records on incomplete evidence.
3537
3883
  logger?.warning(entityMap.ExternalObjectName ?? entityMap.ID, 'ORPHAN_SWEEP_SKIPPED', `Delete-detection was skipped for ${entityMap.Entity}: the record map could not be read completely ` +
3538
- `(${allMaps.Error ?? 'unknown error'}) after ${allMaps.Rows.length} row(s). No records were deleted. ` +
3539
- `Deleting on a partial map would archive live records.`, { rowsRead: allMaps.Rows.length });
3884
+ `(${allMaps.Error ?? 'unknown error'}) after ${allMaps.RowsRead} row(s). No records were deleted. ` +
3885
+ `Deleting on a partial map would archive live records.`, { rowsRead: allMaps.RowsRead });
3540
3886
  return;
3541
3887
  }
3542
- const orphans = allMaps.Rows.filter(m => !fetchedExternalIDs.has(m.ExternalSystemRecordID));
3543
3888
  if (orphans.length === 0)
3544
3889
  return;
3545
3890
  // The sweep is a DELETE PATH and must answer to the same policy as every other delete.
@@ -4728,6 +5073,14 @@ export class IntegrationEngine extends BaseSingleton {
4728
5073
  // 2x margin defended by nothing is not a guard. Same reasoning as baseEngine's own
4729
5074
  // IgnoreMaxRows use, and this file documents the identical trap on the push side.
4730
5075
  IgnoreMaxRows: true,
5076
+ // L4 — this prefetch runs once per batch and every batch's filter is unique, so the
5077
+ // provider's result cache keeps one entry per batch that is never hit again. Memory
5078
+ // then grows O(records processed) for the lifetime of the run, which is how a
5079
+ // ~500k-record drain killed a 3.8 GB box: the KERNEL oom-killed the process at
5080
+ // ~2.3 GB RSS, twice, BEFORE V8's own ceiling was reached — so no
5081
+ // --max-old-space-size value fixes it and box RAM is the binding constraint.
5082
+ // BypassCache makes the call O(batch), matching LoadAllRecordMaps below.
5083
+ BypassCache: true,
4731
5084
  }, contextUser);
4732
5085
  if (!res.Success)
4733
5086
  return undefined;
@@ -5175,8 +5528,17 @@ export class IntegrationEngine extends BaseSingleton {
5175
5528
  * silently skipping rows while still reporting `Complete: true`. That is exactly the
5176
5529
  * truncation this helper exists to prevent, and the orphan sweep would archive live
5177
5530
  * records on the strength of it. Keyset seeks on the last ID seen and cannot shift.
5531
+ *
5532
+ * **STREAMING, when the caller can use it.** Paging bounds the QUERY, not the resident set: with
5533
+ * every page appended to one array, a table with a million mappings for one (CompanyIntegration,
5534
+ * Entity) pair holds a million row objects in the heap for the length of the sweep — and neither
5535
+ * caller wants the rows. The push path wants a `Map` of two of the three columns; the orphan
5536
+ * sweep wants the handful of rows whose external ID is missing from the fetched set. Pass
5537
+ * `onPage` and each page is handed over and dropped: `Rows` comes back EMPTY and `RowsRead`
5538
+ * carries the count. Omit it and the behaviour is exactly as before (rows accumulated), because
5539
+ * the honest reading of "give me everything" is that the caller intends to hold everything.
5178
5540
  */
5179
- async loadAllRecordMaps(companyIntegrationID, entityID, contextUser) {
5541
+ async loadAllRecordMaps(companyIntegrationID, entityID, contextUser, onPage) {
5180
5542
  const PAGE_SIZE = IntegrationEngine.RecordMapPageSize;
5181
5543
  // Backstop only: at the default page size this is 50M mappings for one
5182
5544
  // (CompanyIntegration, Entity) pair. It exists so a provider that ignores the seek key
@@ -5185,6 +5547,7 @@ export class IntegrationEngine extends BaseSingleton {
5185
5547
  const filter = `CompanyIntegrationID='${companyIntegrationID}' AND EntityID='${entityID}'`;
5186
5548
  const rv = new RunView();
5187
5549
  const rows = [];
5550
+ let rowsRead = 0;
5188
5551
  let afterID;
5189
5552
  for (let pageNo = 0; pageNo < MAX_PAGES; pageNo++) {
5190
5553
  const page = await rv.RunView({
@@ -5203,14 +5566,18 @@ export class IntegrationEngine extends BaseSingleton {
5203
5566
  BypassCache: true, // sync decisions must reflect committed record-map state
5204
5567
  }, contextUser);
5205
5568
  if (!page.Success) {
5206
- return { Rows: rows, Complete: false, Error: page.ErrorMessage ?? 'RunView failed' };
5569
+ return { Rows: rows, RowsRead: rowsRead, Complete: false, Error: page.ErrorMessage ?? 'RunView failed' };
5207
5570
  }
5571
+ rowsRead += page.Results.length;
5572
+ if (onPage)
5573
+ onPage(page.Results);
5208
5574
  // No spread: push(...rows) passes every row as a call argument and throws
5209
5575
  // "Maximum call stack size exceeded" past ~100k rows if a provider returns an oversized page.
5210
- for (const row of page.Results)
5211
- rows.push(row);
5576
+ else
5577
+ for (const row of page.Results)
5578
+ rows.push(row);
5212
5579
  if (page.Results.length < PAGE_SIZE)
5213
- return { Rows: rows, Complete: true };
5580
+ return { Rows: rows, RowsRead: rowsRead, Complete: true };
5214
5581
  afterID = page.Results[page.Results.length - 1].ID;
5215
5582
  }
5216
5583
  // Fell out of the loop with full pages still coming: either a genuinely enormous map or a
@@ -5218,8 +5585,9 @@ export class IntegrationEngine extends BaseSingleton {
5218
5585
  // saying so is the whole point of the Complete flag.
5219
5586
  return {
5220
5587
  Rows: rows,
5588
+ RowsRead: rowsRead,
5221
5589
  Complete: false,
5222
- Error: `Record-map paging exceeded ${MAX_PAGES} pages (${rows.length} rows read) without reaching the end.`,
5590
+ Error: `Record-map paging exceeded ${MAX_PAGES} pages (${rowsRead} rows read) without reaching the end.`,
5223
5591
  };
5224
5592
  }
5225
5593
  /**
@@ -5263,6 +5631,7 @@ export class IntegrationEngine extends BaseSingleton {
5263
5631
  ExtraFilter: `CompanyIntegrationID='${companyIntegrationID}' AND EntityID='${entityID}' AND ExternalSystemRecordID=${quotedExternalID}`,
5264
5632
  Fields: ['ID', 'EntityRecordID'],
5265
5633
  MaxRows: 1,
5634
+ SkipTotalRowCount: true,
5266
5635
  ResultType: 'simple',
5267
5636
  BypassCache: true, // upsert-by-identity: a stale miss here re-creates a duplicate record map
5268
5637
  }, contextUser);
@@ -5285,6 +5654,11 @@ export class IntegrationEngine extends BaseSingleton {
5285
5654
  recordMap.ExternalSystemRecordID = externalID;
5286
5655
  recordMap.EntityID = entityID;
5287
5656
  recordMap.EntityRecordID = entityRecordID;
5657
+ // When a batch's write group is active, the map row travels in it with the entity saves
5658
+ // instead of paying its own round trip and commit. Its key is client-generated by
5659
+ // NewRecord(), so the "primary key exists before Submit" rule in enrolInWriteGroup holds.
5660
+ // Outside a group (every current caller) this is a no-op and the save is immediate.
5661
+ this.enrolInWriteGroup(recordMap);
5288
5662
  const saved = await recordMap.Save();
5289
5663
  if (!saved) {
5290
5664
  throw new Error(`Failed to save record map for external ID ${externalID}: ${recordMap.LatestResult?.CompleteMessage ?? 'unknown error'}`);
@@ -5311,6 +5685,9 @@ export class IntegrationEngine extends BaseSingleton {
5311
5685
  // makes a working sync look like it processed zero maps. Retry transient failures before giving up.
5312
5686
  try {
5313
5687
  await WithRetry(async () => {
5688
+ // Same rule as the record map: inside an active write group it travels with
5689
+ // the batch; outside one (every current caller) it saves immediately.
5690
+ this.enrolInWriteGroup(detail);
5314
5691
  const ok = await detail.Save();
5315
5692
  if (!ok)
5316
5693
  throw new Error(detail.LatestResult?.CompleteMessage ?? 'detail.Save() returned false');
@@ -5326,6 +5703,51 @@ export class IntegrationEngine extends BaseSingleton {
5326
5703
  /**
5327
5704
  * Merges an entity-map-level result into the aggregate result.
5328
5705
  */
5706
+ /**
5707
+ * Warn on the run's own stream when the host is running out of memory or disk, and report
5708
+ * whether memory pressure is present so the caller can shed load.
5709
+ *
5710
+ * plan.md line 158 wants the user told, and the only moment that is useful is BEFORE the
5711
+ * failure. Emitted at an entity-map boundary because that is a natural checkpoint - the
5712
+ * measurement is cheap but not free, and per-record would be absurd.
5713
+ *
5714
+ * The WARNING is once per code per run - repeating it every map would bury the run's real
5715
+ * events, and the condition does not become more true by being restated. The RETURN VALUE is
5716
+ * not: it reports the CURRENT reading every time, because the AIMD cap has to keep being told.
5717
+ * Telling it once would cut concurrency a single step and then ramp straight back up into the
5718
+ * same wall.
5719
+ *
5720
+ * Measured even with no logger. A sync with nowhere to write warnings is still a sync that can
5721
+ * be killed, and the throttle is what keeps it alive.
5722
+ */
5723
+ async warnOnResourcePressure(logger, warned, governorShedding = false) {
5724
+ try {
5725
+ const findings = EvaluatePressure(await ReadResourcePressure());
5726
+ let memoryPressure = false;
5727
+ for (const f of findings) {
5728
+ const isMemory = f.Code === 'HOST_MEMORY_PRESSURE';
5729
+ if (isMemory)
5730
+ memoryPressure = true;
5731
+ if (!logger || warned.has(f.Code))
5732
+ continue;
5733
+ warned.add(f.Code);
5734
+ // Carry what we DID, not only what we saw: a customer watching a sync get slower
5735
+ // should be able to tell that the slowdown and the warning are one event, not two
5736
+ // problems. Deliberately a field on the existing warning rather than a new event
5737
+ // type - SyncLogEvent is a closed union every client matches on.
5738
+ logger.warning('sync', f.Code, f.Message, {
5739
+ fraction: f.Fraction,
5740
+ ...(isMemory && !governorShedding ? { action: 'reduced-concurrency' } : {}),
5741
+ });
5742
+ }
5743
+ return memoryPressure;
5744
+ }
5745
+ catch {
5746
+ // Measuring headroom must never be the thing that ends a sync - and must never be the
5747
+ // thing that throttles it either, so an unreadable measurement reports no pressure.
5748
+ return false;
5749
+ }
5750
+ }
5329
5751
  mergeResult(aggregate, mapResult) {
5330
5752
  aggregate.RecordsProcessed += mapResult.RecordsProcessed;
5331
5753
  aggregate.RecordsCreated += mapResult.RecordsCreated;
@@ -5336,10 +5758,35 @@ export class IntegrationEngine extends BaseSingleton {
5336
5758
  // Bound the retained error SAMPLE: only the first MAX_AGGREGATE_ERRORS are ever persisted
5337
5759
  // (FinalizeRun slices to 100). Accumulating every per-record error across a multi-million-row
5338
5760
  // failing run would hold the whole set in RAM for no gain — RecordsErrored already has the count.
5761
+ // Feed the LIVE snapshot from the same accumulation.
5762
+ //
5763
+ // These four fields existed on the snapshot and on OperationProgressOutput, and the
5764
+ // resolver returned them, but NOTHING ever wrote them — they were initialised to 0 and
5765
+ // stayed 0 for the whole run. That is why the UI showed a bare "+" for created and "~"
5766
+ // for updated with no breakdown: the numbers were always zero, not mis-rendered.
5767
+ //
5768
+ // Here rather than on the progress tick because SyncProgress carries no outcome counts at
5769
+ // all; it only knows position. This is the one place a map's real outcome is folded, and
5770
+ // the aggregate is already monotonic, so the snapshot inherits that for free.
5771
+ const snap = this.currentRunContext?.progressSnapshot;
5772
+ if (snap) {
5773
+ snap.RecordsProcessed = aggregate.RecordsProcessed;
5774
+ snap.RecordsCreated = aggregate.RecordsCreated;
5775
+ snap.RecordsUpdated = aggregate.RecordsUpdated;
5776
+ snap.RecordsErrored = aggregate.RecordsErrored;
5777
+ snap.RecordsSkipped = aggregate.RecordsSkipped;
5778
+ // Persist now as well as on the next tick: the final map has no tick after it, so
5779
+ // without this the run's last counts never reach a reader in another process.
5780
+ void this.currentRunContext?.ownership?.WriteProgress(JSON.stringify(snap));
5781
+ }
5339
5782
  if (aggregate.Errors.length < MAX_AGGREGATE_ERRORS && mapResult.Errors.length > 0) {
5340
5783
  const room = MAX_AGGREGATE_ERRORS - aggregate.Errors.length;
5341
5784
  aggregate.Errors.push(...mapResult.Errors.slice(0, room));
5342
5785
  }
5786
+ // MJ-RUN-4: the per-map result is where an object is marked incomplete, and the run total is
5787
+ // what the completion message reads. Without this the list never left the map that set it.
5788
+ for (const name of mapResult.IncompleteObjects ?? [])
5789
+ this.markIncomplete(aggregate, name);
5343
5790
  if (mapResult.RecordsErrored > 0) {
5344
5791
  aggregate.Success = false;
5345
5792
  }
@@ -5482,18 +5929,18 @@ export class IntegrationEngine extends BaseSingleton {
5482
5929
  if (!detailInfo?.SchemaName || !detailInfo.BaseTable || !ciId)
5483
5930
  return;
5484
5931
  // Cutoff = StartedAt of the Nth-most-recent run for this CI. If there aren't MORE than
5485
- // `keep` runs, there's nothing to prune.
5932
+ // `keep` runs, there's nothing to prune. Reads `keep + 1` rows and counts them.
5486
5933
  const recent = await new RunView().RunView({
5487
5934
  EntityName: runInfo.Name,
5488
5935
  ExtraFilter: `CompanyIntegrationID='${String(ciId).replace(/'/g, "''")}'`,
5489
5936
  OrderBy: 'StartedAt DESC',
5490
5937
  Fields: ['StartedAt'],
5491
- MaxRows: keep,
5938
+ MaxRows: keep + 1,
5492
5939
  ResultType: 'simple',
5493
5940
  }, contextUser);
5494
- if (!recent.Success || (recent.TotalRowCount ?? 0) <= keep)
5941
+ if (!recent.Success || (recent.Results?.length ?? 0) <= keep)
5495
5942
  return;
5496
- const cutoffRaw = recent.Results?.[recent.Results.length - 1]?.StartedAt;
5943
+ const cutoffRaw = recent.Results[keep - 1]?.StartedAt;
5497
5944
  if (!cutoffRaw)
5498
5945
  return;
5499
5946
  const provider = md;
@@ -5686,9 +6133,6 @@ export class IntegrationEngine extends BaseSingleton {
5686
6133
  get EntityMaps() {
5687
6134
  return this.Base.EntityMaps;
5688
6135
  }
5689
- get FieldMaps() {
5690
- return this.Base.FieldMaps;
5691
- }
5692
6136
  get Watermarks() {
5693
6137
  return this.Base.Watermarks;
5694
6138
  }
@@ -5708,8 +6152,8 @@ export class IntegrationEngine extends BaseSingleton {
5708
6152
  GetEntityMapsForCompanyIntegration(companyIntegrationID) {
5709
6153
  return this.Base.GetEntityMapsForCompanyIntegration(companyIntegrationID);
5710
6154
  }
5711
- GetFieldMapsForEntityMap(entityMapID) {
5712
- return this.Base.GetFieldMapsForEntityMap(entityMapID);
6155
+ LoadFieldMapsForEntityMap(entityMapID, contextUser) {
6156
+ return this.Base.LoadFieldMapsForEntityMap(entityMapID, contextUser);
5713
6157
  }
5714
6158
  GetEnabledEntityMaps(companyIntegrationID) {
5715
6159
  return this.Base.GetEnabledEntityMaps(companyIntegrationID);
@@ -5765,4 +6209,25 @@ export class IntegrationEngine extends BaseSingleton {
5765
6209
  return IntegrationEngine.getInstance();
5766
6210
  }
5767
6211
  }
6212
+ /**
6213
+ * The message a finished sync run is finalized with.
6214
+ *
6215
+ * MJ-RUN-4: a run that left objects INCOMPLETE says which, after anything the run already had to
6216
+ * say (an error count, for one), rather than in place of it. A cancelled run keeps its own message.
6217
+ */
6218
+ export function BuildRunCompletionMessage(incomplete, errorMessage, aborted) {
6219
+ if (aborted || incomplete.length === 0)
6220
+ return errorMessage;
6221
+ const names = `${incomplete.slice(0, 10).join(', ')}${incomplete.length > 10 ? ', …' : ''}`;
6222
+ return `${errorMessage ?? 'Sync run complete'} — ${incomplete.length} object(s) INCOMPLETE: ${names}`;
6223
+ }
6224
+ /** What each lever is called in the one sentence a customer reads. */
6225
+ const LEVER_COPY = {
6226
+ HOLD_ADMISSIONS: 'not starting more tables for now',
6227
+ REDUCE_CONCURRENCY: 'syncing fewer tables at once',
6228
+ SHRINK_BATCH: 'reading smaller pages from your source',
6229
+ FLUSH_ACCUMULATOR: 'saving more often',
6230
+ DROP_HASH_PREFETCH: 'skipping an optimisation',
6231
+ PAUSE_OTHER_SYNC: 'pausing another sync'
6232
+ };
5768
6233
  //# sourceMappingURL=IntegrationEngine.js.map