Исходный код СУБД 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
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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
package onnxruntime
 
import (
    "context"
    "errors"
    "math"
    "os"
    "path/filepath"
    "strings"
    "sync"
    "sync/atomic"
    "testing"
    "time"
)
 
func testdataPath(name string) string {
    return filepath.Join("..", "testdata", name)
}
 
func TestNewSessionAddModel(t *testing.T) {
    sess, err := NewSession(testdataPath("add_f32.onnx"), nil)
    if err != nil {
        t.Fatal(err)
    }
    defer sess.Close()
 
    inputs := sess.Inputs()
    if len(inputs) != 2 {
        t.Fatalf("expected 2 inputs, got %d", len(inputs))
    }
    for _, in := range inputs {
        if in.DataType != TensorElementDataTypeFloat32 {
            t.Errorf("input %s: expected Float32, got %s", in.Name, in.DataType)
        }
        if len(in.Shape) != 2 || in.Shape[0] != 2 || in.Shape[1] != 3 {
            t.Errorf("input %s: expected shape [2,3], got %v", in.Name, in.Shape)
        }
    }
 
    outputs := sess.Outputs()
    if len(outputs) != 1 {
        t.Fatalf("expected 1 output, got %d", len(outputs))
    }
    if outputs[0].DataType != TensorElementDataTypeFloat32 {
        t.Errorf("output dtype: expected Float32, got %s", outputs[0].DataType)
    }
}
 
func TestRunAddModel(t *testing.T) {
    sess, err := NewSession(testdataPath("add_f32.onnx"), nil)
    if err != nil {
        t.Fatal(err)
    }
    defer sess.Close()
 
    a := []float32{1, 2, 3, 4, 5, 6}
    b := []float32{10, 20, 30, 40, 50, 60}
    expected := []float32{11, 22, 33, 44, 55, 66}
 
    tensorA, err := CreateTensor[float32]([]int64{2, 3}, a)
    if err != nil {
        t.Fatal(err)
    }
    defer tensorA.Close()
 
    tensorB, err := CreateTensor[float32]([]int64{2, 3}, b)
    if err != nil {
        t.Fatal(err)
    }
    defer tensorB.Close()
 
    results, err := sess.Run(context.Background(), map[string]*Tensor{
        "A": tensorA,
        "B": tensorB,
    }, nil)
    if err != nil {
        t.Fatal(err)
    }
    defer func() {
        for _, r := range results {
            r.Close()
        }
    }()
 
    out, ok := results["C"]
    if !ok {
        t.Fatal("output C not found")
    }
 
    data, err := TensorData[float32](out)
    if err != nil {
        t.Fatal(err)
    }
 
    for i, v := range data {
        if math.Abs(float64(v-expected[i])) > 1e-6 {
            t.Errorf("output[%d]: expected %f, got %f", i, expected[i], v)
        }
    }
}
 
func TestNewSessionFromBytes(t *testing.T) {
    data, err := os.ReadFile(testdataPath("add_f32.onnx"))
    if err != nil {
        t.Fatal(err)
    }
    sess, err := NewSessionFromBytes(data, nil)
    if err != nil {
        t.Fatal(err)
    }
    defer sess.Close()
 
    if len(sess.Inputs()) != 2 {
        t.Fatalf("expected 2 inputs, got %d", len(sess.Inputs()))
    }
}
 
func TestDynamicShapeModel(t *testing.T) {
    sess, err := NewSession(testdataPath("matmul_dynamic.onnx"), nil)
    if err != nil {
        t.Fatal(err)
    }
    defer sess.Close()
 
    inputs := sess.Inputs()
    aInfo := inputs[0]
    hasDynamic := false
    for _, d := range aInfo.Shape {
        if d == -1 {
            hasDynamic = true
        }
    }
    if !hasDynamic {
        t.Errorf("expected dynamic dim (-1) in input shape, got %v", aInfo.Shape)
    }
 
    a := []float32{1, 0, 0, 1, 0, 1, 1, 0}
    b := []float32{1, 2, 3, 4, 5, 6, 7, 8}
 
    tensorA, err := CreateTensor[float32]([]int64{2, 4}, a)
    if err != nil {
        t.Fatal(err)
    }
    defer tensorA.Close()
 
    tensorB, err := CreateTensor[float32]([]int64{4, 2}, b)
    if err != nil {
        t.Fatal(err)
    }
    defer tensorB.Close()
 
    results, err := sess.Run(context.Background(), map[string]*Tensor{
        "A": tensorA,
        "B": tensorB,
    }, nil)
    if err != nil {
        t.Fatal(err)
    }
    defer func() {
        for _, r := range results {
            r.Close()
        }
    }()
 
    out := results["C"]
    if out.Shape()[0] != 2 || out.Shape()[1] != 2 {
        t.Errorf("expected output shape [2,2], got %v", out.Shape())
    }
}
 
func TestZeroLengthDimension(t *testing.T) {
    sess, err := NewSession(testdataPath("kvconcat.onnx"), nil)
    if err != nil {
        t.Fatal(err)
    }
    defer sess.Close()
 
    past, err := CreateTensor[float32]([]int64{1, 2, 0, 4}, []float32{})
    if err != nil {
        t.Fatal(err)
    }
    defer past.Close()
 
    newVal, err := CreateTensor[float32]([]int64{1, 2, 1, 4}, []float32{
        1, 2, 3, 4, 5, 6, 7, 8,
    })
    if err != nil {
        t.Fatal(err)
    }
    defer newVal.Close()
 
    results, err := sess.Run(context.Background(), map[string]*Tensor{
        "past":    past,
        "new_val": newVal,
    }, nil)
    if err != nil {
        t.Fatal(err)
    }
    defer func() {
        for _, r := range results {
            r.Close()
        }
    }()
 
    out := results["out"]
    if out == nil {
        t.Fatalf("output 'out' not found in results (keys: %v)", mapKeys(results))
    }
    if out.Shape()[2] != 1 {
        t.Errorf("expected concat output seq dim = 1 (0+1), got %v", out.Shape())
    }
}
 
func TestSubsetOutputNames(t *testing.T) {
    sess, err := NewSession(testdataPath("add_f32.onnx"), nil)
    if err != nil {
        t.Fatal(err)
    }
    defer sess.Close()
 
    a, _ := CreateTensor[float32]([]int64{2, 3}, []float32{1, 2, 3, 4, 5, 6})
    b, _ := CreateTensor[float32]([]int64{2, 3}, []float32{1, 1, 1, 1, 1, 1})
    defer a.Close()
    defer b.Close()
 
    results, err := sess.Run(context.Background(), map[string]*Tensor{
        "A": a, "B": b,
    }, []string{"C"})
    if err != nil {
        t.Fatal(err)
    }
    defer func() {
        for _, r := range results {
            r.Close()
        }
    }()
 
    if len(results) != 1 {
        t.Errorf("expected 1 output, got %d", len(results))
    }
}
 
func TestConcurrentRun(t *testing.T) {
    sess, err := NewSession(testdataPath("add_f32.onnx"), nil)
    if err != nil {
        t.Fatal(err)
    }
    defer sess.Close()
 
    var wg sync.WaitGroup
    errs := make(chan error, 16*50)
 
    for g := 0; g < 16; g++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            for i := 0; i < 50; i++ {
                a, _ := CreateTensor[float32]([]int64{2, 3}, []float32{1, 2, 3, 4, 5, 6})
                b, _ := CreateTensor[float32]([]int64{2, 3}, []float32{1, 1, 1, 1, 1, 1})
 
                results, err := sess.Run(context.Background(), map[string]*Tensor{
                    "A": a, "B": b,
                }, nil)
                a.Close()
                b.Close()
                if err != nil {
                    errs <- err
                    continue
                }
                for _, r := range results {
                    r.Close()
                }
            }
        }()
    }
 
    wg.Wait()
    close(errs)
    for err := range errs {
        t.Error(err)
    }
}
 
func TestCancelledContext(t *testing.T) {
    sess, err := NewSession(testdataPath("add_f32.onnx"), nil)
    if err != nil {
        t.Fatal(err)
    }
    defer sess.Close()
 
    ctx, cancel := context.WithCancel(context.Background())
    cancel()
 
    a, _ := CreateTensor[float32]([]int64{2, 3}, []float32{1, 2, 3, 4, 5, 6})
    b, _ := CreateTensor[float32]([]int64{2, 3}, []float32{1, 1, 1, 1, 1, 1})
    defer a.Close()
    defer b.Close()
 
    _, err = sess.Run(ctx, map[string]*Tensor{"A": a, "B": b}, nil)
    if err == nil {
        t.Fatal("expected error from cancelled context")
    }
}
 
func TestSessionOptions(t *testing.T) {
    opts, err := NewSessionOptions()
    if err != nil {
        t.Fatal(err)
    }
    defer opts.Close()
 
    if err := opts.SetIntraOpNumThreads(1); err != nil {
        t.Fatal(err)
    }
    if err := opts.SetInterOpNumThreads(1); err != nil {
        t.Fatal(err)
    }
    if err := opts.SetGraphOptimizationLevel(GraphOptimizationLevelAll); err != nil {
        t.Fatal(err)
    }
 
    sess, err := NewSession(testdataPath("add_f32.onnx"), opts)
    if err != nil {
        t.Fatal(err)
    }
    sess.Close()
}
 
func TestRunEmptyOutputNames(t *testing.T) {
    sess, err := NewSession(testdataPath("add_f32.onnx"), nil)
    if err != nil {
        t.Fatal(err)
    }
    defer sess.Close()
 
    a, _ := CreateTensor[float32]([]int64{2, 3}, []float32{1, 2, 3, 4, 5, 6})
    b, _ := CreateTensor[float32]([]int64{2, 3}, []float32{1, 1, 1, 1, 1, 1})
    defer a.Close()
    defer b.Close()
 
    _, err = sess.Run(context.Background(), map[string]*Tensor{
        "A": a, "B": b,
    }, []string{})
    if err == nil {
        t.Fatal("expected error for empty output names")
    }
}
 
func TestRunAfterClose(t *testing.T) {
    sess, err := NewSession(testdataPath("add_f32.onnx"), nil)
    if err != nil {
        t.Fatal(err)
    }
    sess.Close()
 
    a, _ := CreateTensor[float32]([]int64{2, 3}, []float32{1, 2, 3, 4, 5, 6})
    b, _ := CreateTensor[float32]([]int64{2, 3}, []float32{1, 1, 1, 1, 1, 1})
    defer a.Close()
    defer b.Close()
 
    _, err = sess.Run(context.Background(), map[string]*Tensor{
        "A": a, "B": b,
    }, nil)
    if err == nil {
        t.Fatal("expected error running on closed session")
    }
    if got := err.Error(); got != "ort: run: session is closed" {
        t.Errorf("unexpected error message: %s", got)
    }
}
 
func TestNewSessionFromBytesCorrupt(t *testing.T) {
    garbage := []byte("this is not a valid onnx model at all")
    _, err := NewSessionFromBytes(garbage, nil)
    if err == nil {
        t.Fatal("expected error for corrupt model bytes")
    }
}
 
func TestNewSessionFromBytesEmpty(t *testing.T) {
    _, err := NewSessionFromBytes(nil, nil)
    if err == nil {
        t.Fatal("expected error for nil model bytes")
    }
 
    _, err = NewSessionFromBytes([]byte{}, nil)
    if err == nil {
        t.Fatal("expected error for empty model bytes")
    }
}
 
func mapKeys(m map[string]*Tensor) []string {
    keys := make([]string, 0, len(m))
    for k := range m {
        keys = append(keys, k)
    }
    return keys
}
 
func TestRunNilTensor(t *testing.T) {
    sess, err := NewSession(testdataPath("add_f32.onnx"), nil)
    if err != nil {
        t.Fatal(err)
    }
    defer sess.Close()
 
    tensorA, err := CreateTensor[float32]([]int64{2, 3}, []float32{1, 2, 3, 4, 5, 6})
    if err != nil {
        t.Fatal(err)
    }
    defer tensorA.Close()
 
    _, err = sess.Run(context.Background(), map[string]*Tensor{
        "A": tensorA,
        "B": nil,
    }, nil)
    if err == nil {
        t.Fatal("expected error for nil input tensor")
    }
}
 
func TestRunClosedTensor(t *testing.T) {
    sess, err := NewSession(testdataPath("add_f32.onnx"), nil)
    if err != nil {
        t.Fatal(err)
    }
    defer sess.Close()
 
    tensorA, err := CreateTensor[float32]([]int64{2, 3}, []float32{1, 2, 3, 4, 5, 6})
    if err != nil {
        t.Fatal(err)
    }
    defer tensorA.Close()
 
    tensorB, err := CreateTensor[float32]([]int64{2, 3}, []float32{10, 20, 30, 40, 50, 60})
    if err != nil {
        t.Fatal(err)
    }
    _ = tensorB.Close()
 
    _, err = sess.Run(context.Background(), map[string]*Tensor{
        "A": tensorA,
        "B": tensorB,
    }, nil)
    if err == nil {
        t.Fatal("expected error for closed input tensor")
    }
}
 
// addModelInputs returns fresh inputs for add_f32.onnx and a cleanup func.
func addModelInputs(t testing.TB) (map[string]*Tensor, func()) {
    t.Helper()
 
    a, err := CreateTensor[float32]([]int64{2, 3}, []float32{1, 2, 3, 4, 5, 6})
    if err != nil {
        t.Fatal(err)
    }
    b, err := CreateTensor[float32]([]int64{2, 3}, []float32{10, 20, 30, 40, 50, 60})
    if err != nil {
        _ = a.Close()
        t.Fatal(err)
    }
    return map[string]*Tensor{"A": a, "B": b}, func() {
        _ = a.Close()
        _ = b.Close()
    }
}
 
func closeTensorMap(tensors map[string]*Tensor) {
    for _, tensor := range tensors {
        _ = tensor.Close()
    }
}
 
func TestRunWithOptionsCancelledBeforeCall(t *testing.T) {
    sess, err := NewSession(testdataPath("add_f32.onnx"), nil)
    if err != nil {
        t.Fatal(err)
    }
    defer sess.Close()
 
    opts, err := NewRunOptions()
    if err != nil {
        t.Fatal(err)
    }
    defer opts.Close()
 
    inputs, cleanup := addModelInputs(t)
    defer cleanup()
 
    ctx, cancel := context.WithCancel(context.Background())
    cancel()
 
    _, err = sess.RunWithOptions(ctx, opts, inputs, []string{"C"})
    if !errors.Is(err, context.Canceled) {
        t.Fatalf("expected context.Canceled, got %v", err)
    }
 
    results, err := sess.RunWithOptions(context.Background(), opts, inputs, []string{"C"})
    if err != nil {
        t.Fatalf("reusing run options after a cancelled run: %v", err)
    }
    closeTensorMap(results)
}
 
func TestRunWithOptionsExpiredDeadline(t *testing.T) {
    sess, err := NewSession(testdataPath("add_f32.onnx"), nil)
    if err != nil {
        t.Fatal(err)
    }
    defer sess.Close()
 
    opts, err := NewRunOptions()
    if err != nil {
        t.Fatal(err)
    }
    defer opts.Close()
 
    inputs, cleanup := addModelInputs(t)
    defer cleanup()
 
    ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second))
    defer cancel()
 
    _, err = sess.RunWithOptions(ctx, opts, inputs, []string{"C"})
    if !errors.Is(err, context.DeadlineExceeded) {
        t.Fatalf("expected context.DeadlineExceeded, got %v", err)
    }
}
 
// countingContext reports whether the run subscribed to cancellation.
type countingContext struct {
    context.Context
    doneCalls atomic.Int64
}
 
func (c *countingContext) Done() <-chan struct{} {
    c.doneCalls.Add(1)
    return c.Context.Done()
}
 
// TestRunWithOptionsWatchesContext pins that caller-supplied run options do not
// disable cancellation: the run must watch ctx.Done() so it can terminate an
// in-flight run, exactly as it does for the options it creates itself.
func TestRunWithOptionsWatchesContext(t *testing.T) {
    sess, err := NewSession(testdataPath("add_f32.onnx"), nil)
    if err != nil {
        t.Fatal(err)
    }
    defer sess.Close()
 
    opts, err := NewRunOptions()
    if err != nil {
        t.Fatal(err)
    }
    defer opts.Close()
 
    inputs, cleanup := addModelInputs(t)
    defer cleanup()
 
    base, cancel := context.WithCancel(context.Background())
    defer cancel()
    ctx := &countingContext{Context: base}
 
    results, err := sess.RunWithOptions(ctx, opts, inputs, []string{"C"})
    if err != nil {
        t.Fatal(err)
    }
    closeTensorMap(results)
 
    if ctx.doneCalls.Load() == 0 {
        t.Fatal("run never consulted ctx.Done(): cancellation is ignored when the caller supplies run options")
    }
}
 
// TestRunWithOptionsCancelledDuringRunKeepsOptionsUsable pins the terminate
// restore: the watcher sets the terminate flag on the caller's run options, and
// that flag is sticky, so leaving it set would abort the caller's next run.
// runInner is called directly because RunWithOptions rejects an already
// cancelled context before the watcher would ever start.
func TestRunWithOptionsCancelledDuringRunKeepsOptionsUsable(t *testing.T) {
    sess, err := NewSession(testdataPath("add_f32.onnx"), nil)
    if err != nil {
        t.Fatal(err)
    }
    defer sess.Close()
 
    opts, err := NewRunOptions()
    if err != nil {
        t.Fatal(err)
    }
    defer opts.Close()
 
    const iterations = 20
    terminated := 0
    for i := range iterations {
        inputs, cleanup := addModelInputs(t)
 
        ctx, cancel := context.WithCancel(context.Background())
        cancel()
 
        results, err := sess.runInner(ctx, inputs, []string{"C"}, opts)
        switch {
        case err == nil:
            // The run reached ORT's terminate check before the watcher fired; these
            // single-node models cannot be aborted once the kernel is running.
            closeTensorMap(results)
        case errors.Is(err, context.Canceled):
            terminated++
        default:
            cleanup()
            t.Fatalf("iteration %d: expected context.Canceled, got %v", i, err)
        }
 
        results, err = sess.RunWithOptions(context.Background(), opts, inputs, []string{"C"})
        if err != nil {
            cleanup()
            t.Fatalf("iteration %d: run options left terminated by the cancelled run: %v", i, err)
        }
        closeTensorMap(results)
        cleanup()
    }
    t.Logf("%d/%d cancellations reached ORT before the run finished", terminated, iterations)
}
 
// TestRunWithOptionsPreservesCallerTerminate pins that context cancellation
// restores a terminate flag which the caller had already set.
func TestRunWithOptionsPreservesCallerTerminate(t *testing.T) {
    sess, err := NewSession(testdataPath("add_f32.onnx"), nil)
    if err != nil {
        t.Fatal(err)
    }
    defer sess.Close()
 
    opts, err := NewRunOptions()
    if err != nil {
        t.Fatal(err)
    }
    defer opts.Close()
 
    inputs, cleanup := addModelInputs(t)
    defer cleanup()
 
    if err := opts.SetTerminate(); err != nil {
        t.Fatal(err)
    }
 
    ctx, cancel := context.WithCancel(context.Background())
    cancel()
 
    if _, err := sess.runInner(ctx, inputs, []string{"C"}, opts); !errors.Is(err, context.Canceled) {
        t.Fatalf("expected context.Canceled, got %v", err)
    }
    if _, err := sess.RunWithOptions(context.Background(), opts, inputs, []string{"C"}); err == nil {
        t.Fatal("context cancellation cleared the caller's pre-existing terminate flag")
    }
}
 
func TestRunWithClosedOptions(t *testing.T) {
    sess, err := NewSession(testdataPath("add_f32.onnx"), nil)
    if err != nil {
        t.Fatal(err)
    }
    defer sess.Close()
 
    opts, err := NewRunOptions()
    if err != nil {
        t.Fatal(err)
    }
    if err := opts.Close(); err != nil {
        t.Fatal(err)
    }
 
    inputs, cleanup := addModelInputs(t)
    defer cleanup()
 
    if _, err := sess.RunWithOptions(context.Background(), opts, inputs, []string{"C"}); err == nil {
        t.Fatal("expected error for closed run options")
    }
}
 
func TestNewSessionWithClosedOptions(t *testing.T) {
    opts, err := NewSessionOptions()
    if err != nil {
        t.Fatal(err)
    }
    if err := opts.Close(); err != nil {
        t.Fatal(err)
    }
 
    if _, err := NewSession(testdataPath("add_f32.onnx"), opts); err == nil {
        t.Fatal("expected error for closed session options")
    }
}
 
// TestRunWithOptionsReuseAfterCancelledRun cancels concurrently with the run, so
// the watcher fires before, during, and after the call, and requires the
// caller's run options to stay usable in every case.
func TestRunWithOptionsReuseAfterCancelledRun(t *testing.T) {
    sess, err := NewSession(testdataPath("add_f32.onnx"), nil)
    if err != nil {
        t.Fatal(err)
    }
    defer sess.Close()
 
    opts, err := NewRunOptions()
    if err != nil {
        t.Fatal(err)
    }
    defer opts.Close()
 
    inputs, cleanup := addModelInputs(t)
    defer cleanup()
 
    for i := range 50 {
        ctx, cancel := context.WithCancel(context.Background())
        go cancel()
 
        results, err := sess.RunWithOptions(ctx, opts, inputs, []string{"C"})
        if err != nil && !errors.Is(err, context.Canceled) {
            t.Fatalf("iteration %d: expected context.Canceled or success, got %v", i, err)
        }
        closeTensorMap(results)
 
        results, err = sess.RunWithOptions(context.Background(), opts, inputs, []string{"C"})
        if err != nil {
            t.Fatalf("iteration %d: run options left terminated by the cancelled run: %v", i, err)
        }
        closeTensorMap(results)
    }
}
 
// TestRunCancelRace shakes the run options Run creates for itself: cancelling
// around the moment the run finishes leaves the watcher parked on options that
// must not be released before it is joined.
func TestRunCancelRace(t *testing.T) {
    sess, err := NewSession(testdataPath("add_f32.onnx"), nil)
    if err != nil {
        t.Fatal(err)
    }
    defer sess.Close()
 
    const workers = 8
    const iterations = 40
 
    var wg sync.WaitGroup
    errs := make(chan error, workers*iterations)
    for range workers {
        inputs, cleanup := addModelInputs(t)
        defer cleanup()
 
        wg.Add(1)
        go func() {
            defer wg.Done()
            for i := range iterations {
                // Timeouts straddle the run duration, so cancellation lands before,
                // during, and just after the call into ORT.
                ctx, cancel := context.WithTimeout(context.Background(), time.Duration(i%20*10)*time.Microsecond)
                results, err := sess.Run(ctx, inputs, []string{"C"})
                cancel()
 
                if err != nil && !errors.Is(err, context.Canceled) && !errors.Is(err, context.DeadlineExceeded) {
                    errs <- err
                }
                closeTensorMap(results)
            }
        }()
    }
 
    wg.Wait()
    close(errs)
    for err := range errs {
        t.Error(err)
    }
}
 
func TestNewSessionUnicodePath(t *testing.T) {
    data, err := os.ReadFile(testdataPath("add_f32.onnx"))
    if err != nil {
        t.Fatal(err)
    }
 
    path := filepath.Join(t.TempDir(), "模型-mödel-🎉.onnx")
    if err := os.WriteFile(path, data, 0o600); err != nil {
        t.Fatal(err)
    }
 
    sess, err := NewSession(path, nil)
    if err != nil {
        t.Fatalf("load model from non-ASCII path: %v", err)
    }
    defer sess.Close()
 
    if len(sess.Inputs()) != 2 {
        t.Errorf("expected 2 inputs, got %d", len(sess.Inputs()))
    }
}
 
func TestNewSessionRejectsNULInPath(t *testing.T) {
    // Without the NUL check, the path is truncated at the NUL and the model at
    // the truncated path loads instead — silently ignoring what the caller asked for.
    sess, err := NewSession(testdataPath("add_f32.onnx")+"\x00ignored", nil)
    if err == nil {
        sess.Close()
        t.Fatal("expected error for path containing NUL byte, but a model loaded")
    }
    if !strings.Contains(err.Error(), "NUL") {
        t.Errorf("expected a NUL-byte error, got: %v", err)
    }
}
 
func TestRunRejectsNULInNames(t *testing.T) {
    sess, err := NewSession(testdataPath("add_f32.onnx"), nil)
    if err != nil {
        t.Fatal(err)
    }
    defer sess.Close()
 
    inputs, cleanup := addModelInputs(t)
    defer cleanup()
 
    badInputs := map[string]*Tensor{
        "A\x00ignored": inputs["A"],
        "B":            inputs["B"],
    }
    if _, err := sess.Run(context.Background(), badInputs, []string{"C"}); err == nil {
        t.Fatal("expected error for NUL in input name")
    }
    if _, err := sess.Run(context.Background(), inputs, []string{"C\x00ignored"}); err == nil {
        t.Fatal("expected error for NUL in output name")
    }
}
 
func TestRunRejectsDuplicateOutputNames(t *testing.T) {
    sess, err := NewSession(testdataPath("add_f32.onnx"), nil)
    if err != nil {
        t.Fatal(err)
    }
    defer sess.Close()
    inputs, cleanup := addModelInputs(t)
    defer cleanup()
 
    if _, err := sess.Run(context.Background(), inputs, []string{"C", "C"}); err == nil {
        t.Fatal("expected error for duplicate output names")
    }
}
 
func TestNilSessionClose(t *testing.T) {
    var session *Session
    if err := session.Close(); err != nil {
        t.Fatal(err)
    }
}
 
func BenchmarkSessionRun(b *testing.B) {
    sess, err := NewSession(testdataPath("add_f32.onnx"), nil)
    if err != nil {
        b.Fatal(err)
    }
    defer sess.Close()
 
    inputs, cleanup := addModelInputs(b)
    defer cleanup()
    outputNames := []string{"C"}
 
    b.ReportAllocs()
    b.ResetTimer()
    for b.Loop() {
        outputs, err := sess.Run(context.Background(), inputs, outputNames)
        if err != nil {
            b.Fatal(err)
        }
        for _, output := range outputs {
            _ = output.Close()
        }
    }
}