diff --git a/src/Libraries/robot_cpp/CMakeLists.txt b/src/Libraries/robot_cpp/CMakeLists.txt index 3b941ee..5b148fd 100644 --- a/src/Libraries/robot_cpp/CMakeLists.txt +++ b/src/Libraries/robot_cpp/CMakeLists.txt @@ -264,6 +264,35 @@ if(BUILD_TESTS) # Add test to CTest add_test(NAME NodeHandleTest COMMAND test_node_handle) - - message(STATUS "Test executable 'test_node_handle' will be built") + + # ------------------------------------------------------------------ + # Throttled logging: the throttle window must be private to each call + # site, and must survive concurrent calls, so this test needs threads. + # ------------------------------------------------------------------ + find_package(Threads REQUIRED) + + add_executable(test_console_throttle + test/test_console_throttle.cpp + ) + + target_include_directories(test_console_throttle + PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/include + ) + + target_link_libraries(test_console_throttle + PRIVATE + ${PROJECT_NAME} + Threads::Threads + ) + + set_target_properties(test_console_throttle PROPERTIES + LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR} + BUILD_RPATH "${CMAKE_BINARY_DIR}" + INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib" + ) + + add_test(NAME ConsoleThrottleTest COMMAND test_console_throttle) + + message(STATUS "Test executables 'test_node_handle', 'test_console_throttle' will be built") endif() diff --git a/src/Libraries/robot_cpp/include/robot/console.h b/src/Libraries/robot_cpp/include/robot/console.h index f70d864..847d170 100644 --- a/src/Libraries/robot_cpp/include/robot/console.h +++ b/src/Libraries/robot_cpp/include/robot/console.h @@ -459,9 +459,24 @@ namespace robot * Logs an error message with red text color. Use for errors that indicate * problems or failures. * + * The throttle interval is tracked separately for each call site, so two + * different places in the code never silence one another. The unit of + * granularity is the call site, not the message: a call site inside a loop + * that formats a different value each pass still prints at most once per + * interval. + * + * @warning Call it directly. Behind a helper of your own the grouping + * stops being something you control: the helper may be inlined, or + * the call may become a tail call, and the window then follows the + * helper's callers instead of the helper. The effect is always + * more log lines than expected, never fewer. + * + * @param throttle Minimum interval between two prints [s]. Zero, negative + * or NaN disables throttling (prints every time) rather + * than silencing the call site. * @param format printf-style format string. * @param ... Variable arguments for format string. - */ + */ void log_error_throttle(double throttle, const char *format, ...); /** @@ -470,6 +485,21 @@ namespace robot * Logs a debug message with cyan text color. Use for debugging information * that is typically only needed during development. * + * The throttle interval is tracked separately for each call site, so two + * different places in the code never silence one another. The unit of + * granularity is the call site, not the message: a call site inside a loop + * that formats a different value each pass still prints at most once per + * interval. + * + * @warning Call it directly. Behind a helper of your own the grouping + * stops being something you control: the helper may be inlined, or + * the call may become a tail call, and the window then follows the + * helper's callers instead of the helper. The effect is always + * more log lines than expected, never fewer. + * + * @param throttle Minimum interval between two prints [s]. Zero, negative + * or NaN disables throttling (prints every time) rather + * than silencing the call site. * @param format printf-style format string. * @param ... Variable arguments for format string. */ @@ -481,6 +511,21 @@ namespace robot * Logs a success message with green text color. Use for successful operations * or positive status updates. * + * The throttle interval is tracked separately for each call site, so two + * different places in the code never silence one another. The unit of + * granularity is the call site, not the message: a call site inside a loop + * that formats a different value each pass still prints at most once per + * interval. + * + * @warning Call it directly. Behind a helper of your own the grouping + * stops being something you control: the helper may be inlined, or + * the call may become a tail call, and the window then follows the + * helper's callers instead of the helper. The effect is always + * more log lines than expected, never fewer. + * + * @param throttle Minimum interval between two prints [s]. Zero, negative + * or NaN disables throttling (prints every time) rather + * than silencing the call site. * @param format printf-style format string. * @param ... Variable arguments for format string. */ @@ -492,6 +537,21 @@ namespace robot * Logs a warning message with yellow text color. Use for warnings that don't * prevent operation but should be noted. * + * The throttle interval is tracked separately for each call site, so two + * different places in the code never silence one another. The unit of + * granularity is the call site, not the message: a call site inside a loop + * that formats a different value each pass still prints at most once per + * interval. + * + * @warning Call it directly. Behind a helper of your own the grouping + * stops being something you control: the helper may be inlined, or + * the call may become a tail call, and the window then follows the + * helper's callers instead of the helper. The effect is always + * more log lines than expected, never fewer. + * + * @param throttle Minimum interval between two prints [s]. Zero, negative + * or NaN disables throttling (prints every time) rather + * than silencing the call site. * @param format printf-style format string. * @param ... Variable arguments for format string. */ diff --git a/src/Libraries/robot_cpp/src/console.cpp b/src/Libraries/robot_cpp/src/console.cpp index 1e7f66e..fc6b039 100644 --- a/src/Libraries/robot_cpp/src/console.cpp +++ b/src/Libraries/robot_cpp/src/console.cpp @@ -1,18 +1,45 @@ #include "robot/console.h" #include +#include +#include +#include #include #include #include #include #include +#include +#include #include #include +// Identifies the caller of a throttled log function. Every call site has its +// own return address, which is what lets the throttle window be private per +// call site without changing any public signature. +#if defined(__GNUC__) || defined(__clang__) +#define ROBOT_LOG_CALL_SITE() __builtin_return_address(0) +#else +// Without the builtin the format string pointer alone keys the throttle. That +// is weaker (identical literals may be folded together) but still far better +// than one window shared by the whole process. +#define ROBOT_LOG_CALL_SITE() static_cast(nullptr) +#endif + namespace robot { - // Global flag to enable/disable colors - static bool color_enabled = true; + // Written through set_color_enabled() and read by every log call, so it is + // touched from the control loop, sensor callbacks and planner threads at + // once. Plain bool made that a data race. + static std::atomic color_enabled{true}; + + // TERM and NO_COLOR do not change while the process runs, but + // is_color_enabled() is called two to three times per log line. Detecting + // support on every one of them meant several getenv() calls per line inside + // the control loop, and getenv() is not safe against a concurrent setenv(). + // Detect once, then answer from the cache. + static std::once_flag color_support_once; + static bool color_supported_cached = true; static inline bool format_ends_with_newline(const char *format) { @@ -24,7 +51,7 @@ namespace robot return (n > 0 && format[n - 1] == '\n'); } - bool is_color_supported() + static bool detect_color_support() { // Check if NO_COLOR environment variable is set const char *no_color = std::getenv("NO_COLOR"); @@ -52,14 +79,22 @@ namespace robot return true; } + bool is_color_supported() + { + std::call_once(color_support_once, + []() { color_supported_cached = detect_color_support(); }); + return color_supported_cached; + } + void set_color_enabled(bool enabled) { - color_enabled = enabled && is_color_supported(); + color_enabled.store(enabled && is_color_supported(), + std::memory_order_relaxed); } bool is_color_enabled() { - return color_enabled && is_color_supported(); + return color_enabled.load(std::memory_order_relaxed) && is_color_supported(); } // Helper function to format timestamp as "sec.nsec" @@ -359,68 +394,180 @@ namespace robot va_end(args); } + // ---------------------------------------------------------------------- + // Per-call-site throttle state + // + // The throttle window has to belong to the call site, not to the function. + // move_base2's controller_runner alone holds eleven log_error_throttle() + // calls; with one shared timestamp, whichever fired first silenced the other + // ten for the rest of the window, so real faults were swallowed. + // + // The call site is identified by its return address, which keeps the public + // signatures untouched - no caller has to change. The format pointer is + // mixed in as a second key because identical string literals can be folded + // into one address by the linker. + // + // Known limit: if a caller invokes one of these functions as the very last + // thing it does, the compiler may turn it into a tail call, and the return + // address then belongs to that caller's own caller. The window is then kept + // per calling site of the wrapper instead of per wrapper. That splits a + // window into several, never merges two into one, so the failure mode is + // extra log lines rather than a swallowed message. Tests pin their call + // sites down with a volatile read to keep this out of the measurement. + // + // The table is fixed size and lock free on purpose: these functions are + // called from the control loop, so no allocation and no mutex on the path. + // ---------------------------------------------------------------------- + constexpr std::size_t kThrottleSlots = 512; // power of two: mask, not modulo + constexpr std::size_t kThrottleProbe = 8; // linear probing depth + + struct ThrottleSlot + { + std::atomic key{0}; // 0 marks a free slot + std::atomic last_ns{0}; + }; + + static ThrottleSlot throttle_slots[kThrottleSlots]; + + static inline std::uintptr_t throttle_key(const void *site, const void *format) + { + std::uint64_t key = static_cast(reinterpret_cast(site)); + key ^= static_cast(reinterpret_cast(format)) + + 0x9E3779B97F4A7C15ull + (key << 6) + (key >> 2); + key *= 0xFF51AFD7ED558CCDull; + key ^= key >> 33; + const std::uintptr_t folded = static_cast(key); + return (folded == 0) ? 1 : folded; // 0 is reserved for "slot free" + } + + /** + * @brief Decide whether this call site may print now. + * + * @param site Return address of the caller. Must be taken in the public + * log function, never inside this helper: from here the + * builtin would report an address in this function and every + * call site would collapse back onto a single key. + * @param format Format string pointer, used as a second key component. + * @param throttle Minimum interval between two prints [s]. + */ + static bool throttle_allows(const void *site, const void *format, double throttle) + { + const std::int64_t now_ns = + std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()) + .count(); + + // A NaN or negative interval means "do not throttle" rather than "never + // log again". A bad parameter must make the log noisy, never silent - + // NaN used to fail the >= test forever and mute the call site for good. + std::int64_t window_ns = 0; + if (std::isfinite(throttle) && throttle > 0.0) + { + const double scaled = throttle * 1e9; + window_ns = (scaled >= 9.0e18) + ? std::numeric_limits::max() + : static_cast(scaled); + } + if (window_ns <= 0) + { + return true; + } + + const std::uintptr_t key = throttle_key(site, format); + const std::size_t home = static_cast(key) & (kThrottleSlots - 1); + + for (std::size_t probe = 0; probe < kThrottleProbe; ++probe) + { + ThrottleSlot &slot = throttle_slots[(home + probe) & (kThrottleSlots - 1)]; + + std::uintptr_t owner = slot.key.load(std::memory_order_acquire); + if (owner == 0) + { + std::uintptr_t expected = 0; + owner = slot.key.compare_exchange_strong(expected, key, + std::memory_order_acq_rel, + std::memory_order_acquire) + ? key + : expected; // lost the race, another site owns it now + } + if (owner != key) + { + continue; // slot belongs to a different call site + } + + const std::int64_t last = slot.last_ns.load(std::memory_order_relaxed); + // last == 0 is a slot nobody has printed from yet: always print, which + // matches the old default-constructed time_point behaviour. + if (last != 0 && (now_ns - last) < window_ns) + { + return false; + } + // The exchange is what stops two threads printing in the same window; + // the loser sees the updated timestamp and gives up. + std::int64_t expected_ns = last; + return slot.last_ns.compare_exchange_strong(expected_ns, now_ns, + std::memory_order_relaxed); + } + + // Table full: print. A saturated table must cost extra log lines, never a + // swallowed fault. + return true; + } + void log_error_throttle(double throttle, const char *format, ...) { - static auto last_log_time = std::chrono::steady_clock::time_point{}; - auto now = std::chrono::steady_clock::now(); - auto elapsed = std::chrono::duration(now - last_log_time).count(); - - if (elapsed >= throttle) + const void *site = ROBOT_LOG_CALL_SITE(); + if (!throttle_allows(site, format, throttle)) { - last_log_time = now; - va_list args; - va_start(args, format); - vprintf_color(color::RED, format, args); - va_end(args); + return; } + + va_list args; + va_start(args, format); + vprintf_color(color::RED, format, args); + va_end(args); } void log_info_throttle(double throttle, const char *format, ...) { - static auto last_log_time = std::chrono::steady_clock::time_point{}; - auto now = std::chrono::steady_clock::now(); - auto elapsed = std::chrono::duration(now - last_log_time).count(); - - if (elapsed >= throttle) + const void *site = ROBOT_LOG_CALL_SITE(); + if (!throttle_allows(site, format, throttle)) { - last_log_time = now; - va_list args; - va_start(args, format); - vprintf_color(color::BRIGHT_BLUE, format, args); - va_end(args); + return; } + + va_list args; + va_start(args, format); + vprintf_color(color::BRIGHT_BLUE, format, args); + va_end(args); } void log_success_throttle(double throttle, const char *format, ...) { - static auto last_log_time = std::chrono::steady_clock::time_point{}; - auto now = std::chrono::steady_clock::now(); - auto elapsed = std::chrono::duration(now - last_log_time).count(); - - if (elapsed >= throttle) + const void *site = ROBOT_LOG_CALL_SITE(); + if (!throttle_allows(site, format, throttle)) { - last_log_time = now; - va_list args; - va_start(args, format); - vprintf_color(color::GREEN, format, args); - va_end(args); + return; } + + va_list args; + va_start(args, format); + vprintf_color(color::GREEN, format, args); + va_end(args); } void log_warning_throttle(double throttle, const char *format, ...) { - static auto last_log_time = std::chrono::steady_clock::time_point{}; - auto now = std::chrono::steady_clock::now(); - auto elapsed = std::chrono::duration(now - last_log_time).count(); - - if (elapsed >= throttle) + const void *site = ROBOT_LOG_CALL_SITE(); + if (!throttle_allows(site, format, throttle)) { - last_log_time = now; - va_list args; - va_start(args, format); - vprintf_color(color::YELLOW, format, args); - va_end(args); + return; } + + va_list args; + va_start(args, format); + vprintf_color(color::YELLOW, format, args); + va_end(args); } void log_assert(bool condition, const char *format, ...) @@ -474,3 +621,5 @@ namespace robot } } // namespace robot + +#undef ROBOT_LOG_CALL_SITE diff --git a/src/Libraries/robot_cpp/test/test_console_throttle.cpp b/src/Libraries/robot_cpp/test/test_console_throttle.cpp new file mode 100644 index 0000000..f33cd3c --- /dev/null +++ b/src/Libraries/robot_cpp/test/test_console_throttle.cpp @@ -0,0 +1,310 @@ +/********************************************************************* + * + * Test program for the throttled logging functions in robot/console.h + * + * The point of these tests is that a throttle window belongs to a call + * site, not to the logging function. Before that fix a single static + * timestamp per function meant the first call site to fire silenced every + * other one process-wide, which swallowed real fault messages in the + * navigation stack. + * + * All test reporting goes to stderr, because stdout is redirected to a + * temporary file while the log calls run. + * + *********************************************************************/ + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +int g_failures = 0; + +void check(bool condition, const std::string &message) +{ + if (condition) + { + std::cerr << "PASS: " << message << std::endl; + } + else + { + std::cerr << "FAIL: " << message << std::endl; + ++g_failures; + } +} + +/** + * @brief Run @p body with stdout redirected, return everything it printed. + * + * dup/dup2 rather than freopen so the real stdout can be restored: the test + * has to keep reporting after the capture ends. + */ +std::string capture(const std::function &body) +{ + char path[] = "/tmp/robot_cpp_throttle_XXXXXX"; + const int tmp_fd = ::mkstemp(path); + if (tmp_fd < 0) + { + std::cerr << "FAIL: cannot create temp file for capture" << std::endl; + ++g_failures; + return ""; + } + + std::fflush(stdout); + const int saved_fd = ::dup(STDOUT_FILENO); + ::dup2(tmp_fd, STDOUT_FILENO); + + body(); + + std::fflush(stdout); + ::dup2(saved_fd, STDOUT_FILENO); + ::close(saved_fd); + + ::lseek(tmp_fd, 0, SEEK_SET); + std::string out; + char buffer[4096]; + ssize_t got = 0; + while ((got = ::read(tmp_fd, buffer, sizeof(buffer))) > 0) + { + out.append(buffer, static_cast(got)); + } + ::close(tmp_fd); + ::unlink(path); + return out; +} + +/// Number of non-overlapping occurrences of @p needle in @p haystack. +int countOf(const std::string &haystack, const std::string &needle) +{ + int count = 0; + std::size_t pos = haystack.find(needle); + while (pos != std::string::npos) + { + ++count; + pos = haystack.find(needle, pos + needle.size()); + } + return count; +} + +// A throttle window far longer than the test run: anything printed twice +// under this interval means the throttle failed, and anything printed once +// per call site means it worked. +constexpr double kLongWindow = 1000.0; + +/// Two distinct call sites, distinct format strings, must not silence each other. +void testDistinctCallSites() +{ + const std::string out = capture([]() { + robot::log_warning_throttle(kLongWindow, "SITE_ONE %d", 1); + robot::log_warning_throttle(kLongWindow, "SITE_TWO %d", 2); + }); + + check(countOf(out, "SITE_ONE") == 1, "first call site printed"); + check(countOf(out, "SITE_TWO") == 1, + "second call site printed despite the first holding the window"); +} + +/// Same test with an identical format string in both places: the linker may +/// fold the two literals into one address, so the return address is the only +/// thing left that can tell the call sites apart. +void testDistinctCallSitesSharedLiteral() +{ + const std::string out = capture([]() { + robot::log_error_throttle(kLongWindow, "SHARED_LITERAL"); + robot::log_error_throttle(kLongWindow, "SHARED_LITERAL"); + }); + + check(countOf(out, "SHARED_LITERAL") == 2, + "two call sites sharing one format literal both printed"); +} + +/// One call site hammered in a loop prints exactly once per window. +void testSameCallSiteThrottled() +{ + const std::string out = capture([]() { + for (int i = 0; i < 100; ++i) + { + robot::log_warning_throttle(kLongWindow, "LOOP_SITE %d", i); + } + }); + + check(countOf(out, "LOOP_SITE") == 1, "repeated call site printed once"); +} + +// Wrapped in a function so every call below really is the same call site. +// Three separate lines would be three call sites and the test would pass +// without the window ever expiring. +// +// Two attributes are needed to pin the call site down: +// - noinline, or each call would be inlined and get its own return address; +// - the volatile read, which leaves a live instruction after the log call so +// the compiler cannot turn it into a tail call. A tail call would hand +// log_info_throttle the return address of *this* function's caller, and +// the three calls below would again look like three different sites. +__attribute__((noinline)) void expiryLogger() +{ + robot::log_info_throttle(0.05, "EXPIRY_SITE"); + static volatile int keep_frame = 0; + (void)keep_frame; +} + +/// The window has to expire. +void testWindowExpires() +{ + const std::string out = capture([]() { + expiryLogger(); + expiryLogger(); // same window, must be swallowed + std::this_thread::sleep_for(std::chrono::milliseconds(120)); + expiryLogger(); + }); + + check(countOf(out, "EXPIRY_SITE") == 2, + "call site printed once per window, again after it expired"); +} + +/// The four functions keep separate state from one another. +void testFunctionsIndependent() +{ + const std::string out = capture([]() { + robot::log_error_throttle(kLongWindow, "FN_ERROR"); + robot::log_warning_throttle(kLongWindow, "FN_WARNING"); + robot::log_info_throttle(kLongWindow, "FN_INFO"); + robot::log_success_throttle(kLongWindow, "FN_SUCCESS"); + }); + + check(countOf(out, "FN_ERROR") == 1 && countOf(out, "FN_WARNING") == 1 && + countOf(out, "FN_INFO") == 1 && countOf(out, "FN_SUCCESS") == 1, + "all four throttled log levels printed"); +} + +/// A bad interval must make the call site noisy, never silent. NaN used to +/// fail the >= comparison forever and mute the call site for the whole run. +void testDegenerateIntervals() +{ + const std::string out = capture([]() { + for (int i = 0; i < 3; ++i) + { + robot::log_warning_throttle(std::nan(""), "NAN_SITE"); + } + for (int i = 0; i < 3; ++i) + { + robot::log_warning_throttle(-1.0, "NEGATIVE_SITE"); + } + for (int i = 0; i < 3; ++i) + { + robot::log_warning_throttle(0.0, "ZERO_SITE"); + } + }); + + check(countOf(out, "NAN_SITE") == 3, "NaN interval does not silence the call site"); + check(countOf(out, "NEGATIVE_SITE") == 3, "negative interval prints every time"); + check(countOf(out, "ZERO_SITE") == 3, "zero interval prints every time"); +} + +// Called from every worker thread, so all of them share one call site and +// therefore one throttle slot. Exactly one print may get through. +__attribute__((noinline)) void concurrentLogger() +{ + robot::log_warning_throttle(kLongWindow, "THREAD_SITE"); + static volatile int keep_frame = 0; // see expiryLogger(): blocks tail call + (void)keep_frame; +} + +/// Concurrent calls from one call site: the old plain timestamp was a data +/// race and could let several threads print inside one window. +void testConcurrentSameCallSite() +{ + const std::string out = capture([]() { + constexpr int kThreads = 8; + constexpr int kIterations = 50; + + std::atomic go{false}; + std::vector workers; + workers.reserve(kThreads); + + for (int t = 0; t < kThreads; ++t) + { + workers.emplace_back([&go]() { + while (!go.load(std::memory_order_acquire)) + { + std::this_thread::yield(); + } + for (int i = 0; i < kIterations; ++i) + { + concurrentLogger(); + } + }); + } + + go.store(true, std::memory_order_release); + for (std::thread &worker : workers) + { + worker.join(); + } + }); + + check(countOf(out, "THREAD_SITE") == 1, + "8 threads x 50 calls on one call site printed exactly once"); +} + +/// Colour can be turned off and on, and the cached terminal detection does not +/// freeze the answer at its first value. +void testColorToggle() +{ + const std::string colored = capture([]() { + robot::set_color_enabled(true); + robot::log_warning_throttle(0.0, "COLOR_ON_SITE"); + }); + + const std::string plain = capture([]() { + robot::set_color_enabled(false); + robot::log_warning_throttle(0.0, "COLOR_OFF_SITE"); + }); + + robot::set_color_enabled(true); + + check(countOf(plain, "COLOR_OFF_SITE") == 1 && plain.find("\033[") == std::string::npos, + "colour disabled emits no escape sequence"); + // Whether colour is actually available depends on the environment the test + // runs in, so only assert the message itself here. + check(countOf(colored, "COLOR_ON_SITE") == 1, "colour enabled still logs the message"); +} + +} // namespace + +int main() +{ + std::cerr << "=== robot::log_*_throttle tests ===" << std::endl; + + testDistinctCallSites(); + testDistinctCallSitesSharedLiteral(); + testSameCallSiteThrottled(); + testWindowExpires(); + testFunctionsIndependent(); + testDegenerateIntervals(); + testConcurrentSameCallSite(); + testColorToggle(); + + if (g_failures == 0) + { + std::cerr << "\nAll throttle tests passed." << std::endl; + return 0; + } + + std::cerr << "\n" << g_failures << " throttle test(s) failed." << std::endl; + return 1; +}