Skip to content

Add SvgCodec: decode/rasterize-only SVG codec (Phase 6) - #13

Merged
Malcolmnixon merged 57 commits into
mainfrom
feature/svg-codec
Sep 24, 2026
Merged

Malcolmnixon merged 57 commits into
mainfrom
feature/svg-codec

Conversation

@Malcolmnixon

Copy link
Copy Markdown
Member

Summary

Implements Phase 6 of the CanvasNet roadmap: DemaConsulting.CanvasNet.Codecs.SvgCodec, a hand-rolled, decode/rasterize-only codec for a practical real-world subset of SVG (no Save/encode - SVG is a vector format, not a raster round-trip format like the other codecs).

Supported subset

  • Shapes: rect (+ rounded corners), circle, ellipse, line, polyline, polygon, full path 'd' mini-language (M/L/H/V/C/S/Q/T/A/Z, absolute+relative)
  • g grouping with transform + presentation-attribute inheritance
  • transform: translate/scale/rotate/skewX/skewY/matrix, composed
  • Presentation attributes: fill/stroke (colors, gradients), fill-rule, opacity, stroke-width/cap/join/miterlimit/dasharray/dashoffset
  • defs + linearGradient/radialGradient (userSpaceOnUse/objectBoundingBox, spreadMethod, stop-opacity, href-chain inheritance)
  • use (including x/y offset)
  • Basic text via the Fonts unit (TrueTypeFont), caller-supplied font lookup

Explicitly out of scope (documented, tolerantly ignored)

CSS stylesheets/selectors, filters/masks/clip-paths, animation, image embedding, patterns, markers, nested viewBox, complex text layout (tspan/text-on-path/bidi).

Security hardening (found via local review, all fixed pre-push)

  • Stack-overflow DoS from unbounded <g>/<use>\ nesting depth -> \MaxElementDepth/\MaxUseDepth\ caps
  • Exponential-blowup DoS from <use>\ fan-out (distinct bug from the depth cap) -> \MaxTotalRenderedElements\ total-work budget

Test fixtures

Includes two real-world, CC0-licensed SVG fixtures from Wikimedia Commons (\SvgGradient.svg, \InkscapeFilters.svg) alongside hand-authored synthetic fixtures, following the same real-asset-testing pattern established for Open Sans in the Fonts phase. Visual output independently spot-checked by rendering all fixtures to PNG and inspecting pixels.

Process

Fully local implementation -> 3 rounds of local code-review + 2 rounds of local formal-review (each round found and fixed a genuine issue, including two independent DoS-class bugs) -> clean local build/lint -> pushed only once fully clean.

2952/2952 tests passing across net8.0/net9.0/net10.0.

Malcolm Nixon added 14 commits September 23, 2026 00:11
- SvgCodecTests.cs: hand-authored SVG string fixtures covering shapes, path
  data commands, group inheritance/opacity, transform functions,
  presentation attributes, gradients (incl. href inheritance and cycle
  detection), the use element, text rendering/anchor/font fallback,
  viewBox fitting, GetInfo fallback, malformed-input rejection, tolerant
  unsupported-construct handling, and argument validation.
- SvgFixtureTests.cs + SvgFixtures/*.svg: real-file corpus tests, including
  a real-font (OpenSans-Regular.ttf) text-rendering integration test.
- CanvasNetTests.cs: new system-integration SvgLoad test.
- csproj: copy SvgFixtures/** to output, mirroring other fixture folders.
- docs/reqstream/canvas-net/codecs/svg-codec.yaml: 20 unit-tier requirements
  covering shapes, path commands, group/transform inheritance, transform
  functions, presentation attributes, gradients + href inheritance, use
  element, text rendering/anchor/font-fallback, viewBox fitting, GetInfo +
  fallback, malformed-input rejection, tolerant unsupported-construct
  handling, and argument validation.
- docs/reqstream/canvas-net/codecs.yaml: 9 subsystem-tier CanvasNet-Codecs-Svg*
  requirements linking down to the unit tier.
- docs/reqstream/canvas-net.yaml: new SVG Codec API system-tier section with
  9 CanvasNet-Lib-Svg* requirements linking down to the subsystem tier.
- requirements.yaml: registered the new unit-level yaml in includes.

Verified with 'dotnet reqstream --requirements requirements.yaml --lint' and
'--enforce': zero orphaned/unreachable requirements.
- docs/design/canvas-net/codecs/svg-codec.md: new unit design doc covering
  in/out-of-scope subset, viewBox-fitting policy, GetInfo fallback policy,
  presentation-attribute inheritance model, gradient/use/text support and
  limits, font-lookup and silent-skip policy, and error-handling policy
  (including the caller-supplied-dimensions rationale).
- docs/design/canvas-net/codecs.md: 5 units now (not 4); corrected the
  'depends only on Canvas' claim to note SvgCodec also depends on
  Geometry/Drawing/Fonts.
- docs/design/introduction.md: 5 units in Codecs, folder tree, and
  dependency correction.
- docs/verification/canvas-net/codecs/svg-codec.md: new unit verification
  doc, one subsection per unit-tier requirement id.
- docs/verification/canvas-net/codecs.md: added SvgCodec, corrected the
  'only dependency is Surface' sentence.
- docs/sysml2/model/canvas-net/codecs/svg-codec.sysml: new part def SvgCodec
  with doc/sourceRef/testRef/designRef/verificationRef/reqRef.
- docs/sysml2/model/canvas-net/codecs.sysml: add part svgCodec : SvgCodec,
  and note SvgCodec's additional Geometry/Drawing/Fonts dependency in the
  Codecs part doc.

Validated with 'dotnet sysml2tools lint docs/sysml2/**/*.sysml': no errors.
Mirrors the existing CanvasNet-Codecs-BmpCodec/JpegCodec entries: unit
requirements/design/verification/SysML2 model, unit source
(SvgCodec.cs), the shared NamespaceDoc.cs, and the unit/fixture test
files. Validated with 'dotnet reviewmark --lint': no issues.
- README.md: new Features bullet and a Usage snippet showing
  SvgCodec.Load(path, width, height).
- docs/user_guide/introduction.md: new '### SvgCodec' API-reference
  subsection (mirroring '### JpegCodec') documenting all four public
  overloads, plus 'Example 13: Decoding and Rasterizing an SVG Document'
  under Examples (verified runnable).
Whitelists CSS color-keyword names and remaining SVG-specific terms
flagged by the spelling linter across the SvgCodec implementation,
tests, and documentation (recovered from an in-progress lint pass
interrupted by a machine restart).
…flow

RenderElement recursed into <g>/<symbol> children with no depth limit,
so a document with many levels of plain nested groups (no <use>
involved) could drive the render call stack into an uncatchable
StackOverflowException, terminating the process and bypassing this
codec's documented InvalidDataException-wrapping error-handling
policy. Only <use> reference cycles were previously guarded
(MaxUseDepth).

Add a MaxElementDepth=100 bound, mirroring the existing MaxUseDepth
pattern and GlyfLocaReader's MaxDepth precedent in the Fonts unit.
RenderElement now threads an elementDepth counter (incremented on
every recursive descent, whether via g/symbol nesting or a use
reference) and throws InvalidDataException before recursing further
once the depth is reached.

- src/DemaConsulting.CanvasNet/Codecs/SvgCodec.cs: add MaxElementDepth
  constant; thread elementDepth through RenderDocument/RenderElement/
  RenderUse; fail-fast check before recursion.
- test/.../Codecs/SvgCodecTests.cs: add
  SvgCodec_Load_DeeplyNestedGroups_ThrowsInvalidDataException
  regression test (500 nested <g> elements - safely below the actual
  stack-overflow threshold, comfortably above the new cap).
- docs/design/canvas-net/codecs/svg-codec.md: document the new
  element/group nesting depth bound alongside the existing use-cycle
  guard.
- docs/reqstream/canvas-net/codecs/svg-codec.yaml +
  docs/reqstream/canvas-net/codecs.yaml: add
  CanvasNet-Codecs-SvgCodec-ElementNestingDepthLimit requirement,
  wired into CanvasNet-Codecs-SvgLoad's children list.
- docs/verification/canvas-net/codecs/svg-codec.md: add matching
  verification entry linking the requirement to the new test.
Adds SvgGradient.svg and InkscapeFilters.svg, both CC0 1.0 Universal
Public Domain Dedication fixtures sourced from Wikimedia Commons, alongside
a WikimediaCommons.LICENSE provenance/attribution file and an updated
SvgFixtures/README.md documenting them as real-world third-party fixtures
distinct from this folder's hand-authored ones. Both files are copied
byte-for-byte with no modification other than a PascalCase rename to match
this repository's fixture naming convention.
Adds two non-vacuous SvgFixtureTests methods that exercise SvgCodec.Load
against the new real-world SvgGradient.svg/InkscapeFilters.svg fixtures:

- SvgCodec_Load_SvgGradientFixture_RendersVaryingGradientAndPinkBackground
  asserts the leftmost userSpaceOnUse linearGradient bar is bright near its
  white stop and much darker near its black stop (not a flat fallback
  color), and that the fill="pink" background rect is visible at a point
  outside every gradient bar/use shape.

- SvgCodec_Load_InkscapeFiltersFixture_ToleratesFiltersAndRendersFlowerContent
  asserts Load does not throw despite dozens of unsupported
  filter="url(#...)" references, that a flower petal rendered behind one
  such filter reference still paints its genuine fill color, and that a
  gap between flowers remains transparent (ruling out a degenerate
  whole-canvas-fill false positive).

Also references both new tests from the existing
CanvasNet-Codecs-SvgCodec-Gradients and
CanvasNet-Codecs-SvgCodec-UnsupportedConstructsIgnored requirements in
docs/reqstream and their corresponding docs/verification entry, and adds
"Inkscape"/"RRGGBB" to .cspell.yaml. Verified with `dotnet reqstream --lint`
(zero issues) and fix.ps1/build.ps1/lint.ps1 (all clean).
…tion

MaxUseDepth and MaxElementDepth only bound recursion depth along any
single reference chain. A <use> element can legitimately (non-cyclically)
be referenced by several sibling <use> elements whose targets themselves
fan out further, causing the total number of elements rendered to grow
exponentially with nesting depth while every individual chain stays well
within both depth caps - manifesting as extreme CPU time rather than a
stack overflow.

Add a third, independent bound - MaxTotalRenderedElements (100,000) -
threaded through RenderElement/RenderUse as a ref counter, charged before
each element is processed further, following the same 'total resolved
work' budget pattern GlyfLocaReader already uses for the analogous
composite-glyph amplification. Throws InvalidDataException once
exceeded, matching this codec's existing exception style.

Update the SvgCodec design doc to correct the overstated claim that
depth/cycle guards alone bound unbounded recursion/looping - they do not
bound total work under non-cyclic fan-out - and add a matching
CanvasNet-Codecs-SvgCodec-TotalElementBudget requirement (wired into its
parent's children list), verification-doc entry, and a regression test
that fails fast well before the fan-out becomes computationally
expensive.

Existing MaxUseDepth/MaxElementDepth/cycle-detection guards are
unchanged - this is an additional bound, not a replacement.
Copilot AI lite review requested due to automatic review settings September 23, 2026 13:26

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

One or more issues must be addressed before approval.

Get a fresh assessment by requesting another Copilot review.

Review effort: Lite
Findings: 1 High severity · 2 Medium severity · 1 Low severity

Open (4)
What changed in this PR

Adds a decode/rasterize-only SvgCodec supporting shapes, paths, transforms, gradients, <use>, and text, with extensive tests, fixtures, documentation, and traceability artifacts.

Changes:

  • Implements SVG parsing and rasterization.
  • Adds unit, integration, fixture, and security-boundary tests.
  • Updates API documentation, requirements, SysML2, and review configuration.
File Description
test/​DemaConsulting.CanvasNet.Tests/​SvgFixtures/​WikimediaCommons.LICENSE Updated as part of this pull request.
test/​DemaConsulting.CanvasNet.Tests/​SvgFixtures/​use-reference.svg Updated as part of this pull request.
test/​DemaConsulting.CanvasNet.Tests/​SvgFixtures/​tolerant-unsupported.svg Updated as part of this pull request.
test/​DemaConsulting.CanvasNet.Tests/​SvgFixtures/​text.svg Updated as part of this pull request.
test/​DemaConsulting.CanvasNet.Tests/​SvgFixtures/​SvgGradient.svg Updated as part of this pull request.
test/​DemaConsulting.CanvasNet.Tests/​SvgFixtures/​shapes.svg Updated as part of this pull request.
test/​DemaConsulting.CanvasNet.Tests/​SvgFixtures/​README.md Updated as part of this pull request.
test/​DemaConsulting.CanvasNet.Tests/​SvgFixtures/​InkscapeFilters.svg Updated as part of this pull request.
test/​DemaConsulting.CanvasNet.Tests/​SvgFixtures/​groups-and-transforms.svg Updated as part of this pull request.
test/​DemaConsulting.CanvasNet.Tests/​SvgFixtures/​gradient.svg Updated as part of this pull request.
test/​DemaConsulting.CanvasNet.Tests/​DemaConsulting.CanvasNet.Tests.csproj Updated as part of this pull request.
test/​DemaConsulting.CanvasNet.Tests/​Codecs/​SvgFixtureTests.cs Updated as part of this pull request.
test/​DemaConsulting.CanvasNet.Tests/​Codecs/​SvgCodecTests.cs Updated as part of this pull request.
test/​DemaConsulting.CanvasNet.Tests/​CanvasNetTests.cs Updated as part of this pull request.
src/​DemaConsulting.CanvasNet/​Codecs/​NamespaceDoc.cs Updated as part of this pull request.
requirements.yaml Updated as part of this pull request.
README.md Updated as part of this pull request.
docs/​verification/​canvas-net/​codecs/​svg-codec.md Updated as part of this pull request.
docs/​verification/​canvas-net/​codecs.md Updated as part of this pull request.
docs/​user_guide/​introduction.md Updated as part of this pull request.
docs/​sysml2/​model/​canvas-net/​codecs/​svg-codec.sysml Updated as part of this pull request.
docs/​sysml2/​model/​canvas-net/​codecs.sysml Updated as part of this pull request.
docs/​reqstream/​canvas-net/​codecs/​svg-codec.yaml Updated as part of this pull request.
docs/​reqstream/​canvas-net/​codecs.yaml Updated as part of this pull request.
docs/​reqstream/​canvas-net.yaml Updated as part of this pull request.
docs/​design/​introduction.md Updated as part of this pull request.
docs/​design/​canvas-net/​codecs/​svg-codec.md Updated as part of this pull request.
docs/​design/​canvas-net/​codecs.md Updated as part of this pull request.
.reviewmark.yaml Updated as part of this pull request.
.cspell.yaml Updated as part of this pull request.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread docs/design/canvas-net/codecs.md Resolved
Malcolm Nixon added 5 commits September 23, 2026 10:06
GetInfo(Stream) previously called the same LoadRootElement() that performs a full XDocument.Load parse of the entire document, so a large or deeply-malformed document body could make GetInfo cost as much time/memory as a full Load even though it only reports the resolved intrinsic size. Add LoadRootElementAttributesOnly(Stream), which uses a forward-only XmlReader bounded to the root svg start-tag's own attributes and never advances further, and have GetInfo call it instead. Load is unchanged and keeps using the full-document LoadRootElement/XDocument.Load path. Update the class-level Error-handling policy remarks and the svg-codec.md design doc's GetInfo/Error Handling sections to describe the new bounded-parse contract, and add a regression test proving GetInfo no longer throws for a document malformed only beyond the root element's own attributes, while Load (unchanged) still rejects the same input.
float.Parse successfully parses NaN/Infinity/-Infinity literal text, and float exponent overflow (e.g. '1e400') silently produces Infinity instead of throwing, so every direct float.Parse call site in SvgCodec.cs that parses a raw SVG numeric attribute/token could previously produce a non-finite value that then silently propagated into rendering (or, for GetInfo's width/height, into the reported image size), rather than being rejected as malformed input. Add a float.IsFinite check to ParseCoordinate (throwing InvalidDataException, consistent with its existing malformed-number error style) and to TryReadNumber (returning false, consistent with its existing bool 'malformed token' failure contract, which ParseNumberList already surfaces as InvalidDataException). Add <exception> XML doc tags to the direct/indirect callers of these two methods (GetFloatAttribute, GetOptionalFloat, ParseOpacityValue, ParseOptionalOpacity). ParseLength (the root <svg> width/height fallback tier) is a separate, pre-existing, explicitly out-of-scope TryParse-based issue and is intentionally left untouched. Add regression tests: a literal 'NaN'/'Infinity' attribute value (which reaches ParseCoordinate's float.Parse unfiltered) and an exponent-overflow numeric token in path 'd' data / a points list (the only way to reach TryReadNumber's new check, since its character-class scan never matches literal NaN/Infinity text), plus a test confirming negative numbers, scientific notation, and percentages still parse and render correctly.
The Codecs subsystem design doc's opening sentence claimed all five codecs (BmpCodec, PngCodec, TiffCodec, JpegCodec, SvgCodec) each convert to and from a Surface pixel buffer. This is false for SvgCodec, which is decode/rasterize-only (Load/GetInfo) with no Save/encode direction - the rest of the paragraph already correctly describes this distinction. Reword the opening sentence to separate the four raster codecs (which round-trip to/from a Surface) from SvgCodec (decode-only into a Surface).
…ion doc

Convert the two bold-text pseudo-headings introduced by the prior two commits' Additional Regression Test Scenarios section into proper #### headings, resolving a markdownlint MD036 (emphasis-used-instead-of-heading) violation.
…t width/height)

ParsePercentOrNumber and ParseLength were missed by the prior non-finite guard fix
(f0db476), which only covered ParseCoordinate/TryReadNumber. Non-finite (NaN/Infinity)
values reaching ParsePercentOrNumber could throw an uncaught ArgumentOutOfRangeException
from GradientStop's constructor, or silently saturate/opacify rgb()/rgba() channels and
gradient coordinates; non-finite values reaching ParseLength could saturate the reported
root <svg> width/height. Both methods now reject a non-finite parse result the same
tolerant way they already treat an unparseable value: falling back to null/absent,
matching each method's own pre-existing contract rather than introducing a new throw
site. Adds 6 regression tests (4 proven to fail pre-fix via a stash/verify cycle) and
rewords the verification/design docs to describe the two distinct failure modes now in
the file (throwing vs. tolerant fallback) instead of a single uniform-rejection claim.
Copilot AI review requested due to automatic review settings September 23, 2026 15:04

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

Unresolved critical and moderate correctness, robustness, and contract issues remain.

Get a fresh assessment by requesting another Copilot review.

Review effort: Lite
Findings: 2 High severity · 1 Medium severity · 1 Low severity

Open (4)
Resolved since last review (4)

Malcolm Nixon added 5 commits September 23, 2026 11:51
…throwing

ParseValidMiterLimit previously delegated to GetOptionalFloat/ParseGeometryCoordinate,
whose ParseCoordinate already throws InvalidDataException for any non-finite parsed
value. This preempted ParseValidMiterLimit's own float.IsFinite(v) check, making
stroke-miterlimit="NaN"/"Infinity" throw instead of falling back to the inherited
miterlimit as documented in this method's xmldoc, the class remarks, the design doc,
and the reqstream requirement text.

ParseValidMiterLimit now reads and parses the raw stroke-miterlimit attribute
directly (duplicating the percentage-suffix rejection to preserve
PercentageGeometryRejected, then calling float.Parse directly) instead of routing
through the shared coordinate parser, so the non-finite-falls-back path is
reachable for this attribute specifically. GetOptionalFloat/ParseGeometryCoordinate/
ParseCoordinate are unchanged and still used identically by every other attribute.

Adds regression tests for stroke-miterlimit="NaN" and stroke-miterlimit="Infinity",
verified to fail with InvalidDataException before this fix and pass after.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

Critical rasterization-budget, counter-overflow, and gradient-work amplification issues remain unresolved, along with additional correctness and test gaps.

Get a fresh assessment by requesting another Copilot review.

Review effort: Lite
Findings: 6 High severity · 1 Medium severity · 1 Low severity

Open (8)
Resolved since last review (1)

Malcolm Nixon added 10 commits September 23, 2026 19:45
…dentity

The existing SvgCodec_Load_GradientReferencedByManyShapes_CachesStopsAndRendersIdenticallyToUncached test only asserts rendered-pixel output, which is identical whether ResolveGradientStops caches its result or always re-parses the gradient's stop children - it still passes even if the caching fix is fully reverted. Add SvgCodec_ResolveGradientStops_SameGradientElementResolvedTwice_ReturnsCachedListInstance, which reflects the private ResolveGradientStops static method and RenderContext type (matching the existing BindingFlags.NonPublic idiom used by CmapTableTests) to invoke ResolveGradientStops twice with the same gradient element and context, asserting Assert.Same on the two results and that GradientStopCache holds exactly one entry. Empirically verified: this test fails when the caching logic is reverted and passes when restored. Update the verification doc's Gradient Stop Caching section to list both tests and explain the gap the new test closes.
Copilot AI review requested due to automatic review settings September 24, 2026 01:05

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread docs/user_guide/introduction.md Resolved
Malcolm Nixon added 4 commits September 23, 2026 21:40
Add a separate MaxOnIntervalCount budget (distinct from the existing
MaxOnIntervalIterations iteration-cost estimate) to DashSplitter.BuildOnIntervals,
bounding how many 'on' intervals/output segments can be materialized and retained in
memory. A dash pattern shaped so most transitions are 'on' (e.g. [1, 1]) can stay at or
under the iteration-count budget while still retaining tens of millions of intervals,
each of which Split turns into its own extracted polyline segment and outline polygon -
a distinct 'counted vs. retained' gap from the iteration cap.

Extends the existing pre-flight estimate with a second, independent on-interval-count
estimate, and adds an in-loop incremental backstop for either estimate under-counting.
When either budget is exceeded, DashSplitter falls back to a solid stroke, mirroring the
existing iteration-budget fallback.

Adds a deterministic regression test proving the new budget triggers the solid-stroke
fallback for a case (a 50,000,000-unit path with a [1, 1] pattern) that the existing
iteration-count budget alone does not catch, and documents the new budget in the
PathStroker design/verification docs.
…de in SvgCodec

SvgCodec's MaxCoordinateMagnitude bound was previously enforced only pre-transform, at
parse time, on a source-literal coordinate/length value. A transform argument only needs
to stay at or under the same bound to pass its own parse-time check (the comparison is
strict '>', so a literal of exactly 1,000,000 is not rejected), so an in-bound local
coordinate composed with an in-bound-but-large transform (e.g. scale(1000000)) could
still produce a final pixel-space magnitude the flattening/stroking pipeline was never
meant to see.

Adds a post-transform coordinate-magnitude check in RenderShape immediately after
TransformPath is applied, covering shapes, glyph runs, and arc-converted geometry
uniformly through the single TransformPath call point. On failure, the whole shape is
tolerantly skipped, mirroring BuildRectPath/BuildEllipsePath's existing tolerant-skip
convention for an overflowing arc conversion.

Also closes a second, independent gap: stroke-width is validated finite/positive
pre-transform, but is then scaled by the transform post-validation with no bound,
producing potentially unbounded effective stroke width even when the composed scale
stays finite. Extends RenderStroke's existing finite/positive guard to also reject when
the post-transform-scaled stroke width exceeds MaxCoordinateMagnitude.

Adds two deterministic regression tests (a scaled coordinate-magnitude skip and a scaled
stroke-width skip) and documents both new enforcement points in the SvgCodec design and
verification docs.
…dth/height

The GetInfo(Stream) XML doc and the mirrored user-guide bullet both overstated that a
malformed width/height attribute causes InvalidDataException. In reality, ParseLength
treats a blank, percentage, unparseable, or non-finite width/height value as absent and
falls through to the next GetInfo fallback tier (ultimately the 300x150 default size)
rather than throwing - only a malformed viewBox (not exactly four numbers, or
non-positive width/height) or the root-tag character-cap violation actually throw.

Corrects both the SvgCodec.cs XML doc and docs/user_guide/introduction.md to state the
accurate contract. No behavior change - the existing
SvgCodec_GetInfo_WidthHeightInfinity_FallsBackToDefaultSize test already proves the true
behavior; this commit additionally links that test to the
CanvasNet-Codecs-SvgCodec-GetInfoFallback requirement in the reqstream YAML, since its
justification is exactly the contract being corrected here.
…SvgCodec

stroke-miterlimit is parsed with no upper bound (ParseValidMiterLimit only
requires finite and >= 1). Combined with an in-bound-but-large stroke-width
and a near-straight/near-reversed 'spike' vertex, StrokeOutliner's
TryCreateMiter can synthesize a miter-join point many orders of magnitude
beyond MaxCoordinateMagnitude, even though every individual literal
(coordinates, stroke-width, miterlimit) passes its own existing check. This
does not currently hang/crash (the rasterizer's clip-bounds intersection
with the canvas absorbs it harmlessly), but it is the same class of
documented-gap issue the post-transform coordinate/stroke-width checks
(commit b4de5d7) already close.

Rather than guessing an arbitrary stroke-miterlimit ceiling, RenderStroke
now re-checks the actual outline PathStroker.Stroke synthesizes against
MaxCoordinateMagnitude immediately after stroking, reusing the existing
IsWithinCoordinateMagnitudeBudget helper (PathStroker.Stroke only emits
LineTo commands, so the helper applies unmodified). On failure, the whole
stroke is tolerantly skipped, mirroring the established convention.

Adds a regression test reproducing the reviewer's exact scenario
(stroke-width=900000, stroke-miterlimit=1e12, ~0.005-degree spike vertex)
confirming the oversized stroke is now skipped instead of engulfing the
canvas, plus a normal-miter-join test (small stroke-width, default
miterlimit of 4, 90-degree corner) proving legitimate joins are unaffected.

Updates the SvgCodec design and verification docs with the third guard.
No reqstream changes: consistent with commit b4de5d7's own precedent, this
internal defense-in-depth guard has no corresponding reqstream entry.
Copilot AI review requested due to automatic review settings September 24, 2026 02:27

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

Unresolved moderate findings affect gradient resource bounds, opacity handling, namespace probing, dash parsing, and interval-cap enforcement.

Get a fresh assessment by requesting another Copilot review.

Review effort: Lite
Findings: 1 Low severity

Open (1)
Resolved since last review (4)

The GetInfo(string path) overload's InvalidDataException doc claimed
malformed sizing attributes throw, contradicting the actual fallback
behavior already documented accurately on GetInfo(Stream). Replaced
with matching text describing the real contract: viewBox malformed
conditions throw, but malformed/unparseable width/height fall back to
the next sizing tier rather than throwing.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot AI review requested due to automatic review settings September 24, 2026 02:42

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🔵 Needs a closer look

Unresolved moderate SVG correctness and resource-use issues must be addressed before approval.

Review effort: Lite
Findings: None

Resolved since last review (1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants