edge-impulse-linux 1.25.4 → 1.26.1
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 +17 -3
- package/build/cli/linux/runner-downloader.js +24 -1
- package/build/cli/linux/runner-downloader.js.map +1 -1
- package/build/cli/linux/runner-utils.d.ts +5 -0
- package/build/cli/linux/runner-utils.js +6 -1
- package/build/cli/linux/runner-utils.js.map +1 -1
- package/build/cli/linux/runner.js +254 -73
- package/build/cli/linux/runner.js.map +1 -1
- package/build/cli-common/model-monitor.d.ts +13 -0
- package/build/cli-common/model-monitor.js +68 -8
- 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 +31 -16
- package/build/cli-common/remote-mgmt-service.js.map +1 -1
- package/build/library/classifier/audio-classifier.d.ts +12 -3
- package/build/library/classifier/audio-classifier.js +49 -39
- package/build/library/classifier/audio-classifier.js.map +1 -1
- package/build/library/classifier/libcwrapper.d.ts +7 -1
- package/build/library/classifier/libcwrapper.js +10 -2
- package/build/library/classifier/libcwrapper.js.map +1 -1
- package/build/library/classifier/linux-impulse-runner.d.ts +28 -0
- package/build/library/classifier/linux-impulse-runner.js +253 -55
- package/build/library/classifier/linux-impulse-runner.js.map +1 -1
- package/build/library/sensors/gstreamer.js +38 -5
- package/build/library/sensors/gstreamer.js.map +1 -1
- package/build/library/sensors/recorder.js +61 -23
- package/build/library/sensors/recorder.js.map +1 -1
- package/build/sdk/studio/sdk/model/device.d.ts +9 -0
- package/build/sdk/studio/sdk/model/device.js.map +1 -1
- package/build/sdk/studio/sdk/model/deviceDeploymentEvent.d.ts +9 -0
- package/build/sdk/studio/sdk/model/deviceDeploymentEvent.js.map +1 -1
- package/build/sdk/studio/sdk/model/deviceWorkload.d.ts +12 -0
- package/build/sdk/studio/sdk/model/deviceWorkload.js +4 -0
- package/build/sdk/studio/sdk/model/deviceWorkload.js.map +1 -0
- package/build/sdk/studio/sdk/model/deviceWorkloadModel.d.ts +13 -0
- package/build/sdk/studio/sdk/model/deviceWorkloadModel.js +4 -0
- package/build/sdk/studio/sdk/model/deviceWorkloadModel.js.map +1 -0
- package/build/sdk/studio/sdk/model/impulseType.d.ts +4 -2
- package/build/sdk/studio/sdk/model/impulseType.js +1 -1
- package/build/sdk/studio/sdk/model/impulseType.js.map +1 -1
- package/build/sdk/studio/sdk/model/inferenceHistoryAggregate.d.ts +8 -0
- package/build/sdk/studio/sdk/model/learnBlock.d.ts +2 -1
- package/build/sdk/studio/sdk/model/learnBlockType.d.ts +2 -3
- package/build/sdk/studio/sdk/model/learnBlockType.js +1 -1
- package/build/sdk/studio/sdk/model/learnBlockType.js.map +1 -1
- package/build/sdk/studio/sdk/model/models.d.ts +2 -0
- package/build/sdk/studio/sdk/model/models.js +2 -0
- package/build/sdk/studio/sdk/model/models.js.map +1 -1
- package/build/sdk/studio/sdk/model/monitoringEventContext.d.ts +8 -0
- package/build/sdk/studio/sdk/model/monitoringEventEvaluationConfig.d.ts +4 -2
- package/build/sdk/studio/sdk/model/monitoringEventEvaluationConfig.js +1 -1
- package/build/sdk/studio/sdk/model/monitoringEventEvaluationConfig.js.map +1 -1
- package/build/sdk/studio/sdk/model/organizationTransferLearningOperatesOn.d.ts +1 -1
- package/build/sdk/studio/sdk/model/organizationTransferLearningOperatesOn.js +1 -1
- package/build/sdk/studio/sdk/model/organizationTransferLearningOperatesOn.js.map +1 -1
- package/package.json +4 -1
- package/test/agent-bundle-lifecycle.test.ts +445 -0
- package/test/agent-client.test.ts +246 -16
- package/test/agent-command-processor.test.ts +194 -0
- package/test/agent-runner-configuration.test.ts +110 -0
- package/test/agent-runner-integration.test.ts +330 -0
- package/test/model-monitor.test.ts +121 -0
- package/test/monitoring-policy-protocol.test.ts +62 -0
- package/test/utils/agent-runner-fixtures.ts +132 -0
- package/test/agent-runner-metadata.test.ts +0 -31
- package/test/sensor-selection.test.ts +0 -26
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
import assert from 'node:assert';
|
|
2
|
+
import { spawn, ChildProcess } from 'node:child_process';
|
|
3
|
+
import fs from 'node:fs/promises';
|
|
4
|
+
import http, { ServerResponse } from 'node:http';
|
|
5
|
+
import net from 'node:net';
|
|
6
|
+
import os from 'node:os';
|
|
7
|
+
import Path from 'node:path';
|
|
8
|
+
import {
|
|
9
|
+
ActivateBundleCommand,
|
|
10
|
+
CommandResult,
|
|
11
|
+
EventBatch,
|
|
12
|
+
InferenceRunnerRegistration,
|
|
13
|
+
} from '../shared/device-protocol/workload-contract';
|
|
14
|
+
import { writeBundle } from './utils/agent-runner-fixtures';
|
|
15
|
+
|
|
16
|
+
/** Requests observed by the fake agent across the retiring and replacement workload sessions. */
|
|
17
|
+
type AgentObservations = {
|
|
18
|
+
registrations: InferenceRunnerRegistration[];
|
|
19
|
+
results: CommandResult[];
|
|
20
|
+
events: EventBatch[];
|
|
21
|
+
commandStreams: number;
|
|
22
|
+
commandStream?: ServerResponse;
|
|
23
|
+
pendingEventResponse?: ServerResponse;
|
|
24
|
+
holdNextEvent: boolean;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
/** Exit details retained before assertions begin so an early runner failure cannot be missed. */
|
|
28
|
+
type ProcessExit = {
|
|
29
|
+
code: number | null;
|
|
30
|
+
signal: NodeJS.Signals | null;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
/** Retains one runner process, its diagnostics and its single eventual exit observation. */
|
|
34
|
+
type SpawnedRunner = {
|
|
35
|
+
child: ChildProcess;
|
|
36
|
+
output: Buffer[];
|
|
37
|
+
exited: Promise<ProcessExit>;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Exercises the externally visible agent-managed CLI flow using real runner processes and a fake
|
|
42
|
+
* workload API. Startup registers empty state, activation commits model 1 and serves inference, and
|
|
43
|
+
* replacement closes inference, flushes pending events and exits for supervisor restart. A fresh
|
|
44
|
+
* process then registers empty state, receives the replayed command, prepares changed sensor metadata,
|
|
45
|
+
* commits model 2 and reports subsequent inference against that new canonical identity.
|
|
46
|
+
*/
|
|
47
|
+
describe('agent-managed runner process', () => {
|
|
48
|
+
// The real process must commit canonical metadata, serve inference, then retire atomically for replacement.
|
|
49
|
+
it('activates an initial bundle, retires, then activates the replayed replacement', async () => {
|
|
50
|
+
// Arrange a complete local workload boundary: staged bundles, agent socket and inference port.
|
|
51
|
+
const tempDir = await fs.mkdtemp(Path.join(os.tmpdir(), 'ei-agent-runner-'));
|
|
52
|
+
const socketPath = Path.join(tempDir, 'agent.sock');
|
|
53
|
+
const observations: AgentObservations = {
|
|
54
|
+
registrations: [],
|
|
55
|
+
results: [],
|
|
56
|
+
events: [],
|
|
57
|
+
commandStreams: 0,
|
|
58
|
+
holdNextEvent: true,
|
|
59
|
+
};
|
|
60
|
+
const agentServer = await startAgentServer(socketPath, observations);
|
|
61
|
+
const port = await availablePort();
|
|
62
|
+
const bundleOptions = {
|
|
63
|
+
thresholds: [{ id: 1, type: 'classification', min_score: 0.5 }],
|
|
64
|
+
classifyScore: 0.6,
|
|
65
|
+
};
|
|
66
|
+
// Replacement changes accelerometer to positional input, proving the fresh process prepares
|
|
67
|
+
// runtime metadata from the replayed bundle rather than retaining properties from model 1.
|
|
68
|
+
const first = await writeBundle(tempDir, { ...bundleOptions, deploymentVersion: 1, sensor: 2 });
|
|
69
|
+
const replacement = await writeBundle(tempDir, { ...bundleOptions, deploymentVersion: 2, sensor: 4 });
|
|
70
|
+
const runnerPath = Path.resolve(__dirname, '..', 'build', 'cli', 'linux', 'runner.js');
|
|
71
|
+
|
|
72
|
+
// Run the compiled CLI so this test covers its argument handling, lifecycle wiring and process exit.
|
|
73
|
+
const firstProcess = spawnRunner(runnerPath, socketPath, port);
|
|
74
|
+
let secondProcess: SpawnedRunner | undefined;
|
|
75
|
+
|
|
76
|
+
try {
|
|
77
|
+
// Initial startup registers an empty workload before the agent is allowed to select a bundle.
|
|
78
|
+
await waitFor(() => observations.commandStream !== undefined, 'runner command stream');
|
|
79
|
+
sendCommand(observations, first);
|
|
80
|
+
|
|
81
|
+
// Activation completes only after the model is prepared, the HTTP pipeline is serving and
|
|
82
|
+
// the agent has accepted a registration containing that model.
|
|
83
|
+
await waitFor(() => observations.registrations.length === 2, 'active model registration');
|
|
84
|
+
await waitFor(() => observations.results.some(result => result.commandId === first.id),
|
|
85
|
+
'initial activation result');
|
|
86
|
+
|
|
87
|
+
assert.deepStrictEqual(observations.registrations[0].models, []);
|
|
88
|
+
// Registration describes the original `.eim`; the 0.8 CLI override belongs only to runtime state.
|
|
89
|
+
assert.deepStrictEqual(observations.registrations[1].models[0]?.thresholds, [
|
|
90
|
+
{ id: 1, type: 'classification', min_score: 0.5 },
|
|
91
|
+
]);
|
|
92
|
+
assert.strictEqual(observations.results.find(result => result.commandId === first.id)?.success, true);
|
|
93
|
+
|
|
94
|
+
// A 0.6 result is filtered by the runtime 0.8 threshold while its raw event is posted to the agent.
|
|
95
|
+
const inference = await requestJson(port, '/api/features', { features: [ 0 ] });
|
|
96
|
+
assert.strictEqual(inference.statusCode, 200);
|
|
97
|
+
assert.deepStrictEqual((JSON.parse(inference.body) as { result: { classification: object } })
|
|
98
|
+
.result.classification, { value: 0 });
|
|
99
|
+
await waitFor(() => observations.events.length === 1, 'pending inference event');
|
|
100
|
+
assert.deepStrictEqual(
|
|
101
|
+
observations.events[0]?.events[0]?.results?.[0]?.result.classification,
|
|
102
|
+
{ value: 0.6 }
|
|
103
|
+
);
|
|
104
|
+
|
|
105
|
+
// Keep that event request pending, then replace the bundle. The retiring process must close
|
|
106
|
+
// inference immediately, leave the activation command unanswered and wait for the event flush.
|
|
107
|
+
sendCommand(observations, replacement);
|
|
108
|
+
await waitForAsync(async () => (await requestJson(port, '/', undefined)).statusCode === 503,
|
|
109
|
+
'inference shutdown gate');
|
|
110
|
+
|
|
111
|
+
// Accepting the pending event releases graceful shutdown and allows the supervisor restart exit.
|
|
112
|
+
observations.pendingEventResponse?.writeHead(200, { 'content-type': 'application/json' });
|
|
113
|
+
observations.pendingEventResponse?.end(JSON.stringify({ accepted: 1, dropped: 0 }));
|
|
114
|
+
observations.pendingEventResponse = undefined;
|
|
115
|
+
|
|
116
|
+
const termination = await firstProcess.exited;
|
|
117
|
+
assert.deepStrictEqual(
|
|
118
|
+
termination,
|
|
119
|
+
{ code: 75, signal: null },
|
|
120
|
+
Buffer.concat(firstProcess.output).toString('utf8')
|
|
121
|
+
);
|
|
122
|
+
assert.strictEqual(observations.results.some(result => result.commandId === replacement.id), false);
|
|
123
|
+
assert.strictEqual(observations.events[0]?.events[0]?.results?.[0]?.modelId, 'model-1');
|
|
124
|
+
|
|
125
|
+
// A fresh process advertises empty state before the agent replays the unanswered command.
|
|
126
|
+
secondProcess = spawnRunner(runnerPath, socketPath, port);
|
|
127
|
+
await waitFor(
|
|
128
|
+
() => observations.commandStreams === 2 && observations.registrations.length === 3,
|
|
129
|
+
'replacement runner session'
|
|
130
|
+
);
|
|
131
|
+
assert.deepStrictEqual(observations.registrations[2].models, []);
|
|
132
|
+
sendCommand(observations, replacement);
|
|
133
|
+
|
|
134
|
+
// Replay completes only after model 2 is serving and registered as canonical.
|
|
135
|
+
await waitFor(() => observations.registrations.length === 4, 'replacement model registration');
|
|
136
|
+
await waitFor(
|
|
137
|
+
() => observations.results.some(result => result.commandId === replacement.id),
|
|
138
|
+
'replacement activation result'
|
|
139
|
+
);
|
|
140
|
+
assert.strictEqual(observations.registrations[3].models[0]?.id, 'model-2');
|
|
141
|
+
assert.strictEqual(
|
|
142
|
+
observations.results.find(result => result.commandId === replacement.id)?.success,
|
|
143
|
+
true
|
|
144
|
+
);
|
|
145
|
+
|
|
146
|
+
// Inference from the replacement process must report the new canonical model identity.
|
|
147
|
+
const replacementInference = await requestJson(port, '/api/features', { features: [ 0 ] });
|
|
148
|
+
assert.strictEqual(replacementInference.statusCode, 200);
|
|
149
|
+
await waitFor(() => observations.events.length === 2, 'replacement inference event');
|
|
150
|
+
assert.strictEqual(observations.events[1]?.events[0]?.results?.[0]?.modelId, 'model-2');
|
|
151
|
+
}
|
|
152
|
+
finally {
|
|
153
|
+
// Keep a failed assertion from leaving the fake agent or child runner alive for later tests.
|
|
154
|
+
observations.pendingEventResponse?.end();
|
|
155
|
+
observations.commandStream?.end();
|
|
156
|
+
await stopRunner(secondProcess);
|
|
157
|
+
await stopRunner(firstProcess);
|
|
158
|
+
await closeServer(agentServer);
|
|
159
|
+
await fs.rm(tempDir, { recursive: true, force: true });
|
|
160
|
+
}
|
|
161
|
+
}).timeout(15_000);
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
/** Starts the workload API needed to drive and observe a real runner process. */
|
|
165
|
+
async function startAgentServer(socketPath: string, observations: AgentObservations): Promise<http.Server> {
|
|
166
|
+
const server = http.createServer(async (request, response) => {
|
|
167
|
+
const body = await requestBody(request);
|
|
168
|
+
if (request.method === 'POST' && request.url === '/v1/register') {
|
|
169
|
+
// Retain both the empty startup registration and the canonical committed model registration.
|
|
170
|
+
observations.registrations.push(JSON.parse(body) as InferenceRunnerRegistration);
|
|
171
|
+
respondJson(response, {
|
|
172
|
+
workloadId: 'runner',
|
|
173
|
+
inputPolicy: { mode: 'none' },
|
|
174
|
+
inlineSizeLimitBytes: 1024,
|
|
175
|
+
});
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
if (request.method === 'GET' && request.url === '/v1/commands') {
|
|
179
|
+
// Hold the stream open so the test can deliver initial activation and replacement in order.
|
|
180
|
+
response.writeHead(200, {
|
|
181
|
+
'content-type': 'text/event-stream',
|
|
182
|
+
'cache-control': 'no-cache',
|
|
183
|
+
});
|
|
184
|
+
response.flushHeaders();
|
|
185
|
+
observations.commandStreams++;
|
|
186
|
+
observations.commandStream = response;
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
if (request.method === 'POST' && request.url?.startsWith('/v1/commands/') &&
|
|
190
|
+
request.url.endsWith('/result')) {
|
|
191
|
+
// Results reveal whether each command completed in this process or was left for replay.
|
|
192
|
+
observations.results.push(JSON.parse(body) as CommandResult);
|
|
193
|
+
respondJson(response, {});
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
if (request.method === 'POST' && request.url === '/v1/events') {
|
|
197
|
+
observations.events.push(JSON.parse(body) as EventBatch);
|
|
198
|
+
if (observations.holdNextEvent) {
|
|
199
|
+
// Hold the first event so replacement shutdown proves that close() flushes started events.
|
|
200
|
+
observations.holdNextEvent = false;
|
|
201
|
+
observations.pendingEventResponse = response;
|
|
202
|
+
}
|
|
203
|
+
else {
|
|
204
|
+
respondJson(response, { accepted: 1, dropped: 0 });
|
|
205
|
+
}
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
response.writeHead(404).end();
|
|
209
|
+
});
|
|
210
|
+
await new Promise<void>(resolve => server.listen(socketPath, resolve));
|
|
211
|
+
return server;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Sends one command record over the fake agent's established server-sent event stream. */
|
|
215
|
+
function sendCommand(observations: AgentObservations, command: ActivateBundleCommand): void {
|
|
216
|
+
if (!observations.commandStream) throw new Error('Command stream is not open');
|
|
217
|
+
observations.commandStream.write(`data: ${JSON.stringify(command)}\n\n`);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Starts the production CLI with the arguments shared by both supervised process generations. */
|
|
221
|
+
function spawnRunner(runnerPath: string, socketPath: string, port: number): SpawnedRunner {
|
|
222
|
+
const child = spawn(process.execPath, [
|
|
223
|
+
runnerPath,
|
|
224
|
+
'--agent', socketPath,
|
|
225
|
+
'--run-http-server', String(port),
|
|
226
|
+
'--force-target', 'test-target',
|
|
227
|
+
'--thresholds', '1.min_score=0.8',
|
|
228
|
+
'--shm-behavior', 'never',
|
|
229
|
+
'--dont-print-predictions',
|
|
230
|
+
], {
|
|
231
|
+
cwd: Path.resolve(__dirname, '..'),
|
|
232
|
+
env: { ...process.env, EI_RUNNER_IMAGE: 'runner:test' },
|
|
233
|
+
});
|
|
234
|
+
const output: Buffer[] = [];
|
|
235
|
+
child.stdout?.on('data', data => output.push(data));
|
|
236
|
+
child.stderr?.on('data', data => output.push(data));
|
|
237
|
+
return { child, output, exited: processExit(child) };
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** Terminates a surviving fixture process and waits briefly for its exit listener to settle. */
|
|
241
|
+
async function stopRunner(runner: SpawnedRunner | undefined): Promise<void> {
|
|
242
|
+
if (!runner) return;
|
|
243
|
+
if (runner.child.exitCode === null && runner.child.signalCode === null) runner.child.kill('SIGKILL');
|
|
244
|
+
await Promise.race([ runner.exited, new Promise(resolve => setTimeout(resolve, 1000)) ]);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Reserves and releases an ephemeral TCP port for the child runner's inference server. */
|
|
248
|
+
async function availablePort(): Promise<number> {
|
|
249
|
+
const server = net.createServer();
|
|
250
|
+
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
|
|
251
|
+
const address = server.address();
|
|
252
|
+
if (!address || typeof address === 'string') throw new Error('Cannot allocate an HTTP port');
|
|
253
|
+
await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
|
|
254
|
+
return address.port;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Posts optional JSON to the runner and returns its complete HTTP response. */
|
|
258
|
+
function requestJson(port: number, path: string, body: object | undefined): Promise<{
|
|
259
|
+
statusCode: number | undefined;
|
|
260
|
+
body: string;
|
|
261
|
+
}> {
|
|
262
|
+
const encoded = body === undefined ? undefined : JSON.stringify(body);
|
|
263
|
+
return new Promise((resolve, reject) => {
|
|
264
|
+
const request = http.request({
|
|
265
|
+
host: '127.0.0.1',
|
|
266
|
+
port,
|
|
267
|
+
path,
|
|
268
|
+
method: body === undefined ? 'GET' : 'POST',
|
|
269
|
+
headers: encoded === undefined ? undefined : {
|
|
270
|
+
'content-type': 'application/json',
|
|
271
|
+
'content-length': Buffer.byteLength(encoded),
|
|
272
|
+
},
|
|
273
|
+
}, response => {
|
|
274
|
+
let responseBody = '';
|
|
275
|
+
response.setEncoding('utf8');
|
|
276
|
+
response.on('data', chunk => responseBody += chunk);
|
|
277
|
+
response.on('end', () => resolve({ statusCode: response.statusCode, body: responseBody }));
|
|
278
|
+
});
|
|
279
|
+
request.on('error', reject);
|
|
280
|
+
request.end(encoded);
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** Resolves with one child exit even when it occurs before the test reaches its assertions. */
|
|
285
|
+
function processExit(child: ChildProcess): Promise<ProcessExit> {
|
|
286
|
+
return new Promise(resolve => child.once('exit', (code, signal) => resolve({ code, signal })));
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** Reads one small JSON request body from the fake agent transport. */
|
|
290
|
+
async function requestBody(request: http.IncomingMessage): Promise<string> {
|
|
291
|
+
let body = '';
|
|
292
|
+
request.setEncoding('utf8');
|
|
293
|
+
for await (const chunk of request) body += chunk;
|
|
294
|
+
return body;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** Completes one fake-agent request with a JSON response. */
|
|
298
|
+
function respondJson(response: ServerResponse, body: object): void {
|
|
299
|
+
response.writeHead(200, { 'content-type': 'application/json' });
|
|
300
|
+
response.end(JSON.stringify(body));
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** Waits for a synchronous observation without coupling the test to process scheduling. */
|
|
304
|
+
async function waitFor(predicate: () => boolean, description: string): Promise<void> {
|
|
305
|
+
const deadline = Date.now() + 10_000;
|
|
306
|
+
while (!predicate()) {
|
|
307
|
+
if (Date.now() >= deadline) throw new Error(`Timed out waiting for ${description}`);
|
|
308
|
+
await new Promise(resolve => setTimeout(resolve, 10));
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** Waits for an HTTP-observed state transition while tolerating connection setup races. */
|
|
313
|
+
async function waitForAsync(predicate: () => Promise<boolean>, description: string): Promise<void> {
|
|
314
|
+
const deadline = Date.now() + 10_000;
|
|
315
|
+
while (true) {
|
|
316
|
+
try {
|
|
317
|
+
if (await predicate()) return;
|
|
318
|
+
}
|
|
319
|
+
catch {
|
|
320
|
+
// The HTTP server may not yet be listening or may be between lifecycle operations.
|
|
321
|
+
}
|
|
322
|
+
if (Date.now() >= deadline) throw new Error(`Timed out waiting for ${description}`);
|
|
323
|
+
await new Promise(resolve => setTimeout(resolve, 10));
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** Stops the fake agent after its runner has released the open command stream. */
|
|
328
|
+
function closeServer(server: http.Server): Promise<void> {
|
|
329
|
+
return new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
|
|
330
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import assert from 'assert';
|
|
2
|
+
import fs from 'fs/promises';
|
|
3
|
+
import os from 'os';
|
|
4
|
+
import Path from 'path';
|
|
5
|
+
import { Config } from '../cli-common/config';
|
|
6
|
+
import { ImpulseRecord, ModelMonitor } from '../cli-common/model-monitor';
|
|
7
|
+
import { ModelInformation } from '../library/classifier/linux-impulse-runner-types';
|
|
8
|
+
|
|
9
|
+
describe('model monitoring summary cadence', () => {
|
|
10
|
+
for (const interval of [ undefined, 5_000, 10_000, 60_000, 120_000 ]) {
|
|
11
|
+
it(`starts safely with configured interval ${interval ?? 'automatic'}`, async () => {
|
|
12
|
+
const storagePath = await fs.mkdtemp(Path.join(os.tmpdir(), 'mm-cadence-'));
|
|
13
|
+
try {
|
|
14
|
+
const config = {
|
|
15
|
+
getDeploymentVersion: async () => 1,
|
|
16
|
+
getStoragePath: async () => Path.join(storagePath, '1', '1'),
|
|
17
|
+
getDefaultStoragePath: () => storagePath,
|
|
18
|
+
getStorageMaxSizeMb: async () => undefined,
|
|
19
|
+
getStorageIndex: async () => 0,
|
|
20
|
+
getMonitorSummaryIntervalMs: async () => interval,
|
|
21
|
+
} as unknown as Config;
|
|
22
|
+
const model = {
|
|
23
|
+
project: { id: 1 },
|
|
24
|
+
modelParameters: {
|
|
25
|
+
model_type: 'classification', has_anomaly: 0,
|
|
26
|
+
thresholds: [{ type: 'classification', min_score: 0.5 }],
|
|
27
|
+
},
|
|
28
|
+
} as unknown as ModelInformation;
|
|
29
|
+
const monitor = await ModelMonitor.getModelMonitor(config, model);
|
|
30
|
+
const calculator = (monitor as unknown as {
|
|
31
|
+
_metricsCalculator: { updateMetrics(record: ImpulseRecord): Promise<boolean> };
|
|
32
|
+
})._metricsCalculator;
|
|
33
|
+
const expectedInterval = Math.max(interval ?? 60_000, 60_000);
|
|
34
|
+
for (const elapsed of [ 0, expectedInterval - 1, expectedInterval ]) {
|
|
35
|
+
const record: ImpulseRecord = {
|
|
36
|
+
timestamp: 1_000_000 + elapsed,
|
|
37
|
+
index: elapsed,
|
|
38
|
+
rawData: { type: 'wav', bufferBase64: '' },
|
|
39
|
+
impulseRecord: {
|
|
40
|
+
result: { classification: { keyword: 0.9 } },
|
|
41
|
+
timing: { dsp: 1, classification: 1, anomaly: 0 },
|
|
42
|
+
info: undefined,
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
assert.strictEqual(await calculator.updateMetrics(record), elapsed === expectedInterval);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
finally {
|
|
49
|
+
await fs.rm(storagePath, { recursive: true, force: true });
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
describe('adaptive model monitoring cadence', () => {
|
|
57
|
+
for (const configured of [ undefined, 5_000, 10_000, 60_000 ]) {
|
|
58
|
+
it(`adapts an in-flight aggregate and preserves preference ${configured}`, async () => {
|
|
59
|
+
const storagePath = await fs.mkdtemp(Path.join(os.tmpdir(), 'mm-adaptive-'));
|
|
60
|
+
try {
|
|
61
|
+
const config = {
|
|
62
|
+
getDeploymentVersion: async () => 1,
|
|
63
|
+
getStoragePath: async () => Path.join(storagePath, '1', '1'),
|
|
64
|
+
getDefaultStoragePath: () => storagePath,
|
|
65
|
+
getStorageMaxSizeMb: async () => undefined,
|
|
66
|
+
getStorageIndex: async () => 0,
|
|
67
|
+
getMonitorSummaryIntervalMs: async () => configured,
|
|
68
|
+
} as unknown as Config;
|
|
69
|
+
const model = {
|
|
70
|
+
project: { id: 1 },
|
|
71
|
+
modelParameters: {
|
|
72
|
+
model_type: 'classification', has_anomaly: 0,
|
|
73
|
+
thresholds: [{ type: 'classification', min_score: 0.5 }],
|
|
74
|
+
},
|
|
75
|
+
} as unknown as ModelInformation;
|
|
76
|
+
const monitor = await ModelMonitor.getModelMonitor(config, model);
|
|
77
|
+
const calculator = (monitor as unknown as {
|
|
78
|
+
_metricsCalculator: {
|
|
79
|
+
updateMetrics(record: ImpulseRecord): Promise<boolean>;
|
|
80
|
+
getMetrics(): { start: { index: number }; end: { index: number } };
|
|
81
|
+
};
|
|
82
|
+
})._metricsCalculator;
|
|
83
|
+
const policy = { intervalMs: 60_000, minimumIntervalMs: 5_000,
|
|
84
|
+
preparationWindowMs: 0, requirementsMet: true };
|
|
85
|
+
monitor.applySummaryPolicy(policy);
|
|
86
|
+
assert.strictEqual(monitor.effectiveSummaryIntervalMs, configured ?? 60_000);
|
|
87
|
+
const update = (index: number, elapsed: number) => calculator.updateMetrics({
|
|
88
|
+
timestamp: 1_000_000 + elapsed, index,
|
|
89
|
+
rawData: { type: 'wav', bufferBase64: '' },
|
|
90
|
+
impulseRecord: { result: { classification: { keyword: 0.9 } },
|
|
91
|
+
timing: { dsp: 1, classification: 1, anomaly: 0 }, info: undefined },
|
|
92
|
+
});
|
|
93
|
+
assert.strictEqual(await update(0, 0), false);
|
|
94
|
+
assert.strictEqual(await update(1, 4_000), false);
|
|
95
|
+
monitor.applySummaryPolicy({ ...policy, intervalMs: 5_000, preparationWindowMs: 120_000 });
|
|
96
|
+
assert.strictEqual(await update(2, 5_100), true);
|
|
97
|
+
assert.deepStrictEqual([ calculator.getMetrics().start.index, calculator.getMetrics().end.index ],
|
|
98
|
+
[ 0, 2 ]);
|
|
99
|
+
assert.strictEqual(await update(3, 5_450), false);
|
|
100
|
+
monitor.applySummaryPolicy(policy);
|
|
101
|
+
const slower = configured ?? 60_000;
|
|
102
|
+
assert.strictEqual(await update(4, 5_450 + slower - 1), false);
|
|
103
|
+
assert.strictEqual(await update(5, 5_450 + slower), true);
|
|
104
|
+
assert.deepStrictEqual([ calculator.getMetrics().start.index, calculator.getMetrics().end.index ],
|
|
105
|
+
[ 3, 5 ]);
|
|
106
|
+
assert.strictEqual(monitor.configuredSummaryIntervalMs, configured);
|
|
107
|
+
monitor.applySummaryPolicy({ ...policy, intervalMs: NaN });
|
|
108
|
+
assert.strictEqual(monitor.effectiveSummaryIntervalMs, slower, 'invalid policy preserves last cadence');
|
|
109
|
+
monitor.applySummaryPolicy({ ...policy, intervalMs: 60_000, minimumIntervalMs: 60_000,
|
|
110
|
+
preparationWindowMs: 120_000, requirementsMet: false });
|
|
111
|
+
assert.strictEqual(monitor.effectiveSummaryIntervalMs, 60_000);
|
|
112
|
+
monitor.applySummaryPolicy(undefined);
|
|
113
|
+
assert.strictEqual(monitor.effectiveSummaryIntervalMs, 60_000,
|
|
114
|
+
'a server without policy support restores the safe legacy cadence');
|
|
115
|
+
}
|
|
116
|
+
finally {
|
|
117
|
+
await fs.rm(storagePath, { recursive: true, force: true });
|
|
118
|
+
}
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
});
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import assert from 'assert';
|
|
2
|
+
import { EventEmitter } from 'events';
|
|
3
|
+
import { RemoteMgmt } from '../cli-common/remote-mgmt-service';
|
|
4
|
+
import { MonitoringSummaryPolicy } from '../shared/device-protocol/remote-management';
|
|
5
|
+
|
|
6
|
+
describe('monitoring policy protocol', () => {
|
|
7
|
+
for (const supportsPolicy of [ false, true ]) {
|
|
8
|
+
it(`handles ${supportsPolicy ? 'new' : 'old'} servers and keeps policy messages separate from record ACKs`, async () => {
|
|
9
|
+
const policies: (MonitoringSummaryPolicy | undefined)[] = [];
|
|
10
|
+
const sent: { hello?: { supportsMonitoringSummaryPolicy: boolean };
|
|
11
|
+
getMonitoringSummaryPolicy?: boolean }[] = [];
|
|
12
|
+
const ws = Object.assign(new EventEmitter(), {
|
|
13
|
+
send: (data: string) => { sent.push(JSON.parse(data)); }, ping: () => undefined,
|
|
14
|
+
});
|
|
15
|
+
const policy: MonitoringSummaryPolicy = { intervalMs: 5_000, minimumIntervalMs: 5_000,
|
|
16
|
+
preparationWindowMs: 120_000, requirementsMet: true };
|
|
17
|
+
// Use the real dispatch/Hello methods without opening sockets or installing the reconnect timer.
|
|
18
|
+
const remote = Object.assign(Object.create(RemoteMgmt.prototype), {
|
|
19
|
+
_ws: ws, _projectId: 1, _devKeys: { apiKey: 'test' },
|
|
20
|
+
_eiConfig: { command: 'test', endpoints: { internal: { api: 'http://localhost/v1' } } },
|
|
21
|
+
_device: { connected: () => true, getDeviceId: async () => 'device',
|
|
22
|
+
getDeviceType: async () => 'test', getConnectionType: () => 'ip',
|
|
23
|
+
getSensors: () => [], supportsSnapshotStreaming: () => false },
|
|
24
|
+
_inferenceInfo: {},
|
|
25
|
+
_monitor: { getStorageStatus: async () => undefined,
|
|
26
|
+
applySummaryPolicy: (value: MonitoringSummaryPolicy | undefined) => policies.push(value),
|
|
27
|
+
abortImpulseRecordsRequest: () => { throw new Error('policy consumed as a record ACK'); } },
|
|
28
|
+
checkName: async () => 'test',
|
|
29
|
+
getProjectInfo: async () => ({ name: 'project' }),
|
|
30
|
+
}) as { attachWsHandlers(): void; sendHello(): Promise<void>; registerPingPong(): void };
|
|
31
|
+
remote.attachWsHandlers();
|
|
32
|
+
await remote.sendHello();
|
|
33
|
+
assert.strictEqual(sent[0].hello?.supportsMonitoringSummaryPolicy, true);
|
|
34
|
+
ws.emit('message', Buffer.from(JSON.stringify({ hello: true, serverTimestamp: 123,
|
|
35
|
+
...(supportsPolicy ? { supportsMonitoringSummaryPolicy: true, monitoringSummaryPolicy: policy } : {}),
|
|
36
|
+
})));
|
|
37
|
+
await new Promise(resolve => setImmediate(resolve));
|
|
38
|
+
assert.deepStrictEqual(policies, [ supportsPolicy ? policy : undefined ]);
|
|
39
|
+
const originalInterval = global.setInterval;
|
|
40
|
+
const originalTimeout = global.setTimeout;
|
|
41
|
+
try {
|
|
42
|
+
global.setInterval = ((fn: () => void, delay: number) => {
|
|
43
|
+
assert.strictEqual(delay, 30_000);
|
|
44
|
+
fn();
|
|
45
|
+
return 0;
|
|
46
|
+
}) as unknown as typeof setInterval;
|
|
47
|
+
global.setTimeout = (() => 0) as unknown as typeof setTimeout;
|
|
48
|
+
remote.registerPingPong();
|
|
49
|
+
}
|
|
50
|
+
finally {
|
|
51
|
+
global.setInterval = originalInterval;
|
|
52
|
+
global.setTimeout = originalTimeout;
|
|
53
|
+
}
|
|
54
|
+
assert.strictEqual(sent.some(message => message.getMonitoringSummaryPolicy), supportsPolicy);
|
|
55
|
+
ws.emit('message', Buffer.from(JSON.stringify({ monitoringSummaryPolicyUpdate: { ...policy, intervalMs: 60_000 } })));
|
|
56
|
+
ws.emit('message', Buffer.from(JSON.stringify({ impulseRecordAck: true, index: 1 })));
|
|
57
|
+
ws.emit('message', Buffer.from(JSON.stringify({ err: 'Policy lookup failed' })));
|
|
58
|
+
assert.strictEqual(policies.length, supportsPolicy ? 2 : 1);
|
|
59
|
+
if (supportsPolicy) assert.strictEqual(policies[1]?.intervalMs, 60_000);
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
});
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import Path from 'node:path';
|
|
4
|
+
import { ActivateBundleCommand, BlockThreshold } from '../../shared/device-protocol/workload-contract';
|
|
5
|
+
|
|
6
|
+
/** Selects the model identity and behavior exposed by a staged bundle fixture. */
|
|
7
|
+
export type BundleFixtureOptions = {
|
|
8
|
+
deploymentVersion: number;
|
|
9
|
+
sensor?: number;
|
|
10
|
+
inferencingEngine?: number;
|
|
11
|
+
manifestEngine?: string;
|
|
12
|
+
thresholds?: BlockThreshold[];
|
|
13
|
+
classifyScore?: number;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
/** Selects the protocol responses and termination behavior of a mock `.eim` process. */
|
|
17
|
+
export type MockEimOptions = {
|
|
18
|
+
deploymentVersion?: number;
|
|
19
|
+
sensor?: number;
|
|
20
|
+
inferencingEngine?: number;
|
|
21
|
+
thresholds?: BlockThreshold[];
|
|
22
|
+
classifyScore?: number;
|
|
23
|
+
exitAfterHello?: boolean;
|
|
24
|
+
killAfterHello?: boolean;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
/** Stages a valid model bundle beneath a test-owned directory. */
|
|
28
|
+
export async function writeBundle(
|
|
29
|
+
rootDirectory: string,
|
|
30
|
+
options: BundleFixtureOptions
|
|
31
|
+
): Promise<ActivateBundleCommand> {
|
|
32
|
+
const {
|
|
33
|
+
deploymentVersion,
|
|
34
|
+
sensor = 3,
|
|
35
|
+
inferencingEngine = 2,
|
|
36
|
+
manifestEngine = 'tflite',
|
|
37
|
+
thresholds = [],
|
|
38
|
+
classifyScore,
|
|
39
|
+
} = options;
|
|
40
|
+
const bundlePath = Path.join(rootDirectory, `bundle-${deploymentVersion}`);
|
|
41
|
+
const modelPath = Path.join(bundlePath, 'model.eim');
|
|
42
|
+
await fs.mkdir(bundlePath);
|
|
43
|
+
const source = mockEimSource({
|
|
44
|
+
deploymentVersion,
|
|
45
|
+
sensor,
|
|
46
|
+
inferencingEngine,
|
|
47
|
+
thresholds,
|
|
48
|
+
classifyScore,
|
|
49
|
+
});
|
|
50
|
+
await fs.writeFile(modelPath, source, { mode: 0o755 });
|
|
51
|
+
await fs.writeFile(Path.join(bundlePath, 'manifest.json'), JSON.stringify({
|
|
52
|
+
manifestVersion: 1,
|
|
53
|
+
kind: 'model',
|
|
54
|
+
target: 'test-target',
|
|
55
|
+
runtime: { kind: 'inference_runner', minVersion: '1.0.0' },
|
|
56
|
+
models: [{
|
|
57
|
+
id: `model-${deploymentVersion}`,
|
|
58
|
+
projectId: 1,
|
|
59
|
+
impulseId: 1,
|
|
60
|
+
deploymentVersion,
|
|
61
|
+
engine: manifestEngine,
|
|
62
|
+
modelType: 'classification',
|
|
63
|
+
path: 'model.eim',
|
|
64
|
+
sha256: createHash('sha256').update(source).digest('hex'),
|
|
65
|
+
}],
|
|
66
|
+
}));
|
|
67
|
+
return {
|
|
68
|
+
id: `activate-${deploymentVersion}`,
|
|
69
|
+
type: 'activateBundle',
|
|
70
|
+
bundle: { kind: 'model', path: bundlePath, deploymentVersion },
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Returns a protocol-compatible `.eim` executable with test-selected behavior. */
|
|
75
|
+
export function mockEimSource(options: MockEimOptions = {}): string {
|
|
76
|
+
const {
|
|
77
|
+
deploymentVersion = 1,
|
|
78
|
+
sensor = 2,
|
|
79
|
+
inferencingEngine = 2,
|
|
80
|
+
thresholds = [],
|
|
81
|
+
classifyScore,
|
|
82
|
+
exitAfterHello = false,
|
|
83
|
+
killAfterHello = false,
|
|
84
|
+
} = options;
|
|
85
|
+
return `#!/usr/bin/env node
|
|
86
|
+
const net = require('net');
|
|
87
|
+
const socketPath = process.argv[2];
|
|
88
|
+
const server = net.createServer(socket => {
|
|
89
|
+
let buffered = '';
|
|
90
|
+
socket.on('data', chunk => {
|
|
91
|
+
buffered += chunk.toString('utf8');
|
|
92
|
+
const lines = buffered.split('\\n');
|
|
93
|
+
buffered = lines.pop() || '';
|
|
94
|
+
for (const line of lines) {
|
|
95
|
+
if (!line) continue;
|
|
96
|
+
const request = JSON.parse(line);
|
|
97
|
+
if (request.hello === 1) {
|
|
98
|
+
socket.write(JSON.stringify({
|
|
99
|
+
id: request.id,
|
|
100
|
+
success: true,
|
|
101
|
+
project: { id: 1, name: 'Test', owner: 'Owner', deploy_version: ${deploymentVersion} },
|
|
102
|
+
model_parameters: {
|
|
103
|
+
axis_count: 1, frequency: 1, has_anomaly: 0, input_features_count: 1,
|
|
104
|
+
image_input_height: 1, image_input_width: 1, image_input_frames: 1,
|
|
105
|
+
image_channel_count: 3, image_resize_mode: 'squash', interval_ms: 1,
|
|
106
|
+
label_count: 1, sensor: ${sensor}, labels: [ 'value' ], model_type: 'classification',
|
|
107
|
+
use_continuous_mode: false, has_performance_calibration: false,
|
|
108
|
+
inferencing_engine: ${inferencingEngine}, thresholds: ${JSON.stringify(thresholds)}
|
|
109
|
+
},
|
|
110
|
+
inferencing_engine: { inferencing_engine: ${inferencingEngine}, properties: [] }
|
|
111
|
+
}) + '\\n');
|
|
112
|
+
if (${exitAfterHello}) setTimeout(() => process.exit(0), 20);
|
|
113
|
+
if (${killAfterHello}) setTimeout(() => process.kill(process.pid, 'SIGKILL'), 20);
|
|
114
|
+
}
|
|
115
|
+
else if (request.set_threshold) {
|
|
116
|
+
socket.write(JSON.stringify({ id: request.id, success: true }) + '\\n');
|
|
117
|
+
}
|
|
118
|
+
else if (request.classify && ${classifyScore !== undefined}) {
|
|
119
|
+
socket.write(JSON.stringify({
|
|
120
|
+
id: request.id,
|
|
121
|
+
success: true,
|
|
122
|
+
result: { classification: { value: ${classifyScore ?? 0} } },
|
|
123
|
+
timing: { dsp: 1, classification: 1, anomaly: 0 }
|
|
124
|
+
}) + '\\n');
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
});
|
|
129
|
+
server.listen(socketPath);
|
|
130
|
+
process.on('SIGINT', () => server.close(() => process.exit(0)));
|
|
131
|
+
`;
|
|
132
|
+
}
|