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.
Files changed (90) hide show
  1. package/README.md +7 -2
  2. package/build/cli/linux/agent-capture.d.ts +29 -0
  3. package/build/cli/linux/agent-capture.js +94 -0
  4. package/build/cli/linux/agent-capture.js.map +1 -0
  5. package/build/cli/linux/agent-runner-metadata.d.ts +12 -3
  6. package/build/cli/linux/agent-runner-metadata.js +15 -3
  7. package/build/cli/linux/agent-runner-metadata.js.map +1 -1
  8. package/build/cli/linux/audio-utils.d.ts +1 -10
  9. package/build/cli/linux/audio-utils.js +2 -25
  10. package/build/cli/linux/audio-utils.js.map +1 -1
  11. package/build/cli/linux/runner-downloader.js +3 -0
  12. package/build/cli/linux/runner-downloader.js.map +1 -1
  13. package/build/cli/linux/runner-utils.js +1 -1
  14. package/build/cli/linux/runner-utils.js.map +1 -1
  15. package/build/cli/linux/runner.js +96 -60
  16. package/build/cli/linux/runner.js.map +1 -1
  17. package/build/cli-common/model-monitor.d.ts +97 -10
  18. package/build/cli-common/model-monitor.js +380 -373
  19. package/build/cli-common/model-monitor.js.map +1 -1
  20. package/build/cli-common/remote-mgmt-service.d.ts +1 -0
  21. package/build/cli-common/remote-mgmt-service.js +29 -11
  22. package/build/cli-common/remote-mgmt-service.js.map +1 -1
  23. package/build/library/classifier/audio-classifier.d.ts +16 -0
  24. package/build/library/classifier/audio-classifier.js +77 -1
  25. package/build/library/classifier/audio-classifier.js.map +1 -1
  26. package/build/library/classifier/image-classifier.d.ts +14 -0
  27. package/build/library/classifier/image-classifier.js +79 -3
  28. package/build/library/classifier/image-classifier.js.map +1 -1
  29. package/build/library/classifier/linux-impulse-runner.d.ts +8 -1
  30. package/build/library/classifier/linux-impulse-runner.js +13 -0
  31. package/build/library/classifier/linux-impulse-runner.js.map +1 -1
  32. package/build/library/sensors/audio-utils.d.ts +4 -0
  33. package/build/library/sensors/audio-utils.js +23 -0
  34. package/build/library/sensors/audio-utils.js.map +1 -0
  35. package/build/library/sensors/gstreamer.d.ts +1 -1
  36. package/build/library/sensors/gstreamer.js +7 -4
  37. package/build/library/sensors/gstreamer.js.map +1 -1
  38. package/build/sdk/studio/sdk/api/devicesApi.d.ts +2 -2
  39. package/build/sdk/studio/sdk/api/devicesApi.js +2 -2
  40. package/build/sdk/studio/sdk/model/additionalMetricOptionalFullPrecisionValue.d.ts +7 -0
  41. package/build/sdk/studio/sdk/model/additionalMetricOptionalFullPrecisionValue.js +4 -0
  42. package/build/sdk/studio/sdk/model/additionalMetricOptionalFullPrecisionValue.js.map +1 -0
  43. package/build/sdk/studio/sdk/model/dSPGroupItem.d.ts +9 -1
  44. package/build/sdk/studio/sdk/model/dSPGroupItem.js +3 -1
  45. package/build/sdk/studio/sdk/model/dSPGroupItem.js.map +1 -1
  46. package/build/sdk/studio/sdk/model/device.d.ts +5 -5
  47. package/build/sdk/studio/sdk/model/deviceApplication.d.ts +12 -0
  48. package/build/sdk/studio/sdk/model/{deviceWorkload.js → deviceApplication.js} +1 -1
  49. package/build/sdk/studio/sdk/model/deviceApplication.js.map +1 -0
  50. package/build/sdk/studio/sdk/model/{deviceWorkloadModel.d.ts → deviceApplicationModel.d.ts} +2 -2
  51. package/build/sdk/studio/sdk/model/{deviceWorkloadModel.js → deviceApplicationModel.js} +1 -1
  52. package/build/sdk/studio/sdk/model/deviceApplicationModel.js.map +1 -0
  53. package/build/sdk/studio/sdk/model/deviceDeploymentEvent.d.ts +4 -4
  54. package/build/sdk/studio/sdk/model/deviceModelDeploymentRequest.d.ts +5 -0
  55. package/build/sdk/studio/sdk/model/foldModelMetadata.d.ts +5 -0
  56. package/build/sdk/studio/sdk/model/getMonitoringEventDetailsResponse.d.ts +4 -0
  57. package/build/sdk/studio/sdk/model/getMonitoringEventDetailsResponse.js.map +1 -1
  58. package/build/sdk/studio/sdk/model/inferenceHistoryAggregate.d.ts +2 -2
  59. package/build/sdk/studio/sdk/model/kerasModelMetadata.d.ts +5 -0
  60. package/build/sdk/studio/sdk/model/kerasModelMetadataBase.d.ts +5 -0
  61. package/build/sdk/studio/sdk/model/kerasModelMetadataResponse.d.ts +5 -0
  62. package/build/sdk/studio/sdk/model/models.d.ts +3 -2
  63. package/build/sdk/studio/sdk/model/models.js +3 -2
  64. package/build/sdk/studio/sdk/model/models.js.map +1 -1
  65. package/build/sdk/studio/sdk/model/monitoringEventContext.d.ts +6 -2
  66. package/build/sdk/studio/sdk/model/monitoringInferenceSummary.d.ts +4 -0
  67. package/build/sdk/studio/sdk/model/userOrganization.d.ts +2 -0
  68. package/build/shared/viewmodels/init.d.ts +0 -1
  69. package/build/shared/viewmodels/init.js +0 -1
  70. package/build/shared/viewmodels/init.js.map +1 -1
  71. package/package.json +2 -2
  72. package/test/agent-bundle-lifecycle.test.ts +2 -2
  73. package/test/agent-bundle.test.ts +104 -0
  74. package/test/agent-capture.test.ts +528 -0
  75. package/test/agent-client.test.ts +64 -169
  76. package/test/agent-command-processor.test.ts +1 -1
  77. package/test/agent-preview-replacement.test.ts +114 -0
  78. package/test/agent-runner-configuration.test.ts +12 -3
  79. package/test/agent-runner-integration.test.ts +50 -8
  80. package/test/gstreamer.test.ts +1 -1
  81. package/test/helpers/mock-agent.ts +106 -0
  82. package/test/model-monitor.test.ts +250 -55
  83. package/test/monitoring-fixture.ts +168 -0
  84. package/test/monitoring-policy-protocol.test.ts +193 -1
  85. package/test/runner-preview.test.ts +59 -0
  86. package/test/summary-rules-fixtures.test.ts +194 -0
  87. package/test/utils/agent-runner-fixtures.ts +22 -7
  88. package/build/sdk/studio/sdk/model/deviceWorkload.d.ts +0 -12
  89. package/build/sdk/studio/sdk/model/deviceWorkload.js.map +0 -1
  90. package/build/sdk/studio/sdk/model/deviceWorkloadModel.js.map +0 -1
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Shared setup for monitoring stream and protocol tests. ModelMonitor and its file storage
3
+ * are real; model inputs, CLI configuration and time are controlled by the test. Expected summaries
4
+ * belong in the tests, not here. Always dispose the fixture and restore the clock in cleanup.
5
+ */
6
+ import fs from 'fs/promises';
7
+ import os from 'os';
8
+ import Path from 'path';
9
+ import { Config } from '../cli-common/config';
10
+ import { ImpulseRecord, InferenceMetrics, ModelMonitor } from '../cli-common/model-monitor';
11
+ import { ModelInformation, RunnerBlockThreshold,
12
+ RunnerClassifyResponseSuccess } from '../library/classifier/linux-impulse-runner-types';
13
+
14
+ /**
15
+ * Controls wall time and timeout delivery independently, so tests can choose whether a timer or
16
+ * prediction arrives first without sleeping. Replaces globals: use only in sequential tests.
17
+ * This is not a full Node clock; intervals and asynchronous callback completion are not controlled.
18
+ */
19
+ export class MonitoringClock {
20
+ now = 1_000_000;
21
+ private readonly _now = Date.now;
22
+ private readonly _setTimeout = global.setTimeout;
23
+ private readonly _clearTimeout = global.clearTimeout;
24
+ private readonly _timers = new Map<object, { at: number, callback: () => void }>();
25
+
26
+ /** Install the clock, retaining the original globals for restore(). */
27
+ constructor() {
28
+ Date.now = () => this.now;
29
+ global.setTimeout = ((callback: () => void, delay = 0) => {
30
+ // Production timers call unref(); this fake handle has no process-lifetime effect.
31
+ const timer = { unref: () => undefined };
32
+ this._timers.set(timer, { at: this.now + delay, callback });
33
+ return timer;
34
+ }) as unknown as typeof setTimeout;
35
+ global.clearTimeout = ((timer: object) => this._timers.delete(timer)) as unknown as typeof clearTimeout;
36
+ }
37
+
38
+ /**
39
+ * Set wall time and invoke currently due callbacks in deadline order, without awaiting their
40
+ * asynchronous work. Callers must separately await the monitoring operation they trigger.
41
+ */
42
+ fireDue(now: number): void {
43
+ this.now = now;
44
+ // Iterate a snapshot: timers created by these callbacks wait for the next fireDue() call.
45
+ for (const [ timer, task ] of [ ...this._timers ].sort((a, b) => a[1].at - b[1].at)) {
46
+ if (task.at <= now && this._timers.delete(timer)) task.callback();
47
+ }
48
+ }
49
+
50
+ /** Restore all replaced globals and discard outstanding fake timers, including after failures. */
51
+ restore(): void {
52
+ Date.now = this._now;
53
+ global.setTimeout = this._setTimeout;
54
+ global.clearTimeout = this._clearTimeout;
55
+ this._timers.clear();
56
+ }
57
+ }
58
+
59
+ /** Hold a prediction or storage operation pending until the test explicitly resolves it. */
60
+ export function deferred<T>() {
61
+ let resolve: (value: T | PromiseLike<T>) => void = () => undefined;
62
+ const promise = new Promise<T>(accept => resolve = accept);
63
+ return { promise, resolve };
64
+ }
65
+
66
+ /** Build a prediction with fixed timings, so summary timing averages have known inputs. */
67
+ export function monitoringResult(classification: Record<string, number>): RunnerClassifyResponseSuccess {
68
+ return { result: { classification }, timing: { dsp: 2, classification: 4, anomaly: 0 }, info: undefined };
69
+ }
70
+
71
+ /**
72
+ * Build the minimal project-1 classification metadata used by monitoring tests.
73
+ * null means that the model reported no threshold, not a zero cutoff. Tests applying local settings
74
+ * before creating a monitor must copy the original thresholds and pass them explicitly to the fixture.
75
+ * This is not a complete trained model.
76
+ */
77
+ export function monitoringModel(version = 1, cutoff: number | null = 0.5): ModelInformation {
78
+ const model = {
79
+ project: { id: 1, owner: 'test', name: 'monitoring', deploy_version: version },
80
+ modelParameters: {
81
+ model_type: 'classification', has_anomaly: 0, labels: [ 'cat', 'dog' ],
82
+ thresholds: cutoff === null ? [] : [{ id: 42, type: 'classification', min_score: cutoff }],
83
+ },
84
+ } as unknown as ModelInformation;
85
+ return model;
86
+ }
87
+
88
+ /**
89
+ * Create a real monitor with an isolated temporary storage root and in-memory CLI configuration.
90
+ * Models must use project 1, matching the storage paths below. Records are read back from
91
+ * production-written files; delivered summaries accumulate from the real monitor event.
92
+ * Supply reportedThresholds explicitly if the model already contains local threshold overrides.
93
+ * Otherwise its current thresholds stand in for the Hello snapshot, copied before monitor creation.
94
+ * The caller must dispose() in finally, and restore any MonitoringClock separately afterwards.
95
+ */
96
+ export async function monitoringFixture(model = monitoringModel(),
97
+ {
98
+ reportedThresholds = model.modelParameters.thresholds ?? [],
99
+ configuredSummaryIntervalMs,
100
+ }: {
101
+ reportedThresholds?: readonly RunnerBlockThreshold[];
102
+ configuredSummaryIntervalMs?: number;
103
+ } = {}) {
104
+ const thresholds = reportedThresholds.map(block => ({ ...block }));
105
+ const root = await fs.mkdtemp(Path.join(os.tmpdir(), 'ei-monitoring-'));
106
+ let deploymentVersion = model.project.deploy_version;
107
+ let storagePath = Path.join(root, '1', deploymentVersion.toString());
108
+ let nextIndex = 0;
109
+ const config = {
110
+ /** Read the selected deployment, which tests can change before replacing the model. */
111
+ getDeploymentVersion: async () => deploymentVersion,
112
+ /** Select a deployment without touching the user's CLI configuration. */
113
+ setDeploymentVersion: async (version: number) => { deploymentVersion = version; },
114
+ /** Read the storage directory currently selected by the production storage manager. */
115
+ getStoragePath: async () => storagePath,
116
+ /** Retain directory changes made during storage initialization or model replacement. */
117
+ storeStoragePath: async (path: string) => { storagePath = path; },
118
+ /** Keep all deployment directories inside this fixture's temporary root. */
119
+ getDefaultStoragePath: () => root,
120
+ /** Supply no explicit storage size limit. */
121
+ getStorageMaxSizeMb: async () => undefined,
122
+ /** Read the record index retained between monitor instances. */
123
+ getStorageIndex: async () => nextIndex,
124
+ /** Retain the production index update; tests may delay this write to exercise queue ordering. */
125
+ storeStorageIndex: async (index: number) => { nextIndex = index; },
126
+ /** Supply the saved cadence preference selected by this test, or automatic cadence by default. */
127
+ getMonitorSummaryIntervalMs: async () => configuredSummaryIntervalMs,
128
+ } as unknown as Config;
129
+ const monitor = await ModelMonitor.getModelMonitor(config, model, { reportedThresholds: thresholds })
130
+ .catch(async error => {
131
+ await fs.rm(root, { recursive: true, force: true });
132
+ throw error;
133
+ });
134
+ const summaries: InferenceMetrics[] = [];
135
+ monitor.on('inference-summary', summary => summaries.push(summary));
136
+
137
+ return {
138
+ root, config, summaries, monitor,
139
+ /**
140
+ * Read a deployment's persisted records in index order, without calculating expected values.
141
+ * Raw JPEG bytes live in separate files; record JSON contains their paths.
142
+ */
143
+ async saved(version = deploymentVersion) {
144
+ const path = Path.join(root, '1', version.toString());
145
+ const records: ImpulseRecord[] = [];
146
+ for (const segment of await fs.readdir(path, { withFileTypes: true })) {
147
+ if (!segment.isDirectory() || !/^\d+$/.test(segment.name)) continue;
148
+ for (const name of await fs.readdir(Path.join(path, segment.name))) {
149
+ // Segment directories also contain raw image files, which are not record JSON.
150
+ if (!name.endsWith('.json')) continue;
151
+ records.push(JSON.parse(await fs.readFile(Path.join(path, segment.name, name), 'utf8')));
152
+ }
153
+ }
154
+ records.sort((left, right) => left.index - right.index);
155
+ return { records };
156
+ },
157
+ /** Drain/stop the monitor, remove listeners and delete only this fixture's temporary root. */
158
+ async dispose() {
159
+ try {
160
+ await monitor.stop();
161
+ }
162
+ finally {
163
+ monitor.removeAllListeners();
164
+ await fs.rm(root, { recursive: true, force: true });
165
+ }
166
+ },
167
+ };
168
+ }
@@ -1,11 +1,91 @@
1
+ /**
2
+ * Exercise real Hello negotiation, reconnect handlers and summary delivery without a server.
3
+ * Sockets and device/API lookups are simulated; the stream cases use real monitoring and file storage.
4
+ * Policy support controls cadence independently of the capability that permits telemetry transmission.
5
+ */
1
6
  import assert from 'assert';
2
7
  import { EventEmitter } from 'events';
3
8
  import { RemoteMgmt } from '../cli-common/remote-mgmt-service';
4
9
  import { MonitoringSummaryPolicy } from '../shared/device-protocol/remote-management';
10
+ import { InferenceMetrics, ModelMonitor } from '../cli-common/model-monitor';
11
+ import { MgmtInterfaceInferenceInfo } from '../shared/MgmtInterfaceTypes';
12
+ import { MonitoringClock, monitoringFixture, monitoringModel, monitoringResult } from './monitoring-fixture';
13
+
14
+ /** Outbound protocol fields inspected by these tests; not a replacement for the full wire contract. */
15
+ type SentMessage = {
16
+ hello?: { mode: string, supportsMonitoringSummaryPolicy?: boolean, inferenceInfo?: MgmtInterfaceInferenceInfo };
17
+ inferenceSummary?: InferenceMetrics;
18
+ modelUpdateSuccess?: boolean;
19
+ };
20
+
21
+ /** Capture outgoing JSON and let tests deliver socket events in a chosen order, without networking. */
22
+ class MonitoringSocket extends EventEmitter {
23
+ readonly sent: SentMessage[] = [];
24
+ /** Decode the actual outgoing payload so assertions observe what RemoteMgmt sends. */
25
+ send(data: string | Buffer): void { this.sent.push(JSON.parse(data.toString())); }
26
+ /** No-op: these tests exercise policy requests, not network ping/pong delivery. */
27
+ ping(): void { /* No network in protocol tests. */ }
28
+ /** Trigger the production close handler, including its reconnect scheduling. */
29
+ close(): void { this.emit('close'); }
30
+ /** Treat forced termination as closure; there is no underlying connection to destroy. */
31
+ terminate(): void { this.close(); }
32
+ }
33
+
34
+ /**
35
+ * Attach real RemoteMgmt methods to a monitor, substituting sockets and device/API responses.
36
+ * Skip the constructor's perpetual ping interval, as the existing protocol tests do. The caller
37
+ * must disconnect and dispose the monitor; create a new harness if the monitor itself is restarted.
38
+ */
39
+ function monitoringRemote(monitor: ModelMonitor) {
40
+ const sockets: MonitoringSocket[] = [];
41
+ // As in the existing protocol test, use real methods but avoid the constructor's perpetual ping timer.
42
+ const remote = Object.assign(Object.create(RemoteMgmt.prototype), {
43
+ _projectId: 1, _isConnected: false, _devKeys: { apiKey: 'test' }, _monitor: monitor,
44
+ _eiConfig: { command: 'test', endpoints: { internal: { api: 'http://localhost/v1', ws: 'ws://localhost' } } },
45
+ _createWebsocket: () => {
46
+ const socket = new MonitoringSocket();
47
+ sockets.push(socket);
48
+ return socket;
49
+ },
50
+ _device: { connected: () => true, beforeConnect: async () => undefined,
51
+ getDeviceId: async () => 'device', getDeviceType: async () => 'test', getConnectionType: () => 'ip',
52
+ getSensors: () => [], supportsSnapshotStreaming: () => false },
53
+ checkName: async () => 'test', getProjectInfo: async () => ({ name: 'project' }),
54
+ }) as RemoteMgmt;
55
+ const methods = remote as unknown as { sendHello(): Promise<void> };
56
+ monitor.on('inference-summary', summary => remote.inferenceSummaryListener(summary));
57
+ return {
58
+ remote, sockets,
59
+ /** Connect through production handlers, then send Hello explicitly instead of a network open event. */
60
+ async connect() {
61
+ await remote.connect(true, { projectId: 1, projectOwner: 'test', projectName: 'monitoring',
62
+ deploymentVersion: 1, modelType: 'classification' });
63
+ await methods.sendHello();
64
+ return sockets[sockets.length - 1];
65
+ },
66
+ /** Deliver a server Hello with independently chosen telemetry and policy support, then await its handler. */
67
+ async accept(socket: MonitoringSocket, supportsTelemetry: boolean | undefined, supportsPolicy: boolean) {
68
+ socket.emit('message', Buffer.from(JSON.stringify({ hello: true,
69
+ ...(supportsTelemetry === undefined ? {} :
70
+ { capabilities: { summaryRulesVersion: supportsTelemetry } }),
71
+ ...(supportsPolicy ? { supportsMonitoringSummaryPolicy: true, monitoringSummaryPolicy: {
72
+ intervalMs: 5_000, minimumIntervalMs: 5_000, preparationWindowMs: 0, requirementsMet: true,
73
+ } } : {}),
74
+ })));
75
+ // Allow the asynchronous Hello handler to finish setting connection state.
76
+ await new Promise<void>(resolve => setImmediate(resolve));
77
+ assert.strictEqual(remote.isConnected, true, 'Hello was accepted');
78
+ },
79
+ /** Send Hello on the socket created by the real scheduled reconnect callback. */
80
+ sendHello: () => methods.sendHello(),
81
+ };
82
+ }
5
83
 
6
84
  describe('monitoring policy protocol', () => {
7
85
  for (const supportsPolicy of [ false, true ]) {
8
- it(`handles ${supportsPolicy ? 'new' : 'old'} servers and keeps policy messages separate from record ACKs`, async () => {
86
+ const name = `handles servers ${supportsPolicy ? 'with' : 'without'} summary-policy support ` +
87
+ 'and keeps policy messages separate from record ACKs';
88
+ it(name, async () => {
9
89
  const policies: (MonitoringSummaryPolicy | undefined)[] = [];
10
90
  const sent: { hello?: { supportsMonitoringSummaryPolicy: boolean };
11
91
  getMonitoringSummaryPolicy?: boolean }[] = [];
@@ -60,3 +140,115 @@ describe('monitoring policy protocol', () => {
60
140
  });
61
141
  }
62
142
  });
143
+
144
+ describe('monitoring telemetry transmission', () => {
145
+ let clock: MonitoringClock;
146
+ const input = { type: 'wav' as const, buffer: Buffer.from([ 0, 1 ]) };
147
+
148
+ beforeEach(() => { clock = new MonitoringClock(); });
149
+ afterEach(() => { clock.restore(); });
150
+
151
+ for (const supportsTelemetry of [ undefined, false ]) {
152
+ it(`does not send telemetry when support is ${supportsTelemetry}`, async () => {
153
+ const fixture = await monitoringFixture();
154
+ const connection = monitoringRemote(fixture.monitor);
155
+ const warnings: string[] = [];
156
+ const warn = console.warn;
157
+ try {
158
+ console.warn = (...args: Parameters<typeof console.warn>) => warnings.push(args.join(' '));
159
+ const socket = await connection.connect();
160
+ await connection.accept(socket, supportsTelemetry, true);
161
+ await fixture.monitor.processResult(monitoringResult({ cat: 1 }), input);
162
+ await fixture.monitor.flushMetrics();
163
+ assert.strictEqual(socket.sent.some(message => message.inferenceSummary), false);
164
+ assert.strictEqual(warnings.some(message => message.includes(
165
+ 'Model monitoring summaries are disabled because this server does not support')), true);
166
+ }
167
+ finally {
168
+ console.warn = warn;
169
+ connection.remote.disconnect();
170
+ await fixture.dispose();
171
+ }
172
+ });
173
+ }
174
+
175
+ /** Send one exact summary after telemetry support is negotiated, without requiring policy support. */
176
+ it('sends telemetry after negotiation', async () => {
177
+ const fixture = await monitoringFixture();
178
+ const connection = monitoringRemote(fixture.monitor);
179
+ try {
180
+ const socket = await connection.connect();
181
+ await fixture.monitor.processResult(monitoringResult({ beforeHello: 1 }), input);
182
+ await fixture.monitor.flushMetrics();
183
+ assert.strictEqual(socket.sent.some(message => message.inferenceSummary), false,
184
+ 'summaries are not sent before an accepted Hello');
185
+
186
+ await connection.accept(socket, true, false);
187
+ const timestamp = ++clock.now;
188
+ await fixture.monitor.processResult(monitoringResult({ cat: 0.75, dog: 0.25 }), input);
189
+ await fixture.monitor.flushMetrics();
190
+ assert.deepStrictEqual(socket.sent.filter(message => message.inferenceSummary)
191
+ .map(message => message.inferenceSummary), [{
192
+ rulesVersion: 2,
193
+ start: { index: 2, timestamp }, end: { index: 2, timestamp },
194
+ classificationCounter: [{ label: 'cat', value: 1 }],
195
+ mean: [{ label: 'cat', value: 0.75 }, { label: 'dog', value: 0.25 }],
196
+ standardDeviation: [{ label: 'cat', value: 0 }, { label: 'dog', value: 0 }],
197
+ metrics: { avg_inference_time: { dsp: 2, classification: 4 } },
198
+ }]);
199
+ }
200
+ finally {
201
+ connection.remote.disconnect();
202
+ await fixture.dispose();
203
+ }
204
+ });
205
+
206
+ /** Start a window, reconnect, and verify results on both connections close as one summary. */
207
+ it('preserves an open window across reconnects', async () => {
208
+ const fixture = await monitoringFixture();
209
+ const connection = monitoringRemote(fixture.monitor);
210
+ try {
211
+ const old = await connection.connect();
212
+ await connection.accept(old, true, false);
213
+ const timestamp = clock.now;
214
+ await fixture.monitor.processResult(monitoringResult({ cat: 1 }), input);
215
+
216
+ const current = await connection.connect();
217
+ await connection.accept(current, true, false);
218
+ clock.now++;
219
+ await fixture.monitor.processResult(monitoringResult({ dog: 1 }), input);
220
+ await fixture.monitor.flushMetrics();
221
+ const summaries = current.sent.filter(message => message.inferenceSummary)
222
+ .map(message => message.inferenceSummary!);
223
+ assert.strictEqual(summaries.length, 1);
224
+ assert.deepStrictEqual([ summaries[0].start, summaries[0].end ],
225
+ [{ index: 1, timestamp }, { index: 2, timestamp: timestamp + 1 }]);
226
+ assert.strictEqual(old.sent.some(message => message.inferenceSummary), false);
227
+ }
228
+ finally {
229
+ connection.remote.disconnect();
230
+ await fixture.dispose();
231
+ }
232
+ });
233
+
234
+ /** Preserve replacement deployment metadata while disconnected and advertise it on the next Hello. */
235
+ it('reports an offline replacement deployment on reconnect', async () => {
236
+ const fixture = await monitoringFixture();
237
+ const connection = monitoringRemote(fixture.monitor);
238
+ try {
239
+ const socket = await connection.connect();
240
+ await connection.accept(socket, true, false);
241
+ connection.remote.disconnect();
242
+ await connection.remote.sendModelUpdateStatus(monitoringModel(2), true);
243
+ clock.fireDue(clock.now + 1_000);
244
+ await new Promise<void>(resolve => setImmediate(resolve));
245
+ await connection.sendHello();
246
+ const reconnected = connection.sockets[connection.sockets.length - 1];
247
+ assert.strictEqual(reconnected.sent[0].hello?.inferenceInfo?.deploymentVersion, 2);
248
+ }
249
+ finally {
250
+ connection.remote.disconnect();
251
+ await fixture.dispose();
252
+ }
253
+ });
254
+ });
@@ -0,0 +1,59 @@
1
+ import assert from 'node:assert';
2
+ import { EventEmitter } from 'node:events';
3
+ import { Server as HttpServer } from 'node:http';
4
+ import { Server as SocketIoServer } from 'socket.io';
5
+ import { startWebServer } from '../cli/linux/runner-utils';
6
+ import type { ImageClassifier } from '../library/classifier/image-classifier';
7
+ import type { ModelInformation } from '../library/classifier/linux-impulse-runner';
8
+ import type { ICamera } from '../library/sensors/icamera';
9
+
10
+ /** The preview may filter its presentation without changing the shared camera event. */
11
+ describe('camera preview results', () => {
12
+ it('filters a copy and leaves raw scores available to later event listeners', async () => {
13
+ const originalListen = HttpServer.prototype.listen;
14
+ const originalEmit = SocketIoServer.prototype.emit;
15
+ let preview: { result: { classification: Record<string, number> } } | undefined;
16
+ const classifier = new EventEmitter();
17
+ const camera = new EventEmitter();
18
+ // Exercise the real result handler without opening a server socket.
19
+ HttpServer.prototype.listen = function(this: HttpServer, ...args: unknown[]) {
20
+ const callback = args.find((arg) => typeof arg === 'function');
21
+ if (typeof callback === 'function') callback();
22
+ return this;
23
+ } as typeof originalListen;
24
+ SocketIoServer.prototype.emit = function(event: string, ...args: unknown[]) {
25
+ if (event === 'classification') {
26
+ preview = args[0] as typeof preview;
27
+ }
28
+ return false;
29
+ } as typeof originalEmit;
30
+ try {
31
+ await startWebServer({
32
+ type: 'camera',
33
+ camera: camera as unknown as ICamera,
34
+ imgClassifier: classifier as unknown as ImageClassifier,
35
+ model: {
36
+ modelParameters: {
37
+ model_type: 'classification',
38
+ thresholds: [{ id: 1, type: 'classification', min_score: 0.5 }],
39
+ },
40
+ } as unknown as ModelInformation,
41
+ streamResolution: 'scaled-using-impulse',
42
+ verbose: false,
43
+ host: '127.0.0.1',
44
+ port: 0,
45
+ });
46
+ const raw = { result: { classification: { low: 0.2, high: 0.8 } } };
47
+ let observed: typeof raw | undefined;
48
+ classifier.on('result', (event: typeof raw) => { observed = event; });
49
+ classifier.emit('result', raw, 1, Buffer.alloc(0));
50
+ assert.deepStrictEqual(preview?.result.classification, { low: 0, high: 0.8 });
51
+ assert.deepStrictEqual(raw.result.classification, { low: 0.2, high: 0.8 });
52
+ assert.strictEqual(observed, raw);
53
+ }
54
+ finally {
55
+ HttpServer.prototype.listen = originalListen;
56
+ SocketIoServer.prototype.emit = originalEmit;
57
+ }
58
+ });
59
+ });
@@ -0,0 +1,194 @@
1
+ /**
2
+ * Replay every current-rules corpus window through the Linux runner's production calculator and compare
3
+ * complete summaries and ordering with the shared expected outputs. Persistence and continuous timer
4
+ * behaviour are covered in model-monitor.test.ts; this suite owns arithmetic conformance.
5
+ */
6
+ import assert from 'assert';
7
+ import { existsSync } from 'fs';
8
+ import fs from 'fs/promises';
9
+ import Path from 'path';
10
+ import { InferenceEvent, RegisterRequest } from '../shared/device-protocol/application-contract';
11
+ import { InferenceSummary } from '../shared/device-protocol/remote-management';
12
+ import { InferenceMetrics, MetricsCalculator } from '../cli-common/model-monitor';
13
+
14
+ const RULES = Path.join(__dirname, '../../../device-services-contracts/summary-rules');
15
+
16
+ type Summary = InferenceSummary['inferenceSummary'];
17
+ type LabelValues = { label: string, value: number }[];
18
+
19
+ type Input = {
20
+ registrations: { applicationId: string, atMs: number, request: RegisterRequest }[];
21
+ records: { index: number, applicationId: string, event: InferenceEvent }[];
22
+ };
23
+
24
+ type WindowEntry = { cadence: number, startMs: number, endMs: number, summaries: InferenceSummary[] };
25
+
26
+ type Rules = {
27
+ rules: { id: string, params?: { [name: string]: { value: unknown } } }[];
28
+ };
29
+
30
+ /**
31
+ * Feed each non-empty series in one explicit, start-inclusive/end-exclusive corpus window to its
32
+ * own calculator and close it at the supplied deadline. No expected arithmetic is calculated here.
33
+ */
34
+ async function runnerSummaries(input: Input, window: WindowEntry): Promise<InferenceMetrics[]> {
35
+ const series = new Map<string, MetricsCalculator>();
36
+ for (const record of input.records) {
37
+ const timestamp = record.event.inferenceTimestamp;
38
+ if (timestamp < window.startMs || timestamp >= window.endMs) continue;
39
+ const registration = registrationAt(input, record.applicationId, timestamp);
40
+ // A failure does not exclude any results carried by that event.
41
+ for (const result of record.event.results ?? []) {
42
+ const model = registration.request.models.find(candidate => candidate.id === result.modelId);
43
+ assert.ok(model, 'every result names a registered model');
44
+ const key = JSON.stringify([ record.applicationId, model.id, model.deploymentVersion ]);
45
+ let calculator = series.get(key);
46
+ if (!calculator) {
47
+ calculator = await MetricsCalculator.getMetricsInstance(
48
+ { getMonitorSummaryIntervalMs: async () => undefined },
49
+ { modelParameters: { model_type: model.modelType, has_anomaly: 0, thresholds: model.thresholds },
50
+ reportedThresholds: model.thresholds ?? [] });
51
+ // Corpus windows are explicit; runner windows normally start at their first result.
52
+ // Align this first window's deadline to the supplied end, then use real closure.
53
+ calculator.setSummaryIntervalMs(window.endMs - timestamp);
54
+ series.set(key, calculator);
55
+ }
56
+ assert.strictEqual(await calculator.updateMetrics({ index: record.index, timestamp,
57
+ impulseRecord: { result: result.result, timing: result.timing, info: undefined } }), false,
58
+ 'a result inside the supplied window does not close it');
59
+ }
60
+ }
61
+ const summaries: InferenceMetrics[] = [];
62
+ for (const calculator of series.values()) {
63
+ const summary = await calculator.closeDueWindow(window.endMs);
64
+ assert.ok(summary, 'a non-empty series closes at its deadline');
65
+ summaries.push(summary);
66
+ }
67
+ return summaries;
68
+ }
69
+
70
+ /** Index labels while rejecting duplicates and extra fields, regardless of the ordering policy. */
71
+ function byLabel(values: LabelValues) {
72
+ const map = new Map<string, number>();
73
+ for (const entry of values) {
74
+ assert.deepStrictEqual(Object.keys(entry).sort(), [ 'label', 'value' ], 'fields of a label value');
75
+ const { label, value } = entry;
76
+ assert.strictEqual(typeof label, 'string', 'label type');
77
+ assert.strictEqual(typeof value, 'number', 'label value type');
78
+ assert.ok(!map.has(label), 'duplicate label ' + label);
79
+ map.set(label, value);
80
+ }
81
+ return map;
82
+ }
83
+
84
+ /** Compare label values exactly or within tolerance, preserving the version's array-order requirement. */
85
+ function assertLabelValues(actual: LabelValues, expected: LabelValues, exact: boolean, tolerance: number,
86
+ name: string, order: 'any' | 'codePoint') {
87
+ const actualMap = byLabel(actual);
88
+ const expectedMap = byLabel(expected);
89
+ const actualLabels = [ ...actualMap.keys() ];
90
+ const expectedLabels = [ ...expectedMap.keys() ];
91
+ assert.deepStrictEqual(order === 'any' ? actualLabels.sort() : actualLabels,
92
+ order === 'any' ? expectedLabels.sort() : expectedLabels, name + ': labels');
93
+ for (const [ label, value ] of expectedMap) {
94
+ const got = actualMap.get(label)!;
95
+ if (exact) assert.strictEqual(got, value, name + '.' + label);
96
+ else assert.ok(Math.abs(got - value) <= tolerance, name + '.' + label + ': ' + got + ' is not ' + value);
97
+ }
98
+ }
99
+
100
+ /** Compare numeric metric keys within tolerance, but compare the anomaly counter exactly. */
101
+ function assertNumbers(actualObject: object | undefined, expectedObject: object | undefined, tolerance: number,
102
+ name: string) {
103
+ const actual = actualObject as { [key: string]: number };
104
+ const expected = expectedObject as { [key: string]: number };
105
+ assert.deepStrictEqual(Object.keys(actual).sort(), Object.keys(expected).sort(), name + ': keys');
106
+ for (const key of Object.keys(expected)) {
107
+ // Do not let numeric strings pass through subtraction's implicit conversion.
108
+ assert.strictEqual(typeof actual[key], 'number', name + '.' + key + ': type');
109
+ if (key === 'anomaly_count') {
110
+ assert.strictEqual(actual[key], expected[key], name + '.' + key);
111
+ }
112
+ else {
113
+ assert.ok(Math.abs(actual[key] - expected[key]) <= tolerance,
114
+ name + '.' + key + ': ' + actual[key] + ' is not ' + expected[key]);
115
+ }
116
+ }
117
+ }
118
+
119
+ /** Compare full summaries without hiding extra fields; only floating-point statistics permit tolerance. */
120
+ function assertSummary(actual: InferenceMetrics, expected: Summary, tolerance: number,
121
+ labelOrder: 'any' | 'codePoint') {
122
+ assert.deepStrictEqual(Object.keys(actual).sort(), Object.keys(expected).sort(), 'fields of the summary');
123
+ assert.deepStrictEqual(actual.start, expected.start, 'start');
124
+ assert.deepStrictEqual(actual.end, expected.end, 'end');
125
+ assert.strictEqual(actual.rulesVersion, expected.rulesVersion, 'rulesVersion');
126
+ assertLabelValues(actual.classificationCounter, expected.classificationCounter, true, tolerance,
127
+ 'classificationCounter', labelOrder);
128
+ assertLabelValues(actual.mean, expected.mean, false, tolerance, 'mean', labelOrder);
129
+ assertLabelValues(actual.standardDeviation, expected.standardDeviation, false, tolerance,
130
+ 'standardDeviation', labelOrder);
131
+ const { avg_inference_time: actualTime, ...actualRest } = actual.metrics;
132
+ const { avg_inference_time: expectedTime, ...expectedRest } = expected.metrics;
133
+ assertNumbers(actualTime, expectedTime, tolerance, 'avg_inference_time');
134
+ assertNumbers(actualRest, expectedRest, tolerance, 'metrics');
135
+ }
136
+
137
+ /** Select the latest registration at/before the event time; file order breaks equal-time ties. */
138
+ function registrationAt(input: Input, applicationId: string, timeMs: number) {
139
+ let latest: Input['registrations'][0] | undefined;
140
+ for (const registration of input.registrations) {
141
+ if (registration.applicationId === applicationId && registration.atMs <= timeMs &&
142
+ (latest === undefined || registration.atMs >= latest.atMs)) {
143
+ latest = registration;
144
+ }
145
+ }
146
+ assert.ok(latest, `${applicationId} has a registration at ${timeMs}`);
147
+ return latest;
148
+ }
149
+
150
+ /** Load every current-rules corpus case, verify complete window coverage, and compare production output. */
151
+ function summaryRulesConformanceSuite(): void {
152
+ describe('summary rules conformance', () => {
153
+ it('reproduces every corpus window through the runner calculator', async () => {
154
+ const directory = Path.join(RULES, 'v2');
155
+ const rules = JSON.parse(await fs.readFile(Path.join(directory, 'rules.json'), 'utf8')) as Rules;
156
+ const params = rules.rules.find(rule => rule.id === 'output')!.params!;
157
+ const tolerance = params.tolerance.value as number;
158
+ const labelOrder = params.labelOrder.value as 'any' | 'codePoint';
159
+ assert.ok(tolerance > 0, 'the rules give a tolerance');
160
+ assert.ok(labelOrder === 'any' || labelOrder === 'codePoint', 'the rules give a label ordering');
161
+ const names = (await fs.readdir(Path.join(directory, 'outputs')))
162
+ .filter(name => name.endsWith('.json')).sort();
163
+ assert.ok(names.length > 0, 'the corpus has cases');
164
+ let checked = 0;
165
+ for (const name of names) {
166
+ const input = JSON.parse(await fs.readFile(Path.join(RULES, 'inputs', name), 'utf8')) as Input;
167
+ const output = JSON.parse(await fs.readFile(Path.join(directory, 'outputs', name), 'utf8')) as {
168
+ windows: WindowEntry[];
169
+ };
170
+ assert.ok(output.windows.length > 0, name + ' has entries');
171
+ for (const entry of output.windows) {
172
+ try {
173
+ const actual = await runnerSummaries(input, entry);
174
+ const expected = entry.summaries.map(summary => summary.inferenceSummary);
175
+ assert.strictEqual(actual.length, expected.length, 'number of summaries');
176
+ actual.forEach((summary, index) =>
177
+ assertSummary(summary, expected[index], tolerance, labelOrder));
178
+ }
179
+ catch (error) {
180
+ throw new Error(name + ' cadence ' + entry.cadence + ' window ' + entry.startMs +
181
+ ' entry ' + JSON.stringify(entry) + ': ' + (error as Error).message);
182
+ }
183
+ checked++;
184
+ }
185
+ }
186
+ assert.ok(checked > 0, 'the entries are checked');
187
+ });
188
+ });
189
+ }
190
+
191
+ // Public exports lack the contracts workspace; register corpus suites only inside the monorepo.
192
+ if (existsSync(Path.join(__dirname, '../../../device-services-contracts'))) {
193
+ summaryRulesConformanceSuite();
194
+ }