From 205cac3996d0efb4ccba2be63402c578917c08d0 Mon Sep 17 00:00:00 2001 From: jimblackler Date: Tue, 3 Nov 2026 10:38:10 +0000 Subject: [PATCH 1/5] thermal_monitor: Add thermal monitor binary Add thermal_monitor, a standalone Android executable that samples the framework thermal state via the NDK AThermal API while a capture is running, and writes it into the trace as atrace counters (ATrace_setCounter): - sherlock.thermal.status: AThermal_getCurrentThermalStatus() (Android 11+). - sherlock.thermal.headroom: AThermal_getThermalHeadroom(0) (Android 12+), multiplied by 1000 because atrace counters are integers. - sherlock.thermal.headroom.forecast: a 10-second headroom forecast (overridable via --forecast-seconds), sampled on alternate ticks because AThermal_getThermalHeadroom() is rate-limited to about 1 Hz whatever the horizon. A failed forecast tick emits no headroom rather than retrying the current headroom, and the forecast is dropped after 3 failures in a row, because a single NaN can just mean the call was rate-limited. - sherlock.thermal.headroom.threshold.: the device-reported thresholds from AThermal_getThermalHeadroomThresholds() (Android 15+), re-emitted with every headroom sample because the monitor starts before tracing does. The monitor polls once a second (--poll-interval-ms can slow it down but not speed it up, because of the rate limit). Unknown arguments and malformed values are logged and ignored. The Android build now targets API 31 (Sherlock's minimum), so the AThermal calls link directly; AThermal_getThermalHeadroomThresholds() (API 35) is weakly linked and guarded by __builtin_available. Android Performance Analyzer ships the binary in its companion APK next to agi_launch_producer, and reads these counters in its trace viewer. It is built and installed to bin/ like agi_launch_producer. The sampling policy (ThermalCollector) has no Android dependencies, so it is built on the host too and unit tested with GoogleTest (test_thermal_collector). --- BUILD.md | 2 +- CMakeLists.txt | 4 + scripts/android.py | 2 +- thermal_monitor/CMakeLists.txt | 35 +++ thermal_monitor/main.cpp | 179 ++++++++++++ thermal_monitor/test/CMakeLists.txt | 22 ++ .../test/test_thermal_collector.cpp | 270 ++++++++++++++++++ thermal_monitor/thermal_collector.cpp | 70 +++++ thermal_monitor/thermal_collector.h | 115 ++++++++ 9 files changed, 697 insertions(+), 2 deletions(-) create mode 100644 thermal_monitor/CMakeLists.txt create mode 100644 thermal_monitor/main.cpp create mode 100644 thermal_monitor/test/CMakeLists.txt create mode 100644 thermal_monitor/test/test_thermal_collector.cpp create mode 100644 thermal_monitor/thermal_collector.cpp create mode 100644 thermal_monitor/thermal_collector.h diff --git a/BUILD.md b/BUILD.md index 548542e27b..ce82dd01c8 100644 --- a/BUILD.md +++ b/BUILD.md @@ -218,7 +218,7 @@ See https://developer.android.com/ndk/guides/cmake#command-line for CMake NDK do # Build release binary for arm64-v8a cmake -S . -B build \ -D CMAKE_TOOLCHAIN_FILE=$ANDROID_NDK_HOME/build/cmake/android.toolchain.cmake \ - -D ANDROID_PLATFORM=29 \ + -D ANDROID_PLATFORM=31 \ -D CMAKE_ANDROID_ARCH_ABI=arm64-v8a \ -D CMAKE_ANDROID_STL_TYPE=c++_static \ -D ANDROID_USE_LEGACY_TOOLCHAIN_FILE=NO \ diff --git a/CMakeLists.txt b/CMakeLists.txt index 3787aa7618..71ddce6361 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -138,6 +138,10 @@ if(ANDROID) add_subdirectory(agi_launch_producer) endif() +if(ANDROID OR BUILD_TESTS) + add_subdirectory(thermal_monitor) +endif() + if(BUILD_LAYERMGR) if(NOT Qt6_FOUND) message("WARNING: Vulkan Configurator will be excluded from the build because Qt6 was not found. Please add Qt6 into the PATH environment variable") diff --git a/scripts/android.py b/scripts/android.py index db9bd09d63..942403d2bd 100755 --- a/scripts/android.py +++ b/scripts/android.py @@ -116,7 +116,7 @@ def main(): cmake_cmd += f' -D BUILD_TESTS={build_tests}' cmake_cmd += f' -D CMAKE_ANDROID_STL_TYPE=c++_static' - cmake_cmd += ' -D ANDROID_PLATFORM=29' + cmake_cmd += ' -D ANDROID_PLATFORM=31' cmake_cmd += ' -D ANDROID_USE_LEGACY_TOOLCHAIN_FILE=NO' RunShellCmd(cmake_cmd) diff --git a/thermal_monitor/CMakeLists.txt b/thermal_monitor/CMakeLists.txt new file mode 100644 index 0000000000..dfc0d248f0 --- /dev/null +++ b/thermal_monitor/CMakeLists.txt @@ -0,0 +1,35 @@ +# Copyright (C) 2026 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# The sampling policy has no Android dependencies, so it is also built on the host for the unit tests. +add_library(thermal_collector STATIC thermal_collector.cpp thermal_collector.h) +target_include_directories(thermal_collector PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) + +if(WIN32 AND (QT_TARGET_TYPE STREQUAL STATIC_LIBRARY)) + set_property(TARGET thermal_collector PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") +endif() + +if(ANDROID) + add_executable(thermal_monitor main.cpp) + target_link_libraries(thermal_monitor PRIVATE thermal_collector android log) + # AThermal_getThermalHeadroomThresholds() is API 35, above ANDROID_PLATFORM, so it is weakly + # linked and guarded by __builtin_available. + target_compile_definitions(thermal_monitor PRIVATE __ANDROID_UNAVAILABLE_SYMBOLS_ARE_WEAK__) + target_compile_options(thermal_monitor PRIVATE -Werror=unguarded-availability) + install(TARGETS thermal_monitor DESTINATION ${CMAKE_INSTALL_BINDIR}) +endif() + +if(BUILD_TESTS AND NOT ANDROID) + add_subdirectory(test) +endif() diff --git a/thermal_monitor/main.cpp b/thermal_monitor/main.cpp new file mode 100644 index 0000000000..9682e14df5 --- /dev/null +++ b/thermal_monitor/main.cpp @@ -0,0 +1,179 @@ +/* Copyright (C) 2026 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "thermal_collector.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace apa::thermal { +namespace { + +constexpr const char* kLogTag = "ThermalMonitor"; + +// Queries the Android framework's thermal state via the NDK AThermal API in libandroid.so. +// The binary targets API 31 (see scripts/android.py), which covers everything except +// AThermal_getThermalHeadroomThresholds() (API 35). That symbol is weakly linked +// (__ANDROID_UNAVAILABLE_SYMBOLS_ARE_WEAK__) and guarded by __builtin_available. +class NdkThermalSource final : public ThermalSource { + public: + NdkThermalSource() : manager_(AThermal_acquireManager()) {} + + ~NdkThermalSource() override { + if (manager_ != nullptr) { + AThermal_releaseManager(manager_); + } + } + + NdkThermalSource(const NdkThermalSource&) = delete; + NdkThermalSource& operator=(const NdkThermalSource&) = delete; + + [[nodiscard]] bool IsValid() const { return manager_ != nullptr; } + + std::optional ThermalStatus() override { + const AThermalStatus status = AThermal_getCurrentThermalStatus(manager_); + if (status <= ATHERMAL_STATUS_ERROR) { + return std::nullopt; + } + return static_cast(status); + } + + std::optional ThermalHeadroom(int forecast_seconds) override { + const float headroom = AThermal_getThermalHeadroom(manager_, forecast_seconds); + if (std::isnan(headroom)) { + return std::nullopt; + } + return static_cast(headroom); + } + + std::map ThermalHeadroomThresholds() override { + std::map result; + // Added in Android 15 (API 35). Older devices only get the SEVERE line, which the viewer + // derives from the API definition. + if (__builtin_available(android 35, *)) { + const AThermalHeadroomThreshold* thresholds = nullptr; + size_t size = 0; + if (AThermal_getThermalHeadroomThresholds(manager_, &thresholds, &size) != 0 || thresholds == nullptr) { + return result; + } + for (size_t i = 0; i < size; ++i) { + result[static_cast(thresholds[i].thermalStatus)] = static_cast(thresholds[i].headroom); + } + // The NDK allocates the array and documents that the client array-deletes it. + delete[] thresholds; + } + return result; + } + + private: + AThermalManager* manager_ = nullptr; +}; + +volatile std::sig_atomic_t g_stop_requested = 0; + +void HandleStopSignal(int /*signum*/) { g_stop_requested = 1; } + +std::optional ParseInt(std::string_view str) { + int value = 0; + const char* begin = str.data(); + const char* end = begin + str.size(); + const auto [ptr, ec] = std::from_chars(begin, end, value); + if (ec != std::errc() || ptr != end) { + return std::nullopt; + } + return value; +} + +struct Options { + int poll_interval_ms = ThermalConstants::kDefaultPollIntervalMs; + int forecast_seconds = ThermalConstants::kDefaultForecastSeconds; +}; + +// Reads the value that follows argv[*i] into *out, warning instead of silently keeping the default +// when it is missing or malformed. +void ParseIntOption(int argc, char** argv, int* i, int* out) { + const char* flag = argv[*i]; + if (*i + 1 >= argc) { + __android_log_print(ANDROID_LOG_WARN, kLogTag, "Missing value for %s", flag); + return; + } + const char* value = argv[++*i]; + if (const std::optional parsed = ParseInt(value); parsed.has_value()) { + *out = *parsed; + } else { + __android_log_print(ANDROID_LOG_WARN, kLogTag, "Ignoring invalid value '%s' for %s", value, flag); + } +} + +Options ParseOptions(int argc, char** argv) { + Options options; + for (int i = 1; i < argc; ++i) { + if (std::strcmp(argv[i], "--poll-interval-ms") == 0) { + ParseIntOption(argc, argv, &i, &options.poll_interval_ms); + } else if (std::strcmp(argv[i], "--forecast-seconds") == 0) { + ParseIntOption(argc, argv, &i, &options.forecast_seconds); + } else { + __android_log_print(ANDROID_LOG_WARN, kLogTag, "Ignoring unknown argument '%s'", argv[i]); + } + } + options.poll_interval_ms = std::max(options.poll_interval_ms, ThermalConstants::kMinPollIntervalMs); + options.forecast_seconds = std::clamp(options.forecast_seconds, 0, ThermalConstants::kMaxForecastSeconds); + return options; +} + +} // namespace +} // namespace apa::thermal + +int main(int argc, char** argv) { + using namespace apa::thermal; + + struct sigaction sa = {}; + sa.sa_handler = HandleStopSignal; + sigemptyset(&sa.sa_mask); + sigaction(SIGTERM, &sa, nullptr); + sigaction(SIGINT, &sa, nullptr); + + const Options options = ParseOptions(argc, argv); + + NdkThermalSource source; + if (!source.IsValid()) { + __android_log_print(ANDROID_LOG_WARN, kLogTag, "AThermalManager is unavailable on this device"); + return 0; + } + + ThermalCollector collector( + source, [](const char* name, int64_t value) { ATrace_setCounter(name, value); }, options.forecast_seconds); + + while (!g_stop_requested) { + collector.Sample(); + if (g_stop_requested) { + break; + } + poll(nullptr, 0, options.poll_interval_ms); + } + + return 0; +} diff --git a/thermal_monitor/test/CMakeLists.txt b/thermal_monitor/test/CMakeLists.txt new file mode 100644 index 0000000000..6da0645ae1 --- /dev/null +++ b/thermal_monitor/test/CMakeLists.txt @@ -0,0 +1,22 @@ +# Copyright (C) 2026 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +add_executable(test_thermal_collector test_thermal_collector.cpp) +target_link_libraries(test_thermal_collector PRIVATE thermal_collector GTest::gtest GTest::gtest_main) +add_test(NAME test_thermal_collector COMMAND test_thermal_collector) +set_target_properties(test_thermal_collector PROPERTIES FOLDER "thermal_monitor/Test") + +if(WIN32 AND (QT_TARGET_TYPE STREQUAL STATIC_LIBRARY)) + set_property(TARGET test_thermal_collector PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") +endif() diff --git a/thermal_monitor/test/test_thermal_collector.cpp b/thermal_monitor/test/test_thermal_collector.cpp new file mode 100644 index 0000000000..020a668bd2 --- /dev/null +++ b/thermal_monitor/test/test_thermal_collector.cpp @@ -0,0 +1,270 @@ +/* Copyright (C) 2026 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "thermal_collector.h" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace apa::thermal { +namespace { + +using CounterSample = std::pair; + +class FakeThermalSource final : public ThermalSource { + public: + FakeThermalSource(std::optional status, std::optional headroom, std::optional forecast = std::nullopt, + std::map thresholds = {}) + : status_(status), headroom_(headroom), forecast_(forecast), thresholds_(std::move(thresholds)) {} + + std::optional ThermalStatus() override { return status_; } + + std::optional ThermalHeadroom(int forecast_seconds) override { + headroom_queries_.push_back(forecast_seconds); + return forecast_seconds == 0 ? headroom_ : forecast_; + } + + std::map ThermalHeadroomThresholds() override { + ++thresholds_read_count_; + return thresholds_; + } + + int ThresholdsReadCount() const { return thresholds_read_count_; } + + const std::vector& HeadroomQueries() const { return headroom_queries_; } + + private: + std::optional status_; + std::optional headroom_; + std::optional forecast_; + std::map thresholds_; + int thresholds_read_count_ = 0; + std::vector headroom_queries_; +}; + +// Tests for ThermalCollector's sampling policy, which is the part that has to cope with what real +// devices actually report. +class ThermalCollectorTest : public ::testing::Test { + protected: + std::vector emitted_; + ThermalCollector::Emitter emitter_ = [this](const char* name, int64_t value) { emitted_.emplace_back(name, value); }; +}; + +TEST_F(ThermalCollectorTest, InterleavesCurrentAndForecastHeadroomOnAlternatingTicks) { + FakeThermalSource source(/*status=*/2, /*headroom=*/0.93, /*forecast=*/1.04); + ThermalCollector collector(source, emitter_, /*forecast_seconds=*/10); + + collector.Sample(); + collector.Sample(); + collector.Sample(); + + EXPECT_EQ(source.HeadroomQueries(), (std::vector{0, 10, 0})); + const std::vector expected = { + {ThermalConstants::kStatusCounter, 2}, {ThermalConstants::kHeadroomCounter, 930}, + {ThermalConstants::kStatusCounter, 2}, {ThermalConstants::kHeadroomForecastCounter, 1040}, + {ThermalConstants::kStatusCounter, 2}, {ThermalConstants::kHeadroomCounter, 930}, + }; + EXPECT_EQ(emitted_, expected); +} + +TEST_F(ThermalCollectorTest, DisablesForecastWhenHorizonIsZero) { + FakeThermalSource source(/*status=*/1, /*headroom=*/0.8, /*forecast=*/0.9); + ThermalCollector collector(source, emitter_, /*forecast_seconds=*/0); + + collector.Sample(); + collector.Sample(); + + EXPECT_EQ(source.HeadroomQueries(), (std::vector{0, 0})); + const std::vector expected = { + {ThermalConstants::kStatusCounter, 1}, + {ThermalConstants::kHeadroomCounter, 800}, + {ThermalConstants::kStatusCounter, 1}, + {ThermalConstants::kHeadroomCounter, 800}, + }; + EXPECT_EQ(emitted_, expected); +} + +TEST_F(ThermalCollectorTest, SkipsFailedForecastTickWithoutRetryingCurrentHeadroom) { + FakeThermalSource source(/*status=*/1, /*headroom=*/0.8, /*forecast=*/std::nullopt); + ThermalCollector collector(source, emitter_, /*forecast_seconds=*/10); + + collector.Sample(); + collector.Sample(); + + // Retrying the current headroom on the failed forecast tick would hit the ~1 Hz rate limit. + EXPECT_EQ(source.HeadroomQueries(), (std::vector{0, 10})); + const std::vector expected = { + {ThermalConstants::kStatusCounter, 1}, + {ThermalConstants::kHeadroomCounter, 800}, + {ThermalConstants::kStatusCounter, 1}, + }; + EXPECT_EQ(emitted_, expected); +} + +TEST_F(ThermalCollectorTest, DropsForecastOnlyAfterRepeatedFailures) { + FakeThermalSource source(/*status=*/std::nullopt, /*headroom=*/0.8, /*forecast=*/std::nullopt); + ThermalCollector collector(source, emitter_, /*forecast_seconds=*/10); + + for (int i = 0; i < 9; ++i) { + collector.Sample(); + } + + // Three failed forecast ticks (1, 3, 5) disable the forecast; after that every tick is current. + EXPECT_EQ(source.HeadroomQueries(), (std::vector{0, 10, 0, 10, 0, 10, 0, 0, 0})); +} + +TEST_F(ThermalCollectorTest, KeepsForecastAfterTransientFailures) { + // Each fake failure is followed by a success, so the failure count never reaches the limit. + class FlakyForecastSource final : public ThermalSource { + public: + std::optional ThermalStatus() override { return std::nullopt; } + std::optional ThermalHeadroom(int forecast_seconds) override { + if (forecast_seconds == 0) { + return 0.8; + } + return (forecast_calls_++ % 2) == 0 ? std::nullopt : std::optional(0.9); + } + std::map ThermalHeadroomThresholds() override { return {}; } + + private: + int forecast_calls_ = 0; + } source; + ThermalCollector collector(source, emitter_, /*forecast_seconds=*/10); + + for (int i = 0; i < 12; ++i) { + collector.Sample(); + } + + const std::vector expected = { + {ThermalConstants::kHeadroomCounter, 800}, {ThermalConstants::kHeadroomCounter, 800}, + {ThermalConstants::kHeadroomForecastCounter, 900}, {ThermalConstants::kHeadroomCounter, 800}, + {ThermalConstants::kHeadroomCounter, 800}, {ThermalConstants::kHeadroomForecastCounter, 900}, + {ThermalConstants::kHeadroomCounter, 800}, {ThermalConstants::kHeadroomCounter, 800}, + {ThermalConstants::kHeadroomForecastCounter, 900}, + }; + EXPECT_EQ(emitted_, expected); +} + +TEST_F(ThermalCollectorTest, KeepsThreeDecimalPlacesOfHeadroom) { + // The Galaxy S25 puts LIGHT at 0.867 and MODERATE at 0.933, so rounding to hundredths would + // merge distinguishable states. + FakeThermalSource source(/*status=*/0, /*headroom=*/0.8674); + ThermalCollector(source, emitter_).Sample(); + + ASSERT_EQ(emitted_.size(), 2u); + EXPECT_EQ(emitted_[1], CounterSample(ThermalConstants::kHeadroomCounter, 867)); +} + +TEST_F(ThermalCollectorTest, OmitsHeadroomEntirelyOnDeviceThatDoesNotReportIt) { + FakeThermalSource source( + /*status=*/1, + /*headroom=*/std::nullopt, + /*forecast=*/std::nullopt, + /*thresholds=*/{{1, 0.7}}); + ThermalCollector collector(source, emitter_); + + collector.Sample(); + + // A status track and no headroom track, rather than a headroom track full of a sentinel the + // host would have to strip. Thresholds are also suppressed when headroom is absent. + const std::vector expected = { + {ThermalConstants::kStatusCounter, 1}, + }; + EXPECT_EQ(emitted_, expected); +} + +TEST_F(ThermalCollectorTest, IgnoresNonFiniteOrNegativeHeadroom) { + FakeThermalSource nan_source( + /*status=*/1, + /*headroom=*/std::numeric_limits::quiet_NaN(), + /*forecast=*/std::nullopt, + /*thresholds=*/{{1, 0.7}}); + ThermalCollector(nan_source, emitter_).Sample(); + + FakeThermalSource negative_source( + /*status=*/1, + /*headroom=*/-1.0, + /*forecast=*/-1.0, + /*thresholds=*/{{1, 0.7}}); + ThermalCollector negative_collector(negative_source, emitter_, /*forecast_seconds=*/10); + negative_collector.Sample(); + negative_collector.Sample(); + + // A rejected forecast tick emits no headroom rather than retrying the current headroom. + EXPECT_EQ(negative_source.HeadroomQueries(), (std::vector{0, 10})); + const std::vector expected = { + {ThermalConstants::kStatusCounter, 1}, + {ThermalConstants::kStatusCounter, 1}, + {ThermalConstants::kStatusCounter, 1}, + }; + EXPECT_EQ(emitted_, expected); +} + +TEST_F(ThermalCollectorTest, OmitsStatusOnDeviceThatDoesNotReportIt) { + FakeThermalSource source(/*status=*/std::nullopt, /*headroom=*/0.5); + ThermalCollector collector(source, emitter_); + + collector.Sample(); + + const std::vector expected = { + {ThermalConstants::kHeadroomCounter, 500}, + }; + EXPECT_EQ(emitted_, expected); +} + +TEST_F(ThermalCollectorTest, ReadsThresholdsOnceAndReEmitsWithCurrentHeadroomOnly) { + // The Galaxy S25 reports SEVERE as NaN even though LIGHT and MODERATE are populated. + FakeThermalSource source( + /*status=*/0, + /*headroom=*/0.8, + /*forecast=*/0.9, + /*thresholds=*/ + { + {0, 0.0}, + {1, 0.867}, + {2, 0.933}, + {3, std::numeric_limits::quiet_NaN()}, + }); + ThermalCollector collector(source, emitter_, /*forecast_seconds=*/10); + + collector.Sample(); + collector.Sample(); + collector.Sample(); + + EXPECT_EQ(source.ThresholdsReadCount(), 1); + const std::vector expected = { + {ThermalConstants::kStatusCounter, 0}, + {ThermalConstants::kHeadroomCounter, 800}, + {"sherlock.thermal.headroom.threshold.light", 867}, + {"sherlock.thermal.headroom.threshold.moderate", 933}, + {ThermalConstants::kStatusCounter, 0}, + {ThermalConstants::kHeadroomForecastCounter, 900}, + {ThermalConstants::kStatusCounter, 0}, + {ThermalConstants::kHeadroomCounter, 800}, + {"sherlock.thermal.headroom.threshold.light", 867}, + {"sherlock.thermal.headroom.threshold.moderate", 933}, + }; + EXPECT_EQ(emitted_, expected); +} + +} // namespace +} // namespace apa::thermal diff --git a/thermal_monitor/thermal_collector.cpp b/thermal_monitor/thermal_collector.cpp new file mode 100644 index 0000000000..fef07a955c --- /dev/null +++ b/thermal_monitor/thermal_collector.cpp @@ -0,0 +1,70 @@ +/* Copyright (C) 2026 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "thermal_collector.h" + +#include +#include + +namespace apa::thermal { + +ThermalCollector::ThermalCollector(ThermalSource& source, Emitter emit, int forecast_seconds) + : source_(source), emit_(std::move(emit)), forecast_seconds_(forecast_seconds), forecast_supported_(forecast_seconds > 0) {} + +void ThermalCollector::Sample() { + if (const std::optional status = source_.ThermalStatus(); status.has_value()) { + emit_(ThermalConstants::kStatusCounter, static_cast(*status)); + } + if (forecast_supported_ && (tick_++ % 2) == 1) { + if (EmitHeadroom(ThermalConstants::kHeadroomForecastCounter, source_.ThermalHeadroom(forecast_seconds_))) { + forecast_failures_ = 0; + } else if (++forecast_failures_ >= kMaxForecastFailures) { + forecast_supported_ = false; + } + return; + } + if (EmitHeadroom(ThermalConstants::kHeadroomCounter, source_.ThermalHeadroom(0))) { + for (const auto& [name, value] : GetThresholds()) { + EmitHeadroom(name, value); + } + } +} + +const ThermalCollector::ThresholdList& ThermalCollector::GetThresholds() { + if (!thresholds_.has_value()) { + ThresholdList resolved; + for (const auto& [status, value] : source_.ThermalHeadroomThresholds()) { + const char* name = ThermalConstants::ThresholdCounterName(status); + if (name != nullptr) { + resolved.emplace_back(name, value); + } + } + thresholds_ = std::move(resolved); + } + return *thresholds_; +} + +bool ThermalCollector::EmitHeadroom(const char* counter, std::optional headroom) { + // Headroom is 1.0 at SEVERE throttling, so values this large are bogus; the cap also keeps the + // scaled value well inside the range of std::llround. + constexpr double kMaxHeadroom = 1e6; + if (!headroom.has_value() || !std::isfinite(*headroom) || *headroom < 0.0 || *headroom > kMaxHeadroom) { + return false; + } + emit_(counter, std::llround(*headroom * ThermalConstants::kHeadroomScale)); + return true; +} + +} // namespace apa::thermal diff --git a/thermal_monitor/thermal_collector.h b/thermal_monitor/thermal_collector.h new file mode 100644 index 0000000000..9f66bacd6e --- /dev/null +++ b/thermal_monitor/thermal_collector.h @@ -0,0 +1,115 @@ +/* Copyright (C) 2026 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace apa::thermal { + +// Must match the counter names and scale that the Android Performance Analyzer trace viewer reads. +namespace ThermalConstants { +inline constexpr int kDefaultPollIntervalMs = 1000; +// Polling faster than this would only collect NaNs from the ~1 Hz rate-limited headroom API. +inline constexpr int kMinPollIntervalMs = kDefaultPollIntervalMs; +inline constexpr int kDefaultForecastSeconds = 10; +inline constexpr int kMaxForecastSeconds = 60; +inline constexpr const char* kHeadroomCounter = "sherlock.thermal.headroom"; +inline constexpr const char* kHeadroomForecastCounter = "sherlock.thermal.headroom.forecast"; +inline constexpr const char* kStatusCounter = "sherlock.thermal.status"; +// Atrace counters are integers, so headroom values are emitted multiplied by this. +inline constexpr int64_t kHeadroomScale = 1000; + +// Counter names for the AThermalStatus / PowerManager.THERMAL_STATUS_* values that can carry a +// headroom threshold. +inline constexpr const char* ThresholdCounterName(int status) { + switch (status) { + case 1: + return "sherlock.thermal.headroom.threshold.light"; + case 2: + return "sherlock.thermal.headroom.threshold.moderate"; + case 3: + return "sherlock.thermal.headroom.threshold.severe"; + case 4: + return "sherlock.thermal.headroom.threshold.critical"; + case 5: + return "sherlock.thermal.headroom.threshold.emergency"; + case 6: + return "sherlock.thermal.headroom.threshold.shutdown"; + default: + return nullptr; + } +} +} // namespace ThermalConstants + +// Reads framework thermal signals (AThermal / PowerManager). Abstracted so ThermalCollector can be +// unit tested without a device. +class ThermalSource { + public: + virtual ~ThermalSource() = default; + + virtual std::optional ThermalStatus() = 0; + + // AThermal_getThermalHeadroom(forecast_seconds); 0 asks for the current headroom. + virtual std::optional ThermalHeadroom(int forecast_seconds) = 0; + + // Headroom at which each THERMAL_STATUS_* starts, or empty if the device or OS version cannot + // report it. + virtual std::map ThermalHeadroomThresholds() = 0; +}; + +// Samples the framework's thermal state and emits it as trace counters. +// AThermal_getThermalHeadroom() is rate-limited to ~1 Hz across all forecast_seconds values, which +// is why ThermalConstants::kDefaultPollIntervalMs is one second and why, when forecast_seconds is +// positive, current and forecast headroom are sampled on alternating ticks rather than on the same +// tick. A forecast tick that fails emits no headroom at all rather than retrying the current +// headroom, which the rate limit would reject. +class ThermalCollector { + public: + using Emitter = std::function; + + ThermalCollector(ThermalSource& source, Emitter emit, int forecast_seconds = ThermalConstants::kDefaultForecastSeconds); + + void Sample(); + + private: + using ThresholdList = std::vector>; + + // AThermal_getThermalHeadroom() also returns NaN when it is called too often or the thermal + // service hiccups, so one failure does not prove that the device cannot forecast. + static constexpr int kMaxForecastFailures = 3; + + // The thresholds are static for a device, so they are read from source_ once, but re-emitted + // with every headroom sample because the monitor starts before tracing does and a one-off + // emission at startup would not land in the trace. + const ThresholdList& GetThresholds(); + + bool EmitHeadroom(const char* counter, std::optional headroom); + + ThermalSource& source_; + Emitter emit_; + int forecast_seconds_; + std::optional thresholds_; + int tick_ = 0; + int forecast_failures_ = 0; + bool forecast_supported_; +}; + +} // namespace apa::thermal From 235b7fedced0ea88b2031091d2dcf1dabc37421e Mon Sep 17 00:00:00 2001 From: jimblackler Date: Thu, 5 Nov 2026 11:09:31 +0000 Subject: [PATCH 2/5] thermal_monitor: Address review feedback on PR #55 - Return a ThermalStatus enum from ThermalSource::CurrentThermalStatus() instead of int. It mirrors AThermalStatus, which the host test build cannot include, and main.cpp static_asserts that the values match. Threshold maps and ThresholdCounterName() are keyed by it too. - Carry headroom as float, as the NDK returns it, instead of double. - Document the headroom range of ThermalSource::ThermalHeadroom(). - Reword the comment on AThermal_getThermalHeadroomThresholds() so it only describes what the monitor does on older Android versions. - Rename ThermalCollector's emit / emit_ to emitter / emitter_. --- thermal_monitor/main.cpp | 31 +++++--- .../test/test_thermal_collector.cpp | 72 +++++++++---------- thermal_monitor/thermal_collector.cpp | 19 ++--- thermal_monitor/thermal_collector.h | 52 +++++++++----- 4 files changed, 102 insertions(+), 72 deletions(-) diff --git a/thermal_monitor/main.cpp b/thermal_monitor/main.cpp index 9682e14df5..bbe142363b 100644 --- a/thermal_monitor/main.cpp +++ b/thermal_monitor/main.cpp @@ -34,6 +34,14 @@ namespace { constexpr const char* kLogTag = "ThermalMonitor"; +static_assert(static_cast(ThermalStatus::kNone) == ATHERMAL_STATUS_NONE); +static_assert(static_cast(ThermalStatus::kLight) == ATHERMAL_STATUS_LIGHT); +static_assert(static_cast(ThermalStatus::kModerate) == ATHERMAL_STATUS_MODERATE); +static_assert(static_cast(ThermalStatus::kSevere) == ATHERMAL_STATUS_SEVERE); +static_assert(static_cast(ThermalStatus::kCritical) == ATHERMAL_STATUS_CRITICAL); +static_assert(static_cast(ThermalStatus::kEmergency) == ATHERMAL_STATUS_EMERGENCY); +static_assert(static_cast(ThermalStatus::kShutdown) == ATHERMAL_STATUS_SHUTDOWN); + // Queries the Android framework's thermal state via the NDK AThermal API in libandroid.so. // The binary targets API 31 (see scripts/android.py), which covers everything except // AThermal_getThermalHeadroomThresholds() (API 35). That symbol is weakly linked @@ -53,26 +61,26 @@ class NdkThermalSource final : public ThermalSource { [[nodiscard]] bool IsValid() const { return manager_ != nullptr; } - std::optional ThermalStatus() override { + std::optional CurrentThermalStatus() override { const AThermalStatus status = AThermal_getCurrentThermalStatus(manager_); - if (status <= ATHERMAL_STATUS_ERROR) { + if (status < ATHERMAL_STATUS_NONE || status > ATHERMAL_STATUS_SHUTDOWN) { return std::nullopt; } - return static_cast(status); + return static_cast(status); } - std::optional ThermalHeadroom(int forecast_seconds) override { + std::optional ThermalHeadroom(int forecast_seconds) override { const float headroom = AThermal_getThermalHeadroom(manager_, forecast_seconds); if (std::isnan(headroom)) { return std::nullopt; } - return static_cast(headroom); + return headroom; } - std::map ThermalHeadroomThresholds() override { - std::map result; - // Added in Android 15 (API 35). Older devices only get the SEVERE line, which the viewer - // derives from the API definition. + std::map ThermalHeadroomThresholds() override { + std::map result; + // AThermal_getThermalHeadroomThresholds() was added in Android 15 (API 35). Older versions + // cannot report thresholds, so they get an empty map. if (__builtin_available(android 35, *)) { const AThermalHeadroomThreshold* thresholds = nullptr; size_t size = 0; @@ -80,7 +88,10 @@ class NdkThermalSource final : public ThermalSource { return result; } for (size_t i = 0; i < size; ++i) { - result[static_cast(thresholds[i].thermalStatus)] = static_cast(thresholds[i].headroom); + const AThermalStatus status = thresholds[i].thermalStatus; + if (status >= ATHERMAL_STATUS_NONE && status <= ATHERMAL_STATUS_SHUTDOWN) { + result[static_cast(status)] = thresholds[i].headroom; + } } // The NDK allocates the array and documents that the client array-deletes it. delete[] thresholds; diff --git a/thermal_monitor/test/test_thermal_collector.cpp b/thermal_monitor/test/test_thermal_collector.cpp index 020a668bd2..c039539e81 100644 --- a/thermal_monitor/test/test_thermal_collector.cpp +++ b/thermal_monitor/test/test_thermal_collector.cpp @@ -32,18 +32,18 @@ using CounterSample = std::pair; class FakeThermalSource final : public ThermalSource { public: - FakeThermalSource(std::optional status, std::optional headroom, std::optional forecast = std::nullopt, - std::map thresholds = {}) + FakeThermalSource(std::optional status, std::optional headroom, + std::optional forecast = std::nullopt, std::map thresholds = {}) : status_(status), headroom_(headroom), forecast_(forecast), thresholds_(std::move(thresholds)) {} - std::optional ThermalStatus() override { return status_; } + std::optional CurrentThermalStatus() override { return status_; } - std::optional ThermalHeadroom(int forecast_seconds) override { + std::optional ThermalHeadroom(int forecast_seconds) override { headroom_queries_.push_back(forecast_seconds); return forecast_seconds == 0 ? headroom_ : forecast_; } - std::map ThermalHeadroomThresholds() override { + std::map ThermalHeadroomThresholds() override { ++thresholds_read_count_; return thresholds_; } @@ -53,10 +53,10 @@ class FakeThermalSource final : public ThermalSource { const std::vector& HeadroomQueries() const { return headroom_queries_; } private: - std::optional status_; - std::optional headroom_; - std::optional forecast_; - std::map thresholds_; + std::optional status_; + std::optional headroom_; + std::optional forecast_; + std::map thresholds_; int thresholds_read_count_ = 0; std::vector headroom_queries_; }; @@ -70,7 +70,7 @@ class ThermalCollectorTest : public ::testing::Test { }; TEST_F(ThermalCollectorTest, InterleavesCurrentAndForecastHeadroomOnAlternatingTicks) { - FakeThermalSource source(/*status=*/2, /*headroom=*/0.93, /*forecast=*/1.04); + FakeThermalSource source(/*status=*/ThermalStatus::kModerate, /*headroom=*/0.93f, /*forecast=*/1.04f); ThermalCollector collector(source, emitter_, /*forecast_seconds=*/10); collector.Sample(); @@ -87,7 +87,7 @@ TEST_F(ThermalCollectorTest, InterleavesCurrentAndForecastHeadroomOnAlternatingT } TEST_F(ThermalCollectorTest, DisablesForecastWhenHorizonIsZero) { - FakeThermalSource source(/*status=*/1, /*headroom=*/0.8, /*forecast=*/0.9); + FakeThermalSource source(/*status=*/ThermalStatus::kLight, /*headroom=*/0.8f, /*forecast=*/0.9f); ThermalCollector collector(source, emitter_, /*forecast_seconds=*/0); collector.Sample(); @@ -104,7 +104,7 @@ TEST_F(ThermalCollectorTest, DisablesForecastWhenHorizonIsZero) { } TEST_F(ThermalCollectorTest, SkipsFailedForecastTickWithoutRetryingCurrentHeadroom) { - FakeThermalSource source(/*status=*/1, /*headroom=*/0.8, /*forecast=*/std::nullopt); + FakeThermalSource source(/*status=*/ThermalStatus::kLight, /*headroom=*/0.8f, /*forecast=*/std::nullopt); ThermalCollector collector(source, emitter_, /*forecast_seconds=*/10); collector.Sample(); @@ -121,7 +121,7 @@ TEST_F(ThermalCollectorTest, SkipsFailedForecastTickWithoutRetryingCurrentHeadro } TEST_F(ThermalCollectorTest, DropsForecastOnlyAfterRepeatedFailures) { - FakeThermalSource source(/*status=*/std::nullopt, /*headroom=*/0.8, /*forecast=*/std::nullopt); + FakeThermalSource source(/*status=*/std::nullopt, /*headroom=*/0.8f, /*forecast=*/std::nullopt); ThermalCollector collector(source, emitter_, /*forecast_seconds=*/10); for (int i = 0; i < 9; ++i) { @@ -136,14 +136,14 @@ TEST_F(ThermalCollectorTest, KeepsForecastAfterTransientFailures) { // Each fake failure is followed by a success, so the failure count never reaches the limit. class FlakyForecastSource final : public ThermalSource { public: - std::optional ThermalStatus() override { return std::nullopt; } - std::optional ThermalHeadroom(int forecast_seconds) override { + std::optional CurrentThermalStatus() override { return std::nullopt; } + std::optional ThermalHeadroom(int forecast_seconds) override { if (forecast_seconds == 0) { - return 0.8; + return 0.8f; } - return (forecast_calls_++ % 2) == 0 ? std::nullopt : std::optional(0.9); + return (forecast_calls_++ % 2) == 0 ? std::nullopt : std::optional(0.9f); } - std::map ThermalHeadroomThresholds() override { return {}; } + std::map ThermalHeadroomThresholds() override { return {}; } private: int forecast_calls_ = 0; @@ -167,7 +167,7 @@ TEST_F(ThermalCollectorTest, KeepsForecastAfterTransientFailures) { TEST_F(ThermalCollectorTest, KeepsThreeDecimalPlacesOfHeadroom) { // The Galaxy S25 puts LIGHT at 0.867 and MODERATE at 0.933, so rounding to hundredths would // merge distinguishable states. - FakeThermalSource source(/*status=*/0, /*headroom=*/0.8674); + FakeThermalSource source(/*status=*/ThermalStatus::kNone, /*headroom=*/0.8674f); ThermalCollector(source, emitter_).Sample(); ASSERT_EQ(emitted_.size(), 2u); @@ -176,10 +176,10 @@ TEST_F(ThermalCollectorTest, KeepsThreeDecimalPlacesOfHeadroom) { TEST_F(ThermalCollectorTest, OmitsHeadroomEntirelyOnDeviceThatDoesNotReportIt) { FakeThermalSource source( - /*status=*/1, + /*status=*/ThermalStatus::kLight, /*headroom=*/std::nullopt, /*forecast=*/std::nullopt, - /*thresholds=*/{{1, 0.7}}); + /*thresholds=*/{{ThermalStatus::kLight, 0.7f}}); ThermalCollector collector(source, emitter_); collector.Sample(); @@ -194,17 +194,17 @@ TEST_F(ThermalCollectorTest, OmitsHeadroomEntirelyOnDeviceThatDoesNotReportIt) { TEST_F(ThermalCollectorTest, IgnoresNonFiniteOrNegativeHeadroom) { FakeThermalSource nan_source( - /*status=*/1, - /*headroom=*/std::numeric_limits::quiet_NaN(), + /*status=*/ThermalStatus::kLight, + /*headroom=*/std::numeric_limits::quiet_NaN(), /*forecast=*/std::nullopt, - /*thresholds=*/{{1, 0.7}}); + /*thresholds=*/{{ThermalStatus::kLight, 0.7f}}); ThermalCollector(nan_source, emitter_).Sample(); FakeThermalSource negative_source( - /*status=*/1, - /*headroom=*/-1.0, - /*forecast=*/-1.0, - /*thresholds=*/{{1, 0.7}}); + /*status=*/ThermalStatus::kLight, + /*headroom=*/-1.0f, + /*forecast=*/-1.0f, + /*thresholds=*/{{ThermalStatus::kLight, 0.7f}}); ThermalCollector negative_collector(negative_source, emitter_, /*forecast_seconds=*/10); negative_collector.Sample(); negative_collector.Sample(); @@ -220,7 +220,7 @@ TEST_F(ThermalCollectorTest, IgnoresNonFiniteOrNegativeHeadroom) { } TEST_F(ThermalCollectorTest, OmitsStatusOnDeviceThatDoesNotReportIt) { - FakeThermalSource source(/*status=*/std::nullopt, /*headroom=*/0.5); + FakeThermalSource source(/*status=*/std::nullopt, /*headroom=*/0.5f); ThermalCollector collector(source, emitter_); collector.Sample(); @@ -234,15 +234,15 @@ TEST_F(ThermalCollectorTest, OmitsStatusOnDeviceThatDoesNotReportIt) { TEST_F(ThermalCollectorTest, ReadsThresholdsOnceAndReEmitsWithCurrentHeadroomOnly) { // The Galaxy S25 reports SEVERE as NaN even though LIGHT and MODERATE are populated. FakeThermalSource source( - /*status=*/0, - /*headroom=*/0.8, - /*forecast=*/0.9, + /*status=*/ThermalStatus::kNone, + /*headroom=*/0.8f, + /*forecast=*/0.9f, /*thresholds=*/ { - {0, 0.0}, - {1, 0.867}, - {2, 0.933}, - {3, std::numeric_limits::quiet_NaN()}, + {ThermalStatus::kNone, 0.0f}, + {ThermalStatus::kLight, 0.867f}, + {ThermalStatus::kModerate, 0.933f}, + {ThermalStatus::kSevere, std::numeric_limits::quiet_NaN()}, }); ThermalCollector collector(source, emitter_, /*forecast_seconds=*/10); diff --git a/thermal_monitor/thermal_collector.cpp b/thermal_monitor/thermal_collector.cpp index fef07a955c..a82a6fa4c4 100644 --- a/thermal_monitor/thermal_collector.cpp +++ b/thermal_monitor/thermal_collector.cpp @@ -20,12 +20,15 @@ namespace apa::thermal { -ThermalCollector::ThermalCollector(ThermalSource& source, Emitter emit, int forecast_seconds) - : source_(source), emit_(std::move(emit)), forecast_seconds_(forecast_seconds), forecast_supported_(forecast_seconds > 0) {} +ThermalCollector::ThermalCollector(ThermalSource& source, Emitter emitter, int forecast_seconds) + : source_(source), + emitter_(std::move(emitter)), + forecast_seconds_(forecast_seconds), + forecast_supported_(forecast_seconds > 0) {} void ThermalCollector::Sample() { - if (const std::optional status = source_.ThermalStatus(); status.has_value()) { - emit_(ThermalConstants::kStatusCounter, static_cast(*status)); + if (const std::optional status = source_.CurrentThermalStatus(); status.has_value()) { + emitter_(ThermalConstants::kStatusCounter, static_cast(*status)); } if (forecast_supported_ && (tick_++ % 2) == 1) { if (EmitHeadroom(ThermalConstants::kHeadroomForecastCounter, source_.ThermalHeadroom(forecast_seconds_))) { @@ -56,14 +59,14 @@ const ThermalCollector::ThresholdList& ThermalCollector::GetThresholds() { return *thresholds_; } -bool ThermalCollector::EmitHeadroom(const char* counter, std::optional headroom) { +bool ThermalCollector::EmitHeadroom(const char* counter, std::optional headroom) { // Headroom is 1.0 at SEVERE throttling, so values this large are bogus; the cap also keeps the // scaled value well inside the range of std::llround. - constexpr double kMaxHeadroom = 1e6; - if (!headroom.has_value() || !std::isfinite(*headroom) || *headroom < 0.0 || *headroom > kMaxHeadroom) { + constexpr float kMaxHeadroom = 1e6f; + if (!headroom.has_value() || !std::isfinite(*headroom) || *headroom < 0.0f || *headroom > kMaxHeadroom) { return false; } - emit_(counter, std::llround(*headroom * ThermalConstants::kHeadroomScale)); + emitter_(counter, std::llround(*headroom * ThermalConstants::kHeadroomScale)); return true; } diff --git a/thermal_monitor/thermal_collector.h b/thermal_monitor/thermal_collector.h index 9f66bacd6e..e0fe3a96df 100644 --- a/thermal_monitor/thermal_collector.h +++ b/thermal_monitor/thermal_collector.h @@ -24,6 +24,18 @@ namespace apa::thermal { +// Mirrors AThermalStatus from , which is not available in the host build that +// unit tests ThermalCollector. main.cpp static_asserts that the values match. +enum class ThermalStatus : int { + kNone = 0, + kLight = 1, + kModerate = 2, + kSevere = 3, + kCritical = 4, + kEmergency = 5, + kShutdown = 6, +}; + // Must match the counter names and scale that the Android Performance Analyzer trace viewer reads. namespace ThermalConstants { inline constexpr int kDefaultPollIntervalMs = 1000; @@ -37,21 +49,20 @@ inline constexpr const char* kStatusCounter = "sherlock.thermal.status"; // Atrace counters are integers, so headroom values are emitted multiplied by this. inline constexpr int64_t kHeadroomScale = 1000; -// Counter names for the AThermalStatus / PowerManager.THERMAL_STATUS_* values that can carry a -// headroom threshold. -inline constexpr const char* ThresholdCounterName(int status) { +// Counter names for the thermal statuses that can carry a headroom threshold. +inline constexpr const char* ThresholdCounterName(ThermalStatus status) { switch (status) { - case 1: + case ThermalStatus::kLight: return "sherlock.thermal.headroom.threshold.light"; - case 2: + case ThermalStatus::kModerate: return "sherlock.thermal.headroom.threshold.moderate"; - case 3: + case ThermalStatus::kSevere: return "sherlock.thermal.headroom.threshold.severe"; - case 4: + case ThermalStatus::kCritical: return "sherlock.thermal.headroom.threshold.critical"; - case 5: + case ThermalStatus::kEmergency: return "sherlock.thermal.headroom.threshold.emergency"; - case 6: + case ThermalStatus::kShutdown: return "sherlock.thermal.headroom.threshold.shutdown"; default: return nullptr; @@ -65,14 +76,19 @@ class ThermalSource { public: virtual ~ThermalSource() = default; - virtual std::optional ThermalStatus() = 0; + // AThermal_getCurrentThermalStatus(), or nullopt if the device cannot report it. + virtual std::optional CurrentThermalStatus() = 0; - // AThermal_getThermalHeadroom(forecast_seconds); 0 asks for the current headroom. - virtual std::optional ThermalHeadroom(int forecast_seconds) = 0; + // AThermal_getThermalHeadroom(forecast_seconds); 0 asks for the current headroom. The returned + // headroom is 0.0 with no thermal load and rises with it: 1.0 means the device is (or, for a + // forecast, will be) throttled at ThermalStatus::kSevere, and values above 1.0 mean it is + // throttled beyond kSevere. Returns nullopt if the API returns NaN, e.g. when the device does + // not support headroom or the call was rate-limited. + virtual std::optional ThermalHeadroom(int forecast_seconds) = 0; - // Headroom at which each THERMAL_STATUS_* starts, or empty if the device or OS version cannot + // Headroom at which each thermal status starts, or empty if the device or OS version cannot // report it. - virtual std::map ThermalHeadroomThresholds() = 0; + virtual std::map ThermalHeadroomThresholds() = 0; }; // Samples the framework's thermal state and emits it as trace counters. @@ -85,12 +101,12 @@ class ThermalCollector { public: using Emitter = std::function; - ThermalCollector(ThermalSource& source, Emitter emit, int forecast_seconds = ThermalConstants::kDefaultForecastSeconds); + ThermalCollector(ThermalSource& source, Emitter emitter, int forecast_seconds = ThermalConstants::kDefaultForecastSeconds); void Sample(); private: - using ThresholdList = std::vector>; + using ThresholdList = std::vector>; // AThermal_getThermalHeadroom() also returns NaN when it is called too often or the thermal // service hiccups, so one failure does not prove that the device cannot forecast. @@ -101,10 +117,10 @@ class ThermalCollector { // emission at startup would not land in the trace. const ThresholdList& GetThresholds(); - bool EmitHeadroom(const char* counter, std::optional headroom); + bool EmitHeadroom(const char* counter, std::optional headroom); ThermalSource& source_; - Emitter emit_; + Emitter emitter_; int forecast_seconds_; std::optional thresholds_; int tick_ = 0; From 69c5994abd6e0c4853c87ec9c3faf32be788fef0 Mon Sep 17 00:00:00 2001 From: jimblackler Date: Thu, 5 Nov 2026 11:21:14 +0000 Subject: [PATCH 3/5] thermal_monitor: Write counters with the Perfetto SDK instead of atrace Write the thermal counters as Perfetto track event counters in a "SherlockThermal" category, in the same way as the device_memory_report layer, instead of with ATrace_setCounter(): - Counters are doubles, so headroom is written as the API's value rather than multiplied by 1000 and rounded. The float is written as the double nearest to its shortest decimal form, so that 0.8f shows as 0.8 rather than 0.800000011920929. - The trace no longer depends on atrace app tags being enabled for the monitor's process. - The headroom thresholds are written once at the start of each tracing session (from a TrackEventSessionObserver) instead of with every current headroom sample, so ThermalCollector reads them at construction and EmitThresholds() writes them. thermal_monitor links the Perfetto SDK from layersvt/perfetto, built as a separate static library so that the availability checks only apply to main.cpp. The stripped arm64 binary is now about 1.3 MB. --- thermal_monitor/CMakeLists.txt | 10 +- thermal_monitor/main.cpp | 51 +++++++++- .../test/test_thermal_collector.cpp | 94 ++++++++++++------- thermal_monitor/thermal_collector.cpp | 60 +++++++----- thermal_monitor/thermal_collector.h | 31 +++--- 5 files changed, 175 insertions(+), 71 deletions(-) diff --git a/thermal_monitor/CMakeLists.txt b/thermal_monitor/CMakeLists.txt index dfc0d248f0..f4eda704d6 100644 --- a/thermal_monitor/CMakeLists.txt +++ b/thermal_monitor/CMakeLists.txt @@ -21,8 +21,16 @@ if(WIN32 AND (QT_TARGET_TYPE STREQUAL STATIC_LIBRARY)) endif() if(ANDROID) + # The Perfetto SDK that the layers use. Built as its own library so that the availability checks + # below only apply to main.cpp. + set(PERFETTO_SDK_DIR ${PROJECT_SOURCE_DIR}/layersvt/perfetto) + add_library(thermal_monitor_perfetto STATIC ${PERFETTO_SDK_DIR}/perfetto.cc) + target_include_directories(thermal_monitor_perfetto PUBLIC ${PROJECT_SOURCE_DIR}/layersvt) + target_compile_options(thermal_monitor_perfetto PRIVATE -Wno-deprecated-declarations) + target_link_libraries(thermal_monitor_perfetto PUBLIC log) + add_executable(thermal_monitor main.cpp) - target_link_libraries(thermal_monitor PRIVATE thermal_collector android log) + target_link_libraries(thermal_monitor PRIVATE thermal_collector thermal_monitor_perfetto android log) # AThermal_getThermalHeadroomThresholds() is API 35, above ANDROID_PLATFORM, so it is weakly # linked and guarded by __builtin_available. target_compile_definitions(thermal_monitor PRIVATE __ANDROID_UNAVAILABLE_SYMBOLS_ARE_WEAK__) diff --git a/thermal_monitor/main.cpp b/thermal_monitor/main.cpp index bbe142363b..af8421de18 100644 --- a/thermal_monitor/main.cpp +++ b/thermal_monitor/main.cpp @@ -17,7 +17,6 @@ #include #include -#include #include #include @@ -29,9 +28,19 @@ #include #include +#include "perfetto/perfetto.h" + +// TRACE_COUNTER needs the category as a literal, so this repeats +// ThermalConstants::kTrackEventCategory (checked below). +PERFETTO_DEFINE_CATEGORIES(perfetto::Category("SherlockThermal").SetDescription("Framework thermal status and headroom")); + +PERFETTO_TRACK_EVENT_STATIC_STORAGE(); + namespace apa::thermal { namespace { +static_assert(std::string_view(ThermalConstants::kTrackEventCategory) == "SherlockThermal"); + constexpr const char* kLogTag = "ThermalMonitor"; static_assert(static_cast(ThermalStatus::kNone) == ATHERMAL_STATUS_NONE); @@ -103,6 +112,31 @@ class NdkThermalSource final : public ThermalSource { AThermalManager* manager_ = nullptr; }; +// Emits the headroom thresholds at the start of every tracing session that enables the category. +// The thresholds never change, so emitting them once per session is enough, and the monitor can be +// started before tracing is. +class ThresholdSessionObserver final : public perfetto::TrackEventSessionObserver { + public: + explicit ThresholdSessionObserver(const ThermalCollector& collector) : collector_(collector) { + perfetto::TrackEvent::AddSessionObserver(this); + } + + ~ThresholdSessionObserver() override { perfetto::TrackEvent::RemoveSessionObserver(this); } + + ThresholdSessionObserver(const ThresholdSessionObserver&) = delete; + ThresholdSessionObserver& operator=(const ThresholdSessionObserver&) = delete; + + void OnStart(const perfetto::DataSourceBase::StartArgs&) override { collector_.EmitThresholds(); } + + private: + const ThermalCollector& collector_; +}; + +void EmitCounter(const char* name, double value) { + // The names are ThermalConstants string literals, so they outlive the track. + TRACE_COUNTER("SherlockThermal", perfetto::CounterTrack(perfetto::StaticString{name}), value); +} + volatile std::sig_atomic_t g_stop_requested = 0; void HandleStopSignal(int /*signum*/) { g_stop_requested = 1; } @@ -175,8 +209,17 @@ int main(int argc, char** argv) { return 0; } - ThermalCollector collector( - source, [](const char* name, int64_t value) { ATrace_setCounter(name, value); }, options.forecast_seconds); + perfetto::TracingInitArgs args; + args.backends = perfetto::kSystemBackend; + perfetto::Tracing::Initialize(args); + perfetto::TrackEvent::Register(); + + ThermalCollector collector(source, EmitCounter, options.forecast_seconds); + ThresholdSessionObserver observer(collector); + // OnStart() only reports sessions that start after the observer is added. + if (TRACE_EVENT_CATEGORY_ENABLED("SherlockThermal")) { + collector.EmitThresholds(); + } while (!g_stop_requested) { collector.Sample(); @@ -186,5 +229,7 @@ int main(int argc, char** argv) { poll(nullptr, 0, options.poll_interval_ms); } + // Commits the last samples to the tracing service before the process exits. + perfetto::TrackEvent::Flush(); return 0; } diff --git a/thermal_monitor/test/test_thermal_collector.cpp b/thermal_monitor/test/test_thermal_collector.cpp index c039539e81..ff088a3dd2 100644 --- a/thermal_monitor/test/test_thermal_collector.cpp +++ b/thermal_monitor/test/test_thermal_collector.cpp @@ -17,7 +17,6 @@ #include -#include #include #include #include @@ -28,7 +27,7 @@ namespace apa::thermal { namespace { -using CounterSample = std::pair; +using CounterSample = std::pair; class FakeThermalSource final : public ThermalSource { public: @@ -66,7 +65,7 @@ class FakeThermalSource final : public ThermalSource { class ThermalCollectorTest : public ::testing::Test { protected: std::vector emitted_; - ThermalCollector::Emitter emitter_ = [this](const char* name, int64_t value) { emitted_.emplace_back(name, value); }; + ThermalCollector::Emitter emitter_ = [this](const char* name, double value) { emitted_.emplace_back(name, value); }; }; TEST_F(ThermalCollectorTest, InterleavesCurrentAndForecastHeadroomOnAlternatingTicks) { @@ -79,9 +78,9 @@ TEST_F(ThermalCollectorTest, InterleavesCurrentAndForecastHeadroomOnAlternatingT EXPECT_EQ(source.HeadroomQueries(), (std::vector{0, 10, 0})); const std::vector expected = { - {ThermalConstants::kStatusCounter, 2}, {ThermalConstants::kHeadroomCounter, 930}, - {ThermalConstants::kStatusCounter, 2}, {ThermalConstants::kHeadroomForecastCounter, 1040}, - {ThermalConstants::kStatusCounter, 2}, {ThermalConstants::kHeadroomCounter, 930}, + {ThermalConstants::kStatusCounter, 2}, {ThermalConstants::kHeadroomCounter, 0.93}, + {ThermalConstants::kStatusCounter, 2}, {ThermalConstants::kHeadroomForecastCounter, 1.04}, + {ThermalConstants::kStatusCounter, 2}, {ThermalConstants::kHeadroomCounter, 0.93}, }; EXPECT_EQ(emitted_, expected); } @@ -96,9 +95,9 @@ TEST_F(ThermalCollectorTest, DisablesForecastWhenHorizonIsZero) { EXPECT_EQ(source.HeadroomQueries(), (std::vector{0, 0})); const std::vector expected = { {ThermalConstants::kStatusCounter, 1}, - {ThermalConstants::kHeadroomCounter, 800}, + {ThermalConstants::kHeadroomCounter, 0.8}, {ThermalConstants::kStatusCounter, 1}, - {ThermalConstants::kHeadroomCounter, 800}, + {ThermalConstants::kHeadroomCounter, 0.8}, }; EXPECT_EQ(emitted_, expected); } @@ -114,7 +113,7 @@ TEST_F(ThermalCollectorTest, SkipsFailedForecastTickWithoutRetryingCurrentHeadro EXPECT_EQ(source.HeadroomQueries(), (std::vector{0, 10})); const std::vector expected = { {ThermalConstants::kStatusCounter, 1}, - {ThermalConstants::kHeadroomCounter, 800}, + {ThermalConstants::kHeadroomCounter, 0.8}, {ThermalConstants::kStatusCounter, 1}, }; EXPECT_EQ(emitted_, expected); @@ -155,23 +154,39 @@ TEST_F(ThermalCollectorTest, KeepsForecastAfterTransientFailures) { } const std::vector expected = { - {ThermalConstants::kHeadroomCounter, 800}, {ThermalConstants::kHeadroomCounter, 800}, - {ThermalConstants::kHeadroomForecastCounter, 900}, {ThermalConstants::kHeadroomCounter, 800}, - {ThermalConstants::kHeadroomCounter, 800}, {ThermalConstants::kHeadroomForecastCounter, 900}, - {ThermalConstants::kHeadroomCounter, 800}, {ThermalConstants::kHeadroomCounter, 800}, - {ThermalConstants::kHeadroomForecastCounter, 900}, + {ThermalConstants::kHeadroomCounter, 0.8}, {ThermalConstants::kHeadroomCounter, 0.8}, + {ThermalConstants::kHeadroomForecastCounter, 0.9}, {ThermalConstants::kHeadroomCounter, 0.8}, + {ThermalConstants::kHeadroomCounter, 0.8}, {ThermalConstants::kHeadroomForecastCounter, 0.9}, + {ThermalConstants::kHeadroomCounter, 0.8}, {ThermalConstants::kHeadroomCounter, 0.8}, + {ThermalConstants::kHeadroomForecastCounter, 0.9}, }; EXPECT_EQ(emitted_, expected); } -TEST_F(ThermalCollectorTest, KeepsThreeDecimalPlacesOfHeadroom) { - // The Galaxy S25 puts LIGHT at 0.867 and MODERATE at 0.933, so rounding to hundredths would - // merge distinguishable states. +TEST_F(ThermalCollectorTest, EmitsTheShortestDecimalOfTheFloatHeadroom) { + // Converting 0.8f straight to a double would give 0.800000011920929. + FakeThermalSource source(/*status=*/std::nullopt, /*headroom=*/0.8f, /*forecast=*/std::nullopt, + /*thresholds=*/{{ThermalStatus::kModerate, 0.93333334f}}); + ThermalCollector collector(source, emitter_, /*forecast_seconds=*/0); + + collector.Sample(); + collector.EmitThresholds(); + + const std::vector expected = { + {ThermalConstants::kHeadroomCounter, 0.8}, + {"sherlock.thermal.headroom.threshold.moderate", 0.93333334}, + }; + EXPECT_EQ(emitted_, expected); +} + +TEST_F(ThermalCollectorTest, EmitsHeadroomWithoutRounding) { + // The Galaxy S25 puts LIGHT at 0.867 and MODERATE at 0.933, so any rounding has to keep at + // least three decimal places. Perfetto counters are doubles, so there is none. FakeThermalSource source(/*status=*/ThermalStatus::kNone, /*headroom=*/0.8674f); ThermalCollector(source, emitter_).Sample(); ASSERT_EQ(emitted_.size(), 2u); - EXPECT_EQ(emitted_[1], CounterSample(ThermalConstants::kHeadroomCounter, 867)); + EXPECT_EQ(emitted_[1], CounterSample(ThermalConstants::kHeadroomCounter, 0.8674)); } TEST_F(ThermalCollectorTest, OmitsHeadroomEntirelyOnDeviceThatDoesNotReportIt) { @@ -185,7 +200,7 @@ TEST_F(ThermalCollectorTest, OmitsHeadroomEntirelyOnDeviceThatDoesNotReportIt) { collector.Sample(); // A status track and no headroom track, rather than a headroom track full of a sentinel the - // host would have to strip. Thresholds are also suppressed when headroom is absent. + // host would have to strip. const std::vector expected = { {ThermalConstants::kStatusCounter, 1}, }; @@ -226,12 +241,29 @@ TEST_F(ThermalCollectorTest, OmitsStatusOnDeviceThatDoesNotReportIt) { collector.Sample(); const std::vector expected = { - {ThermalConstants::kHeadroomCounter, 500}, + {ThermalConstants::kHeadroomCounter, 0.5}, }; EXPECT_EQ(emitted_, expected); } -TEST_F(ThermalCollectorTest, ReadsThresholdsOnceAndReEmitsWithCurrentHeadroomOnly) { +TEST_F(ThermalCollectorTest, SamplesDoNotIncludeThresholds) { + FakeThermalSource source( + /*status=*/ThermalStatus::kNone, + /*headroom=*/0.8f, + /*forecast=*/std::nullopt, + /*thresholds=*/{{ThermalStatus::kLight, 0.867f}}); + ThermalCollector collector(source, emitter_, /*forecast_seconds=*/0); + + collector.Sample(); + + const std::vector expected = { + {ThermalConstants::kStatusCounter, 0}, + {ThermalConstants::kHeadroomCounter, 0.8}, + }; + EXPECT_EQ(emitted_, expected); +} + +TEST_F(ThermalCollectorTest, ReadsThresholdsOnceAndEmitsTheValidOnes) { // The Galaxy S25 reports SEVERE as NaN even though LIGHT and MODERATE are populated. FakeThermalSource source( /*status=*/ThermalStatus::kNone, @@ -246,22 +278,16 @@ TEST_F(ThermalCollectorTest, ReadsThresholdsOnceAndReEmitsWithCurrentHeadroomOnl }); ThermalCollector collector(source, emitter_, /*forecast_seconds=*/10); - collector.Sample(); - collector.Sample(); - collector.Sample(); + // Once per tracing session. + collector.EmitThresholds(); + collector.EmitThresholds(); EXPECT_EQ(source.ThresholdsReadCount(), 1); const std::vector expected = { - {ThermalConstants::kStatusCounter, 0}, - {ThermalConstants::kHeadroomCounter, 800}, - {"sherlock.thermal.headroom.threshold.light", 867}, - {"sherlock.thermal.headroom.threshold.moderate", 933}, - {ThermalConstants::kStatusCounter, 0}, - {ThermalConstants::kHeadroomForecastCounter, 900}, - {ThermalConstants::kStatusCounter, 0}, - {ThermalConstants::kHeadroomCounter, 800}, - {"sherlock.thermal.headroom.threshold.light", 867}, - {"sherlock.thermal.headroom.threshold.moderate", 933}, + {"sherlock.thermal.headroom.threshold.light", 0.867}, + {"sherlock.thermal.headroom.threshold.moderate", 0.933}, + {"sherlock.thermal.headroom.threshold.light", 0.867}, + {"sherlock.thermal.headroom.threshold.moderate", 0.933}, }; EXPECT_EQ(emitted_, expected); } diff --git a/thermal_monitor/thermal_collector.cpp b/thermal_monitor/thermal_collector.cpp index a82a6fa4c4..0bace18119 100644 --- a/thermal_monitor/thermal_collector.cpp +++ b/thermal_monitor/thermal_collector.cpp @@ -15,20 +15,42 @@ #include "thermal_collector.h" +#include #include +#include +#include #include namespace apa::thermal { +namespace { + +// The NDK reports headroom as a float, and converting it straight to a double keeps the float's +// rounding error (0.8f becomes 0.800000011920929). Returns the double nearest to the shortest +// decimal that identifies the float instead (0.8). +double ToCounterValue(float value) { + // std::to_chars gives the shortest form, but the NDK's libc++ has no floating-point + // std::from_chars, so it is parsed with strtod. Neither the monitor nor the tests change the + // locale from "C", so the decimal point is '.'. + char buffer[32]; + if (const auto [end, ec] = std::to_chars(buffer, buffer + sizeof(buffer) - 1, value); ec == std::errc()) { + *end = '\0'; + return std::strtod(buffer, nullptr); + } + return static_cast(value); +} + +} // namespace ThermalCollector::ThermalCollector(ThermalSource& source, Emitter emitter, int forecast_seconds) : source_(source), emitter_(std::move(emitter)), + thresholds_(ReadThresholds(source)), forecast_seconds_(forecast_seconds), forecast_supported_(forecast_seconds > 0) {} void ThermalCollector::Sample() { if (const std::optional status = source_.CurrentThermalStatus(); status.has_value()) { - emitter_(ThermalConstants::kStatusCounter, static_cast(*status)); + emitter_(ThermalConstants::kStatusCounter, static_cast(*status)); } if (forecast_supported_ && (tick_++ % 2) == 1) { if (EmitHeadroom(ThermalConstants::kHeadroomForecastCounter, source_.ThermalHeadroom(forecast_seconds_))) { @@ -38,35 +60,31 @@ void ThermalCollector::Sample() { } return; } - if (EmitHeadroom(ThermalConstants::kHeadroomCounter, source_.ThermalHeadroom(0))) { - for (const auto& [name, value] : GetThresholds()) { - EmitHeadroom(name, value); - } + EmitHeadroom(ThermalConstants::kHeadroomCounter, source_.ThermalHeadroom(0)); +} + +void ThermalCollector::EmitThresholds() const { + for (const auto& [name, value] : thresholds_) { + EmitHeadroom(name, value); } } -const ThermalCollector::ThresholdList& ThermalCollector::GetThresholds() { - if (!thresholds_.has_value()) { - ThresholdList resolved; - for (const auto& [status, value] : source_.ThermalHeadroomThresholds()) { - const char* name = ThermalConstants::ThresholdCounterName(status); - if (name != nullptr) { - resolved.emplace_back(name, value); - } +ThermalCollector::ThresholdList ThermalCollector::ReadThresholds(ThermalSource& source) { + ThresholdList thresholds; + for (const auto& [status, value] : source.ThermalHeadroomThresholds()) { + const char* name = ThermalConstants::ThresholdCounterName(status); + if (name != nullptr) { + thresholds.emplace_back(name, value); } - thresholds_ = std::move(resolved); } - return *thresholds_; + return thresholds; } -bool ThermalCollector::EmitHeadroom(const char* counter, std::optional headroom) { - // Headroom is 1.0 at SEVERE throttling, so values this large are bogus; the cap also keeps the - // scaled value well inside the range of std::llround. - constexpr float kMaxHeadroom = 1e6f; - if (!headroom.has_value() || !std::isfinite(*headroom) || *headroom < 0.0f || *headroom > kMaxHeadroom) { +bool ThermalCollector::EmitHeadroom(const char* counter, std::optional headroom) const { + if (!headroom.has_value() || !std::isfinite(*headroom) || *headroom < 0.0f) { return false; } - emitter_(counter, std::llround(*headroom * ThermalConstants::kHeadroomScale)); + emitter_(counter, ToCounterValue(*headroom)); return true; } diff --git a/thermal_monitor/thermal_collector.h b/thermal_monitor/thermal_collector.h index e0fe3a96df..4c64475a45 100644 --- a/thermal_monitor/thermal_collector.h +++ b/thermal_monitor/thermal_collector.h @@ -15,7 +15,6 @@ #pragma once -#include #include #include #include @@ -36,8 +35,11 @@ enum class ThermalStatus : int { kShutdown = 6, }; -// Must match the counter names and scale that the Android Performance Analyzer trace viewer reads. +// Must match the track event category and counter names that the Android Performance Analyzer trace +// viewer reads. namespace ThermalConstants { +// Perfetto track event category that the counters are written to. +inline constexpr const char* kTrackEventCategory = "SherlockThermal"; inline constexpr int kDefaultPollIntervalMs = 1000; // Polling faster than this would only collect NaNs from the ~1 Hz rate-limited headroom API. inline constexpr int kMinPollIntervalMs = kDefaultPollIntervalMs; @@ -46,8 +48,6 @@ inline constexpr int kMaxForecastSeconds = 60; inline constexpr const char* kHeadroomCounter = "sherlock.thermal.headroom"; inline constexpr const char* kHeadroomForecastCounter = "sherlock.thermal.headroom.forecast"; inline constexpr const char* kStatusCounter = "sherlock.thermal.status"; -// Atrace counters are integers, so headroom values are emitted multiplied by this. -inline constexpr int64_t kHeadroomScale = 1000; // Counter names for the thermal statuses that can carry a headroom threshold. inline constexpr const char* ThresholdCounterName(ThermalStatus status) { @@ -92,19 +92,29 @@ class ThermalSource { }; // Samples the framework's thermal state and emits it as trace counters. +// // AThermal_getThermalHeadroom() is rate-limited to ~1 Hz across all forecast_seconds values, which // is why ThermalConstants::kDefaultPollIntervalMs is one second and why, when forecast_seconds is // positive, current and forecast headroom are sampled on alternating ticks rather than on the same // tick. A forecast tick that fails emits no headroom at all rather than retrying the current // headroom, which the rate limit would reject. +// +// The headroom thresholds are static for a device, so they are read once, at construction, and +// emitted separately by EmitThresholds() once per tracing session. class ThermalCollector { public: - using Emitter = std::function; + using Emitter = std::function; ThermalCollector(ThermalSource& source, Emitter emitter, int forecast_seconds = ThermalConstants::kDefaultForecastSeconds); + // Emits the current status and either the current or the forecast headroom. Call it once per + // poll interval. void Sample(); + // Emits the device's headroom thresholds. Only reads state that is fixed at construction, so it + // can be called from another thread than Sample(), as long as the emitter is thread-safe. + void EmitThresholds() const; + private: using ThresholdList = std::vector>; @@ -112,17 +122,14 @@ class ThermalCollector { // service hiccups, so one failure does not prove that the device cannot forecast. static constexpr int kMaxForecastFailures = 3; - // The thresholds are static for a device, so they are read from source_ once, but re-emitted - // with every headroom sample because the monitor starts before tracing does and a one-off - // emission at startup would not land in the trace. - const ThresholdList& GetThresholds(); + static ThresholdList ReadThresholds(ThermalSource& source); - bool EmitHeadroom(const char* counter, std::optional headroom); + bool EmitHeadroom(const char* counter, std::optional headroom) const; ThermalSource& source_; - Emitter emitter_; + const Emitter emitter_; + const ThresholdList thresholds_; int forecast_seconds_; - std::optional thresholds_; int tick_ = 0; int forecast_failures_ = 0; bool forecast_supported_; From 8a034d3ecc6e7fd41baa37550b20f160d07353a4 Mon Sep 17 00:00:00 2001 From: jimblackler Date: Thu, 5 Nov 2026 15:52:14 +0000 Subject: [PATCH 4/5] thermal_monitor: Use AThermalStatus instead of a mirror enum Use the NDK's AThermalStatus directly in ThermalSource, ThresholdCounterName() and the threshold maps, instead of the ThermalStatus enum that mirrored it. This drops the enum and the static_asserts in main.cpp that kept it in sync. The host build, which unit tests ThermalCollector, has no NDK, so it puts host_stubs/ on the include path. host_stubs/android/thermal.h declares only the AThermalStatus enum, with its NDK ABI values. Android builds use the real header. --- thermal_monitor/CMakeLists.txt | 4 ++ thermal_monitor/host_stubs/android/thermal.h | 32 ++++++++++++ thermal_monitor/main.cpp | 18 ++----- .../test/test_thermal_collector.cpp | 52 +++++++++---------- thermal_monitor/thermal_collector.cpp | 2 +- thermal_monitor/thermal_collector.h | 36 +++++-------- 6 files changed, 81 insertions(+), 63 deletions(-) create mode 100644 thermal_monitor/host_stubs/android/thermal.h diff --git a/thermal_monitor/CMakeLists.txt b/thermal_monitor/CMakeLists.txt index f4eda704d6..298bf49ddc 100644 --- a/thermal_monitor/CMakeLists.txt +++ b/thermal_monitor/CMakeLists.txt @@ -15,6 +15,10 @@ # The sampling policy has no Android dependencies, so it is also built on the host for the unit tests. add_library(thermal_collector STATIC thermal_collector.cpp thermal_collector.h) target_include_directories(thermal_collector PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) +if(NOT ANDROID) + # Stands in for the NDK's so that the collector builds off-device. + target_include_directories(thermal_collector PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/host_stubs) +endif() if(WIN32 AND (QT_TARGET_TYPE STREQUAL STATIC_LIBRARY)) set_property(TARGET thermal_collector PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") diff --git a/thermal_monitor/host_stubs/android/thermal.h b/thermal_monitor/host_stubs/android/thermal.h new file mode 100644 index 0000000000..b34ba185ab --- /dev/null +++ b/thermal_monitor/host_stubs/android/thermal.h @@ -0,0 +1,32 @@ +/* Copyright (C) 2026 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Host-only stand-in for the NDK's , so that ThermalCollector, which only needs +// the AThermalStatus type, can be built and unit tested off-device. Only on the include path for +// non-Android builds; Android builds use the real NDK header. The values are part of the NDK ABI. + +#pragma once + +enum AThermalStatus { + ATHERMAL_STATUS_ERROR = -1, + ATHERMAL_STATUS_NONE = 0, + ATHERMAL_STATUS_LIGHT = 1, + ATHERMAL_STATUS_MODERATE = 2, + ATHERMAL_STATUS_SEVERE = 3, + ATHERMAL_STATUS_CRITICAL = 4, + ATHERMAL_STATUS_EMERGENCY = 5, + ATHERMAL_STATUS_SHUTDOWN = 6, +}; +typedef enum AThermalStatus AThermalStatus; diff --git a/thermal_monitor/main.cpp b/thermal_monitor/main.cpp index af8421de18..819dc73cbf 100644 --- a/thermal_monitor/main.cpp +++ b/thermal_monitor/main.cpp @@ -43,14 +43,6 @@ static_assert(std::string_view(ThermalConstants::kTrackEventCategory) == "Sherlo constexpr const char* kLogTag = "ThermalMonitor"; -static_assert(static_cast(ThermalStatus::kNone) == ATHERMAL_STATUS_NONE); -static_assert(static_cast(ThermalStatus::kLight) == ATHERMAL_STATUS_LIGHT); -static_assert(static_cast(ThermalStatus::kModerate) == ATHERMAL_STATUS_MODERATE); -static_assert(static_cast(ThermalStatus::kSevere) == ATHERMAL_STATUS_SEVERE); -static_assert(static_cast(ThermalStatus::kCritical) == ATHERMAL_STATUS_CRITICAL); -static_assert(static_cast(ThermalStatus::kEmergency) == ATHERMAL_STATUS_EMERGENCY); -static_assert(static_cast(ThermalStatus::kShutdown) == ATHERMAL_STATUS_SHUTDOWN); - // Queries the Android framework's thermal state via the NDK AThermal API in libandroid.so. // The binary targets API 31 (see scripts/android.py), which covers everything except // AThermal_getThermalHeadroomThresholds() (API 35). That symbol is weakly linked @@ -70,12 +62,12 @@ class NdkThermalSource final : public ThermalSource { [[nodiscard]] bool IsValid() const { return manager_ != nullptr; } - std::optional CurrentThermalStatus() override { + std::optional CurrentThermalStatus() override { const AThermalStatus status = AThermal_getCurrentThermalStatus(manager_); if (status < ATHERMAL_STATUS_NONE || status > ATHERMAL_STATUS_SHUTDOWN) { return std::nullopt; } - return static_cast(status); + return status; } std::optional ThermalHeadroom(int forecast_seconds) override { @@ -86,8 +78,8 @@ class NdkThermalSource final : public ThermalSource { return headroom; } - std::map ThermalHeadroomThresholds() override { - std::map result; + std::map ThermalHeadroomThresholds() override { + std::map result; // AThermal_getThermalHeadroomThresholds() was added in Android 15 (API 35). Older versions // cannot report thresholds, so they get an empty map. if (__builtin_available(android 35, *)) { @@ -99,7 +91,7 @@ class NdkThermalSource final : public ThermalSource { for (size_t i = 0; i < size; ++i) { const AThermalStatus status = thresholds[i].thermalStatus; if (status >= ATHERMAL_STATUS_NONE && status <= ATHERMAL_STATUS_SHUTDOWN) { - result[static_cast(status)] = thresholds[i].headroom; + result[status] = thresholds[i].headroom; } } // The NDK allocates the array and documents that the client array-deletes it. diff --git a/thermal_monitor/test/test_thermal_collector.cpp b/thermal_monitor/test/test_thermal_collector.cpp index ff088a3dd2..abc0d10ca5 100644 --- a/thermal_monitor/test/test_thermal_collector.cpp +++ b/thermal_monitor/test/test_thermal_collector.cpp @@ -31,18 +31,18 @@ using CounterSample = std::pair; class FakeThermalSource final : public ThermalSource { public: - FakeThermalSource(std::optional status, std::optional headroom, - std::optional forecast = std::nullopt, std::map thresholds = {}) + FakeThermalSource(std::optional status, std::optional headroom, + std::optional forecast = std::nullopt, std::map thresholds = {}) : status_(status), headroom_(headroom), forecast_(forecast), thresholds_(std::move(thresholds)) {} - std::optional CurrentThermalStatus() override { return status_; } + std::optional CurrentThermalStatus() override { return status_; } std::optional ThermalHeadroom(int forecast_seconds) override { headroom_queries_.push_back(forecast_seconds); return forecast_seconds == 0 ? headroom_ : forecast_; } - std::map ThermalHeadroomThresholds() override { + std::map ThermalHeadroomThresholds() override { ++thresholds_read_count_; return thresholds_; } @@ -52,10 +52,10 @@ class FakeThermalSource final : public ThermalSource { const std::vector& HeadroomQueries() const { return headroom_queries_; } private: - std::optional status_; + std::optional status_; std::optional headroom_; std::optional forecast_; - std::map thresholds_; + std::map thresholds_; int thresholds_read_count_ = 0; std::vector headroom_queries_; }; @@ -69,7 +69,7 @@ class ThermalCollectorTest : public ::testing::Test { }; TEST_F(ThermalCollectorTest, InterleavesCurrentAndForecastHeadroomOnAlternatingTicks) { - FakeThermalSource source(/*status=*/ThermalStatus::kModerate, /*headroom=*/0.93f, /*forecast=*/1.04f); + FakeThermalSource source(/*status=*/ATHERMAL_STATUS_MODERATE, /*headroom=*/0.93f, /*forecast=*/1.04f); ThermalCollector collector(source, emitter_, /*forecast_seconds=*/10); collector.Sample(); @@ -86,7 +86,7 @@ TEST_F(ThermalCollectorTest, InterleavesCurrentAndForecastHeadroomOnAlternatingT } TEST_F(ThermalCollectorTest, DisablesForecastWhenHorizonIsZero) { - FakeThermalSource source(/*status=*/ThermalStatus::kLight, /*headroom=*/0.8f, /*forecast=*/0.9f); + FakeThermalSource source(/*status=*/ATHERMAL_STATUS_LIGHT, /*headroom=*/0.8f, /*forecast=*/0.9f); ThermalCollector collector(source, emitter_, /*forecast_seconds=*/0); collector.Sample(); @@ -103,7 +103,7 @@ TEST_F(ThermalCollectorTest, DisablesForecastWhenHorizonIsZero) { } TEST_F(ThermalCollectorTest, SkipsFailedForecastTickWithoutRetryingCurrentHeadroom) { - FakeThermalSource source(/*status=*/ThermalStatus::kLight, /*headroom=*/0.8f, /*forecast=*/std::nullopt); + FakeThermalSource source(/*status=*/ATHERMAL_STATUS_LIGHT, /*headroom=*/0.8f, /*forecast=*/std::nullopt); ThermalCollector collector(source, emitter_, /*forecast_seconds=*/10); collector.Sample(); @@ -135,14 +135,14 @@ TEST_F(ThermalCollectorTest, KeepsForecastAfterTransientFailures) { // Each fake failure is followed by a success, so the failure count never reaches the limit. class FlakyForecastSource final : public ThermalSource { public: - std::optional CurrentThermalStatus() override { return std::nullopt; } + std::optional CurrentThermalStatus() override { return std::nullopt; } std::optional ThermalHeadroom(int forecast_seconds) override { if (forecast_seconds == 0) { return 0.8f; } return (forecast_calls_++ % 2) == 0 ? std::nullopt : std::optional(0.9f); } - std::map ThermalHeadroomThresholds() override { return {}; } + std::map ThermalHeadroomThresholds() override { return {}; } private: int forecast_calls_ = 0; @@ -166,7 +166,7 @@ TEST_F(ThermalCollectorTest, KeepsForecastAfterTransientFailures) { TEST_F(ThermalCollectorTest, EmitsTheShortestDecimalOfTheFloatHeadroom) { // Converting 0.8f straight to a double would give 0.800000011920929. FakeThermalSource source(/*status=*/std::nullopt, /*headroom=*/0.8f, /*forecast=*/std::nullopt, - /*thresholds=*/{{ThermalStatus::kModerate, 0.93333334f}}); + /*thresholds=*/{{ATHERMAL_STATUS_MODERATE, 0.93333334f}}); ThermalCollector collector(source, emitter_, /*forecast_seconds=*/0); collector.Sample(); @@ -182,7 +182,7 @@ TEST_F(ThermalCollectorTest, EmitsTheShortestDecimalOfTheFloatHeadroom) { TEST_F(ThermalCollectorTest, EmitsHeadroomWithoutRounding) { // The Galaxy S25 puts LIGHT at 0.867 and MODERATE at 0.933, so any rounding has to keep at // least three decimal places. Perfetto counters are doubles, so there is none. - FakeThermalSource source(/*status=*/ThermalStatus::kNone, /*headroom=*/0.8674f); + FakeThermalSource source(/*status=*/ATHERMAL_STATUS_NONE, /*headroom=*/0.8674f); ThermalCollector(source, emitter_).Sample(); ASSERT_EQ(emitted_.size(), 2u); @@ -191,10 +191,10 @@ TEST_F(ThermalCollectorTest, EmitsHeadroomWithoutRounding) { TEST_F(ThermalCollectorTest, OmitsHeadroomEntirelyOnDeviceThatDoesNotReportIt) { FakeThermalSource source( - /*status=*/ThermalStatus::kLight, + /*status=*/ATHERMAL_STATUS_LIGHT, /*headroom=*/std::nullopt, /*forecast=*/std::nullopt, - /*thresholds=*/{{ThermalStatus::kLight, 0.7f}}); + /*thresholds=*/{{ATHERMAL_STATUS_LIGHT, 0.7f}}); ThermalCollector collector(source, emitter_); collector.Sample(); @@ -209,17 +209,17 @@ TEST_F(ThermalCollectorTest, OmitsHeadroomEntirelyOnDeviceThatDoesNotReportIt) { TEST_F(ThermalCollectorTest, IgnoresNonFiniteOrNegativeHeadroom) { FakeThermalSource nan_source( - /*status=*/ThermalStatus::kLight, + /*status=*/ATHERMAL_STATUS_LIGHT, /*headroom=*/std::numeric_limits::quiet_NaN(), /*forecast=*/std::nullopt, - /*thresholds=*/{{ThermalStatus::kLight, 0.7f}}); + /*thresholds=*/{{ATHERMAL_STATUS_LIGHT, 0.7f}}); ThermalCollector(nan_source, emitter_).Sample(); FakeThermalSource negative_source( - /*status=*/ThermalStatus::kLight, + /*status=*/ATHERMAL_STATUS_LIGHT, /*headroom=*/-1.0f, /*forecast=*/-1.0f, - /*thresholds=*/{{ThermalStatus::kLight, 0.7f}}); + /*thresholds=*/{{ATHERMAL_STATUS_LIGHT, 0.7f}}); ThermalCollector negative_collector(negative_source, emitter_, /*forecast_seconds=*/10); negative_collector.Sample(); negative_collector.Sample(); @@ -248,10 +248,10 @@ TEST_F(ThermalCollectorTest, OmitsStatusOnDeviceThatDoesNotReportIt) { TEST_F(ThermalCollectorTest, SamplesDoNotIncludeThresholds) { FakeThermalSource source( - /*status=*/ThermalStatus::kNone, + /*status=*/ATHERMAL_STATUS_NONE, /*headroom=*/0.8f, /*forecast=*/std::nullopt, - /*thresholds=*/{{ThermalStatus::kLight, 0.867f}}); + /*thresholds=*/{{ATHERMAL_STATUS_LIGHT, 0.867f}}); ThermalCollector collector(source, emitter_, /*forecast_seconds=*/0); collector.Sample(); @@ -266,15 +266,15 @@ TEST_F(ThermalCollectorTest, SamplesDoNotIncludeThresholds) { TEST_F(ThermalCollectorTest, ReadsThresholdsOnceAndEmitsTheValidOnes) { // The Galaxy S25 reports SEVERE as NaN even though LIGHT and MODERATE are populated. FakeThermalSource source( - /*status=*/ThermalStatus::kNone, + /*status=*/ATHERMAL_STATUS_NONE, /*headroom=*/0.8f, /*forecast=*/0.9f, /*thresholds=*/ { - {ThermalStatus::kNone, 0.0f}, - {ThermalStatus::kLight, 0.867f}, - {ThermalStatus::kModerate, 0.933f}, - {ThermalStatus::kSevere, std::numeric_limits::quiet_NaN()}, + {ATHERMAL_STATUS_NONE, 0.0f}, + {ATHERMAL_STATUS_LIGHT, 0.867f}, + {ATHERMAL_STATUS_MODERATE, 0.933f}, + {ATHERMAL_STATUS_SEVERE, std::numeric_limits::quiet_NaN()}, }); ThermalCollector collector(source, emitter_, /*forecast_seconds=*/10); diff --git a/thermal_monitor/thermal_collector.cpp b/thermal_monitor/thermal_collector.cpp index 0bace18119..718d2881a5 100644 --- a/thermal_monitor/thermal_collector.cpp +++ b/thermal_monitor/thermal_collector.cpp @@ -49,7 +49,7 @@ ThermalCollector::ThermalCollector(ThermalSource& source, Emitter emitter, int f forecast_supported_(forecast_seconds > 0) {} void ThermalCollector::Sample() { - if (const std::optional status = source_.CurrentThermalStatus(); status.has_value()) { + if (const std::optional status = source_.CurrentThermalStatus(); status.has_value()) { emitter_(ThermalConstants::kStatusCounter, static_cast(*status)); } if (forecast_supported_ && (tick_++ % 2) == 1) { diff --git a/thermal_monitor/thermal_collector.h b/thermal_monitor/thermal_collector.h index 4c64475a45..c4ffae7c7f 100644 --- a/thermal_monitor/thermal_collector.h +++ b/thermal_monitor/thermal_collector.h @@ -15,6 +15,8 @@ #pragma once +#include + #include #include #include @@ -23,18 +25,6 @@ namespace apa::thermal { -// Mirrors AThermalStatus from , which is not available in the host build that -// unit tests ThermalCollector. main.cpp static_asserts that the values match. -enum class ThermalStatus : int { - kNone = 0, - kLight = 1, - kModerate = 2, - kSevere = 3, - kCritical = 4, - kEmergency = 5, - kShutdown = 6, -}; - // Must match the track event category and counter names that the Android Performance Analyzer trace // viewer reads. namespace ThermalConstants { @@ -50,19 +40,19 @@ inline constexpr const char* kHeadroomForecastCounter = "sherlock.thermal.headro inline constexpr const char* kStatusCounter = "sherlock.thermal.status"; // Counter names for the thermal statuses that can carry a headroom threshold. -inline constexpr const char* ThresholdCounterName(ThermalStatus status) { +inline constexpr const char* ThresholdCounterName(AThermalStatus status) { switch (status) { - case ThermalStatus::kLight: + case ATHERMAL_STATUS_LIGHT: return "sherlock.thermal.headroom.threshold.light"; - case ThermalStatus::kModerate: + case ATHERMAL_STATUS_MODERATE: return "sherlock.thermal.headroom.threshold.moderate"; - case ThermalStatus::kSevere: + case ATHERMAL_STATUS_SEVERE: return "sherlock.thermal.headroom.threshold.severe"; - case ThermalStatus::kCritical: + case ATHERMAL_STATUS_CRITICAL: return "sherlock.thermal.headroom.threshold.critical"; - case ThermalStatus::kEmergency: + case ATHERMAL_STATUS_EMERGENCY: return "sherlock.thermal.headroom.threshold.emergency"; - case ThermalStatus::kShutdown: + case ATHERMAL_STATUS_SHUTDOWN: return "sherlock.thermal.headroom.threshold.shutdown"; default: return nullptr; @@ -77,18 +67,18 @@ class ThermalSource { virtual ~ThermalSource() = default; // AThermal_getCurrentThermalStatus(), or nullopt if the device cannot report it. - virtual std::optional CurrentThermalStatus() = 0; + virtual std::optional CurrentThermalStatus() = 0; // AThermal_getThermalHeadroom(forecast_seconds); 0 asks for the current headroom. The returned // headroom is 0.0 with no thermal load and rises with it: 1.0 means the device is (or, for a - // forecast, will be) throttled at ThermalStatus::kSevere, and values above 1.0 mean it is - // throttled beyond kSevere. Returns nullopt if the API returns NaN, e.g. when the device does + // forecast, will be) throttled at ATHERMAL_STATUS_SEVERE, and values above 1.0 mean it + // is throttled beyond that. Returns nullopt if the API returns NaN, e.g. when the device does // not support headroom or the call was rate-limited. virtual std::optional ThermalHeadroom(int forecast_seconds) = 0; // Headroom at which each thermal status starts, or empty if the device or OS version cannot // report it. - virtual std::map ThermalHeadroomThresholds() = 0; + virtual std::map ThermalHeadroomThresholds() = 0; }; // Samples the framework's thermal state and emits it as trace counters. From f70f55b37e04c12df7ad6e48714501f0977e6914 Mon Sep 17 00:00:00 2001 From: jimblackler Date: Fri, 6 Nov 2026 11:17:06 +0000 Subject: [PATCH 5/5] thermal_monitor: Address second round of review feedback on PR #55 - Rename the Perfetto track event category from SherlockThermal to Thermals and reference ThermalConstants::kTrackEventCategory directly in Perfetto macros. - Log an error and exit with status 1 on unknown CLI flags or missing or malformed integer option values. - Call collector.EmitThresholds() unconditionally at startup and let Perfetto drop the events when the category is disabled. - Remove ToCounterValue() and pass float headroom values directly to the counter emitter. --- thermal_monitor/main.cpp | 30 ++++++----- .../test/test_thermal_collector.cpp | 50 +++++++------------ thermal_monitor/thermal_collector.cpp | 23 +-------- thermal_monitor/thermal_collector.h | 2 +- 4 files changed, 33 insertions(+), 72 deletions(-) diff --git a/thermal_monitor/main.cpp b/thermal_monitor/main.cpp index 819dc73cbf..ad63f77942 100644 --- a/thermal_monitor/main.cpp +++ b/thermal_monitor/main.cpp @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -30,17 +31,14 @@ #include "perfetto/perfetto.h" -// TRACE_COUNTER needs the category as a literal, so this repeats -// ThermalConstants::kTrackEventCategory (checked below). -PERFETTO_DEFINE_CATEGORIES(perfetto::Category("SherlockThermal").SetDescription("Framework thermal status and headroom")); +PERFETTO_DEFINE_CATEGORIES( + perfetto::Category(apa::thermal::ThermalConstants::kTrackEventCategory).SetDescription("Framework thermal status and headroom")); PERFETTO_TRACK_EVENT_STATIC_STORAGE(); namespace apa::thermal { namespace { -static_assert(std::string_view(ThermalConstants::kTrackEventCategory) == "SherlockThermal"); - constexpr const char* kLogTag = "ThermalMonitor"; // Queries the Android framework's thermal state via the NDK AThermal API in libandroid.so. @@ -126,7 +124,7 @@ class ThresholdSessionObserver final : public perfetto::TrackEventSessionObserve void EmitCounter(const char* name, double value) { // The names are ThermalConstants string literals, so they outlive the track. - TRACE_COUNTER("SherlockThermal", perfetto::CounterTrack(perfetto::StaticString{name}), value); + TRACE_COUNTER(ThermalConstants::kTrackEventCategory, perfetto::CounterTrack(perfetto::StaticString{name}), value); } volatile std::sig_atomic_t g_stop_requested = 0; @@ -149,20 +147,21 @@ struct Options { int forecast_seconds = ThermalConstants::kDefaultForecastSeconds; }; -// Reads the value that follows argv[*i] into *out, warning instead of silently keeping the default -// when it is missing or malformed. +// Reads the value that follows argv[*i] into *out, logging an error and exiting when it is missing +// or malformed. void ParseIntOption(int argc, char** argv, int* i, int* out) { const char* flag = argv[*i]; if (*i + 1 >= argc) { - __android_log_print(ANDROID_LOG_WARN, kLogTag, "Missing value for %s", flag); - return; + __android_log_print(ANDROID_LOG_ERROR, kLogTag, "Missing value for %s", flag); + std::exit(1); } const char* value = argv[++*i]; if (const std::optional parsed = ParseInt(value); parsed.has_value()) { *out = *parsed; - } else { - __android_log_print(ANDROID_LOG_WARN, kLogTag, "Ignoring invalid value '%s' for %s", value, flag); + return; } + __android_log_print(ANDROID_LOG_ERROR, kLogTag, "Invalid value '%s' for %s", value, flag); + std::exit(1); } Options ParseOptions(int argc, char** argv) { @@ -173,7 +172,8 @@ Options ParseOptions(int argc, char** argv) { } else if (std::strcmp(argv[i], "--forecast-seconds") == 0) { ParseIntOption(argc, argv, &i, &options.forecast_seconds); } else { - __android_log_print(ANDROID_LOG_WARN, kLogTag, "Ignoring unknown argument '%s'", argv[i]); + __android_log_print(ANDROID_LOG_ERROR, kLogTag, "Unknown argument '%s'", argv[i]); + std::exit(1); } } options.poll_interval_ms = std::max(options.poll_interval_ms, ThermalConstants::kMinPollIntervalMs); @@ -209,9 +209,7 @@ int main(int argc, char** argv) { ThermalCollector collector(source, EmitCounter, options.forecast_seconds); ThresholdSessionObserver observer(collector); // OnStart() only reports sessions that start after the observer is added. - if (TRACE_EVENT_CATEGORY_ENABLED("SherlockThermal")) { - collector.EmitThresholds(); - } + collector.EmitThresholds(); while (!g_stop_requested) { collector.Sample(); diff --git a/thermal_monitor/test/test_thermal_collector.cpp b/thermal_monitor/test/test_thermal_collector.cpp index abc0d10ca5..905d6b43d6 100644 --- a/thermal_monitor/test/test_thermal_collector.cpp +++ b/thermal_monitor/test/test_thermal_collector.cpp @@ -78,9 +78,9 @@ TEST_F(ThermalCollectorTest, InterleavesCurrentAndForecastHeadroomOnAlternatingT EXPECT_EQ(source.HeadroomQueries(), (std::vector{0, 10, 0})); const std::vector expected = { - {ThermalConstants::kStatusCounter, 2}, {ThermalConstants::kHeadroomCounter, 0.93}, - {ThermalConstants::kStatusCounter, 2}, {ThermalConstants::kHeadroomForecastCounter, 1.04}, - {ThermalConstants::kStatusCounter, 2}, {ThermalConstants::kHeadroomCounter, 0.93}, + {ThermalConstants::kStatusCounter, 2}, {ThermalConstants::kHeadroomCounter, 0.93f}, + {ThermalConstants::kStatusCounter, 2}, {ThermalConstants::kHeadroomForecastCounter, 1.04f}, + {ThermalConstants::kStatusCounter, 2}, {ThermalConstants::kHeadroomCounter, 0.93f}, }; EXPECT_EQ(emitted_, expected); } @@ -95,9 +95,9 @@ TEST_F(ThermalCollectorTest, DisablesForecastWhenHorizonIsZero) { EXPECT_EQ(source.HeadroomQueries(), (std::vector{0, 0})); const std::vector expected = { {ThermalConstants::kStatusCounter, 1}, - {ThermalConstants::kHeadroomCounter, 0.8}, + {ThermalConstants::kHeadroomCounter, 0.8f}, {ThermalConstants::kStatusCounter, 1}, - {ThermalConstants::kHeadroomCounter, 0.8}, + {ThermalConstants::kHeadroomCounter, 0.8f}, }; EXPECT_EQ(emitted_, expected); } @@ -113,7 +113,7 @@ TEST_F(ThermalCollectorTest, SkipsFailedForecastTickWithoutRetryingCurrentHeadro EXPECT_EQ(source.HeadroomQueries(), (std::vector{0, 10})); const std::vector expected = { {ThermalConstants::kStatusCounter, 1}, - {ThermalConstants::kHeadroomCounter, 0.8}, + {ThermalConstants::kHeadroomCounter, 0.8f}, {ThermalConstants::kStatusCounter, 1}, }; EXPECT_EQ(emitted_, expected); @@ -154,27 +154,11 @@ TEST_F(ThermalCollectorTest, KeepsForecastAfterTransientFailures) { } const std::vector expected = { - {ThermalConstants::kHeadroomCounter, 0.8}, {ThermalConstants::kHeadroomCounter, 0.8}, - {ThermalConstants::kHeadroomForecastCounter, 0.9}, {ThermalConstants::kHeadroomCounter, 0.8}, - {ThermalConstants::kHeadroomCounter, 0.8}, {ThermalConstants::kHeadroomForecastCounter, 0.9}, - {ThermalConstants::kHeadroomCounter, 0.8}, {ThermalConstants::kHeadroomCounter, 0.8}, - {ThermalConstants::kHeadroomForecastCounter, 0.9}, - }; - EXPECT_EQ(emitted_, expected); -} - -TEST_F(ThermalCollectorTest, EmitsTheShortestDecimalOfTheFloatHeadroom) { - // Converting 0.8f straight to a double would give 0.800000011920929. - FakeThermalSource source(/*status=*/std::nullopt, /*headroom=*/0.8f, /*forecast=*/std::nullopt, - /*thresholds=*/{{ATHERMAL_STATUS_MODERATE, 0.93333334f}}); - ThermalCollector collector(source, emitter_, /*forecast_seconds=*/0); - - collector.Sample(); - collector.EmitThresholds(); - - const std::vector expected = { - {ThermalConstants::kHeadroomCounter, 0.8}, - {"sherlock.thermal.headroom.threshold.moderate", 0.93333334}, + {ThermalConstants::kHeadroomCounter, 0.8f}, {ThermalConstants::kHeadroomCounter, 0.8f}, + {ThermalConstants::kHeadroomForecastCounter, 0.9f}, {ThermalConstants::kHeadroomCounter, 0.8f}, + {ThermalConstants::kHeadroomCounter, 0.8f}, {ThermalConstants::kHeadroomForecastCounter, 0.9f}, + {ThermalConstants::kHeadroomCounter, 0.8f}, {ThermalConstants::kHeadroomCounter, 0.8f}, + {ThermalConstants::kHeadroomForecastCounter, 0.9f}, }; EXPECT_EQ(emitted_, expected); } @@ -186,7 +170,7 @@ TEST_F(ThermalCollectorTest, EmitsHeadroomWithoutRounding) { ThermalCollector(source, emitter_).Sample(); ASSERT_EQ(emitted_.size(), 2u); - EXPECT_EQ(emitted_[1], CounterSample(ThermalConstants::kHeadroomCounter, 0.8674)); + EXPECT_EQ(emitted_[1], CounterSample(ThermalConstants::kHeadroomCounter, 0.8674f)); } TEST_F(ThermalCollectorTest, OmitsHeadroomEntirelyOnDeviceThatDoesNotReportIt) { @@ -258,7 +242,7 @@ TEST_F(ThermalCollectorTest, SamplesDoNotIncludeThresholds) { const std::vector expected = { {ThermalConstants::kStatusCounter, 0}, - {ThermalConstants::kHeadroomCounter, 0.8}, + {ThermalConstants::kHeadroomCounter, 0.8f}, }; EXPECT_EQ(emitted_, expected); } @@ -284,10 +268,10 @@ TEST_F(ThermalCollectorTest, ReadsThresholdsOnceAndEmitsTheValidOnes) { EXPECT_EQ(source.ThresholdsReadCount(), 1); const std::vector expected = { - {"sherlock.thermal.headroom.threshold.light", 0.867}, - {"sherlock.thermal.headroom.threshold.moderate", 0.933}, - {"sherlock.thermal.headroom.threshold.light", 0.867}, - {"sherlock.thermal.headroom.threshold.moderate", 0.933}, + {"sherlock.thermal.headroom.threshold.light", 0.867f}, + {"sherlock.thermal.headroom.threshold.moderate", 0.933f}, + {"sherlock.thermal.headroom.threshold.light", 0.867f}, + {"sherlock.thermal.headroom.threshold.moderate", 0.933f}, }; EXPECT_EQ(emitted_, expected); } diff --git a/thermal_monitor/thermal_collector.cpp b/thermal_monitor/thermal_collector.cpp index 718d2881a5..4548319f00 100644 --- a/thermal_monitor/thermal_collector.cpp +++ b/thermal_monitor/thermal_collector.cpp @@ -15,31 +15,10 @@ #include "thermal_collector.h" -#include #include -#include -#include #include namespace apa::thermal { -namespace { - -// The NDK reports headroom as a float, and converting it straight to a double keeps the float's -// rounding error (0.8f becomes 0.800000011920929). Returns the double nearest to the shortest -// decimal that identifies the float instead (0.8). -double ToCounterValue(float value) { - // std::to_chars gives the shortest form, but the NDK's libc++ has no floating-point - // std::from_chars, so it is parsed with strtod. Neither the monitor nor the tests change the - // locale from "C", so the decimal point is '.'. - char buffer[32]; - if (const auto [end, ec] = std::to_chars(buffer, buffer + sizeof(buffer) - 1, value); ec == std::errc()) { - *end = '\0'; - return std::strtod(buffer, nullptr); - } - return static_cast(value); -} - -} // namespace ThermalCollector::ThermalCollector(ThermalSource& source, Emitter emitter, int forecast_seconds) : source_(source), @@ -84,7 +63,7 @@ bool ThermalCollector::EmitHeadroom(const char* counter, std::optional he if (!headroom.has_value() || !std::isfinite(*headroom) || *headroom < 0.0f) { return false; } - emitter_(counter, ToCounterValue(*headroom)); + emitter_(counter, *headroom); return true; } diff --git a/thermal_monitor/thermal_collector.h b/thermal_monitor/thermal_collector.h index c4ffae7c7f..d35a800bf6 100644 --- a/thermal_monitor/thermal_collector.h +++ b/thermal_monitor/thermal_collector.h @@ -29,7 +29,7 @@ namespace apa::thermal { // viewer reads. namespace ThermalConstants { // Perfetto track event category that the counters are written to. -inline constexpr const char* kTrackEventCategory = "SherlockThermal"; +inline constexpr const char* kTrackEventCategory = "Thermals"; inline constexpr int kDefaultPollIntervalMs = 1000; // Polling faster than this would only collect NaNs from the ~1 Hz rate-limited headroom API. inline constexpr int kMinPollIntervalMs = kDefaultPollIntervalMs;