-
Notifications
You must be signed in to change notification settings - Fork 660
Expand file tree
/
Copy pathTestMultiMMap.cs
More file actions
2702 lines (2475 loc) · 121 KB
/
Copy pathTestMultiMMap.cs
File metadata and controls
2702 lines (2475 loc) · 121 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 J2N;
using Lucene.Net.Attributes;
using Lucene.Net.Documents;
using Lucene.Net.Index.Extensions;
using NUnit.Framework;
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Assert = Lucene.Net.TestFramework.Assert;
namespace Lucene.Net.Store
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using BytesRef = Util.BytesRef;
using Document = Document;
using Field = Field;
using IndexInputSlicer = Directory.IndexInputSlicer;
using IndexReader = Index.IndexReader;
using LuceneTestCase = Util.LuceneTestCase;
using MockAnalyzer = Analysis.MockAnalyzer;
using RandomIndexWriter = Index.RandomIndexWriter;
using TestUtil = Util.TestUtil;
/// <summary>
/// Tests MMapDirectory's MultiMMapIndexInput
/// <para/>
/// Because .NET's <see cref="Span{T}"/> and <see cref="ReadOnlySpan{T}"/> use an int to address the
/// values, and because we use a similar chunking approach to Lucene, it's necessary to access a file >
/// <see cref="Int32.MaxValue"/> in size using multiple byte buffers.
/// </summary>
[TestFixture]
public class TestMultiMMap : LuceneTestCase
{
[SetUp]
public override void SetUp()
{
base.SetUp();
// LUCENENET NOTE:
// Java seems to have issues releasing memory mapped resources when calling close()
// http://stackoverflow.com/a/2973059/181087
// However, according to MSDN, the Dispose() method of the MemoryMappedFile class will "release all resources".
// https://msdn.microsoft.com/en-us/library/system.io.memorymappedfiles.memorymappedfile(v=vs.110).aspx
// Therefore, I am assuming removing the below line is the correct choice for .NET.
//AssumeTrue("test requires a jre that supports unmapping", MMapDirectory.UNMAP_SUPPORTED);
}
[Test]
public virtual void TestCloneSafety()
{
MMapDirectory mmapDir = new MMapDirectory(CreateTempDir("testCloneSafety"));
IndexOutput io = mmapDir.CreateOutput("bytes", NewIOContext(Random));
io.WriteVInt32(5);
io.Dispose();
IndexInput one = mmapDir.OpenInput("bytes", IOContext.DEFAULT);
IndexInput two = (IndexInput)one.Clone();
IndexInput three = (IndexInput)two.Clone(); // clone of clone
one.Dispose();
try
{
one.ReadVInt32();
Assert.Fail("Must throw ObjectDisposedException");
}
catch (Exception ignore) when (ignore.IsAlreadyClosedException())
{
// pass
}
try
{
two.ReadVInt32();
Assert.Fail("Must throw ObjectDisposedException");
}
catch (Exception ignore) when (ignore.IsAlreadyClosedException())
{
// pass
}
try
{
three.ReadVInt32();
Assert.Fail("Must throw ObjectDisposedException");
}
catch (Exception ignore) when (ignore.IsAlreadyClosedException())
{
// pass
}
two.Dispose();
three.Dispose();
// test double close of master:
one.Dispose();
mmapDir.Dispose();
}
[Test]
public virtual void TestCloneClose()
{
MMapDirectory mmapDir = new MMapDirectory(CreateTempDir("testCloneClose"));
IndexOutput io = mmapDir.CreateOutput("bytes", NewIOContext(Random));
io.WriteVInt32(5);
io.Dispose();
IndexInput one = mmapDir.OpenInput("bytes", IOContext.DEFAULT);
IndexInput two = (IndexInput)one.Clone();
IndexInput three = (IndexInput)two.Clone(); // clone of clone
two.Dispose();
Assert.AreEqual(5, one.ReadVInt32());
try
{
two.ReadVInt32();
Assert.Fail("Must throw ObjectDisposedException");
}
catch (Exception ignore) when (ignore.IsAlreadyClosedException())
{
// pass
}
Assert.AreEqual(5, three.ReadVInt32());
one.Dispose();
three.Dispose();
mmapDir.Dispose();
}
[Test]
public virtual void TestCloneSliceSafety()
{
MMapDirectory mmapDir = new MMapDirectory(CreateTempDir("testCloneSliceSafety"));
IndexOutput io = mmapDir.CreateOutput("bytes", NewIOContext(Random));
io.WriteInt32(1);
io.WriteInt32(2);
io.Dispose();
IndexInputSlicer slicer = mmapDir.CreateSlicer("bytes", NewIOContext(Random));
IndexInput one = slicer.OpenSlice("first int", 0, 4);
IndexInput two = slicer.OpenSlice("second int", 4, 4);
IndexInput three = (IndexInput)one.Clone(); // clone of clone
IndexInput four = (IndexInput)two.Clone(); // clone of clone
slicer.Dispose();
try
{
one.ReadInt32();
Assert.Fail("Must throw ObjectDisposedException");
}
catch (Exception ignore) when (ignore.IsAlreadyClosedException())
{
// pass
}
try
{
two.ReadInt32();
Assert.Fail("Must throw ObjectDisposedException");
}
catch (Exception ignore) when (ignore.IsAlreadyClosedException())
{
// pass
}
try
{
three.ReadInt32();
Assert.Fail("Must throw ObjectDisposedException");
}
catch (Exception ignore) when (ignore.IsAlreadyClosedException())
{
// pass
}
try
{
four.ReadInt32();
Assert.Fail("Must throw ObjectDisposedException");
}
catch (Exception ignore) when (ignore.IsAlreadyClosedException())
{
// pass
}
one.Dispose();
two.Dispose();
three.Dispose();
four.Dispose();
// test double-close of slicer:
slicer.Dispose();
mmapDir.Dispose();
}
[Test]
public virtual void TestCloneSliceClose()
{
MMapDirectory mmapDir = new MMapDirectory(CreateTempDir("testCloneSliceClose"));
IndexOutput io = mmapDir.CreateOutput("bytes", NewIOContext(Random));
io.WriteInt32(1);
io.WriteInt32(2);
io.Dispose();
IndexInputSlicer slicer = mmapDir.CreateSlicer("bytes", NewIOContext(Random));
IndexInput one = slicer.OpenSlice("first int", 0, 4);
IndexInput two = slicer.OpenSlice("second int", 4, 4);
one.Dispose();
try
{
one.ReadInt32();
Assert.Fail("Must throw ObjectDisposedException");
}
catch (Exception ignore) when (ignore.IsAlreadyClosedException())
{
// pass
}
Assert.AreEqual(2, two.ReadInt32());
// reopen a new slice "one":
one = slicer.OpenSlice("first int", 0, 4);
Assert.AreEqual(1, one.ReadInt32());
one.Dispose();
two.Dispose();
slicer.Dispose();
mmapDir.Dispose();
}
// LUCENENET specific: exercises the shared MemoryMappedFile refactor
// where OpenInput, CreateSlicer, its slices, and clones all piggyback
// on a single MemoryMappedFile per file (per directory instance).
// Verifies that (a) concurrent IndexInputs all see correct bytes,
// (b) disposing in arbitrary order keeps siblings functional, and
// (c) once the last referrer is disposed the OS handle is released
// (on Windows a still-open mapping would prevent the file delete).
[Test, LuceneNetSpecific]
public virtual void TestSharedMappingLifecycle()
{
var tempDir = CreateTempDir("testSharedMappingLifecycle");
MMapDirectory mmapDir = new MMapDirectory(tempDir);
const string name = "bytes";
using (IndexOutput io = mmapDir.CreateOutput(name, NewIOContext(Random)))
{
// 4 ints at offsets 0, 4, 8, 12 — each slice reads a known value.
io.WriteInt32(10);
io.WriteInt32(20);
io.WriteInt32(30);
io.WriteInt32(40);
}
// Open several IndexInputs for the same file through both
// OpenInput and CreateSlicer. All should share one mapping.
IndexInput root = mmapDir.OpenInput(name, IOContext.DEFAULT);
IndexInput rootClone = (IndexInput)root.Clone();
IndexInputSlicer slicer = mmapDir.CreateSlicer(name, NewIOContext(Random));
IndexInput sliceA = slicer.OpenSlice("a", 0, 4);
IndexInput sliceB = slicer.OpenSlice("b", 8, 4);
IndexInput sliceAClone = (IndexInput)sliceA.Clone();
// Reads across all instances must be independent and correct.
Assert.AreEqual(10, root.ReadInt32());
Assert.AreEqual(10, rootClone.ReadInt32());
Assert.AreEqual(10, sliceA.ReadInt32());
Assert.AreEqual(30, sliceB.ReadInt32());
Assert.AreEqual(10, sliceAClone.ReadInt32());
// Dispose a clone first; the root and siblings must keep working.
rootClone.Dispose();
root.Seek(4);
Assert.AreEqual(20, root.ReadInt32());
sliceB.Seek(0);
Assert.AreEqual(30, sliceB.ReadInt32());
// Dispose a slice; its siblings from the same slicer must keep working.
sliceAClone.Dispose();
sliceA.Seek(0);
Assert.AreEqual(10, sliceA.ReadInt32());
// Dispose the remaining slice-side instances. The root IndexInput
// owns its own mapping, so it must stay alive and readable.
sliceA.Dispose();
sliceB.Dispose();
slicer.Dispose();
root.Seek(12);
Assert.AreEqual(40, root.ReadInt32());
// Disposing the root tears down its MemoryMappedFile and backing
// FileStream.
root.Dispose();
// If any OS file handle is still open, this delete will fail on
// Windows. On Unix it silently unlinks but the test still proves
// the read-phase invariants above.
mmapDir.DeleteFile(name);
Assert.IsFalse(File.Exists(Path.Combine(tempDir.FullName, name)));
mmapDir.Dispose();
}
[Test]
public virtual void TestSeekZero()
{
for (int i = 0; i < 31; i++)
{
MMapDirectory mmapDir = new MMapDirectory(CreateTempDir("testSeekZero"), null, 1 << i);
IndexOutput io = mmapDir.CreateOutput("zeroBytes", NewIOContext(Random));
io.Dispose();
IndexInput ii = mmapDir.OpenInput("zeroBytes", NewIOContext(Random));
ii.Seek(0L);
ii.Dispose();
mmapDir.Dispose();
}
}
[Test]
public virtual void TestSeekSliceZero()
{
for (int i = 0; i < 31; i++)
{
MMapDirectory mmapDir = new MMapDirectory(CreateTempDir("testSeekSliceZero"), null, 1 << i);
IndexOutput io = mmapDir.CreateOutput("zeroBytes", NewIOContext(Random));
io.Dispose();
IndexInputSlicer slicer = mmapDir.CreateSlicer("zeroBytes", NewIOContext(Random));
IndexInput ii = slicer.OpenSlice("zero-length slice", 0, 0);
ii.Seek(0L);
ii.Dispose();
slicer.Dispose();
mmapDir.Dispose();
}
}
[Test]
public virtual void TestSeekEnd()
{
for (int i = 0; i < 17; i++)
{
MMapDirectory mmapDir = new MMapDirectory(CreateTempDir("testSeekEnd"), null, 1 << i);
IndexOutput io = mmapDir.CreateOutput("bytes", NewIOContext(Random));
var bytes = new byte[1 << i];
Random.NextBytes(bytes);
io.WriteBytes(bytes, bytes.Length);
io.Dispose();
IndexInput ii = mmapDir.OpenInput("bytes", NewIOContext(Random));
var actual = new byte[1 << i];
ii.ReadBytes(actual, 0, actual.Length);
Assert.AreEqual(new BytesRef(bytes), new BytesRef(actual));
ii.Seek(1 << i);
ii.Dispose();
mmapDir.Dispose();
}
}
[Test]
public virtual void TestSeekSliceEnd()
{
for (int i = 0; i < 17; i++)
{
MMapDirectory mmapDir = new MMapDirectory(CreateTempDir("testSeekSliceEnd"), null, 1 << i);
IndexOutput io = mmapDir.CreateOutput("bytes", NewIOContext(Random));
var bytes = new byte[1 << i];
Random.NextBytes(bytes);
io.WriteBytes(bytes, bytes.Length);
io.Dispose();
IndexInputSlicer slicer = mmapDir.CreateSlicer("bytes", NewIOContext(Random));
IndexInput ii = slicer.OpenSlice("full slice", 0, bytes.Length);
var actual = new byte[1 << i];
ii.ReadBytes(actual, 0, actual.Length);
Assert.AreEqual(new BytesRef(bytes), new BytesRef(actual));
ii.Seek(1 << i);
ii.Dispose();
slicer.Dispose();
mmapDir.Dispose();
}
}
[Test]
[Slow]
public virtual void TestSeeking()
{
for (int i = 0; i < 10; i++)
{
MMapDirectory mmapDir = new MMapDirectory(CreateTempDir("testSeeking"), null, 1 << i);
IndexOutput io = mmapDir.CreateOutput("bytes", NewIOContext(Random));
var bytes = new byte[1 << (i + 1)]; // make sure we switch buffers
Random.NextBytes(bytes);
io.WriteBytes(bytes, bytes.Length);
io.Dispose();
IndexInput ii = mmapDir.OpenInput("bytes", NewIOContext(Random));
var actual = new byte[1 << (i + 1)]; // first read all bytes
ii.ReadBytes(actual, 0, actual.Length);
Assert.AreEqual(new BytesRef(bytes), new BytesRef(actual));
for (int sliceStart = 0; sliceStart < bytes.Length; sliceStart++)
{
for (int sliceLength = 0; sliceLength < bytes.Length - sliceStart; sliceLength++)
{
var slice = new byte[sliceLength];
ii.Seek(sliceStart);
ii.ReadBytes(slice, 0, slice.Length);
Assert.AreEqual(new BytesRef(bytes, sliceStart, sliceLength), new BytesRef(slice));
}
}
ii.Dispose();
mmapDir.Dispose();
}
}
// note instead of seeking to offset and reading length, this opens slices at the
// the various offset+length and just does readBytes.
[Test]
[Slow]
public virtual void TestSlicedSeeking()
{
for (int i = 0; i < 10; i++)
{
MMapDirectory mmapDir = new MMapDirectory(CreateTempDir("testSlicedSeeking"), null, 1 << i);
IndexOutput io = mmapDir.CreateOutput("bytes", NewIOContext(Random));
var bytes = new byte[1 << (i + 1)]; // make sure we switch buffers
Random.NextBytes(bytes);
io.WriteBytes(bytes, bytes.Length);
io.Dispose();
IndexInput ii = mmapDir.OpenInput("bytes", NewIOContext(Random));
var actual = new byte[1 << (i + 1)]; // first read all bytes
ii.ReadBytes(actual, 0, actual.Length);
ii.Dispose();
Assert.AreEqual(new BytesRef(bytes), new BytesRef(actual));
IndexInputSlicer slicer = mmapDir.CreateSlicer("bytes", NewIOContext(Random));
for (int sliceStart = 0; sliceStart < bytes.Length; sliceStart++)
{
for (int sliceLength = 0; sliceLength < bytes.Length - sliceStart; sliceLength++)
{
var slice = new byte[sliceLength];
IndexInput input = slicer.OpenSlice("bytesSlice", sliceStart, slice.Length);
input.ReadBytes(slice, 0, slice.Length);
input.Dispose();
Assert.AreEqual(new BytesRef(bytes, sliceStart, sliceLength), new BytesRef(slice));
}
}
slicer.Dispose();
mmapDir.Dispose();
}
}
[Test]
public virtual void TestRandomChunkSizes()
{
int num = AtLeast(10);
for (int i = 0; i < num; i++)
{
AssertChunking(Random, TestUtil.NextInt32(Random, 20, 100));
}
}
private void AssertChunking(Random random, int chunkSize)
{
DirectoryInfo path = CreateTempDir("mmap" + chunkSize);
MMapDirectory mmapDir = new MMapDirectory(path, null, chunkSize);
// LUCENENET specific - unmap hack not needed
//// we will map a lot, try to turn on the unmap hack
//if (MMapDirectory.UNMAP_SUPPORTED)
//{
// mmapDir.UseUnmap = true;
//}
MockDirectoryWrapper dir = new MockDirectoryWrapper(random, mmapDir);
RandomIndexWriter writer = new RandomIndexWriter(random, dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).SetMergePolicy(NewLogMergePolicy()));
Document doc = new Document();
Field docid = NewStringField("docid", "0", Field.Store.YES);
Field junk = NewStringField("junk", "", Field.Store.YES);
doc.Add(docid);
doc.Add(junk);
int numDocs = 100;
for (int i = 0; i < numDocs; i++)
{
docid.SetStringValue("" + i);
junk.SetStringValue(TestUtil.RandomUnicodeString(random));
writer.AddDocument(doc);
}
IndexReader reader = writer.GetReader();
writer.Dispose();
int numAsserts = AtLeast(100);
for (int i = 0; i < numAsserts; i++)
{
int docID = random.Next(numDocs);
Assert.AreEqual("" + docID, reader.Document(docID).Get("docid"));
}
reader.Dispose();
dir.Dispose();
}
// LUCENENET: Regression test for GitHub #1090. A background thread
// extends a file on disk while the foreground thread repeatedly
// opens it with MMapDirectory.OpenInput. The original failure
// mode was ArgumentOutOfRangeException(paramName="capacity")
// from MemoryMappedFile.CreateFromFile, because the on-disk file
// size could exceed our caller-computed capacity by the time the
// framework did its internal stat. .NET Framework's
// CreateFromFile reads fileStream.Length multiple times
// non-atomically (referencesource MemoryMappedFile.cs L192-L243);
// modern .NET snapshots it into a single local
// (dotnet/runtime MemoryMappedFile.cs L237-L268). Even when we
// pass capacity: 0 the .NET Framework path still races because
// the length is re-read for both the defaulting step and the
// capacity-vs-size guard. SharedMapping.Create handles the
// residual race with a retry loop. This test asserts that
// OpenInput continues to succeed under concurrent file
// extension.
//
// Test design notes:
// - The writer extends only (never truncates). Truncating a
// user-mapped file on Windows fails with ERROR_USER_MAPPED_FILE
// and is unrelated to what we're verifying here.
// - The reader runs a bounded number of iterations rather than a
// wall-clock loop. Sustained mmap churn (thousands of
// map/unmap pairs per second) can transiently exhaust Windows
// kernel resources (ERROR_NO_SYSTEM_RESOURCES,
// ERROR_ACCESS_DENIED on view creation), which is also
// unrelated to the capacity race. A few hundred iterations
// are plenty to repeatedly hit the race window.
[Test, LuceneNetSpecific, Nightly]
public void TestOpenInputConcurrentFileExtension_Issue1090()
{
var dir = CreateTempDir("testOpenInputConcurrentFileExtension");
const string name = "data.bin";
string filePath = Path.Combine(dir.FullName, name);
// Seed with a small initial payload.
File.WriteAllBytes(filePath, new byte[64]);
using var mmapDir = new MMapDirectory(dir);
const long maxFileSize = 64L * 1024 * 1024; // 64 MiB safety cap
using var stop = new ManualResetEventSlim(false);
Exception writerError = null;
var writer = new Thread(() =>
{
var chunk = new byte[64];
try
{
// ReSharper disable once AccessToDisposedClosure - thread joined below
while (!stop.IsSet)
{
using var fs = new FileStream(filePath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite);
fs.Seek(0, SeekOrigin.End);
if (fs.Length >= maxFileSize)
{
// Stop extending if we somehow reach the cap. The
// reader's bounded iteration count guarantees this
// is far above what we'll hit in a normal run.
break;
}
fs.Write(chunk, 0, chunk.Length);
}
}
catch (Exception e)
{
writerError = e;
}
})
{ IsBackground = true, Name = "mmap-issue1090-extender" };
writer.Start();
try
{
// Bounded iteration count keeps mmap churn well below the
// Windows kernel-resource threshold while still exercising
// the capacity race many times over.
const int iterations = 500;
for (int i = 0; i < iterations; i++)
{
using (var _ = mmapDir.OpenInput(name, NewIOContext(Random)))
{
// Just open and dispose; the race occurs during construction.
}
}
}
finally
{
stop.Set();
writer.Join();
}
if (writerError != null)
{
throw new Exception("Writer thread failed", writerError);
}
}
// Regression test for issue #1013: sporadic AccessViolationException
// during concurrent search with SearcherManager on MMapDirectory.
//
// Strategy: spin many reader threads cloning + reading a shared
// IndexInput while another thread disposes it mid-flight. The
// invariant under test: concurrent Clone/read against a Dispose
// must only ever surface AlreadyClosed-style exceptions — never an
// AVE (which crashes the test host), never an NRE, never an IOE
// from a half-torn-down mapping.
//
// Under the chunked, reclaimer-backed design, clones observe the closed
// mapping (a chunk crossing after close throws) and throw AlreadyClosed
// promptly after the root is disposed. A successful pass here is
// therefore a *positive* result — not Inconclusive — because the
// expected behavior is that the invariant holds throughout.
// [Nightly]: wall-clock stress loop (up to ~30s). Kept out of the
// default run so CI isn't lengthened, but exercised in nightly runs
// where catching regressions in the #1013 race path is worth the time.
[Test, LuceneNetSpecific, Slow, Nightly, NonParallelizable]
public void TestConcurrentCloneReadVsDispose_Issue1013()
{
var dirPath = CreateTempDir("testIssue1013");
using var mmapDir = new MMapDirectory(dirPath);
const string name = "bytes";
const int fileSize = 1 << 20; // 1 MiB
var random = Random;
using (var io = mmapDir.CreateOutput(name, NewIOContext(random)))
{
var buf = new byte[4096];
random.NextBytes(buf);
for (int written = 0; written < fileSize; written += buf.Length)
{
io.WriteBytes(buf, 0, buf.Length);
}
}
const int readerThreads = 8;
const int maxSeconds = 30;
var sw = Stopwatch.StartNew();
int iteration = 0;
int raceObserved = 0;
var unexpectedExceptions = new ConcurrentBag<Exception>();
while (sw.Elapsed < TimeSpan.FromSeconds(maxSeconds) && raceObserved == 0)
{
iteration++;
var primary = mmapDir.OpenInput(name, NewIOContext(random));
using var start = new ManualResetEventSlim(false);
var threads = new Thread[readerThreads];
long totalReads = 0;
for (int i = 0; i < readerThreads; i++)
{
threads[i] = new Thread(() =>
{
// ReSharper disable once AccessToDisposedClosure - thread joined below
start.Wait();
try
{
while (true)
{
IndexInput clone;
try
{
// ReSharper disable once AccessToDisposedClosure - thread joined below
clone = (IndexInput)primary.Clone();
}
catch (Exception e) when (e.IsAlreadyClosedException())
{
return;
}
try
{
for (int p = 0; p < fileSize; p++)
{
clone.ReadByte();
Interlocked.Increment(ref totalReads);
}
}
catch (Exception e) when (e.IsAlreadyClosedException())
{
return;
}
}
}
catch (Exception e)
{
unexpectedExceptions.Add(e);
Interlocked.Exchange(ref raceObserved, 1);
}
})
{ IsBackground = true, Name = $"issue1013-reader-{i}" };
threads[i].Start();
}
start.Set();
Thread.Sleep(random.Next(1, 5));
primary.Dispose();
// Join every reader. The reclaimer blocks the unmap until
// in-flight reads drain, and clones that cross into a closed
// chunk observe it and exit via the expected-AlreadyClosed
// catch. So Join timing out would itself be a defect - either
// the reclaimer is leaking or a reader is stuck in a broken
// state. Record that and fail rather than silently abandoning
// the thread.
foreach (var t in threads)
{
if (!t.Join(TimeSpan.FromSeconds(10)))
{
unexpectedExceptions.Add(new TimeoutException(
$"Reader thread {t.Name} did not exit within 10s after primary.Dispose(); " +
"expected AlreadyClosed to propagate out of the read path."));
Interlocked.Exchange(ref raceObserved, 1);
// Continue joining the rest so we don't leak live
// threads holding IndexInput clones into later
// iterations or subsequent tests.
}
}
if (iteration % 50 == 0)
{
TestContext.Progress.WriteLine(
$"issue1013 repro: iteration={iteration}, elapsed={sw.Elapsed.TotalSeconds:0.0}s, reads={totalReads}");
}
}
if (raceObserved != 0)
{
var example = unexpectedExceptions.FirstOrDefault();
Assert.Fail(
$"Issue #1013 invariant violated on iteration {iteration}: " +
$"concurrent clone/read vs Dispose produced an unexpected exception type. " +
$"Example: {example?.GetType().FullName}: {example?.Message}\n{example}");
}
Assert.Pass(
$"Issue #1013 invariant held across {iteration} iterations in " +
$"{sw.Elapsed.TotalSeconds:0.0}s — no AVE / NRE / unexpected exception " +
"under concurrent clone/read vs Dispose.");
}
// LUCENENET-specific (#1013): the disposing thread is the SAME thread that
// owns and is reading the primary, while OTHER threads concurrently read
// clones that share the primary's mapping. This pins the invariant that a
// same-thread Dispose is NOT the Java unmap-hack: disposing the owning input
// closes the shared mapping (requesting its unmap), but the DrainReclaimer
// blocks the actual unmap until every in-flight reader drains, so concurrent
// readers on sibling clones are never left dereferencing a freed view.
// Expected outcomes for the sibling readers: valid bytes, or AlreadyClosed
// once they cross into a closed chunk. Never an AVE, NRE, or
// torn-down-mapping IOException.
// [Nightly]: wall-clock stress loop (~15s).
[Test, LuceneNetSpecific, Slow, Nightly, NonParallelizable]
public void TestSameThreadOwnerDisposeWhileSiblingClonesRead_NoAVE()
{
var dirPath = CreateTempDir("testSameThreadDisposeVsSiblingReads");
using var mmapDir = new MMapDirectory(dirPath);
const string name = "bytes";
const int fileSize = 1 << 20; // 1 MiB, spans multiple chunks
var random = Random;
using (var io = mmapDir.CreateOutput(name, NewIOContext(random)))
{
var buf = new byte[4096];
random.NextBytes(buf);
for (int w = 0; w < fileSize; w += buf.Length)
io.WriteBytes(buf, 0, buf.Length);
}
const int siblingReaders = 6;
var unexpected = new ConcurrentBag<Exception>();
int iterations = 0;
var sw = Stopwatch.StartNew();
while (sw.Elapsed < TimeSpan.FromSeconds(15) && unexpected.IsEmpty)
{
iterations++;
// The primary is opened, read, AND disposed all on THIS thread.
var primary = mmapDir.OpenInput(name, NewIOContext(random));
using var start = new ManualResetEventSlim(false);
using var stop = new ManualResetEventSlim(false);
var readers = new Thread[siblingReaders];
for (int i = 0; i < readers.Length; i++)
{
readers[i] = new Thread(() =>
{
// Each sibling reads its OWN clone, which shares primary's
// mapping. Clone before the barrier; if the primary is
// already disposed (later iterations race), Clone throws
// AlreadyClosed, which is an acceptable outcome.
IndexInput clone;
try
{
// ReSharper disable once AccessToDisposedClosure - thread joined below
clone = (IndexInput)primary.Clone();
}
catch (Exception e) when (e.IsAlreadyClosedException())
{
return;
}
// ReSharper disable once AccessToDisposedClosure - thread joined below
start.Wait();
try
{
// ReSharper disable once AccessToDisposedClosure - thread joined below
while (!stop.IsSet)
{
clone.Seek(0);
for (int p = 0; p < fileSize; p++)
clone.ReadByte();
}
}
catch (Exception e) when (e.IsAlreadyClosedException())
{
// Expected once the owner disposes and we cross into a
// closed chunk.
}
catch (Exception e)
{
unexpected.Add(e);
}
})
{ IsBackground = true, Name = $"sibling-reader-{i}" };
readers[i].Start();
}
start.Set();
// The owning thread reads the primary itself for a beat, then
// disposes it SAME-THREAD while the siblings are mid-read.
try
{
primary.Seek(0);
for (int p = 0; p < fileSize && p < 64 * 1024; p++)
primary.ReadByte();
}
catch (Exception e) when (e.IsAlreadyClosedException())
{
// Not expected here (we haven't disposed yet), but harmless.
}
primary.Dispose(); // same-thread close of the owning input
stop.Set();
foreach (var t in readers)
{
if (!t.Join(TimeSpan.FromSeconds(10)))
{
unexpected.Add(new TimeoutException(
$"Sibling reader {t.Name} did not exit within 10s after the " +
"owner's same-thread Dispose; expected AlreadyClosed to propagate."));
}
}
}
if (!unexpected.IsEmpty)
{
var ex = unexpected.First();
Assert.Fail(
$"Same-thread owner Dispose vs concurrent sibling-clone reads produced an " +
$"unexpected exception after {iterations} iterations: " +
$"{ex.GetType().FullName}: {ex.Message}\n{ex}");
}
Assert.Pass(
$"Same-thread owner Dispose did not AVE concurrent sibling readers across " +
$"{iterations} iterations in {sw.Elapsed.TotalSeconds:0.0}s.");
}
// LUCENENET-specific: race-condition coverage for the chunked,
// reclaimer-backed MMapIndexInput. These tests complement the
// single-threaded TestCloneClose / TestCloneSliceSafety /
// TestCloneSliceClose tests by exercising concurrent Dispose vs.
// read, Dispose vs. Clone, and slicer-cascade scenarios.
// Concurrent Clone during Dispose: the root is disposed while many
// threads repeatedly call Clone() + ReadByte(). Invariants:
// - No AVE / NRE / memory corruption.
// - Once primary.Dispose has returned and the cloner thread has
// observed that, subsequent reads on its current clone throw
// AlreadyClosed.
// - After join, calling Clone() + read on the disposed primary
// from the main thread throws AlreadyClosed — pinning that a
// disposed root cannot silently hand out a working clone.
// [Nightly]: wall-clock stress loop (~15s). See Issue1013 rationale.
[Test, LuceneNetSpecific, Slow, Nightly, NonParallelizable]
public void TestConcurrentCloneVsDispose_RaceScenario()
{
var dirPath = CreateTempDir("testCloneVsDispose");
using var mmapDir = new MMapDirectory(dirPath);
const string name = "bytes";
const int fileSize = 64 * 1024;
var random = Random;
using (var io = mmapDir.CreateOutput(name, NewIOContext(random)))
{
var buf = new byte[4096];
random.NextBytes(buf);
for (int w = 0; w < fileSize; w += buf.Length)
io.WriteBytes(buf, 0, buf.Length);
}
var unexpected = new ConcurrentBag<Exception>();
int iterations = 0;
var sw = Stopwatch.StartNew();
while (sw.Elapsed < TimeSpan.FromSeconds(15))
{
iterations++;
var primary = mmapDir.OpenInput(name, NewIOContext(random));
using var start = new ManualResetEventSlim(false);
var cloners = new Thread[6];
for (int i = 0; i < cloners.Length; i++)
{
cloners[i] = new Thread(() =>
{
// ReSharper disable once AccessToDisposedClosure - thread joined below
start.Wait();
try
{
while (true)
{
IndexInput c;
// ReSharper disable once AccessToDisposedClosure - thread joined below
try { c = (IndexInput)primary.Clone(); }
catch (Exception e) when (e.IsAlreadyClosedException()) { return; }
// Touch a byte on the clone — but don't read past dispose to keep the test focused on Clone itself.
try { c.ReadByte(); }
catch (Exception e) when (e.IsAlreadyClosedException()) { return; }
}
}
catch (Exception e) { unexpected.Add(e); }
}) { IsBackground = true };
cloners[i].Start();
}
start.Set();
Thread.Sleep(random.Next(0, 3));
primary.Dispose();
foreach (var t in cloners)
{
if (!t.Join(TimeSpan.FromSeconds(5)))
{
unexpected.Add(new TimeoutException(
"Cloner thread did not exit within 5s after primary.Dispose()."));
}
}
// Positive contract check: after Dispose, Clone() on the
// disposed root either throws AlreadyClosed or produces a
// clone whose first read throws AlreadyClosed. The failure
// mode we want to catch is a clone that silently hands back
// bytes from a released mapping.
try
{
var postDisposeClone = (IndexInput)primary.Clone();
try
{
postDisposeClone.ReadByte();
unexpected.Add(new InvalidOperationException(
"Clone() + ReadByte() on disposed primary returned without throwing AlreadyClosed."));
}
catch (Exception e) when (e.IsAlreadyClosedException())
{
// expected
}
}
catch (Exception e) when (e.IsAlreadyClosedException())
{
// also acceptable: Clone() itself refused
}
}
if (!unexpected.IsEmpty)
{
var ex = unexpected.First();
Assert.Fail($"Concurrent Clone-vs-Dispose produced unexpected exception after {iterations} iterations: {ex.GetType().FullName}: {ex.Message}\n{ex}");
}
}
// Concurrent read of the SAME instance during Dispose of that
// instance. Drain-barrier must prevent the disposer from releasing
// the pointer while a reader is mid-CopyBlockUnaligned.
// [Nightly]: wall-clock stress loop (~15s). See Issue1013 rationale.
[Test, LuceneNetSpecific, Slow, Nightly, NonParallelizable]
public void TestConcurrentReadVsSelfDispose_RaceScenario()
{
var dirPath = CreateTempDir("testReadVsSelfDispose");
using var mmapDir = new MMapDirectory(dirPath);
const string name = "bytes";
const int fileSize = 1 << 18; // 256 KiB — enough for several buffer refills
var random = Random;
using (var io = mmapDir.CreateOutput(name, NewIOContext(random)))
{
var buf = new byte[4096];
random.NextBytes(buf);
for (int w = 0; w < fileSize; w += buf.Length)
io.WriteBytes(buf, 0, buf.Length);