Skip to content

armgit / moss

Public Imported from GitHub
0

MOSS: a small, mostly 3D-printed litter-picking rover. Cleaner streets, one maker at a time.

Python

lidar odometry: absorb the first registration failure; cockpit unit stack limit; bench fix

metrox62c1b136c5d4
diff --git a/benches/bench_lidar_odometry_cold.py b/benches/bench_lidar_odometry_cold.py
index c26edcb..d11a9e0 100644
--- a/benches/bench_lidar_odometry_cold.py
+++ b/benches/bench_lidar_odometry_cold.py
@@ -95,9 +95,19 @@ class LocalMap:
class Registration:
+ """The registration "finds" exactly the prediction: the published pose is
+ then the prior the bench commanded. `fail_first` makes the next N calls
+ raise the board's thread-pool error, as the real one does once at start."""
+
+ def __init__(self):
+ self.calls = 0
+ self.fail_first = 0
+
def align_points_to_map(self, points, voxel_map, initial_guess, max_correspondance_distance, kernel):
- # the registration "finds" exactly the prediction: the published pose
- # is then the prior the bench commanded
+ self.calls += 1
+ if self.fail_first > 0:
+ self.fail_first -= 1
+ raise RuntimeError("pthread_create has failed: Invalid argument")
return np.asarray(initial_guess)
@@ -354,6 +364,35 @@ for m in REAL:
gc.collect()
print()
+print("F. the first registration call fails once (thread pool start-up): absorbed, never a lost run")
+reg_fail = Registration(); reg_fail.fail_first = 1
+kiss6 = Kiss(); kiss6.registration = reg_fail
+_kiss_mod.KissICP = lambda cfg: kiss6
+o6 = LO.LidarOdometry(use_gyro_prior=False)
+try:
+ o6.log_every_s = 1e9
+ o6.odom, o6.lidar, o6.tf, o6.camera_floor = Sink(), Sink(), Sink(), Sink()
+ _ms = LO.Module.start
+ LO.Module.start = lambda self: None # the dimOS runtime is not under test here
+ try:
+ o6.start()
+ finally:
+ LO.Module.start = _ms
+ check(o6._kiss is kiss6 and reg_fail.calls == 2, f"start(): the warm-up failed once and was retried ({reg_fail.calls} registration calls)")
+ check(kiss6.local_map.updates == 0, "the warm-up touched no map")
+ _a = np.linspace(0.0, 2.0 * math.pi, 64, endpoint=False)
+ ring6 = np.stack([2.0 * np.cos(_a), 2.0 * np.sin(_a), np.zeros_like(_a)], 1)
+ reg_fail.fail_first = 1
+ drive(o6, 1, ring6)
+ check(len(o6.odom.msgs) == 1 and reg_fail.calls == 4, f"a scan whose first registration fails is retried and published ({len(o6.odom.msgs)} odom, {reg_fail.calls} calls)")
+ reg_fail.fail_first = 2
+ drive(o6, 1, ring6)
+ check(len(o6.odom.msgs) == 1 and o6._dropped == 1, f"two failures in a row: the revolution is dropped, nothing escapes (dropped {o6._dropped})")
+ drive(o6, 1, ring6)
+ check(len(o6.odom.msgs) == 2, "the next revolution publishes again")
+finally:
+ _kiss_mod.KissICP = lambda cfg: Kiss(cfg=cfg)
+
print(f"{OK} OK, {KO} KO")
print("TEST PASSED" if KO == 0 else "TEST FAILED")
sys.exit(1 if KO else 0)
diff --git a/benches/bench_moss_fly_gates_cold.py b/benches/bench_moss_fly_gates_cold.py
index 8147ccd..c6f7519 100644
--- a/benches/bench_moss_fly_gates_cold.py
+++ b/benches/bench_moss_fly_gates_cold.py
@@ -673,8 +673,11 @@ if shutil.which("systemd-analyze"):
cwd=ud, capture_output=True, text=True, timeout=60)
(ud / "broken.service").write_text(lb.read_text().replace("Type=oneshot", "Type=oneshoot"))
vb = subprocess.run(["systemd-analyze", "verify", "./broken.service"], cwd=ud, capture_output=True, text=True, timeout=60)
+ # only lines about OUR units count: systemd-analyze also warns about unrelated
+ # system units it loads (a newer key in an older systemd, for example)
+ ours = [l for l in (va.stderr + va.stdout).split("\n") if "lcm-loopback.service" in l or "moss-cockpit.service" in l]
check("systemd-analyze verify: both units (the cockpit filled by the install sed) pass",
- va.returncode == 0 and not va.stderr.strip(), " / ".join((va.stderr or va.stdout).split("\n"))[:200])
+ va.returncode == 0 and not ours, " / ".join(ours)[:200])
check("... control: the same check refuses a broken copy", vb.returncode != 0,
" / ".join((vb.stderr or "").strip().split("\n"))[-120:])
else:
diff --git a/moss_dimos/lidar_odometry.py b/moss_dimos/lidar_odometry.py
index d8d3226..53e129b 100644
--- a/moss_dimos/lidar_odometry.py
+++ b/moss_dimos/lidar_odometry.py
@@ -146,6 +146,7 @@ class LidarOdometry(Module):
# dimOS pickles module instances into their worker: no lock, no native
# object before start().
self._kiss: Any = None
+ self._dropped = 0 # revolutions lost to a registration that failed twice
self._lock: Any = None
self._n = 0
self._last_log = 0.0
@@ -181,6 +182,7 @@ class LidarOdometry(Module):
cfg.adaptive_threshold.min_motion_th = 0.02
self._kiss = KissICP(cfg)
self._lock = threading.Lock()
+ self._warm_up()
logger.info(f"lidar odometry up (kiss-icp, voxel {self.voxel_size_m} m, range "
f"{self.min_range_m}-{self.max_range_m} m, prior: gyro={self.use_gyro_prior} "
f"axis {self.gyro_axis}, wheels NEVER) -> {self.world_frame}")
@@ -189,6 +191,39 @@ class LidarOdometry(Module):
def stop(self) -> None:
super().stop()
+ # ── registration, with the first-call failure absorbed ──────────────
+ def _warm_up(self) -> None:
+ """One registration on a synthetic ring before the first scan. On this
+ board the first call into kiss-icp's registration can fail once with
+ 'pthread_create has failed: Invalid argument' (its thread pool starting
+ up); the next call works. Taking that failure here keeps the first real
+ revolution and keeps the error out of the run log. The map is not
+ touched (registration only)."""
+ k = self._kiss
+ ang = np.linspace(0.0, 2.0 * math.pi, 64, endpoint=False)
+ ring = np.stack([2.0 * np.cos(ang), 2.0 * np.sin(ang), np.zeros_like(ang)], 1)
+ try:
+ source, _ = k.voxelize(ring)
+ sigma = k.adaptive_threshold.get_threshold()
+ self._register(k, source, np.eye(4), sigma, where="warm-up")
+ except Exception as exc: # noqa: BLE001 - a warm-up never stops the module
+ logger.warning(f"lidar odometry: registration warm-up skipped ({type(exc).__name__}: {exc})")
+
+ @staticmethod
+ def _register(k, source, initial_guess, sigma, where: str = "scan"):
+ """align_points_to_map with ONE retry: a RuntimeError from the first
+ attempt (thread pool start-up) is logged and the call repeated; a second
+ failure propagates to the caller, which drops that revolution."""
+ try:
+ return k.registration.align_points_to_map(
+ points=source, voxel_map=k.local_map, initial_guess=initial_guess,
+ max_correspondance_distance=3 * sigma, kernel=sigma)
+ except RuntimeError as exc:
+ logger.warning(f"lidar odometry: registration failed once at {where} ({exc}) - retrying")
+ return k.registration.align_points_to_map(
+ points=source, voxel_map=k.local_map, initial_guess=initial_guess,
+ max_correspondance_distance=3 * sigma, kernel=sigma)
+
# ── priors ─────────────────────────────────────────────────────────
async def handle_imu(self, msg: Imu) -> None:
w = msg.angular_velocity
@@ -329,9 +364,13 @@ class LidarOdometry(Module):
source, frame_down = k.voxelize(frame)
sigma = k.adaptive_threshold.get_threshold()
initial_guess = np.asarray(k.last_pose) @ prior
- new_pose = k.registration.align_points_to_map(
- points=source, voxel_map=k.local_map, initial_guess=initial_guess,
- max_correspondance_distance=3 * sigma, kernel=sigma)
+ try:
+ new_pose = self._register(k, source, initial_guess, sigma)
+ except RuntimeError as exc:
+ self._dropped += 1
+ logger.warning(f"lidar odometry: registration failed twice, revolution dropped ({exc}); "
+ f"dropped so far: {self._dropped}")
+ return
corr = np.linalg.inv(initial_guess) @ np.asarray(new_pose)
k.adaptive_threshold.update_model_deviation(corr)
k.local_map.update(frame_down, new_pose)
diff --git a/tools/moss-cockpit.service b/tools/moss-cockpit.service
index 97af50b..59ac4bd 100644
--- a/tools/moss-cockpit.service
+++ b/tools/moss-cockpit.service
@@ -31,6 +31,10 @@ RestartSec=3
# in this unit's cgroup: a cockpit restart, crash or stop must end the cockpit
# only, never a flight it started. Stop a flight with tools/moss-fly.sh stop.
KillMode=process
+# The same stack limit as a login shell (8 MB). A stack launched from the page inherits
+# this unit's limits; with an unlimited stack, thread pools size their stacks from it and
+# thread creation can fail with EINVAL.
+LimitSTACK=8M
[Install]
WantedBy=multi-user.target