Fixing #408 Exponential Time Complexity Bug Causing Hangs with Nested <p> Tags #409
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fix: Exponential Time Complexity in P Converter Causing Hangs with Nested Paragraphs
Problem
The
Pconverter had a critical performance bug whereTreatChildren(node)was called multiple times (2-3x) per<p>tag, causing O(2^n) exponential time complexity with nested paragraphs. This resulted in:Real-world impact: WYSIWYG editors with ~26 nested
<p>tags would cause 67+ million recursive calls and never complete.Root Cause
In
P.cs, theConvert()method computedTreatChildren(node)and stored it in acontentvariable, but then calledTreatChildren(node)again in the return statement, ignoring the cached value:Solution
Use the cached
contentvariable instead of recalculating:Performance Improvement
Changes Made
1. Fixed P.cs converter (
src/ReverseMarkdown/Converters/P.cs)TreatChildren(node)only once2. Added comprehensive test coverage (
src/ReverseMarkdown.Test/ConverterTests.cs)Added 9 regression tests covering various nesting patterns:
When_NestedParagraphs_FiveLevelsDeep_ThenConvertCorrectly- Moderate nestingWhen_NestedSpans_FiveLevelsDeep_ThenConvertCorrectly- Span bypass testingWhen_InterleavedParagraphsAndSpans_ThenConvertCorrectly- Common malformed patternWhen_ManySequentialUnclosedParagraphs_ThenConvertCorrectly- User-generated contentWhen_UnclosedParagraphsWithSpansAndTextNodes_ThenConvertCorrectly- Mixed contentWhen_EmptyNestedParagraphs_ThenConvertCorrectly- Edge caseWhen_AlternatingEmptyAndFilledNestedParagraphs_ThenConvertCorrectly- Complex patternWhen_NestedParagraphs_TenLevelsDeep_ThenConvertCorrectly- Performance regression testTesting
Risk Assessment
Risk: Low
Related Issues
Fixes #408 (or reference the issue number where this bug was reported)
Breaking Changes
None - this is purely a performance fix with no behavioral changes.