feat(Point-LIO): 默认关闭的滤波器更新链跟踪

回答两个只能靠证据而不是推断的问题:信息形式分支是否被选中过、
哪类更新贡献了主要位置变化。

运行时性质:
- 关闭时只做一次 relaxed atomic load 即返回:不格式化、不写盘、不建目录。
- 生产者不阻塞:对预分配环形缓冲做 try-lock,抢不到或满了就计数丢弃。
- 记账闭合:关机后 attempted == written + dropped。
- 写失败只关闭跟踪,滤波器继续跑,且只告知调用方一次。

新参数 runtime_update_trace_enable 默认 false。
This commit is contained in:
walunt5
2026-11-05 11:58:42 +08:00
parent d9eb7a6ea3
commit 5a67417fbe
4 changed files with 976 additions and 1 deletions
@@ -0,0 +1,522 @@
// Tests for runtime_update_trace.h.
//
// Built with the same flags as the production translation unit (see
// extract_flags.py), so the real header and the real record helpers are used.
//
// 1. disabled: no directory, no file, no counters
// 2. enabled: CSV header, every field, round-trip precision on real epoch times
// 3. bounded queue: overflow counted, accounting closes
// 4. producer does not wait when the writer holds the lock
// 5. publish velocity is converted body -> world with a nonzero yaw
// 6. unopenable destination: initialize fails, filter still correct
// 7. wrapping an esekf update in trace calls is bit-identical
// 8. mid-write failure in a size-limited child process: accounting closes,
// output reported incomplete, no partial claims of success
#include <common_lib.h>
#include <runtime_update_trace.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <unistd.h>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
Eigen::Matrix<double, 30, 1> process_dummy_state(state_output &, const input_ikfom &);
Eigen::Matrix<double, 30, 30> process_jacobian_dummy_state(state_output &, const input_ikfom &);
namespace {
int g_failures = 0;
void check(bool condition, const char * what)
{
if (!condition) {
std::printf(" FAIL: %s\n", what);
++g_failures;
}
}
std::vector<std::string> split(const std::string & line)
{
std::vector<std::string> out;
std::stringstream ss(line);
std::string item;
while (std::getline(ss, item, ',')) {
out.push_back(item);
}
return out;
}
std::vector<std::vector<std::string>> read_csv(const std::filesystem::path & path)
{
std::vector<std::vector<std::string>> rows;
std::ifstream in(path);
std::string line;
while (std::getline(in, line)) {
if (!line.empty()) {
rows.push_back(split(line));
}
}
return rows;
}
point_lio::RuntimeUpdateTrace::Record make_record(int event)
{
point_lio::RuntimeUpdateTrace::Record r;
r.event = event;
r.scan_id = 7;
r.batch_id = 3;
r.t_before = 1793688042.795865774;
r.t_after = 1793688042.806857109;
r.dt = 0.010991335;
r.ok = 1;
r.pos_before[0] = 1.5;
r.pos_before[1] = -2.5;
r.pos_before[2] = 0.125;
r.pos_after[0] = 1.75;
r.pos_after[1] = -2.25;
r.pos_after[2] = 0.25;
r.vel_before[0] = 0.5;
r.vel_before[1] = 0.0;
r.vel_before[2] = -0.5;
r.vel_after[0] = 0.75;
r.vel_after[1] = 0.25;
r.vel_after[2] = -0.75;
r.state_dof = 30;
r.effective_m = 12;
r.branch = 1;
r.predict_state = 1;
r.prop_cov = 0;
return r;
}
void test_disabled_writes_nothing(const std::filesystem::path & root)
{
std::printf("[1] disabled\n");
const std::filesystem::path dir = root / "disabled";
point_lio::RuntimeUpdateTrace trace;
check(trace.initialize(false, dir), "initialize(false) reports success");
check(!trace.enabled(), "trace stays disabled");
for (int i = 0; i < 500; ++i) {
trace.record(make_record(point_lio::RuntimeUpdateTrace::kPredict));
}
trace.shutdown();
check(trace.attempted() == 0, "nothing attempted");
check(trace.written() == 0, "nothing written");
check(!std::filesystem::exists(dir), "disabled trace creates no directory");
}
void test_fields_and_precision(const std::filesystem::path & root)
{
std::printf("[2] enabled: header, fields, precision\n");
const std::filesystem::path dir = root / "fields";
point_lio::RuntimeUpdateTrace trace;
check(trace.initialize(true, dir), "initialize(true) succeeds");
check(trace.enabled(), "trace enabled");
auto predict = make_record(point_lio::RuntimeUpdateTrace::kPredict);
// Positions one nanometre apart must survive the round trip.
predict.pos_after[0] = 0.123456789123;
predict.pos_before[0] = 0.123456799123;
trace.record(predict);
auto lidar = make_record(point_lio::RuntimeUpdateTrace::kLidarUpdate);
lidar.dt = 0.0;
lidar.effective_m = 45;
lidar.branch = 1;
lidar.predict_state = -1;
lidar.prop_cov = -1;
trace.record(lidar);
auto publish = make_record(point_lio::RuntimeUpdateTrace::kPublish);
publish.batch_id = 9;
trace.record(publish);
trace.flush();
trace.shutdown();
const auto rows = read_csv(dir / "runtime_update_trace.csv");
check(rows.size() == 4, "header plus three records");
if (rows.size() != 4) {
return;
}
const auto & header = rows[0];
check(header.size() == 27, "27 columns");
const auto & row = rows[1];
check(row[0] == "2", "trace_version 2");
check(row[1] == "1", "sequence starts at 1");
check(row[4] == "predict", "event name");
check(row[21] == "world", "frame is world");
check(row[22] == "30", "state_dof");
check(row[23] == "12", "effective_m");
check(row[24] == "1", "branch = information form");
// Round-trip precision: epoch doubles 10.991335 ms apart must stay distinct,
// and a 1e-8 position difference must survive.
const double t_before = std::stod(row[5]);
const double t_after = std::stod(row[6]);
const double gap = t_after - t_before;
std::printf(" epoch gap recovered: %.9f s\n", gap);
check(std::fabs(gap - 0.010991335) < 1e-7, "epoch time gap preserved");
const double x_before = std::stod(row[9]);
const double x_after = std::stod(row[12]);
std::printf(" pos gap recovered: %.12f m\n", x_after - x_before);
check(std::fabs((x_after - x_before) - (-1.0e-8)) < 1e-13,
"1e-8 position difference preserved");
const auto & lidar_row = rows[2];
check(lidar_row[4] == "lidar_update", "second row is lidar_update");
check(lidar_row[23] == "45", "effective_m carried through");
check(lidar_row[25] == "-1", "not-applicable marker");
}
void test_bounded_queue(const std::filesystem::path & root)
{
std::printf("[3] bounded queue\n");
const std::filesystem::path dir = root / "bounded";
point_lio::RuntimeUpdateTrace trace;
trace.set_capacity(2);
check(trace.initialize(true, dir), "initialize succeeds");
const int total = 20000;
for (int i = 0; i < total; ++i) {
trace.record(make_record(point_lio::RuntimeUpdateTrace::kPredict));
}
trace.shutdown();
std::printf(" attempted=%llu written=%llu dropped=%llu (full=%llu contended=%llu)\n",
static_cast<unsigned long long>(trace.attempted()),
static_cast<unsigned long long>(trace.written()),
static_cast<unsigned long long>(trace.dropped()),
static_cast<unsigned long long>(trace.full_drops()),
static_cast<unsigned long long>(trace.contended_drops()));
check(trace.dropped() > 0, "capacity-2 queue with 20k records drops some");
check(trace.full_drops() > 0, "overflow drops are attributed to the full queue");
check(trace.attempted() <= static_cast<uint64_t>(total),
"attempted never exceeds the call count");
check(trace.written() + trace.dropped() == trace.attempted(),
"written + dropped accounts for every accepted record");
}
void test_producer_does_not_wait(const std::filesystem::path & root)
{
std::printf("[4] producer does not wait\n");
const std::filesystem::path dir = root / "nonblocking";
point_lio::RuntimeUpdateTrace trace;
trace.set_capacity(64);
check(trace.initialize(true, dir), "initialize succeeds");
std::thread holder([&trace] {
trace.debug_hold_lock_for(std::chrono::milliseconds(400));
});
std::this_thread::sleep_for(std::chrono::milliseconds(50));
const auto start = std::chrono::steady_clock::now();
for (int i = 0; i < 200; ++i) {
trace.record(make_record(point_lio::RuntimeUpdateTrace::kPredict));
}
const auto elapsed_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - start).count();
holder.join();
std::printf(" 200 records while lock held took %lld ms, contended drops=%llu\n",
static_cast<long long>(elapsed_ms),
static_cast<unsigned long long>(trace.contended_drops()));
check(elapsed_ms < 100, "record() returned without waiting for the lock");
check(trace.contended_drops() > 0, "contention is counted, not hidden");
trace.shutdown();
check(trace.written() + trace.dropped() == trace.attempted(),
"accounting closes under contention");
}
void test_publish_velocity_frame()
{
std::printf("[5] publish velocity frame\n");
// yaw = 90 degrees: q = (0, 0, sin45, cos45)
const double s = std::sqrt(0.5);
const double q[4] = {0.0, 0.0, s, s};
const double v_body[3] = {1.0, 0.0, 0.0};
double v_world[3] = {0.0, 0.0, 0.0};
point_lio::rotate_body_to_world(q, v_body, v_world);
std::printf(" body (1,0,0) at yaw 90 -> world (%.6f,%.6f,%.6f)\n",
v_world[0], v_world[1], v_world[2]);
check(std::fabs(v_world[0] - 0.0) < 1e-12, "world x = 0");
check(std::fabs(v_world[1] - 1.0) < 1e-12, "world y = 1");
check(std::fabs(v_world[2] - 0.0) < 1e-12, "world z = 0");
// At identity the same body velocity must pass through unchanged.
const double q_id[4] = {0.0, 0.0, 0.0, 1.0};
double v_id[3] = {0.0, 0.0, 0.0};
point_lio::rotate_body_to_world(q_id, v_body, v_id);
check(std::fabs(v_id[0] - 1.0) < 1e-12, "identity leaves x unchanged");
}
bool run_reference(double & dx0_out, double & p00_out)
{
Eigen::MatrixXd P = Eigen::MatrixXd::Identity(30, 30);
Eigen::MatrixXd H = Eigen::MatrixXd::Zero(12, 30);
H(0, 0) = 1.0;
Eigen::VectorXd z = Eigen::VectorXd::Zero(12);
z(0) = 0.1;
const double r = 0.01;
Eigen::MatrixXd S = H * P * H.transpose() + r * Eigen::MatrixXd::Identity(12, 12);
Eigen::LLT<Eigen::MatrixXd> llt(S);
if (llt.info() != Eigen::Success) {
return false;
}
Eigen::MatrixXd K = llt.solve(H * P).transpose();
dx0_out = (K * z)(0);
p00_out = (P - K * H * P)(0, 0);
return true;
}
void test_open_failure_does_not_disturb_filter()
{
std::printf("[6] unopenable destination\n");
point_lio::RuntimeUpdateTrace trace;
bool error_seen = false;
trace.set_error_sink([&](const std::string &) { error_seen = true; });
const bool ok = trace.initialize(true, "/proc/self/definitely_not_writable");
check(!ok, "initialize reports failure");
check(!trace.enabled(), "trace stays disabled after a failed open");
check(error_seen, "error sink invoked once");
double dx0 = 0.0;
double p00 = 0.0;
check(run_reference(dx0, p00), "reference solved");
check(std::fabs(dx0 - 0.0990099009900990) < 1e-9, "reference dx0 unchanged");
trace.shutdown();
}
Eigen::MatrixXd g_h;
Eigen::VectorXd g_z;
double g_noise = 0.01;
void measurement_cb(state_output &, Eigen::Matrix3d, Eigen::Matrix3d,
esekfom::dyn_share_modified<double> & share)
{
share.valid = true;
share.h_x = g_h;
share.z = g_z;
share.M_Noise = g_noise;
}
state_output make_state()
{
state_output s;
s.pos = vect3();
s.rot = SO3();
s.offset_R_L_I = SO3();
s.offset_T_L_I = vect3();
s.vel = vect3();
s.omg = vect3();
s.acc = vect3();
s.gravity = vect3();
s.gravity(2) = -9.81;
s.bg = vect3();
s.ba = vect3();
return s;
}
struct Snapshot
{
Eigen::Vector3d pos = Eigen::Vector3d::Zero();
Eigen::Vector3d vel = Eigen::Vector3d::Zero();
Eigen::MatrixXd P = Eigen::MatrixXd::Zero(30, 30);
};
Snapshot run_update(bool with_trace, point_lio::RuntimeUpdateTrace * trace,
const Eigen::MatrixXd & P0)
{
typedef esekfom::esekf<state_output, 30, input_ikfom> ekf_type;
state_output x0 = make_state();
ekf_type ekf(x0);
ekf.init_dyn_share_modified_2h(process_dummy_state, process_jacobian_dummy_state,
measurement_cb);
ekf.change_x(x0);
ekf_type::cov P_cov = P0;
ekf.change_P(P_cov);
if (!with_trace) {
ekf.update_iterated_dyn_share_modified();
} else {
point_lio::RuntimeUpdateTrace::Record r;
r.event = point_lio::RuntimeUpdateTrace::kLidarUpdate;
for (int i = 0; i < 3; ++i) {
r.pos_before[i] = ekf.get_x().pos(i);
r.vel_before[i] = ekf.get_x().vel(i);
}
const bool ok = ekf.update_iterated_dyn_share_modified();
for (int i = 0; i < 3; ++i) {
r.pos_after[i] = ekf.get_x().pos(i);
r.vel_after[i] = ekf.get_x().vel(i);
}
r.ok = ok ? 1 : 0;
if (ok) {
r.effective_m = ekf.last_update_effective_m();
r.state_dof = ekf.last_update_state_dof();
r.branch = ekf.last_update_information_branch() ? 1 : 0;
} else {
r.effective_m = point_lio::RuntimeUpdateTrace::kNotApplicable;
r.branch = point_lio::RuntimeUpdateTrace::kNotApplicable;
}
trace->record(r);
}
Snapshot out;
for (int i = 0; i < 3; ++i) {
out.pos(i) = ekf.get_x().pos(i);
out.vel(i) = ekf.get_x().vel(i);
}
out.P = ekf.get_P();
return out;
}
void test_wrapping_does_not_change_the_posterior(const std::filesystem::path & root)
{
std::printf("[7] wrapping leaves the filter unchanged\n");
g_h = Eigen::MatrixXd::Zero(12, 12);
g_h.setIdentity();
g_z = Eigen::VectorXd::Ones(12) * 0.02;
g_noise = 0.01;
const Eigen::MatrixXd P0 = Eigen::MatrixXd::Identity(30, 30) * 2.0;
const Snapshot plain = run_update(false, nullptr, P0);
const std::filesystem::path dir = root / "wrapped";
point_lio::RuntimeUpdateTrace trace;
check(trace.initialize(true, dir), "initialize succeeds");
const Snapshot wrapped = run_update(true, &trace, P0);
trace.flush();
trace.shutdown();
const double pos_gap = (plain.pos - wrapped.pos).cwiseAbs().maxCoeff();
const double vel_gap = (plain.vel - wrapped.vel).cwiseAbs().maxCoeff();
const double cov_gap = (plain.P - wrapped.P).cwiseAbs().maxCoeff();
std::printf(" gaps: pos=%.3e vel=%.3e cov=%.3e\n", pos_gap, vel_gap, cov_gap);
check(pos_gap == 0.0, "position identical with and without trace");
check(vel_gap == 0.0, "velocity identical with and without trace");
check(cov_gap == 0.0, "covariance identical with and without trace");
const auto rows = read_csv(dir / "runtime_update_trace.csv");
check(rows.size() == 2, "one lidar_update record written");
if (rows.size() == 2) {
check(rows[1][23] == "12", "effective_m = 12");
check(rows[1][24] == "0", "covariance branch reported");
}
}
// Runs as a child process with RLIMIT_FSIZE so writes fail part way through
// without touching the real filesystem's free space.
int run_size_limited_child()
{
struct rlimit limit;
limit.rlim_cur = 1024;
limit.rlim_max = 1024;
setrlimit(RLIMIT_FSIZE, &limit);
signal(SIGXFSZ, SIG_IGN);
const std::filesystem::path dir = "trace_test_out/limited";
point_lio::RuntimeUpdateTrace trace;
trace.set_capacity(64);
if (!trace.initialize(true, dir)) {
std::printf("init_failed\n");
return 0;
}
for (int i = 0; i < 4000; ++i) {
trace.record(make_record(point_lio::RuntimeUpdateTrace::kPredict));
}
trace.shutdown();
std::printf("attempted=%llu written=%llu dropped=%llu write_failures=%llu incomplete=%d\n",
static_cast<unsigned long long>(trace.attempted()),
static_cast<unsigned long long>(trace.written()),
static_cast<unsigned long long>(trace.dropped()),
static_cast<unsigned long long>(trace.write_failures()),
static_cast<int>(trace.output_incomplete()));
return 0;
}
void test_mid_write_failure(const char * self)
{
std::printf("[8] mid-write failure (size-limited child)\n");
const std::string command = std::string(self) + " --size-limited";
FILE * pipe = popen(command.c_str(), "r");
if (pipe == nullptr) {
check(false, "could not start the size-limited child");
return;
}
std::string output;
char buffer[512];
while (std::fgets(buffer, sizeof(buffer), pipe) != nullptr) {
output += buffer;
}
const int status = pclose(pipe);
std::printf(" child said: %s", output.c_str());
check(status == 0, "child exited cleanly");
unsigned long long attempted = 0, written = 0, dropped = 0, failures = 0;
int incomplete = -1;
const int parsed = std::sscanf(output.c_str(),
"attempted=%llu written=%llu dropped=%llu write_failures=%llu incomplete=%d",
&attempted, &written, &dropped, &failures, &incomplete);
check(parsed == 5, "child reported all counters");
if (parsed != 5) {
return;
}
check(attempted > 0, "records were attempted");
check(failures > 0, "the write failure was detected");
check(written + dropped == attempted,
"accounting closes after a partial write (this was the reported defect)");
check(incomplete == 1, "output is reported incomplete");
}
} // namespace
Eigen::Matrix<double, 30, 1> process_dummy_state(state_output &, const input_ikfom &)
{
return Eigen::Matrix<double, 30, 1>::Zero();
}
Eigen::Matrix<double, 30, 30> process_jacobian_dummy_state(state_output &, const input_ikfom &)
{
return Eigen::Matrix<double, 30, 30>::Identity();
}
int main(int argc, char ** argv)
{
if (argc > 1 && std::strcmp(argv[1], "--size-limited") == 0) {
return run_size_limited_child();
}
const std::filesystem::path root = "trace_test_out";
std::error_code ec;
std::filesystem::create_directories(root, ec);
test_disabled_writes_nothing(root);
test_fields_and_precision(root);
test_bounded_queue(root);
test_producer_does_not_wait(root);
test_publish_velocity_frame();
test_open_failure_does_not_disturb_filter();
test_wrapping_does_not_change_the_posterior(root);
test_mid_write_failure(argv[0]);
std::printf("\n%s (%d failure%s)\n", g_failures == 0 ? "ALL PASS" : "FAILURES",
g_failures, g_failures == 1 ? "" : "s");
return g_failures == 0 ? 0 : 1;
}