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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/dist/ActionMetadataGenerator.d.ts +45 -0
  2. package/dist/ActionMetadataGenerator.d.ts.map +1 -1
  3. package/dist/ActionMetadataGenerator.js +75 -5
  4. package/dist/ActionMetadataGenerator.js.map +1 -1
  5. package/dist/AdaptiveConcurrency.d.ts +15 -0
  6. package/dist/AdaptiveConcurrency.d.ts.map +1 -1
  7. package/dist/AdaptiveConcurrency.js +21 -0
  8. package/dist/AdaptiveConcurrency.js.map +1 -1
  9. package/dist/BaseIntegrationConnector.d.ts +70 -0
  10. package/dist/BaseIntegrationConnector.d.ts.map +1 -1
  11. package/dist/BaseIntegrationConnector.js +112 -9
  12. package/dist/BaseIntegrationConnector.js.map +1 -1
  13. package/dist/BaseRESTIntegrationConnector.d.ts +2 -2
  14. package/dist/BaseRESTIntegrationConnector.d.ts.map +1 -1
  15. package/dist/BaseRESTIntegrationConnector.js +43 -4
  16. package/dist/BaseRESTIntegrationConnector.js.map +1 -1
  17. package/dist/CatalogScope.d.ts +152 -0
  18. package/dist/CatalogScope.d.ts.map +1 -0
  19. package/dist/CatalogScope.js +399 -0
  20. package/dist/CatalogScope.js.map +1 -0
  21. package/dist/CatalogSource.d.ts +53 -0
  22. package/dist/CatalogSource.d.ts.map +1 -0
  23. package/dist/CatalogSource.js +82 -0
  24. package/dist/CatalogSource.js.map +1 -0
  25. package/dist/CatalogWriter.d.ts +216 -0
  26. package/dist/CatalogWriter.d.ts.map +1 -0
  27. package/dist/CatalogWriter.js +457 -0
  28. package/dist/CatalogWriter.js.map +1 -0
  29. package/dist/CompanyIntegrationCatalogStore.d.ts +109 -0
  30. package/dist/CompanyIntegrationCatalogStore.d.ts.map +1 -0
  31. package/dist/CompanyIntegrationCatalogStore.js +229 -0
  32. package/dist/CompanyIntegrationCatalogStore.js.map +1 -0
  33. package/dist/DeclaredSampleMerge.d.ts +10 -4
  34. package/dist/DeclaredSampleMerge.d.ts.map +1 -1
  35. package/dist/DeclaredSampleMerge.js +17 -6
  36. package/dist/DeclaredSampleMerge.js.map +1 -1
  37. package/dist/DiscoveryWatchdog.d.ts +38 -1
  38. package/dist/DiscoveryWatchdog.d.ts.map +1 -1
  39. package/dist/DiscoveryWatchdog.js +56 -1
  40. package/dist/DiscoveryWatchdog.js.map +1 -1
  41. package/dist/IntegrationActionGenerator.d.ts.map +1 -1
  42. package/dist/IntegrationActionGenerator.js +36 -26
  43. package/dist/IntegrationActionGenerator.js.map +1 -1
  44. package/dist/IntegrationConnectorCreationPipeline.d.ts +181 -4
  45. package/dist/IntegrationConnectorCreationPipeline.d.ts.map +1 -1
  46. package/dist/IntegrationConnectorCreationPipeline.js +646 -68
  47. package/dist/IntegrationConnectorCreationPipeline.js.map +1 -1
  48. package/dist/IntegrationEngine.d.ts +86 -2
  49. package/dist/IntegrationEngine.d.ts.map +1 -1
  50. package/dist/IntegrationEngine.js +760 -209
  51. package/dist/IntegrationEngine.js.map +1 -1
  52. package/dist/IntegrationSchemaSync.d.ts +97 -0
  53. package/dist/IntegrationSchemaSync.d.ts.map +1 -1
  54. package/dist/IntegrationSchemaSync.js +302 -49
  55. package/dist/IntegrationSchemaSync.js.map +1 -1
  56. package/dist/MatchEngine.d.ts.map +1 -1
  57. package/dist/MatchEngine.js +6 -0
  58. package/dist/MatchEngine.js.map +1 -1
  59. package/dist/MemoryGovernor.d.ts +183 -0
  60. package/dist/MemoryGovernor.d.ts.map +1 -0
  61. package/dist/MemoryGovernor.js +225 -0
  62. package/dist/MemoryGovernor.js.map +1 -0
  63. package/dist/ResourcePressure.d.ts +80 -0
  64. package/dist/ResourcePressure.d.ts.map +1 -0
  65. package/dist/ResourcePressure.js +143 -0
  66. package/dist/ResourcePressure.js.map +1 -0
  67. package/dist/RunMemoryControl.d.ts +122 -0
  68. package/dist/RunMemoryControl.d.ts.map +1 -0
  69. package/dist/RunMemoryControl.js +237 -0
  70. package/dist/RunMemoryControl.js.map +1 -0
  71. package/dist/SchemaPersistCounts.d.ts +29 -0
  72. package/dist/SchemaPersistCounts.d.ts.map +1 -0
  73. package/dist/SchemaPersistCounts.js +27 -0
  74. package/dist/SchemaPersistCounts.js.map +1 -0
  75. package/dist/SyncLogger.d.ts +21 -0
  76. package/dist/SyncLogger.d.ts.map +1 -1
  77. package/dist/SyncLogger.js +92 -1
  78. package/dist/SyncLogger.js.map +1 -1
  79. package/dist/WatermarkService.d.ts.map +1 -1
  80. package/dist/WatermarkService.js +1 -0
  81. package/dist/WatermarkService.js.map +1 -1
  82. package/dist/index.d.ts +12 -0
  83. package/dist/index.d.ts.map +1 -1
  84. package/dist/index.js +8 -0
  85. package/dist/index.js.map +1 -1
  86. package/dist/types.d.ts +46 -0
  87. package/dist/types.d.ts.map +1 -1
  88. package/package.json +7 -7
@@ -0,0 +1,225 @@
1
+ /**
2
+ * What to give up, when the machine is filling.
3
+ *
4
+ * A sync holds memory in several places at once, and the cheapest thing to give up is rarely the
5
+ * same twice. `ResourcePressure` answers "are we in trouble"; this answers "what do we give up
6
+ * first", which is a different question and the one that was never asked. The engine's only
7
+ * response to pressure was to halve one number — per-layer concurrency — which frees nothing at
8
+ * all once concurrency is already 1 and a single object is handing back 2,000 records per request.
9
+ * That was the sandbox on 2026-09-14: killed at 3,478 MB of 3,830 MB, twice.
10
+ *
11
+ * THE MODEL. Memory in flight is an inventory of CONTRIBUTORS, each with an estimated size and a
12
+ * set of LEVERS that would shrink it. Choosing is then arithmetic rather than a policy argument:
13
+ * take the lever with the best bytes-freed per unit of throughput surrendered, apply it, measure
14
+ * again, repeat until the projection is under target. Greedy, because the levers are close to
15
+ * independent and an optimal search over them would cost more than it saves.
16
+ *
17
+ * WHY RANKING MATTERS MORE THAN THE THRESHOLD. The same two levers invert between connectors.
18
+ * Shrinking the requested batch size is the best lever that exists on a connector that HONOURS it
19
+ * — it is nearly free, since a smaller page costs one extra round trip and no work. On a connector
20
+ * that ignores it, the identical lever frees exactly zero and spends a round trip to do it. The
21
+ * engine already knows which it is facing, on the first batch, from
22
+ * `IntegrationEngine.ClassifyOversizedBatch`. Feeding that verdict in here is what makes one
23
+ * algorithm correct for both, with no per-connector configuration and no advance knowledge.
24
+ *
25
+ * WHAT CANNOT BE MEASURED, AND WHAT IS DONE ABOUT IT. Node cannot attribute resident memory to one
26
+ * object in a shared heap. So per-contributor cost is MODELLED — records in flight times observed
27
+ * bytes per record — and then CALIBRATED: after shedding, the projected saving is compared against
28
+ * the actual movement in RSS, and the ratio corrects future estimates. Without that step this is a
29
+ * heuristic that sounds principled; with it, a model that is wrong by 3x converges within a few
30
+ * batches. The calibration is deliberately damped and clamped, because RSS also moves for reasons
31
+ * that have nothing to do with us (GC timing, another sync, the OS).
32
+ *
33
+ * Pure. No I/O, no clock, no process access — the caller supplies the reading and the inventory.
34
+ */
35
+ /**
36
+ * Fraction of host memory above which shedding starts, and the fraction it sheds back down TO.
37
+ *
38
+ * Two numbers, not one, on purpose: shedding to exactly the trigger guarantees an immediate
39
+ * re-trigger and a sawtooth that spends its whole life at the edge of a kill. The gap is the
40
+ * hysteresis that lets a sync do some work between decisions.
41
+ *
42
+ * Measured as memory in use on the HOST (see `PressureBytes`). The kernel kills when the host runs
43
+ * out, and a deployment commonly gives V8 most of the box: a heap sized at (RAM - 1 GB) x 0.70 is 65%
44
+ * of a 16 GB machine, which a large workspace fills just by booting (10.2 GB, 72.7%, five minutes after
45
+ * a restart, with nothing running). A trigger at 0.70 made that ordinary state "pressure", and a
46
+ * release line at 0.55 sat below the idle floor, where it could never fire. 0.85 still leaves 15% of
47
+ * RAM for the kernel to hand out; 0.75 is reachable from a normal idle.
48
+ */
49
+ export const SHED_ABOVE_FRACTION = 0.85;
50
+ export const SHED_DOWN_TO_FRACTION = 0.75;
51
+ /**
52
+ * Operator overrides for both thresholds.
53
+ *
54
+ * Two reasons, and the second is the important one.
55
+ *
56
+ * A tenant KNOWN to be tight can be told to start shedding earlier, without waiting for it to fall
57
+ * over first. And a safety mechanism whose only proof is the disaster it exists to prevent is not
58
+ * a tested mechanism: verifying this on a healthy workspace previously required making the
59
+ * workspace unhealthy. Lowering the trigger for one run makes it demonstrable on demand, which is
60
+ * how it should have been provable from the start.
61
+ *
62
+ * Clamped to a sane band and validated as a pair: a trigger at or below the target would shed
63
+ * forever, and a nonsense value silently ignored is worse than one rejected, so both fall back
64
+ * together to the defaults rather than half-applying.
65
+ */
66
+ export function ResolveThresholds(env = process.env) {
67
+ const num = (v) => {
68
+ if (!v)
69
+ return null;
70
+ const n = Number(v);
71
+ return Number.isFinite(n) && n > 0 && n < 1 ? n : null;
72
+ };
73
+ const above = num(env.MJ_INTEGRATION_SHED_ABOVE_FRACTION);
74
+ const downTo = num(env.MJ_INTEGRATION_SHED_DOWN_TO_FRACTION);
75
+ if (above === null && downTo === null) {
76
+ return { ShedAbove: SHED_ABOVE_FRACTION, ShedDownTo: SHED_DOWN_TO_FRACTION };
77
+ }
78
+ const a = above ?? SHED_ABOVE_FRACTION;
79
+ const d = downTo ?? SHED_DOWN_TO_FRACTION;
80
+ // The target must sit BELOW the trigger or every shed re-triggers immediately and the run
81
+ // spends its life at the edge. An inverted pair is a mistake, not an instruction.
82
+ if (d >= a) {
83
+ return { ShedAbove: SHED_ABOVE_FRACTION, ShedDownTo: SHED_DOWN_TO_FRACTION };
84
+ }
85
+ return { ShedAbove: a, ShedDownTo: d };
86
+ }
87
+ /** Calibration is damped and bounded — RSS moves for reasons that are not ours. */
88
+ export const CALIBRATION_DAMPING = 0.3;
89
+ export const CALIBRATION_MIN = 0.25;
90
+ export const CALIBRATION_MAX = 4;
91
+ /**
92
+ * Rank one lever. Higher is better.
93
+ *
94
+ * Bytes per unit of throughput surrendered. A free lever cannot divide by zero and must not be
95
+ * merely "very good" — it has to outrank every costed lever no matter how large that one's saving,
96
+ * because taking a free lever first is never wrong.
97
+ */
98
+ export function ScoreLever(l) {
99
+ if (l.FreesBytes <= 0)
100
+ return -1;
101
+ if (l.ThroughputCost <= 0)
102
+ return Number.POSITIVE_INFINITY;
103
+ return l.FreesBytes / l.ThroughputCost;
104
+ }
105
+ /** Order: best score, then reversible before not, then soonest effect. */
106
+ export function RankLevers(levers) {
107
+ return levers
108
+ .filter(l => l.FreesBytes > 0)
109
+ .slice()
110
+ .sort((a, b) => {
111
+ const d = ScoreLever(b) - ScoreLever(a);
112
+ if (d !== 0 && Number.isFinite(d))
113
+ return d;
114
+ if (ScoreLever(a) !== ScoreLever(b))
115
+ return ScoreLever(b) === Number.POSITIVE_INFINITY ? 1 : -1;
116
+ if (a.Reversible !== b.Reversible)
117
+ return a.Reversible ? -1 : 1;
118
+ return a.LatencyBatches - b.LatencyBatches;
119
+ });
120
+ }
121
+ /**
122
+ * Decide what to give up.
123
+ *
124
+ * Takes levers in ranked order until the calibrated projection reaches the target, and STOPS —
125
+ * over-shedding is its own failure, because every lever surrendered is throughput the customer
126
+ * paid for and a ramp-back that has to be earned again.
127
+ *
128
+ * Returns an empty plan when there is no pressure, and an EXHAUSTED plan when there is pressure
129
+ * and nothing left to give. Exhausted is the honest signal that the workspace is too small for the
130
+ * work — it is not a reason to keep cutting past the point of progress.
131
+ */
132
+ export function PlanShedding(reading, contributors, calibration = 1, shedAbove = SHED_ABOVE_FRACTION, shedDownTo = SHED_DOWN_TO_FRACTION) {
133
+ const total = reading.HostTotalBytes;
134
+ if (!total || total <= 0) {
135
+ // No denominator, no judgement. Guessing here is how a workspace off Linux gets throttled
136
+ // for no reason.
137
+ return { Levers: [], ProjectedFreedBytes: 0, Exhausted: false, Reason: 'host memory unknown' };
138
+ }
139
+ const used = PressureBytes(reading);
140
+ const fraction = used / total;
141
+ if (fraction < shedAbove) {
142
+ return { Levers: [], ProjectedFreedBytes: 0, Exhausted: false, Reason: 'within headroom' };
143
+ }
144
+ const targetBytes = total * shedDownTo;
145
+ const mustFree = used - targetBytes;
146
+ const ranked = RankLevers(contributors.flatMap(c => c.Levers));
147
+ const taken = [];
148
+ let freed = 0;
149
+ for (const lever of ranked) {
150
+ if (freed >= mustFree)
151
+ break;
152
+ taken.push(lever);
153
+ freed += lever.FreesBytes * calibration;
154
+ }
155
+ return {
156
+ Levers: taken,
157
+ ProjectedFreedBytes: freed,
158
+ Exhausted: freed < mustFree,
159
+ Reason: taken.length === 0
160
+ ? 'under pressure with no lever available'
161
+ : `at ${Math.round(fraction * 100)}% of machine memory — shedding ${taken.length} of ${ranked.length} available`
162
+ };
163
+ }
164
+ /**
165
+ * The memory the HOST has in use: total minus MemAvailable.
166
+ *
167
+ * This process's RSS is the wrong number for a decision about the kernel. It counts heap the
168
+ * deployment deliberately gave V8, which V8 fills before it collects, and it leaves out every other
169
+ * process on the box. MemAvailable is what the kernel can still hand out, reclaimable cache
170
+ * included, so it is the number that reaches zero right before a kill. Off Linux there is no
171
+ * MemAvailable, and RSS is the only reading there is.
172
+ */
173
+ export function PressureBytes(reading) {
174
+ const total = reading.HostTotalBytes;
175
+ const available = reading.HostAvailableBytes;
176
+ if (total && total > 0 && available !== null && available >= 0) {
177
+ return Math.max(0, total - available);
178
+ }
179
+ return reading.ResidentBytes;
180
+ }
181
+ /**
182
+ * Correct the model against reality.
183
+ *
184
+ * `actualFreedBytes` is the drop in RSS observed after the plan took effect; negative means memory
185
+ * grew anyway, which happens and must not invert the model. Damped so one noisy sample cannot
186
+ * swing the estimate, and clamped so a pathological reading cannot drive the governor into either
187
+ * doing nothing or shedding everything.
188
+ */
189
+ export function Calibrate(previous, projectedFreedBytes, actualFreedBytes) {
190
+ if (projectedFreedBytes <= 0)
191
+ return previous;
192
+ const observed = Math.max(0, actualFreedBytes) / projectedFreedBytes;
193
+ const next = previous * (1 - CALIBRATION_DAMPING) + observed * CALIBRATION_DAMPING;
194
+ return Math.min(CALIBRATION_MAX, Math.max(CALIBRATION_MIN, next));
195
+ }
196
+ /**
197
+ * The per-object cost model: records held times observed bytes per record.
198
+ *
199
+ * `observedBatchSize` is what the connector ACTUALLY returned, never what was asked for — the gap
200
+ * between the two is the whole reason this exists.
201
+ */
202
+ export function EstimateEntityMapBytes(observedBatchSize, bytesPerRecord) {
203
+ if (observedBatchSize <= 0 || bytesPerRecord <= 0)
204
+ return 0;
205
+ return observedBatchSize * bytesPerRecord;
206
+ }
207
+ /**
208
+ * Build the batch-size lever, which is the one that inverts between connectors.
209
+ *
210
+ * `honoursBatchSize` comes from the engine's own first-batch verdict. When false the lever is
211
+ * still RETURNED, with a zero saving, rather than omitted — so a caller can see that it was
212
+ * considered and rejected on evidence, instead of wondering whether anyone looked.
213
+ */
214
+ export function BatchSizeLever(contributorID, currentBytes, honoursBatchSize) {
215
+ return {
216
+ Code: 'SHRINK_BATCH',
217
+ ContributorID: contributorID,
218
+ FreesBytes: honoursBatchSize ? Math.floor(currentBytes / 2) : 0,
219
+ // Nearly free where it works: one extra round trip per page, no extra work.
220
+ ThroughputCost: 0.05,
221
+ LatencyBatches: 1,
222
+ Reversible: true
223
+ };
224
+ }
225
+ //# sourceMappingURL=MemoryGovernor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MemoryGovernor.js","sourceRoot":"","sources":["../src/MemoryGovernor.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AA4DH;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,IAAI,CAAC;AACxC,MAAM,CAAC,MAAM,qBAAqB,GAAG,IAAI,CAAC;AAE1C;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,iBAAiB,CAAC,MAA0C,OAAO,CAAC,GAAG;IAInF,MAAM,GAAG,GAAG,CAAC,CAAqB,EAAiB,EAAE;QACjD,IAAI,CAAC,CAAC;YAAE,OAAO,IAAI,CAAC;QACpB,MAAM,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;QACpB,OAAO,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,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AAc,EAAE,CAAC;QACjB,UAAU,EAAE,IAAI;KACnB,CAAC;AACN,CAAC"}
@@ -0,0 +1,80 @@
1
+ export interface ResourcePressureReading {
2
+ /** V8 heap in use, bytes. */
3
+ HeapUsedBytes: number;
4
+ /** The ceiling V8 will not grow past — --max-old-space-size, or the platform default. */
5
+ HeapLimitBytes: number;
6
+ /** 0..1. Above ~0.9 a long sync is usually already in trouble. */
7
+ HeapUsedFraction: number;
8
+ /** Resident set: what the CONTAINER sees, which is what an OOM killer acts on. */
9
+ ResidentBytes: number;
10
+ /** Host RAM, total and actually allocatable. Null off Linux or when /proc is unreadable. */
11
+ HostMemTotalBytes: number | null;
12
+ HostMemAvailableBytes: number | null;
13
+ /**
14
+ * Resident set as a fraction of host RAM — the number the OOM killer effectively acts on.
15
+ *
16
+ * This exists because HeapUsedFraction cannot see the memory that actually kills a sync.
17
+ * `--max-old-space-size` bounds V8's OLD SPACE only; `Buffer`/`ArrayBuffer` — where an HTTP
18
+ * response body lives before it is parsed — is external and counted in neither. Proven on the
19
+ * sandbox 2026-09-14: the kernel killed node at 3,478 MB RSS on a 3,830 MB box against a
20
+ * 1,964 MB heap ceiling (1.8x), while heap usage was unremarkable. A throttle watching only
21
+ * the heap reads healthy right up to the kill.
22
+ */
23
+ ResidentFraction: number | null;
24
+ /** Free bytes on the volume holding run artifacts, or null when it cannot be read. */
25
+ ArtifactDiskFreeBytes: number | null;
26
+ ArtifactDiskTotalBytes: number | null;
27
+ /** Free bytes on the volume RSU writes migrations and compiles into. */
28
+ WorkDirFreeBytes: number | null;
29
+ WorkDirTotalBytes: number | null;
30
+ /** Retained run directories, against the retention cap that prunes them. */
31
+ RunDirCount: number | null;
32
+ /** Syncs this process is currently running. */
33
+ ActiveSyncCount: number;
34
+ }
35
+ export declare function ReadResourcePressure(opts?: {
36
+ artifactDir?: string;
37
+ workDir?: string;
38
+ runDirCount?: number | null;
39
+ activeSyncCount?: number;
40
+ }): Promise<ResourcePressureReading>;
41
+ /** Pressure severities, in the order a caller should act on them. */
42
+ export type PressureCode = 'HOST_MEMORY_PRESSURE' | 'HOST_DISK_PRESSURE';
43
+ export interface PressureFinding {
44
+ Code: PressureCode;
45
+ /** Plain enough to show a customer. No paths, no byte counts without units. */
46
+ Message: string;
47
+ /** 0..1 of the relevant ceiling, so a caller can rank findings. */
48
+ Fraction: number;
49
+ }
50
+ /**
51
+ * Default thresholds. Deliberately generous: this fires to WARN, ahead of the failure, and a
52
+ * warning nobody can act on is noise. 0.85 heap leaves room to finish a batch and checkpoint;
53
+ * 500 MB of disk is roughly one large migration plus a compile.
54
+ */
55
+ export declare const HEAP_WARN_FRACTION = 0.85;
56
+ export declare const DISK_WARN_FREE_BYTES: number;
57
+ /**
58
+ * Findings for one reading. The memory line is host RAM in use as a fraction of host RAM, above
59
+ * which a sync is heading for an OOM kill.
60
+ *
61
+ * Lower than the heap threshold on purpose. The heap ceiling is a wall V8 enforces, so 0.85 of it
62
+ * still leaves the process alive to checkpoint. The host has no such wall — crossing it is a
63
+ * SIGKILL with no stack, no run record and no chance to save a watermark, so the warning has to
64
+ * arrive with enough headroom left to actually shed load.
65
+ *
66
+ * It is the governor's line (`SHED_ABOVE_FRACTION`, or the operator override), read at call time
67
+ * from `ResolveThresholds` so the two cannot diverge, and judged on the same reading — memory in
68
+ * use on the host. It used to be 0.70 of this process's RSS, which a workspace whose heap is sized
69
+ * at (RAM - 1 GB) x 0.70 crosses just by booting.
70
+ */
71
+ export declare function EvaluatePressure(r: ResourcePressureReading, heapWarnFraction?: number, diskWarnFreeBytes?: number, residentWarnFraction?: number): PressureFinding[];
72
+ /**
73
+ * Classify a thrown error as running out of disk.
74
+ *
75
+ * Sits beside the DB-contention classifier for the same reason: without it, ENOSPC surfaces as a
76
+ * generic failure and the customer is told the sync failed, not that the disk is full — which is
77
+ * the one thing that would let them fix it.
78
+ */
79
+ export declare function IsOutOfSpaceError(err: unknown): boolean;
80
+ //# sourceMappingURL=ResourcePressure.d.ts.map
@@ -0,0 +1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AAE,MAAM,CAAC;CACpB;AAED;;;;GAIG;AACH,eAAO,MAAM,kBAAkB,OAAO,CAAC;AACvC,eAAO,MAAM,oBAAoB,QAAoB,CAAC;AACtD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,gBAAgB,CAC5B,CAAC,EAAE,uBAAuB,EAC1B,gBAAgB,SAAqB,EACrC,iBAAiB,SAAuB,EACxC,oBAAoB,SAAgC,GACrD,eAAe,EAAE,CAqCnB;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CAKvD"}
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Host resource pressure, measured on the tenant.
3
+ *
4
+ * plan.md line 158 asks what happens "if we run out of storage when we sync, how do we alert the
5
+ * user, OOM (MJC should handle)". The split is deliberate: the TENANT can measure — it is the
6
+ * process that fills the heap and the disk — and the control plane decides what to do about it.
7
+ * Neither half works alone, and today neither exists, so a sync that dies of OOM or ENOSPC does so
8
+ * with no signal anywhere ahead of it.
9
+ *
10
+ * Everything here is a MEASUREMENT. No thresholds are enforced and nothing is refused; callers
11
+ * decide. The only opinion expressed is which numbers matter.
12
+ */
13
+ import { readFile, statfs } from 'node:fs/promises';
14
+ import { join } from 'node:path';
15
+ import v8 from 'node:v8';
16
+ import { PressureBytes, ResolveThresholds } from './MemoryGovernor.js';
17
+ /** Free/total for a path, or nulls when the path is unreadable — never throws. */
18
+ async function volume(path) {
19
+ try {
20
+ const s = await statfs(path);
21
+ // bavail, not bfree: bfree includes blocks reserved for root, which a service account
22
+ // cannot use. Reporting those as free is how a "5% left" reading turns into ENOSPC.
23
+ return { free: s.bsize * Number(s.bavail), total: s.bsize * Number(s.blocks) };
24
+ }
25
+ catch {
26
+ return { free: null, total: null };
27
+ }
28
+ }
29
+ /**
30
+ * Host RAM from /proc/meminfo. MemAvailable, never MemFree: `os.freemem()` returns MemFree on
31
+ * Linux, which excludes reclaimable page cache and therefore reads far tighter than what a
32
+ * process can actually obtain. Returns nulls anywhere /proc is absent — never throws.
33
+ */
34
+ async function hostMemory() {
35
+ try {
36
+ const text = await readFile('/proc/meminfo', 'utf8');
37
+ const kb = (key) => {
38
+ const m = new RegExp(`^${key}:\\s+(\\d+) kB$`, 'm').exec(text);
39
+ return m ? Number(m[1]) * 1024 : null;
40
+ };
41
+ return { total: kb('MemTotal'), available: kb('MemAvailable') };
42
+ }
43
+ catch {
44
+ return { total: null, available: null };
45
+ }
46
+ }
47
+ export async function ReadResourcePressure(opts = {}) {
48
+ const heap = v8.getHeapStatistics();
49
+ const mem = process.memoryUsage();
50
+ const artifactDir = opts.artifactDir ?? join(process.cwd(), 'logs', 'integration-runs');
51
+ const workDir = opts.workDir ?? process.env.RSU_WORK_DIR ?? process.cwd();
52
+ const [art, work, host] = await Promise.all([volume(artifactDir), volume(workDir), hostMemory()]);
53
+ const limit = heap.heap_size_limit;
54
+ return {
55
+ HeapUsedBytes: heap.used_heap_size,
56
+ HeapLimitBytes: limit,
57
+ HeapUsedFraction: limit > 0 ? heap.used_heap_size / limit : 0,
58
+ ResidentBytes: mem.rss,
59
+ HostMemTotalBytes: host.total,
60
+ HostMemAvailableBytes: host.available,
61
+ ResidentFraction: host.total && host.total > 0 ? mem.rss / host.total : null,
62
+ ArtifactDiskFreeBytes: art.free,
63
+ ArtifactDiskTotalBytes: art.total,
64
+ WorkDirFreeBytes: work.free,
65
+ WorkDirTotalBytes: work.total,
66
+ RunDirCount: opts.runDirCount ?? null,
67
+ ActiveSyncCount: opts.activeSyncCount ?? 0,
68
+ };
69
+ }
70
+ /**
71
+ * Default thresholds. Deliberately generous: this fires to WARN, ahead of the failure, and a
72
+ * warning nobody can act on is noise. 0.85 heap leaves room to finish a batch and checkpoint;
73
+ * 500 MB of disk is roughly one large migration plus a compile.
74
+ */
75
+ export const HEAP_WARN_FRACTION = 0.85;
76
+ export const DISK_WARN_FREE_BYTES = 500 * 1024 * 1024;
77
+ /**
78
+ * Findings for one reading. The memory line is host RAM in use as a fraction of host RAM, above
79
+ * which a sync is heading for an OOM kill.
80
+ *
81
+ * Lower than the heap threshold on purpose. The heap ceiling is a wall V8 enforces, so 0.85 of it
82
+ * still leaves the process alive to checkpoint. The host has no such wall — crossing it is a
83
+ * SIGKILL with no stack, no run record and no chance to save a watermark, so the warning has to
84
+ * arrive with enough headroom left to actually shed load.
85
+ *
86
+ * It is the governor's line (`SHED_ABOVE_FRACTION`, or the operator override), read at call time
87
+ * from `ResolveThresholds` so the two cannot diverge, and judged on the same reading — memory in
88
+ * use on the host. It used to be 0.70 of this process's RSS, which a workspace whose heap is sized
89
+ * at (RAM - 1 GB) x 0.70 crosses just by booting.
90
+ */
91
+ export function EvaluatePressure(r, heapWarnFraction = HEAP_WARN_FRACTION, diskWarnFreeBytes = DISK_WARN_FREE_BYTES, residentWarnFraction = ResolveThresholds().ShedAbove) {
92
+ const out = [];
93
+ // Two independent ways to run out of memory, and the RSS one is the one that kills. Report the
94
+ // WORSE of the two under a single code so a caller has one number to act on: heap exhaustion is
95
+ // a V8 abort the process can sometimes survive, while crossing the host's limit is a SIGKILL.
96
+ const heapFrac = r.HeapLimitBytes > 0 ? r.HeapUsedFraction : 0;
97
+ // The governor's reading and line: memory in use on the HOST, not this process's RSS. The engine
98
+ // halves its in-flight cap whenever this fires, after every map, so a second, stricter line here
99
+ // undid what the governor had just released.
100
+ const hostFrac = r.HostMemTotalBytes && r.HostMemTotalBytes > 0
101
+ ? PressureBytes({ ResidentBytes: r.ResidentBytes, HostTotalBytes: r.HostMemTotalBytes, HostAvailableBytes: r.HostMemAvailableBytes }) / r.HostMemTotalBytes
102
+ : (r.ResidentFraction ?? 0);
103
+ const worst = Math.max(heapFrac >= heapWarnFraction ? heapFrac : 0, hostFrac >= residentWarnFraction ? hostFrac : 0);
104
+ if (worst > 0) {
105
+ const hostBound = hostFrac >= residentWarnFraction && hostFrac >= heapFrac;
106
+ out.push({
107
+ Code: 'HOST_MEMORY_PRESSURE',
108
+ Fraction: worst,
109
+ Message: hostBound
110
+ ? `This workspace is using ${Math.round(hostFrac * 100)}% of its machine's memory. Syncing fewer tables at once will help; if it keeps happening on a normal sync, this workspace needs a larger size.`
111
+ : `This workspace is using ${Math.round(heapFrac * 100)}% of the memory available to it. A large sync may not finish; running fewer at once, or a smaller batch size, will help.`,
112
+ });
113
+ }
114
+ // Either volume filling stops a sync: artifacts are the run's own record, and the work dir is
115
+ // where RSU writes a migration and compiles. Report the tighter of the two.
116
+ const disks = [r.ArtifactDiskFreeBytes, r.WorkDirFreeBytes].filter((v) => v !== null);
117
+ if (disks.length > 0) {
118
+ const free = Math.min(...disks);
119
+ if (free <= diskWarnFreeBytes) {
120
+ out.push({
121
+ Code: 'HOST_DISK_PRESSURE',
122
+ Fraction: 1,
123
+ Message: `This workspace has ${Math.max(0, Math.round(free / (1024 * 1024)))} MB of disk left. Syncs and schema updates write to disk and will start failing; older run history can be cleared to recover space.`,
124
+ });
125
+ }
126
+ }
127
+ return out;
128
+ }
129
+ /**
130
+ * Classify a thrown error as running out of disk.
131
+ *
132
+ * Sits beside the DB-contention classifier for the same reason: without it, ENOSPC surfaces as a
133
+ * generic failure and the customer is told the sync failed, not that the disk is full — which is
134
+ * the one thing that would let them fix it.
135
+ */
136
+ export function IsOutOfSpaceError(err) {
137
+ const code = err?.code;
138
+ if (code === 'ENOSPC' || code === 'EDQUOT')
139
+ return true;
140
+ const msg = err instanceof Error ? err.message : String(err ?? '');
141
+ return /ENOSPC|no space left on device|disk quota exceeded/i.test(msg);
142
+ }
143
+ //# sourceMappingURL=ResourcePressure.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ResourcePressure.js","sourceRoot":"","sources":["../src/ResourcePressure.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,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,QAAQ;QAAE,OAAO,IAAI,CAAC;IACxD,MAAM,GAAG,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,IAAI,EAAE,CAAC,CAAC;IACnE,OAAO,qDAAqD,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC3E,CAAC"}
@@ -0,0 +1,122 @@
1
+ import { type SheddingPlan } from './MemoryGovernor.js';
2
+ export interface RunMemoryControlHooks {
3
+ /** Stop the in-flight cap from growing. Free: costs nothing already running. */
4
+ HoldAdmissions(): void;
5
+ /** Halve the in-flight cap, floored at 1. */
6
+ ReduceConcurrency(): void;
7
+ /**
8
+ * How many maps the layer is currently allowed to run at once.
9
+ *
10
+ * Asked rather than passed, because it is the CURRENT cap and the governor itself moves it —
11
+ * a value captured when the batch started would be stale by the time the next decision uses it.
12
+ */
13
+ CurrentInFlight(): number;
14
+ /** Report what was done, once per pressure episode. */
15
+ Report(plan: SheddingPlan): void;
16
+ /** Let the in-flight cap grow again once the host has recovered. Optional: without it the hold stands. */
17
+ ReleaseAdmissions?(): void;
18
+ /** The clock decisions are paced by. `Date.now` when absent; a test supplies its own. */
19
+ Now?(): number;
20
+ }
21
+ /**
22
+ * The smallest page this will ask for.
23
+ *
24
+ * Shrinking without a floor converges on one record per round trip, which frees no more memory
25
+ * than a sane page and turns a sync into a latency test. 25 is small enough to matter and large
26
+ * enough that the request overhead still amortises.
27
+ */
28
+ export declare const MIN_BATCH_SIZE = 25;
29
+ /**
30
+ * The shortest gap between two decisions in one run.
31
+ *
32
+ * Every in-flight map calls NoteBatch after every page, so without a gap one pressure reading was acted
33
+ * on once per map per page: five maps took the in-flight cap to 1 and the page from 200 to 25 within
34
+ * seconds, before the first cut could free anything. One step, then wait long enough for it to show in
35
+ * the reading. The same gap paces the release, one step at a time.
36
+ */
37
+ export declare const DECISION_INTERVAL_MS = 10000;
38
+ /**
39
+ * Bytes per record, from one sample.
40
+ *
41
+ * Deliberately crude: stringify ONE record and double it, because a JS string is UTF-16 in memory
42
+ * and a parsed object carries per-property overhead beyond its serialised form. It will be wrong.
43
+ * That is tolerable only because `Calibrate` measures the error against real RSS movement and
44
+ * corrects it — without that feedback this number would be superstition. Never stringify the whole
45
+ * batch: measuring the memory problem must not become one.
46
+ */
47
+ export declare function EstimateBytesPerRecord(sample: unknown): number;
48
+ export declare class RunMemoryControl {
49
+ private readonly hooks;
50
+ private calibration;
51
+ private pendingProjection;
52
+ private pressureAtDecision;
53
+ private reported;
54
+ private lastDecisionAt;
55
+ /** Whether anything taken is still outstanding — the hold, or a page below the configured size. */
56
+ private shedding;
57
+ private readonly initialBatchSize;
58
+ private batchSize;
59
+ /**
60
+ * The smallest page shrinking may reach.
61
+ *
62
+ * `min` of the default floor and the CONFIGURED size, never `max`. A floor applied to the
63
+ * initial value would silently RAISE a deliberately small batch size — which is a real setting,
64
+ * used by connectors with huge rows and by tests that pin the pagination rule — and raising it
65
+ * would both change fetch behaviour and stop an over-size batch from reading as over-size.
66
+ */
67
+ private readonly floor;
68
+ constructor(hooks: RunMemoryControlHooks, initialBatchSize: number);
69
+ /**
70
+ * The page size this run should ask for, which is NOT the engine's field.
71
+ *
72
+ * Per-run because the engine is a singleton: shrinking a shared field would make one
73
+ * connection's misbehaviour set every other connection's page size for as long as the process
74
+ * lived.
75
+ */
76
+ get BatchSize(): number;
77
+ /** The live calibration factor, for tests and for the run stream. */
78
+ get Calibration(): number;
79
+ /**
80
+ * Whether something this control took is still outstanding — the hold, or a page below the
81
+ * configured size.
82
+ *
83
+ * While it is, this control owns the run's response to memory pressure: it chose its levers
84
+ * by cost and escalates on its own if the host stays above the line. The engine's per-map
85
+ * pressure check defers to it, so a second, unranked halving does not override a hold.
86
+ */
87
+ get IsShedding(): boolean;
88
+ /**
89
+ * Called after every fetched batch.
90
+ *
91
+ * Never throws and never blocks the sync: a governor that can fail a run is worse than no
92
+ * governor, because it turns an occasional memory problem into a constant availability one.
93
+ */
94
+ NoteBatch(opts: {
95
+ EntityMapID: string;
96
+ ObservedRecords: number;
97
+ SampleRecord: unknown;
98
+ HonoursBatchSize: boolean;
99
+ }): Promise<SheddingPlan | null>;
100
+ /**
101
+ * Give back one step of what was taken, once the host is under the release line.
102
+ *
103
+ * Every lever is marked Reversible, and nothing used to reverse any of them: the hold stopped the
104
+ * cap growing for the rest of the run and the page stayed at its floor — 25 records a page for 75
105
+ * minutes while 711 maps never got a slot. Releasing the hold lets the concurrency controller ramp
106
+ * again on clean maps; the page doubles back towards what was configured. Fully restored, the next
107
+ * episode is a new one and is reported again.
108
+ */
109
+ private recover;
110
+ private read;
111
+ /**
112
+ * What is holding memory right now, as best this process can tell.
113
+ *
114
+ * The current map's batch is modelled from the records ACTUALLY returned — the gap between
115
+ * that and what was requested is the whole point. Other in-flight maps are assumed to cost the
116
+ * same, which is wrong in detail and right in aggregate: they are running the same connector
117
+ * against the same-shaped source, and calibration absorbs the rest.
118
+ */
119
+ private inventory;
120
+ private apply;
121
+ }
122
+ //# sourceMappingURL=RunMemoryControl.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RunMemoryControl.d.ts","sourceRoot":"","sources":["../src/RunMemoryControl.ts"],"names":[],"mappings":"AAiBA,OAAO,EAE2B,KAAK,YAAY,EAClD,MAAM,qBAAqB,CAAC;AAE7B,MAAM,WAAW,qBAAqB;IAClC,gFAAgF;IAChF,cAAc,IAAI,IAAI,CAAC;IACvB,6CAA6C;IAC7C,iBAAiB,IAAI,IAAI,CAAC;IAC1B;;;;;OAKG;IACH,eAAe,IAAI,MAAM,CAAC;IAC1B,uDAAuD;IACvD,MAAM,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAAC;IACjC,0GAA0G;IAC1G,iBAAiB,CAAC,IAAI,IAAI,CAAC;IAC3B,yFAAyF;IACzF,GAAG,CAAC,IAAI,MAAM,CAAC;CAClB;AAKD;;;;;;GAMG;AACH,eAAO,MAAM,cAAc,KAAK,CAAC;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