-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWorkerProcessPoolTests.cs
More file actions
1322 lines (1172 loc) · 48.7 KB
/
Copy pathWorkerProcessPoolTests.cs
File metadata and controls
1322 lines (1172 loc) · 48.7 KB
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
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Buffers.Binary;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using DotPython.Protocol;
using DotPython.Runtime.Native;
using DotPython.Worker;
using Xunit;
namespace DotPython.WorkerTests;
[SuppressMessage(
"Reliability",
"CA2007:Consider calling ConfigureAwait on the awaited task",
Justification = "xUnit tests intentionally resume in the test context."
)]
public sealed class WorkerProcessPoolTests
{
[Fact]
public async Task Worker_ImportsStableAbiModuleThroughManagedExecution()
{
SkipNativeFixtureOnWindows();
await using var pool = new WorkerProcessPool(CreateOptions(stableAbiModule: true));
await using var session = await pool.OpenSessionAsync(
TestContext.Current.CancellationToken
);
var result = await session.ExecuteAsync(
"import dotpython_fixture\nprint(dotpython_fixture.increment(41))",
cancellationToken: TestContext.Current.CancellationToken
);
var failure = await session.ExecuteAsync(
"import dotpython_fixture\ndotpython_fixture.fail()",
cancellationToken: TestContext.Current.CancellationToken
);
Assert.True(result.Success, string.Join(Environment.NewLine, result.Diagnostics));
Assert.Equal("42" + Environment.NewLine, result.StandardOutput);
Assert.False(failure.Success);
Assert.Contains(
failure.Diagnostics,
diagnostic =>
diagnostic.Code == "DPY8005"
&& diagnostic.Message.Contains(
"ValueError: fixture failure",
StringComparison.Ordinal
)
);
Assert.Contains("managed-stable-abi-fixture-v4", session.WorkerIdentity.Features);
Assert.Equal(WorkerProcessState.Running, pool.State);
}
[Fact]
public async Task Worker_ImportsIndependentStableAbiModulesFromQualifiedCatalog()
{
SkipNativeFixtureOnWindows();
await using var pool = new WorkerProcessPool(
CreateOptions(stableAbiModule: true, secondaryStableAbiModule: true)
);
await using var session = await pool.OpenSessionAsync(
TestContext.Current.CancellationToken
);
var result = await session.ExecuteAsync(
"""
import dotpython_fixture
import dotpython_fixture_secondary
print(dotpython_fixture.increment(41))
print(dotpython_fixture_secondary.double(21))
""",
cancellationToken: TestContext.Current.CancellationToken
);
var secondaryFailure = await session.ExecuteAsync(
"import dotpython_fixture_secondary\ndotpython_fixture_secondary.fail()",
cancellationToken: TestContext.Current.CancellationToken
);
var primaryAfterFailure = await session.ExecuteAsync(
"import dotpython_fixture\nprint(dotpython_fixture.increment(9))",
cancellationToken: TestContext.Current.CancellationToken
);
Assert.True(result.Success, string.Join(Environment.NewLine, result.Diagnostics));
Assert.Equal($"42{Environment.NewLine}42{Environment.NewLine}", result.StandardOutput);
Assert.False(secondaryFailure.Success);
Assert.Contains(
secondaryFailure.Diagnostics,
diagnostic =>
diagnostic.Message.Contains("secondary fixture failure", StringComparison.Ordinal)
);
Assert.True(
primaryAfterFailure.Success,
string.Join(Environment.NewLine, primaryAfterFailure.Diagnostics)
);
Assert.Equal($"10{Environment.NewLine}", primaryAfterFailure.StandardOutput);
Assert.Contains("managed-stable-abi-fixture-v4", session.WorkerIdentity.Features);
Assert.Contains("managed-stable-abi-fixture-secondary-v2", session.WorkerIdentity.Features);
Assert.Equal(WorkerProcessState.Running, pool.State);
}
[Fact]
public void Worker_RejectsDuplicateStableAbiCatalogArtifactsBeforeStartup()
{
SkipNativeFixtureOnWindows();
var options = CreateOptions(stableAbiModule: true);
var module = options.StableAbiModules.Single();
var invalid = options with { StableAbiModules = [module, module] };
var exception = Assert.Throws<ArgumentException>(() => new WorkerProcessPool(invalid));
Assert.Equal("StableAbiModules", exception.ParamName);
Assert.Contains("must be unique", exception.Message, StringComparison.Ordinal);
}
[Fact]
public async Task Worker_FreezesStableAbiCatalogAtPoolConstruction()
{
SkipNativeFixtureOnWindows();
var options = CreateOptions(stableAbiModule: true);
var mutableCatalog = options.StableAbiModules.ToList();
await using var pool = new WorkerProcessPool(
options with
{
StableAbiModules = mutableCatalog,
}
);
mutableCatalog.Clear();
await using var session = await pool.OpenSessionAsync(
TestContext.Current.CancellationToken
);
var result = await session.ExecuteAsync(
"import dotpython_fixture\nprint(dotpython_fixture.increment(4))",
cancellationToken: TestContext.Current.CancellationToken
);
Assert.True(result.Success, string.Join(Environment.NewLine, result.Diagnostics));
Assert.Equal($"5{Environment.NewLine}", result.StandardOutput);
}
[Fact]
public async Task Worker_ImportsUnchangedAnyverWheelThroughGenericStableAbiObjects()
{
SkipAnyverPackageWhenUnavailable();
await using var pool = new WorkerProcessPool(CreateQualifiedAnyverOptions());
await using var session = await pool.OpenSessionAsync(
TestContext.Current.CancellationToken
);
var result = await session.ExecuteAsync(
"""
import anyver
print(anyver.__version__)
print(anyver.compare("1.0", "2.0"))
print(anyver.eq("1.0", "1.0.0"))
print(anyver.sort_versions(["2.0", "1.0-alpha", "1.0"]))
value = anyver.Version("1.2.3-rc.1+build.42")
print(value)
print(value.raw)
print(value.major)
print(value.minor)
print(value.patch)
print(value.is_prerelease)
print(value[0])
print(value.to_dict()["raw"])
gate = anyver.Version("1.2.3")
print(repr(gate))
print(len(gate))
print(gate < anyver.Version("2.0"))
print(anyver.Version.from_dict(gate.to_dict()) == gate)
""",
fileName: "<generic-anyver-qualification>",
cancellationToken: TestContext.Current.CancellationToken
);
Assert.True(result.Success, string.Join(Environment.NewLine, result.Diagnostics));
Assert.Equal(
string.Join(
Environment.NewLine,
"1.1.0",
"-1",
"True",
"['1.0-alpha', '1.0', '2.0']",
"1.2.3-rc.1+build.42",
"1.2.3-rc.1+build.42",
"1",
"2",
"3",
"True",
"1",
"1.2.3-rc.1+build.42",
"Version('1.2.3')",
"3",
"True",
"True"
) + Environment.NewLine,
result.StandardOutput
);
Assert.Equal(WorkerProcessState.Running, pool.State);
}
[Fact]
public async Task Worker_RecordsUnchangedAnyverUpstreamSuiteQualification()
{
SkipAnyverPackageWhenUnavailable();
var sourceRoot = Environment.GetEnvironmentVariable("DOTPYTHON_ANYVER_SOURCE");
var pythonPath = Environment.GetEnvironmentVariable("DOTPYTHON_ANYVER_PYTHON");
if (string.IsNullOrWhiteSpace(sourceRoot) || string.IsNullOrWhiteSpace(pythonPath))
{
Assert.Skip(
"Set DOTPYTHON_ANYVER_SOURCE and DOTPYTHON_ANYVER_PYTHON to qualify the pinned upstream suite."
);
}
var fullSourceRoot = Path.GetFullPath(sourceRoot);
var fullPythonPath = Path.GetFullPath(pythonPath);
Assert.True(Directory.Exists(fullSourceRoot));
Assert.True(File.Exists(fullPythonPath));
var testPath = Path.Combine(fullSourceRoot, "tests", "test_anyver.py");
var testBytes = await File.ReadAllBytesAsync(
testPath,
TestContext.Current.CancellationToken
);
Assert.Equal(
"9432cc519e7caa01295df0ec83c4f37ad246073c0841a1ca58578a281552fe6e",
Convert.ToHexStringLower(SHA256.HashData(testBytes))
);
var testSource = Encoding.UTF8.GetString(testBytes);
var packageRoot = NativeFixturePath("anyver-package");
var pythonVersion = await RunQualificationProcessAsync(
fullPythonPath,
["--version"],
fullSourceRoot,
packageRoot
);
var pytestVersion = await RunQualificationProcessAsync(
fullPythonPath,
["-B", "-m", "pytest", "--version"],
fullSourceRoot,
packageRoot
);
var collection = await RunQualificationProcessAsync(
fullPythonPath,
[
"-B",
"-m",
"pytest",
"-p",
"no:cacheprovider",
"--color=no",
"--collect-only",
"-q",
"tests/test_anyver.py",
],
fullSourceRoot,
packageRoot
);
var nodeIds = collection
.StandardOutput.Split(
'\n',
StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries
)
.Where(line => line.StartsWith("tests/test_anyver.py::", StringComparison.Ordinal))
.ToArray();
Assert.Equal(325, nodeIds.Length);
Assert.Equal(nodeIds.Length, nodeIds.Distinct(StringComparer.Ordinal).Count());
var (shimRoot, shimSha256) = StagePytestShim();
await using var pool = new WorkerProcessPool(CreateQualifiedAnyverOptions(shimRoot));
await using var session = await pool.OpenSessionAsync(
TestContext.Current.CancellationToken
);
var run = await QualificationSuiteRunner.RunAsync(
session,
testSource,
fileName: "tests/test_anyver.py",
nodeIds,
TestContext.Current.CancellationToken,
attemptParametrized: true
);
Assert.Equal(nodeIds.Length, run.Cases.Count);
var evidence = new AnyverQualificationEvidence
{
SchemaVersion = 3,
Package = "anyver",
PackageVersion = "1.1.0",
Wheel = "anyver-1.1.0-cp311-abi3-macosx_11_0_arm64.whl",
WheelSha256 = "0f2fa90663b0203d3086c313d6384a6d74177e1f52508abf613cb17439edc4f9",
SourceRevision = "3dc892e3eb9d1a4baf7a315a6ce4a41b3893337e",
SourceTestFile = "tests/test_anyver.py",
SourceTestFileSha256 =
"9432cc519e7caa01295df0ec83c4f37ad246073c0841a1ca58578a281552fe6e",
Platform = "macos-arm64",
Collector = new AnyverQualificationCollector
{
PythonVersion = pythonVersion.StandardOutput.Trim(),
PytestVersion = pytestVersion.StandardOutput.Trim(),
Command =
"python -B -m pytest -p no:cacheprovider --color=no --collect-only -q tests/test_anyver.py",
},
Execution = new AnyverQualificationExecution
{
Provider = "dotpython-managed-abi3",
ProviderVersion = "0.1.0",
LanguageProfile = "3.14",
Isolation = "worker-process",
SourceModified = false,
SuiteAdmissionAttempts = 1,
AttemptedCases = run.AttemptedCases,
PytestShim = new AnyverQualificationShim
{
File = "pytest.py",
Sha256 = shimSha256,
},
Blockers = run.Blockers,
},
Summary = new AnyverQualificationSummary
{
Collected = nodeIds.Length,
Passed = run.Cases.Count(item => item.Outcome == "passed"),
Failed = run.Cases.Count(item => item.Outcome == "failed"),
Skipped = run.Cases.Count(item => item.Outcome == "skipped"),
},
Cases = run.Cases,
};
var generated =
JsonSerializer.Serialize(
evidence,
AnyverQualificationJsonContext.Default.AnyverQualificationEvidence
) + "\n";
var evidencePath = Path.Combine(
FindRepositoryRoot(),
"native",
"dotpython-abi3",
"anyver-upstream-qualification.json"
);
if (
string.Equals(
Environment.GetEnvironmentVariable("DOTPYTHON_ANYVER_UPDATE_EVIDENCE"),
"1",
StringComparison.Ordinal
)
)
{
await File.WriteAllTextAsync(
evidencePath,
generated,
new UTF8Encoding(encoderShouldEmitUTF8Identifier: false),
TestContext.Current.CancellationToken
);
}
else
{
Assert.Equal(
generated,
(
await File.ReadAllTextAsync(evidencePath, TestContext.Current.CancellationToken)
).ReplaceLineEndings("\n")
);
}
}
[Fact]
public async Task Worker_AttemptsQualificationCasesWhenTheSuiteIsAdmitted()
{
await using var pool = new WorkerProcessPool(CreateOptions());
await using var session = await pool.OpenSessionAsync(
TestContext.Current.CancellationToken
);
var run = await QualificationSuiteRunner.RunAsync(
session,
"class TestMath:\n"
+ " def test_ok(self):\n"
+ " assert 1 + 1 == 2\n"
+ " def test_bad(self):\n"
+ " assert 1 == 2, 'broken math'\n"
+ "def test_top():\n"
+ " assert True\n",
fileName: "tests/test_synthetic.py",
[
"tests/test_synthetic.py::TestMath::test_ok",
"tests/test_synthetic.py::TestMath::test_bad",
"tests/test_synthetic.py::test_top",
"tests/test_synthetic.py::TestMath::test_param[1-2]",
],
TestContext.Current.CancellationToken
);
Assert.True(run.SuiteAdmitted);
Assert.Equal(3, run.AttemptedCases);
Assert.Equal(
["passed", "failed", "passed", "skipped"],
run.Cases.Select(item => item.Outcome)
);
Assert.Contains("broken math", run.Cases[1].Detail, StringComparison.Ordinal);
Assert.Equal(QualificationSuiteRunner.ParametrizeBlockerId, run.Cases[3].Blocker);
var blocker = Assert.Single(run.Blockers);
Assert.Equal(QualificationSuiteRunner.ParametrizeBlockerId, blocker.Id);
Assert.Equal(1, blocker.Occurrences);
}
[Fact]
public async Task Worker_ReusesPinnedAnyverCachesAcrossLogicalModuleLoads()
{
SkipAnyverPackageWhenUnavailable();
await using var pool = new WorkerProcessPool(CreateQualifiedAnyverOptions());
for (var iteration = 0; iteration < 10; iteration++)
{
await using var session = await pool.OpenSessionAsync(
TestContext.Current.CancellationToken
);
var result = await session.ExecuteAsync(
"import anyver\nprint(anyver.compare('2.0', '2.0'))",
cancellationToken: TestContext.Current.CancellationToken
);
Assert.True(result.Success, string.Join(Environment.NewLine, result.Diagnostics));
Assert.Equal("0" + Environment.NewLine, result.StandardOutput);
}
Assert.Equal(WorkerProcessState.Running, pool.State);
}
[Fact]
public async Task Worker_HashesAndDeduplicatesNativeValuesInManagedCollections()
{
SkipAnyverPackageWhenUnavailable();
await using var pool = new WorkerProcessPool(CreateQualifiedAnyverOptions());
await using var session = await pool.OpenSessionAsync(
TestContext.Current.CancellationToken
);
var result = await session.ExecuteAsync(
"from anyver import Version\n"
+ "s = {Version('1.0'), Version('1.0.0'), Version('2.0')}\n"
+ "d = {Version('1.0'): 'one'}\n"
+ "print(len(s), d[Version('1.0.0')], hash(Version('1.0')) == hash(Version('1.0.0')))\n"
+ "print(Version('1.0') == Version('1.0.0'), Version('1.0') in [Version('1.0.0')])",
cancellationToken: TestContext.Current.CancellationToken
);
Assert.True(result.Success, string.Join(Environment.NewLine, result.Diagnostics));
Assert.Equal(
"2 one True" + Environment.NewLine + "True True" + Environment.NewLine,
result.StandardOutput
);
Assert.Equal(WorkerProcessState.Running, pool.State);
}
[Fact]
public async Task Worker_ContainsRepeatedAnyverFailuresWithoutPoisoningOwnerLane()
{
SkipAnyverPackageWhenUnavailable();
await using var pool = new WorkerProcessPool(CreateQualifiedAnyverOptions());
await using var session = await pool.OpenSessionAsync(
TestContext.Current.CancellationToken
);
for (var iteration = 0; iteration < 64; iteration++)
{
var failure = await session.ExecuteAsync(
"import anyver\nanyver.compare('1.0', '2.0', 'dotpython-invalid-ecosystem')",
cancellationToken: TestContext.Current.CancellationToken
);
Assert.False(failure.Success);
Assert.Contains(
failure.Diagnostics,
diagnostic => diagnostic.Message.Contains("ValueError", StringComparison.Ordinal)
);
}
var success = await session.ExecuteAsync(
"import anyver\nprint(anyver.compare('1.0', '2.0'))",
cancellationToken: TestContext.Current.CancellationToken
);
Assert.True(success.Success, string.Join(Environment.NewLine, success.Diagnostics));
Assert.Equal("-1" + Environment.NewLine, success.StandardOutput);
Assert.Equal(WorkerProcessState.Running, pool.State);
}
[Fact]
public async Task Worker_RestartsPinnedAnyverAfterOrderlyProcessShutdown()
{
SkipAnyverPackageWhenUnavailable();
for (var iteration = 0; iteration < 4; iteration++)
{
await using var pool = new WorkerProcessPool(CreateQualifiedAnyverOptions());
await using var session = await pool.OpenSessionAsync(
TestContext.Current.CancellationToken
);
var result = await session.ExecuteAsync(
$"import anyver\nprint(anyver.Version('1.2.{iteration}').raw)",
cancellationToken: TestContext.Current.CancellationToken
);
Assert.True(result.Success, string.Join(Environment.NewLine, result.Diagnostics));
Assert.Equal($"1.2.{iteration}{Environment.NewLine}", result.StandardOutput);
Assert.Equal(WorkerProcessState.Running, pool.State);
}
}
[Fact]
public async Task Worker_RejectsUnconfiguredStableAbiImportWithoutFallback()
{
SkipNativeFixtureOnWindows();
await using var pool = new WorkerProcessPool(
CreateOptions(packageRoots: [NativeFixturePath(string.Empty)])
);
await using var session = await pool.OpenSessionAsync(
TestContext.Current.CancellationToken
);
var result = await session.ExecuteAsync(
"import dotpython_fixture",
cancellationToken: TestContext.Current.CancellationToken
);
Assert.False(result.Success);
Assert.Contains(result.Diagnostics, diagnostic => diagnostic.Code == "DPY4027");
Assert.Equal(WorkerProcessState.Running, pool.State);
}
[Fact]
public async Task Worker_RecreatesNativeModuleStateAfterCrash()
{
SkipNativeFixtureOnWindows();
await using var pool = new WorkerProcessPool(
CreateOptions(enableTestFaultInjection: true, stableAbiModule: true)
);
await using var session = await pool.OpenSessionAsync(
TestContext.Current.CancellationToken
);
var initial = await session.ExecuteAsync(
"import dotpython_fixture\nprint(dotpython_fixture.increment(1))",
cancellationToken: TestContext.Current.CancellationToken
);
var failedIdentity = session.WorkerIdentity;
Assert.True(initial.Success, string.Join(Environment.NewLine, initial.Diagnostics));
_ = await Assert.ThrowsAsync<WorkerProtocolException>(() =>
pool.InjectTestFaultAsync(WorkerTestFault.Crash, TestContext.Current.CancellationToken)
);
await using var replacement = await pool.OpenSessionAsync(
TestContext.Current.CancellationToken
);
var restarted = await replacement.ExecuteAsync(
"import dotpython_fixture\nprint(dotpython_fixture.increment(41))",
cancellationToken: TestContext.Current.CancellationToken
);
Assert.Equal(failedIdentity.Generation + 1, replacement.WorkerIdentity.Generation);
Assert.True(restarted.Success, string.Join(Environment.NewLine, restarted.Diagnostics));
Assert.Equal("42" + Environment.NewLine, restarted.StandardOutput);
}
[Fact]
public async Task Worker_ReportsNativeHashFailureThroughImport()
{
SkipNativeFixtureOnWindows();
var invalidHashOptions = CreateOptions(stableAbiModule: true);
invalidHashOptions = invalidHashOptions with
{
StableAbiModules =
[
invalidHashOptions.StableAbiModules.Single() with
{
ModuleSha256 = new string('0', 64),
},
],
};
await using var hashPool = new WorkerProcessPool(invalidHashOptions);
await using var hashSession = await hashPool.OpenSessionAsync(
TestContext.Current.CancellationToken
);
var hashFailure = await hashSession.ExecuteAsync(
"import dotpython_fixture",
cancellationToken: TestContext.Current.CancellationToken
);
Assert.False(hashFailure.Success);
Assert.Contains(hashFailure.Diagnostics, diagnostic => diagnostic.Code == "DPY8001");
Assert.Equal(WorkerProcessState.Running, hashPool.State);
}
[Fact]
public async Task Worker_ContainsNativePreflightFailureWithoutPoisoningManagedExecution()
{
SkipNativeFixtureOnWindows();
using var temporary = new TemporaryDirectory();
var invalidModule = Path.Combine(temporary.Path, "dotpython_fixture.abi3.so");
var bytes = new byte[4096];
if (OperatingSystem.IsMacOS())
{
BinaryPrimitives.WriteUInt32LittleEndian(bytes, 0xfeedfacf);
BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(4), 0x0100000c);
}
else
{
bytes[0] = 0x7f;
bytes[1] = (byte)'E';
bytes[2] = (byte)'L';
bytes[3] = (byte)'F';
bytes[4] = 2;
bytes[5] = 1;
BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(18), 62);
}
await File.WriteAllBytesAsync(invalidModule, bytes, TestContext.Current.CancellationToken);
await using var pool = new WorkerProcessPool(
CreateOptions(stableAbiModule: true, nativeModulePath: invalidModule)
);
await using var session = await pool.OpenSessionAsync(
TestContext.Current.CancellationToken
);
var failure = await session.ExecuteAsync(
"import dotpython_fixture",
cancellationToken: TestContext.Current.CancellationToken
);
var managed = await session.ExecuteAsync(
"print(42)",
cancellationToken: TestContext.Current.CancellationToken
);
Assert.False(failure.Success);
Assert.Contains(failure.Diagnostics, diagnostic => diagnostic.Code == "DPY8004");
Assert.True(managed.Success);
Assert.Equal("42" + Environment.NewLine, managed.StandardOutput);
Assert.Equal(WorkerProcessState.Running, pool.State);
}
[Fact]
public async Task Worker_ExecutesManagedCodeAndShutsDownCleanly()
{
await using var pool = new WorkerProcessPool(CreateOptions());
await pool.StartAsync(TestContext.Current.CancellationToken);
await using var session = await pool.OpenSessionAsync(
TestContext.Current.CancellationToken
);
var result = await session.ExecuteAsync(
"print('worker', 42)",
cancellationToken: TestContext.Current.CancellationToken
);
Assert.True(result.Success);
Assert.Equal($"worker 42{Environment.NewLine}", result.StandardOutput);
Assert.Empty(result.StandardError);
Assert.Equal(WorkerProcessState.Running, pool.State);
Assert.Equal("dotpython-managed", session.WorkerIdentity.RuntimeId);
}
[Fact]
public async Task Worker_EnforcesOutputAndSessionLimitsWithoutCorruptingProcess()
{
var limits = new WorkerProtocolLimits(4096, 32, 1, 1);
await using var pool = new WorkerProcessPool(
CreateOptions(policy: new WorkerResourcePolicy { Limits = limits })
);
await using var session = await pool.OpenSessionAsync(
TestContext.Current.CancellationToken
);
var outputFault = await Assert.ThrowsAsync<WorkerProtocolException>(() =>
session.ExecuteAsync(
$"print('{new string('x', 64)}')",
cancellationToken: TestContext.Current.CancellationToken
)
);
var sessionFault = await Assert.ThrowsAsync<WorkerProtocolException>(() =>
pool.OpenSessionAsync(TestContext.Current.CancellationToken)
);
var recovery = await session.ExecuteAsync(
"print('ok')",
cancellationToken: TestContext.Current.CancellationToken
);
Assert.Equal(WorkerProtocolFaultCodes.LimitExceeded, outputFault.Fault.Code);
Assert.Equal(WorkerProtocolFaultCodes.LimitExceeded, sessionFault.Fault.Code);
Assert.Equal($"ok{Environment.NewLine}", recovery.StandardOutput);
Assert.Equal(WorkerProcessState.Running, pool.State);
}
[Fact]
public async Task Worker_RejectsOversizedRequestBeforeSendingIt()
{
var limits = new WorkerProtocolLimits(1024, 128, 1, 2);
await using var pool = new WorkerProcessPool(
CreateOptions(policy: new WorkerResourcePolicy { Limits = limits })
);
await using var session = await pool.OpenSessionAsync(
TestContext.Current.CancellationToken
);
var exception = await Assert.ThrowsAsync<WorkerProtocolException>(() =>
session.ExecuteAsync(
new string('x', 2048),
cancellationToken: TestContext.Current.CancellationToken
)
);
var recovery = await session.ExecuteAsync(
"print('bounded')",
cancellationToken: TestContext.Current.CancellationToken
);
Assert.Equal(WorkerProtocolFaultCodes.LimitExceeded, exception.Fault.Code);
Assert.Equal($"bounded{Environment.NewLine}", recovery.StandardOutput);
}
[Fact]
public async Task Worker_CooperativelyCancelsWithoutRecyclingHealthyGeneration()
{
var policy = new WorkerResourcePolicy
{
ExecutionTimeout = TimeSpan.FromSeconds(5),
TerminationGracePeriod = TimeSpan.FromSeconds(1),
};
await using var pool = new WorkerProcessPool(CreateOptions(policy: policy));
await using var session = await pool.OpenSessionAsync(
TestContext.Current.CancellationToken
);
var generation = session.WorkerIdentity.Generation;
using var cancellation = new CancellationTokenSource(TimeSpan.FromMilliseconds(50));
await Assert.ThrowsAnyAsync<OperationCanceledException>(() =>
session.ExecuteAsync(
"value = 0\nwhile True:\n value = value + 1",
instructionLimit: long.MaxValue,
cancellationToken: cancellation.Token
)
);
var recovery = await session.ExecuteAsync(
"print('still-running')",
cancellationToken: TestContext.Current.CancellationToken
);
Assert.Equal(generation, session.WorkerIdentity.Generation);
Assert.Equal(WorkerProcessState.Running, pool.State);
Assert.Equal($"still-running{Environment.NewLine}", recovery.StandardOutput);
}
[Fact]
public async Task Worker_HardTimeoutTerminatesAndReplacesHungGeneration()
{
var policy = new WorkerResourcePolicy
{
ExecutionTimeout = TimeSpan.FromMilliseconds(75),
TerminationGracePeriod = TimeSpan.FromMilliseconds(25),
};
await using var pool = new WorkerProcessPool(
CreateOptions(policy: policy, enableTestFaultInjection: true)
);
await pool.StartAsync(TestContext.Current.CancellationToken);
var first = Assert.IsType<WorkerIdentity>(pool.ActiveIdentity);
var exception = await Assert.ThrowsAsync<WorkerProtocolException>(() =>
pool.InjectTestFaultAsync(WorkerTestFault.Hang, TestContext.Current.CancellationToken)
);
await pool.StartAsync(TestContext.Current.CancellationToken);
var replacement = Assert.IsType<WorkerIdentity>(pool.ActiveIdentity);
Assert.Equal(WorkerProtocolFaultCodes.HardTimeout, exception.Fault.Code);
Assert.Equal(first.Generation + 1, replacement.Generation);
Assert.NotEqual(first.WorkerId, replacement.WorkerId);
Assert.Equal(WorkerProcessState.Running, pool.State);
}
[Fact]
public async Task Worker_CrashIsContainedAndGenerationCanBeReplaced()
{
await using var pool = new WorkerProcessPool(CreateOptions(enableTestFaultInjection: true));
await pool.StartAsync(TestContext.Current.CancellationToken);
var first = Assert.IsType<WorkerIdentity>(pool.ActiveIdentity);
var exception = await Assert.ThrowsAsync<WorkerProtocolException>(() =>
pool.InjectTestFaultAsync(WorkerTestFault.Crash, TestContext.Current.CancellationToken)
);
await pool.StartAsync(TestContext.Current.CancellationToken);
var replacement = Assert.IsType<WorkerIdentity>(pool.ActiveIdentity);
Assert.Equal(WorkerProtocolFaultCodes.WorkerTerminated, exception.Fault.Code);
Assert.Equal(first.Generation + 1, replacement.Generation);
Assert.Equal(WorkerProcessState.Running, pool.State);
}
[Fact]
public async Task Worker_RejectsTruncatedAndDuplicateResponses()
{
await using var truncatedPool = new WorkerProcessPool(
CreateOptions(enableTestFaultInjection: true)
);
await truncatedPool.StartAsync(TestContext.Current.CancellationToken);
var truncated = await Assert.ThrowsAsync<WorkerProtocolException>(() =>
truncatedPool.InjectTestFaultAsync(
WorkerTestFault.TruncatedMessage,
TestContext.Current.CancellationToken
)
);
await using var duplicatePool = new WorkerProcessPool(
CreateOptions(enableTestFaultInjection: true)
);
await duplicatePool.StartAsync(TestContext.Current.CancellationToken);
await duplicatePool.InjectTestFaultAsync(
WorkerTestFault.DuplicateResponse,
TestContext.Current.CancellationToken
);
await WaitForStateAsync(duplicatePool, WorkerProcessState.Faulted);
Assert.Equal(WorkerProtocolFaultCodes.HandshakeFailed, truncated.Fault.Code);
Assert.Equal(WorkerProcessState.Faulted, duplicatePool.State);
}
[Fact]
public async Task Worker_RejectsProtocolMajorSkewDuringStartup()
{
var baseline = CreateOptions();
var options = baseline with
{
Arguments = [.. baseline.Arguments, "--protocol-major", "4"],
};
await using var pool = new WorkerProcessPool(options);
var exception = await Assert.ThrowsAsync<WorkerProtocolException>(() =>
pool.StartAsync(TestContext.Current.CancellationToken)
);
Assert.Equal(WorkerProtocolFaultCodes.HandshakeFailed, exception.Fault.Code);
Assert.Equal(WorkerProcessState.Stopped, pool.State);
}
[Fact]
public async Task RecyclingInvalidatesOldHandlesAndIncrementsGenerationDeterministically()
{
await using var pool = new WorkerProcessPool(CreateOptions());
await using var oldSession = await pool.OpenSessionAsync(
TestContext.Current.CancellationToken
);
var oldIdentity = oldSession.WorkerIdentity;
var handle = new WorkerObjectHandle(
oldIdentity.ProviderId,
oldIdentity.WorkerId,
oldIdentity.Generation,
oldSession.SessionId,
1
);
oldSession.ValidateHandle(handle);
await pool.RecycleAsync(TestContext.Current.CancellationToken);
await using var newSession = await pool.OpenSessionAsync(
TestContext.Current.CancellationToken
);
var stale = Assert.Throws<WorkerProtocolException>(() => oldSession.ValidateHandle(handle));
Assert.Equal(WorkerProtocolFaultCodes.StaleHandle, stale.Fault.Code);
Assert.Equal(oldIdentity.Generation + 1, newSession.WorkerIdentity.Generation);
}
[Fact]
public async Task RequestCountPolicyRecyclesBeforeOpeningNextSession()
{
var policy = new WorkerResourcePolicy { MaxRequestsPerWorker = 1 };
await using var pool = new WorkerProcessPool(CreateOptions(policy: policy));
await using (
var firstSession = await pool.OpenSessionAsync(TestContext.Current.CancellationToken)
)
{
_ = await firstSession.ExecuteAsync(
"value = 1",
cancellationToken: TestContext.Current.CancellationToken
);
}
var first = Assert.IsType<WorkerIdentity>(pool.ActiveIdentity);
await using var secondSession = await pool.OpenSessionAsync(
TestContext.Current.CancellationToken
);
Assert.Equal(first.Generation + 1, secondSession.WorkerIdentity.Generation);
}
[Fact]
public void LaunchPolicy_DoesNotInheritAmbientEnvironment()
{
var options = CreateOptions() with
{
EnvironmentVariables = new Dictionary<string, string> { ["DOTPYTHON_SAFE"] = "1" },
};
var startInfo = WorkerProcessClient.CreateStartInfo(options, Guid.NewGuid(), 1);
Assert.Single(startInfo.Environment);
Assert.Equal("1", startInfo.Environment["DOTPYTHON_SAFE"]);
Assert.False(startInfo.Environment.ContainsKey("PATH"));
Assert.False(startInfo.Environment.ContainsKey("HOME"));
Assert.False(startInfo.UseShellExecute);
}
private static WorkerProcessOptions CreateOptions(
WorkerResourcePolicy? policy = null,
bool enableTestFaultInjection = false,
bool stableAbiModule = false,
bool secondaryStableAbiModule = false,
string nativeModuleFileName = "dotpython_fixture.abi3.so",
string nativeManifestFileName = "symbol-manifest.json",
string? nativeModulePath = null,
IReadOnlyList<string>? packageRoots = null
)
{
var appPath = Path.Combine(AppContext.BaseDirectory, "worker", "DotPython.Worker.Host.dll");
var runtimeDirectory = new DirectoryInfo(RuntimeEnvironment.GetRuntimeDirectory());
var dotnetRoot =
runtimeDirectory.Parent?.Parent?.Parent
?? throw new InvalidOperationException("The dotnet host root could not be resolved.");
var dotnetHost = Path.Combine(
dotnetRoot.FullName,
OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"
);
var nativeOptions = new List<WorkerStableAbiModuleOptions>();
if (stableAbiModule)
{
var bridge = NativeFixturePath(
OperatingSystem.IsMacOS() ? "libdotpython_abi3.dylib" : "libdotpython_abi3.so"
);
var module = nativeModulePath ?? NativeFixturePath(nativeModuleFileName);
var manifest = NativeFixturePath(nativeManifestFileName);
nativeOptions.Add(CreateStableAbiModuleOptions(bridge, module, manifest));
if (secondaryStableAbiModule)
{
nativeOptions.Add(
CreateStableAbiModuleOptions(
bridge,
NativeFixturePath("dotpython_fixture_secondary.abi3.so"),
NativeFixturePath("secondary-symbol-manifest.json")
)
);
}
}
return new WorkerProcessOptions
{
FileName = dotnetHost,
Arguments = [appPath],
WorkingDirectory = Path.GetFullPath(AppContext.BaseDirectory),
EnvironmentHash = "sha256:worker-tests",
Policy = policy ?? new WorkerResourcePolicy(),
EnableTestFaultInjection = enableTestFaultInjection,
StableAbiModules = nativeOptions,
PackageRoots =
packageRoots
?? (
nativeOptions.Count == 0
? Array.Empty<string>()
: [Path.GetDirectoryName(nativeOptions[0].ModulePath)!]
),
RequiredFeatures = RequiredStableAbiFeatures(
stableAbiModule,
secondaryStableAbiModule,
nativeManifestFileName
),
};
}
private static WorkerStableAbiModuleOptions CreateStableAbiModuleOptions(
string bridge,
string module,
string manifest
) =>
new()
{
BridgePath = bridge,
ModulePath = module,
ManifestPath = manifest,
BridgeSha256 = StableAbiModuleLoader.ComputeSha256(bridge),
ModuleSha256 = StableAbiModuleLoader.ComputeSha256(module),
ManifestSha256 = StableAbiModuleLoader.ComputeSha256(manifest),
};
private static List<string> RequiredStableAbiFeatures(
bool stableAbiModule,
bool secondaryStableAbiModule,
string manifestFileName
)
{
if (!stableAbiModule)
{
return ["managed-execution"];
}
var features = new List<string>
{
"managed-execution",
manifestFileName == "anyver-symbol-manifest.json"
? "managed-stable-abi-qualified-v2"
: "managed-stable-abi-fixture-v4",
};
if (secondaryStableAbiModule)
{