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
@@ -10,13 +10,14 @@ import {
10
10
  CommandResult,
11
11
  EventBatch,
12
12
  InferenceRunnerRegistration,
13
- } from '../shared/device-protocol/workload-contract';
13
+ } from '../shared/device-protocol/application-contract';
14
14
  import { writeBundle } from './utils/agent-runner-fixtures';
15
15
 
16
- /** Requests observed by the fake agent across the retiring and replacement workload sessions. */
16
+ /** Requests observed by the fake agent across the retiring and replacement application sessions. */
17
17
  type AgentObservations = {
18
18
  registrations: InferenceRunnerRegistration[];
19
19
  results: CommandResult[];
20
+ resultRegistrations: InferenceRunnerRegistration[];
20
21
  events: EventBatch[];
21
22
  commandStreams: number;
22
23
  commandStream?: ServerResponse;
@@ -39,7 +40,7 @@ type SpawnedRunner = {
39
40
 
40
41
  /**
41
42
  * 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
+ * application API. Startup registers empty state, activation commits model 1 and serves inference, and
43
44
  * replacement closes inference, flushes pending events and exits for supervisor restart. A fresh
44
45
  * process then registers empty state, receives the replayed command, prepares changed sensor metadata,
45
46
  * commits model 2 and reports subsequent inference against that new canonical identity.
@@ -47,12 +48,13 @@ type SpawnedRunner = {
47
48
  describe('agent-managed runner process', () => {
48
49
  // The real process must commit canonical metadata, serve inference, then retire atomically for replacement.
49
50
  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
+ // Arrange a complete local application boundary: staged bundles, agent socket and inference port.
51
52
  const tempDir = await fs.mkdtemp(Path.join(os.tmpdir(), 'ei-agent-runner-'));
52
53
  const socketPath = Path.join(tempDir, 'agent.sock');
53
54
  const observations: AgentObservations = {
54
55
  registrations: [],
55
56
  results: [],
57
+ resultRegistrations: [],
56
58
  events: [],
57
59
  commandStreams: 0,
58
60
  holdNextEvent: true,
@@ -72,9 +74,10 @@ describe('agent-managed runner process', () => {
72
74
  // Run the compiled CLI so this test covers its argument handling, lifecycle wiring and process exit.
73
75
  const firstProcess = spawnRunner(runnerPath, socketPath, port);
74
76
  let secondProcess: SpawnedRunner | undefined;
77
+ let thirdProcess: SpawnedRunner | undefined;
75
78
 
76
79
  try {
77
- // Initial startup registers an empty workload before the agent is allowed to select a bundle.
80
+ // Initial startup registers an empty application before the agent is allowed to select a bundle.
78
81
  await waitFor(() => observations.commandStream !== undefined, 'runner command stream');
79
82
  sendCommand(observations, first);
80
83
 
@@ -85,11 +88,14 @@ describe('agent-managed runner process', () => {
85
88
  'initial activation result');
86
89
 
87
90
  assert.deepStrictEqual(observations.registrations[0].models, []);
91
+ assert.deepStrictEqual(observations.registrations[0].capabilities, [ 'activateBundle', 'inputPolicy' ]);
92
+ assert.strictEqual(observations.registrations[0].activeBundle, undefined);
88
93
  // Registration describes the original `.eim`; the 0.8 CLI override belongs only to runtime state.
89
94
  assert.deepStrictEqual(observations.registrations[1].models[0]?.thresholds, [
90
95
  { id: 1, type: 'classification', min_score: 0.5 },
91
96
  ]);
92
97
  assert.strictEqual(observations.results.find(result => result.commandId === first.id)?.success, true);
98
+ assert.strictEqual(observations.resultRegistrations[0].models[0]?.deploymentVersion, 1);
93
99
 
94
100
  // A 0.6 result is filtered by the runtime 0.8 threshold while its raw event is posted to the agent.
95
101
  const inference = await requestJson(port, '/api/features', { features: [ 0 ] });
@@ -148,20 +154,55 @@ describe('agent-managed runner process', () => {
148
154
  assert.strictEqual(replacementInference.statusCode, 200);
149
155
  await waitFor(() => observations.events.length === 2, 'replacement inference event');
150
156
  assert.strictEqual(observations.events[1]?.events[0]?.results?.[0]?.modelId, 'model-2');
157
+ assert.strictEqual(observations.resultRegistrations[1].models[0]?.deploymentVersion, 2);
158
+
159
+ // Static rejection leaves B serving; runtime rejection happens only after a fresh restart.
160
+ const corrupt = await writeBundle(tempDir, { ...bundleOptions, deploymentVersion: 3 });
161
+ await fs.appendFile(Path.join(corrupt.bundle.path, 'model.eim'), '\nchanged');
162
+ sendCommand(observations, corrupt);
163
+ await waitFor(() => observations.results.some(result => result.commandId === corrupt.id),
164
+ 'static candidate rejection');
165
+ assert.strictEqual(observations.results.find(result => result.commandId === corrupt.id)?.success, false);
166
+ assert.strictEqual((await requestJson(port, '/api/features', { features: [ 0 ] })).statusCode, 200);
167
+
168
+ const badRuntime = await writeBundle(tempDir, { ...bundleOptions, deploymentVersion: 4,
169
+ mock: { deploymentVersion: 99 } });
170
+ sendCommand(observations, badRuntime);
171
+ assert.deepStrictEqual(await secondProcess.exited, { code: 75, signal: null });
172
+ assert.strictEqual(observations.results.some(result => result.commandId === badRuntime.id), false);
173
+ thirdProcess = spawnRunner(runnerPath, socketPath, port);
174
+ await waitFor(() => observations.commandStreams === 3, 'recovery runner session');
175
+ assert.deepStrictEqual(observations.registrations[observations.registrations.length - 1].models, []);
176
+ sendCommand(observations, badRuntime);
177
+ await waitFor(() => observations.results.some(result => result.commandId === badRuntime.id),
178
+ 'runtime candidate rejection after restart');
179
+ assert.strictEqual(observations.results.find(result => result.commandId === badRuntime.id)?.success, false);
180
+ const rollback = { ...first, id: 'rollback-to-1' };
181
+ sendCommand(observations, rollback);
182
+ await waitFor(() => observations.results.some(result => result.commandId === rollback.id),
183
+ 'rollback command registration and result');
184
+ assert.strictEqual(observations.results.find(result => result.commandId === rollback.id)?.success, true);
185
+ assert.strictEqual(observations.resultRegistrations[observations.resultRegistrations.length - 1]
186
+ .models[0]?.deploymentVersion, 1);
187
+ assert.strictEqual((await requestJson(port, '/api/features', { features: [ 0 ] })).statusCode, 200);
188
+ await waitFor(() => observations.events.length === 4, 'rollback inference event');
189
+ assert.strictEqual(observations.events[3]?.events[0]?.results?.[0]?.modelId, 'model-1');
190
+
151
191
  }
152
192
  finally {
153
193
  // Keep a failed assertion from leaving the fake agent or child runner alive for later tests.
154
194
  observations.pendingEventResponse?.end();
155
195
  observations.commandStream?.end();
196
+ await stopRunner(thirdProcess);
156
197
  await stopRunner(secondProcess);
157
198
  await stopRunner(firstProcess);
158
199
  await closeServer(agentServer);
159
200
  await fs.rm(tempDir, { recursive: true, force: true });
160
201
  }
161
- }).timeout(15_000);
202
+ }).timeout(25_000);
162
203
  });
163
204
 
164
- /** Starts the workload API needed to drive and observe a real runner process. */
205
+ /** Starts the application API needed to drive and observe a real runner process. */
165
206
  async function startAgentServer(socketPath: string, observations: AgentObservations): Promise<http.Server> {
166
207
  const server = http.createServer(async (request, response) => {
167
208
  const body = await requestBody(request);
@@ -169,7 +210,7 @@ async function startAgentServer(socketPath: string, observations: AgentObservati
169
210
  // Retain both the empty startup registration and the canonical committed model registration.
170
211
  observations.registrations.push(JSON.parse(body) as InferenceRunnerRegistration);
171
212
  respondJson(response, {
172
- workloadId: 'runner',
213
+ applicationId: 'runner',
173
214
  inputPolicy: { mode: 'none' },
174
215
  inlineSizeLimitBytes: 1024,
175
216
  });
@@ -190,6 +231,7 @@ async function startAgentServer(socketPath: string, observations: AgentObservati
190
231
  request.url.endsWith('/result')) {
191
232
  // Results reveal whether each command completed in this process or was left for replay.
192
233
  observations.results.push(JSON.parse(body) as CommandResult);
234
+ observations.resultRegistrations.push(observations.registrations[observations.registrations.length - 1]);
193
235
  respondJson(response, {});
194
236
  return;
195
237
  }
@@ -2154,7 +2154,7 @@ Freeing pipeline ...
2154
2154
  const devices = await testGetDevices({
2155
2155
  gstDeviceMonitor: () => gstMonitorOutput,
2156
2156
  gstInspect: () => gstInspectOutput,
2157
- modeOverride: 'qualcomm-yupik'
2157
+ modeOverride: 'jmo-perspec-1'
2158
2158
  });
2159
2159
  assert.equal(devices.length, 3);
2160
2160
  assert.equal(devices[0].id, '0');
@@ -0,0 +1,106 @@
1
+ import http from 'node:http';
2
+ import { InferenceRunnerRegistration } from '../../shared/device-protocol/application-contract';
3
+
4
+ /** Decoded request body exposed to a mock application API handler. */
5
+ export type MockAgentRequest = {
6
+ body: unknown;
7
+ };
8
+
9
+ /** HTTP response or open command stream returned by a mock application API route. */
10
+ export type MockAgentResponse = {
11
+ statusCode?: number;
12
+ headers?: http.OutgoingHttpHeaders;
13
+ body?: object | string;
14
+ keepOpen?: boolean;
15
+ };
16
+
17
+ /** Application API method and path paired with a fixed response or request handler. */
18
+ export type MockAgentRoute = {
19
+ method: 'GET' | 'POST';
20
+ path: string;
21
+ response: MockAgentResponse | ((request: MockAgentRequest) => MockAgentResponse | Promise<MockAgentResponse>);
22
+ };
23
+
24
+ /**
25
+ * Starts a mock device agent on a Unix socket. Routes declare the response data directly or provide
26
+ * a callback when a test needs to inspect a request, delay a response or record that a stream opened.
27
+ * Unregistered method/path combinations return HTTP 404.
28
+ *
29
+ * @param socketPath Unix socket on which the mock agent should listen.
30
+ * @param routes Application API routes and the responses they should return.
31
+ */
32
+ export async function mockAgentServer(socketPath: string, routes: MockAgentRoute[]): Promise<http.Server> {
33
+ const server = http.createServer(async (request, response) => {
34
+ const route = routes.find(candidate =>
35
+ candidate.method === request.method && candidate.path === request.url);
36
+ if (!route) {
37
+ response.writeHead(404).end();
38
+ return;
39
+ }
40
+
41
+ try {
42
+ let requestBody = '';
43
+ request.setEncoding('utf-8');
44
+ for await (const chunk of request) {
45
+ requestBody += chunk;
46
+ }
47
+ const mockRequest: MockAgentRequest = {
48
+ body: requestBody ? JSON.parse(requestBody) : undefined,
49
+ };
50
+ const mockResponse = typeof route.response === 'function' ?
51
+ await route.response(mockRequest) : route.response;
52
+ const statusCode = mockResponse.statusCode ?? 200;
53
+ const headers = { ...mockResponse.headers };
54
+ const body = typeof mockResponse.body === 'string' ?
55
+ mockResponse.body : mockResponse.body === undefined ? undefined : JSON.stringify(mockResponse.body);
56
+ if (typeof mockResponse.body === 'object' && !headers['content-type']) {
57
+ headers['content-type'] = 'application/json';
58
+ }
59
+ response.writeHead(statusCode, headers);
60
+ if (body !== undefined) {
61
+ response.write(body);
62
+ }
63
+ if (!mockResponse.keepOpen) {
64
+ response.end();
65
+ }
66
+ }
67
+ catch (error) {
68
+ response.writeHead(500).end(error instanceof Error ? error.message : String(error));
69
+ }
70
+ });
71
+ await new Promise<void>(resolve => server.listen(socketPath, resolve));
72
+ return server;
73
+ }
74
+
75
+ /**
76
+ * Returns the smallest valid inference-runner registration used to exercise the client transport
77
+ * independently of model loading.
78
+ */
79
+ export function testRegistration(): InferenceRunnerRegistration {
80
+ return {
81
+ kind: 'inference_runner',
82
+ version: '1.0.0',
83
+ contractVersion: 1,
84
+ artifact: {
85
+ kind: 'containerImage',
86
+ reference: 'inference-container:test',
87
+ },
88
+ models: [],
89
+ };
90
+ }
91
+
92
+ /**
93
+ * Waits for an asynchronous server observation so the tests can verify command-stream setup without
94
+ * coupling themselves to the exact ordering of Node.js HTTP callbacks.
95
+ *
96
+ * @param predicate Returns true once the expected server-side observation has occurred.
97
+ */
98
+ export async function waitFor(predicate: () => boolean) {
99
+ const deadline = Date.now() + 1000;
100
+ while (!predicate()) {
101
+ if (Date.now() >= deadline) {
102
+ throw new Error('Timed out waiting for condition');
103
+ }
104
+ await new Promise(resolve => setTimeout(resolve, 10));
105
+ }
106
+ }
@@ -1,3 +1,8 @@
1
+ /**
2
+ * Cover monitoring cadence and complete result streams using production calculators and storage.
3
+ * Stream tests control time and delay selected record writes to check window boundaries, delivery,
4
+ * and deployment replacement. Registry arithmetic cases live in summary-rules-fixtures.test.ts.
5
+ */
1
6
  import assert from 'assert';
2
7
  import fs from 'fs/promises';
3
8
  import os from 'os';
@@ -5,6 +10,7 @@ import Path from 'path';
5
10
  import { Config } from '../cli-common/config';
6
11
  import { ImpulseRecord, ModelMonitor } from '../cli-common/model-monitor';
7
12
  import { ModelInformation } from '../library/classifier/linux-impulse-runner-types';
13
+ import { deferred, MonitoringClock, monitoringFixture, monitoringModel, monitoringResult } from './monitoring-fixture';
8
14
 
9
15
  describe('model monitoring summary cadence', () => {
10
16
  for (const interval of [ undefined, 5_000, 10_000, 60_000, 120_000 ]) {
@@ -26,7 +32,9 @@ describe('model monitoring summary cadence', () => {
26
32
  thresholds: [{ type: 'classification', min_score: 0.5 }],
27
33
  },
28
34
  } as unknown as ModelInformation;
29
- const monitor = await ModelMonitor.getModelMonitor(config, model);
35
+ const monitor = await ModelMonitor.getModelMonitor(config, model, {
36
+ reportedThresholds: model.modelParameters.thresholds ?? [],
37
+ });
30
38
  const calculator = (monitor as unknown as {
31
39
  _metricsCalculator: { updateMetrics(record: ImpulseRecord): Promise<boolean> };
32
40
  })._metricsCalculator;
@@ -52,69 +60,256 @@ describe('model monitoring summary cadence', () => {
52
60
  }
53
61
  });
54
62
 
63
+ describe('monitoring result streams', () => {
64
+ let clock: MonitoringClock;
65
+
66
+ beforeEach(() => { clock = new MonitoringClock(); });
67
+ afterEach(() => { clock.restore(); });
68
+
69
+ const input = { type: 'wav' as const, buffer: Buffer.from([ 0, 1 ]) };
70
+ const policy = { intervalMs: 5_000, minimumIntervalMs: 5_000,
71
+ preparationWindowMs: 0, requirementsMet: true };
72
+
73
+ /**
74
+ * Feed a summary window, trigger its timer, then submit a boundary result while closure is queued.
75
+ * Exercise result- and timer-triggered closure of the next windows. Boundary results start new
76
+ * windows, while a late result stays retrievable without changing summaries. Idle time, repeated
77
+ * flushes and stop add no deliveries.
78
+ */
79
+ it('closes an idle window once while a boundary result waits behind timer closure', async () => {
80
+ const fixture = await monitoringFixture();
81
+ const initialTime = clock.now;
82
+ try {
83
+ fixture.monitor.applySummaryPolicy(policy);
84
+ await fixture.monitor.processResult(monitoringResult({ cat: 0.75, dog: 0.25 }), input);
85
+ clock.now = initialTime + 4_999;
86
+ await fixture.monitor.processResult(monitoringResult({ cat: 0.25, dog: 0.75 }), input);
87
+
88
+ clock.fireDue(initialTime + 5_000);
89
+ const boundary = fixture.monitor.processResult(monitoringResult({ cat: 0.5, dog: 0.5 }), input);
90
+ await boundary;
91
+ // Do not fire the next timer: this boundary result must itself close the previous window.
92
+ clock.now = initialTime + 10_000;
93
+ await fixture.monitor.processResult(monitoringResult({ cat: 0.75, dog: 0.25 }), input);
94
+ clock.fireDue(initialTime + 15_000);
95
+ await fixture.monitor.flushMetrics();
96
+ clock.now = initialTime + 14_999;
97
+ await fixture.monitor.processResult(monitoringResult({ obsolete: 1 }), input);
98
+ clock.fireDue(initialTime + 30_000);
99
+ await fixture.monitor.flushMetrics();
100
+ await fixture.monitor.stop();
101
+
102
+ assert.deepStrictEqual(fixture.summaries.map(summary => [ summary.start, summary.end ]), [
103
+ [{ index: 1, timestamp: initialTime }, { index: 2, timestamp: initialTime + 4_999 }],
104
+ [{ index: 3, timestamp: initialTime + 5_000 },
105
+ { index: 3, timestamp: initialTime + 5_000 }],
106
+ [{ index: 4, timestamp: initialTime + 10_000 },
107
+ { index: 4, timestamp: initialTime + 10_000 }],
108
+ ], 'boundary results start the next summary and idle periods add no empty summaries');
109
+ assert.deepStrictEqual(fixture.summaries.map(summary => summary.classificationCounter), [
110
+ [{ label: 'cat', value: 1 }, { label: 'dog', value: 1 }],
111
+ [{ label: 'cat', value: 1 }],
112
+ [{ label: 'cat', value: 1 }],
113
+ ]);
114
+ const saved = await fixture.saved();
115
+ assert.deepStrictEqual(saved.records.map(record => [ record.index, record.timestamp ]),
116
+ [ [ 1, initialTime ], [ 2, initialTime + 4_999 ], [ 3, initialTime + 5_000 ],
117
+ [ 4, initialTime + 10_000 ], [ 5, initialTime + 14_999 ] ]);
118
+ assert.deepStrictEqual(saved.records.map(record => record.impulseRecord.result.classification),
119
+ [{ cat: 0.75, dog: 0.25 }, { cat: 0.25, dog: 0.75 }, { cat: 0.5, dog: 0.5 },
120
+ { cat: 0.75, dog: 0.25 }, { obsolete: 1 }],
121
+ 'late results remain retrievable but cannot modify completed summaries');
122
+ }
123
+ finally {
124
+ await fixture.dispose();
125
+ }
126
+ });
127
+
128
+ /**
129
+ * Stream one JPEG record live, then read the same record through retained-record delivery.
130
+ * The live event must keep the original base64 image, while the JSON file stores a path and
131
+ * the retained-record response loads that file back into base64.
132
+ */
133
+ it('keeps live JPEG data intact while storing and reloading the image file', async () => {
134
+ const fixture = await monitoringFixture();
135
+ const jpeg = Buffer.from([ 0xff, 0xd8, 0xff, 0xd9 ]);
136
+ const live: ImpulseRecord[] = [];
137
+ try {
138
+ fixture.monitor.on('impulse-record', record => live.push(record));
139
+ fixture.monitor.impulseDebug = true;
140
+ await fixture.monitor.processResult(monitoringResult({ cat: 1 }), { type: 'jpg', buffer: jpeg });
141
+ assert.strictEqual(live.length, 1);
142
+ assert.strictEqual(live[0].rawData.bufferBase64, jpeg.toString('base64'));
143
+
144
+ const retained = new Promise<ImpulseRecord>(resolve => {
145
+ fixture.monitor.once('impulse-records-response', record => resolve(record as ImpulseRecord));
146
+ });
147
+ fixture.monitor.getImpulseRecords({ index: 1 });
148
+ assert.strictEqual((await retained).rawData.bufferBase64, jpeg.toString('base64'));
149
+
150
+ const saved = await fixture.saved();
151
+ assert.strictEqual(saved.records.length, 1);
152
+ assert.notStrictEqual(saved.records[0].rawData.bufferBase64, jpeg.toString('base64'));
153
+ assert.strictEqual(Path.extname(saved.records[0].rawData.bufferBase64), '.jpg');
154
+ }
155
+ finally {
156
+ await fixture.dispose();
157
+ }
158
+ });
159
+
160
+ /**
161
+ * Admit one result, reject a timestamp just within the backward-clock tolerance, then move farther
162
+ * backwards. The old window must close once, the corrected timeline must accept a new result, and
163
+ * its timer must close normally rather than repeatedly scheduling against the abandoned future grid.
164
+ */
165
+ it('starts a new window grid after a large backward wall-clock correction', async () => {
166
+ const fixture = await monitoringFixture();
167
+ const initialTime = clock.now;
168
+ try {
169
+ fixture.monitor.applySummaryPolicy(policy);
170
+ await fixture.monitor.processResult(monitoringResult({ cat: 1 }), input);
171
+
172
+ clock.now = initialTime - 10_000;
173
+ await fixture.monitor.processResult(monitoringResult({ dog: 1 }), input);
174
+ assert.strictEqual(fixture.summaries.length, 0, 'a slightly late result does not reset the grid');
175
+
176
+ clock.now = initialTime - 10_001;
177
+ await fixture.monitor.processResult(monitoringResult({ cat: 1 }), input);
178
+ assert.deepStrictEqual(fixture.summaries.map(summary => [ summary.start.index, summary.end.index ]),
179
+ [ [ 1, 1 ] ], 'the clock correction closes the future window without admitting late data');
180
+
181
+ clock.fireDue(initialTime - 5_001);
182
+ await fixture.monitor.flushMetrics();
183
+ assert.deepStrictEqual(fixture.summaries.map(summary => [ summary.start.index, summary.end.index ]),
184
+ [ [ 1, 1 ], [ 3, 3 ] ], 'the corrected grid closes once at its new deadline');
185
+ }
186
+ finally {
187
+ await fixture.dispose();
188
+ }
189
+ });
190
+
191
+ /**
192
+ * Hold the first record's save, queue a second result and flush the deployment before replacing it.
193
+ * Release the save and check that both accepted records contribute to the final old-model summary.
194
+ * Replace the deployment with different original/local cutoffs and verify its own files and original cutoff,
195
+ * retaining the reporting policy and leaving old files unchanged. A terminal stop remains terminal even if
196
+ * deployment state is subsequently replaced, and returning to old storage does not replay prior summaries.
197
+ */
198
+ it('separates replacement deployment history and keeps terminal stop irreversible', async () => {
199
+ const initialModel = monitoringModel();
200
+ const initialThresholds = initialModel.modelParameters.thresholds ?? [];
201
+ const fixture = await monitoringFixture(initialModel, { reportedThresholds: initialThresholds });
202
+ const initialTime = clock.now;
203
+ const saving = deferred<void>();
204
+ const release = deferred<void>();
205
+ const storeIndex = fixture.config.storeStorageIndex.bind(fixture.config);
206
+ try {
207
+ fixture.monitor.applySummaryPolicy(policy);
208
+ // Pause the first record's index write so the second admission and flush queue behind it.
209
+ fixture.config.storeStorageIndex = async index => {
210
+ saving.resolve();
211
+ await release.promise;
212
+ await storeIndex(index);
213
+ };
214
+ const first = fixture.monitor.processResult(monitoringResult({ cat: 0.75, dog: 0.25 }), input);
215
+ await saving.promise;
216
+ clock.now++;
217
+ const second = fixture.monitor.processResult(monitoringResult({ cat: 0.25, dog: 0.75 }), input);
218
+ const flushed = fixture.monitor.flushMetrics();
219
+ release.resolve();
220
+ await Promise.all([ first, second, flushed ]);
221
+ assert.strictEqual(fixture.summaries.length, 1);
222
+ const old = await fixture.saved(1);
223
+ assert.deepStrictEqual(old.records.map(record => record.index), [ 1, 2 ]);
224
+
225
+ const replacement = monitoringModel(2, 0.8);
226
+ const reportedThresholds = replacement.modelParameters.thresholds!.map(block => ({ ...block }));
227
+ replacement.modelParameters.thresholds![0].min_score = 0.1;
228
+ await fixture.config.setDeploymentVersion(2);
229
+ await fixture.monitor.replaceModel(fixture.config, replacement, { reportedThresholds });
230
+ assert.strictEqual(fixture.monitor.effectiveSummaryIntervalMs, 5_000, 'replacement retains the policy');
231
+ clock.now = initialTime + 10_000;
232
+ await fixture.monitor.processResult(monitoringResult({ cat: 0.75, dog: 0.25 }), input);
233
+ await fixture.monitor.flushMetrics();
234
+ assert.strictEqual(fixture.summaries.length, 2);
235
+ assert.deepStrictEqual(fixture.summaries[1].classificationCounter, [{ label: 'no prediction', value: 1 }]);
236
+ const current = await fixture.saved(2);
237
+ assert.strictEqual(current.records.length, 1);
238
+ assert.deepStrictEqual(await fixture.saved(1), old, 'replacement does not rewrite old deployment files');
239
+
240
+ // Returning to a prior deployment must not replay summaries delivered earlier in this session.
241
+ await fixture.config.setDeploymentVersion(1);
242
+ const replacing = fixture.monitor.replaceModel(fixture.config, initialModel, {
243
+ reportedThresholds: initialThresholds,
244
+ });
245
+ const stopped = fixture.monitor.stop();
246
+ await Promise.all([ replacing, stopped ]);
247
+ await fixture.monitor.processResult(monitoringResult({ discarded: 1 }), input);
248
+ assert.strictEqual(fixture.summaries.length, 2);
249
+ assert.deepStrictEqual(await fixture.saved(1), old);
250
+ }
251
+ finally {
252
+ // Failure cleanup must also unblock the queue before stopping the monitor.
253
+ release.resolve();
254
+ fixture.config.storeStorageIndex = storeIndex;
255
+ await fixture.dispose();
256
+ }
257
+ });
258
+ });
259
+
55
260
 
56
261
  describe('adaptive model monitoring cadence', () => {
57
262
  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-'));
263
+ it(`adapts an in-flight aggregate and preserves preference ${configured ?? 'automatic'}`, async () => {
264
+ const clock = new MonitoringClock();
265
+ const fixture = await monitoringFixture(monitoringModel(), {
266
+ configuredSummaryIntervalMs: configured,
267
+ });
268
+ const initialTime = clock.now;
269
+ const input = { type: 'wav' as const, buffer: Buffer.from([ 0, 1 ]) };
270
+ const policy = { intervalMs: 60_000, minimumIntervalMs: 5_000,
271
+ preparationWindowMs: 0, requirementsMet: true };
60
272
  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 },
273
+ fixture.monitor.applySummaryPolicy(policy);
274
+ assert.strictEqual(fixture.monitor.effectiveSummaryIntervalMs, configured ?? 60_000);
275
+ await fixture.monitor.processResult(monitoringResult({ cat: 0.9 }), input);
276
+ clock.now = initialTime + 4_000;
277
+ await fixture.monitor.processResult(monitoringResult({ cat: 0.9 }), input);
278
+
279
+ fixture.monitor.applySummaryPolicy({
280
+ ...policy,
281
+ intervalMs: 5_000,
282
+ preparationWindowMs: 120_000,
92
283
  });
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);
284
+ clock.now = initialTime + 5_000;
285
+ await fixture.monitor.processResult(monitoringResult({ cat: 0.9 }), input);
286
+ assert.deepStrictEqual(fixture.summaries.map(summary => [ summary.start.index, summary.end.index ]),
287
+ [ [ 1, 2 ] ], 'the boundary result starts the accelerated window');
288
+
101
289
  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,
290
+ fixture.monitor.applySummaryPolicy(policy);
291
+ assert.strictEqual(fixture.monitor.effectiveSummaryIntervalMs, slower);
292
+ clock.now = initialTime + 5_000 + slower - 1;
293
+ await fixture.monitor.processResult(monitoringResult({ cat: 0.9 }), input);
294
+ clock.now = initialTime + 5_000 + slower;
295
+ await fixture.monitor.processResult(monitoringResult({ cat: 0.9 }), input);
296
+ assert.deepStrictEqual(fixture.summaries.map(summary => [ summary.start.index, summary.end.index ]),
297
+ [ [ 1, 2 ], [ 3, 4 ] ], 'the relaxed cadence keeps the established window grid');
298
+
299
+ assert.strictEqual(fixture.monitor.configuredSummaryIntervalMs, configured);
300
+ fixture.monitor.applySummaryPolicy({ ...policy, intervalMs: NaN });
301
+ assert.strictEqual(fixture.monitor.effectiveSummaryIntervalMs, slower,
302
+ 'invalid policy preserves last cadence');
303
+ fixture.monitor.applySummaryPolicy({ ...policy, intervalMs: 60_000, minimumIntervalMs: 60_000,
110
304
  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');
305
+ assert.strictEqual(fixture.monitor.effectiveSummaryIntervalMs, 60_000);
306
+ fixture.monitor.applySummaryPolicy(undefined);
307
+ assert.strictEqual(fixture.monitor.effectiveSummaryIntervalMs, 60_000,
308
+ 'a server without policy support restores the conservative cadence');
115
309
  }
116
310
  finally {
117
- await fs.rm(storagePath, { recursive: true, force: true });
311
+ await fixture.dispose();
312
+ clock.restore();
118
313
  }
119
314
  });
120
315
  }