From 278d510442f98047a19fbf23c31759e7754020f6 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:09:23 +0300 Subject: [PATCH 1/2] Decode browser GRep batches on multiple threads --- src/RvtIO/Parsing/BlockParser.cs | 49 ++++++++++++++++++++++- src/RvtIO/RvtFileReader.cs | 21 +++++++--- tests/RvtIO.Tests/GRepBlockDecodeTests.cs | 46 +++++++++++++++++++++ 3 files changed, 108 insertions(+), 8 deletions(-) diff --git a/src/RvtIO/Parsing/BlockParser.cs b/src/RvtIO/Parsing/BlockParser.cs index 7fd9105..ad23edb 100644 --- a/src/RvtIO/Parsing/BlockParser.cs +++ b/src/RvtIO/Parsing/BlockParser.cs @@ -25,8 +25,9 @@ internal static void ApplyPendingGReps(ParsingState state, List pen { var job = pending[index]; var (data, start) = job.Stored?.Read() ?? (job.Chunk, job.Start); - return GRepParserV2.Parse(data, start, job.Size); + return (Data: data, Start: start, job.Size); }, + block => GRepParserV2.Parse(block.Data, block.Start, block.Size), (index, geometry) => ApplyPendingGRep(state, pending[index], geometry), progress); } @@ -47,11 +48,55 @@ internal static void ApplyPendingGRep(ParsingState state, PendingGRep job, GRepD } /// Decodes blocks and applies each result on the calling thread in index order. - /// A browser decodes and applies one block at a time; elsewhere the blocks are decoded in parallel. + /// The single-threaded browser path decodes and applies one block at a time. internal static void DecodeGRepBlocksInOrder(int count, Func decode, Action apply, Action? progress = null) => DecodeGRepBlocksInOrder(count, decode, apply, OperatingSystem.IsBrowser(), progress); + internal static void DecodeGRepBlocksInOrder(int count, Func read, Func decode, + Action apply, Action? progress = null) + { + if (!OperatingSystem.IsBrowser() || Environment.ProcessorCount < 2) + { + DecodeGRepBlocksInOrder(count, index => decode(read(index)), apply, progress); + return; + } + + // Scratch reads and result commits call browser imports on the reader's owning thread. + DecodeBrowserBatches(count, read, decode, apply, Math.Min(4, Environment.ProcessorCount), progress); + } + + internal static void DecodeBrowserBatches(int count, Func read, Func decode, + Action apply, int workers, Action? progress) + { + if (count == 0) return; + // Keep at most one decoded block per worker waiting to be committed. + var inputs = new T[Math.Min(count, workers)]; + var results = new GRepData?[inputs.Length]; + var options = new ParallelOptions { MaxDegreeOfParallelism = workers }; + var clock = progress == null ? null : System.Diagnostics.Stopwatch.StartNew(); + progress?.Invoke(0, count); + for (int offset = 0; offset < count; offset += inputs.Length) + { + int length = Math.Min(inputs.Length, count - offset); + for (int index = 0; index < length; index++) + inputs[index] = read(offset + index); + Parallel.For(0, length, options, index => results[index] = decode(inputs[index])); + for (int index = 0; index < length; index++) + { + apply(offset + index, results[index]); + results[index] = null; + inputs[index] = default!; + } + int completed = offset + length; + if (clock != null && (completed == count || clock.ElapsedMilliseconds >= 500)) + { + progress!(completed, count); + clock.Restart(); + } + } + } + /// The seam of the overload above: selects the one-block-at-a-time path of a /// browser. internal static void DecodeGRepBlocksInOrder( diff --git a/src/RvtIO/RvtFileReader.cs b/src/RvtIO/RvtFileReader.cs index 1afc4d0..d136533 100644 --- a/src/RvtIO/RvtFileReader.cs +++ b/src/RvtIO/RvtFileReader.cs @@ -997,13 +997,18 @@ private static void ScanElementStrings(PartitionChunks chunks, ParsingState stat { int first = start; int count = Math.Min(partialResults.Length, chunks.Count - first); - // Keep both memory use and merge order independent of task completion order. - Parallel.For(0, count, index => + void Scan(int index) { var localStrings = new Dictionary>(); StringScanner.ScanChunk(chunks[first + index], state.AllKnownIds, localStrings, firstNameOnly); if (localStrings.Count > 0) partialResults[index] = localStrings; - }); + } + // The OPFS stream can only be read on the worker that opened it. + if (OperatingSystem.IsBrowser() && chunks.Store != null) + { + for (int index = 0; index < count; index++) Scan(index); + } + else Parallel.For(0, count, Scan); MergeElemScanStringsInChunkOrder(partialResults, state.ElemScanStrings, seen, firstNameOnly); Array.Clear(partialResults); start += count; @@ -3029,11 +3034,15 @@ private static int ApplyFirstDecodableGReps( index => { var job = jobs[index]; - var clock = slowDiag ? System.Diagnostics.Stopwatch.StartNew() : null; var (data, start) = job.Block.Read(); - var geometry = GRepParserV2.Parse(data, start, job.Size); + return (Data: data, Start: start, job.Size, job.Eid); + }, + block => + { + var clock = slowDiag ? System.Diagnostics.Stopwatch.StartNew() : null; + var geometry = GRepParserV2.Parse(block.Data, block.Start, block.Size); if (clock != null && (clock.ElapsedMilliseconds > 2000 || geometry?.Faces.Count > 100000)) - DiagnosticSink.WriteLine($"slow GRep eid={job.Eid} ms={clock.ElapsedMilliseconds} faces={geometry?.Faces.Count}"); + DiagnosticSink.WriteLine($"slow GRep eid={block.Eid} ms={clock.ElapsedMilliseconds} faces={geometry?.Faces.Count}"); return geometry; }, (index, geometry) => diff --git a/tests/RvtIO.Tests/GRepBlockDecodeTests.cs b/tests/RvtIO.Tests/GRepBlockDecodeTests.cs index 840456a..6963ed6 100644 --- a/tests/RvtIO.Tests/GRepBlockDecodeTests.cs +++ b/tests/RvtIO.Tests/GRepBlockDecodeTests.cs @@ -116,6 +116,52 @@ public void DecodeGRepBlocks_InABrowserDecodesAndAppliesOneBlockAtATime() Assert.Equal(updates.Distinct().Order(), updates); } + [Fact] + public void DecodeBrowserBatches_ParallelizesOnlyTheDecodeAndPreservesOrder() + { + const int count = 11; + const int workers = 2; + int caller = Environment.CurrentManagedThreadId; + int prepared = 0; + int applied = 0; + int started = 0; + var blocks = SyntheticBlocks(count); + var updates = new List(); + using var firstBatch = new Barrier(workers); + + BlockParser.DecodeBrowserBatches(count, + index => + { + Assert.Equal(caller, Environment.CurrentManagedThreadId); + Assert.Equal(prepared++, index); + Assert.InRange(prepared - applied, 1, workers); + return index; + }, + index => + { + if (Environment.ProcessorCount >= workers && Interlocked.Increment(ref started) <= workers) + Assert.True(firstBatch.SignalAndWait(DecodeWait)); + return blocks[index]; + }, + (index, geometry) => + { + Assert.Equal(caller, Environment.CurrentManagedThreadId); + Assert.Equal(applied++, index); + Assert.Same(blocks[index], geometry); + }, + workers, (completed, total) => + { + Assert.Equal(caller, Environment.CurrentManagedThreadId); + Assert.Equal(count, total); + Assert.Equal(applied, completed); + updates.Add(completed); + }); + + Assert.Equal(count, applied); + Assert.Equal(0, updates[0]); + Assert.Equal(count, updates[^1]); + } + [Fact] public void DecodeGRepBlocks_AFailedDecodeOutsideABrowserAppliesNothingAndStaysAMalformedInputFailure() { From e9b5aef86f7f05c38794a6f873d989cd5290d1e1 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:31:24 +0300 Subject: [PATCH 2/2] Keep GRep decode exceptions on their owning thread --- src/RvtIO/Parsing/GRepParserV2.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/RvtIO/Parsing/GRepParserV2.cs b/src/RvtIO/Parsing/GRepParserV2.cs index 3404ee8..3f046e0 100644 --- a/src/RvtIO/Parsing/GRepParserV2.cs +++ b/src/RvtIO/Parsing/GRepParserV2.cs @@ -26,7 +26,10 @@ internal static partial class GRepParserV2 private static double ChordTolerance => TessellationChordToleranceFeet * (t_coarseTessellation ? 16 : 1); private sealed class DecodeStop : Exception { } - private static readonly DecodeStop Stop = new(); + [ThreadStatic] private static DecodeStop? t_stop; + + // Throwing updates the exception's stack trace. Reuse it only on the current thread. + private static DecodeStop Stop => t_stop ??= new(); /// /// Serialized class ids of the Face and Edge objects whose per-block counts feed