From c14aeab49f356655685b5ab51483b1d517f2e0e6 Mon Sep 17 00:00:00 2001 From: Matthew Lorimor Date: Tue, 10 Nov 2026 16:26:02 -0600 Subject: [PATCH] Read on through a background collection until its pause lands in a read (#357) TestAReadIsMeasuredExactlyWithABackgroundCollectionRunning's guard failed once in 9 full net10.0 runs, and in one clean-clone run on a loaded machine on both frameworks: DpswSketch's large-form read counted 4,648,328 bytes at most, with nothing to keep a background collection out, against 4,648,328 quietly. It passed run alone, and on all five CI runners. The cause is where a background collection reaches the count. It does so once, at the pause that ends its marking: there, with the runtime suspended, it voids every thread's allocation context, zeroing its pointer and limit without taking the part left unused off alloc_bytes, where a blocking collection's fix_allocation_context takes it off; and GetAllocatedBytesForCurrentThread is alloc_bytes + alloc_bytes_uoh - (alloc_limit - alloc_ptr). So a count is high by what the read's context had left, if and only if that pause comes during the read. dotnet/runtime v10.0.14 gc.cpp: gc_heap::background_mark_phase, after bgc_suspend_EE, ends calling repair_allocation_contexts (FALSE), which applies void_allocation; comutilnative.cpp GCInterface::GetAllocatedBytesForCurrentThread. v11.0.0 has the same in background.cpp and allocation.cpp. Read 2026-11-10. Neither of the guesses the plan named: in none of 2,460 probed attempts did the collection end before the read began, and in every one it had started before it. What decides it is how long marking takes against the read. - Probed with the runtime's GC events (GCStart/End, SuspendEE/RestartEE) timing each read against its collection's pauses: 1,671 of the 1,680 reads the final pause fell in came out high, by 16 to 8,192 bytes; none of the 140 that ended before it, nor the 180 started after it (a read made to wait for the pause before starting), was disturbed. - In full-suite runs, marking (start to final pause) took 2 to 30 ms against a read of about 11 to 21 ms, varying between runs with the machine. In the three runs where it took longest (one framework alone, and both at once), 12, 16 and 19 reads in 100 came out exact, and the 16 timed against the pause had all ended before it; in eight others, both frameworks at once with up to two other suites beside them, 0 to 5 in 100 did. - With small objects added to the live heap, marking lengthened in step: 0 MB 0.8 ms, 400 MB 12.7 ms, 800 MB 21.6 ms, 1.6 GB 42 ms, against reads of 9 to 20 ms; reads ending before the pause went 0/60, 4/60, 59/60, 60/60. - What made marking slow in some full runs and not others was not pinned down. It was not which CCD of this 7950X3D the suite ran on (pinned to either, it marked in 2 to 5 ms), nor sharing one CPU (2.3 ms against a 22 ms read, run alone), and two suites looping beside it did not bring it on. So the old guard, which counted one read straight after starting each of five collections, failed whenever marking outlasted the read for the length of the test, and retrying that same attempt does not help when a heap or a machine holds the condition: at 1.6 GB every one of 60 missed. The guard now reads on while a collection runs, starting another only once it has ended, until a read counts above quiet, for at most GuardReads = 50 reads. The end of a collection is told by GCKind.Background's index, noted after the blocking collections that start each one, since those wait for one still running. The loop is CountUntilDisturbed, which the test calls and three scripted tests hold: it reads on through a collection and starts another only once it has ended; with nothing disturbed it counts every read it may and returns the most; and it reaches the longest wait measured. A fourth test holds the hook itself: a collection started while another is still marking is taken for ended once it has ended and not before, and the other once it has. The guard also gets its other direction: the read counted the same way after the same blocking collections, with no background one, must come out no higher than quiet, so a count high for another reason cannot pass for a disturbance. The cap rests on reads to a disturbance, measured with the new loop: - 0 or 400 MB added: 1 read in all of 60 waits. 800 MB: 2 in all of 30. - 1.6 GB, one framework: 3 in 28 of 30, 4 in one, 10 (in two collections) in one. 1.6 GB, both frameworks at once: 3 to 12 in 10 waits (12 over two collections), and 3 to 8 in 50 more. Longest: 12; collections that ended without disturbing a read: 2 of the 92 started at 1.6 GB. - 50 is about four times 12. Counted in a region instead, where nothing can disturb it, the read took the guard to its fiftieth read and a failure in about two seconds, run alone. Red and green under the condition made certain, a probe running the guard as it was at 7e9e63d and as it is now in one process, with both frameworks at once: - 800 MB added: old failed 10 of 10 on net10.0 and 10 of 10 on net11.0; new passed 10 of 10 on each. - 1.6 GB added: old failed 5 of 5 on each; new passed 5 of 5, and 25 of 25 more on each. - Nothing added: both passed 10 of 10 on each. In ordinary full runs on this 16-core 7950X3D, loaded with other suites, the old test did not fail: marking stayed fast, and the old guard took the most of five reads, so at the machine's low miss rate all five rarely missed at once. It passed 30 full runs on each framework, loaded with two other suites. The failure is reproduced by lengthening marking, not by load alone here, which is why the probe adds to the live heap; the original report had it once in 9 net10.0 runs on another machine. Green, the fix in full suite runs with both frameworks: 10 loaded two-framework rounds with two other suites looping beside each, and 3 net10.0 runs alone, all passed the test, which on this fast machine is disturbed at its first read every time. Each framework runs 2,711 tests, 4 more than 7e9e63d's 2,707: the one test becomes itself plus three that hold the read-on loop from a script and one that holds the end-of-collection hook. Mutation through scripts/mutate.sh on this commit, scoped to TestAllocationMeasurement, both frameworks (the script reads each framework's summary). Every condition the fix adds, dropped, flipped or shifted; the counts are failing tests on net10.0 and net11.0: G1 guard counts in a region, so no read is ever disturbed killed (1, 1) G2 the background collection made blocking killed (2, 2) G3 cap of 1 killed (1, 1) G4 cap of 11, one short of the longest wait measured killed (1, 1) G5 every count without a region 8 bytes high killed (1, 1) G6 the undisturbed control counts with a collection started killed (1, 1) L1 a count equal to quiet taken for a disturbance killed (3, 3) L2 a collection started before every read, not only when ended killed (3, 3) L3 no collection started after the first killed (2, 2) L4 one read short of the cap killed (1, 1) L5 one read past the cap killed (1, 1) L6 the last count returned, not the most killed (1, 1) L7 the least count returned, not the most killed (1, 1) L8 collections not counted killed (3, 3) L9 nothing disturbed, but one over the most returned killed (1, 1) S1 the last end noted before the blocking collections killed (1, 1) S2 the end told by an index that has not changed killed (1, 1) S3 a collection never taken for ended killed (1, 1) S4 no blocking collection before the background one killed (1, 1) 19 killed, 0 survived. The brief's two named mutants are G1 and G3: G1 changes only the guard's own count, to one taken in a region where no collection can disturb it, so a disturbance never happens -- killed by the guard test itself, the one failing test on each framework, which is the vacuity guard still biting. G3 is killed by TestTheGuardReadsAsFarAsTheLongestWaitForADisturbanceMeasured, which fails by count whatever the machine, so the cap is pinned deterministically rather than by a race this fast machine happens to win. TESTING.md records the lesson beside #293's. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01KK3MspnYsGe3E6AZW1Prra --- TESTING.md | 13 + .../TestAllocationMeasurement.cs | 278 ++++++++++++++++-- 2 files changed, 267 insertions(+), 24 deletions(-) diff --git a/TESTING.md b/TESTING.md index 18cdb94..8d7f987 100644 --- a/TESTING.md +++ b/TESTING.md @@ -929,6 +929,19 @@ rest of a message survives, as it should, and one that deletes the guard does no guard needs the same read, counted without a region, to come out high, so that a runtime whose counter no longer minds fails the test rather than passing it. A new measurement uses the helper, not the counter. +- **A guard waits for what it needs to see, rather than retrying a race for it.** That + guard counted one read straight after starting each of five collections, and a loaded + run counted all five exactly (#357). A background collection reaches the count only at + the pause that ends its marking, where it voids every thread's allocation context without + taking what was left unused in it off the thread's count (gc.cpp, + `gc_heap::background_mark_phase`, at v10.0.14 and v11.0.0); a read that ends before that + pause is counted exactly. Whether a read held it was not a draw but how long marking took + against the read, which a heap or a machine can hold for every repeat: with 800 MB of + small objects added to the live heap, 59 reads in 60 ended before the pause, and the old + guard failed ten times in ten on each framework; with 1.6 GB, 60 in 60 did, and no number + of retries would have helped. The guard now reads on while each collection runs until a + read holds its pause, and gives up after 50 reads, about four times the longest wait + measured. - **A refusal's number is held to loading.** Honest charges were not enough: a refusal named the running total at the charge that failed, so a read refused needing a number was refused again, needing more, under exactly that number. Every read is now priced diff --git a/TestProbabilisticDataStructures/TestAllocationMeasurement.cs b/TestProbabilisticDataStructures/TestAllocationMeasurement.cs index 25f0f1d..7b9d95b 100644 --- a/TestProbabilisticDataStructures/TestAllocationMeasurement.cs +++ b/TestProbabilisticDataStructures/TestAllocationMeasurement.cs @@ -1,9 +1,11 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime; +using System.Threading; using Microsoft.VisualStudio.TestTools.UnitTesting; using ProbabilisticDataStructures; @@ -29,11 +31,18 @@ public class TestAllocationMeasurement /// read, quietly 4,648,320 bytes, was once measured at 4,656,208, past the margin /// its test allows (#293). A background collection started before each repeat is /// that run's condition made certain. The read is that one, the longest the - /// suite's budget samples make. The guard measures the same read the same way - /// without the measurement's own protection, and needs it to come out high at - /// least once, so that a runtime whose counter a background collection no longer - /// disturbs fails here rather than passing by testing nothing. Not run in parallel, - /// so that the collections are this test's own. + /// suite's budget samples make. Not run in parallel, so that the collections are + /// this test's own. + /// + /// The guard counts the same read the same way without the measurement's protection, + /// and needs a count to come out high, so that a runtime whose counter a background + /// collection no longer disturbs fails here rather than passing by testing nothing. A + /// collection disturbs only a read that the end of its marking falls in, so the guard + /// reads on until one does, as says (#357). It also + /// needs the read counted that way after the same blocking collections, with no + /// background one, to come out no higher than quietly, so that a count high for some + /// other reason cannot pass for a disturbance. + /// /// [TestMethod] [DoNotParallelize] @@ -49,27 +58,235 @@ public void TestAReadIsMeasuredExactlyWithABackgroundCollectionRunning() Read(); var quiet = TestReadBudget.Allocated(Read); - var unprotected = Enumerable.Range(0, 5).Max(_ => - { - StartABackgroundCollection(); - var before = GC.GetAllocatedBytesForCurrentThread(); - GC.KeepAlive(Read()); - return GC.GetAllocatedBytesForCurrentThread() - before; - }); - var busy = TestReadBudget.LeastAllocated(Read, 5, StartABackgroundCollection); + var disturbed = CountUntilDisturbed(() => CountedWithoutARegion(Read), quiet, StartABackgroundCollection); + CollectFully(); + var undisturbed = CountedWithoutARegion(Read); + var busy = TestReadBudget.LeastAllocated(Read, 5, () => StartABackgroundCollection()); Console.WriteLine( - $"[MEASUREMENT] {sample.Name}: quietly {quiet:N0}, unprotected with a background collection " + - $"started first at most {unprotected:N0}, measured so {busy:N0}"); + $"[MEASUREMENT] {sample.Name}: quietly {quiet:N0}; without a region, {undisturbed:N0} with no " + + $"background collection, and {disturbed.Counted:N0} at read {disturbed.Reads}, in collection " + + $"{disturbed.Collections}, with them running; measured so {busy:N0}"); - Assert.IsGreaterThan(quiet, unprotected, - $"{sample.Name}'s read counted {unprotected:N0} bytes at most with a background collection started " + - $"before it and nothing to keep it out, and {quiet:N0} quietly, so the collection did not disturb " + - "the count and this shows nothing"); + Assert.IsGreaterThan(quiet, disturbed.Counted, + $"{sample.Name}'s read counted {disturbed.Counted:N0} bytes at most in {disturbed.Reads} reads, with " + + $"{disturbed.Collections} background collections running beside them and nothing to keep them out, " + + $"and {quiet:N0} quietly, so no collection disturbed the count and this shows nothing"); + Assert.IsLessThanOrEqualTo(quiet, undisturbed, + $"{sample.Name}'s read counted {undisturbed:N0} bytes with nothing to keep a collection out and no " + + $"background collection running, more than the {quiet:N0} it allocates quietly, so a count comes out " + + "high without a collection disturbing it and the guard shows nothing"); Assert.AreEqual(quiet, busy, $"{sample.Name}'s read was measured at {busy:N0} bytes with a background collection started before " + $"each repeat, and {quiet:N0} quietly: the collection reached the count"); } + /// + /// The guard reads on while a collection runs and starts another only once it has + /// ended, and the first count above quiet is the one it returns. + /// + [TestMethod] + public void TestTheGuardReadsOnThroughACollectionAndStartsAnotherOnlyOnceItHasEnded() + { + // The first collection ends after its second read, undisturbed; the second is + // disturbed at its second read. + var guard = new ScriptedGuard(counts: [100, 100, 100, 108], readsPerCollection: [2, 10]); + + var disturbed = CountUntilDisturbed(guard.Count, 100, guard.Start, reads: 10); + + Assert.AreEqual((108L, 4, 2), disturbed, "the guard did not read on through each collection to the count above quiet"); + Assert.AreEqual(2, guard.Started, "the guard did not start a collection once, and once more after the first ended"); + } + + /// + /// A guard no collection ever disturbs counts every read it may and no more, and + /// returns the most it counted, so that the test fails saying how far it went. + /// + [TestMethod] + public void TestAGuardNothingDisturbsCountsEveryReadItMayAndReturnsTheMost() + { + // The most is neither the first count, the last nor the least. + var guard = new ScriptedGuard(counts: [76, 92, 100, 88, 96, 84, 90], readsPerCollection: [3, 3, 3]); + + var undisturbed = CountUntilDisturbed(guard.Count, 100, guard.Start, reads: 7); + + Assert.AreEqual((100L, 7, 3), undisturbed, + "the guard did not count all seven reads, starting a collection every third, and return the most"); + Assert.AreEqual(7, guard.Counted, "the guard counted reads past the most it may"); + } + + /// + /// The guard reads as far as the longest wait for a disturbance measured: twelve + /// reads, over two collections. + /// + /// + /// Measured with 1.6 GB of small objects added to the live heap, where marking took 38 + /// to 50 ms against a read of about 18. Of 90 waits, 30 with one framework running and + /// 60 with both at once, every one took three reads or more and the longest twelve; + /// with 800 MB added, all of 30 took two, and with 400 MB or none, one (#357). Which + /// read the first collection ended at was not recorded, so the script has it run + /// through all twelve. See . + /// + [TestMethod] + public void TestTheGuardReadsAsFarAsTheLongestWaitForADisturbanceMeasured() + { + var guard = new ScriptedGuard( + counts: [100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 104], readsPerCollection: [12]); + + var disturbed = CountUntilDisturbed(guard.Count, 100, guard.Start); + + Assert.AreEqual((104L, 12, 1), disturbed, + $"the guard gives up after {GuardReads} reads, short of the twelve a disturbance has been measured to take"); + } + + /// + /// A background collection the guard starts is taken for ended once it has ended and + /// not before, though one it started before is still running when it starts. + /// + /// + /// The scripted tests above stand in for the collections; this one holds the hook the + /// guard runs. The second collection is started straight after the first, whose + /// marking is still under way, so the second's blocking collections wait for the + /// first to end. The wait for the second to end is bounded so that a hook that never + /// tells fails rather than hanging. + /// + [TestMethod] + [DoNotParallelize] + public void TestABackgroundCollectionIsTakenForEndedOnceItHasEndedAndNotBefore() + { + if (GCSettings.LatencyMode == GCLatencyMode.Batch) + { + Assert.Inconclusive("background collection is turned off in this process, so none can run"); + } + + var first = StartABackgroundCollection(); + var second = StartABackgroundCollection(); + + Assert.IsTrue(first(), + "the first collection was not taken for ended, though the second's blocking collections waited for it"); + Assert.IsFalse(second(), + "the second collection was taken for ended as soon as it began: the first's end was taken for it"); + + var waited = Stopwatch.StartNew(); + while (!second() && waited.Elapsed < TimeSpan.FromSeconds(30)) + { + Thread.Sleep(1); + } + + Assert.IsTrue(second(), $"the second collection was not taken for ended in {waited.Elapsed.TotalSeconds:N0} s"); + } + + /// + /// The most reads the guard counts without a region, waiting for a background + /// collection to disturb one, before it fails. + /// + /// + /// About four times the longest wait measured, twelve reads (see + /// ), so that + /// a collection that ends without disturbing a read, as 2 of the 92 started with 1.6 GB + /// added did, does not bring the guard near failing. Counted in a region instead, where + /// nothing can disturb it, the read took the guard to its fiftieth and failing in about + /// two seconds, run alone. + /// + internal const int GuardReads = 50; + + /// + /// Counts reads with while background collections run, starting + /// one with and another only once that one has ended, until a + /// count comes out above or have been + /// counted. Returns that count, or the most counted if none came out above, with the + /// reads and collections it took. + /// + /// + /// A background collection disturbs a thread's count once, at the pause that ends its + /// marking. There, with the runtime suspended, it voids every thread's allocation + /// context, setting its pointer and limit to zero without taking what the context had + /// left unused off the bytes the thread is counted as allocating, where a blocking + /// collection takes it off; and + /// subtracts only what a context still holds unused. So a count is high by what the + /// read's context had left when the pause came, if the pause came during the read, and + /// not otherwise: dotnet/runtime v10.0.14, gc.cpp, gc_heap::background_mark_phase + /// ends calling repair_allocation_contexts (FALSE), whose void_allocation + /// leaves alloc_bytes alone, while fix_allocation_context subtracts the + /// unused part; comutilnative.cpp, GCInterface::GetAllocatedBytesForCurrentThread. + /// v11.0.0 has the same, in background.cpp and allocation.cpp. Read 2026-11-10. + /// + /// Measured that way, with the pause timed by the runtime's own events, 1,671 of the + /// 1,680 reads it fell in came out high, by 16 to 8,192 bytes, and none of the 320 that + /// ended before it or started after it. The guard first counted one read per + /// collection, started straight after it, which catches the pause only when marking + /// takes less time than the read. In the whole suite, marking took 2 to 30 ms against + /// a read of about 11 to 21, and in the runs where it took longest, 12 to 19 reads in + /// 100 came out exact; with 800 MB of small objects added to the live heap, 59 in 60 + /// ended before the pause, and all five of a test's repeats can miss it (#357). + /// Reading on while the collection runs brings its pause into a read, whatever its + /// marking takes. A collection can still end without disturbing one, when its pause + /// falls between two reads or a read's context is empty, and the guard then starts + /// another. + /// + /// + internal static (long Counted, int Reads, int Collections) CountUntilDisturbed( + Func count, long quiet, Func> start, int reads = GuardReads) + { + long most = 0; + var collections = 0; + Func ended = null; + for (var read = 1; read <= reads; read++) + { + if (ended is null || ended()) + { + ended = start(); + collections++; + } + + var counted = count(); + if (counted > quiet) + { + return (counted, read, collections); + } + + most = Math.Max(most, counted); + } + + return (most, reads, collections); + } + + /// + /// What allocates on this thread, counted with nothing to keep + /// a collection out: the guard's count, which only this class takes. + /// + private static long CountedWithoutARegion(Func read) + { + var before = GC.GetAllocatedBytesForCurrentThread(); + GC.KeepAlive(read()); + return GC.GetAllocatedBytesForCurrentThread() - before; + } + + /// + /// Counts and collections played from a script, for holding + /// to what it does with them. + /// + private sealed class ScriptedGuard(long[] counts, int[] readsPerCollection) + { + private int readsInThisCollection; + + public int Started { get; private set; } + + public int Counted { get; private set; } + + public long Count() + { + readsInThisCollection++; + return counts[Counted++]; + } + + public Func Start() + { + var runsFor = readsPerCollection[Started++]; + readsInThisCollection = 0; + return () => readsInThisCollection >= runsFor; + } + } + /// /// An attempt whose region a collection ended is not counted: the work is measured /// again in a region of its own, and what comes back is that count. @@ -336,16 +553,29 @@ private static List Called(MethodBase method) .ToDictionary(op => op.Value)); /// - /// Starts a background collection, after a full blocking one: started alone, one - /// sometimes left a repeat undisturbed, measured in one repeat of ten, and after a - /// full collection none did, in twenty. + /// Starts a background collection, after a full blocking one, and returns whether it + /// has ended yet: started alone, one sometimes left a repeat undisturbed, measured in + /// one repeat of ten, and after a full collection none did, in twenty. /// - private static void StartABackgroundCollection() + /// + /// The last background collection to end is noted after the blocking ones, which wait + /// for one still running: noted before them, a collection still running when this is + /// called would end in them and be taken for this one ending as soon as it began. + /// + private static Func StartABackgroundCollection() + { + CollectFully(); + var ended = GC.GetGCMemoryInfo(GCKind.Background).Index; + GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: false); + return () => GC.GetGCMemoryInfo(GCKind.Background).Index != ended; + } + + /// A full blocking collection, with the finalizers it queued run and collected after it. + private static void CollectFully() { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); - GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: false); } } }