fix: seven defects an adversarial audit found, and the gates that missed them
Release / test (full, windows-latest, 3.11) (push) Canceled after 0s
Release / test (pdf, ubuntu-latest, 3.11) (push) Canceled after 0s
Release / test (pdf, ubuntu-latest, 3.12) (push) Canceled after 0s
Release / build (push) Canceled after 0s
Release / publish-pypi (push) Canceled after 0s
Release / github-release (push) Canceled after 0s

Every one of these was reported ok/clean to the caller while being wrong.

Silently wrong numbers
- selection_filter(min_area) read `entity.dxf.get("area", 0.0)` for SOLID,
  TRACE and HATCH, none of which carry that attribute, so every hatch
  measured 0.0. A 1600 mm^2 hatch was excluded by min_area=1.0 while
  `filtered_by` asserted the filter had run, and COM (which reads ActiveX
  .Area) returned a different selection for the same call. It now answers
  from the measurement `entity_measure` uses, so the two cannot disagree.
- Every headless dimension rendered through ezdxf's bare `Standard` style:
  1.0 mm text with a comma decimal marker, against ISO 3098's 2.5 mm minimum
  and ISO 129's point -- while the document header itself said $DIMTXT 2.5.
  `ezdxf.new(setup=True)` is not the fix; measured, it renders a 100 mm
  dimension as "10000". The attributes are now stored explicitly.
- Saving writes `dimrnd = 0.0` onto the Standard style, and ezdxf applies
  `xround(value, dimrnd)` whenever the attribute is present at all --
  `xround(33.333, 0.0)` is 33. So on any reopened file, including one this
  server saved, every dimension was rounded to a whole unit before DIMDEC
  formatted it: a 12.75 mm feature dimensioned 13. AutoCAD means DIMRND 0 as
  *no* rounding; the sentinel is now discarded at every load site, and a real
  0.5 mm rounding is left alone.
- The DIM* header fold gave out-of-range values teeth they did not have when
  they died in the header: dim_decimals=-1 returned ok and then killed the
  next dimension with `ValueError: Format specifier missing precision` from
  inside ezdxf, and 40 printed forty digits of float noise onto the sheet.
  Ranges are now AutoCAD's own (DIMDEC 0-8, DIMZIN 0-15, lengths positive).

Security
- security.py recorded the policy as "sanitize_command and sanitize_lisp each
  have exactly ONE caller ... the policy is scoped to the CHANNEL". The
  premise was false. `_ensure_linetype_loaded` and `ComBackend.linetype_load`
  build `_-LINETYPE _LOAD {name} {file}` and hand it to SendCommand, which
  treats a newline and ';' as segment separators -- so a `linetype=` argument
  carrying either injected further AutoCAD commands, and the 36-verb denylist
  never saw that channel. Guarded with the DXF symbol-name rule (the
  injection characters fall out of it rather than being enumerated) plus
  validate_path for the file argument, which was also the one path-taking
  tool reaching the filesystem unchecked. The policy comment is corrected.

Gates that could not see
- drawing_critique returned zero issues on a quarantined document: all seven
  checks wrapped their backend call in a bare `except Exception`. CLAUDE.md
  rule 7 makes that call the gate an agent is told to trust. Only the
  quarantine now escapes; an ordinary broken check still degrades.
  `_check_dimension_legibility` also read `_doc` directly from the event loop
  thread, missing the gate and performing exactly the unsynchronised access
  the quarantine exists to prevent. `construction_clear` answered
  "deleted: 0" -- there was nothing to clear -- for the same reason.
- The iso128 focus checked layer lineweights only, so a sheet lettered at
  1.0 mm critiqued clean. It now reads the effective dimension height and
  separator, header-then-style, in the order the renderer resolves.
- check_doc_numbers.py derived five values it never checked, and those were
  the ones that had drifted. The collected-test count (README said 1274, the
  tree had 1369) and the A/B pass-rate and Fixed columns are now gated.
- benchmarks/README.md's v1.4.0 table was impossible on its face -- 21
  passing plus 5 fixed is 26, not 24 -- and contradicted the report it
  linked, because `ab-v1.4.0-vs-v1.5.0.json` was regenerated from a tree that
  already carried the dimension fixes and so never measured the v1.5.0 tag.
  Replaced with a real run: ab-v1.4.0-vs-v1.5.1.json, 21/26 -> 26/26.

Release gate
- release.yml ran one ubuntu/3.11 lane, so a Windows-only defect could reach
  PyPI with no Windows job having executed. That is not hypothetical: v1.5.0
  shipped `except pywintypes.com_error` raising NameError wherever pywin32 is
  absent. It now runs the same three lanes as ci.yml, Windows included.

1368 passed, 1 xfailed. ruff clean. Tool inventory and all 16 gated document
numbers match the tree.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Umut CAN
2026-08-06 23:07:50 +03:00
co-authored by Claude Opus 5
parent 6b9860e68e
commit ca1c79fd01
28 changed files with 3376 additions and 148 deletions
+50
View File
@@ -431,3 +431,53 @@ async def test_a_simple_polyline_is_not_flagged():
backend = _measure_backend(entity)
assert (await backend.entity_measure("8A5"))["self_intersecting"] is False
# ── the member profile, measured on a live AutoCAD 2026 (2026-08-06) ────────
#
# Probed on a fresh seat with a throwaway drawing, nothing saved:
# AcDbCircle Area 314.1593 Circumference 62.8319 (no Length, no Coordinates)
# AcDbPolyline Area 1600.0 Length 160.0 Coordinates present
# AcDbHatch Area 942.4778 -- r20 with an r10 island, so pi*(400-100):
# AutoCAD's hatch area DOES subtract islands
# AcDbRegion Area 1600.0 Perimeter 160.0
# AcDb3dSolid Area ABSENT Volume 1000.0
#
# The last row is the one that matters: ActiveX exposes no `.Area` on a 3DSOLID
# at all, so "REGION / 3DSOLID area" was half a claim.
@pytest.mark.asyncio
async def test_a_circle_uses_circumference_for_its_perimeter():
"""Measured: AcDbCircle has `.Circumference` and no `.Length`."""
backend = _measure_backend(_Entity("AcDbCircle", Area=314.1593, Circumference=62.8319))
result = await backend.entity_measure("C01")
assert result["area"] == pytest.approx(314.1593)
assert result["perimeter"] == pytest.approx(62.8319)
assert result["perimeter_exact"] is True
@pytest.mark.asyncio
async def test_a_region_uses_perimeter():
"""Measured: AcDbRegion has `.Perimeter` and no `.Length`."""
backend = _measure_backend(_Entity("AcDbRegion", Area=1600.0, Perimeter=160.0))
result = await backend.entity_measure("R01")
assert result["area"] == pytest.approx(1600.0)
assert result["perimeter"] == pytest.approx(160.0)
@pytest.mark.asyncio
async def test_a_3dsolid_is_refused_by_name_because_activex_has_no_area_for_it():
"""Measured: AcDb3dSolid exposes Volume and no Area at all.
The generic "neither an area nor usable vertices" would send the reader
hunting for geometry that was never the problem.
"""
backend = _measure_backend(_Entity("AcDb3dSolid", Volume=1000.0))
with pytest.raises(RuntimeError, match="no surface-area member"):
await backend.entity_measure("S01")
+74
View File
@@ -117,6 +117,80 @@ async def test_genuine_deadline_still_rebuilds_the_executor(com_backend, monkeyp
assert await asyncio.wait_for(com_backend._run(lambda: "fresh"), timeout=3) == "fresh"
# ── R32 — what the timeout message must admit, and the undo mark it must record ──
async def test_com_timeout_says_the_call_may_still_land(com_backend, monkeypatch):
"""AutoCAD's own command processor arbitrates the abandoned call, not us.
Unlike the ezdxf backend there is no ``self._doc`` to quarantine — the
drawing belongs to the operator and lives in AutoCAD's process. What the
server *can* do is stop the message implying the operation is dead: the
worker is still blocked inside an uncancellable COM call, so a blind retry
double-applies it.
"""
monkeypatch.setattr(config.settings, "com_call_timeout", 0.2)
release = threading.Event()
finished = threading.Event()
def _hang():
try:
release.wait(5.0)
finally:
finished.set()
try:
with pytest.raises(RuntimeError) as excinfo:
await com_backend._run(_hang)
finally:
release.set()
assert finished.wait(5)
message = str(excinfo.value).lower()
assert "may still" in message, "the abandoned call can still execute in AutoCAD"
assert "retry" in message and "double" in message
async def test_timed_out_transaction_begin_does_not_hide_an_open_undo_mark(
com_backend, monkeypatch
):
"""RED: ``_transaction_active`` was set only after ``_run`` returned.
A timed-out ``transaction_begin`` therefore left ``StartUndoMark`` open in
AutoCAD while the server recorded no transaction, and the next
``transaction_begin`` nested a second mark nobody could see — the exact
inverse of the R16 fix ``transaction_commit`` already carries.
"""
monkeypatch.setattr(config.settings, "com_call_timeout", 0.2)
release = threading.Event()
finished = threading.Event()
marks = []
class _FakeDoc:
def StartUndoMark(self):
marks.append("start")
try:
release.wait(5.0)
finally:
finished.set()
monkeypatch.setattr(cb, "_acad_doc", lambda: _FakeDoc())
try:
with pytest.raises(RuntimeError, match="did not respond"):
await com_backend.transaction_begin()
assert com_backend._transaction_active is True, (
"the mark may already be set in AutoCAD; recording nothing is the unsafe direction"
)
again = await com_backend.transaction_begin()
assert again == {"ok": False, "error": "A transaction is already active"}
assert marks == ["start"], "the second begin must not nest another undo mark"
finally:
release.set()
assert finished.wait(5)
def _raise_value_error():
raise ValueError("nope")
+342
View File
@@ -0,0 +1,342 @@
"""DIM* header variables have to reach the dimension, not just the header.
v1.5.1 fixed exactly one of them. `system_set_variable("DIMSCALE", 4)` grew a
fold that carried `$DIMSCALE` onto the per-dimension override, because ezdxf
renders a DIMENSION from the dimstyle table entry plus that override and never
reads the document header. Every *other* DIM* variable kept the original defect:
drawing_new()
system_set_variable("DIMTXT", 5.0) -> {"ok": True}
system_set_variable("DIMASZ", 6.0) -> {"ok": True}
system_set_variable("DIMDEC", 1) -> {"ok": True}
system_set_variable("DIMDSEP", 44) -> {"ok": True}
system_set_variable("DIMZIN", 0) -> {"ok": True}
dimension_linear(0, 0, 33.333, 0, 16, -30)
Measured before the fix: five `ok: True` results, a header that reads back every
one of the five values, and a dimension still rendered at 2.5 mm text with 2.5
arrows and "33.33" — byte-identical to the one drawn before the writes. A live
AutoCAD seat builds a dimension from the current dimvars, so the same five calls
did change the drawing there: one tool call, one reported success, two engines
drawing different sheets.
These tests read the *rendered* geometry block rather than the header, because
the header was never the thing that was broken.
"""
from __future__ import annotations
import pytest
pytestmark = pytest.mark.asyncio
def _rendered(backend, handle):
"""(text, text height, arrow scales) out of the dimension's geometry block.
The override lands in the dimension's XDATA, not on `dim.dxf`, so the block
ezdxf renders is the only honest witness. Arrow size shows up as the xscale
of the `_CLOSEDFILLED` arrowhead INSERT — the one non-text observable here,
which is what keeps these tests from passing on a text-only patch.
"""
dim = backend._doc.entitydb.get(handle)
block = backend._doc.blocks.get(dim.dxf.geometry)
text = None
height = None
arrows = []
for entity in block:
if entity.dxftype() == "MTEXT" and text is None:
text, height = entity.text, round(float(entity.dxf.char_height), 4)
elif entity.dxftype() == "TEXT" and text is None:
text, height = entity.dxf.text, round(float(entity.dxf.height), 4)
elif entity.dxftype() == "INSERT":
arrows.append(round(float(entity.dxf.get("xscale", 1.0)), 4))
if text is None:
raise AssertionError("the dimension block carries no text")
return text, height, sorted(set(arrows))
# ── text height ─────────────────────────────────────────────────────────────
async def test_dimtxt_reaches_the_next_dimension(backend):
"""Asserted as a ratio, for the reason recorded in the DIMSCALE tests.
Hardcoding 5.0 would hide the day the base height moves; hardcoding 2.5
would make the test depend on the ISO default it is not measuring.
"""
plain = await backend.dimension_linear(0, 0, 33.333, 0, 16, -30)
_t, base, _a = _rendered(backend, plain.handle)
await backend.system_set_variable("DIMTXT", base * 2)
after = await backend.dimension_linear(0, 0, 33.333, 0, 16, -60)
_t, height, _a = _rendered(backend, after.handle)
assert height == pytest.approx(base * 2), (
f"DIMTXT must letter the next dimension: {base} -> {height}"
)
async def test_dimtxt_and_dimscale_still_multiply(backend):
"""`text_height = get_char_height(...) * dimscale` (ezdxf dim_base.py).
Both fold into the same override dict, so the two must compose rather than
the later one winning.
"""
plain = await backend.dimension_linear(0, 0, 100, 0, 50, -30)
_t, base, _a = _rendered(backend, plain.handle)
await backend.system_set_variable("DIMTXT", base * 2)
await backend.system_set_variable("DIMSCALE", 3.0)
after = await backend.dimension_linear(0, 0, 100, 0, 50, -60)
_t, height, _a = _rendered(backend, after.handle)
assert height == pytest.approx(base * 6)
async def test_a_fixed_height_text_style_still_defeats_dimtxt(backend):
"""A limitation this fold cannot repair, pinned so nobody assumes it can.
`get_char_height` reads the *text style's* height first and only falls back
to DIMTXT when it is 0 (ezdxf dim_base.py). Measured: with the `Standard`
text style at 3.0 mm, DIMTXT 5.0 still renders 3.0 — the header write
reports success and the sheet does not move. Only a height-0 (variable)
text style lets DIMTXT through, which is what `drawing_new` ships.
"""
backend._doc.styles.get("Standard").dxf.height = 3.0
await backend.system_set_variable("DIMTXT", 5.0)
dim = await backend.dimension_linear(0, 0, 100, 0, 50, -30)
_t, height, _a = _rendered(backend, dim.handle)
assert height == pytest.approx(3.0), "a fixed-height text style outranks DIMTXT"
# ── arrows: the one non-text observable ─────────────────────────────────────
async def test_dimasz_scales_the_arrowheads(backend):
plain = await backend.dimension_linear(0, 0, 100, 0, 50, -30)
_t, _h, base = _rendered(backend, plain.handle)
assert base, "no arrowhead INSERT to measure"
await backend.system_set_variable("DIMASZ", 6.0)
after = await backend.dimension_linear(0, 0, 100, 0, 50, -60)
_t, _h, arrows = _rendered(backend, after.handle)
assert arrows == pytest.approx([6.0]), f"DIMASZ must size the arrows: {base} -> {arrows}"
# ── number formatting ───────────────────────────────────────────────────────
@pytest.mark.parametrize(("decimals", "expected"), [(1, "33.3"), (0, "33")])
async def test_dimdec_sets_the_decimal_places(backend, decimals, expected):
await backend.system_set_variable("DIMDEC", decimals)
dim = await backend.dimension_linear(0, 0, 33.333, 0, 16, -30)
text, _h, _a = _rendered(backend, dim.handle)
assert text == expected
async def test_dimdsep_switches_the_decimal_marker(backend):
"""44 is the char code for a comma; ezdxf refuses a string in the header."""
await backend.system_set_variable("DIMDSEP", 44)
dim = await backend.dimension_linear(0, 0, 33.333, 0, 16, -30)
text, _h, _a = _rendered(backend, dim.handle)
assert text == "33,33"
async def test_an_untouched_drawing_still_uses_a_point(backend):
"""The converse regression: ISO 129 wants a point, and ezdxf's own renderer
fallback for `dimdsep` is 0 -> a comma. A fold keyed on the wrong baseline
would reintroduce the comma on every dimension."""
dim = await backend.dimension_linear(0, 0, 33.333, 0, 16, -30)
text, _h, _a = _rendered(backend, dim.handle)
assert text == "33.33"
@pytest.mark.parametrize(("dimzin", "expected"), [(0, "100.000"), (8, "100")])
async def test_dimzin_controls_trailing_zeros(backend, dimzin, expected):
await backend.system_set_variable("DIMDEC", 3)
await backend.system_set_variable("DIMZIN", dimzin)
dim = await backend.dimension_linear(0, 0, 100, 0, 50, -30)
text, _h, _a = _rendered(backend, dim.handle)
assert text == expected
# ── all five tools, not just linear ─────────────────────────────────────────
async def test_dimtxt_reaches_all_five_dimension_tools(backend):
"""aligned and angular do not go through `build_dim_override`.
That is exactly how they were missed when DIMSCALE was folded the first
time (see `test_dimscale_reaches_aligned_and_angular_too`), so every tool
is measured here rather than trusting the shared helper.
"""
plain = {
"linear": await backend.dimension_linear(0, 0, 100, 0, 50, -30),
"aligned": await backend.dimension_aligned(0, 0, 60, 60, 40, 70),
"angular": await backend.dimension_angular(0, 0, 50, 0, -30, 50, 30, 30),
"radius": await backend.dimension_radius(0, 0, 20, 0, 10),
"diameter": await backend.dimension_diameter(0, 0, 40, 0, 10),
}
base = {name: _rendered(backend, info.handle)[1] for name, info in plain.items()}
await backend.system_set_variable("DIMTXT", 5.0)
scaled = {
"linear": await backend.dimension_linear(0, 0, 100, 0, 50, -60),
"aligned": await backend.dimension_aligned(0, 0, 60, 60, 40, 90),
"angular": await backend.dimension_angular(0, 0, 50, 0, -30, 50, 50, 50),
"radius": await backend.dimension_radius(0, 0, 20, 0, 30),
"diameter": await backend.dimension_diameter(0, 0, 40, 0, 30),
}
for name, info in scaled.items():
_t, height, _a = _rendered(backend, info.handle)
assert height == pytest.approx(5.0), f"{name}: {base[name]} -> {height}, wanted 5.0"
async def test_angular_text_is_a_different_knob_and_is_deliberately_not_folded(backend):
"""DIMDEC does not format an angular dimension — DIMADEC does.
Pinned because $DIMADEC and $DIMAZIN sit at 0 in a fresh header while
ezdxf's renderer falls back to 2 and 2. Adding them to the fold table to
make it look "complete" would silently reformat every angular dimension
this server has ever drawn, from 239.04 deg to 239 deg. The allowlist is
measured, not exhaustive.
"""
await backend.system_set_variable("DIMDEC", 0)
dim = await backend.dimension_angular(0, 0, 50, 0, -30, 50, 30, 30)
text, _h, _a = _rendered(backend, dim.handle)
assert text.startswith("239.04"), f"angular text must keep DIMADEC's 2 places, got {text!r}"
# ── the fold must not litter ────────────────────────────────────────────────
async def test_a_fresh_drawing_carries_no_dimension_override(backend):
"""Generalises `test_the_default_dimscale_adds_no_override`.
After `drawing_new` the header and the `Standard` dimstyle agree on every
folded variable ($DIMTXT 2.5/2.5, $DIMASZ 2.5/2.5, $DIMDEC 2/2, $DIMDSEP
46/46, $DIMSCALE and $DIMZIN unset on the style and equal to the renderer
fallback), so the fold has nothing to say and the dimension must carry no
XDATA override at all.
"""
dim = await backend.dimension_linear(0, 0, 100, 0, 50, -30)
entity = backend._doc.entitydb.get(dim.handle)
style = backend._doc.dimstyles.get("Standard")
assert entity.get_acad_dstyle(style) == {}
async def test_the_basic_tolerance_box_survives_the_fold(backend):
"""`tol_mode="basic"` sets dimgap=-1.0 to draw the theoretically-exact box.
The fold runs *after* `build_dim_override` and must only `setdefault`, so a
caller's explicit value always outranks the header. dimgap is not in the
table today, but this pins the ordering that protects it if it ever is.
"""
await backend.system_set_variable("DIMTXT", 5.0)
dim = await backend.dimension_linear(0, 0, 100, 0, 50, -30, tol_mode="basic")
entity = backend._doc.entitydb.get(dim.handle)
style = backend._doc.dimstyles.get("Standard")
overrides = entity.get_acad_dstyle(style)
assert overrides.get("dimgap") == pytest.approx(-1.0)
assert overrides.get("dimtxt") == pytest.approx(5.0)
# ── precedence, both directions ─────────────────────────────────────────────
async def test_setting_the_variable_back_reverts_the_next_dimension(backend):
plain = await backend.dimension_linear(0, 0, 100, 0, 50, -30)
_t, base, _a = _rendered(backend, plain.handle)
await backend.system_set_variable("DIMTXT", 5.0)
await backend.dimension_linear(0, 0, 100, 0, 50, -60)
await backend.system_set_variable("DIMTXT", base)
reverted = await backend.dimension_linear(0, 0, 100, 0, 50, -90)
_t, height, _a = _rendered(backend, reverted.handle)
assert height == pytest.approx(base)
async def test_a_rollback_restores_the_header_and_the_next_dimension(backend):
"""Transactions snapshot the whole DXF, header included."""
plain = await backend.dimension_linear(0, 0, 100, 0, 50, -30)
_t, base, _a = _rendered(backend, plain.handle)
await backend.transaction_begin()
await backend.system_set_variable("DIMTXT", 5.0)
await backend.transaction_rollback()
after = await backend.dimension_linear(0, 0, 100, 0, 50, -60)
_t, height, _a = _rendered(backend, after.handle)
assert height == pytest.approx(base)
# ── opened files ────────────────────────────────────────────────────────────
async def test_an_opened_file_honours_its_own_header(backend, tmp_path):
"""A file whose header disagrees with its dimstyle used to draw the style.
`drawing_open` never runs `_apply_iso_dimstyle`, so before the fold the
header of an opened template was decorative: it could claim $DIMTXT 5.0
and every dimension still came out at the style's 2.5. AutoCAD builds a
dimension from the current dimvars, so the file stops lying about itself.
"""
import ezdxf
doc = ezdxf.new(dxfversion="R2010")
doc.dimstyles.get("Standard").dxf.dimtxt = 2.5
doc.header["$DIMTXT"] = 5.0
path = tmp_path / "header_says_five.dxf"
doc.saveas(str(path))
await backend.drawing_open(str(path))
dim = await backend.dimension_linear(0, 0, 100, 0, 50, -30)
_t, height, _a = _rendered(backend, dim.handle)
assert height == pytest.approx(5.0)
# ── the fold itself ─────────────────────────────────────────────────────────
async def test_a_header_without_the_variable_does_not_break_the_fold():
"""An opened file may be missing a DIM* var, or carry junk in it."""
from backends.ezdxf_backend import _with_header_dimvars
class _Header:
def get(self, name, default=None):
return {"$DIMTXT": "not a number"}.get(name, default)
class _Doc:
header = _Header()
dimstyles = None # resolving the style must not be required either
assert _with_header_dimvars(_Doc(), None) is None
assert _with_header_dimvars(_Doc(), {"dimgap": -1.0}) == {"dimgap": -1.0}
async def test_the_dollar_prefixed_name_is_still_rejected(backend):
"""`system_set_variable` prefixes '$' unconditionally, so '$DIMTXT' becomes
'$$DIMTXT' and ezdxf refuses it. Pinned because the original bug report
reached for the dollar form and read the resulting exception as the no-op:
a test written that way would fail for the wrong reason forever."""
with pytest.raises(Exception, match=r"\$\$DIMTXT"):
await backend.system_set_variable("$DIMTXT", 5.0)
+244
View File
@@ -0,0 +1,244 @@
"""Headless dimensions must be readable ISO drawings, not ezdxf defaults.
`drawing_new` called `ezdxf.new(dxfversion=...)` without `setup=True`, and
nothing in the repo ever created or configured a dimstyle. So every headless
dimension rendered through ezdxf's bare `Standard` style: **1.0 mm** text with a
**comma** decimal marker. ISO 3098 puts the minimum lettering height at 2.5 mm,
and ISO 129 wants a point.
Two things made that worse than a cosmetic default:
* The document's own header already said ``$DIMTXT 2.5``. ezdxf renders from the
dimstyle table entry and never reads the header, so the file asserted one
height and drew another.
* A live AutoCAD seat renders from whatever its template carries, so the two
engines printed a different text height *and* a different decimal marker for
byte-identical tool calls, with no capability key or test recording it.
"""
from __future__ import annotations
import pytest
pytestmark = pytest.mark.asyncio
#: ISO 3098 minimum lettering height for technical drawings.
ISO_MIN_TEXT_MM = 2.5
def _rendered(backend, handle):
"""The text and height a drafter actually sees, out of the dimension block."""
dim = backend._doc.entitydb.get(handle)
block = backend._doc.blocks.get(dim.dxf.geometry)
for entity in block:
if entity.dxftype() == "MTEXT":
return entity.text, float(entity.dxf.char_height)
if entity.dxftype() == "TEXT":
return entity.dxf.text, float(entity.dxf.height)
raise AssertionError("the dimension block carries no text")
async def test_a_headless_dimension_is_lettered_at_iso_height(backend):
dim = await backend.dimension_linear(0, 0, 100, 0, 50, -20, layer="DIM")
_text, height = _rendered(backend, dim.handle)
assert height >= ISO_MIN_TEXT_MM, (
f"rendered at {height} mm; ISO 3098 minimum is {ISO_MIN_TEXT_MM} mm"
)
async def test_the_decimal_marker_is_a_point(backend):
"""ISO 129 wants a point. ezdxf's bare default is a comma."""
dim = await backend.dimension_linear(0, 0, 33.333, 0, 16, -20, layer="DIM")
text, _height = _rendered(backend, dim.handle)
assert "," not in text, f"rendered {text!r} with a comma decimal marker"
assert "33.33" in text
async def test_the_header_and_the_dimstyle_agree_about_text_height(backend):
"""The file used to assert $DIMTXT 2.5 and draw 1.0."""
header = float(backend._doc.header.get("$DIMTXT"))
style = backend._doc.dimstyles.get("Standard")
assert float(style.dxf.dimtxt) == pytest.approx(header)
async def test_a_reopened_drawing_keeps_the_style(backend, tmp_path):
"""The style has to be in the file, not applied in memory on the way out."""
import ezdxf
dim = await backend.dimension_linear(0, 0, 100, 0, 50, -20, layer="DIM")
path = tmp_path / "styled.dxf"
await backend.drawing_save_as(str(path))
reopened = ezdxf.readfile(str(path))
style = reopened.dimstyles.get("Standard")
assert float(style.dxf.dimtxt) >= ISO_MIN_TEXT_MM
assert int(style.dxf.dimdsep) == ord(".")
assert reopened.entitydb.get(dim.handle) is not None
# ── the gate has to be able to see it ───────────────────────────────────────
async def test_the_iso_critique_catches_sub_iso_dimension_text(backend):
"""A drawing whose dimensions are 1.0 mm used to critique clean.
Fixing the default stops this server *producing* such a drawing, but the
gate still has to catch one — a template, an opened file, or a caller who
sets the style back can all reintroduce it, and `drawing_critique`
returning [] is the claim that the sheet is ISO-conformant.
Both the style and the header are pushed down here. Since the DIM* header
fold, the header outranks the style at render time, so setting the style
alone no longer produces a 1.0 mm drawing — it would leave this test
asserting a defect that is not on the sheet.
"""
from engineering.critique import run_critique
backend._doc.dimstyles.get("Standard").dxf.dimtxt = 1.0
await backend.system_set_variable("DIMTXT", 1.0)
await backend.dimension_linear(0, 0, 100, 0, 50, -20, layer="DIM")
issues = await run_critique(backend, focus=["iso128"])
assert issues, "1.0 mm dimension text is below the ISO 3098 minimum"
assert any("2.5" in issue.message for issue in issues)
async def test_the_iso_critique_catches_a_comma_decimal_marker(backend):
from engineering.critique import run_critique
backend._doc.dimstyles.get("Standard").dxf.dimdsep = ord(",")
await backend.system_set_variable("DIMDSEP", ord(","))
await backend.dimension_linear(0, 0, 33.333, 0, 16, -20, layer="DIM")
issues = await run_critique(backend, focus=["iso128"])
assert any("decimal" in issue.message.lower() for issue in issues)
async def test_a_conformant_drawing_still_critiques_clean(backend):
"""The rule must not fire on the styles this server now ships."""
from engineering.critique import run_critique
await backend.drawing_apply_iso_layers("mech")
await backend.dimension_linear(0, 0, 100, 0, 50, -20, layer="DIM")
assert await run_critique(backend, focus=["iso128"]) == []
async def test_the_critique_grades_what_will_actually_be_drawn(backend):
"""When the header and the style disagree, the header is what gets drawn.
Reading the style alone made `drawing_critique` able to be wrong in both
directions once DIM* header variables started reaching the renderer: it
would report a 1.0 mm defect on a sheet lettered at 2.5, and clear a sheet
lettered at 1.0 because the style still said 2.5. The gate has to resolve
the same header-then-style order the renderer does.
"""
from engineering.critique import run_critique
# Style below the minimum, header above it -> the sheet is conformant.
backend._doc.dimstyles.get("Standard").dxf.dimtxt = 1.0
await backend.system_set_variable("DIMTXT", 2.5)
dim = await backend.dimension_linear(0, 0, 100, 0, 50, -20, layer="DIM")
assert _rendered(backend, dim.handle)[1] == pytest.approx(2.5)
assert await run_critique(backend, focus=["iso128"]) == []
# Style above it, header below -> the sheet is not.
backend._doc.dimstyles.get("Standard").dxf.dimtxt = 2.5
await backend.system_set_variable("DIMTXT", 1.0)
dim = await backend.dimension_linear(0, 0, 100, 0, 50, -60, layer="DIM")
assert _rendered(backend, dim.handle)[1] == pytest.approx(1.0)
assert await run_critique(backend, focus=["iso128"])
# ── the DIM* header fold must not fight the ISO defaults ────────────────────
async def test_the_iso_defaults_survive_the_header_fold(backend):
"""The regression that fails if the fold is keyed on the wrong baseline.
The fold skips a variable when the header already agrees with what the
renderer would use. That baseline is ezdxf's *renderer* fallback (dimtxt
1.0, dimasz 0.25, dimdsep 0 -> comma), not the DXF schema default (2.5,
2.5, 44). Key it on the schema defaults and a fresh drawing starts folding
values it should leave alone — most visibly reintroducing the comma this
file exists to keep out.
"""
from engineering.critique import run_critique
await backend.drawing_apply_iso_layers("mech")
dim = await backend.dimension_linear(0, 0, 33.333, 0, 16, -20, layer="DIM")
text, height = _rendered(backend, dim.handle)
assert height == pytest.approx(ISO_MIN_TEXT_MM)
assert text == "33.33"
block = backend._doc.blocks.get(backend._doc.entitydb.get(dim.handle).dxf.geometry)
arrows = {round(float(e.dxf.get("xscale", 1.0)), 3) for e in block if e.dxftype() == "INSERT"}
assert arrows == {2.5}
assert await run_critique(backend, focus=["iso128"]) == []
# ── DIMRND 0.0 means "no rounding", not "round to whole units" ──────────────
async def _reopened(backend, tmp_path):
path = tmp_path / "roundtrip.dxf"
await backend.drawing_save_as(str(path))
await backend.drawing_open(str(path))
return path
def _text(backend, handle) -> str:
dim = backend._doc.entitydb.get(handle)
for entity in backend._doc.blocks.get(dim.dxf.geometry):
if entity.dxftype() == "MTEXT":
return entity.text
if entity.dxftype() == "TEXT":
return entity.dxf.text
raise AssertionError("the dimension block carries no text")
async def test_a_reopened_drawing_does_not_round_every_dimension_to_a_whole_unit(backend, tmp_path):
"""A saved file stores `dimrnd = 0.0`, and ezdxf rounds on it.
AutoCAD's DIMRND 0 means *no* rounding. ezdxf applies `xround(value,
dimrnd)` whenever the attribute is present at all, and `xround(33.333, 0.0)`
is 33 — so every dimension on any reopened file was silently rounded to a
whole unit *before* DIMDEC ever formatted it. Measured on a file this
server saved itself: a 12.75 mm feature dimensioned as 13.
"""
await _reopened(backend, tmp_path)
await backend.drawing_settings({"dim_decimals": 2})
dim = await backend.dimension_linear(0, 0, 33.333, 0, 16, -30)
assert _text(backend, dim.handle) == "33.33"
async def test_dim_decimals_still_works_after_a_reopen(backend, tmp_path):
await _reopened(backend, tmp_path)
for decimals, expected in ((0, "33"), (1, "33.3"), (3, "33.333")):
await backend.drawing_settings({"dim_decimals": decimals})
dim = await backend.dimension_linear(0, 0, 33.333, 0, 16, -30 * (decimals + 2))
assert _text(backend, dim.handle) == expected
async def test_a_real_rounding_value_is_left_alone(backend, tmp_path):
"""Only the 0.0 sentinel is discarded — a drafter who asked for 0.5 mm
rounding must keep it."""
backend._doc.dimstyles.get("Standard").dxf.dimrnd = 0.5
await _reopened(backend, tmp_path)
assert float(backend._doc.dimstyles.get("Standard").dxf.dimrnd) == 0.5
dim = await backend.dimension_linear(0, 0, 33.333, 0, 16, -30)
# 33.5, not 33.33: the rounding survived. The trailing zero is gone because
# DIMZIN defaults to 8, which suppresses it — that is formatting, and it is
# a different knob from the rounding this test is about.
assert _text(backend, dim.handle) == "33.5"
+82 -6
View File
@@ -130,10 +130,86 @@ async def test_the_default_dimscale_adds_no_override(backend):
async def test_dimscale_reaches_aligned_and_angular_too(backend):
"""Those two do not go through `build_dim_override`, so they were missed."""
await backend.drawing_settings({"dimscale": 3.0})
aligned = await backend.dimension_aligned(0, 0, 60, 60, 40, 70)
angular = await backend.dimension_angular(0, 0, 50, 0, 0, 50, 30, 30)
"""Those two do not go through `build_dim_override`, so they were missed.
for handle in (aligned.handle, angular.handle):
assert _dim_text_heights(backend, handle) == pytest.approx([3.0])
Asserted as a *ratio* against the same dimension drawn unscaled. This used
to hardcode 3.0, which only held because the base text height was ezdxf's
bare 1.0 mm — so the assertion silently depended on the very defect that
made every headless drawing non-conformant, and moving the base to the ISO
2.5 mm broke a test that was measuring the right thing by accident.
"""
plain_aligned = await backend.dimension_aligned(0, 0, 60, 60, 40, 70)
plain_angular = await backend.dimension_angular(0, 0, 50, 0, 0, 50, 30, 30)
base_aligned = _dim_text_heights(backend, plain_aligned.handle)
base_angular = _dim_text_heights(backend, plain_angular.handle)
await backend.drawing_settings({"dimscale": 3.0})
aligned = await backend.dimension_aligned(0, 0, 60, 60, 40, 90)
angular = await backend.dimension_angular(0, 0, 50, 0, 0, 50, 50, 50)
assert _dim_text_heights(backend, aligned.handle) == pytest.approx(
[h * 3.0 for h in base_aligned]
)
assert _dim_text_heights(backend, angular.handle) == pytest.approx(
[h * 3.0 for h in base_angular]
)
# ── the rest of the dimension variables need friendly names too ─────────────
def _dim_text(backend, handle) -> str:
dim = backend._doc.entitydb.get(handle)
for entity in backend._doc.blocks.get(dim.dxf.geometry):
if entity.dxftype() == "MTEXT":
return entity.text
if entity.dxftype() == "TEXT":
return entity.dxf.text
raise AssertionError("the dimension block carries no text")
async def test_the_dimension_variables_have_friendly_names(backend):
"""DIMTXT / DIMASZ / DIMDEC / DIMDSEP / DIMZIN had no friendly key at all.
`text_size` is TEXTSIZE — the height of a standalone TEXT entity, not of a
dimension — so the only way to reach dimension lettering was raw
`system_set_variable`, which is exactly the path that silently did nothing
headlessly. A drafter should not have to know a sysvar name to set the
height of the numbers on their own drawing.
"""
res = await backend.drawing_settings(
{
"dim_text_height": 5.0,
"dim_arrow_size": 6.0,
"dim_decimals": 1,
"decimal_separator": ",",
"zero_suppression": 0,
}
)
assert res["ok"] is True, res.get("errors")
dim = await backend.dimension_linear(0, 0, 33.333, 0, 16, -30)
assert _dim_text(backend, dim.handle) == "33,3"
assert _dim_text_heights(backend, dim.handle) == pytest.approx([5.0])
async def test_the_decimal_separator_reads_back_as_a_character(backend):
"""DIMDSEP is an int char code in the header — ezdxf refuses a string
there. The friendly key is the place to translate, so a snapshot says
',' rather than 44."""
await backend.drawing_settings({"decimal_separator": ","})
snap = (await backend.drawing_settings())["settings"]
assert snap["decimal_separator"] == ","
assert snap["dim_text_height"] == 2.5
async def test_a_bad_decimal_separator_is_reported_and_not_written(backend):
before = await backend.system_get_variable("DIMDSEP")
res = await backend.drawing_settings({"decimal_separator": "x"})
assert "decimal_separator" in res["errors"]
assert res["ok"] is False
assert await backend.system_get_variable("DIMDSEP") == before
+42 -16
View File
@@ -29,6 +29,7 @@ import pytest
import config
from backends.com_backend import ComBackend
from backends.ezdxf_backend import EzdxfBackend
from backends.quarantine import DocumentQuarantineError
pytestmark = pytest.mark.asyncio
@@ -113,31 +114,45 @@ async def test_both_backends_declare_the_same_capability_keys():
async def test_slow_call_times_out_and_backend_stays_usable(backend, monkeypatch):
"""The anti-deadlock guarantee, restated after R32.
This used to assert that the next ``drawing_info`` / ``entity_create_line``
*succeeded*, on the strength of a ``_hang`` that only slept and touched no
document. Both assertions were the defect written down as a requirement: the
lock swap that stops the deadlock is exactly what drops mutual exclusion on
the one shared ``Drawing``, so "succeeded" meant "ran against a document
another thread may still be writing". The guarantee that actually holds is
that the next call returns *immediately* — refused, not queued.
"""
monkeypatch.setattr(config.settings, "ezdxf_call_timeout", 0.2)
entered = threading.Event()
release = threading.Event()
def _hang():
entered.set()
time.sleep(2.0)
release.wait(5.0)
return "too late"
started = time.monotonic()
with pytest.raises(RuntimeError) as excinfo:
await backend._async(_hang)
assert entered.is_set()
assert time.monotonic() - started < 1.5, "must abandon the call, not wait it out"
try:
started = time.monotonic()
with pytest.raises(RuntimeError) as excinfo:
await backend._async(_hang)
assert entered.is_set()
assert time.monotonic() - started < 1.5, "must abandon the call, not wait it out"
message = str(excinfo.value)
assert "EZDXF_CALL_TIMEOUT" in message
assert "0.2" in message
message = str(excinfo.value)
assert "EZDXF_CALL_TIMEOUT" in message
assert "0.2" in message
# The anti-deadlock guarantee: the NEXT call must not queue behind the
# abandoned worker thread (which is still sleeping).
monkeypatch.setattr(config.settings, "ezdxf_call_timeout", 10)
info = await asyncio.wait_for(backend.drawing_info(), timeout=3)
assert info.backend == "ezdxf"
line = await asyncio.wait_for(backend.entity_create_line(0, 0, 1, 1), timeout=3)
assert line.handle
monkeypatch.setattr(config.settings, "ezdxf_call_timeout", 10)
started = time.monotonic()
with pytest.raises(DocumentQuarantineError):
await asyncio.wait_for(backend.drawing_info(), timeout=3)
with pytest.raises(DocumentQuarantineError):
await asyncio.wait_for(backend.entity_create_line(0, 0, 1, 1), timeout=3)
assert time.monotonic() - started < 1.0, "refused up front, never queued"
finally:
release.set()
async def test_waiting_on_a_busy_backend_times_out_without_stealing_the_lock(backend, monkeypatch):
@@ -151,6 +166,10 @@ async def test_waiting_on_a_busy_backend_times_out_without_stealing_the_lock(bac
await backend._async(lambda: "never runs")
assert time.monotonic() - started < 1.0
assert backend._lock is live, "the in-flight call's lock must not be swapped out"
# R32: nothing was abandoned here, so nothing may be quarantined — that
# lock is held by a live call which will release it normally.
assert backend._quarantine is None
assert backend._abandoned_calls == []
finally:
live.release()
@@ -166,6 +185,10 @@ async def test_zero_timeout_disables_the_check(backend, monkeypatch):
return "finished"
assert await backend._async(_slow) == "finished"
# R32: with the deadline off there is no abandon branch at all, so there is
# nothing that could quarantine the document.
assert backend._quarantine is None
assert backend._abandoned_calls == []
async def test_async_still_serialises_calls(backend):
@@ -202,6 +225,9 @@ async def test_a_call_raising_TimeoutError_is_not_reported_as_the_deadline(backe
await backend._async(_boom)
assert backend._lock is live, "a call that merely failed must not abandon its lock"
# R32: not our deadline, so no thread was abandoned and the document is fine.
assert backend._quarantine is None
assert backend._abandoned_calls == []
assert await asyncio.wait_for(backend._async(lambda: "next"), timeout=2) == "next"
+415
View File
@@ -0,0 +1,415 @@
"""R32 — a timed-out ezdxf call must quarantine the DOCUMENT, not just the lock.
``EzdxfBackend._async`` cannot cancel an ``asyncio.to_thread`` worker. When a
call overruns ``EZDXF_CALL_TIMEOUT`` the handler swaps in a fresh
``asyncio.Lock`` so later callers do not deadlock behind the orphaned one — and
that swap is precisely what removes the mutual exclusion the lock existed for.
The runaway thread still holds the one shared ``ezdxf.Drawing``, which is
explicitly not thread-safe.
Measured against the unfixed backend, with a runaway ``_sync`` that really
appends LINEs to ``backend._doc``:
* ``entity_create_circle`` after the abandonment returned handle ``A1`` —
full success, no warning.
* ``drawing_info`` reported ``entity_count=116`` for a modelspace observed at
113 -> 118 -> 302 under the same caller, finishing at 310.
* ``drawing_save`` returned ``{"ok": True}`` and wrote a valid DXF holding
15200 of the 60000 entities the abandoned call would go on to write. It reads
back fine. It is a considered document of a state that never existed.
* ``drawing_info`` iterating a container another thread appends to does not
tear loudly — it ran unbounded, blew its own 2.0s deadline at 2.03s and
abandoned a SECOND worker with a SECOND orphaned lock. That is why reads are
refused too.
Only the timed-out caller was ever warned. Every later caller was told nothing.
Every runaway helper here is bounded AND sets its ``finished`` Event in a
``finally``: asyncio joins the default ``to_thread`` executor at loop shutdown,
so a still-spinning worker hangs the pytest process rather than failing a test.
"""
from __future__ import annotations
import asyncio
import logging
import threading
import time
import ezdxf
import pytest
import pytest_asyncio
from fastmcp import Client
import config
import server
from backends.ezdxf_backend import EzdxfBackend
from backends.quarantine import DocumentQuarantineError, QuarantineRecord, real_call_name
pytestmark = pytest.mark.asyncio
# ── runaway helpers ─────────────────────────────────────────────────────────
class _Runaway:
"""A ``_sync`` that outlives its deadline, with a guaranteed way to stop it."""
def __init__(self):
self.started = threading.Event()
self.finished = threading.Event()
self.stop = threading.Event()
self.written = 0
def writer(self, backend, *, delay: float = 0.0005, limit: int = 20_000):
"""Really appends LINEs to the shared Drawing, like a real ``_sync`` would.
The existing honesty test used ``time.sleep(2.0)`` as the stand-in,
which touches no document — which is exactly why the race it was
written to cover was never caught.
"""
def _sync():
try:
msp = backend._doc.modelspace()
self.started.set()
while self.written < limit and not self.stop.is_set():
msp.add_line((0, 0), (1, 1))
self.written += 1
time.sleep(delay) # releases the GIL so the event loop runs
finally:
self.finished.set()
return {"ok": True, "written": self.written}
return _sync
def slow_but_complete(self, extra: float = 0.5, result: str = "value nobody received"):
"""A legitimately slow call that finishes cleanly just past the deadline."""
def _sync():
try:
self.started.set()
self.stop.wait(extra)
finally:
self.finished.set()
return result
return _sync
def slow_then_raises(self, extra: float = 0.5):
def _sync():
try:
self.started.set()
self.stop.wait(extra)
raise ValueError("died mid-write")
finally:
self.finished.set()
return _sync
@pytest.fixture
def runaways():
"""Factory for runaway calls; every one is stopped and joined on teardown."""
made: list[_Runaway] = []
def make() -> _Runaway:
r = _Runaway()
made.append(r)
return r
yield make
for r in made:
r.stop.set()
for r in made:
if r.started.is_set():
assert r.finished.wait(15), "a runaway worker outlived its test"
async def _abandon(backend, monkeypatch, func, *, timeout: float = 0.3) -> RuntimeError:
"""Run ``func`` past a short deadline and return the deadline error."""
monkeypatch.setattr(config.settings, "ezdxf_call_timeout", timeout)
with pytest.raises(RuntimeError) as excinfo:
await backend._async(func)
monkeypatch.setattr(config.settings, "ezdxf_call_timeout", 30)
return excinfo.value
# ── the quarantine ──────────────────────────────────────────────────────────
async def test_a_timed_out_write_quarantines_the_document(backend, monkeypatch, runaways):
"""RED: this returned handle 'A1' off a modelspace another thread was growing."""
r = runaways()
await _abandon(backend, monkeypatch, r.writer(backend))
assert r.started.is_set()
with pytest.raises(DocumentQuarantineError) as refusal:
await backend.entity_create_circle(0, 0, 5)
payload = refusal.value.to_dict()
assert payload["ok"] is False
assert payload["kind"] == "quarantined"
assert payload["quarantine"]["call"] == "writer"
assert payload["quarantine"]["thread_alive"] is True
assert "drawing_open" in payload["error"], "a refusal that names no way out is not help"
assert r.written > 0, "the abandoned thread really was mutating the document"
async def test_reads_are_refused_too(backend, monkeypatch, runaways):
"""RED: drawing_info reported entity_count=116 for a space at 302 and climbing."""
r = runaways()
await _abandon(backend, monkeypatch, r.writer(backend))
with pytest.raises(DocumentQuarantineError):
await backend.drawing_info()
with pytest.raises(DocumentQuarantineError):
await backend.entity_list()
with pytest.raises(DocumentQuarantineError):
await backend.analysis_stats()
async def test_a_read_does_not_cascade_a_second_abandonment(backend, monkeypatch, runaways, caplog):
"""RED: a read on the growing document blew its own deadline and abandoned again.
Measured at 2.03s against a 2.0s deadline, with a second lock swap. Reads on
a container another thread appends to do not tear loudly — they never finish.
"""
r = runaways()
await _abandon(backend, monkeypatch, r.writer(backend))
quarantined_lock = backend._lock
caplog.clear() # the first abandonment is expected; a second one is the defect
with caplog.at_level(logging.ERROR, logger="backends.ezdxf_backend"):
with pytest.raises(DocumentQuarantineError):
await backend.drawing_info()
assert backend._lock is quarantined_lock, "a refusal must not swap the lock again"
assert not [rec for rec in caplog.records if "abandoning the worker" in rec.getMessage()]
assert len(backend._abandoned_calls) == 1
async def test_save_is_refused_while_quarantined(backend, monkeypatch, runaways, tmp_path):
"""RED: this wrote a valid DXF of 15200 of 60000 entities and said {'ok': True}."""
r = runaways()
await _abandon(backend, monkeypatch, r.writer(backend))
target = tmp_path / "torn.dxf"
with pytest.raises(DocumentQuarantineError):
await backend.drawing_save(str(target))
assert not target.exists(), "a refusal must not leave a torn document on disk"
# ── the ways back ───────────────────────────────────────────────────────────
async def test_drawing_open_is_the_way_back(backend, monkeypatch, runaways, tmp_path):
good = tmp_path / "known_good.dxf"
doc = ezdxf.new("R2010")
for i in range(7):
doc.modelspace().add_line((0, i), (1, i))
doc.saveas(str(good))
r = runaways()
await _abandon(backend, monkeypatch, r.writer(backend))
# Reopen WHILE the runaway is still writing: that is the whole point.
assert not r.finished.is_set()
result = await backend.drawing_open(str(good))
assert result["ok"] is True
assert result["quarantine_cleared"]["call"] == "writer"
assert backend._quarantine is None
written_before = r.written
info = await backend.drawing_info()
assert info.entity_count == 7
# Let the runaway write more, then prove none of it landed here.
while r.written < written_before + 20 and not r.finished.is_set():
await asyncio.sleep(0.01)
assert (await backend.drawing_info()).entity_count == 7
assert (await backend.entity_create_circle(0, 0, 5)).handle
async def test_drawing_new_and_drawing_close_also_clear_it(backend, monkeypatch, runaways):
first = runaways()
await _abandon(backend, monkeypatch, first.writer(backend))
assert (await backend.drawing_new())["quarantine_cleared"]["call"] == "writer"
assert backend._quarantine is None
assert (await backend.entity_create_line(0, 0, 1, 1)).handle
second = runaways()
await _abandon(backend, monkeypatch, second.writer(backend))
closed = await backend.drawing_close(save=True)
assert closed["ok"] is True
assert closed["saved"] is False, "a quarantined document must not be saved on the way out"
assert backend._quarantine is None
await backend.drawing_new()
assert (await backend.entity_create_line(0, 0, 1, 1)).handle
async def test_undo_and_rollback_are_not_a_way_back(backend, monkeypatch, runaways):
"""They rebind ``self._doc`` too, but from a snapshot that may itself be torn.
``_snapshot_doc`` does ``self._doc.saveas(tmp)`` on the LIVE document, so any
snapshot pushed during the runaway window was serialised mid-mutation.
"""
monkeypatch.setattr(config.settings, "ezdxf_undo_depth", 5)
r = runaways()
await _abandon(backend, monkeypatch, r.writer(backend))
with pytest.raises(DocumentQuarantineError):
await backend.drawing_undo()
with pytest.raises(DocumentQuarantineError):
await backend.drawing_redo()
with pytest.raises(DocumentQuarantineError):
await backend.transaction_rollback()
assert backend._quarantine is not None
# ── the free exit ───────────────────────────────────────────────────────────
async def test_a_slow_but_complete_call_lifts_the_quarantine(backend, monkeypatch, runaways):
"""The common real trigger is a slow drawing_audit, not a hang.
If the ``_sync`` body ran to completion the document holds exactly the state
that call intended — and everybody else was refused in the meantime, which
is the only reason that inference is sound.
"""
r = runaways()
await _abandon(backend, monkeypatch, r.slow_but_complete(0.5))
assert backend._quarantine is not None
assert r.finished.wait(5)
circle = await backend.entity_create_circle(0, 0, 5)
assert circle.handle, "no reopen should be needed for a call that simply ran long"
status = await backend.system_status()
assert status["quarantine"] is None
(record,) = status["abandoned_calls"]
assert record["outcome"] == "completed_after_deadline"
assert record["result_lost"] is True, "the caller never received the return value"
assert "value nobody received" in record["lost_return_value"]
async def test_a_call_that_raises_after_the_deadline_stays_quarantined(
backend, monkeypatch, runaways
):
r = runaways()
await _abandon(backend, monkeypatch, r.slow_then_raises(0.5))
assert r.finished.wait(5)
with pytest.raises(DocumentQuarantineError):
await backend.entity_create_circle(0, 0, 5)
status = await backend.system_status()
assert status["quarantine"]["outcome"] == "failed_after_deadline"
assert "died mid-write" in status["quarantine"]["detail"]
# ── the diagnostic channel ──────────────────────────────────────────────────
async def test_system_status_reports_the_quarantine_and_is_never_itself_refused(
backend, monkeypatch, runaways
):
"""Otherwise the quarantine's first act is to close the only way to ask why."""
r = runaways()
await _abandon(backend, monkeypatch, r.writer(backend))
status = await backend.system_status()
record = status["quarantine"]
assert record["call"] == "writer"
assert record["timeout"] == pytest.approx(0.3)
assert record["age_seconds"] >= 0
assert record["thread_alive"] is True
assert record["outcome"] == "running"
# ── the message ─────────────────────────────────────────────────────────────
async def test_the_timeout_message_names_the_real_call(backend, monkeypatch, runaways, tmp_path):
"""RED: every real backend method passes a closure literally named ``_sync``.
Measured: ``__name__='_sync'``, ``__qualname__='EzdxfBackend.drawing_save.
<locals>._sync'`` — so in production the error always read
``ezdxf call '_sync' timed out``. The qualname carries the name the user
typed and it was being discarded.
"""
r = runaways()
def _slow_saveas(path, *args, **kwargs):
r.started.set()
try:
r.stop.wait(5)
finally:
r.finished.set()
monkeypatch.setattr(backend._doc, "saveas", _slow_saveas)
monkeypatch.setattr(config.settings, "ezdxf_call_timeout", 0.3)
with pytest.raises(RuntimeError) as excinfo:
await backend.drawing_save(str(tmp_path / "part.dxf"))
message = str(excinfo.value)
assert "drawing_save" in message
assert "_sync" not in message
assert "drawing_open" in message, "the message must name the way back"
assert backend._quarantine.call == "drawing_save"
async def test_real_call_name_falls_back_when_there_is_no_enclosing_method():
assert real_call_name(len) == "len"
assert real_call_name(object()) == "call"
# ── it is not a capability refusal ──────────────────────────────────────────
async def test_the_refusal_is_not_reported_as_a_capability():
"""``_batch_capability_of`` classifies structurally, so a borrowed
``.capability`` here would tell the client the ezdxf engine cannot draw a
circle. The engine is fine; the document is not."""
record = QuarantineRecord("drawing_save", 120.0, _FinishedWatcher())
exc = DocumentQuarantineError(record, "quarantined")
assert not hasattr(exc, "capability")
assert server._batch_capability_of(exc) is None
assert server._classify_batch_error(exc)["kind"] == "quarantined"
class _FinishedWatcher:
finished = True
result = None
error = None
@pytest_asyncio.fixture
async def client(monkeypatch):
monkeypatch.setenv("AUTOCAD_MCP_BACKEND", "ezdxf")
async with Client(server.mcp) as connected:
status = (await connected.call_tool("system_status", {})).structured_content or {}
assert status.get("backend") == "ezdxf", "these tests must never touch live AutoCAD"
await connected.call_tool("drawing_new", {})
yield connected
async def test_the_wire_payload_carries_kind_quarantined(client, monkeypatch):
record = QuarantineRecord("drawing_audit", 120.0, _FinishedWatcher())
async def _refuse(self, *args, **kwargs):
raise DocumentQuarantineError(record, "document quarantined; use drawing_open()")
monkeypatch.setattr(EzdxfBackend, "entity_create_circle", _refuse)
result = await client.call_tool(
"entity_create_circle", {"cx": 0, "cy": 0, "radius": 5}, raise_on_error=False
)
assert result.is_error is True
payload = result.structured_content
assert payload["kind"] == "quarantined"
assert "capability" not in payload
assert payload["quarantine"]["call"] == "drawing_audit"
assert payload["tool"] == "entity_create_circle"
assert payload["backend"] == "ezdxf"
+120
View File
@@ -0,0 +1,120 @@
"""A quarantined document must not be able to pass the quality gate.
`backends/quarantine.py` refuses every call routed through `_async` once a
timed-out write has been abandoned on the document. But `engineering/critique.py`
wraps each check in a bare ``except Exception`` and degrades to ``[]`` — so
`DocumentQuarantineError` was swallowed and `drawing_critique` returned *zero
issues* on a document the backend had declared untrusted.
CLAUDE.md premium rule 7 makes "drawing_critique must return zero issues before
drawing_finalize" the gate an agent is told to trust. A gate that reports clean
because it could not look is worse than no gate: it is the same silent-success
failure the whole quarantine exists to stop, one layer up.
The same swallow sat in `construction_clear` (step 9 of the standard workflow),
which answered ``{"ok": true, "deleted": 0}`` — "there was nothing to clear" —
on a document it could not read.
"""
from __future__ import annotations
import threading
import pytest
import config
from backends.quarantine import DocumentQuarantineError
pytestmark = pytest.mark.asyncio
async def _quarantine(backend, monkeypatch):
"""Abandon a real write, the way a real timeout does.
Hand-building a QuarantineRecord would test the gate against a fixture
rather than against the state the backend actually reaches.
"""
monkeypatch.setattr(config.settings, "ezdxf_call_timeout", 0.2)
entered = threading.Event()
release = threading.Event()
def _writer():
entered.set()
release.wait(5.0)
return "too late"
with pytest.raises(RuntimeError):
await backend._async(_writer)
assert entered.is_set()
assert backend._quarantine is not None
monkeypatch.setattr(config.settings, "ezdxf_call_timeout", 10)
return release
async def test_a_geometric_focus_refuses_rather_than_reporting_clean(backend, monkeypatch):
from engineering.critique import run_critique
await backend.entity_create_line(0, 0, 10, 0, layer="GEOMETRY")
release = await _quarantine(backend, monkeypatch)
try:
with pytest.raises(DocumentQuarantineError):
await run_critique(backend, focus=["duplicate_entities"])
finally:
release.set()
async def test_the_full_critique_refuses_too(backend, monkeypatch):
from engineering.critique import run_critique
release = await _quarantine(backend, monkeypatch)
try:
with pytest.raises(DocumentQuarantineError):
await run_critique(backend, focus=None)
finally:
release.set()
async def test_the_legibility_check_does_not_read_the_document_under_quarantine(
backend, monkeypatch
):
"""It reads `backend._doc` directly, off the event loop thread, with no
lock — the exact unsynchronised access the quarantine exists to prevent."""
from engineering.critique import _check_dimension_legibility
release = await _quarantine(backend, monkeypatch)
try:
with pytest.raises(DocumentQuarantineError):
_check_dimension_legibility(backend)
finally:
release.set()
async def test_construction_clear_does_not_report_nothing_to_clear(backend, monkeypatch):
await backend.entity_create_line(0, 0, 10, 0, layer="CONSTRUCTION")
release = await _quarantine(backend, monkeypatch)
try:
with pytest.raises(DocumentQuarantineError):
await backend.construction_clear()
finally:
release.set()
async def test_an_ordinary_failure_is_still_degraded_not_raised(backend):
"""The bare excepts exist so one broken check cannot fail the whole pass.
Only the quarantine escapes them; everything else keeps degrading.
"""
from engineering.critique import run_critique
async def _boom(*_a, **_k):
raise RuntimeError("layer_list is having a bad day")
backend.layer_list = _boom
issues = await run_critique(backend, focus=["layer_color"])
assert issues == []
+65
View File
@@ -29,6 +29,7 @@ from __future__ import annotations
import ast
import json
import re
import sys
import tomllib
from pathlib import Path
@@ -268,3 +269,67 @@ def test_windows_only_dependencies_carry_a_platform_marker() -> None:
'Windows-only distributions need `; sys_platform == "win32"` or the '
f"extra cannot be installed off Windows: {unmarked}"
)
def test_document_numbers_match_the_tree() -> None:
"""Every figure the docs quote, recomputed from its source of truth.
The A/B suite grew 24 -> 26 and three files kept saying 24: `README.md`
(fixed by hand), `benchmarks/README.md` and `CLAUDE.md` (not). Each was
edited on its own and nobody re-read the other two, so the repository
shipped three different answers to one question. That is a mechanical
failure and it deserves a mechanical gate rather than another careful
reader.
`scripts/check_doc_numbers.py` also fails when a pattern stops matching, so
rewording the sentence around a number cannot silently disarm the check.
"""
import subprocess
completed = subprocess.run(
[sys.executable, str(ROOT / "scripts" / "check_doc_numbers.py")],
capture_output=True,
text=True,
cwd=ROOT,
timeout=120,
)
assert completed.returncode == 0, completed.stdout + completed.stderr
def test_pre_commit_ruff_matches_the_project_pin() -> None:
"""A pre-commit hook that formats differently from CI is a trap, armed.
`.pre-commit-config.yaml` sat at ruff v0.8.6 while `[dependency-groups] dev`
pinned 0.16.1, and 0.16 formats Python inside Markdown where 0.8 does not.
Anyone who ran `pre-commit install` therefore produced commits that failed
CI's own `ruff format --check .` -- the same class of failure the ruff pin
was introduced to end.
"""
config = (ROOT / ".pre-commit-config.yaml").read_text(encoding="utf-8")
hook = re.search(r"ruff-pre-commit\s*\n\s*rev:\s*v?([\d.]+)", config)
assert hook, ".pre-commit-config.yaml no longer pins ruff-pre-commit"
dev_group = _pyproject()["dependency-groups"]["dev"]
pinned = next((d for d in dev_group if d.startswith("ruff==")), None)
assert pinned, "pyproject no longer pins ruff in [dependency-groups] dev"
assert hook.group(1) == pinned.split("==", 1)[1], (
f"pre-commit runs ruff {hook.group(1)} but the project pins {pinned} — "
"a contributor's hook would format differently from CI"
)
def test_the_release_gate_covers_the_platforms_ci_covers() -> None:
"""`release.yml` publishes to PyPI; a lane CI has and it lacks is a hole.
Its test job was one ubuntu/3.11 run, so a Windows-only defect could reach
PyPI with no Windows job having executed. v1.5.0 shipped exactly such a
defect (`except pywintypes.com_error` -> NameError without pywin32).
"""
release = (ROOT / ".github" / "workflows" / "release.yml").read_text(encoding="utf-8")
gate = release.split("build:", 1)[0]
assert "windows-latest" in gate, "the release test gate never runs on Windows"
assert "3.12" in gate, "the release test gate never runs on Python 3.12"
assert "uv sync --locked" in gate, "the release gate must install from the lockfile"
+44
View File
@@ -544,3 +544,47 @@ async def test_the_filter_count_matches_the_handles(backend):
result = await backend.selection_filter(layer="GEOMETRY")
assert result["count"] == len(result["handles"]) == 2
# ── min_area must agree with the measurement tool ───────────────────────────
async def test_min_area_sees_a_hatch_at_the_area_entity_measure_reports(backend):
"""`_area` read `entity.dxf.get("area", 0.0)` for SOLID/TRACE/HATCH.
Those types carry no `area` DXF attribute, so the lookup always fell to the
default and every hatch measured 0.0 — excluded by any positive threshold,
while `filtered_by` asserted the filter had run. Its own docstring says
None means "this shape has no area", not "its area is zero", and the live
COM path reads ActiveX `.Area` correctly, so the two engines returned
different selections for the same call.
"""
hatch = await backend.entity_create_hatch(
"SOLID", [[0, 0], [40, 0], [40, 40], [0, 40]], layer="HATCH"
)
measured = await backend.entity_measure(hatch.handle)
assert measured["area"] == pytest.approx(1600.0)
kept = await backend.selection_filter(entity_type="HATCH", min_area=1.0)
assert kept["handles"] == [hatch.handle], "a 1600 mm^2 hatch must survive a 1 mm^2 threshold"
async def test_min_area_excludes_a_hatch_that_is_genuinely_too_small(backend):
"""The fix must not simply admit everything."""
await backend.entity_create_hatch("SOLID", [[0, 0], [2, 0], [2, 2], [0, 2]], layer="HATCH")
kept = await backend.selection_filter(entity_type="HATCH", min_area=100.0)
assert kept["handles"] == []
async def test_min_area_and_entity_measure_cannot_disagree_on_a_solid(backend):
solid = backend._doc.modelspace().add_solid([(0, 0), (10, 0), (0, 10), (10, 10)])
measured = await backend.entity_measure(solid.dxf.handle)
just_under = await backend.selection_filter(min_area=measured["area"] - 0.5)
just_over = await backend.selection_filter(min_area=measured["area"] + 0.5)
assert solid.dxf.handle in just_under["handles"]
assert solid.dxf.handle not in just_over["handles"]
+71
View File
@@ -0,0 +1,71 @@
"""A setting the renderer cannot use must be refused, not reported applied.
Folding the DIM* header variables into the per-dimension override closed a
silent no-op and opened a louder failure: values that used to die harmlessly in
the header now reach ezdxf's formatter. Measured before this guard existed:
* ``dim_decimals=-1`` returned ``ok: True`` and the *next* dimension of four of
the five kinds died with ``ValueError: Format specifier missing precision``,
from inside the renderer, nowhere near the call that caused it.
* ``dim_decimals=40`` returned ``ok: True`` and printed
``33.3329999999999984083842718973755836486816`` onto the drawing.
* ``dim_text_height=-3.0`` returned ``ok: True`` and changed nothing.
AutoCAD's own ranges are the reference: DIMDEC 0-8, DIMZIN a 0-15 bitmask, and
the two lengths strictly positive. `applied` has to mean applied.
"""
from __future__ import annotations
import pytest
pytestmark = pytest.mark.asyncio
@pytest.mark.parametrize("value", [-1, 9, 40])
async def test_out_of_range_dim_decimals_is_refused(backend, value):
result = await backend.drawing_settings({"dim_decimals": value})
assert result["ok"] is False
assert "dim_decimals" in result["errors"]
assert "dim_decimals" not in result.get("applied", {})
async def test_a_refused_dim_decimals_cannot_break_the_next_dimension(backend):
"""The crash was the point: the bad value reached the formatter."""
await backend.drawing_settings({"dim_decimals": -1})
dim = await backend.dimension_linear(0, 0, 33.333, 0, 16, -30)
assert dim.handle
@pytest.mark.parametrize("value", [0, 2, 8])
async def test_dim_decimals_in_range_is_still_accepted(backend, value):
result = await backend.drawing_settings({"dim_decimals": value})
assert result["ok"] is True, result.get("errors")
@pytest.mark.parametrize("key", ["dim_text_height", "dim_arrow_size"])
@pytest.mark.parametrize("value", [0.0, -3.0])
async def test_a_non_positive_length_is_refused(backend, key, value):
result = await backend.drawing_settings({key: value})
assert result["ok"] is False
assert key in result["errors"]
@pytest.mark.parametrize("value", [-1, 16, 999])
async def test_zero_suppression_outside_the_bitmask_is_refused(backend, value):
result = await backend.drawing_settings({"zero_suppression": value})
assert result["ok"] is False
assert "zero_suppression" in result["errors"]
async def test_one_bad_key_does_not_discard_the_good_ones(backend):
result = await backend.drawing_settings({"dim_text_height": 5.0, "dim_decimals": -1})
assert result["applied"]["dim_text_height"] == 5.0
assert "dim_decimals" in result["errors"]
+87
View File
@@ -0,0 +1,87 @@
"""SendCommand takes a whole macro, so a name interpolated into one is code.
`security.py` recorded the policy as "`sanitize_command` and `sanitize_lisp`
each have exactly ONE caller, both of them the COM-only free-text escape hatch
into SendCommand. The policy is scoped to the CHANNEL." That premise was false.
`_ensure_linetype_loaded` builds ``_-LINETYPE _LOAD {name} {lin_file}`` and
hands it to `doc.SendCommand`, and it is reached from the ``linetype=``
argument of every COM entity-creation and layer tool — plus
`ComBackend.linetype_load`, which interpolates a caller-supplied *file path*
as well. SendCommand treats a newline and ``;`` as segment separators, so a
linetype name carrying either injects further AutoCAD commands, and the 36-verb
denylist and `DANGEROUS_COMMANDS_ENABLED` never see that channel at all.
The guard here is the DXF symbol-name rule rather than a bespoke blocklist:
AutoCAD already forbids these characters in a table name, so anything this
rejects was never a loadable linetype, and the injection characters fall out of
the rule rather than having to be enumerated.
"""
from __future__ import annotations
import pytest
from fastmcp.exceptions import ToolError
from security import sanitize_symbol_name
@pytest.mark.parametrize(
"name",
[
"CENTER",
"HIDDEN2",
"DASHDOT",
"ACAD_ISO02W100",
"My-Linetype_01",
],
)
def test_ordinary_linetype_names_pass(name):
assert sanitize_symbol_name(name, kind="linetype") == name
@pytest.mark.parametrize(
"payload",
[
"CENTER\n_ERASE ALL\n", # newline ends the macro segment
"CENTER;_ERASE ALL", # so does a semicolon
"CENTER\r_QUIT",
'CENTER"',
"CENTER|X",
"CENTER<X",
"CENTER>X",
"CENTER?X",
"CENTER*X",
"CENTER,X",
"CENTER=X",
"CENTER:X",
"CENTER/X",
"CENTER" + chr(92) + "X",
],
)
def test_a_name_that_could_end_the_macro_segment_is_refused(payload):
with pytest.raises(ToolError) as excinfo:
sanitize_symbol_name(payload, kind="linetype")
assert "linetype" in str(excinfo.value).lower()
def test_an_empty_name_is_refused():
with pytest.raises(ToolError):
sanitize_symbol_name(" ", kind="linetype")
def test_the_refusal_does_not_echo_the_payload_back_verbatim():
"""An error message is a channel too."""
with pytest.raises(ToolError) as excinfo:
sanitize_symbol_name("CENTER\n_ERASE ALL\n", kind="linetype")
assert "\n_ERASE" not in str(excinfo.value)
def test_the_com_linetype_loader_refuses_before_it_reaches_sendcommand():
"""The guard has to sit in front of the macro, not inside AutoCAD."""
import backends.com_backend as cb
with pytest.raises(ToolError):
cb._ensure_linetype_loaded("CENTER\n_ERASE ALL\n")