edge-impulse-linux 1.26.1 → 1.26.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -2
- package/build/cli/linux/agent-capture.d.ts +29 -0
- package/build/cli/linux/agent-capture.js +94 -0
- package/build/cli/linux/agent-capture.js.map +1 -0
- package/build/cli/linux/agent-runner-metadata.d.ts +12 -3
- package/build/cli/linux/agent-runner-metadata.js +15 -3
- package/build/cli/linux/agent-runner-metadata.js.map +1 -1
- package/build/cli/linux/audio-utils.d.ts +1 -10
- package/build/cli/linux/audio-utils.js +2 -25
- package/build/cli/linux/audio-utils.js.map +1 -1
- package/build/cli/linux/runner-downloader.js +3 -0
- package/build/cli/linux/runner-downloader.js.map +1 -1
- package/build/cli/linux/runner-utils.js +1 -1
- package/build/cli/linux/runner-utils.js.map +1 -1
- package/build/cli/linux/runner.js +96 -60
- package/build/cli/linux/runner.js.map +1 -1
- package/build/cli-common/model-monitor.d.ts +97 -10
- package/build/cli-common/model-monitor.js +380 -373
- package/build/cli-common/model-monitor.js.map +1 -1
- package/build/cli-common/remote-mgmt-service.d.ts +1 -0
- package/build/cli-common/remote-mgmt-service.js +29 -11
- package/build/cli-common/remote-mgmt-service.js.map +1 -1
- package/build/library/classifier/audio-classifier.d.ts +16 -0
- package/build/library/classifier/audio-classifier.js +77 -1
- package/build/library/classifier/audio-classifier.js.map +1 -1
- package/build/library/classifier/image-classifier.d.ts +14 -0
- package/build/library/classifier/image-classifier.js +79 -3
- package/build/library/classifier/image-classifier.js.map +1 -1
- package/build/library/classifier/linux-impulse-runner.d.ts +8 -1
- package/build/library/classifier/linux-impulse-runner.js +13 -0
- package/build/library/classifier/linux-impulse-runner.js.map +1 -1
- package/build/library/sensors/audio-utils.d.ts +4 -0
- package/build/library/sensors/audio-utils.js +23 -0
- package/build/library/sensors/audio-utils.js.map +1 -0
- package/build/library/sensors/gstreamer.d.ts +1 -1
- package/build/library/sensors/gstreamer.js +7 -4
- package/build/library/sensors/gstreamer.js.map +1 -1
- package/build/sdk/studio/sdk/api/devicesApi.d.ts +2 -2
- package/build/sdk/studio/sdk/api/devicesApi.js +2 -2
- package/build/sdk/studio/sdk/model/additionalMetricOptionalFullPrecisionValue.d.ts +7 -0
- package/build/sdk/studio/sdk/model/additionalMetricOptionalFullPrecisionValue.js +4 -0
- package/build/sdk/studio/sdk/model/additionalMetricOptionalFullPrecisionValue.js.map +1 -0
- package/build/sdk/studio/sdk/model/dSPGroupItem.d.ts +9 -1
- package/build/sdk/studio/sdk/model/dSPGroupItem.js +3 -1
- package/build/sdk/studio/sdk/model/dSPGroupItem.js.map +1 -1
- package/build/sdk/studio/sdk/model/device.d.ts +5 -5
- package/build/sdk/studio/sdk/model/deviceApplication.d.ts +12 -0
- package/build/sdk/studio/sdk/model/{deviceWorkload.js → deviceApplication.js} +1 -1
- package/build/sdk/studio/sdk/model/deviceApplication.js.map +1 -0
- package/build/sdk/studio/sdk/model/{deviceWorkloadModel.d.ts → deviceApplicationModel.d.ts} +2 -2
- package/build/sdk/studio/sdk/model/{deviceWorkloadModel.js → deviceApplicationModel.js} +1 -1
- package/build/sdk/studio/sdk/model/deviceApplicationModel.js.map +1 -0
- package/build/sdk/studio/sdk/model/deviceDeploymentEvent.d.ts +4 -4
- package/build/sdk/studio/sdk/model/deviceModelDeploymentRequest.d.ts +5 -0
- package/build/sdk/studio/sdk/model/foldModelMetadata.d.ts +5 -0
- package/build/sdk/studio/sdk/model/getMonitoringEventDetailsResponse.d.ts +4 -0
- package/build/sdk/studio/sdk/model/getMonitoringEventDetailsResponse.js.map +1 -1
- package/build/sdk/studio/sdk/model/inferenceHistoryAggregate.d.ts +2 -2
- package/build/sdk/studio/sdk/model/kerasModelMetadata.d.ts +5 -0
- package/build/sdk/studio/sdk/model/kerasModelMetadataBase.d.ts +5 -0
- package/build/sdk/studio/sdk/model/kerasModelMetadataResponse.d.ts +5 -0
- package/build/sdk/studio/sdk/model/models.d.ts +3 -2
- package/build/sdk/studio/sdk/model/models.js +3 -2
- package/build/sdk/studio/sdk/model/models.js.map +1 -1
- package/build/sdk/studio/sdk/model/monitoringEventContext.d.ts +6 -2
- package/build/sdk/studio/sdk/model/monitoringInferenceSummary.d.ts +4 -0
- package/build/sdk/studio/sdk/model/userOrganization.d.ts +2 -0
- package/build/shared/viewmodels/init.d.ts +0 -1
- package/build/shared/viewmodels/init.js +0 -1
- package/build/shared/viewmodels/init.js.map +1 -1
- package/package.json +2 -2
- package/test/agent-bundle-lifecycle.test.ts +2 -2
- package/test/agent-bundle.test.ts +104 -0
- package/test/agent-capture.test.ts +528 -0
- package/test/agent-client.test.ts +64 -169
- package/test/agent-command-processor.test.ts +1 -1
- package/test/agent-preview-replacement.test.ts +114 -0
- package/test/agent-runner-configuration.test.ts +12 -3
- package/test/agent-runner-integration.test.ts +50 -8
- package/test/gstreamer.test.ts +1 -1
- package/test/helpers/mock-agent.ts +106 -0
- package/test/model-monitor.test.ts +250 -55
- package/test/monitoring-fixture.ts +168 -0
- package/test/monitoring-policy-protocol.test.ts +193 -1
- package/test/runner-preview.test.ts +59 -0
- package/test/summary-rules-fixtures.test.ts +194 -0
- package/test/utils/agent-runner-fixtures.ts +22 -7
- package/build/sdk/studio/sdk/model/deviceWorkload.d.ts +0 -12
- package/build/sdk/studio/sdk/model/deviceWorkload.js.map +0 -1
- package/build/sdk/studio/sdk/model/deviceWorkloadModel.js.map +0 -1
|
@@ -3,16 +3,19 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.ModelMonitor = exports.hasVisualAd = exports.MIN_MONITOR_SUMMARY_INTERVAL_MS = exports.DEFAULT_MONITOR_SUMMARY_INTERVAL_MS = void 0;
|
|
6
|
+
exports.ModelMonitor = exports.MetricsCalculator = exports.hasVisualAd = exports.MIN_MONITOR_SUMMARY_INTERVAL_MS = exports.DEFAULT_MONITOR_SUMMARY_INTERVAL_MS = void 0;
|
|
7
7
|
const promises_1 = __importDefault(require("fs/promises"));
|
|
8
8
|
const path_1 = __importDefault(require("path"));
|
|
9
9
|
const linux_impulse_runner_types_1 = require("../library/classifier/linux-impulse-runner-types");
|
|
10
10
|
const tsee_1 = require("tsee");
|
|
11
|
-
//
|
|
11
|
+
// Use the conservative cadence until the server confirms that faster summaries can be ingested.
|
|
12
12
|
exports.DEFAULT_MONITOR_SUMMARY_INTERVAL_MS = 60000;
|
|
13
13
|
exports.MIN_MONITOR_SUMMARY_INTERVAL_MS = 5000;
|
|
14
14
|
const MONITOR_PREFIX = '\x1b[34m[MON]\x1b[0m';
|
|
15
|
-
const
|
|
15
|
+
const NO_SUMMARY_POLICY = 'no-policy';
|
|
16
|
+
const CLOCK_BACK_LIMIT_MS = 10000;
|
|
17
|
+
const SUMMARY_CLOSE_RETRY_MS = 1000;
|
|
18
|
+
/** Return whether the path is accessible; inaccessible paths are treated as absent. */
|
|
16
19
|
function checkFileExists(file) {
|
|
17
20
|
return new Promise(resolve => {
|
|
18
21
|
return promises_1.default.access(file, promises_1.default.constants.F_OK)
|
|
@@ -20,6 +23,7 @@ function checkFileExists(file) {
|
|
|
20
23
|
.catch(() => resolve(false));
|
|
21
24
|
});
|
|
22
25
|
}
|
|
26
|
+
/** Limit concurrent iterator calls while collecting their results in input order. */
|
|
23
27
|
async function asyncPool(poolLimit, array, iteratorFn) {
|
|
24
28
|
const ret = [];
|
|
25
29
|
const executing = [];
|
|
@@ -47,20 +51,25 @@ function hasVisualAd(model) {
|
|
|
47
51
|
].includes(model.modelParameters.has_anomaly);
|
|
48
52
|
}
|
|
49
53
|
exports.hasVisualAd = hasVisualAd;
|
|
54
|
+
/**
|
|
55
|
+
* Stores monitoring records by project/deployment. Records use indexed segments;
|
|
56
|
+
* JPEG inputs are separate files, WAV inputs stay inline, and segment cleanup limits record storage.
|
|
57
|
+
*/
|
|
50
58
|
class StorageManager {
|
|
51
59
|
// when the monitor stores the record, storage manager checks if the storage size
|
|
52
60
|
// is above the limit, if it is, it will remove the oldest segment
|
|
53
61
|
// beacues of that feature, it is important to configure segement size and storage limit
|
|
54
62
|
// on a propers level (depending on ther record size and the number of records per second)
|
|
55
63
|
// so there will be more than one segment in the storage
|
|
64
|
+
/** Open the deployment's storage and recover its record bounds and tracked byte usage. */
|
|
56
65
|
static async getStorageManager(conf, model) {
|
|
57
66
|
let storageManager = new StorageManager(conf, model);
|
|
58
67
|
await storageManager.initialize();
|
|
59
68
|
return storageManager;
|
|
60
69
|
}
|
|
70
|
+
/** Retain configuration and model identity; the factory performs asynchronous storage setup. */
|
|
61
71
|
constructor(conf, model) {
|
|
62
72
|
this._storagePath = '';
|
|
63
|
-
this._metricsDir = '';
|
|
64
73
|
this._storageIndex = 0;
|
|
65
74
|
this._isUpdatingStorageIndex = false;
|
|
66
75
|
this._firstIndex = Number.MAX_SAFE_INTEGER;
|
|
@@ -71,6 +80,7 @@ class StorageManager {
|
|
|
71
80
|
this._config = conf;
|
|
72
81
|
this._model = model;
|
|
73
82
|
}
|
|
83
|
+
/** Find record-index bounds from numeric JSON filenames, returning zero bounds when none exist. */
|
|
74
84
|
async getHighestAndLowestIndexes(path) {
|
|
75
85
|
let highest = 0;
|
|
76
86
|
let lowest = Number.MAX_SAFE_INTEGER;
|
|
@@ -95,6 +105,7 @@ class StorageManager {
|
|
|
95
105
|
}
|
|
96
106
|
return { highest, lowest };
|
|
97
107
|
}
|
|
108
|
+
/** Resolve a record's segment directory and create it if needed. */
|
|
98
109
|
async getPathByIndex(index) {
|
|
99
110
|
const segment = Math.floor(index / this._storageIndexSegment);
|
|
100
111
|
const path = path_1.default.join(this._storagePath, segment.toString());
|
|
@@ -103,6 +114,7 @@ class StorageManager {
|
|
|
103
114
|
}
|
|
104
115
|
return path;
|
|
105
116
|
}
|
|
117
|
+
/** Sum file sizes recursively for storage accounting. */
|
|
106
118
|
async getStorageSize(path = this._storagePath) {
|
|
107
119
|
const dirSize = async (dir) => {
|
|
108
120
|
const files = await promises_1.default.readdir(dir, { withFileTypes: true });
|
|
@@ -125,6 +137,7 @@ class StorageManager {
|
|
|
125
137
|
};
|
|
126
138
|
return await dirSize(path);
|
|
127
139
|
}
|
|
140
|
+
/** Select deployment storage, create directories, and recover indexes and usage from disk. */
|
|
128
141
|
async initialize() {
|
|
129
142
|
const modelProjectId = this._model.project.id;
|
|
130
143
|
const deploymentVersion = await this._config.getDeploymentVersion();
|
|
@@ -147,11 +160,6 @@ class StorageManager {
|
|
|
147
160
|
if (storageMaxSizeMb !== undefined) {
|
|
148
161
|
this._storageSizeMaxBytes = storageMaxSizeMb * 1024 * 1024; // convert to bytes
|
|
149
162
|
}
|
|
150
|
-
// set the metrics directory path
|
|
151
|
-
this._metricsDir = path_1.default.join(this._storagePath, 'metrics');
|
|
152
|
-
if (await checkFileExists(this._metricsDir) === false) {
|
|
153
|
-
await promises_1.default.mkdir(this._metricsDir, { recursive: true });
|
|
154
|
-
}
|
|
155
163
|
// get the current storage index (the next index to be used for saving records)
|
|
156
164
|
// storage index may be updated during the initialization if there is a record with higer index
|
|
157
165
|
// we can't overwrite existing records, so we need to start from the next index
|
|
@@ -159,6 +167,9 @@ class StorageManager {
|
|
|
159
167
|
// check if storage directory exists
|
|
160
168
|
if (await checkFileExists(this._storagePath) === false) {
|
|
161
169
|
await promises_1.default.mkdir(this._storagePath, { recursive: true });
|
|
170
|
+
// Empty monitoring storage historically reports zero bounds and allocates record 1 first.
|
|
171
|
+
this._firstIndex = 0;
|
|
172
|
+
this._storageIndex = 1;
|
|
162
173
|
}
|
|
163
174
|
else {
|
|
164
175
|
// if storage exist, then try to restore first and last index
|
|
@@ -195,8 +206,9 @@ class StorageManager {
|
|
|
195
206
|
}
|
|
196
207
|
this._storageSize = await this.getStorageSize();
|
|
197
208
|
}
|
|
198
|
-
|
|
199
|
-
|
|
209
|
+
/**
|
|
210
|
+
* Remove one record segment in the existing storage ordering, retaining at least one segment.
|
|
211
|
+
*/
|
|
200
212
|
async cleanupStorage() {
|
|
201
213
|
// get list of segment directories
|
|
202
214
|
let dirs = await promises_1.default.readdir(this._storagePath, { withFileTypes: true });
|
|
@@ -229,6 +241,7 @@ class StorageManager {
|
|
|
229
241
|
// update the storage size
|
|
230
242
|
this._storageSize -= lowestSegmentSize;
|
|
231
243
|
}
|
|
244
|
+
/** Report retained index bounds and their timestamps for Remote Management's record requests. */
|
|
232
245
|
async getStorageStatus() {
|
|
233
246
|
let temp = await this.getRecord(this._firstIndex);
|
|
234
247
|
const firstTimestamp = temp ? temp.timestamp : 0;
|
|
@@ -241,36 +254,11 @@ class StorageManager {
|
|
|
241
254
|
lastTimestamp: lastTimestamp
|
|
242
255
|
};
|
|
243
256
|
}
|
|
244
|
-
|
|
245
|
-
const metricsPath = path_1.default.join(this._metricsDir, `${fileName}.json`);
|
|
246
|
-
await promises_1.default.writeFile(metricsPath, metricsStr);
|
|
247
|
-
}
|
|
248
|
-
async getLatestInferenceMetrics() {
|
|
249
|
-
try {
|
|
250
|
-
const files = await promises_1.default.readdir(this._metricsDir);
|
|
251
|
-
const metricsFiles = files.filter(file => file.endsWith('.json'));
|
|
252
|
-
if (metricsFiles.length === 0) {
|
|
253
|
-
return undefined;
|
|
254
|
-
}
|
|
255
|
-
// Sort files by the last index in the filename (after the last underscore)
|
|
256
|
-
metricsFiles.sort((a, b) => {
|
|
257
|
-
const indexA = Number(a.replace('.json', '').split('_').pop());
|
|
258
|
-
const indexB = Number(b.replace('.json', '').split('_').pop());
|
|
259
|
-
return indexB - indexA; // Sort in descending order
|
|
260
|
-
});
|
|
261
|
-
const latestFile = metricsFiles[0];
|
|
262
|
-
return await promises_1.default.readFile(path_1.default.join(this._metricsDir, latestFile), 'utf-8');
|
|
263
|
-
}
|
|
264
|
-
catch (error) {
|
|
265
|
-
console.error(MONITOR_PREFIX, 'Error reading metrics files:', error);
|
|
266
|
-
return undefined;
|
|
267
|
-
}
|
|
268
|
-
}
|
|
269
|
-
// we pass raw data separately, so the storage manager can decide how to store it
|
|
270
|
-
// JPEGs are stored in the files on disk, while WAVs are stored in the JSONs (so far)
|
|
257
|
+
/** Allocate an index, persist the record/input, and update usage before applying segment cleanup. */
|
|
271
258
|
async saveRecord(record) {
|
|
272
259
|
let recordSize = 0;
|
|
273
260
|
let rawDataSize = 0;
|
|
261
|
+
let storedRecord = record;
|
|
274
262
|
record.index = this._storageIndex++;
|
|
275
263
|
if (!this._isUpdatingStorageIndex) {
|
|
276
264
|
this._isUpdatingStorageIndex = true;
|
|
@@ -283,9 +271,13 @@ class StorageManager {
|
|
|
283
271
|
const buf = Buffer.from(record.rawData.bufferBase64, 'base64');
|
|
284
272
|
await promises_1.default.writeFile(imgPath, buf);
|
|
285
273
|
rawDataSize = buf.length;
|
|
286
|
-
|
|
274
|
+
// Persist the file reference without replacing the base64 image emitted to live debug clients.
|
|
275
|
+
storedRecord = {
|
|
276
|
+
...record,
|
|
277
|
+
rawData: { ...record.rawData, bufferBase64: imgPath },
|
|
278
|
+
};
|
|
287
279
|
}
|
|
288
|
-
const recordStr = JSON.stringify(
|
|
280
|
+
const recordStr = JSON.stringify(storedRecord, null, 4);
|
|
289
281
|
await promises_1.default.writeFile(recordPath, recordStr, 'utf-8');
|
|
290
282
|
recordSize = recordStr.length;
|
|
291
283
|
this._storageSize += (recordSize + rawDataSize);
|
|
@@ -294,6 +286,7 @@ class StorageManager {
|
|
|
294
286
|
await this.cleanupStorage();
|
|
295
287
|
}
|
|
296
288
|
}
|
|
289
|
+
/** Read a retained record and load its JPEG input into the response; absent records return undefined. */
|
|
297
290
|
async getRecord(index) {
|
|
298
291
|
const recordPath = path_1.default.join(await this.getPathByIndex(index), index.toString() + '.json');
|
|
299
292
|
if (await checkFileExists(recordPath) === false) {
|
|
@@ -318,355 +311,291 @@ class StorageManager {
|
|
|
318
311
|
return record;
|
|
319
312
|
}
|
|
320
313
|
}
|
|
321
|
-
|
|
314
|
+
/** Compare Unicode code points rather than JavaScript's UTF-16 code units or the host locale. */
|
|
315
|
+
function compareSummaryLabels(left, right) {
|
|
316
|
+
const a = Array.from(left, character => character.codePointAt(0));
|
|
317
|
+
const b = Array.from(right, character => character.codePointAt(0));
|
|
318
|
+
for (let index = 0; index < Math.min(a.length, b.length); index++) {
|
|
319
|
+
if (a[index] !== b[index])
|
|
320
|
+
return a[index] - b[index];
|
|
321
|
+
}
|
|
322
|
+
return a.length - b.length;
|
|
323
|
+
}
|
|
324
|
+
/** Incremental mean and population variance for all supplied scores, not just winning predictions. */
|
|
325
|
+
class Moments {
|
|
322
326
|
constructor() {
|
|
323
|
-
this.
|
|
324
|
-
this.
|
|
327
|
+
this.count = 0;
|
|
328
|
+
this.mean = 0;
|
|
329
|
+
this._squares = 0;
|
|
325
330
|
}
|
|
326
|
-
|
|
327
|
-
|
|
331
|
+
/** Incorporate one score using Welford's update without retaining individual observations. */
|
|
332
|
+
add(value) {
|
|
333
|
+
this.count++;
|
|
334
|
+
const delta = value - this.mean;
|
|
335
|
+
this.mean += delta / this.count;
|
|
336
|
+
this._squares += delta * (value - this.mean);
|
|
328
337
|
}
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
}
|
|
333
|
-
// Here we only want to update the mean for the label that was actually
|
|
334
|
-
// predicted (hence, the one >= the threshold, with the highest score).
|
|
335
|
-
// Imagine a model with two classes, A and B, and within some window the model
|
|
336
|
-
// classifies once as A, once as B, with the scores: [ (0.8, 0.2), (0.2, 0.8) ].
|
|
337
|
-
// When looking at the mean for A we should get an answer of 0.8, not 0.5, this is
|
|
338
|
-
// because the question we're answering is "when the model predicts A, how confident
|
|
339
|
-
// is it in its decision?"
|
|
340
|
-
let predictedLabel;
|
|
341
|
-
let predictedScore = 0;
|
|
342
|
-
for (const label of Object.keys(classification)) {
|
|
343
|
-
const score = Number(classification[label]);
|
|
344
|
-
if (score > predictedScore && score >= threshold) {
|
|
345
|
-
predictedScore = score;
|
|
346
|
-
predictedLabel = label;
|
|
347
|
-
}
|
|
348
|
-
}
|
|
349
|
-
if (predictedLabel !== undefined) {
|
|
350
|
-
try {
|
|
351
|
-
this._mean[predictedLabel].count += 1;
|
|
352
|
-
this._mean[predictedLabel].sum += Number(classification[predictedLabel]);
|
|
353
|
-
}
|
|
354
|
-
catch (ex) {
|
|
355
|
-
this._mean[predictedLabel] = { count: 1, sum: Number(classification[predictedLabel]) };
|
|
356
|
-
}
|
|
357
|
-
}
|
|
358
|
-
}
|
|
359
|
-
getMeanByLabel(label) {
|
|
360
|
-
if (this._mean[label] === undefined) {
|
|
361
|
-
return 0;
|
|
362
|
-
}
|
|
363
|
-
return this._mean[label].sum / this._mean[label].count;
|
|
364
|
-
}
|
|
365
|
-
getMetric() {
|
|
366
|
-
let ret = [];
|
|
367
|
-
for (const label in this._mean) {
|
|
368
|
-
if (!this._mean.hasOwnProperty(label)) {
|
|
369
|
-
continue;
|
|
370
|
-
}
|
|
371
|
-
ret.push({ label: label, value: this._mean[label].sum / this._mean[label].count });
|
|
372
|
-
}
|
|
373
|
-
return ret;
|
|
338
|
+
/** Compute population deviation from the accumulated moments; callers require at least one score. */
|
|
339
|
+
get deviation() {
|
|
340
|
+
return Math.sqrt(Math.max(0, this._squares / this.count));
|
|
374
341
|
}
|
|
375
342
|
}
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
343
|
+
/**
|
|
344
|
+
* Accumulates the telemetry statistics for one admitted model and window, independently by result field.
|
|
345
|
+
* Classification statistics include every reported label score, and timing counts actual results.
|
|
346
|
+
* The calculator owns window admission and closure.
|
|
347
|
+
*/
|
|
348
|
+
class InferenceSummaryAccumulator {
|
|
349
|
+
/** Start empty with the model's reported thresholds, without adding runner defaults. */
|
|
350
|
+
constructor(_thresholds) {
|
|
351
|
+
this._thresholds = _thresholds;
|
|
352
|
+
this._labels = new Map();
|
|
353
|
+
this._results = 0;
|
|
354
|
+
this._dsp = 0;
|
|
355
|
+
this._classification = 0;
|
|
356
|
+
this._anomalyTime = 0;
|
|
357
|
+
this._hasAnomalyTime = false;
|
|
358
|
+
this._anomalyScores = new Moments();
|
|
359
|
+
this._visualMeans = new Moments();
|
|
360
|
+
}
|
|
361
|
+
/** Read a numeric parameter from the first block of its type; absent parameters have no fallback. */
|
|
362
|
+
threshold(type, key) {
|
|
363
|
+
// A later block cannot supply a key missing from the first block of this type.
|
|
364
|
+
const value = this._thresholds.find(block => block.type === type)?.[key];
|
|
365
|
+
return typeof value === 'number' ? value : undefined;
|
|
366
|
+
}
|
|
367
|
+
/** Retrieve/create the shared counters and moments for a model or generated label. */
|
|
368
|
+
label(name) {
|
|
369
|
+
const existing = this._labels.get(name);
|
|
370
|
+
if (existing)
|
|
371
|
+
return existing;
|
|
372
|
+
const entry = { counted: 0, scores: new Moments() };
|
|
373
|
+
this._labels.set(name, entry);
|
|
374
|
+
return entry;
|
|
375
|
+
}
|
|
376
|
+
/** Count one prediction or qualifying box for a label. */
|
|
377
|
+
count(name) {
|
|
378
|
+
this.label(name).counted++;
|
|
379
|
+
}
|
|
380
|
+
/** Add a score to a label's mean/deviation independently of whether its prediction counter increments. */
|
|
381
|
+
score(name, value) {
|
|
382
|
+
this.label(name).scores.add(value);
|
|
383
|
+
}
|
|
384
|
+
/** Apply each present result field's summary rule and track result count and index-associated timestamps. */
|
|
385
|
+
add(record) {
|
|
386
|
+
const position = { index: record.index, timestamp: record.timestamp };
|
|
387
|
+
if (!this._first || record.index < this._first.index)
|
|
388
|
+
this._first = position;
|
|
389
|
+
if (!this._last || record.index > this._last.index)
|
|
390
|
+
this._last = position;
|
|
391
|
+
this._results++;
|
|
392
|
+
const { result, timing } = record.impulseRecord;
|
|
393
|
+
this._dsp += timing.dsp;
|
|
394
|
+
this._classification += timing.classification;
|
|
395
|
+
this._anomalyTime += timing.anomaly;
|
|
396
|
+
const classifications = Object.entries(result.classification ?? {});
|
|
397
|
+
const top = classifications.reduce((best, candidate) => {
|
|
398
|
+
if (!best || candidate[1] > best[1] ||
|
|
399
|
+
(candidate[1] === best[1] && compareSummaryLabels(candidate[0], best[0]) < 0))
|
|
400
|
+
return candidate;
|
|
401
|
+
return best;
|
|
402
|
+
}, undefined);
|
|
403
|
+
if (top) {
|
|
404
|
+
const threshold = this.threshold('classification', 'min_score');
|
|
405
|
+
this.count(threshold !== undefined && top[1] < threshold ? 'no prediction' : top[0]);
|
|
406
|
+
for (const [label, value] of classifications)
|
|
407
|
+
this.score(label, value);
|
|
408
|
+
}
|
|
409
|
+
const detectionThreshold = this.threshold('object_detection', 'min_score');
|
|
410
|
+
for (const box of result.bounding_boxes ?? []) {
|
|
411
|
+
if (detectionThreshold === undefined || box.value > detectionThreshold) {
|
|
412
|
+
this.count(box.label);
|
|
413
|
+
this.score(box.label, box.value);
|
|
400
414
|
}
|
|
401
415
|
}
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
this._stdDev[predictedLabel].mean += delta / this._stdDev[predictedLabel].count;
|
|
408
|
-
const delta2 = x - this._stdDev[predictedLabel].mean;
|
|
409
|
-
this._stdDev[predictedLabel].m2 += delta * delta2;
|
|
410
|
-
}
|
|
411
|
-
catch (ex) {
|
|
412
|
-
this._stdDev[predictedLabel] = { count: 1, m2: 0, mean: Number(classification[predictedLabel]) };
|
|
416
|
+
const anomalyThreshold = this.threshold('anomaly_gmm', 'min_anomaly_score');
|
|
417
|
+
if (result.visual_anomaly_max !== undefined) {
|
|
418
|
+
this._hasAnomalyTime = true;
|
|
419
|
+
if (anomalyThreshold !== undefined) {
|
|
420
|
+
this.count(result.visual_anomaly_max > anomalyThreshold ? 'anomaly' : 'no anomaly');
|
|
413
421
|
}
|
|
422
|
+
this.score('anomaly', result.visual_anomaly_max);
|
|
414
423
|
}
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
424
|
+
else if (result.anomaly !== undefined) {
|
|
425
|
+
this._hasAnomalyTime = true;
|
|
426
|
+
this._anomalyScores.add(result.anomaly);
|
|
427
|
+
if (anomalyThreshold !== undefined) {
|
|
428
|
+
this._anomalyCount = (this._anomalyCount ?? 0) + (result.anomaly > anomalyThreshold ? 1 : 0);
|
|
429
|
+
}
|
|
419
430
|
}
|
|
420
|
-
|
|
431
|
+
if (result.visual_anomaly_mean !== undefined)
|
|
432
|
+
this._visualMeans.add(result.visual_anomaly_mean);
|
|
421
433
|
}
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
434
|
+
/**
|
|
435
|
+
* Build a tagged, code-point-ordered snapshot; omit non-finite statistics
|
|
436
|
+
* and suppress empty/invalid timing output.
|
|
437
|
+
*/
|
|
438
|
+
getMetrics() {
|
|
439
|
+
if (!this._first || !this._last)
|
|
440
|
+
return undefined;
|
|
441
|
+
const dsp = this._dsp / this._results;
|
|
442
|
+
const classification = this._classification / this._results;
|
|
443
|
+
if (!Number.isFinite(dsp) || !Number.isFinite(classification))
|
|
444
|
+
return undefined;
|
|
445
|
+
const labels = [...this._labels].sort(([left], [right]) => compareSummaryLabels(left, right));
|
|
446
|
+
const scored = labels.filter(([, label]) => label.scores.count > 0 &&
|
|
447
|
+
Number.isFinite(label.scores.mean) && Number.isFinite(label.scores.deviation));
|
|
448
|
+
const metrics = { avg_inference_time: { dsp, classification } };
|
|
449
|
+
const anomalyTime = this._anomalyTime / this._results;
|
|
450
|
+
if (this._hasAnomalyTime && Number.isFinite(anomalyTime))
|
|
451
|
+
metrics.avg_inference_time.anomaly = anomalyTime;
|
|
452
|
+
if (this._anomalyScores.count && Number.isFinite(this._anomalyScores.mean)) {
|
|
453
|
+
metrics.anomaly_mean = this._anomalyScores.mean;
|
|
454
|
+
}
|
|
455
|
+
if (this._anomalyCount !== undefined)
|
|
456
|
+
metrics.anomaly_count = this._anomalyCount;
|
|
457
|
+
if (this._visualMeans.count && Number.isFinite(this._visualMeans.mean)) {
|
|
458
|
+
metrics.visual_anomaly_mean = this._visualMeans.mean;
|
|
427
459
|
}
|
|
428
|
-
return
|
|
460
|
+
return {
|
|
461
|
+
rulesVersion: 2,
|
|
462
|
+
start: { ...this._first }, end: { ...this._last },
|
|
463
|
+
classificationCounter: labels.filter(([, label]) => label.counted > 0)
|
|
464
|
+
.map(([label, value]) => ({ label, value: value.counted })),
|
|
465
|
+
mean: scored.map(([label, value]) => ({ label, value: value.scores.mean })),
|
|
466
|
+
standardDeviation: scored.map(([label, value]) => ({ label, value: value.scores.deviation })),
|
|
467
|
+
metrics,
|
|
468
|
+
};
|
|
429
469
|
}
|
|
430
470
|
}
|
|
471
|
+
/**
|
|
472
|
+
* Computes inference summaries from the model's original thresholds. Half-open windows close
|
|
473
|
+
* before a boundary result or on a timer; late results are dropped, and empty windows produce no summary.
|
|
474
|
+
*/
|
|
431
475
|
class MetricsCalculator {
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
476
|
+
/** Prepare a fresh accumulator for one deployment and retain its configured and effective cadence. */
|
|
477
|
+
constructor(_model, cadence) {
|
|
478
|
+
this._model = _model;
|
|
479
|
+
this._summaryWindowMs = cadence.summaryWindowMs;
|
|
480
|
+
this.configuredSummaryIntervalMs = cadence.configuredSummaryIntervalMs;
|
|
481
|
+
this._accumulator = this.createAccumulator();
|
|
482
|
+
}
|
|
483
|
+
/** Read the saved preference and create a fresh calculator for this monitoring session. */
|
|
484
|
+
static async getMetricsInstance(config, model) {
|
|
435
485
|
const savedInterval = await config.getMonitorSummaryIntervalMs();
|
|
436
486
|
const configuredInterval = savedInterval && Number.isFinite(savedInterval) && savedInterval > 0 ?
|
|
437
487
|
savedInterval : undefined;
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
488
|
+
return new MetricsCalculator(model, {
|
|
489
|
+
summaryWindowMs: Math.max(configuredInterval ?? exports.DEFAULT_MONITOR_SUMMARY_INTERVAL_MS, exports.DEFAULT_MONITOR_SUMMARY_INTERVAL_MS),
|
|
490
|
+
configuredSummaryIntervalMs: configuredInterval,
|
|
491
|
+
});
|
|
442
492
|
}
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
this.
|
|
450
|
-
dsp: 0,
|
|
451
|
-
classification: 0,
|
|
452
|
-
anomaly: 0,
|
|
453
|
-
};
|
|
454
|
-
this._visualAnomalyMean = 0;
|
|
455
|
-
this._storageManager = storage;
|
|
456
|
-
this._model = model;
|
|
457
|
-
this._summaryWindowMs = summaryWindowMs;
|
|
458
|
-
this.configuredSummaryIntervalMs = configuredSummaryIntervalMs;
|
|
459
|
-
let threshold;
|
|
460
|
-
if (hasVisualAd(model)) {
|
|
461
|
-
const thresholdObj = (model.modelParameters.thresholds || []).find(x => x.type === 'anomaly_gmm');
|
|
462
|
-
if (thresholdObj && thresholdObj.type === 'anomaly_gmm') {
|
|
463
|
-
if (typeof thresholdObj.min_anomaly_score === 'number') {
|
|
464
|
-
threshold = thresholdObj.min_anomaly_score;
|
|
465
|
-
this._confidenceThresholds.set('min_anomaly_score', threshold);
|
|
466
|
-
}
|
|
467
|
-
}
|
|
468
|
-
}
|
|
469
|
-
// An impulse might have both visual AD and classifier/object detection, but classification and object detection
|
|
470
|
-
// are mutually exclusive, so we check them in an if-else statement
|
|
471
|
-
if (model.modelParameters.model_type === 'constrained_object_detection' ||
|
|
472
|
-
model.modelParameters.model_type === 'object_detection') {
|
|
473
|
-
const thresholdObj = (model.modelParameters.thresholds || []).find(x => x.type === 'object_detection');
|
|
474
|
-
if (thresholdObj && thresholdObj.type === 'object_detection') {
|
|
475
|
-
if (typeof thresholdObj.min_score === 'number') {
|
|
476
|
-
threshold = thresholdObj.min_score;
|
|
477
|
-
this._confidenceThresholds.set('min_score', threshold);
|
|
478
|
-
}
|
|
479
|
-
}
|
|
480
|
-
}
|
|
481
|
-
else if (model.modelParameters.model_type === 'classification') {
|
|
482
|
-
const thresholdObj = (model.modelParameters.thresholds || []).find(x => x.type === 'classification');
|
|
483
|
-
if (thresholdObj && thresholdObj.type === 'classification') {
|
|
484
|
-
if (typeof thresholdObj.min_score === 'number') {
|
|
485
|
-
threshold = thresholdObj.min_score;
|
|
486
|
-
this._confidenceThresholds.set('min_score', threshold);
|
|
487
|
-
}
|
|
488
|
-
}
|
|
489
|
-
}
|
|
490
|
-
if (this._confidenceThresholds.size === 0) {
|
|
491
|
-
console.warn(MONITOR_PREFIX, `Model threshold is not defined, using default value of ${DEFAULT_THRESHOLD}`);
|
|
492
|
-
}
|
|
493
|
-
this._meanCalculator = new MeanCalculator();
|
|
494
|
-
this._stdDevCalculator = new StdDevCalculator();
|
|
495
|
-
// init as empty, will be overwritten by restoreMetrics
|
|
496
|
-
this._metrics = {
|
|
497
|
-
start: { index: 0, timestamp: 0 },
|
|
498
|
-
end: { index: 0, timestamp: 0 },
|
|
499
|
-
classificationCounter: [],
|
|
500
|
-
mean: [],
|
|
501
|
-
standardDeviation: [],
|
|
502
|
-
metrics: {},
|
|
503
|
-
};
|
|
493
|
+
/** Create empty statistics using this deployment's original thresholds, never mutable runner settings. */
|
|
494
|
+
createAccumulator() {
|
|
495
|
+
return new InferenceSummaryAccumulator(this._model.reportedThresholds);
|
|
496
|
+
}
|
|
497
|
+
/** Expose the current half-open window's end, or undefined when no window has results. */
|
|
498
|
+
get summaryDeadline() {
|
|
499
|
+
return this._windowEnd;
|
|
504
500
|
}
|
|
501
|
+
/** Expose the policy-adjusted reporting interval. */
|
|
505
502
|
get summaryIntervalMs() {
|
|
506
503
|
return this._summaryWindowMs;
|
|
507
504
|
}
|
|
505
|
+
/** Update cadence while keeping the open window's end strictly after every already-admitted timestamp. */
|
|
508
506
|
setSummaryIntervalMs(intervalMs) {
|
|
509
|
-
// Preserve the in-flight aggregate. The next inference closes it if the shorter deadline is due;
|
|
510
|
-
// speeding up cannot manufacture historical summaries or duplicate the records already included.
|
|
511
507
|
this._summaryWindowMs = intervalMs;
|
|
508
|
+
// Preserve results already admitted beyond a shortened deadline. Subsequent windows use
|
|
509
|
+
// the new interval without manufacturing historical summaries.
|
|
510
|
+
if (this._windowStart !== undefined) {
|
|
511
|
+
this._windowEnd = Math.max(this._windowStart + intervalMs, this._latestTimestamp + 1);
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
/** Finish any valid snapshot before resetting statistics and advancing the late-result cutoff. */
|
|
515
|
+
async closeWindow(endTimestamp) {
|
|
516
|
+
const metrics = this._accumulator.getMetrics();
|
|
517
|
+
this._accumulator = this.createAccumulator();
|
|
518
|
+
this._windowStart = undefined;
|
|
519
|
+
this._windowEnd = undefined;
|
|
520
|
+
this._latestTimestamp = undefined;
|
|
521
|
+
this._closedThrough = endTimestamp;
|
|
522
|
+
return metrics;
|
|
512
523
|
}
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
this.
|
|
516
|
-
|
|
517
|
-
start: { index: this._windowStartIndex, timestamp: this._windowStartTimestamp },
|
|
518
|
-
end: { index: this._windowStartIndex, timestamp: this._windowStartTimestamp },
|
|
519
|
-
classificationCounter: [],
|
|
520
|
-
mean: [],
|
|
521
|
-
standardDeviation: [],
|
|
522
|
-
metrics: {},
|
|
523
|
-
};
|
|
524
|
-
this._totalInferenceTime = {
|
|
525
|
-
dsp: 0,
|
|
526
|
-
classification: 0,
|
|
527
|
-
anomaly: 0,
|
|
528
|
-
};
|
|
529
|
-
this._visualAnomalyMean = 0;
|
|
524
|
+
/** Return whether wall time moved far enough behind known windows that the existing grid is unusable. */
|
|
525
|
+
clockMovedBack(timestamp) {
|
|
526
|
+
const known = Math.max(this._closedThrough ?? Number.NEGATIVE_INFINITY, this._windowStart ?? Number.NEGATIVE_INFINITY);
|
|
527
|
+
return Number.isFinite(known) && timestamp + CLOCK_BACK_LIMIT_MS < known;
|
|
530
528
|
}
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
this._windowStartIndex = record.index;
|
|
537
|
-
this._windowStartTimestamp = record.timestamp;
|
|
538
|
-
this.resetMetrics();
|
|
539
|
-
}
|
|
540
|
-
const incrementClassificationCounter = (key) => {
|
|
541
|
-
// find key index in classificationCounter
|
|
542
|
-
const index = this._metrics.classificationCounter.findIndex((element) => element.label === key);
|
|
543
|
-
if (index < 0) {
|
|
544
|
-
this._metrics.classificationCounter.push({ label: key, value: 1 });
|
|
545
|
-
}
|
|
546
|
-
else {
|
|
547
|
-
this._metrics.classificationCounter[index].value++;
|
|
548
|
-
}
|
|
549
|
-
};
|
|
550
|
-
if (hasVisualAd(this._model) && record.impulseRecord.result.visual_anomaly_max !== undefined) {
|
|
551
|
-
const minAnomalyScore = this._confidenceThresholds.get('min_anomaly_score') ?? DEFAULT_THRESHOLD;
|
|
552
|
-
const isAnomaly = record.impulseRecord.result.visual_anomaly_max > minAnomalyScore;
|
|
553
|
-
const predictedLabel = isAnomaly ? 'anomaly' : 'no anomaly';
|
|
554
|
-
incrementClassificationCounter(predictedLabel);
|
|
555
|
-
const classifications = { [predictedLabel]: record.impulseRecord.result.visual_anomaly_max };
|
|
556
|
-
// update mean and stdev partial values
|
|
557
|
-
this._meanCalculator.update(classifications, minAnomalyScore);
|
|
558
|
-
this._stdDevCalculator.update(classifications, minAnomalyScore);
|
|
559
|
-
}
|
|
560
|
-
// check if property classification exists in record.impulseRecord.result
|
|
561
|
-
if (record.impulseRecord.result.classification !== undefined) {
|
|
562
|
-
const minScore = this._confidenceThresholds.get('min_score') ?? DEFAULT_THRESHOLD;
|
|
563
|
-
// iterate over properites in impulseRecord.result.classification
|
|
564
|
-
for (const key in record.impulseRecord.result.classification) {
|
|
565
|
-
if (!record.impulseRecord.result.classification.hasOwnProperty(key)) {
|
|
566
|
-
continue;
|
|
567
|
-
}
|
|
568
|
-
// check if value is above threshold
|
|
569
|
-
if (Number(record.impulseRecord.result.classification[key]) > minScore) {
|
|
570
|
-
incrementClassificationCounter(key);
|
|
571
|
-
}
|
|
572
|
-
}
|
|
573
|
-
// update mean and stdev partial values
|
|
574
|
-
this._meanCalculator.update(record.impulseRecord.result.classification, minScore);
|
|
575
|
-
this._stdDevCalculator.update(record.impulseRecord.result.classification, minScore);
|
|
576
|
-
}
|
|
577
|
-
if (record.impulseRecord.result.bounding_boxes !== undefined) {
|
|
578
|
-
const minScore = this._confidenceThresholds.get('min_score') ?? DEFAULT_THRESHOLD;
|
|
579
|
-
// iterate over list of bounding boxes
|
|
580
|
-
for (const box of record.impulseRecord.result.bounding_boxes) {
|
|
581
|
-
// check if value is above threshold
|
|
582
|
-
if (box.value > minScore) {
|
|
583
|
-
incrementClassificationCounter(box.label);
|
|
584
|
-
}
|
|
585
|
-
}
|
|
586
|
-
// Convert bounding boxes to a classification data object, i.e go from
|
|
587
|
-
// [{ label: 'cat', value: 0.9, x: 40, y: 50, ... }, { label: 'dog', value: 0.8, x: 10, y: 20, ... }] to
|
|
588
|
-
// { cat: 0.9, dog: 0.8 }, so we can use it for mean and stdev calculations
|
|
589
|
-
const classificationData = record.impulseRecord.result.bounding_boxes.reduce((acc, { label, value }) => {
|
|
590
|
-
acc[label] = value;
|
|
591
|
-
return acc;
|
|
592
|
-
}, {});
|
|
593
|
-
// update mean and stdev partial values
|
|
594
|
-
this._meanCalculator.update(classificationData, minScore);
|
|
595
|
-
this._stdDevCalculator.update(classificationData, minScore);
|
|
596
|
-
}
|
|
597
|
-
// Calculate average inference time, if timing information is present
|
|
598
|
-
if (record.impulseRecord.timing) {
|
|
599
|
-
this._totalInferenceTime.dsp += record.impulseRecord.timing.dsp;
|
|
600
|
-
this._totalInferenceTime.classification += record.impulseRecord.timing.classification;
|
|
601
|
-
this._totalInferenceTime.anomaly += record.impulseRecord.timing.anomaly;
|
|
602
|
-
}
|
|
603
|
-
// Only calculate mean visual anomaly score if relevant
|
|
604
|
-
if (hasVisualAd(this._model) && record.impulseRecord.result.visual_anomaly_mean) {
|
|
605
|
-
this._visualAnomalyMean += record.impulseRecord.result.visual_anomaly_mean;
|
|
606
|
-
}
|
|
607
|
-
// update the end boundary
|
|
608
|
-
this._metrics.end = { index: record.index, timestamp: record.timestamp };
|
|
609
|
-
// Check if the time window has elapsed
|
|
610
|
-
if ((record.timestamp - this._windowStartTimestamp) >= this._summaryWindowMs) {
|
|
611
|
-
// Save metrics and reset window
|
|
612
|
-
await this.saveMetrics();
|
|
613
|
-
this._windowStartTimestamp = 0;
|
|
614
|
-
return true;
|
|
615
|
-
}
|
|
616
|
-
return false;
|
|
529
|
+
/** Close the current window, if any, and forget the future grid after a backward clock correction. */
|
|
530
|
+
async resetAfterClockCorrection() {
|
|
531
|
+
const metrics = this._windowStart === undefined ? undefined : await this.closeWindow(this.summaryDeadline);
|
|
532
|
+
this._closedThrough = undefined;
|
|
533
|
+
return metrics;
|
|
617
534
|
}
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
this._metrics.metrics.avg_inference_time = {
|
|
627
|
-
dsp: this._totalInferenceTime.dsp / numberOfInferences,
|
|
628
|
-
classification: this._totalInferenceTime.classification / numberOfInferences,
|
|
629
|
-
anomaly: this._totalInferenceTime.anomaly / numberOfInferences,
|
|
630
|
-
};
|
|
631
|
-
}
|
|
632
|
-
else {
|
|
633
|
-
this._metrics.metrics.avg_inference_time = {
|
|
634
|
-
dsp: this._totalInferenceTime.dsp / numberOfInferences,
|
|
635
|
-
classification: this._totalInferenceTime.classification / numberOfInferences,
|
|
636
|
-
};
|
|
637
|
-
}
|
|
638
|
-
// Only include visual_anomaly_mean if visual anomaly is relevant
|
|
639
|
-
if (hasVisualAd(this._model)) {
|
|
640
|
-
this._metrics.metrics.visual_anomaly_mean = this._visualAnomalyMean / numberOfInferences;
|
|
641
|
-
}
|
|
642
|
-
else {
|
|
643
|
-
delete this._metrics.metrics.visual_anomaly_mean;
|
|
644
|
-
}
|
|
645
|
-
return this._metrics;
|
|
535
|
+
/** Close an elapsed window, or reset a stale future window after wall time moves backwards. */
|
|
536
|
+
async closeDueWindow(timestamp) {
|
|
537
|
+
if (this.clockMovedBack(timestamp))
|
|
538
|
+
return this.resetAfterClockCorrection();
|
|
539
|
+
const deadline = this.summaryDeadline;
|
|
540
|
+
if (deadline === undefined || timestamp < deadline)
|
|
541
|
+
return undefined;
|
|
542
|
+
return this.closeWindow(deadline);
|
|
646
543
|
}
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
544
|
+
/** Close pending results once at a partial-window cutoff; leave empty windows unreported. */
|
|
545
|
+
async flushMetrics() {
|
|
546
|
+
if (this._windowStart === undefined)
|
|
547
|
+
return undefined;
|
|
548
|
+
return this.closeWindow(Math.max(this._latestTimestamp + 1, Math.min(Date.now(), this.summaryDeadline)));
|
|
652
549
|
}
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
this.
|
|
661
|
-
|
|
550
|
+
/**
|
|
551
|
+
* Reject late records, close a due window before admission,
|
|
552
|
+
* and expose its summary separately from the new window.
|
|
553
|
+
*/
|
|
554
|
+
async updateMetrics(record) {
|
|
555
|
+
let completed = false;
|
|
556
|
+
if (this.clockMovedBack(record.timestamp)) {
|
|
557
|
+
this._completedMetrics = await this.resetAfterClockCorrection();
|
|
558
|
+
completed = this._completedMetrics !== undefined;
|
|
559
|
+
}
|
|
560
|
+
// Once a window closes, a late result cannot change it or enter a newer window.
|
|
561
|
+
if (this._closedThrough !== undefined && record.timestamp < this._closedThrough)
|
|
562
|
+
return false;
|
|
563
|
+
if (this._windowStart !== undefined && record.timestamp < this._windowStart)
|
|
564
|
+
return false;
|
|
565
|
+
const deadline = this.summaryDeadline;
|
|
566
|
+
if (deadline !== undefined && record.timestamp >= deadline) {
|
|
567
|
+
this._completedMetrics = await this.closeWindow(deadline);
|
|
568
|
+
completed = this._completedMetrics !== undefined;
|
|
569
|
+
}
|
|
570
|
+
if (this._windowStart === undefined) {
|
|
571
|
+
const start = this._closedThrough ?? record.timestamp;
|
|
572
|
+
this._windowStart = start +
|
|
573
|
+
Math.floor((record.timestamp - start) / this._summaryWindowMs) * this._summaryWindowMs;
|
|
574
|
+
this._windowEnd = this._windowStart + this._summaryWindowMs;
|
|
575
|
+
}
|
|
576
|
+
this._accumulator.add(record);
|
|
577
|
+
this._latestTimestamp = Math.max(this._latestTimestamp ?? record.timestamp, record.timestamp);
|
|
578
|
+
return completed;
|
|
579
|
+
}
|
|
580
|
+
/** Hand off a record-triggered completed summary once, independently of the new window's snapshot. */
|
|
581
|
+
takeCompletedMetrics() {
|
|
582
|
+
const completed = this._completedMetrics;
|
|
583
|
+
this._completedMetrics = undefined;
|
|
584
|
+
return completed;
|
|
662
585
|
}
|
|
663
586
|
}
|
|
587
|
+
exports.MetricsCalculator = MetricsCalculator;
|
|
664
588
|
/**
|
|
665
|
-
*
|
|
589
|
+
* Coordinates record persistence, calculator updates and summary delivery through one serialized queue.
|
|
590
|
+
* Keeps policy, deployment transitions and debug-record delivery separate from summary aggregation,
|
|
591
|
+
* using the calculator's deadline for timer-driven closure.
|
|
666
592
|
*/
|
|
667
593
|
class ModelMonitor extends tsee_1.EventEmitter {
|
|
594
|
+
/** Prepare event delivery; the factory initializes deployment storage and its calculator asynchronously. */
|
|
668
595
|
constructor(_config) {
|
|
669
596
|
super();
|
|
597
|
+
this._processing = Promise.resolve();
|
|
598
|
+
this._acceptingResults = true;
|
|
670
599
|
this._streamState = 'idle';
|
|
671
600
|
this._streamPrevState = 'idle';
|
|
672
601
|
}
|
|
@@ -674,17 +603,79 @@ class ModelMonitor extends tsee_1.EventEmitter {
|
|
|
674
603
|
* Creates a new instance of ModelMonitor with the provided configuration and model information.
|
|
675
604
|
* @param config The configuration object.
|
|
676
605
|
* @param model The model information object.
|
|
606
|
+
* @param options Original model thresholds supplied by the runner, before local settings are applied.
|
|
677
607
|
* @returns A promise that resolves to a ModelMonitor instance.
|
|
678
608
|
*/
|
|
679
|
-
static async getModelMonitor(config, model) {
|
|
609
|
+
static async getModelMonitor(config, model, options) {
|
|
680
610
|
const monitor = new ModelMonitor(config);
|
|
611
|
+
const reportedThresholds = options.reportedThresholds.map(block => ({ ...block }));
|
|
681
612
|
monitor._storageManager = await StorageManager.getStorageManager(config, model);
|
|
682
|
-
monitor._metricsCalculator = await MetricsCalculator.getMetricsInstance(config,
|
|
613
|
+
monitor._metricsCalculator = await MetricsCalculator.getMetricsInstance(config, {
|
|
614
|
+
modelParameters: model.modelParameters,
|
|
615
|
+
reportedThresholds,
|
|
616
|
+
});
|
|
683
617
|
return monitor;
|
|
684
618
|
}
|
|
619
|
+
/** Serialize record allocation, statistics and flushes while allowing later operations after a failure. */
|
|
620
|
+
enqueue(operation) {
|
|
621
|
+
const pending = this._processing.then(operation);
|
|
622
|
+
this._processing = pending.catch(() => undefined);
|
|
623
|
+
return pending;
|
|
624
|
+
}
|
|
625
|
+
/** Schedule the active deadline, delaying retries if closure fails. */
|
|
626
|
+
scheduleSummary(minimumDelayMs = 0) {
|
|
627
|
+
if (this._summaryTimer)
|
|
628
|
+
clearTimeout(this._summaryTimer);
|
|
629
|
+
this._summaryTimer = undefined;
|
|
630
|
+
const deadline = this._metricsCalculator?.summaryDeadline;
|
|
631
|
+
if (!this._acceptingResults || deadline === undefined)
|
|
632
|
+
return;
|
|
633
|
+
this._summaryTimer = setTimeout(() => {
|
|
634
|
+
void this.enqueue(async () => {
|
|
635
|
+
const summary = await this._metricsCalculator?.closeDueWindow(Date.now());
|
|
636
|
+
if (summary)
|
|
637
|
+
this.emit('inference-summary', summary);
|
|
638
|
+
this.scheduleSummary();
|
|
639
|
+
}).catch(error => {
|
|
640
|
+
console.warn(MONITOR_PREFIX, 'Unable to close summary window', error);
|
|
641
|
+
this.scheduleSummary(SUMMARY_CLOSE_RETRY_MS);
|
|
642
|
+
});
|
|
643
|
+
}, Math.max(minimumDelayMs, deadline - Date.now()));
|
|
644
|
+
this._summaryTimer.unref();
|
|
645
|
+
}
|
|
646
|
+
/** Permanently stop admitting results, then drain and flush the current deployment. */
|
|
647
|
+
async stop() {
|
|
648
|
+
this._acceptingResults = false;
|
|
649
|
+
if (this._summaryTimer)
|
|
650
|
+
clearTimeout(this._summaryTimer);
|
|
651
|
+
this._summaryTimer = undefined;
|
|
652
|
+
await this.flushMetrics();
|
|
653
|
+
}
|
|
654
|
+
/**
|
|
655
|
+
* Replace deployment storage/statistics after the caller pauses inference and flushes the old model.
|
|
656
|
+
* Retain listeners and policy without restarting a monitor that has been terminally stopped.
|
|
657
|
+
*/
|
|
658
|
+
async replaceModel(config, model, options) {
|
|
659
|
+
const reportedThresholds = options.reportedThresholds.map(block => ({ ...block }));
|
|
660
|
+
await this.enqueue(async () => {
|
|
661
|
+
const storage = await StorageManager.getStorageManager(config, model);
|
|
662
|
+
const calculator = await MetricsCalculator.getMetricsInstance(config, {
|
|
663
|
+
modelParameters: model.modelParameters,
|
|
664
|
+
reportedThresholds,
|
|
665
|
+
});
|
|
666
|
+
this._storageManager = storage;
|
|
667
|
+
this._metricsCalculator = calculator;
|
|
668
|
+
const policy = this._lastPolicy && this._lastPolicy !== NO_SUMMARY_POLICY ?
|
|
669
|
+
JSON.parse(this._lastPolicy) : undefined;
|
|
670
|
+
this._lastPolicy = undefined;
|
|
671
|
+
this.applySummaryPolicy(policy);
|
|
672
|
+
});
|
|
673
|
+
}
|
|
674
|
+
/** Expose the saved CLI preference, independent of this session's server policy. */
|
|
685
675
|
get configuredSummaryIntervalMs() {
|
|
686
676
|
return this._metricsCalculator?.configuredSummaryIntervalMs;
|
|
687
677
|
}
|
|
678
|
+
/** Expose the calculator's current policy-adjusted reporting interval. */
|
|
688
679
|
get effectiveSummaryIntervalMs() {
|
|
689
680
|
return this._metricsCalculator?.summaryIntervalMs;
|
|
690
681
|
}
|
|
@@ -706,7 +697,7 @@ class ModelMonitor extends tsee_1.EventEmitter {
|
|
|
706
697
|
console.warn(MONITOR_PREFIX, 'Ignoring invalid summary policy');
|
|
707
698
|
return;
|
|
708
699
|
}
|
|
709
|
-
const policyKey = JSON.stringify(policy) ??
|
|
700
|
+
const policyKey = JSON.stringify(policy) ?? NO_SUMMARY_POLICY;
|
|
710
701
|
if (this._lastPolicy === policyKey)
|
|
711
702
|
return;
|
|
712
703
|
this._lastPolicy = policyKey;
|
|
@@ -714,6 +705,7 @@ class ModelMonitor extends tsee_1.EventEmitter {
|
|
|
714
705
|
const effective = policy ? Math.max(policy.minimumIntervalMs, Math.min(configured ?? policy.intervalMs, policy.intervalMs)) :
|
|
715
706
|
Math.max(configured ?? exports.DEFAULT_MONITOR_SUMMARY_INTERVAL_MS, exports.DEFAULT_MONITOR_SUMMARY_INTERVAL_MS);
|
|
716
707
|
calculator.setSummaryIntervalMs(effective);
|
|
708
|
+
this.scheduleSummary();
|
|
717
709
|
console.log(MONITOR_PREFIX, `Summary interval: configured ${configured ?? 'automatic'}, effective ${effective} ms`);
|
|
718
710
|
if (configured !== undefined && configured !== effective) {
|
|
719
711
|
console.warn(MONITOR_PREFIX, 'The server policy overrides the saved interval for this session; ' +
|
|
@@ -733,21 +725,22 @@ class ModelMonitor extends tsee_1.EventEmitter {
|
|
|
733
725
|
'60-second interval for compatibility. The saved preference is unchanged.');
|
|
734
726
|
}
|
|
735
727
|
}
|
|
728
|
+
/** Queue a flush after admitted records, emit only a new summary, and refresh any remaining timer. */
|
|
736
729
|
async flushMetrics() {
|
|
737
|
-
|
|
738
|
-
await this._metricsCalculator
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
730
|
+
await this.enqueue(async () => {
|
|
731
|
+
const metrics = await this._metricsCalculator?.flushMetrics();
|
|
732
|
+
if (metrics)
|
|
733
|
+
this.emit('inference-summary', metrics);
|
|
734
|
+
this.scheduleSummary();
|
|
735
|
+
});
|
|
736
|
+
}
|
|
737
|
+
/** Report whether processed records are currently streamed live for debugging. */
|
|
742
738
|
get impulseDebug() {
|
|
743
739
|
return this._streamState === 'debug';
|
|
744
740
|
}
|
|
745
741
|
/**
|
|
746
|
-
*
|
|
747
|
-
*
|
|
748
|
-
* When disabled, the model monitor will not emit impulse records.
|
|
749
|
-
* In the 'records-request' state, setting impulseDebug to true will abort the records-request state.
|
|
750
|
-
* In the 'records-request' state, setting impulseDebug to false has no effect.
|
|
742
|
+
* Switch between live debug-record streaming and idle, replacing any records-request state.
|
|
743
|
+
* Summary collection remains active independently of debug streaming.
|
|
751
744
|
*/
|
|
752
745
|
set impulseDebug(enabled) {
|
|
753
746
|
if (this._streamState === 'records-request' && enabled === true) {
|
|
@@ -764,6 +757,7 @@ class ModelMonitor extends tsee_1.EventEmitter {
|
|
|
764
757
|
this._streamPrevState = 'idle';
|
|
765
758
|
}
|
|
766
759
|
}
|
|
760
|
+
/** Return retained record bounds for Remote Management, or zero bounds before storage is available. */
|
|
767
761
|
async getStorageStatus() {
|
|
768
762
|
if (this._storageManager) {
|
|
769
763
|
return await this._storageManager.getStorageStatus();
|
|
@@ -775,6 +769,7 @@ class ModelMonitor extends tsee_1.EventEmitter {
|
|
|
775
769
|
lastTimestamp: 0
|
|
776
770
|
};
|
|
777
771
|
}
|
|
772
|
+
/** Restore the previous streaming state when a record request is aborted. */
|
|
778
773
|
abortImpulseRecordsRequest() {
|
|
779
774
|
this._streamState = this._streamPrevState;
|
|
780
775
|
this._streamPrevState = 'idle';
|
|
@@ -786,7 +781,8 @@ class ModelMonitor extends tsee_1.EventEmitter {
|
|
|
786
781
|
* - index: The index of the single impulse record to retrieve.
|
|
787
782
|
* - range: An object with first and last properties specifying the range of impulse records to retrieve.
|
|
788
783
|
* - list: An array of indices of impulse records to retrieve (in any order)
|
|
789
|
-
*
|
|
784
|
+
* Missing records and inverted ranges emit error responses.
|
|
785
|
+
* @throws Error if the request supplies none of the supported selectors.
|
|
790
786
|
*/
|
|
791
787
|
getImpulseRecords(impulseRequest) {
|
|
792
788
|
if (this._streamState === 'debug') {
|
|
@@ -859,7 +855,13 @@ class ModelMonitor extends tsee_1.EventEmitter {
|
|
|
859
855
|
// restore the previous state
|
|
860
856
|
this._streamState = this._streamPrevState;
|
|
861
857
|
}
|
|
858
|
+
/**
|
|
859
|
+
* Admit an active producer result, persist it before aggregation,
|
|
860
|
+
* and deliver completed summaries/debug records.
|
|
861
|
+
*/
|
|
862
862
|
async processResult(result, rawData) {
|
|
863
|
+
if (!this._acceptingResults)
|
|
864
|
+
return;
|
|
863
865
|
let record = {
|
|
864
866
|
impulseRecord: result,
|
|
865
867
|
timestamp: Date.now(),
|
|
@@ -869,13 +871,18 @@ class ModelMonitor extends tsee_1.EventEmitter {
|
|
|
869
871
|
bufferBase64: rawData.buffer.toString('base64'),
|
|
870
872
|
},
|
|
871
873
|
};
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
874
|
+
await this.enqueue(async () => {
|
|
875
|
+
// Allocation and disk persistence finish before the record contributes to a summary.
|
|
876
|
+
await this._storageManager?.saveRecord(record);
|
|
877
|
+
if (this._metricsCalculator && await this._metricsCalculator.updateMetrics(record)) {
|
|
878
|
+
const metrics = this._metricsCalculator.takeCompletedMetrics();
|
|
879
|
+
if (metrics)
|
|
880
|
+
this.emit('inference-summary', metrics);
|
|
881
|
+
}
|
|
882
|
+
this.scheduleSummary();
|
|
883
|
+
if (this.impulseDebug)
|
|
884
|
+
this.emit('impulse-record', record);
|
|
885
|
+
});
|
|
879
886
|
}
|
|
880
887
|
}
|
|
881
888
|
exports.ModelMonitor = ModelMonitor;
|