From 5a67417fbe77e7e4ce89fe767c76e1c203861469 Mon Sep 17 00:00:00 2001 From: walunt5 Date: Thu, 5 Nov 2026 11:58:42 +0800 Subject: [PATCH] =?UTF-8?q?feat(Point-LIO):=20=E9=BB=98=E8=AE=A4=E5=85=B3?= =?UTF-8?q?=E9=97=AD=E7=9A=84=E6=BB=A4=E6=B3=A2=E5=99=A8=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E9=93=BE=E8=B7=9F=E8=B8=AA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 回答两个只能靠证据而不是推断的问题:信息形式分支是否被选中过、 哪类更新贡献了主要位置变化。 运行时性质: - 关闭时只做一次 relaxed atomic load 即返回:不格式化、不写盘、不建目录。 - 生产者不阻塞:对预分配环形缓冲做 try-lock,抢不到或满了就计数丢弃。 - 记账闭合:关机后 attempted == written + dropped。 - 写失败只关闭跟踪,滤波器继续跑,且只告知调用方一次。 新参数 runtime_update_trace_enable 默认 false。 --- .../test_runtime_update_trace.cpp | 522 ++++++++++++++++++ .../Point-LIO/include/runtime_update_trace.h | 446 +++++++++++++++ .../perception/Point-LIO/src/parameters.cpp | 4 + .../src/perception/Point-LIO/src/parameters.h | 5 +- 4 files changed, 976 insertions(+), 1 deletion(-) create mode 100644 minco_ws/docs/diagnostics/esekfom_update_regression/test_runtime_update_trace.cpp create mode 100644 minco_ws/src/perception/Point-LIO/include/runtime_update_trace.h diff --git a/minco_ws/docs/diagnostics/esekfom_update_regression/test_runtime_update_trace.cpp b/minco_ws/docs/diagnostics/esekfom_update_regression/test_runtime_update_trace.cpp new file mode 100644 index 0000000..7e3671f --- /dev/null +++ b/minco_ws/docs/diagnostics/esekfom_update_regression/test_runtime_update_trace.cpp @@ -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 +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +Eigen::Matrix process_dummy_state(state_output &, const input_ikfom &); +Eigen::Matrix 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 split(const std::string & line) +{ + std::vector out; + std::stringstream ss(line); + std::string item; + while (std::getline(ss, item, ',')) { + out.push_back(item); + } + return out; +} + +std::vector> read_csv(const std::filesystem::path & path) +{ + std::vector> 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(trace.attempted()), + static_cast(trace.written()), + static_cast(trace.dropped()), + static_cast(trace.full_drops()), + static_cast(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(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::steady_clock::now() - start).count(); + holder.join(); + + std::printf(" 200 records while lock held took %lld ms, contended drops=%llu\n", + static_cast(elapsed_ms), + static_cast(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 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 & 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 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(trace.attempted()), + static_cast(trace.written()), + static_cast(trace.dropped()), + static_cast(trace.write_failures()), + static_cast(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 process_dummy_state(state_output &, const input_ikfom &) +{ + return Eigen::Matrix::Zero(); +} + +Eigen::Matrix process_jacobian_dummy_state(state_output &, const input_ikfom &) +{ + return Eigen::Matrix::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; +} diff --git a/minco_ws/src/perception/Point-LIO/include/runtime_update_trace.h b/minco_ws/src/perception/Point-LIO/include/runtime_update_trace.h new file mode 100644 index 0000000..785e130 --- /dev/null +++ b/minco_ws/src/perception/Point-LIO/include/runtime_update_trace.h @@ -0,0 +1,446 @@ +// Minimal, default-off observation of the filter update chain. +// +// Answers two questions with evidence rather than inference: +// 1. was the information-form solver branch ever selected? +// 2. which update type carries most of the position change? +// +// Properties this file has to defend: +// * disabled: one relaxed atomic load, then return. No formatting, no I/O, +// no allocation, no directory creation. +// * the producer never waits. Enqueue is a try-lock against a PREALLOCATED +// ring; if the lock is held or the ring is full the record is counted as +// dropped and discarded. A bounded queue alone does not make a producer +// non-blocking. +// * accounting closes: `attempted == written + dropped` after shutdown, where +// `written` counts records whose bytes actually reached the file and +// `dropped` counts overflow, lock contention, discarded pending data and +// anything lost to a failed flush. +// * a write failure disables the trace only. The filter keeps running and the +// caller is told once. +// +// No ROS dependency, so the offline regression can drive it directly. +#ifndef POINT_LIO_RUNTIME_UPDATE_TRACE_H +#define POINT_LIO_RUNTIME_UPDATE_TRACE_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace point_lio { + +// Body-frame vector to world frame using a quaternion in ROS field order +// (x, y, z, w). Shared with the publish record so the test exercises the very +// conversion the node uses, instead of a hand-filled record. +inline void rotate_body_to_world(const double q_xyzw[4], const double v_body[3], + double v_world[3]) +{ + const double x = q_xyzw[0], y = q_xyzw[1], z = q_xyzw[2], w = q_xyzw[3]; + const double n = std::sqrt(x * x + y * y + z * z + w * w); + if (!(n > 0.0)) { + v_world[0] = v_body[0]; + v_world[1] = v_body[1]; + v_world[2] = v_body[2]; + return; + } + const double qx = x / n, qy = y / n, qz = z / n, qw = w / n; + const double r00 = 1.0 - 2.0 * (qy * qy + qz * qz); + const double r01 = 2.0 * (qx * qy - qz * qw); + const double r02 = 2.0 * (qx * qz + qy * qw); + const double r10 = 2.0 * (qx * qy + qz * qw); + const double r11 = 1.0 - 2.0 * (qx * qx + qz * qz); + const double r12 = 2.0 * (qy * qz - qx * qw); + const double r20 = 2.0 * (qx * qz - qy * qw); + const double r21 = 2.0 * (qy * qz + qx * qw); + const double r22 = 1.0 - 2.0 * (qx * qx + qy * qy); + v_world[0] = r00 * v_body[0] + r01 * v_body[1] + r02 * v_body[2]; + v_world[1] = r10 * v_body[0] + r11 * v_body[1] + r12 * v_body[2]; + v_world[2] = r20 * v_body[0] + r21 * v_body[1] + r22 * v_body[2]; +} + +class RuntimeUpdateTrace +{ +public: + enum EventType : int + { + kPredict = 0, + kImuUpdate = 1, + kLidarUpdate = 2, + kPublish = 3, + }; + + static constexpr int kVersion = 2; + static constexpr size_t kDefaultCapacity = 4096; + static constexpr int kNotApplicable = -1; + + struct Record + { + uint64_t seq = 0; + uint64_t scan_id = 0; + uint64_t batch_id = 0; + int event = 0; + double t_before = 0.0; + double t_after = 0.0; + double dt = 0.0; + int ok = 0; + // World frame (camera_init) by contract; the CSV says so too. + double pos_before[3] = {0.0, 0.0, 0.0}; + double pos_after[3] = {0.0, 0.0, 0.0}; + double vel_before[3] = {0.0, 0.0, 0.0}; + double vel_after[3] = {0.0, 0.0, 0.0}; + int state_dof = kNotApplicable; + int effective_m = kNotApplicable; + int branch = kNotApplicable; // 0 covariance form, 1 information form + int predict_state = kNotApplicable; + int prop_cov = kNotApplicable; + }; + + RuntimeUpdateTrace() = default; + ~RuntimeUpdateTrace() { shutdown(); } + + RuntimeUpdateTrace(const RuntimeUpdateTrace &) = delete; + RuntimeUpdateTrace & operator=(const RuntimeUpdateTrace &) = delete; + + void set_error_sink(std::function sink) + { + error_sink_ = std::move(sink); + } + + void set_capacity(size_t capacity) + { + capacity_ = capacity == 0 ? 1 : capacity; + } + + bool initialize(bool enable, const std::filesystem::path & directory, + const std::string & filename = "runtime_update_trace.csv") + { + if (!enable) { + return true; + } + std::error_code ec; + std::filesystem::create_directories(directory, ec); + if (ec) { + report_error("cannot create trace directory " + directory.string() + ": " + + ec.message()); + return false; + } + const std::filesystem::path path = directory / filename; + stream_.open(path, std::ios::out | std::ios::trunc); + if (!stream_.is_open()) { + report_error("cannot open trace file " + path.string()); + return false; + } + // Round-trip precision. Without it, epoch times 10.991 ms apart and position + // pairs differing by 1e-8 both collapse to six significant digits. + stream_ << std::setprecision(std::numeric_limits::max_digits10); + ensure_header(); + stream_.flush(); + if (!stream_.good()) { + report_error("cannot write trace header to " + path.string()); + stream_.close(); + return false; + } + + // Preallocate: neither the producer nor the writer allocates afterwards. + ring_.assign(capacity_, Record{}); + pending_.assign(capacity_, Record{}); + + path_ = path; + stop_.store(false); + enabled_.store(true); + writer_ = std::thread([this] { writer_loop(); }); + return true; + } + + bool enabled() const { return enabled_.load(std::memory_order_relaxed); } + + // Hot path. Never waits: try-lock plus a preallocated ring. + void record(const Record & record) + { + if (!enabled_.load(std::memory_order_relaxed)) { + return; + } + // Counted before the try-lock: a record rejected for contention was still + // attempted, otherwise `attempted == written + dropped` cannot hold. + ++attempted_; + std::unique_lock lock(mutex_, std::try_to_lock); + if (!lock.owns_lock()) { + ++dropped_; + ++contended_drops_; + return; + } + if (!enabled_.load(std::memory_order_relaxed)) { + --attempted_; // shutdown raced with this call; it never entered the queue + return; + } + if (count_ >= capacity_) { + ++dropped_; + ++full_drops_; + return; + } + Record & slot = ring_[tail_]; + slot = record; + slot.seq = ++sequence_; + tail_ = (tail_ + 1) % capacity_; + ++count_; + lock.unlock(); + wake_.notify_one(); + } + + // Best effort drain. Not used by the filter path. + void flush() + { + if (!enabled()) { + return; + } + std::unique_lock lock(mutex_); + drained_.wait_for(lock, std::chrono::milliseconds(2000), + [this] { return count_ == 0 && !writing_; }); + } + + // Idempotent, and always runs the accounting path even when the writer has + // already disabled the trace after a failure. + void shutdown() + { + enabled_.store(false); + { + std::lock_guard lock(mutex_); + stop_.store(true); + } + wake_.notify_all(); + if (writer_.joinable()) { + writer_.join(); + } + { + std::lock_guard lock(mutex_); + // Accepted but never handed to the writer. + dropped_ += static_cast(count_); + count_ = 0; + } + if (stream_.is_open()) { + // Bytes the writer placed in the stream but never flushed are not on disk. + if (unflushed_ > 0) { + stream_.flush(); + if (stream_.good()) { + written_ += static_cast(unflushed_); + } else { + dropped_ += static_cast(unflushed_); + output_incomplete_ = true; + } + unflushed_ = 0; + } + stream_.close(); + } + } + + uint64_t attempted() const { return attempted_.load(); } + uint64_t written() const { return written_.load(); } + uint64_t dropped() const { return dropped_.load(); } + uint64_t contended_drops() const { return contended_drops_.load(); } + uint64_t full_drops() const { return full_drops_.load(); } + uint64_t write_failures() const { return write_failures_.load(); } + bool output_incomplete() const { return output_incomplete_.load(); } + const std::filesystem::path & path() const { return path_; } + + static const char * event_name(int event) + { + switch (event) { + case kPredict: return "predict"; + case kImuUpdate: return "imu_update"; + case kLidarUpdate: return "lidar_update"; + case kPublish: return "publish"; + default: return "unknown"; + } + } + + // Test-only seam: hold the producer lock so a concurrent record() must take + // the contention path. Never called by the filter. + void debug_hold_lock_for(std::chrono::milliseconds duration) + { + std::lock_guard lock(mutex_); + std::this_thread::sleep_for(duration); + } + +private: + void ensure_header() + { + stream_ << "trace_version,seq,scan_id,batch_id,event,t_before,t_after,dt,ok," + "pos_before_x,pos_before_y,pos_before_z," + "pos_after_x,pos_after_y,pos_after_z," + "vel_before_x,vel_before_y,vel_before_z," + "vel_after_x,vel_after_y,vel_after_z," + "frame,state_dof,effective_m,branch,predict_state,prop_cov\n"; + } + + void report_error(const std::string & message) + { + if (!error_reported_.exchange(true)) { + if (error_sink_) { + error_sink_(message); + } else { + std::fprintf(stderr, "[runtime_update_trace] %s\n", message.c_str()); + } + } + } + + void writer_loop() + { + bool failed = false; + while (!failed) { + size_t batch = 0; + { + std::unique_lock lock(mutex_); + wake_.wait_for(lock, std::chrono::milliseconds(50), + [this] { return stop_.load() || count_ > 0; }); + if (count_ == 0) { + if (stop_.load()) { + break; + } + continue; + } + batch = count_; + for (size_t i = 0; i < batch; ++i) { + pending_[i] = ring_[head_]; + head_ = (head_ + 1) % capacity_; + } + count_ = 0; + writing_ = true; + } + + size_t done = 0; + size_t unaccounted_from = batch; + for (; done < batch; ++done) { + const int outcome = write_one(pending_[done]); + if (outcome != kWritten) { + failed = true; + // kNotAccounted: this record and the rest of the batch are unaccounted. + // kAccountedByFlush: this record was already counted by the failed flush. + unaccounted_from = (outcome == kNotAccounted) ? done : done + 1; + break; + } + } + + { + std::lock_guard lock(mutex_); + writing_ = false; + if (failed) { + // Only records that no flush has accounted for, plus the queue tail. + dropped_ += static_cast(batch - unaccounted_from); + dropped_ += static_cast(count_); + count_ = 0; + ++write_failures_; + enabled_.store(false); + stop_.store(true); + report_error("trace write failed on " + path_.string() + + "; trace disabled, filtering continues"); + } + drained_.notify_all(); + } + if (failed) { + break; + } + } + std::lock_guard lock(mutex_); + drained_.notify_all(); + } + + // 0 = written into the stream (counted as unflushed) + // 1 = stream already bad; this record is NOT accounted for yet + // 2 = the flush that this record triggered failed and already counted its + // whole unflushed batch as dropped, so it must not be counted again + enum WriteOutcome { kWritten = 0, kNotAccounted = 1, kAccountedByFlush = 2 }; + + int write_one(const Record & r) + { + stream_ << kVersion << ',' << r.seq << ',' << r.scan_id << ',' << r.batch_id + << ',' << event_name(r.event) + << ',' << r.t_before << ',' << r.t_after << ',' << r.dt + << ',' << r.ok + << ',' << r.pos_before[0] << ',' << r.pos_before[1] << ',' << r.pos_before[2] + << ',' << r.pos_after[0] << ',' << r.pos_after[1] << ',' << r.pos_after[2] + << ',' << r.vel_before[0] << ',' << r.vel_before[1] << ',' << r.vel_before[2] + << ',' << r.vel_after[0] << ',' << r.vel_after[1] << ',' << r.vel_after[2] + << ",world" + << ',' << r.state_dof << ',' << r.effective_m << ',' << r.branch + << ',' << r.predict_state << ',' << r.prop_cov << '\n'; + if (!stream_.good()) { + // Nothing counted as written: the flush decides whether these bytes land. + return kNotAccounted; + } + ++unflushed_; + if (unflushed_ >= kFlushEvery) { + commit_flush(); + if (!stream_.good()) { + return kAccountedByFlush; + } + } + return kWritten; + } + + // A record counts as written only once its bytes actually reached the file. + void commit_flush() + { + stream_.flush(); + if (stream_.good()) { + written_ += static_cast(unflushed_); + } else { + dropped_ += static_cast(unflushed_); + output_incomplete_ = true; + ++write_failures_; + report_error("trace flush failed on " + path_.string() + + "; trace disabled, filtering continues"); + enabled_.store(false); + stop_.store(true); + } + unflushed_ = 0; + } + + static constexpr size_t kFlushEvery = 256; + + std::atomic enabled_{false}; + std::atomic stop_{false}; + std::atomic error_reported_{false}; + std::atomic output_incomplete_{false}; + std::atomic sequence_{0}; + std::atomic attempted_{0}; + std::atomic written_{0}; + std::atomic dropped_{0}; + std::atomic contended_drops_{0}; + std::atomic full_drops_{0}; + std::atomic write_failures_{0}; + + std::vector ring_; // preallocated ring + std::vector pending_; // preallocated writer staging + size_t head_ = 0; + size_t tail_ = 0; + size_t count_ = 0; + size_t capacity_ = kDefaultCapacity; + size_t unflushed_ = 0; // in the stream, not yet flushed + + mutable std::mutex mutex_; + std::condition_variable wake_; + std::condition_variable drained_; + bool writing_ = false; + + std::thread writer_; + std::ofstream stream_; + std::filesystem::path path_; + std::function error_sink_; +}; + +} // namespace point_lio + +#endif // POINT_LIO_RUNTIME_UPDATE_TRACE_H diff --git a/minco_ws/src/perception/Point-LIO/src/parameters.cpp b/minco_ws/src/perception/Point-LIO/src/parameters.cpp index 2b2af65..64ab1cd 100644 --- a/minco_ws/src/perception/Point-LIO/src/parameters.cpp +++ b/minco_ws/src/perception/Point-LIO/src/parameters.cpp @@ -88,6 +88,8 @@ std::vector gravity_init, gravity; // 初始和当前估计的重力向 // === 系统功能控制 === bool runtime_pos_log; // 运行时统计总开关(IMU/状态/性能) std::string runtime_log_path; // 运行时统计日志目录,空值保持 ROOT_DIR/Log +// 默认关闭;关闭时不格式化、不写盘、不做任何额外工作 +bool runtime_update_trace_enable = false; bool pcd_save_en; // PCD点云文件保存使能 double accumulated_map_publish_hz = 1.0; // 累积地图低频发布频率 bool path_en; // 轨迹路径发布使能 @@ -342,6 +344,8 @@ void readParameters(rclcpp::Node & nh) nh.declare_parameter("runtime_log_path", ""); nh.get_parameter("runtime_log_path", runtime_log_path); + nh.declare_parameter("runtime_update_trace_enable", false); + nh.get_parameter("runtime_update_trace_enable", runtime_update_trace_enable); nh.declare_parameter("pcd_save.pcd_save_en", false); nh.get_parameter("pcd_save.pcd_save_en", pcd_save_en); diff --git a/minco_ws/src/perception/Point-LIO/src/parameters.h b/minco_ws/src/perception/Point-LIO/src/parameters.h index 17cc7dc..9d02c7a 100755 --- a/minco_ws/src/perception/Point-LIO/src/parameters.h +++ b/minco_ws/src/perception/Point-LIO/src/parameters.h @@ -143,7 +143,10 @@ extern std::vector gravity; // 当前估计的重力向量 (世界 // === 日志和调试控制 === extern bool runtime_pos_log; // 运行时统计总开关(IMU/状态/性能) -extern std::string runtime_log_path; // 运行时统计日志目录,空值保持 ROOT_DIR/Log +extern std::string runtime_log_path; +// Default-off observation of the filter update chain. See runtime_update_trace.h. +// Declared with a false default so that leaving it unset cannot change behaviour. +extern bool runtime_update_trace_enable; extern bool pcd_save_en; // 是否启用PCD点云文件保存 extern double accumulated_map_publish_hz; // 累积地图发布频率,<=0 时不发布