Skip to content

Grow DXF entity lists fallibly and check room before placing them (part of #1922) - #3647

Merged
2 commits merged into
storytold:mainfrom
2ez4gcx:fix/dxf-open-oom-error
Nov 30, 2026
Merged

2 commits merged into
storytold:mainfrom
2ez4gcx:fix/dxf-open-oom-error

Conversation

@2ez4gcx

@2ez4gcx 2ez4gcx commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

Part of #1922 (F-06: memory amplification ends in OOM abort). This change covers the growth of the entity lists while a DXF is read, which is where the measured aborts happened. It does not make placing the entities in the drawing fallible: that step gets a preflight check only (see below).

What was wrong

Opening a large DXF could abort the process (handle_alloc_error, exit 0xC0000409 on Windows) instead of returning an error. Since #1833 an entity list reserves its first 65,536 entries fallibly, but past that parse_entities grew it by ordinary pushes. Each doubling (2^19, 2^20, 2^21 entries × 728 bytes) is one allocation that cannot fail cleanly, and those doublings were where every run failed. On wasm32 the same growth panics with capacity overflow once one allocation passes 2 GiB. After reading, the move into the drawing also allocated every entity again (one Arc each) while the read list still held its copy. Those small allocations can't fail cleanly either, and this PR doesn't change that.

Measured on main 32ad922 with a release cadcraft-cli info <file> --compact, run in a Windows job object with a job memory limit. The inputs are synthetic binary/ASCII DXF files of N group codes: LINE entities of 9 groups each, about 1.11M LINEs at 10M groups. The harness is a small script (measure.py style) that reports the exit code, the stderr tail and the job's peak commit. Windows 11 x64.

File Job limit main
lines_binary_10M 1.2, 1.4 GB abort: memory allocation of 381681664 bytes failed (2^19 × 728)
lines_binary_10M 1.6 – 1.8 GB abort: memory allocation of 763363328 bytes failed (2^20 × 728)
lines_binary_10M 2.0 – 3.0 GB abort: memory allocation of 1526726656 bytes failed (2^21 × 728)
lines_binary_10M 3.2, 3.4 GB opens, peak commit 3,215 MB
lines_binary_20M 3.16 GB / 5.5 GB abort (1526726656 / 3053453312 bytes)
lines_ascii_10M 1.7 / 2.2 GB abort (763363328 / 1526726656 bytes)
lines_ascii_10M 3.3 GB opens, peak 2,956 MB

What changes

All in crates/io/src/dxf_read.rs and dxf_read/document.rs:

  • Entity lists grow fallibly (entity_room). A full list doubles, as a push would, but no further than its records can fill. Every record except a follower adds at most one entity, so the list ends at about its final length, without the spare half a last doubling leaves. Only a polygon mesh's faces go past the count, and from there the list doubles again. The up-front reservation is unchanged: at most MAX_RESERVED_ENTITIES before any record is admitted (DXF read: fewer allocations on the per-group and per-entity paths (#1076) #1833). A refused reservation returns IoError::Format("DXF: out of memory reserving N entities"), the same wording entity_list already used.
  • A mesh's faces are reserved together with their polyline and pushed straight into that room. They used to be collected into a second vector first.
  • The handle sets (seen_handles, reserved_entity_handles) and the block list reserve before they insert.
  • Sections: the first ENTITIES or BLOCKS list is moved, not copied. A later one (a damaged file that repeats a section, Damaged DXF opens with exit 0 and keeps 5 of 1,504 recoverable entities, with no warning #865) is added after a fallible reservation.
  • A preflight before placing (room_to_place): before each list (ENTITIES, the model space block, a paper space block, a block definition) moves into the drawing, the reader asks once, fallibly, for an estimate of the memory the drawing's copies take: one Arc per entity plus allocator overhead, a draw-order slot and a handle-index entry. It releases that memory at once and returns IoError::Format("DXF: out of memory reserving N entities in the drawing") if the request is refused. This is a preflight, not a reservation. Placement itself still allocates infallibly: the EntityStore chunks, its handle index and one Arc per entity. If memory runs out after the check, or the estimate is too low, placement aborts as it does on main.
  • read_budgeted gets an entities_refused_past argument, carried in Rx, which is always None when reading. Tests use it to refuse the entity-list reservations and the preflight the way an allocator out of memory would, so those error paths run without exhausting memory. An in-process allocation failure can't be produced otherwise: a failing global allocator needs unsafe, which the workspace forbids.

DWG goes through the same reader: read_source converts it to a DXF rendition and calls dxf_read::read. It is covered by the same code but was not measured separately.

After

The same harness, inputs and limits, with a release build of this branch:

File Job limit main this PR
lines_binary_10M 1.2, 1.4 GB abort exit 1: out of memory reserving 524288 entities
lines_binary_10M 1.6 – 1.9 GB abort exit 1: out of memory reserving 1048576 entities
lines_binary_10M 2.0 – 2.42 GB abort exit 1: out of memory reserving 1111109 entities
lines_binary_10M 2.43 – 2.45 GB abort exit 1: out of memory reserving 1111109 entities in the drawing (the preflight)
lines_binary_10M 2.46 – 3.2 GB abort below 3.2 opens, peak commit 2,519 – 2,532 MB (main: 3,215 MB)
lines_binary_20M 3.16 GB abort exit 1: out of memory reserving 2097152 entities
lines_binary_20M 5.5 GB abort opens, peak 5,067 MB, 8.9 s
lines_ascii_10M 1.7 / 2.2 GB abort exit 1 (... 1048576 entities / ... 1111109 entities in the drawing)
lines_ascii_10M 3.3 GB opens, peak 2,956 MB, 6.8 s opens, peak 2,273 MB, 4.2 s
lines_binary_5M 3.27 GB opens, peak 1,608 MB, 2.8 s opens, peak 1,266 MB, 2.1 s
comment_binary_20M (tag list only) 1.7 GB exit 1 (tag list) exit 1 (tag list), unchanged

The lines_binary_10M sweep ran in 0.1 GB steps from 1.2 to 3.2 GB and in 0.01 GB steps from 2.41 to 2.49 GB. On this branch every run in that sweep either opened or exited 1 with the error; none aborted. That is what these inputs and limits showed, not a guarantee for placement: a limit that falls between the preflight and the placement allocations would still abort. The peak commit also drops: there is no spare half after the last doubling, and the ENTITIES list is no longer copied. Timings are single runs, so treat them as indicative only.

Tests

In dxf_read::entity_list_tests:

  • a_long_entity_list_ends_within_its_record_count: 65,636 LINE records end in a list with no more room than records. Fails on main: room for 131,072.
  • entity_room_doubles_up_to_the_record_count: below the count the list doubles, it stops at the count, past the count it doubles again, and it makes room for a mesh's faces at once. Room already there asks for nothing more. A reservation that can't be had, or one past the ceiling, is Err, not an abort.
  • a_mesh_asks_room_for_all_its_faces: a 3 × 3 polygon mesh gives 4 faces. With room refused past 3 it is Err; at 4 it reads.
  • each_list_checks_its_room_before_it_moves_into_the_drawing: for ENTITIES and for *Model_Space, *Paper_Space and an ordinary block, a refused preflight makes read_budgeted return Err. With room for exactly 3 entities each file reads its 3. This shows that the preflight rejects and that its error reaches the caller. It does not test a failure during placement itself.

The existing entity_list tests, split_entities_section (#865) and skipped_records still pass. The three earlier read_budgeted callers in tests pass None.

Not covered

  • Placing entities in the drawing is not fallible: the EntityStore chunks, its handle index and one Arc per entity still allocate infallibly, and room_to_place only checks beforehand. Making placement itself fallible at the storage boundary, verified with a bounded injected failure, is a possible follow-up. Whether the per-entity Arc can be allocated fallibly on stable Rust was not checked here.
  • Small allocations still abort if they are what crosses the limit: each entity's own strings and vertices, one record's mesh faces before they join the list, the layer set, the per-kind side tables (inserted, image_defs, paper_views_dropped, ...), and Drawing::reserved_handles. The measured failures were all in the large growth steps, which are now fallible.
  • craft_dxf::record_slices (craft-libs) and the indexes and RawTag copies in dxf_raw::read still allocate without a fallible reservation. They are smaller than the entity lists for entity-heavy files and run after the lists are freed. Making them fallible needs dxf_raw::read to return a Result, so it is a separate change.
  • On Linux with overcommit the preflight always passes, which is harmless there because the OOM killer decides. On wasm32 one preflight above 2 GiB is refused even though the copies would come in small pieces; a list that size already takes about 2 GiB itself, so it would not fit in 4 GiB anyway. wasm32 was not run.
  • A possible follow-up is shrinking Entity (696 bytes on x86_64, 728 bytes with its owner and paper flag). It is out of scope here.

How this combines with the other #1922 part e PRs

Testing (Windows 11 x64)

  • cargo xtask ci: fmt, clippy, tests, i18n, assets, layers and wasm all pass ("CI summary: all 7 steps passed").
  • cargo clippy -p cadcraft-io --all-targets -- -D warnings, cargo test -p cadcraft-io.
  • The new test above failed on main as described.
  • Mutation testing, 23 mutants over the new growth, room checks, reservations and append: 18 caught. The 5 survivors are the three handle and block-list try_reserve calls and the preflight's own reservation, which only matter when the allocator really refuses (the measurements above reach the preflight's refusal at 2.43 – 2.45 GB), plus copying the first section's list instead of moving it, which is equivalent except for memory.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • DXF files that require more memory than is available now return an out-of-memory error during loading instead of risking an abrupt failure.
    • Allocation checks are applied while reading entities, blocks, and mesh faces, helping prevent uncontrolled memory growth and improving reliability when loading complex drawings.

2ez4gcx and others added 2 commits November 29, 2026 23:56
Past the 65,536 entries an entity list reserves up front (storytold#1833), the
DXF reader grows it by ordinary pushes. Each doubling is one allocation
that aborts the process when it can't be had, and the last one leaves up
to half the list spare. The new test reads 65,636 LINE records and
expects no more room than records; on main the list ends with room for
131,072.

Part of storytold#1922 (F-06).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…n't fit

Opening a large DXF aborted the process (handle_alloc_error) once an
entity list grew past its fallible up-front reservation, and the move of
the entities into the drawing allocated each of them again while the
list still held its copy.

- Entity lists grow fallibly (entity_room): doubling as a push would, but
  no further than their records can fill, so they end at about their
  final length; past the count (a polygon mesh's faces) they double. The
  up-front cap of storytold#1833 is unchanged. A mesh's faces are reserved with
  their polyline and pushed straight into that room.
- The handle sets and the block list reserve before they insert.
- The first ENTITIES/BLOCKS list is moved, not copied; a repeated section
  (storytold#865) is appended after a fallible reservation.
- Before each list moves into the drawing, room_to_place asks once,
  fallibly, for about the memory the drawing's copies take and hands it
  back for them.
- read_budgeted takes a test-only ceiling (None when reading) so tests can
  refuse a reservation as an allocator out of memory would.

A release cadcraft-cli opening a 10M-group binary DXF of LINEs in a job
with a memory limit now exits 1 with "DXF: out of memory reserving N
entities" at every limit from 1.2 to 2.45 GB (main aborted up to 3.0 GB)
and opens from 2.46 GB (main needed 3.2 GB; peak commit 3,215 -> 2,532 MB).

Part of storytold#1922 (F-06).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The DXF reader now uses fallible allocation for entity parsing and drawing placement. Allocation failures return DXF out-of-memory errors and propagate through the read path. Tests cover collection growth, mesh faces, allocation thresholds, and placement limits.

Changes: DXF allocation handling

Layer / File(s) Summary
Entity parsing and allocation
crates/io/src/dxf_read.rs, crates/io/src/dxf_read/document.rs
Entity collections, reserved handles, and block definitions use fallible reservations. Mesh faces are appended directly after their parent entity. The public read path passes no refusal threshold; tests use the optional threshold to check allocation limits and collection growth.
Drawing placement checks
crates/io/src/dxf_read.rs, crates/io/src/dxf_read/document.rs
Block and ENTITIES placement check the drawing-memory limit and return errors when the limit is exceeded. The read path propagates placement errors.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Possibly related issues

Suggested reviewers: midasmatterhorn, tanish2k09, mbolling

Merge Risk: Minimal · up to 8df3d

Large DXF reads now return an out-of-memory error instead of aborting when memory runs out. No actionable merge-blocking risk was identified, and the change is easy to revert.

Pre-merge checks: Passed 4

Check name Status Explanation
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: DXF entity lists now grow with fallible allocation, and the code checks available room before placing them. The changeset matches this. The title also mentions part of…
Full details: Title check

Explanation

The title names the main change: DXF entity lists now grow with fallible allocation, and the code checks available room before placing them. The changeset matches this. The title also mentions part of #1922, which the objectives do not reference, but that does not affect whether the title describes the change. The objectives link the work to PR #3647, so the issue number in the title may be a mismatch to check.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

CodeRabbit Verify

  • Run CodeRabbit Verify to test the changes in this pull request.
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 32ad922 and 8df3d9a.

Files selected for processing: 2

  • crates/io/src/dxf_read.rs
  • crates/io/src/dxf_read/document.rs

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

@FredApps FredApps left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The fallible reservations and removal of the extra list copy are useful improvements. Please scope the title and issue status to the allocation failures this change actually handles: the drawing-placement check is a temporary preflight, not a guarantee that the subsequent placement allocations can fail normally. The injected refusal tests verify preflight rejection, not placement failure. If the intention is to claim that placement itself returns an error, use a fallible ownership/reservation path at the actual storage boundary and verify it via a bounded injected failure. No real memory-pressure test is needed for this review.

@2ez4gcx 2ez4gcx changed the title Return an out-of-memory error, not an abort, when a DXF's entities don't fit (part of #1922) Grow DXF entity lists fallibly and check room before placing them (part of #1922) Nov 30, 2026
@2ez4gcx

2ez4gcx commented Nov 30, 2026

Copy link
Copy Markdown
Contributor Author

Thanks. I've rescoped the title and the description; the code is unchanged.

  • Title: "Grow DXF entity lists fallibly and check room before placing them (part of F-06: memory amplification ends in OOM abort (1000x-17000x) (Medium) #1922)".
  • The description now calls room_to_place a preflight. Placement itself (the EntityStore chunks, its handle index and one Arc per entity) still allocates infallibly, and a limit that falls after the check would still abort.
  • The injected-refusal test is described as showing that the preflight rejects and its error reaches the caller, not that placement fails.
  • "Not covered" now lists making placement fallible at the storage boundary, with a bounded injected failure, as a possible follow-up.

@FredApps FredApps left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for narrowing the title and description. The PR now accurately distinguishes fallible DXF list growth from the placement preflight, and leaves #1922 open. That addresses my scope request.

I verified that the Ubuntu gate ran on this exact head: 5,255 tests passed, including the focused list growth, mesh reservation, and preflight checks. Later changes on main do not touch these DXF reader or storage paths. Approving the work as scoped; this is not a claim that drawing placement itself is fallible.

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.

3 participants