Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
 
import * as React from 'react';
import { ActivityIndicator, Button, ScrollView, StyleSheet, Text, View, Platform } from 'react-native';
import { InferenceSession, Tensor } from 'onnxruntime-react-native';
import { Buffer } from 'buffer';
import RNFS from 'react-native-fs';
 
interface CallbackTestWorker {
  abort(): void;
  forceInvalidate(): void;
  invalidateEnv(): void;
  waitForDispatch(): void;
  readonly isFinished: boolean;
  readonly wasAborted: boolean;
}
 
// Metro's inline requires can evaluate this module before the native bindings are installed.
const getOrtApi = () =>
  globalThis.OrtApi as typeof globalThis.OrtApi & {
    // eslint-disable-next-line @typescript-eslint/naming-convention
    __testEpContextDataReadCallback(
      callback: (name: string) => unknown,
      maxDataSize: number,
      name: string,
    ): Promise<Uint8Array> & {
      // eslint-disable-next-line @typescript-eslint/naming-convention
      readonly __testWorker: CallbackTestWorker;
    };
  };
 
interface TestResult {
  name: string;
  status: 'pending' | 'running' | 'success' | 'error';
  message?: string;
}
 
interface State {
  testResults: TestResult[];
  isRunning: boolean;
}
 
// A plain (non-EPContext) model. Registering the read callback must not disturb a session that
// never needs external EPContext data.
const MODEL_ASSET = 'test_types_float.ort';
 
const CHECK_NAMES = [
  'Missing callback is rejected',
  'Non-function callback is rejected',
  'Missing maxDataSize is rejected',
  'Zero maxDataSize is rejected',
  'Negative maxDataSize is rejected',
  'Fractional maxDataSize is rejected',
  'Infinite maxDataSize is rejected',
  'Unsafe integer maxDataSize is rejected',
  'Valid option loads and runs a session',
  'Repeated create/release keeps the callback alive',
  'Failed load releases the callback state',
  'Callback bridge marshals sliced Uint8Array data on the JS thread',
  'Callback bridge rejects invalid callback results',
  'Queued/in-flight callback reads and Env teardown unblock workers',
];
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 10,
    color: '#333',
  },
  subtitle: {
    fontSize: 16,
    marginBottom: 20,
    color: '#666',
  },
  buttonContainer: {
    marginBottom: 20,
  },
  summary: {
    fontSize: 16,
    fontWeight: '600',
    marginBottom: 12,
    color: '#333',
  },
  resultsContainer: {
    flex: 1,
  },
  testItem: {
    backgroundColor: '#fff',
    padding: 15,
    marginBottom: 10,
    borderRadius: 8,
    borderWidth: 1,
    borderColor: '#ddd',
  },
  testHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 5,
  },
  testName: {
    fontSize: 16,
    fontWeight: '600',
    color: '#333',
    flexShrink: 1,
    paddingRight: 10,
  },
  statusSuccess: {
    fontSize: 24,
    color: '#4CAF50',
    fontWeight: 'bold',
  },
  statusError: {
    fontSize: 24,
    color: '#F44336',
    fontWeight: 'bold',
  },
  statusPending: {
    fontSize: 24,
    color: '#999',
  },
  successMessage: {
    fontSize: 12,
    color: '#4CAF50',
    marginTop: 5,
  },
  errorMessage: {
    fontSize: 12,
    color: '#F44336',
    marginTop: 5,
  },
});
 
const readAsset = async (asset: string): Promise<Buffer> => {
  if (Platform.OS === 'android') {
    return Buffer.from(await RNFS.readFileAssets(asset, 'base64'), 'base64');
  } else {
    return Buffer.from(await RNFS.readFile(`${RNFS.MainBundlePath}/${asset}`, 'base64'), 'base64');
  }
};
 
// Avoids depending on TextEncoder, which is not available on every JS engine used by React Native.
const validCallback = (name: string): Uint8Array => {
  const bytes = new Uint8Array(name.length);
  for (let i = 0; i < name.length; i++) {
    bytes[i] = name.charCodeAt(i) % 256;
  }
  return bytes;
};
 
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
export default class EPContextDataReadTest extends React.PureComponent<{}, State> {
  private session: InferenceSession | undefined;
 
  // eslint-disable-next-line @typescript-eslint/no-empty-object-type
  constructor(props: {} | Readonly<{}>) {
    super(props);
 
    this.state = {
      testResults: CHECK_NAMES.map((name) => ({ name, status: 'pending' })),
      isRunning: false,
    };
  }
 
  async componentWillUnmount(): Promise<void> {
    await this.releaseSession();
  }
 
  releaseSession = async (): Promise<void> => {
    if (this.session) {
      const session = this.session;
      this.session = undefined;
      try {
        await session.release();
      } catch (err) {
        console.error('Error releasing EPContext data read session:', err);
      }
    }
  };
 
  updateTestResult = (index: number, update: Partial<TestResult>) => {
    if (update.status === 'error') {
      console.error(`EPContext data read check "${CHECK_NAMES[index]}" failed: ${update.message}`);
    }
    this.setState((prevState) => {
      const newResults = [...prevState.testResults];
      newResults[index] = { ...newResults[index], ...update };
      return { testResults: newResults };
    });
  };
 
  // Asserts that creating a session with the given options fails during option validation.
  expectRejected = async (bytes: Uint8Array, index: number, options: unknown): Promise<void> => {
    this.updateTestResult(index, { status: 'running' });
    let session: InferenceSession | undefined;
    try {
      session = await InferenceSession.create(bytes, options as InferenceSession.SessionOptions);
    } catch (err) {
      this.updateTestResult(index, {
        status: 'success',
        message: err instanceof Error ? err.message : String(err),
      });
      return;
    } finally {
      if (session) {
        await session.release();
      }
    }
    this.updateTestResult(index, {
      status: 'error',
      message: 'Session creation unexpectedly succeeded',
    });
  };
 
  runValidOptionCheck = async (bytes: Uint8Array, index: number): Promise<void> => {
    this.updateTestResult(index, { status: 'running' });
    try {
      let callbackCalls = 0;
      this.session = await InferenceSession.create(bytes, {
        epContextDataRead: {
          callback: (name: string) => {
            callbackCalls++;
            return validCallback(name);
          },
          maxDataSize: 1024 * 1024,
        },
      });
 
      const feeds: Record<string, Tensor> = {};
      feeds[this.session.inputNames[0]] = new Tensor('float32', new Float32Array([0, 1, 2, 3, 4]), [1, 5]);
      const output = await this.session.run(feeds);
      const outputTensor = output[this.session.outputNames[0]];
      if (!outputTensor || !outputTensor.data) {
        throw new Error('No output received');
      }
 
      await this.releaseSession();
 
      // The model has no external EPContext data, so ONNX Runtime must not invoke the callback.
      if (callbackCalls !== 0) {
        throw new Error(`Callback was invoked ${callbackCalls} time(s) for a model without EPContext data`);
      }
 
      this.updateTestResult(index, {
        status: 'success',
        message: `Output shape: [${outputTensor.dims.join(', ')}], callback invocations: ${callbackCalls}`,
      });
    } catch (err) {
      await this.releaseSession();
      this.updateTestResult(index, {
        status: 'error',
        message: err instanceof Error ? err.message : String(err),
      });
    }
  };
 
  runLifecycleCheck = async (bytes: Uint8Array, index: number): Promise<void> => {
    this.updateTestResult(index, { status: 'running' });
    try {
      for (let i = 0; i < 5; i++) {
        const session = await InferenceSession.create(bytes, {
          epContextDataRead: {
            callback: validCallback,
            maxDataSize: 16,
          },
        });
        // Releasing must drop the native callback state without disturbing later sessions.
        await session.release();
      }
      this.updateTestResult(index, {
        status: 'success',
        message: 'Created and released 5 sessions',
      });
    } catch (err) {
      this.updateTestResult(index, {
        status: 'error',
        message: err instanceof Error ? err.message : String(err),
      });
    }
  };
 
  // A session that fails to construct must release the callback state right away, and must leave a
  // subsequent load unaffected.
  runFailedLoadCheck = async (bytes: Uint8Array, index: number): Promise<void> => {
    this.updateTestResult(index, { status: 'running' });
    try {
      let callbackCalls = 0;
      const corrupted = Buffer.from(bytes);
      corrupted.fill(0, 0, Math.min(32, corrupted.length));
 
      let rejected = false;
      let badSession: InferenceSession | undefined;
      try {
        badSession = await InferenceSession.create(corrupted, {
          epContextDataRead: {
            callback: (name: string) => {
              callbackCalls++;
              return validCallback(name);
            },
            maxDataSize: 1024,
          },
        });
      } catch {
        rejected = true;
      }
      if (badSession) {
        await badSession.release();
      }
      if (!rejected) {
        throw new Error('Loading a corrupted model unexpectedly succeeded');
      }
      if (callbackCalls !== 0) {
        throw new Error(`Callback was invoked ${callbackCalls} time(s) for a model that failed to load`);
      }
 
      // The next session must still load and release normally.
      const session = await InferenceSession.create(bytes, {
        epContextDataRead: { callback: validCallback, maxDataSize: 1024 },
      });
      await session.release();
 
      this.updateTestResult(index, {
        status: 'success',
        message: 'Rejected load did not disturb the next session',
      });
    } catch (err) {
      this.updateTestResult(index, {
        status: 'error',
        message: err instanceof Error ? err.message : String(err),
      });
    }
  };
 
  runCallbackBridgeCheck = async (index: number): Promise<void> => {
    this.updateTestResult(index, { status: 'running' });
    try {
      const expectedName = 'context/data.bin';
      const result = await getOrtApi().__testEpContextDataReadCallback(
        (name) => {
          if (name !== expectedName) {
            throw new Error(`Unexpected callback name: ${name}`);
          }
          return new Uint8Array([9, 1, 2, 3, 8]).subarray(1, 4);
        },
        3,
        expectedName,
      );
      if (result.length !== 3 || result[0] !== 1 || result[1] !== 2 || result[2] !== 3) {
        throw new Error(`Unexpected callback bytes: ${Array.from(result).join(',')}`);
      }
 
      this.updateTestResult(index, {
        status: 'success',
        message: 'Callback name and sliced Uint8Array bytes were delivered across the native bridge',
      });
    } catch (err) {
      this.updateTestResult(index, {
        status: 'error',
        message: err instanceof Error ? err.message : String(err),
      });
    }
  };
 
  runCallbackBridgeFailureCheck = async (index: number): Promise<void> => {
    this.updateTestResult(index, { status: 'running' });
    try {
      for (const callback of [
        () => new Uint8Array(2),
        () => ({ not: 'bytes' }),
        () => {
          throw new Error('test callback failure');
        },
      ]) {
        let rejected = false;
        try {
          await getOrtApi().__testEpContextDataReadCallback(callback, 1, 'failure.bin');
        } catch {
          rejected = true;
        }
        if (!rejected) {
          throw new Error('Invalid callback result unexpectedly succeeded');
        }
      }
      const empty = await getOrtApi().__testEpContextDataReadCallback(() => new Uint8Array(0), 1, 'empty.bin');
      if (empty.length !== 0) {
        throw new Error('Expected an empty callback result');
      }
 
      this.updateTestResult(index, {
        status: 'success',
        message: 'Oversized, invalid, throwing, and empty callback results were handled',
      });
    } catch (err) {
      this.updateTestResult(index, {
        status: 'error',
        message: err instanceof Error ? err.message : String(err),
      });
    }
  };
 
  runCallbackBridgeCancellationCheck = async (index: number): Promise<void> => {
    this.updateTestResult(index, { status: 'running' });
    try {
      for (const mode of ['in-flight', 'queued', 'env'] as const) {
        const expectedName = `${mode}.bin`;
        let callbackCalls = 0;
        const pendingRead = getOrtApi().__testEpContextDataReadCallback(
          (name) => {
            callbackCalls++;
            if (name !== expectedName) {
              throw new Error(`Unexpected callback name: ${name}`);
            }
            if (mode === 'in-flight') {
              pendingRead.__testWorker.abort();
            }
            return new Uint8Array([1]);
          },
          1,
          expectedName,
        );
        void pendingRead.catch(() => undefined);
        // Do not yield before cancellation: queued reads must never enter the JS callback.
        if (mode === 'queued') {
          pendingRead.__testWorker.abort();
        } else if (mode === 'env') {
          try {
            pendingRead.__testWorker.waitForDispatch();
          } catch (err) {
            pendingRead.__testWorker.forceInvalidate();
            throw err;
          }
          pendingRead.__testWorker.invalidateEnv();
        }
 
        const deadline = Date.now() + 5000;
        while (!pendingRead.__testWorker.isFinished && Date.now() < deadline) {
          await new Promise<void>((resolve) => setTimeout(resolve, 10));
        }
        if (!pendingRead.__testWorker.isFinished) {
          pendingRead.__testWorker.forceInvalidate();
          throw new Error(`${mode} cancellation did not unblock the callback bridge worker`);
        }
        if (pendingRead.__testWorker.wasAborted !== (mode !== 'env')) {
          throw new Error(`Unexpected worker abort state for ${mode} cancellation`);
        }
        if (callbackCalls !== (mode === 'in-flight' ? 1 : 0)) {
          throw new Error(`Unexpected callback invocations for ${mode} cancellation: ${callbackCalls}`);
        }
        if (mode === 'env') {
          let rejection: unknown;
          try {
            await pendingRead;
          } catch (err) {
            rejection = err;
          }
          if (!/released|torn down/.test(String(rejection))) {
            throw new Error(`Env teardown did not reject the read with a release error: ${String(rejection)}`);
          }
        }
      }
 
      this.updateTestResult(index, {
        status: 'success',
        message: 'In-flight and queued aborts, plus Env listener teardown, completed their native workers',
      });
    } catch (err) {
      this.updateTestResult(index, {
        status: 'error',
        message: err instanceof Error ? err.message : String(err),
      });
    }
  };
 
  runAllTests = async (): Promise<void> => {
    this.setState({
      isRunning: true,
      testResults: CHECK_NAMES.map((name) => ({ name, status: 'pending' })),
    });
 
    try {
      const bytes = await readAsset(MODEL_ASSET);
      const paddedBytes = Buffer.alloc(bytes.length + 16);
      bytes.copy(paddedBytes, 8);
      const modelBytes = paddedBytes.subarray(8, 8 + bytes.length);
 
      await this.expectRejected(modelBytes, 0, { epContextDataRead: { maxDataSize: 1024 } });
      await this.expectRejected(modelBytes, 1, {
        epContextDataRead: { callback: 'not-a-function', maxDataSize: 1024 },
      });
      await this.expectRejected(modelBytes, 2, { epContextDataRead: { callback: validCallback } });
      await this.expectRejected(modelBytes, 3, { epContextDataRead: { callback: validCallback, maxDataSize: 0 } });
      await this.expectRejected(modelBytes, 4, { epContextDataRead: { callback: validCallback, maxDataSize: -1 } });
      await this.expectRejected(modelBytes, 5, { epContextDataRead: { callback: validCallback, maxDataSize: 1.5 } });
      await this.expectRejected(modelBytes, 6, {
        epContextDataRead: { callback: validCallback, maxDataSize: Number.POSITIVE_INFINITY },
      });
      await this.expectRejected(modelBytes, 7, {
        epContextDataRead: { callback: validCallback, maxDataSize: Number.MAX_SAFE_INTEGER + 2 },
      });
 
      await this.runValidOptionCheck(modelBytes, 8);
      await this.runLifecycleCheck(modelBytes, 9);
      await this.runFailedLoadCheck(modelBytes, 10);
      await this.runCallbackBridgeCheck(11);
      await this.runCallbackBridgeFailureCheck(12);
      await this.runCallbackBridgeCancellationCheck(13);
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err);
      console.error('Failed to run EPContext data read checks:', message);
      this.setState((prevState) => ({
        testResults: prevState.testResults.map((result) =>
          result.status === 'pending' || result.status === 'running' ? { ...result, status: 'error', message } : result,
        ),
      }));
    }
 
    this.setState({ isRunning: false });
  };
 
  render(): React.JSX.Element {
    const { testResults, isRunning } = this.state;
    const successCount = testResults.filter((result) => result.status === 'success').length;
    const errorCount = testResults.filter((result) => result.status === 'error').length;
    const summary = isRunning
      ? `${successCount}/${CHECK_NAMES.length} checks passed`
      : successCount === CHECK_NAMES.length
        ? `${successCount}/${CHECK_NAMES.length} checks passed`
        : errorCount > 0
          ? `${errorCount} check${errorCount === 1 ? '' : 's'} failed`
          : 'Ready to run';
 
    return (
      <View style={styles.container}>
        <Text style={styles.title}>EPContext Data Read Test</Text>
        <Text style={styles.subtitle}>Validate the epContextDataRead session option and its native lifetime</Text>
 
        <View style={styles.buttonContainer}>
          <Button
            title={isRunning ? 'Running Tests...' : 'Run All Tests'}
            onPress={this.runAllTests}
            disabled={isRunning}
            accessibilityLabel="run-tests-button"
          />
        </View>
 
        <Text style={styles.summary} accessibilityLabel="ep-context-data-read-summary">
          {summary}
        </Text>
 
        <ScrollView style={styles.resultsContainer}>
          {testResults.map((result) => (
            <View key={result.name} style={styles.testItem}>
              <View style={styles.testHeader}>
                <Text style={styles.testName}>{result.name}</Text>
                {result.status === 'running' && (
                  <ActivityIndicator size="small" color="#007AFF" accessibilityLabel="statusRunning" />
                )}
                {result.status === 'success' && (
                  <Text style={styles.statusSuccess} accessibilityLabel="statusSuccess">
                    ✓
                  </Text>
                )}
                {result.status === 'error' && (
                  <Text style={styles.statusError} accessibilityLabel="statusError">
                    ✗
                  </Text>
                )}
                {result.status === 'pending' && (
                  <Text style={styles.statusPending} accessibilityLabel="statusPending">
                    ○
                  </Text>
                )}
              </View>
              {result.message && (
                <Text style={result.status === 'error' ? styles.errorMessage : styles.successMessage}>
                  {result.message}
                </Text>
              )}
            </View>
          ))}
        </ScrollView>
      </View>
    );
  }
}