fix(beast_power): close unit-test holes — non-finite config, SoC guards, literal headers - #190
Conversation
… in DurableCsvWriter NaN/inf max_bytes and fsync_every_n slip past a bare `<= 0` check (both comparisons are False): rotation never fires (silent disk fill) and fsync never runs (zero durability). Refuse loudly instead, like the INA219 threshold validation. A truncated/corrupt header on open (crash mid-header- write) previously appended rows under a garbage column list; now refuse to start rather than corrupt every downstream parse. Also updates the stale ChargeIntegrator docstring: RSHUNT 0.010 ohm was verified off the board 2026-08-07 (PR #187) and measures the buck/5 V logic rail only, so mAh/Wh are logic-rail truth and capacity runs are valid only with every bypassed branch idle. Tests: NaN/inf rejection cases for both parameters, refuse-on-corrupt-header (including lock release), and literal header assertions replacing the COLUMNS self-comparison.
…voltage_to_soc
+inf previously clamped to 1.0 ('100 % battery') and -inf to 0.0 on garbage
input, because only NaN was guarded. Any non-finite volts is a failed
measurement, so it now stays NaN -- never a fabricated SOC.
Tests: non-finite guard (inf/-inf/nan), full 12-knot OCV parametrization
with count and strict-ascending assertions, and a pin that
legacy_fake_percentage(NaN) stays NaN.
…sor test - is_charging with NaN current must not claim charging. - build_telemetry status branches FULL and NOT_CHARGING now asserted exactly (CHARGING/DISCHARGING already were). - the duplicated zero-volts absent-sensor tests merge into one; the OSError-propagation tests already lived in the same file, so behavior coverage is unchanged.
🤖 CodeAnt AI — Review Status
|
Thanks for using CodeAnt! 🎉We're free for open-source projects. if you're enjoying it, help us grow by sharing. Share on X · |
PR Summary by QodoFix beast_power edge cases: reject non-finite configs, guard SoC, harden CSV headers
AI Description
Diagram
High-Level Assessment
Files changed (6)
|
There was a problem hiding this comment.
Pull request overview
This PR hardens beast_power against non-finite/invalid telemetry and logger configuration values, and expands the unit test suite to prevent regressions that could silently corrupt battery status reporting or CSV logs.
Changes:
- Reject non-finite voltages in
voltage_to_soc()(returnNaNinstead of clamping to 0/1) and add tests that pin the full OCV knot table and legacy NaN behavior. - Strengthen
DurableCsvWriterto reject non-finite config values and refuse to append to CSVs with truncated/corrupt headers; update tests to assert literal headers and truncated-header refusal. - Add charging-status edge coverage (NaN current, FULL vs NOT_CHARGING branches) and consolidate overlapping absent-sensor assertions.
Reviewed changes
Copilot reviewed 6 out of 6 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| robot/beast/ros2_ws/src/ugv_main/beast_power/beast_power/logging_core.py | Adds finite checks for writer config and validates header integrity before appending; clarifies ChargeIntegrator docstring. |
| robot/beast/ros2_ws/src/ugv_main/beast_power/beast_power/soc.py | Guards SOC computation against any non-finite voltage input by returning NaN. |
| robot/beast/ros2_ws/src/ugv_main/beast_power/test/test_logging_core.py | Pins literal CSV headers, adds truncated-header refusal test, and adds NaN/inf config rejection cases. |
| robot/beast/ros2_ws/src/ugv_main/beast_power/test/test_soc_curve.py | Adds non-finite SOC tests, pins legacy NaN behavior, and pins the full OCV curve (values/order/count). |
| robot/beast/ros2_ws/src/ugv_main/beast_power/test/test_sign_convention.py | Adds tests for NaN current handling and explicitly asserts FULL / NOT_CHARGING status branches. |
| robot/beast/ros2_ws/src/ugv_main/beast_power/test/test_absent_sensor.py | Consolidates the absent-sensor “never treat 0V as 0% SOC” assertions and adds clarifying doc/comments. |
Suppressed comments (1)
robot/beast/ros2_ws/src/ugv_main/beast_power/beast_power/logging_core.py:224
fsync_every_nis typed asint, but the currentmath.isfinite(...)validation still allows floats (e.g.1.5) and booleans (True->1). Since this value controls a write counter, it’s safer to require an integer >= 1 and rejectboolto avoid silent misconfiguration.
if not math.isfinite(fsync_every_n) or fsync_every_n < 1:
raise ValueError('fsync_every_n must be >= 1 and finite')
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| # NaN/inf slip past a naive `<= 0` check (both comparisons are False) | ||
| # and would disable rotation entirely: `tell() >= NaN` is never True, | ||
| # so an unattended logger fills the disk instead of rotating. Same | ||
| # rejection rule the INA219 threshold validation uses. | ||
| if not math.isfinite(max_bytes) or max_bytes <= 0: | ||
| raise ValueError('max_bytes must be positive and finite') |
Code Review by Qodo
1.
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c4a4e7c6d2
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| with open(self._path, 'r', encoding='utf-8', newline='') as probe: | ||
| first_line = probe.readline() | ||
| expected = ','.join(self._columns) | ||
| if first_line.rstrip('\r\n') != expected: |
There was a problem hiding this comment.
Reject headers missing their record terminator
When a power loss persists every header character but not the trailing newline, readline() returns the expected text and this comparison accepts it because stripping line endings cannot distinguish a missing terminator. The writer then opens in append mode and glues the first telemetry row directly to note, corrupting the CSV header and the experiment log; require an actual \n/\r\n terminator (or repair/rotate the file) before appending.
Useful? React with 👍 / 👎.
| with open(self._path, 'r', encoding='utf-8', newline='') as probe: | ||
| first_line = probe.readline() | ||
| expected = ','.join(self._columns) | ||
| if first_line.rstrip('\r\n') != expected: |
There was a problem hiding this comment.
Suggestion: The header check strips line endings before comparing, so a file containing the complete header without its terminating newline is accepted. Appending then writes the first data row directly after the final note header text, producing a corrupt first CSV record—the exact crash-mid-header case this check is intended to prevent. Require the probed line to end in \n or \r\n before accepting it. [logic error]
Severity Level: Major ⚠️
- ❌ First telemetry row merges with the CSV header.
- ❌ Offline power-log parsing becomes malformed.
- ⚠️ Logger startup accepts corrupted persisted state.(Use Cmd/Ctrl + Click for best experience)
Prompt for AI Agent 🤖
This is a comment left during a code review.
**Path:** robot/beast/ros2_ws/src/ugv_main/beast_power/beast_power/logging_core.py
**Line:** 312:315
**Comment:**
*Logic Error: The header check strips line endings before comparing, so a file containing the complete header without its terminating newline is accepted. Appending then writes the first data row directly after the final `note` header text, producing a corrupt first CSV record—the exact crash-mid-header case this check is intended to prevent. Require the probed line to end in `\n` or `\r\n` before accepting it.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix…ct bool/non-integral config Bot review follow-up on PR #190 (3 findings): 1. Header missing its record terminator was accepted. A power loss can persist every header character but not the trailing newline; an 'a' append then merged the first data row into the header text. The probe now requires the first line to end with '\n' (covers \r\n too); a bare unterminated header raises ValueError like any other corrupt one. 2. The header probe used a separate open(path, 'r'), so a writer holding only write/append permission on its log file failed at startup. _open now opens a single 'a+' handle: appends always land at EOF, the header probe is an explicit read on the same handle (seek(0), then seek to END). No second open, no extra permission requirement; header write on an empty file, fsync, and rotation behavior are unchanged. The handle is closed (not leaked) if the probe refuses. 3. max_bytes/fsync_every_n accepted bools and non-integral floats. Bools are ints to Python and silently mean 1; 1.5 would make rotation/fsync fire at surprising times. Both rejected. Integral floats (YAML '5e6') stay accepted. Tests: unterminated-header refusal (with lock-release check), 4 new invalid-config cases (bool/non-integral for each parameter), and an integral-float acceptance test. All 5 new tests failed before the fix. Full suite: 96 passed, 5 skipped (was 90).
Bot-review follow-up — all three findings fixed in
|
User description
Phase 1 of the beast_power test-improvement plan
3 commits, all green on Windows (90 passed, 5 skipped) and CI-safe on ubuntu (same suite, no ROS).
1. Non-finite
DurableCsvWriterconfig rejection (logging_core.py)max_bytes=NaN/infandfsync_every_n=NaN/infslipped past the bare<= 0checks (NaN comparisons are False), so rotation never fired (silent disk fill) and fsync never ran (zero durability). Now rejected withValueError.max_bytesNaN/inf,fsync_every_nNaN/inf) — each fails without the fix.2.
voltage_to_socnon-finite guard (soc.py)+infclamped to 1.0 ("100 % battery") and-infto 0.0 on garbage input; only NaN was guarded. Any non-finite volts is a failed measurement → returns NaN.+inf,-inf,NaN) assertmath.isnan— all 3 fail without the fix.3. Parametrized full OCV table test (
test_soc_curve.py)All 12 knots written out literally (independent of
_3S_OCV_SOC), exact knot voltage → exact knot SOC, plus an assertion the table is strictly sorted ascending and has exactly 12 entries — a silent table edit (value, count, or order) now fails.4.
legacy_fake_percentage(NaN)pinPins current behavior (NaN in → NaN out) so a future "fix" that clamps to 0/1 is caught.
5. Charging-detection edge coverage (
test_sign_convention.py)is_charging(NaN current, 0.05)must not claim charging.build_telemetryFULL (≥full_soc while charging) and NOT_CHARGING (idle current in deadband, and NaN current) status branches asserted exactly.6. Absent-sensor file surgery (
test_absent_sensor.py)Two overlapping zero-volts tests merged into one (all assertions preserved); the OSError-propagation tests already lived in the same file, so nothing was folded in and coverage did not shrink.
7. Literal CSV header assertions (
test_logging_core.py)The two header tests self-compared against the
COLUMNSconstant (a wrong constant passed). They now assert the literal expected header string written out explicitly.8. Truncated-header recovery (
logging_core.py)Chosen behavior: refuse loudly. A crash mid-header-write left a partial first line; the writer now validates the header line on open and raises
ValueErrorinstead of appending rows under a garbage column list (lock is released; file untouched).9.
ChargeIntegratordocstringNo longer claims RSHUNT is an "unverified LeoRover default": 0.010 Ω was verified off the board 2026-08-07 (PR #187), the shunt measures the buck/5 V logic rail ONLY (motors/servos/IO bypass R21), so mAh/Wh are logic-rail truth and capacity runs are valid only with every bypassed branch idle.
Test counts
CodeAnt-AI Description
Reject invalid power measurements and protect battery logs from corrupted data
What Changed
Impact
✅ No fabricated battery percentages from invalid voltage✅ Clearer full and idle charging status✅ Fewer corrupted or unparseable power logs💡 Usage Guide
Checking Your Pull Request
Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.
Talking to CodeAnt AI
Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:
This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.
Example
Preserve Org Learnings with CodeAnt
You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:
This helps CodeAnt AI learn and adapt to your team's coding style and standards.
Example
Retrigger review
Ask CodeAnt AI to review the PR again, by typing:
Check Your Repository Health
To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.