Skip to content

Keep UPower rate when sysfs power read fails with ENODEV - #12649

Closed
ujo4eva wants to merge 2 commits into
omacom:quattrofrom
ujo4eva:fix/battery-enodev-fallback
Closed

ujo4eva wants to merge 2 commits into
omacom:quattrofrom
ujo4eva:fix/battery-enodev-fallback

Conversation

@ujo4eva

@ujo4eva ujo4eva commented Sep 20, 2026 •

Copy link
Copy Markdown

Single-battery HP/ACPI machines expose a power_now that passes [[ -r ]] but whose read() fails with ENODEV, so the script gets "" and awk coerces it to 0W, discarding UPower's correct energy-rate (~16-30W).

Only trust numeric sysfs reads, otherwise keep UPower's energy-rate. Same guard for the current_now/voltage_now fallback, which had the identical coerce-to-0 hole.

Split out from #6845 per @bjarneo's request — that PR grew to cover 3 failure modes and was closed as a dup of #10392, which only handles multi-battery percentage and keeps this bug. This is the minimal fix for #6895 with regression tests for both empty-read cases.

Fixes #6895.
Extracted from #6845 (3c40745).

Verified: existing battery-status-test.sh + 2 new ENODEV cases pass.

Fixes #12735


Edit: adds a regression case for the numeric power_now path (6a29528d). The guard's real risk is rejecting valid firmware values rather than only failed reads, and power_now previously had no coverage at all — the fixture only ever created it empty.

This is one of four open PRs on this block. #13009 and #13111 address a different failure: the read succeeds but the value is implausible. Those guards are complementary rather than competing, so whichever lands first should keep both. #12755 is a near-duplicate of this PR; the comparison is posted there.

Some HP/ACPI firmware exposes a readable power_now whose read() fails,
so [[ -r ]] passes but the value is empty and awk coerces it to 0W.
Only trust numeric reads, otherwise keep UPower energy-rate. Fixes omacom#6895.
@llstrk

llstrk commented Sep 23, 2026

Copy link
Copy Markdown

No actionable issue found in source review of 50a9350.

Verified by source inspection: omarchy-battery-status now keeps UPower's energy-rate when the selected sysfs reading is empty or nonnumeric. Numeric readings, including zero, still use the existing conversion.

Selected sysfs input          Before                 This PR
numeric power_now            use sysfs watts        unchanged
numeric current + voltage    use their product      unchanged
empty power_now              overwrite with 0W      keep UPower rate
empty current or voltage     overwrite with 0W      keep UPower rate

The two added regression cases cover empty power_now and empty current_now using synthetic files.


Review information

Test scope: Source inspection of the changed script and regression tests. No runtime-validation claim; actual firmware ENODEV, the UPower daemon and the graphical panel were not validated.

Community review: Independent automated community review, unaffiliated with the Omarchy team, intended to help prepare PRs for their review.

Automated AI review: Astra Medium initial inspection, independent Opus 5.5 High and GPT 6 Sol Xhigh technical assessments, followed by Astra synthesis and verification of the stated claims against the source.

@omarchybot omarchybot added bug Something isn't working compatibility Make Omarchy work better on everything! verified Omarchy Triage has verified that this issue is ready for final review labels Sep 27, 2026
@omarchybot

Copy link
Copy Markdown
Collaborator

Reviewed at 50a9350 and reproduced on a worker built from the Omarchy ISO. The fix holds.

Reproduction: with UPower stubbed at 16.8W, I pointed power_now at files that pass [[ -r ]] but whose read() fails (/proc/self/mem, which gives EIO, and a directory, which gives EISDIR). The worker has no battery attribute that returns ENODEV, but the script only sees an empty read either way. On quattro that reports rate 0W; on this head it reports rate 16.8W. The same holds for a failing current_now with a readable voltage_now. Numeric readings are unchanged: 20.5W, 0 and a negative current give the same output as before. The new cases in test/shell.d/battery-status-test.sh pass on this head and fail with the script fix reverted. ./test/cli passes. The HP firmware itself was not exercised.

Second opinion: none. The configured reviewer (Codex Medium) was out of its daily review budget, so this rests on one model's review (Claude Opus 5.5).

Related: this also fixes #12735, the same ENODEV report from a second HP Pavilion, which is now linked. #12755 makes the same change to the same lines. #13009 and #13111 rework the same block to handle numeric but implausible readings, a different failure; whichever lands first will conflict with the others.

Waiting on a second opinion before this can be marked ready, then on the maintainer.

@chiazaekpele

Copy link
Copy Markdown

Tested this on an HP laptop (Omarchy 4.0.4) with the same ENODEV hole, but here the guard alone isn't enough: UPower's energy-rate is also 0 W, so falling back to it still shows 0W while discharging.

What this machine exposes while discharging:

Source Value
BAT0/power_now not present
BAT0/current_now read() fails with ENODEV
BAT0/voltage_now ~11.1 V (works)
BAT0/charge_now works, moves in 4 mAh steps every ~20 s
UPower energy-rate 0 W (and no time to empty)

UPower presumably gets its rate from the same current_now, so there's nothing working left to fall back to.

Suggested follow-up: estimate from charge movement

When the guarded sysfs reads and UPower both give 0 while the battery is Charging/Discharging, the script records energy_now (or charge_now) on each run in $XDG_RUNTIME_DIR, keeps about the last 15 minutes of samples (plus the newest older one), and derives the rate (and time remaining, when UPower has none) from the oldest sample once ≥60 s have passed and the reading has moved in the expected direction. charge_now deltas are multiplied by the current voltage_now rather than storing energy per sample, because voltage noise would swamp the 4 mAh steps.

The panel already re-runs the script every 5 s while open, so it fills in after about a minute (0W until then) and settles as the window grows. On this machine it reads a plausible 4–6 W at idle. Machines with a working power_now/current_now/UPower rate never reach this branch.

I also folded the reads into a small read_number helper. One behaviour change from this PR: if power_now exists but can't be read, it now goes on to try current_now × voltage_now instead of skipping straight to UPower.

Diff on top of this PR (bin/omarchy-battery-status)
diff --git a/bin/omarchy-battery-status b/bin/omarchy-battery-status
index 31544b2..430fbc9 100755
--- a/bin/omarchy-battery-status
+++ b/bin/omarchy-battery-status
@@ -45,24 +45,95 @@ power_rate_raw=$(awk '/energy-rate/ { print $2; exit }' <<<"$battery_info")
 native_path=$(awk '/native-path/ { print $2; exit }' <<<"$battery_info")
 battery_path="$power_supply_path/$native_path"
 
+read_number() {
+  local value
+  value=$(cat "$1" 2>/dev/null || true)
+  [[ $value =~ ^-?[0-9]+$ ]] && echo "$value"
+}
+
 # UPower's energy-rate can lag the kernel telemetry by tens of seconds. Use
 # the instantaneous sysfs reading when available so the open panel stays live.
 # Some ACPI firmware exposes a readable power_now/current_now whose read()
 # fails with ENODEV (#6895) — only trust numeric reads, otherwise keep
 # UPower's energy-rate instead of coercing "" to 0W.
-if [[ -r $battery_path/power_now ]]; then
-  microwatts=$(cat "$battery_path/power_now" 2>/dev/null || true)
-  if [[ $microwatts =~ ^-?[0-9]+$ ]]; then
-    power_rate_raw=$(awk -v microwatts="$microwatts" 'BEGIN { print microwatts / 1000000 }')
+microwatts=$(read_number "$battery_path/power_now")
+microamps=$(read_number "$battery_path/current_now")
+microvolts=$(read_number "$battery_path/voltage_now")
+
+if [[ -n $microwatts ]]; then
+  power_rate_raw=$(awk -v microwatts="$microwatts" 'BEGIN { print microwatts / 1000000 }')
+elif [[ -n $microamps && -n $microvolts ]]; then
+  power_rate_raw=$(awk \
+    -v microamps="$microamps" \
+    -v microvolts="$microvolts" \
+    'BEGIN { print microamps * microvolts / 1000000000000 }')
+fi
+
+# When the firmware reports neither power nor current, UPower is left at 0W
+# as well. Estimate the rate from how fast the stored charge moves between
+# runs, keeping recent samples so each panel refresh extends the window.
+battery_status=$(cat "$battery_path/status" 2>/dev/null || true)
+
+if [[ $battery_status == "Charging" || $battery_status == "Discharging" ]] &&
+  awk -v rate="${power_rate_raw:-0}" 'BEGIN { exit !(rate == 0) }'; then
+  if stored=$(read_number "$battery_path/energy_now"); then
+    stored_unit=uWh
+    stored_full=$(read_number "$battery_path/energy_full")
+  elif stored=$(read_number "$battery_path/charge_now"); then
+    stored_unit=uAh
+    stored_full=$(read_number "$battery_path/charge_full")
   fi
-elif [[ -r $battery_path/current_now && -r $battery_path/voltage_now ]]; then
-  microamps=$(cat "$battery_path/current_now" 2>/dev/null || true)
-  microvolts=$(cat "$battery_path/voltage_now" 2>/dev/null || true)
-  if [[ $microamps =~ ^-?[0-9]+$ && $microvolts =~ ^-?[0-9]+$ ]]; then
-    power_rate_raw=$(awk \
-      -v microamps="$microamps" \
-      -v microvolts="$microvolts" \
-      'BEGIN { print microamps * microvolts / 1000000000000 }')
+
+  if [[ -n $stored && ( $stored_unit == "uWh" || -n $microvolts ) ]]; then
+    samples_file="${XDG_RUNTIME_DIR:-/tmp}/omarchy-battery-samples-$native_path"
+    now=$(date +%s)
+
+    # Keep samples from the last 15 minutes plus the newest older one (up to
+    # an hour), dropping any taken in another state or unit.
+    samples=$(awk -v now="$now" -v status="$battery_status" -v unit="$stored_unit" '
+      $3 == status && $4 == unit && now - $1 <= 3600 && now > $1 { line[++n] = $0; age[n] = now - $1 }
+      END {
+        first = 1
+        for (i = 1; i <= n; i++) if (age[i] > 900) first = i
+        for (i = first; i <= n; i++) print line[i]
+      }' "$samples_file" 2>/dev/null)
+
+    printf '%s%s %s %s %s\n' "${samples:+$samples$'\n'}" "$now" "$stored" "$battery_status" "$stored_unit" >"$samples_file.tmp" &&
+      mv "$samples_file.tmp" "$samples_file"
+
+    # Rate from the oldest kept sample, once a minute has passed and the
+    # reading has moved in the direction the battery state says it should.
+    read -r estimated_rate estimated_hours < <(awk \
+      -v now="$now" -v stored="$stored" -v full="${stored_full:-0}" -v status="$battery_status" \
+      -v unit="$stored_unit" -v microvolts="${microvolts:-0}" '
+      NR == 1 { then = $1; start = $2 }
+      END {
+        elapsed = now - then
+        delta = status == "Discharging" ? start - stored : stored - start
+        if (elapsed < 60 || delta <= 0) exit
+        per_hour = delta * 3600 / elapsed
+        watts = per_hour / 1000000
+        if (unit == "uAh") watts *= microvolts / 1000000
+        hours = status == "Discharging" ? stored / per_hour : (full - stored) / per_hour
+        printf "%s %s\n", watts, (hours > 0 ? hours : 0)
+      }' "$samples_file")
+
+    if [[ -n $estimated_rate ]]; then
+      power_rate_raw=$estimated_rate
+
+      if [[ -z $time_remaining ]]; then
+        time_remaining=$(awk -v hours="$estimated_hours" 'BEGIN {
+          if (hours < 1) {
+            printf "%dm", int(hours * 60)
+          } else {
+            whole = int(hours)
+            minutes = int((hours - whole) * 60)
+            if (minutes > 0) printf "%dh %dm", whole, minutes
+            else printf "%dh", whole
+          }
+        }')
+      fi
+    fi
   fi
 fi
 

Happy to open this as a separate PR with tests once this one lands, if that's preferred.

@ujo4eva

ujo4eva commented Oct 7, 2026

Copy link
Copy Markdown
Author

Thanks for the field report — this is exactly the case #12649 doesn't cover, and I'd rather you filed it than sat on it waiting.

It doesn't need to wait for #12649. The patch is written as a diff on 31544b2 so it reads as stacked, but the logic is independent. On your machine power_now is absent and current_now fails ENODEV, so both reads reject, power_rate_raw stays at UPower's 0W, and the rate == 0 gate fires. Unmodified quattro gets there identically. Please open it against quattro — your bug is "the read fails and UPower is also 0W", while #12649 is "the read fails and UPower has a good value". Different failure modes, so there's no reason for either to block the other.

Two things in the patch I'd want fixed before it goes up for review:

1. $samples_file.tmp is a fixed path. The panel re-runs the script every 5s while open, so overlapping invocations are the normal case rather than the exception. Two concurrent runs truncate and interleave the same tmp file, then mv a corrupt file into place. Separately, both read the same pre-update state, so samples are lost on every overlap. mktemp "$samples_file.XXXXXX" fixes both halves.

2. rate == 0 is exact float equality on an awk-produced value. rate < 0.05 behaves identically on your machine but doesn't pin the display if UPower ever reports something like 0.0001 W, which would otherwise read 0W indefinitely.

Two smaller notes, take or leave:

  • The $4 == unit filter means a switch between energy_now and charge_now silently resets the window. Probably fine, but worth a comment in the code so it doesn't read as a bug later.
  • The -z $time_remaining check won't fire if UPower prints time to empty: 0 seconds rather than omitting the line entirely — that parses to 0h, which is non-empty, so your estimate gets skipped in precisely the case where it's most needed.

On triage, so you're not surprised: this one won't verify automatically. The repro is specific to your firmware, so expect to be asked to justify the 15-minute retention window and the 60s warmup, and writing both rate and time-remaining from accumulated on-disk state is a larger surface than a read-guard. That's appropriate scrutiny rather than an objection — it's just the right call for what it's doing.

#12649 is up and verified, waiting on a maintainer, and I'm not widening its scope. Happy to re-test against your branch once you push, with one caveat: my HP hardware is the power_now-ENODEV case with no working current_now, so I can only exercise the "both reads reject" path, not the charge estimation itself.

The guard for unreadable sysfs reads risks rejecting valid firmware values
instead of just failed ones, and power_now had no coverage at all: the
fixture only ever created it empty. Pin the happy path so an over-tight
regex fails here rather than silently degrading to UPower's rate on real
hardware.
@greptile-apps

greptile-apps Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Medium risk] Battery status reading adds validation for sysfs power data.

The PR appears safe to merge; no actionable issues were found.

What we checked:

  • Failed reads show zero watts: The script reads UPower’s rate first. It replaces that value only when the required sysfs readings are numeric.

Summary

Keeps UPower’s energy-rate when readable battery files return empty or nonnumeric values.

  • Numeric power_now readings still take priority.
  • The current_now × voltage_now fallback now requires both values to be numeric.
  • Adds tests for valid power readings and both empty-read cases.
  • Review was based on code inspection; tests were not run.

Reviews (1) · Last reviewed commit: "Cover the numeric power_now path in the ..." · Reviewed by Greptile

@omarchybot omarchybot added verified Omarchy Triage has verified that this issue is ready for final review ready Good to merge and removed verified Omarchy Triage has verified that this issue is ready for final review labels Oct 7, 2026
@omarchybot

Copy link
Copy Markdown
Collaborator

Re-reviewed at 6a29528, which adds a numeric power_now case to test/shell.d/battery-status-test.sh, and re-ran everything on a worker built from the Omarchy ISO against current quattro. The fix holds and the new case tests what it says.

Reproduction: with UPower stubbed at 16.8W, a power_now that passes [[ -r ]] but fails to read (a directory, giving EISDIR, and /proc/self/mem, giving EIO) reports 0W on quattro and 16.8W on this head; a failing current_now beside a readable voltage_now does the same. Numeric, zero and negative readings give the same output as before. The new numeric case sets power_now to 20.5W against 10.8W from current_now × voltage_now and 7.3W from UPower, so it does prove power_now still wins, and the later cases overwrite and remove that file before they run, so their coverage is unchanged. The PR's test fails with the script fix reverted, and ./test/cli and battery-status-test.sh pass. The HP firmware's ENODEV itself was not exercised; the script sees an empty read either way.

Second opinion: Codex Medium reviewed the change and found nothing to fix, agreeing with this review; independence between the two is not guaranteed. Asked to choose between this and #12755 without being told an answer, it chose this one: #12755 also tries current_now × voltage_now when power_now fails and rejects negative readings, which is a different fallback preference rather than a defect here.

Related: #12755 makes the same fix and is newer. #13009 and #13111 handle numeric but implausible readings, a different failure, and will conflict with this block whichever lands first. The case @chiazaekpele reported, where UPower's own rate is also 0W, is outside what this fixes.

Waiting on the maintainer.

@jandrusk

Copy link
Copy Markdown

Still a real bug on live quattro: readable-but-ENODEV power_now is slurped as empty and coerced to 0W, wiping UPower’s energy-rate.

Near-duplicate open PR #12755 (“fail or are non-numeric”) looks like the broader fix; #13111 is related (implausible sysfs rate → UPower). Prefer #12755 and close this as duplicate once it covers the empty-read case (your tests for empty power_now/current_now are worth carrying over).

@ujo4eva

ujo4eva commented Oct 12, 2026

Copy link
Copy Markdown
Author

The collapse to one is right, and agreed the empty-read tests should carry over — that's the part I'd insist on.

One correction on the premise: #12755 already covers the empty-read code path (cat fails → guard rejects → UPower stands). What it lacks is my regression cases for it. So porting the tests is the requirement; a straight close without them swaps tested coverage for untested.

For the record, it's also not purely broader — ^[0-9]+$ rejects negative current_now, which the kernel ABI allows while discharging (omarchybot flagged exactly this on #12755 as a behaviour change for the maintainer to know about). Mine keeps sign handling. It is broader in one real sense: on a failed power_now read it falls through to current_now × voltage_now instead of skipping straight to UPower, which #12649 doesn't do. Both defensible; just want both on the page before anyone closes anything.

I've offered @anandude a deal on #12755: they take the signed regex and my two empty-read tests, I close this one in their favour.

@paulogeyer

Copy link
Copy Markdown
Contributor

Compared the PRs for the 0 W power reading when sysfs power_now passes -r but can't be read (#15373, also #6895, #12735). Tested on my laptop with a stub harness (fake upower reporting 21.5 W, fake power_supply tree); stock quattro reports 0W in every unreadable case.

PR Unreadable / garbage power_now Good sysfs still preferred Merges
#12649 pass / pass pass clean
#12755 pass / pass pass clean
#15541 pass / pass pass clean
#15389 pass / fail (non-numeric gives 0W) pass clean
#15377 not run not run conflicts

#12649 is the one to merge: it passes every case, keeps the live sysfs reading when it is good, and already closes #6895 and #12735. #12755, #15541, #15389 and #15377 fix the same bug and can be closed as duplicates; #13009 and #13111 cover it too as part of larger plausibility checks and both conflict.

Suggestion: add Fixes #15373 to #12649 so the newest report closes with it.

@anandude

Copy link
Copy Markdown
Contributor

Adding the one row where these two actually differ, since it decides whether they are duplicates.

The difference is where the numeric guard sits. #12649 keeps the outer -r $battery_path/power_now test with the guard inside that branch, so a readable power_now whose read yields nothing numeric enters the branch, fails the inner guard, and never reaches current_now × voltage_now — the rate stays UPower's energy-rate. #12755 folds the numeric check into the branch condition, so the same case falls through to current_now × voltage_now.

Measured just now on one stub harness (UPower 5.5W; current_now 3.0A × voltage_now 3.6V = 10.8W live), both at their current heads:

power_now #12755 #12649
readable, unknown 10.8W 5.5W
readable, 20500000 20.5W 20.5W
absent 10.8W 10.8W
readable, empty read (ENODEV-style) 10.8W 5.5W

They agree everywhere except the readable-but-unusable case, where #12755 reports the live sensor and #12649 reports UPower's lagging rate. Both are a long way from the 0W in #15373, so neither leaves the bug open — it is a difference in which non-zero number the panel shows, and that extra path is the case the last review on #12755 turned on.

Not arguing for either: both are green on quattro now and the choice is the maintainer's. Only noting the row, since "pass" on both sides of your table is right and this is the tie-break.

@anandude

Copy link
Copy Markdown
Contributor

@ujo4eva — #12755 is green on current quattro and back to verified/ready, which was the condition you set for closing here. No rush, and the maintainer may still prefer this one; just flagging that it's no longer blocked on my side.

@ujo4eva

ujo4eva commented Oct 18, 2026

Copy link
Copy Markdown
Author

Closing in favour of #12755, as I said I would once it was green and back to verified/ready — @anandude confirmed that above.

The negative-current_now objection I raised against #12755 is withdrawn: its guards now use ^-?[0-9]+$ in both branches, which was my reason for keeping this separate. I also checked its suite at the current head rather than taking it on faith — numeric power_now, non-numeric power_now and current_now, empty reads on both sysfs paths, the signed case, and an ENODEV case driven by a failing cat stub instead of an empty file, which exercises the failed read more directly than my simulation does. It's a superset of the three cases here, so nothing is lost by closing this and the coverage I cared about is already in place.

One row for the record, not an objection: on a readable-but-unusable power_now this head keeps UPower's energy-rate while #12755 falls through to current_now × voltage_now. Nonzero either way, and a preference rather than a defect.

@paulogeyer — your harness pointed at this PR, so flagging that I've gone the other way on that one row rather than on your table, which I think is right as measured.

#15373 is the newest report of the same fault and should carry the Fixes keyword on #12755 so it closes with whichever lands. Leaving the branch up, so this can be reopened if a maintainer prefers it.

@ujo4eva ujo4eva closed this Oct 18, 2026
anandude added a commit to anandude/omarchy that referenced this pull request Oct 23, 2026
…mment

The issue it points at is closed, so the comparison cannot be followed up.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working compatibility Make Omarchy work better on everything! ready Good to merge verified Omarchy Triage has verified that this issue is ready for final review

Projects

None yet

7 participants