@memberjunction/integration-engine 6.2.0-edge.6 → 6.2.0-edge.8

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