Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
 
import assert from 'assert';
import { spawn } from 'child_process';
import * as fs from 'fs';
import { InferenceSession, Tensor } from 'onnxruntime-common';
import * as path from 'path';
 
import { onnxruntimeBackend } from '../../../lib/backend';
import { binding } from '../../../lib/binding';
import { assertTensorEqual } from '../../test-utils';
 
const SQUEEZENET_INPUT0_DATA = require(path.join(__dirname, '../../testdata/squeezenet.input0.json'));
const SQUEEZENET_OUTPUT0_DATA = require(path.join(__dirname, '../../testdata/squeezenet.output0.json'));
 
const MODEL_PATH = path.join(__dirname, '../../testdata/squeezenet.onnx');
const SMALL_MODEL_PATH = path.join(__dirname, '../../testdata/test_types_float.onnx');
 
const validOptions = (): InferenceSession.SessionOptions => ({
  epContextDataRead: { callback: () => new Uint8Array(0), maxDataSize: 1024 * 1024 },
});
 
describe('UnitTests - InferenceSession.SessionOptions.epContextDataRead', () => {
  const createAny: any = InferenceSession.create;
 
  const assertTypeError = async (epContextDataRead: unknown) => {
    await assert.rejects(
      async () => {
        await createAny(SMALL_MODEL_PATH, { epContextDataRead });
      },
      { name: 'TypeError', message: /epContextDataRead/ },
    );
  };
 
  const assertRangeError = async (maxDataSize: unknown) => {
    await assert.rejects(
      async () => {
        await createAny(SMALL_MODEL_PATH, { epContextDataRead: { callback: () => new Uint8Array(0), maxDataSize } });
      },
      { name: 'RangeError', message: /epContextDataRead\.maxDataSize/ },
    );
  };
 
  // #region setup validation
 
  it('BAD CALL - epContextDataRead is not an object', async () => {
    await assertTypeError('yes please');
  });
  it('BAD CALL - epContextDataRead is a number', async () => {
    await assertTypeError(42);
  });
  it('BAD CALL - callback is missing', async () => {
    await assertTypeError({ maxDataSize: 1024 });
  });
  it('BAD CALL - callback is not a function', async () => {
    await assertTypeError({ callback: 'not a function', maxDataSize: 1024 });
  });
  it('BAD CALL - callback is null', async () => {
    await assertTypeError({ callback: null, maxDataSize: 1024 });
  });
  it('BAD CALL - maxDataSize is missing', async () => {
    await assertTypeError({ callback: () => new Uint8Array(0) });
  });
  it('BAD CALL - maxDataSize is not a number', async () => {
    await assertTypeError({ callback: () => new Uint8Array(0), maxDataSize: '1024' });
  });
  it('BAD CALL - maxDataSize is NaN', async () => {
    await assertRangeError(NaN);
  });
  it('BAD CALL - maxDataSize is Infinity', async () => {
    await assertRangeError(Infinity);
  });
  it('BAD CALL - maxDataSize is not an integer', async () => {
    await assertRangeError(1024.5);
  });
  it('BAD CALL - maxDataSize is zero', async () => {
    await assertRangeError(0);
  });
  it('BAD CALL - maxDataSize is negative', async () => {
    await assertRangeError(-1);
  });
  it('BAD CALL - maxDataSize is above Number.MAX_SAFE_INTEGER', async () => {
    await assertRangeError(Number.MAX_SAFE_INTEGER + 1);
  });
 
  it('epContextDataRead is optional', async () => {
    const session = await InferenceSession.create(SMALL_MODEL_PATH, {});
    await session.release();
  });
  it('epContextDataRead accepts undefined', async () => {
    const session = await createAny(SMALL_MODEL_PATH, { epContextDataRead: undefined });
    await session.release();
  });
  it('epContextDataRead accepts null', async () => {
    const session = await createAny(SMALL_MODEL_PATH, { epContextDataRead: null });
    await session.release();
  });
  it('epContextDataRead accepts a valid configuration', async () => {
    const session = await InferenceSession.create(SMALL_MODEL_PATH, validOptions());
    await session.release();
  });
  it('epContextDataRead accepts maxDataSize === 1', async () => {
    const session = await InferenceSession.create(SMALL_MODEL_PATH, {
      epContextDataRead: { callback: () => new Uint8Array(0), maxDataSize: 1 },
    });
    await session.release();
  });
 
  it('dispatches callback data through the native worker-thread bridge', async () => {
    const callbackName = 'context/data.bin';
    const backing = new Uint8Array([9, 1, 2, 3, 8]);
    let receivedName: string | undefined;
    const result = await binding.__testEpContextDataReadCallback(
      (name) => {
        receivedName = name;
        return backing.subarray(1, 4);
      },
      3,
      callbackName,
    );
 
    assert.strictEqual(receivedName, callbackName);
    assert.deepStrictEqual(result, Buffer.from([1, 2, 3]));
  });
 
  it('supports empty callback data through the native worker-thread bridge', async () => {
    const result = await binding.__testEpContextDataReadCallback(() => new Uint8Array(0), 1, 'empty.bin');
    assert.strictEqual(result.byteLength, 0);
  });
 
  it('rejects oversized, wrong-type, and throwing callback results through the native bridge', async () => {
    await assert.rejects(
      binding.__testEpContextDataReadCallback(() => new Uint8Array(2), 1, 'large.bin'),
      /exceeds/,
    );
    await assert.rejects(
      binding.__testEpContextDataReadCallback(() => new Uint8Array(1).buffer, 4, 'wrong.bin'),
      /Uint8Array/,
    );
    await assert.rejects(
      binding.__testEpContextDataReadCallback(
        () => {
          throw new Error('test callback failure');
        },
        4,
        'throw.bin',
      ),
      /test callback failure/,
    );
  });
 
  it('the callback is not invoked for a model without EPContext data', async function () {
    // eslint-disable-next-line no-invalid-this
    this.timeout(60000);
 
    let callCount = 0;
    const session = await InferenceSession.create(MODEL_PATH, {
      epContextDataRead: {
        callback: (name: string) => {
          callCount++;
          throw new Error(`unexpected callback for '${name}'`);
        },
        maxDataSize: 1024 * 1024,
      },
    });
    await session.release();
    assert.strictEqual(callCount, 0);
  });
  // #endregion
 
  // #region asynchronous session construction
 
  for (const source of ['path', 'buffer'] as const) {
    it(`defers native construction for a model ${source} without a callback`, async () => {
      let optionsRead = false;
      const pathOrBuffer = source === 'path' ? SMALL_MODEL_PATH : new Uint8Array(fs.readFileSync(SMALL_MODEL_PATH));
      const promise = onnxruntimeBackend.createInferenceSessionHandler(pathOrBuffer, {
        get graphOptimizationLevel(): InferenceSession.SessionOptions['graphOptimizationLevel'] {
          optionsRead = true;
          return 'disabled';
        },
      });
 
      assert.strictEqual(optionsRead, false, 'native construction ran before create returned its promise');
      await Promise.resolve();
      assert.strictEqual(optionsRead, false, 'native construction ran before the next event-loop turn');
 
      const session = await promise;
      try {
        assert.strictEqual(optionsRead, true, 'native construction did not inspect the session options');
        assert.deepStrictEqual(session.inputNames, ['input']);
      } finally {
        await session.dispose();
      }
    });
  }
 
  it('uses the synchronous fast path for a model path without a callback', async () => {
    const session = new binding.InferenceSession();
    const promise = session.loadModel(SMALL_MODEL_PATH, {});
 
    // The no-callback path finishes native construction before loadModel returns, while preserving
    // the Promise API for callers.
    assert.deepStrictEqual(
      session.inputMetadata.map(({ name }) => name),
      ['input'],
    );
    await promise;
    session.dispose();
  });
 
  it('uses the synchronous fast path for a model buffer without an effective callback', async () => {
    const modelData = new Uint8Array(fs.readFileSync(SMALL_MODEL_PATH));
    const session = new binding.InferenceSession();
    const promise = session.loadModel(modelData.buffer, modelData.byteOffset, modelData.byteLength, {
      epContextDataRead: null,
    } as unknown as InferenceSession.SessionOptions);
 
    assert.deepStrictEqual(
      session.inputMetadata.map(({ name }) => name),
      ['input'],
    );
    await promise;
    session.dispose();
  });
 
  it('the event loop stays available while the session is being created', async function () {
    // eslint-disable-next-line no-invalid-this
    this.timeout(60000);
 
    let ticks = 0;
    let settled = false;
    const spin = () => {
      if (settled) {
        return;
      }
      ticks++;
      setImmediate(spin);
    };
    setImmediate(spin);
 
    const session = await InferenceSession.create(MODEL_PATH, validOptions());
    const ticksDuringCreate = ticks;
    settled = true;
    await session.release();
 
    // A synchronous native session constructor would block the event loop, so the spin counter could
    // only advance a couple of times. Genuine asynchronous construction lets it advance freely.
    assert.ok(
      ticksDuringCreate > 5,
      `expected the event loop to keep running, but it only ticked ${ticksDuringCreate} times`,
    );
  });
 
  it('concurrent session creation', async function () {
    // eslint-disable-next-line no-invalid-this
    this.timeout(60000);
 
    const sessions = await Promise.all([
      InferenceSession.create(MODEL_PATH, validOptions()),
      InferenceSession.create(MODEL_PATH, validOptions()),
      InferenceSession.create(SMALL_MODEL_PATH, validOptions()),
    ]);
    for (const session of sessions) {
      await session.release();
    }
  });
  // #endregion
 
  // #region model buffer lifetime
 
  it('the model buffer stays alive until the native session is created', async function () {
    // eslint-disable-next-line no-invalid-this
    this.timeout(60000);
 
    // Wrap the model bytes in a view with a non-zero byteOffset so that the offset handling is covered.
    const modelBytes = fs.readFileSync(MODEL_PATH);
    const padded = new Uint8Array(modelBytes.byteLength + 8);
    padded.set(modelBytes, 8);
    let modelData: Uint8Array | null = padded.subarray(8);
 
    const promise = InferenceSession.create(modelData, validOptions());
    // Drop the only JavaScript reference to the view while the native session is still being created.
    modelData = null;
    global.gc?.();
 
    const session = await promise;
    assert.deepStrictEqual(session.inputNames, ['data_0']);
 
    const output = await session.run({
      data_0: new Tensor('float32', SQUEEZENET_INPUT0_DATA, [1, 3, 224, 224]),
    });
    assertTensorEqual(output.softmaxout_1, new Tensor('float32', SQUEEZENET_OUTPUT0_DATA, [1, 1000, 1, 1]));
    await session.release();
  });
 
  it('the model buffer can be transferred after session creation starts', async function () {
    // eslint-disable-next-line no-invalid-this
    this.timeout(60000);
 
    const modelData = new Uint8Array(fs.readFileSync(MODEL_PATH));
    const session = new binding.InferenceSession();
    const promise = session.loadModel(modelData.buffer, modelData.byteOffset, modelData.byteLength, validOptions());
    assert.throws(() => session.inputMetadata, /not initialized/i);
    structuredClone(modelData.buffer, { transfer: [modelData.buffer] });
    assert.strictEqual(modelData.byteLength, 0);
 
    await promise;
    assert.deepStrictEqual(
      session.inputMetadata.map(({ name }) => name),
      ['data_0'],
    );
    session.dispose();
  });
 
  it('EXPECTED FAILURE - empty buffer', async () => {
    await assert.rejects(
      async () => {
        await createAny(new Uint8Array(0), validOptions());
      },
      { name: 'Error', message: /Model data pointer is null./ },
    );
  });
  // #endregion
 
  // #region failed construction and disposal
 
  it('EXPECTED FAILURE - invalid model path', async () => {
    await assert.rejects(
      async () => {
        await createAny('/this/is/an/invalid/path.onnx', validOptions());
      },
      { name: 'Error', message: /failed/ },
    );
  });
 
  it('a failed session creation does not break the next one', async function () {
    // eslint-disable-next-line no-invalid-this
    this.timeout(60000);
 
    for (let i = 0; i < 3; i++) {
      await assert.rejects(async () => {
        await createAny('/this/is/an/invalid/path.onnx', validOptions());
      });
    }
 
    const session = await InferenceSession.create(SMALL_MODEL_PATH, validOptions());
    await session.release();
  });
 
  it('release() twice fails', async () => {
    const session = await InferenceSession.create(SMALL_MODEL_PATH, validOptions());
    await session.release();
    await assert.rejects(async () => {
      await session.release();
    }, /disposed/);
  });
 
  it('the session can be left unreleased', async () => {
    // The callback state is owned by the session wrapper and released by its finalizer.
    await InferenceSession.create(SMALL_MODEL_PATH, validOptions());
  });
  // #endregion
});
 
describe('UnitTests - InferenceSession.SessionOptions.epContextDataRead (standalone process)', () => {
  const runTest = async (
    args: string[] = [],
  ): Promise<{ code: number | null; signal: NodeJS.Signals | null; stdout: string; stderr: string }> =>
    new Promise((resolve, reject) => {
      const testFile = path.join(__dirname, '../../standalone/ep-context-data-read-main.js');
      const child = spawn('node', [testFile, ...args], { stdio: 'pipe' });
 
      let stdout = '';
      let stderr = '';
 
      child.stdout.on('data', (data) => (stdout += data.toString()));
      child.stderr.on('data', (data) => (stderr += data.toString()));
 
      child.on('close', (code, signal) => resolve({ code, signal, stdout, stderr }));
      child.on('error', reject);
    });
 
  // The callback must not keep the Node.js event loop alive: these processes never call process.exit(),
  // so a leaked thread-safe function reference would hang them until the test times out.
  it('the process exits after a successful session creation', async function () {
    // eslint-disable-next-line no-invalid-this
    this.timeout(60000);
 
    const result = await runTest();
    assert.strictEqual(result.signal, null, `process terminated by ${result.signal}`);
    assert.strictEqual(result.code, 0, result.stderr);
    assert.ok(result.stdout.includes('SUCCESS: Inference completed'), result.stdout);
  });
 
  it('the process exits after releasing the session', async function () {
    // eslint-disable-next-line no-invalid-this
    this.timeout(60000);
 
    const result = await runTest(['--release']);
    assert.strictEqual(result.signal, null, `process terminated by ${result.signal}`);
    assert.strictEqual(result.code, 0, result.stderr);
    assert.ok(result.stdout.includes('Session released'), result.stdout);
  });
 
  it('the process exits after a failed session creation', async function () {
    // eslint-disable-next-line no-invalid-this
    this.timeout(60000);
 
    const result = await runTest(['--fail-first']);
    assert.strictEqual(result.signal, null, `process terminated by ${result.signal}`);
    assert.strictEqual(result.code, 0, result.stderr);
    assert.ok(result.stdout.includes('SUCCESS: Session creation failed as expected'), result.stdout);
    assert.ok(result.stdout.includes('SUCCESS: Inference completed'), result.stdout);
  });
});