Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 47 additions & 2 deletions src/RvtIO/Parsing/BlockParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,9 @@ internal static void ApplyPendingGReps(ParsingState state, List<PendingGRep> 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);
}

Expand All @@ -47,11 +48,55 @@ internal static void ApplyPendingGRep(ParsingState state, PendingGRep job, GRepD
}

/// <summary>Decodes <paramref name="count"/> 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.</summary>
/// The single-threaded browser path decodes and applies one block at a time.</summary>
internal static void DecodeGRepBlocksInOrder(int count, Func<int, GRepData?> decode, Action<int, GRepData?> apply,
Action<int, int>? progress = null) =>
DecodeGRepBlocksInOrder(count, decode, apply, OperatingSystem.IsBrowser(), progress);

internal static void DecodeGRepBlocksInOrder<T>(int count, Func<int, T> read, Func<T, GRepData?> decode,
Action<int, GRepData?> apply, Action<int, int>? 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<T>(int count, Func<int, T> read, Func<T, GRepData?> decode,
Action<int, GRepData?> apply, int workers, Action<int, int>? 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();
}
}
}

/// <summary>The seam of the overload above: <paramref name="sequential"/> selects the one-block-at-a-time path of a
/// browser.</summary>
internal static void DecodeGRepBlocksInOrder(
Expand Down
5 changes: 4 additions & 1 deletion src/RvtIO/Parsing/GRepParserV2.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();

/// <summary>
/// Serialized class ids of the Face and Edge objects whose per-block counts feed <see
Expand Down
21 changes: 15 additions & 6 deletions src/RvtIO/RvtFileReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<uint, List<string>>();
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;
Expand Down Expand Up @@ -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) =>
Expand Down
46 changes: 46 additions & 0 deletions tests/RvtIO.Tests/GRepBlockDecodeTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<int>();
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()
{
Expand Down
Loading