world_atlas_accel: validate inputs, contiguous packed_cells, and native output bounds/finiteness

This commit is contained in:
IlyassRS
2026-11-25 09:17:15 +01:00
parent 3f81d46ac0
commit f5ef8d0dfa
2 changed files with 71 additions and 5 deletions

View File

@ -81,6 +81,59 @@ class FallbackTest(unittest.TestCase):
self.assertEqual(run(self.inputs, True), self.expected)
load.return_value.assert_called_once()
def test_malformed_inputs_fall_back_before_loading_native(self):
cells = np.zeros((4, 3, 3), dtype=np.int32)
tiles = np.zeros((1, 3, 3), dtype=np.int32)
good_order = [0, 1, 2, 3]
bad_calls = [
("nan_margin", tiles, cells, good_order, float("nan")),
("inf_margin", tiles, cells, good_order, float("inf")),
("bool_margin", tiles, cells, good_order, True),
("short_order", tiles, cells, [0, 1], 0.1),
("oob_order", tiles, cells, [0, 1, 2, 99], 0.1),
("neg_order", tiles, cells, [-1, 0, 1, 2], 0.1),
("bool_order", tiles, cells, [True, 0, 1, 2], 0.1),
]
with mock.patch.dict(os.environ, {"LEONIDA_WORLD_ATLAS_NATIVE": "1"}), \
mock.patch.object(accel, "_load", side_effect=AssertionError("must not load")):
for label, t, c, order, margin in bad_calls:
with self.subTest(case=label):
self.assertIsNone(accel.match(np, t, c, order, margin))
def test_corrupt_native_outputs_fall_back_safely(self):
cells = np.zeros((4, 3, 3), dtype=np.int32)
tiles = np.zeros((1, 3, 3), dtype=np.int32)
order = [0, 1, 2, 3]
corrupt_rows = [
("oob_clear", 4, 0, 0.5),
("oob_placed", -1, 4, 0.5),
("neg_clear", -2, 0, 0.5),
("neg_placed", -1, -2, 0.5),
("nan_overlap", -1, 0, float("nan")),
("inf_overlap", -1, 0, float("inf")),
]
for label, clear_idx, placed_idx, overlap in corrupt_rows:
with self.subTest(case=label):
def bad_kernel(_t, _tl, _c, _cl, _w, _m, out, _ol, cl=clear_idx, pl=placed_idx, ov=overlap):
out[0].clear = cl
out[0].placed = pl
out[0].overlap = ov
return 0
with mock.patch.dict(os.environ, {"LEONIDA_WORLD_ATLAS_NATIVE": "1"}), \
mock.patch.object(accel, "_load", return_value=bad_kernel):
self.assertIsNone(accel.match(np, tiles, cells, order, 0.1))
# End-to-end match_mask falls back to Python reference when native emits an OOB index.
def oob_kernel(_t, _tl, _c, _cl, _w, _m, out, _ol):
out[0].clear = 999
out[0].placed = 0
out[0].overlap = 0.5
return 0
with mock.patch.object(accel, "_load", return_value=oob_kernel):
self.assertEqual(run(self.inputs, True), self.expected)
@unittest.skipIf(np is None, "NumPy is required")
class NativeTest(unittest.TestCase):

View File

@ -2,6 +2,7 @@
import ctypes
from functools import lru_cache
import math
import os
from pathlib import Path
import sys
@ -42,18 +43,25 @@ def match(np, tiles, cells, order, margin):
The native kernel sees cells in text order. A tied best overlap cannot
be a clear anchor, so the reordering does not affect anchor selection.
"""
if (os.environ.get("LEONIDA_WORLD_ATLAS_NATIVE") == "0" or tiles.ndim != 3 or not tiles.size
or not len(cells) or tiles.shape[1:] != cells.shape[1:]):
if (os.environ.get("LEONIDA_WORLD_ATLAS_NATIVE") == "0" or tiles.ndim != 3 or cells.ndim != 3
or not tiles.size or not len(cells) or tiles.shape[1:] != cells.shape[1:]):
return None
if isinstance(margin, bool) or not isinstance(margin, (int, float)) or not math.isfinite(margin):
return None
n_cells = len(cells)
if len(order) != n_cells or any(
isinstance(idx, bool) or not isinstance(idx, (int, np.integer)) or idx < 0 or idx >= n_cells
for idx in order):
return None
kernel = _load()
if kernel is None:
return None
words = (tiles.shape[1] * tiles.shape[2] + 63) // 64
if (words > 4096 or max(len(tiles), len(cells)) * words > 8 * 1024**2
or len(tiles) * len(cells) > 8 * 1024**2):
if (words > 4096 or max(len(tiles), n_cells) * words > 8 * 1024**2
or len(tiles) * n_cells > 8 * 1024**2):
return None
packed_tiles = _pack(np, tiles)
packed_cells = _pack(np, cells)[order]
packed_cells = np.require(_pack(np, cells)[order], requirements=("C", "A"))
out = (_Match * len(tiles))()
try:
status = kernel(packed_tiles.ctypes.data, packed_tiles.size, packed_cells.ctypes.data,
@ -62,6 +70,11 @@ def match(np, tiles, cells, order, margin):
return None
if status != 0:
return None
for row in out:
if row.clear < -1 or row.clear >= n_cells or row.placed < -1 or row.placed >= n_cells:
return None
if row.placed >= 0 and not math.isfinite(row.overlap):
return None
clear = {i: order[row.clear] for i, row in enumerate(out) if row.clear >= 0}
placed = {i: order[row.placed] for i, row in enumerate(out) if row.placed >= 0}
scores = sorted(row.overlap for row in out if row.placed >= 0)