new Insert(BlockRecord) deep-copies nested blocks: quadratic time and stack overflow

Open
#1,283 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 3 days

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
43/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
csharp
Domain
backend

Research direction

Start with Insert.cs around line 230 and trace the constructor through BlockRecord.Clone() and Insert.Clone(). Reproduce the nested block chain from the issue, then check how reading a DWG handles nested blocks. Done means constructing deeply nested blocks avoids quadratic copying and stack overflow while preserving the expected block reference behavior.

Written by the indexing model from the issue text.

Description

Describe the bug
new Insert(BlockRecord) clones the block record when it already belongs to a document, and the clone copies every Insert inside it, which clones its block record again (Insert..ctor(BlockRecord) → BlockRecord.Clone() → Insert.Clone() → BlockRecord.Clone() → …). A chain of nested block definitions built one new Insert(previous) at a time therefore takes quadratic time (3 000 levels: about 85 s, writing included) and overflows a 1 MB stack at about 1 500 levels (StackOverflowException, the process terminates). For a block record that inserts itself, the copy does not end.

Insert.cs (master, v3.8.10), line 230:

if (block.Document != null)
{
    this.Block = (BlockRecord)block.Clone();
}

To Reproduce
On a thread with a 1 MB stack:

var doc = new CadDocument();
BlockRecord previous = null;
for (int i = 0; i < 10_000; i++)
{
    var rec = new BlockRecord("B" + i);
    rec.Entities.Add(i == 0 ? new Line(XYZ.Zero, new XYZ(1, 0, 0)) : new Insert(previous));
    doc.BlockRecords.Add(rec);
    previous = rec;
}

Expected behavior
The constructor references the block record (as reading a DWG does: 3 000 nested levels read fine on a 256 KB stack) and copies only when asked.

Version
ACadSharp 3.8.0 (NuGet); same code on master.

Dominant language
C#
Stars
873
Forks
223
Avg merge
1d 15h
Merged PRs (30d)
28

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from DomCR/ACadSharp

All issues in DomCR/ACadSharp

Similar issues

More C# issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.