Skip to content
Merged
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
5 changes: 4 additions & 1 deletion .github/docs/specs/standardqr-decoder.md
Original file line number Diff line number Diff line change
Expand Up @@ -894,8 +894,11 @@ End-to-end numbers are in `src/FeatherQR.Benchmark`. `QRCodeDecodeEndToEnd` cove
- Each grid attempt used to rent its own buffer, so a dimension could have three buffers of one size out at once (the first sampling, another grid compared against it, and a coverage re-read).
- The array pool keeps one array a size per thread, so the second and third came from per-core stacks every thread shares. With other tests decoding beside it, the failure path allocated 4,120 B in every round, in one of six runs on .NET 8. Alone it never did.
- Since 2026-09-29 a scan rents one array of three grids for the largest dimension it has sampled (`ModuleWorkspace`), again only for a larger one.
- `DecodeAllocationTest` checks the peak count of buffers out at once per image (`QRImageDecoder.ModuleBuffersPeak`). Before the change that count was 2 or 3 on the bowed symbol, the next triple and noise.
- `DecodeAllocationTest` checks, through the array pool's events, the most arrays of one size out at once per image. Before the change the module buffers alone reached 2 or 3 on the bowed symbol, the next triple and noise.
- The inverted image's buffer is still out during the negative pass, and a module buffer of the same size bucket then still comes from the shared stacks.
- The several-symbol call rented its candidate list (4,096 finders, 65,536 bytes) once a reading, and the inverted image's buffer apart, so an image of up to 65,536 pixels has two arrays of one size out (one symbol at 199 × 199 px). They stay apart.
- One array for both was tried and undone (2026-11-28, .NET 10, 32 threads). Four rents of 65,536 bytes took 91 ns a call on one thread and 238 ns on 32, against 8.5 and 19 ns for one rent of 262,144 bytes, and neither allocated from the pool. The Micro QR several-symbol call, which has three or four such lists out, allocated only its texts on 32 threads, at 19 to 108 µs a call.
- One array rounds up to the next power of two: 2 MiB on a 1000 × 1000 image, where apart the buffers are 1 MiB and 64 KiB.
- The reads measured 0.3 to 1.3 % slower in the fastest of twelve alternating runs (version 6 at 4 px/module, 9.75 to 9.88 µs), the failing images within 0.6 %. Without the counters, and with the workspace renting one grid instead of three, the reads were still 0.5 to 1.0 % slower, so neither is the cause. It was not traced further.
- A workspace passed by `ref` beside spans must not be a `ref struct`. The compiler refuses a `ref ModuleWorkspace` argument next to a stack-allocated span, or next to an `ImageView` built from a local passed by `in` (CS8350), because a ref struct's fields could capture either.
- The workspace holds only an array and a length, so it is a plain struct.
Expand Down
5 changes: 2 additions & 3 deletions .github/docs/specs/standardqr-encoder.md
Original file line number Diff line number Diff line change
Expand Up @@ -230,9 +230,8 @@ These test sets were sized against faults planted in the lanes, the walk and the

The test also checks what the plan does not show:

- where each batch from the floor lands against the scalar search's answer (the second batch below either ceiling, at three budgets and at four, and only once).
- where each batch from the floor lands against the scalar search's answer.
- the reach `KeptOffBits` gives that batch.
- the walks one plan takes per call site, which the planner counts per thread for this purpose.


The search does not walk the answer again. The probe that last lowers the ceiling walked at the final budget, so its split is handed back, kept aside because a later failing probe overwrites the caller's buffer. The text is walked a final time only when no walk ran at the final budget, which happens when the capacity itself was the answer. The same test file requires the returned split to be the walk at the returned budget, across pinned versions that put the answer at the top of the bracket.
Expand All @@ -255,7 +254,7 @@ Only symbols that need a plan get a lane, in order, eight per pass. A digit chun

NEON keeps 32-bit keys, because the cost times eight cannot fit the budget walker's 16-bit representation. Groups with too little useful work relative to their longest chunk use scalar planning, so a vector pass is not spent mostly on padding. The parent layout and tie-break are shared, so plans and emitted modules are identical across backends. `ModeSegmenterLaneParityTest` compares costs, final states and reconstructed runs against an independent all-states reference, including every UTF-16 classification value, uneven groups, surrogate boundaries and U+FEFF.

None of the three changes what is written, so the writer counts, per thread, the chunks it plans alone and the passes that plan chunks together. `StructuredAppendStreamTest` checks both counts on prose (neither), twelve symbols of order lines (two passes), three symbols (one pass, the fewest a pass takes) and a label of two (two planned alone).
None of the three changes what is written. `StructuredAppendWriterPlanTest` requires the same modules whether the chunks are planned together or one by one.

The program records only what the walk back needs. Three of a character's six predecessors are fixed by the packing groups (Numeric0 comes from Numeric2, Numeric2 from Numeric1, and Alnum0 from Alnum1), so the table holds the other three in two bytes per character instead of seven, and the stack holds a table of 256 characters instead of 73.

Expand Down
4 changes: 0 additions & 4 deletions src/FeatherQR/Internals/MicroQR/MicroQRGridEvidence.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,6 @@ internal static class MicroQRGridEvidence
/// <summary>Passed for a quiet zone not read: it earns nothing.</summary>
public const int QuietZoneUnread = -1;

/// <summary>Set by a test around a decode on its own thread, to see what the decode reads without the rule: the premise of a test that the rule refuses an image.</summary>
[ThreadStatic]
internal static bool SuspendedOnThisThread;

private const int UnitsPerBit = 256;
private const int MaxTimingModules = 2 * (17 - 8);
private const int MaxQuietZoneModules = 2 * 17 + 1;
Expand Down
2 changes: 1 addition & 1 deletion src/FeatherQR/Internals/MicroQR/MicroQRMatrixDecoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ private static DecodeStatus Decode<TModules, TQuietZone>(ReadOnlySpan<byte> pixe
}

decidedByModules = false;
if (sampled && !MicroQRGridEvidence.SuspendedOnThisThread && !Earns(pixels, modules, size, version, eccLevel, formatDistance, errorsCorrected, luminance, width, height, threshold, quietZone))
if (sampled && !Earns(pixels, modules, size, version, eccLevel, formatDistance, errorsCorrected, luminance, width, height, threshold, quietZone))
{
info = new MicroQRCodeDecodeInfo(DecodeStatus.DataUncorrectable, version, eccLevel, maskPattern, errorsCorrected);
return DecodeStatus.DataUncorrectable;
Expand Down
26 changes: 3 additions & 23 deletions src/FeatherQR/Internals/StandardQR/QRImageDecoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ private static bool SameTriple(ReadOnlySpan<FinderPattern> triple, ReadOnlySpan<
/// </summary>
/// <remarks>
/// A dimension needs three grids at once: the first sampling, another grid compared against it, and a coverage re-read compared against either.
/// The thread's slot of the array pool holds one array a size, and a second of the same size would come from the per-core stacks every thread shares, where a thread decoding beside this one can take it and the rent allocates.
/// The thread's slot of the array pool holds one array a size, and a second of the same size would come from the per-core stacks every thread shares. Those are empty while other threads hold the arrays they had, and the rent then allocates.
/// </remarks>
internal struct ModuleWorkspace
{
Expand All @@ -207,7 +207,7 @@ public void Reserve(int dimension)
if (length <= _capacity)
return;
Dispose();
_rented = RentModules(3 * length);
_rented = ArrayPool<byte>.Shared.Rent(3 * length);
_capacity = length;
}

Expand All @@ -230,7 +230,7 @@ public void Dispose()
{
if (_rented is null)
return;
ReturnModules(_rented);
ArrayPool<byte>.Shared.Return(_rented, clearArray: false);
_rented = null;
_capacity = 0;
}
Expand Down Expand Up @@ -842,26 +842,6 @@ internal static DecodeStatus DecodeWithMirrorRetry(Span<byte> modules, int dimen
/// </summary>
private static SearchResult<QRCodeDecodeInfo> NewResult() => new(Reporting, NotDetectedInfo);

/// <summary>
/// The module buffers this thread has out, and the most it has had out at once since a test last cleared <see cref="ModuleBuffersPeak"/>.
/// No decode reads them, but tests that pin how many a scan holds do. One increment and one decrement a buffer.
/// </summary>
[ThreadStatic]
internal static int ModuleBuffersOut, ModuleBuffersPeak;

private static byte[] RentModules(int length)
{
if (++ModuleBuffersOut > ModuleBuffersPeak)
ModuleBuffersPeak = ModuleBuffersOut;
return ArrayPool<byte>.Shared.Rent(length);
}

private static void ReturnModules(byte[] rented)
{
ModuleBuffersOut--;
ArrayPool<byte>.Shared.Return(rented, clearArray: false);
}

/// <summary>BCH(18,6) version information codewords of versions 7-40, indexed by version − 7.</summary>
private static readonly uint[] VersionCodewords = CreateVersionCodewords();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,6 @@ internal static bool TryNarrowWithLanes(ReadOnlySpan<char> text, EciMode charset
/// </summary>
internal static bool WalkLanes(ReadOnlySpan<char> text, EciMode charset, int version, ReadOnlySpan<int> budgets, int limit, int placed, int start, Span<int> counts, Span<int> laneEnds, out int apartSteps)
{
LaneBatches++;
// The search supplies QR capacities. Keep the 32-bit reference for direct walks
// outside the 16-bit cost domain, including budgets smaller than the set headers.
if (AdvSimd.Arm64.IsSupported && BudgetsFit16(budgets, charset))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,6 @@ internal static partial class StructuredAppendPlanner

private const char ByteOrderMark = ModeSegmenter.ByteOrderMark;

/// <summary>
/// The walks taken on this thread, scalar and eight budgets at once: what the search spends, which no plan shows, for tests that pin where it spends it. One increment a walk of thousands of steps.
/// </summary>
[ThreadStatic]
internal static int ScalarWalks, LaneBatches;

/// <summary>
/// Plans the split. <paramref name="chunkEnds"/> receives the end offset of each chunk (at least <see cref="MaxSymbols"/> entries). <paramref name="chunkCount"/> is 1 when the text fits one symbol within the range even with the set header every chunk is priced with, in which case nothing else is planned. Whether the text fits one symbol without that header, which is what makes it not a set, is the caller's to ask, the way <c>Create</c> asks it, of a text this splits or refuses.
/// Returns <c>false</c> when the text needs more than sixteen symbols at <paramref name="maxVersion"/>, or some single character cannot fit a symbol there.
Expand Down Expand Up @@ -545,7 +539,6 @@ internal static int CountChunks(ReadOnlySpan<char> text, EciMode charset, bool u
/// <summary>The walk resumed: <paramref name="count"/> chunks are already in <paramref name="chunkEnds"/> and the next starts at <paramref name="start"/>.</summary>
private static int CountChunks(ReadOnlySpan<char> text, EciMode charset, bool utf8Bom, QRSegmentation segmentation, int version, int budgetBits, int limit, Span<int> chunkEnds, int count, int start, bool kanji)
{
ScalarWalks++;
while (start < text.Length)
{
if (count == limit)
Expand Down
13 changes: 0 additions & 13 deletions src/FeatherQR/QRCodeGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -374,12 +374,6 @@ private static bool TryResolveVersion(ReadOnlySpan<char> text, QREccLevel eccLev
public static QRCodeData[] CreateStructuredAppend(ReadOnlySpan<char> textSpan, QREccLevel eccLevel, in QRCodeGeneratorOptions options = default)
=> CreateStructuredAppend(textSpan, eccLevel, in options, planTogether: true);

/// <summary>
/// What a set spends on this thread beside the planner's walks (<c>StructuredAppendPlanner.ScalarWalks</c>): the chunks the writer plans one by one, its passes that plan up to eight together, the one-symbol questions, and for a Kanji-eligible text the Kanji and UTF-8 sets planned to be weighed. No set shows them, but tests that pin where the work goes read them. One increment a plan or a question.
/// </summary>
[ThreadStatic]
internal static int ChunkPlans, LanePlanPasses, OneSymbolQuestions, KanjiSetPlans, Utf8SetPlans;

/// <summary>
/// <see cref="CreateStructuredAppend(ReadOnlySpan{char}, QREccLevel, in QRCodeGeneratorOptions)"/> with the choice of planning the symbols of the set together left to the caller. The set is the same either way, which is what <c>StructuredAppendWriterPlanTest</c> holds it to.
/// </summary>
Expand Down Expand Up @@ -497,7 +491,6 @@ private static QRCodeData[] CreateStructuredAppend(ReadOnlySpan<char> textSpan,
{
rentedLaneTable ??= ArrayPool<byte>.Shared.Rent(longestChunk * ModeSegmenter.LaneTableBytesPerChar);
QRSegmentPlanner.PlanChunks(textSpan, laneStarts.Slice(0, lanes), laneLengths.Slice(0, lanes), charset, version, rentedLaneTable, laneBits, laneStates);
LanePlanPasses++;
lanesToWrite = lanes;
}
else
Expand Down Expand Up @@ -552,7 +545,6 @@ private static bool TryPlanSetOrSymbol(ReadOnlySpan<char> text, QREccLevel eccLe

if ((planned && count == 1) || !mayBeOneSymbol)
return planned;
OneSymbolQuestions++;
if (!TryResolveVersion(text, eccLevel, in wholeText, in options, options.Segmentation != QRSegmentation.Single, out _))
return planned;

Expand Down Expand Up @@ -637,13 +629,11 @@ private static bool TryPlanKanjiSetOrUtf8Set(ReadOnlySpan<char> text, QREccLevel

private static bool PlanKanjiSet(ReadOnlySpan<char> text, QREccLevel eccLevel, in QRCodeGeneratorOptions options, Span<int> chunkEnds, out int count, out int version, out bool mayBeOneSymbol)
{
KanjiSetPlans++;
return StructuredAppendPlanner.TryPlanKanji(text, eccLevel, options.Segmentation, options.Version.Min, options.Version.Max, chunkEnds, out count, out version, out _, out mayBeOneSymbol);
}

private static bool PlanUtf8Set(ReadOnlySpan<char> text, QREccLevel eccLevel, in TextAnalysisResult wholeText, in QRCodeGeneratorOptions options, Span<int> chunkEnds, out int count, out int version, out bool oneRunPlans, out bool mayBeOneSymbol)
{
Utf8SetPlans++;
return StructuredAppendPlanner.TryPlan(text, eccLevel, wholeText.EciMode, wholeText.EncodingMode, options.Utf8Bom, options.Segmentation, options.Version.Min, options.Version.Max, chunkEnds, out count, out version, out _, out oneRunPlans, out mayBeOneSymbol, allowLanes: true);
}

Expand Down Expand Up @@ -694,7 +684,6 @@ private static QRCodeData[] CreateKanjiSet(ReadOnlySpan<char> textSpan, QREccLev
var header = new QRStructuredAppend(i, count, parity);
if (segmentation == QRSegmentation.Optimal)
{
ChunkPlans++;
if (!QRSegmentPlanner.TryBuildKanjiPlan(chunk, version, level, plan, out var segmentCount, out var planBits) || planBits + StructuredAppendPlanner.HeaderBits > capacity)
throw new InvalidOperationException($"A Structured Append chunk of {chunk.Length} characters does not fit version {version} at ECC level {level} after planning.");
var planned = new QRConfiguration(version, level, EncodingMode.Kanji, EciMode.Default, false, eccInfo, chunk.Length, header);
Expand Down Expand Up @@ -866,8 +855,6 @@ private static QRCodeData CreateSymbol(ReadOnlySpan<char> chunk, in TextAnalysis
if (TakesPlan(in analysis, segmentation, bomApplies, oneRunPlans))
{
int segmentCount, planBits;
if (laneTable.IsEmpty)
ChunkPlans++;
#if NET8_0_OR_GREATER
var built = laneTable.IsEmpty
? QRSegmentPlanner.TryBuildPlan(chunk, charset, version, eccLevel, plan, out segmentCount, out planBits)
Expand Down
14 changes: 1 addition & 13 deletions tests/FeatherQR.Tests/MicroQR/MicroQRGridEvidenceTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ public async Task TextureLikeGrid_KeepsFewerCorrections(MicroQRVersion version,

/// <summary>
/// A real M4-M symbol at its correction limit whose format word is a bit off and whose timing modules all read the other way: Reed-Solomon reads it, the structure does not earn that, and a clean quiet zone does.
/// With the grid evidence rule removed, it reads with the dark quiet zone too (2026-11-28).
/// </summary>
[Test]
[Arguments(false)]
Expand All @@ -103,19 +104,6 @@ public async Task SampledGrid_ReadAtTheLimit_KeptOnlyWhenItsStructureEarnsIt(boo

var damaged = Decode(grid, size, quietZoneDark: 2 * size + 1, mirrored);
var clean = Decode(grid, size, quietZoneDark: 0, mirrored);
MicroQRGridEvidence.SuspendedOnThisThread = true;
(DecodeStatus Status, MicroQRCodeDecodeInfo Info, string Text) suspended;
try
{
suspended = Decode(grid, size, quietZoneDark: 2 * size + 1, mirrored);
}
finally
{
MicroQRGridEvidence.SuspendedOnThisThread = false;
}

await Assert.That(suspended.Status).IsEqualTo(DecodeStatus.Success);
await Assert.That(suspended.Info.ErrorsCorrected).IsEqualTo(5);
await Assert.That(damaged.Status).IsEqualTo(DecodeStatus.DataUncorrectable);
await Assert.That(damaged.Info.ErrorsCorrected).IsEqualTo(5);
await Assert.That(clean.Status).IsEqualTo(DecodeStatus.Success);
Expand Down
60 changes: 60 additions & 0 deletions tests/FeatherQR.Tests/Shared/ArrayPoolRentWatch.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
using System.Buffers;
using System.Diagnostics.Tracing;

namespace FeatherQR.Tests;

/// <summary>
/// Watches the rents and returns of <see cref="ArrayPool{T}.Shared"/> for bytes on the thread that created it, through the pool's event source.
/// </summary>
/// <remarks>
/// The pool's thread slot holds one array a size. A second array of a size rented while the first is out comes from the per-core stacks every thread shares.
/// Those are empty while other threads hold the arrays they had, and the rent then allocates. <see cref="MostOutOfOneSize"/> is the most arrays of one length this thread had out at once.
/// Arrays are told apart by length, since every array of a bucket has the bucket's length, and the event names no bucket for an array the pool allocates.
/// The event source calls the listener on the thread that rents or returns, so rents on other threads are left out by their thread id.
/// </remarks>
internal sealed class ArrayPoolRentWatch : EventListener
{
private const int BufferRentedEvent = 1;
private const int BufferReturnedEvent = 3;

private readonly int _threadId = Environment.CurrentManagedThreadId;
private readonly int _poolId = ArrayPool<byte>.Shared.GetHashCode();
private readonly Dictionary<int, int> _lengthOf = [];
private readonly Dictionary<int, int> _outOfLength = [];
private volatile bool _watching;

public int MostOutOfOneSize { get; private set; }

public ArrayPoolRentWatch() => _watching = true;

protected override void OnEventSourceCreated(EventSource source)
{
if (source.Name == "System.Buffers.ArrayPoolEventSource")
EnableEvents(source, EventLevel.Verbose);
}

protected override void OnEventWritten(EventWrittenEventArgs e)
{
if (!_watching || Environment.CurrentManagedThreadId != _threadId || e.Payload is null || (int)e.Payload[2]! != _poolId)
return;
var bufferId = (int)e.Payload[0]!;
if (e.EventId == BufferRentedEvent)
{
var length = (int)e.Payload[1]!;
_lengthOf[bufferId] = length;
var outNow = _outOfLength.TryGetValue(length, out var n) ? n + 1 : 1;
_outOfLength[length] = outNow;
MostOutOfOneSize = Math.Max(MostOutOfOneSize, outNow);
}
else if (e.EventId == BufferReturnedEvent && _lengthOf.Remove(bufferId, out var length))
{
_outOfLength[length]--;
}
}

public override void Dispose()
{
_watching = false;
base.Dispose();
}
}
Loading
Loading