Files
ocp/tests/test_bintools_gate.py
stroblme 6139852768 Phase 10A/10B Inc 0: build system, handle model, first module surface
Builds n3xd-ocp end to end and publishes 7.9.3.1.dev1 to the Gitea registry,
where it installs anonymously and passes its suite.

- occt/Dockerfile: OCCT 7.9.3 compiled once into a manylinux_2_28 builder
  image (base digest + tarball sha256 pinned), Draw/VTK/Tk/Xlib/OpenGL off,
  FreeType on, -O2 without fast-math or march=native. A final layer asserts
  TKService/TKV3d exist with no libGL/libX11 DT_NEEDED, which is what lets the
  app image drop libgl1/libx11-6. Mounted into, never built FROM.
- scikit-build-core + nanobind STABLE_ABI -> one cp312-abi3 extension that
  registers every OCP.* submodule via PyImport_AddModule, so `import
  OCP.TopoDS` needs no shim and cls.__module__ is right. Version <occt>.N is
  asserted against the OCCT found, keeping occt_version() truthful.
- occt_handle.h: type caster for opencascade::handle<T> over OCCT's intrusive
  refcount. Wrappers are non-owning instances holding exactly one handle in
  their keep-alive list, reusing an existing wrapper so identity survives a
  round trip. Transient constructors go through ocp_new (never nb::init<>,
  which would let OCCT delete nanobind's storage); the caster refuses a
  refcount-0 object rather than corrupt the heap. Verified under ASAN with no
  memory-safety errors, plus an RSS bound over 50k create/destroy cycles.
- Sub-shapes are returned by value everywhere, making the TShape lifetime class
  that segfaulted a process-global face memo unrepresentable.
- Standard_Failure derives RuntimeError, with ~20 concrete types dispatched on
  the dynamic OCCT type (cad_pool marshals failures home by type name).
- Inc 0 surface: gp subset, TopAbs, TopoDS (+ downcasts), TopExp, TopLoc,
  TopTools, BRep, BinTools, Poly, Standard. 34 of the app's 139 symbols.
- n3xd_ocp: additive APIs kept out of the OCP namespace so parity testing stays
  meaningful. bintools (shape <-> bytes, GIL-free, byte-identical) and _debug.

Two findings worth the record, both verified against the stock wheel rather
than assumed: upstream binds __hash__ but leaves __eq__ at identity, which is
exactly what geom_memo.py's hash-bucket + IsSame scan is built around, so we
match it instead of "fixing" it; and BinTools can release the GIL after all, by
slurping the file-like object instead of bridging a streambuf that would call
back into Python.

Gate: BREP round-trips are byte-identical to cadquery-ocp-novtk across six
fixtures (the generator asserts stock idempotency first). That matters beyond
IPC — derive.py content-addresses BREP payloads by sha256 and stores the ref.
2026-08-10 16:10:28 +02:00

87 lines
3.2 KiB
Python

"""The Inc 0 exit gate: BREP serialisation is byte-identical to the stock wheel.
Every subprocess pool moves shapes as BinTools bytes, so this is the IPC
contract. It is also a storage contract: cad/derive.py content-addresses BREP
payloads (payloads/derived/brep/<sha256>.brep) and stores the ref inside the
document, so bytes that differ would silently rewrite every derived payload.
The comparison is our-rewrite vs stock-rewrite. tools/gen_fixtures.py already
proved stock is idempotent for each fixture, which is what makes the stored
digest a fixed reference rather than one arbitrary encoding of many.
"""
from __future__ import annotations
import hashlib
import io
import pytest
from OCP.BinTools import BinTools
from OCP.TopAbs import TopAbs_FACE
from OCP.TopExp import TopExp
from OCP.TopoDS import TopoDS_Shape
from OCP.TopTools import TopTools_IndexedMapOfShape
from .conftest import DATA
def _rewrite(data: bytes) -> bytes:
shape = TopoDS_Shape()
BinTools.Read_s(shape, io.BytesIO(data))
out = io.BytesIO()
BinTools.Write_s(shape, out)
return out.getvalue()
def test_roundtrip_is_byte_identical(manifest):
for name, expected in manifest["shapes"].items():
original = (DATA / f"{name}.brep").read_bytes()
assert hashlib.sha256(original).hexdigest() == expected["sha256"], (
f"{name}.brep does not match the manifest — regenerate fixtures"
)
assert hashlib.sha256(_rewrite(original)).hexdigest() == expected["sha256"], (
f"{name}: rewritten bytes differ from the stock wheel's"
)
def test_face_map_ordering_survives_the_roundtrip(manifest, fixture_shapes):
# Face identity throughout the topology code is the map ordinal, so a
# round trip that renumbered faces would silently retarget every anchor.
for name, shape in fixture_shapes.items():
faces = TopTools_IndexedMapOfShape()
TopExp.MapShapes_s(shape, TopAbs_FACE, faces)
assert faces.Extent() == manifest["shapes"][name]["faces"], name
def test_empty_compound_survives():
shape = TopoDS_Shape()
BinTools.Read_s(shape, io.BytesIO((DATA / "empty_compound.brep").read_bytes()))
assert not shape.IsNull()
def test_extension_bytes_api_matches_the_drop_in(fixture_shapes):
# n3xd_ocp.bintools exists to skip the BytesIO detour on the pool paths; it
# is only usable there if it produces the very same bytes.
from n3xd_ocp import bintools
for name, shape in fixture_shapes.items():
buf = io.BytesIO()
BinTools.Write_s(shape, buf)
assert bintools.write_bytes(shape) == buf.getvalue(), name
restored = bintools.read_bytes(buf.getvalue())
assert bintools.write_bytes(restored) == buf.getvalue(), name
@pytest.mark.parametrize("name", ["box", "fused"])
def test_write_appends_to_the_stream_position(name):
# BinTools.Write_s writes through a file-like object; a caller that already
# wrote a header must still find its bytes intact.
shape = TopoDS_Shape()
BinTools.Read_s(shape, io.BytesIO((DATA / f"{name}.brep").read_bytes()))
buf = io.BytesIO()
buf.write(b"HEADER")
BinTools.Write_s(shape, buf)
assert buf.getvalue().startswith(b"HEADER")