Skip to content

Guard battery sysfs rate against bogus EC readings - #13009

Open
Kristijan-K wants to merge 15 commits into
omacom:quattrofrom
Kristijan-K:fix/battery-bogus-sysfs-rate
Open

Kristijan-K wants to merge 15 commits into
omacom:quattrofrom
Kristijan-K:fix/battery-bogus-sysfs-rate

Conversation

@Kristijan-K

@Kristijan-K Kristijan-K commented Sep 23, 2026 •

Copy link
Copy Markdown

On some machines the EC reports a bogus but numeric current. My MSI Prestige 14 Flip AI+ (BAT1 BIF0_9) reports current_now=-65A for a ~7.5W discharge, so the panel showed Discharging -1124W while UPower correctly reported 7.5W.

The sysfs override only guarded readability, so any numeric value clobbered the good UPower rate. This now:

  • only trusts sysfs reads that succeed and are numeric (allows negative current_now, the normal discharging sign),
  • rejects insane magnitudes (>150W) or values wildly above UPower's rate (>3x when UPower is solid), keeping the UPower value instead,
  • displays the rate as magnitude (state already says charging/discharging, so no more -1124W),
  • compares idle against magnitude so a large negative rate cannot fake charge-idle,
  • omits cycle_count 0 when UPower reports charge-cycles N/A so the panel shows — instead of a misleading 0.

Fallback when UPower wedges entirely. On the same hardware UPower can sit at energy-rate: 0 W for hours, and it then drops its time to empty line as well. charge_now still moves, so the script estimates the rate from charge deltas across a 30–120s history kept in $XDG_RUNTIME_DIR (or OMARCHY_BATTERY_CACHE). Each cache line records the battery and state, so a sample from another battery, another state, the future, or outside the window is never measured against the current one. The estimate only runs when neither sysfs nor UPower supplied a usable rate. Time left comes from the rate the script settled on, so the two always agree. Batteries that expose energy but no charge carry no sample and keep UPower's rate.

Scope. Rebasing onto current quattro dropped the parts this PR had duplicated: #15285 now derives time left from the rate shown and #15326 formats durations through omarchy-i18n, so the branch's own time derivation and its untruncated-capacity fix are gone. What remains is the plausibility guard, the cycle-count suppression and the charge-delta estimator. If the estimator makes this hard to classify, say so and I will split it into its own PR — the guard and cycle display stand alone as a bug fix.

Complements #12649/#12755 (those cover failed/empty reads); this covers bogus-but-numeric reads. Overlaps #13111: same sysfs block and same test file, with a different policy for high-but-plausible sysfs values (it accepts a plausible 60W against UPower's 8W; the 3x guard here keeps UPower's 8W). Happy to rebase on whichever lands first.

Verified with the extended test/shell.d/battery-status-test.sh (bogus -65A, non-numeric, sane negative discharge, plausible-but-high, estimator window/identity/validation, cycle suppression) plus live hardware: bogus -1113W discharge now shows 7.5W, and a sane 29.1W charge still uses the live sysfs value.

@llstrk

llstrk commented Sep 23, 2026

Copy link
Copy Markdown

No actionable defects found in the reviewed scope at 373d63a.

Verified: With synthetic sysfs inputs and stubbed UPower reporting 7.3 W, the actual base and PR scripts produced:

Input Base PR
Current −65 A, voltage 12 V −780 W 7.3 W fallback
Non-numeric current 0 W 7.3 W fallback
Current −0.5 A, voltage 12 V −6 W 6 W
Current 0.9 A, voltage 12 V 10.8 W 10.8 W

Source inspection also confirms that idle detection uses magnitude, and that omitting an unavailable zero cycle count reaches the panel's missing-value fallback.


Review information

Test scope: Targeted synthetic base/PR comparisons and source inspection, not execution of the stock test suite. Real battery hardware, rendered UI and UPower refresh timing were not tested. The ratio guard can also reject genuine rapid load increases while UPower lags; the practical frequency and duration of that trade-off remain unverified.

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, then Astra synthesis against source and targeted evidence. Opus ran the synthetic comparisons; Sol's assessment was source-only.

@llstrk

llstrk commented Sep 24, 2026

Copy link
Copy Markdown

Automated AI review

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

Follow-up to the earlier automated review of 373d63a. Checked revision: ed23094 ("Estimate battery rate from charge deltas when UPower wedges at 0W").

Outcome: The earlier review's verified results still hold at ed23094. The new charge-delta fallback computes the expected value in its test case. ed23094 introduces three new findings in when the fallback runs and how it samples, plus a timing-dependent test assertion.

Verified:

  • The earlier table is unchanged at ed23094 (stubbed UPower 7.3 W: −65 A gives 7.3 W, non-numeric gives 7.3 W, −0.5 A gives 6 W, 0.9 A gives 10.8 W). The fallback only runs when UPower reports 0.5 W or less, and the ratio guard only applies above 0.5 W, so the two never interact. Magnitude-based idle detection, the zero cycle-count omission and the earlier ratio-guard trade-off are unchanged.
  • The estimate arithmetic is correct: sysfs charge_now in µAh times voltage_now in µV, over the elapsed hours. 9000 µAh in 60 s at 12 V is 6.48 W, shown as 6.5W. It only accepts a falling charge while discharging and a rising charge while charging, a 5 to 600 s window and results from 0.2 to 150 W.
  • The premise matches UPower v1.91.4 source: after one reading above 0.01 W, UPower stops using its own history estimator, and it zeroes readings above 300 W. A persistent −65 A report can therefore keep energy-rate at 0 W. The UPower version the author tested is not stated.
  • Both new assertions catch what they claim. The new test fails against the 373d63a script at the wedge assertion, and a variant without the 600 s limit fails the stale-cache assertion.

New: The estimate window restarts on every call

bin/omarchy-battery-status rewrites the cache on every call, so each estimate covers only the time since the previous call. The power panel refreshes every 5 s while open (shell/plugins/panels/power/Panel.qml:231). The kernel ACPI battery driver exposes charge_now in whole 1 mAh steps for charge-unit batteries, and one step in 5 s at 12 V is 8.64 W.

Predicted panel values (synthetic arithmetic: 12 V, constant load, 1 mAh steps, exact 5 s polling; not measured on hardware):

Actual load Displayed rate
about 4 W alternates between 0W and 8.6W
7.5 W mostly 8.6W, sometimes 0W
20 W alternates between 17.3W and 25.9W
7.5 W, polled every 60 s 7.2W to 7.9W

A gap under 5 s, including an apparent 4 s gap from whole-second timestamps, gives no estimate but still replaces the reference sample.

Impact: On the targeted hardware, the open panel is likely to jump between 0W and multiples of about 8.6 W instead of following the load. The real firmware step size and panel behavior were not observed.

Suggested change: Keep the reference sample until a minimum window has passed (for example 30 to 60 s), or keep a small ring of samples and use the oldest one within 600 s. UPower's own estimator requires at least 15 s of history and looks back over several samples.

New: The fallback replaces an accepted sysfs reading

The fallback only checks that UPower reports 0.5 W or less (bin/omarchy-battery-status:85). It does not check whether the sysfs rate was rejected. With UPower at 0 W and a sane sysfs reading of 0.9 A at 12 V:

Revision Cache Displayed rate
373d63a none 10.8W (sysfs)
ed23094 none 10.8W (sysfs)
ed23094 9000 µAh drop over 60 s 6.5W (estimate)

Impact: The UPower v1.91.4 source reports 0 W for about 10 s after AC plug or unplug and after resume, so on healthy hardware a live reading can briefly give way to an older average. On the bogus-current hardware this PR targets, sysfs is rejected anyway.

Suggested change: Run the estimate only when the sysfs reading was absent or rejected, as the "last resort" comment describes.

New: The cached sample has no battery or state identity

The cache line holds only timestamp charge voltage in one file (bin/omarchy-battery-status:108). Nothing checks that the sample came from the battery now selected (upower -e | grep BAT | head -n 1) or from the same charge state. Synthetic cases with stubbed UPower at 0 W and rejected sysfs current:

Sequence Displayed rate
BAT0 sampled, then BAT1 listed first, BAT1 idle at similar charge 6.5W for a battery that is not discharging
Charging, then unplugged, 10 W actual discharge 4.6W
Discharging, then plugged in, 30 W actual charge 1.2W
Pack swapped on AC, sample kept through the no-battery gap 36W

Impact: It needs a multi-battery or hot-swap machine, or a charge/discharge change inside the window. The sign is never wrong, and the effect usually lasts one refresh. After the panel is reopened it can use a sample up to 600 s old.

Suggested change: Write native_path and state into the cache line and reject the sample unless both match. Optionally name the cache file after native_path.

Optional test improvement: The wedge test writes the cache as $(date +%s) - 60 (test/shell.d/battery-status-test.sh:95), and the script reads the clock again. If a second boundary passes between those reads, the gap is 61 s and the output is 6.4W, not 6.5W. The unmodified test failed 7 of 400 sandboxed runs, each time on this assertion, and a clock stub that advances 1 s per call fails every time. Adding a date stub to $tmp_dir/wedge/bin, or picking values that round the same way at 60 and 61 s, would make the test deterministic.

Note: When XDG_RUNTIME_DIR is unset, the cache falls back to a fixed name in the shared /tmp. Batteries that expose only energy_now get no fallback estimate.


Review information

Test scope: Source inspection of ed23094 against 373d63a, UPower v1.91.4 and the Linux power-supply ABI and ACPI battery driver, plus sandboxed runs of the head battery-status-test.sh and synthetic scenarios. The scenarios used stubbed UPower, synthetic sysfs files and a controlled clock. No real battery, EC, UPower daemon or rendered panel was used, and the full test suite was not run. The estimate-window figures are arithmetic predictions. The author's firmware step size and UPower version are unknown.

AI process: Opus 5.5 Medium coordination and synthesis. Independent Opus 5.5 Xhigh and GPT 6 Sol Xhigh technical assessments of this follow-up, each followed by one targeted cross-check. Opus 5.5 Medium editorial check.

Opt out: To stop receiving these reviews, reply to this comment saying so.

@Kristijan-K

Copy link
Copy Markdown
Author

Addressed in 354495d1 ("Hold charge-delta samples long enough to stop panel flicker"):

  1. Window restarts every call — now keeps a history of samples and estimates across the oldest sample at least 30s old (max 600s), so 5s polling no longer quantises into 0W/8.6W alternation. Verified by simulating 5s polling at 1mAh steps: stable ~6-7W instead of flicker.
  2. Fallback replaced accepted sysfs — the estimate now runs only when the sysfs reading was absent or rejected, gated on sysfs_usable.
  3. No battery/state identity — each cache line records native_path and state; mismatched samples are ignored. Tests cover foreign-battery and foreign-state samples.
  4. Flaky test assertion — a date stub returns a fixed +%s, so the 60s window is deterministic (previously failed ~7/400 sandboxed runs).

Full ./test/shell failures are byte-identical to the base branch (5 pre-existing environment failures: omarchy-pkgs, linux-omarchy headers, omasnap), so no regressions.

UPower version tested: 1.91.3 (upowerd on this machine).

@Kristijan-K

Copy link
Copy Markdown
Author

Follow-up (commit 05f1edc1): derive the remaining time when UPower omits it.

Hit a second symptom of the same wedge on this machine. When upowerd wedges at energy-rate: 0 W, it also drops its time to empty line completely, so the panel showed a correct rate from the charge-delta fallback but — for time left:

percentage  92%
state       discharging
rate        9.1W      # charge-delta fallback
size        82Wh
time                  # UPower omitted it, nothing filled in

The script only ever sourced time from UPower, so I added a fallback: when UPower gives no time estimate but a usable rate is available, derive it from energy over that rate — energy / rate while discharging, (energy-full - energy) / rate while charging. Now 92% · 9h 50m left · 7.7W.

Tests cover both shapes: time derived while UPower is wedged (4h 22m), and time derived when UPower reports a rate but omits time (3h 52m). ./test/shell still fails only the 5 pre-existing environment cases (omarchy-pkgs, linux-omarchy headers, omasnap), same as base.

Root cause note: the EC reports current_now ≈ -65A for a real ~9W draw, which poisons upowerd repeatedly (it zeroes the impossible rate and gives up its estimator). That is a firmware/kernel reporting bug — this PR is the userspace workaround.

@llstrk

llstrk commented Sep 27, 2026

Copy link
Copy Markdown

Automated AI review

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

Follow-up to the earlier automated review of ed23094 and the author's replies (1, 2). Checked revision: 05f1edc ("Derive remaining time from energy when UPower omits it").

Outcome: Three of the earlier findings are resolved at 05f1edc. The battery-identity finding is resolved for three of its four cases; the same-slot pack swap remains. The new 10-minute history introduces two new findings: after a suspend, a hold on AC or a same-slot pack swap, the estimate can stay badly wrong for several minutes (and the new remaining time with it), and cached charge and voltage fields reach shell arithmetic without validation. A smaller issue affects time to full.

Earlier findings

Earlier finding Status at 05f1edc Synthetic result (12 V, 1 mAh steps, UPower at 0 W)
Estimate window restarts on every call Resolved Sysfs rejected, 5 s polling: 7.5 W load reads 7.3W–7.7W after the first minute, instead of 8.6W/0W. 0W for the first 30 s, as the code comment describes.
Fallback replaces an accepted sysfs reading Resolved Accepted sysfs 0.9 A with a 60 s cache: 10.8W (sysfs), previously 6.5W (estimate)
Cached sample has no battery or state identity Three of four cases resolved Foreign battery, charging then unplugged, discharging then plugged in: now 0W instead of a borrowed value. Same-slot pack swap: still wrong, see the first new finding.
Clock-dependent wedge test (optional) Resolved A date stub fixes the clock; the test passed 50 of 50 sandboxed runs

Verified:

  • The estimate now uses the oldest kept sample that is at least 30 s old, up to 600 s. It runs only when sysfs was absent or rejected, and each cache line records native_path and state.
  • The author's UPower 1.91.3 matches the premise. Once a rate above 0.01 W has been seen, UPower keeps trusting the reported current and zeroes rates above 300 W. It computes a time only when its rate is above 0.01 W, and upower -i prints the time only when it is above 0. So a wedged 0 W rate also drops the time line, as the second reply describes.
  • The new tests for sysfs preference and for foreign battery and state each fail when that guard is removed.

Not rechecked: The replies' statement that the full ./test/shell failures match the base branch. Within ./test/shell, only battery-status-test.sh runs this script.

New: The 10-minute window spans suspend, AC holds and same-slot swaps

The window uses wall-clock timestamps (date +%s) and always measures from the oldest kept sample, up to 600 s old. Nothing resets the history when the reading is interrupted:

  • The wall clock keeps running during suspend.
  • pending-charge, fully-charged and unknown skip sampling but leave the cache as it is (bin/omarchy-battery-status:109-116), so a battery held at a charge limit on AC and then unplugged reuses samples from before the hold.
  • A pack swapped into the same slot keeps BAT0 and the same state, so it passes the identity check.

A window that includes little or no drain underestimates the rate, and the new time derivation divides energy by that rate, so the remaining time is inflated by the same factor. A swapped pack instead gives a rate that is far too high.

Synthetic timelines (10 W actual load, 0.5 W while suspended, 5 s polling while the panel is open; "settles" means first within 15% of the actual rate):

Scenario First estimate at 05f1edc Settles after ed23094
Discharging with the panel open, suspended 180 s, panel reopened 1.5W, 31h 41m left (about 4h 41m once settled) ~415 s 1.1W for one refresh, then 8.6W/17.3W
Suspended 300 s with the panel open 5.3W, 8h 50m, flat for ~5 min ~305 s 0.7W for one refresh
Discharging 60 s, held on AC (pending-charge) 180 s, unplugged 2.6W, 18h 4m ~420 s 0W for one refresh, then 8.6W
Same-slot pack swap, 30 W actual charge (script output; see the panel note below) 0W for ~20 s, then 147.7W; about 50W after 9 minutes ~585 s 36W for one refresh

UPower's own estimator discards its history on resume and on AC changes. The code comment at :101-102 says "a swapped pack or an AC transition can never borrow a reading from the previous battery state"; the swap and AC-hold sequences above do. The earlier review suggested using the oldest sample within 600 s, and that suggestion did not account for these interruptions.

Impact: On the hardware this PR targets (where the UPower wedge persists across resume), opening the lid after a suspend, or unplugging after a hold at a charge limit, can show a rate several times too low with a remaining time several times too long, for several minutes. At ed23094, the carried-over sample affected only one refresh in these sequences. A steady load after a 5 W to 25 W step also takes about 8 minutes to reach within 15%.

Suggested change: A shorter maximum window, for example maximum_window=120, fixed all four scenarios in the synthetic runs. The first three recovered within about 30 s (0W, then about 10 W), the swap in about 2 minutes. A steady 7.5 W still read 7.2W–7.7W, and the 5 W to 25 W step settled in 95 s instead of 485 s. The cost is 0W for the first 30 s after any gap longer than 120 s. Alternatively, clearing the history when the gap between samples exceeds about 30 s and on any state other than charging or discharging fixed suspend, the AC hold and the swap in the synthetic runs, but not the slow response to a load step.

Optional test improvement: No test checks which sample is used as the reference. A variant that uses the youngest sample at least 30 s old passes the current test file.

New: Cached charge and voltage fields are not validated before arithmetic

The cache reader checks only the timestamp (:125). The charge and voltage fields go straight into $((charge_sample - sample_charge)) and $(((volt_sample + sample_volt) / 2)) (:139, :142). ed23094 checked all three fields against ^[0-9]+$.

Cache field (synthetic, estimate path) 05f1edc ed23094
Charge containing a command substitution inside an array subscript The command ran, and the line was kept in the rewritten cache Line ignored
Charge 46abc value too great for base on stderr, rate 0W Line ignored
Voltage missing 3.2W, 8h 44m (instead of 6.5W, 4h 22m) Line ignored

Impact: The cache normally sits in the user's own $XDG_RUNTIME_DIR. When XDG_RUNTIME_DIR is unset, it falls back to the fixed /tmp/omarchy-battery-rate.cache, which another local account could create first. The unchecked arithmetic only runs when the estimate runs, so the likelihood is low on a single-user laptop. A corrupt line still gives a wrong reading. Cross-account /tmp behavior was not tested.

Suggested change: Add [[ $sample_charge =~ ^[0-9]+$ && $sample_volt =~ ^[0-9]+$ ]] || continue to the read loop. Optionally, skip caching when XDG_RUNTIME_DIR is unset.

New: Time to full uses the truncated capacity

The charging branch computes capacity - energy_now (:176-177), but capacity is energy-full truncated to whole Wh for display (:42). Synthetic: 55.9 of 56.7 Wh charging at 5 W shows 1m, while UPower's formula gives about 9.6 minutes. The error is at most 1 Wh divided by the rate, so it matters most near full.

Impact: Near full charge, the time to full is too short. It appears in the omarchy-notification-battery line, and in the panel from 99% up (see the note below).

Suggested change: Parse energy-full separately, without %d, for this calculation. None of the new tests cover the charging branch.

Note (panel, base behavior): While charging below 99% with UPower's rate at 0 W, the power panel does not show the script's estimated rate or derived time to full. Model.chargeThresholdActive treats a charging battery at 0.2 W or less as held (shell/plugins/panels/power/Model.js:63), so the panel shows "Charge limit" and "Holding" instead. This is unchanged from the base branch (source inspection, no rendered panel). Discharging, the case in the replies, is shown normally. The charging-side estimate currently reaches the user mainly through the notification.

Note: Open PR #13111 addresses the same bogus-current symptom with a different policy. It accepts a plausible sysfs rate far above UPower's (60 W against 8 W in its test), where this PR's 3x guard keeps UPower's 8 W. Both add a guard in the same sysfs-rate block and change the same test file.

Note (unchanged): When XDG_RUNTIME_DIR is unset, the cache still falls back to the shared /tmp. Batteries that expose only energy_now still get no estimate.


Review information

Test scope: Source inspection of 05f1edc against ed23094 and the base, UPower 1.91.3 and the power panel source, plus sandboxed runs of the head battery-status-test.sh and synthetic timelines with stubbed UPower and date, synthetic sysfs and a controlled clock. No real battery, EC, UPower daemon, suspend or rendered panel was used, and the full test suite was not run. The window figures are arithmetic predictions for the stated synthetic loads. Real firmware step sizes and suspend drain are unknown.

AI process: Opus 5.5 Medium coordination and synthesis, Opus 5.5 Xhigh technical review and final fact check, GPT 6 Sol Xhigh search for related issues, Opus 5.5 Medium editorial check.

Opt out: To stop receiving these reviews, reply to this comment saying so.

@Kristijan-K

Copy link
Copy Markdown
Author

All three new findings addressed in cd81d771 ("Bound the charge-delta window and validate its cache").

1. 10-minute window spanned suspend, AC holds and same-slot swaps

  • maximum_window 600 → 120, so a stale reading ages out within two minutes instead of ten.
  • Added a reset_gap of 45s: if the newest sample is older than that, the whole history is discarded rather than measured across. Suspend, a hold at a charge limit (pending-charge/fully-charged sample nothing and left the cache alone) and a same-slot pack swap all now start from a clean window.
  • Cost as you described: 0W for the first 30s after any gap, then the estimate.

2. Cache fields reached shell arithmetic unvalidated

  • The read loop now requires sample_charge and sample_volt to match ^[0-9]+$, same as the timestamp. An invalid line is dropped and not carried into the rewritten cache.
  • Also removed the shared-/tmp fallback: with neither OMARCHY_BATTERY_CACHE nor XDG_RUNTIME_DIR set, the script does not cache at all rather than trusting a fixed world-writable name.

3. Time to full used the truncated capacity

  • energy-full is now parsed separately without %d and used for the charging branch. 55.9 of 56.7 Wh at 5W now reports 9m instead of 1m.

Tests. Added coverage for the oldest-sample reference, gap reset, non-numeric cache fields and untruncated capacity. I checked each new assertion is load-bearing by removing the guard it covers and confirming the test goes red — the first attempt at the cache-field test passed without the guard because the 60s gap was dropping the line via the gap reset, so that sample is now recent enough to isolate the validation.

./test/shell still fails only the same 5 pre-existing environment cases (omarchy-pkgs, linux-omarchy headers, omasnap).

On #13111: agreed it overlaps — same sysfs-rate block and same test file, different policy on plausible-but-high sysfs values (its 60W vs UPower 8W case, where the 3x guard here keeps UPower). Happy to rebase on whichever lands first so the other only has to reconcile the policy difference.

@llstrk

llstrk commented Sep 30, 2026

Copy link
Copy Markdown

Automated AI review

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

Outcome: The 45 s reset also fires after the panel is closed for over 45 s, so quick glances show no estimate.

Earlier findings (review, rechecked at cd81d77 after the author's reply): all resolved (window across suspend, holds and swaps for gaps over 45 s; cache validation; time to full; test).

Reopening the panel after 45 s restarts the estimate

When UPower is wedged and sysfs rejected, a reopen after 45 s shows 0W and no time for 30 s. A hotkey press gets an estimate only if the script ran 30 to 45 s earlier. 05f1edc estimated on the first refresh; the base never estimates, so this is not a regression.

Suggested change: Keep history across ordinary closes (for example resetting on resume, not elapsed time), or document this cost at bin/omarchy-battery-status:102-104.

Reproducer (sandboxed run at cd81d77 and 05f1edc)

Reproducer: the 45 s reset also discards history between panel openings

Reviewed head: cd81d771454f9c4349fb59d72ea5e6b7c7367c75. Compared with 05f1edc.

This is the behaviour the author accepted ("0W for the first 30s after any
gap"); the reproducer shows that an ordinary panel close counts as such a gap.

PR-style snippet

Appended to test/shell.d/battery-status-test.sh before the final rg
check (reuses the wedge fixture: UPower 0 W, sysfs current -65 A,
charge_now 4600000, 12 V, date +%s = 1800000060):

# Steady 7.5 W (19 mAh in 110 s), last refresh 60 s ago, panel reopened now.
printf 'BAT0 discharging 1799999950 4619000 12000000\n' >"$tmp_dir/reopen.cache"
printf 'BAT0 discharging 1800000000 4610000 12000000\n' >>"$tmp_dir/reopen.cache"
reopen_output=$(OMARCHY_POWER_SUPPLY_PATH="$tmp_dir/wedge/power" OMARCHY_BATTERY_CACHE="$tmp_dir/reopen.cache" PATH="$tmp_dir/wedge/bin:$PATH" "$ROOT/bin/omarchy-battery-status" --shell)
printf 'REPRO reopen: %s | %s\n' "$(grep $'^rate\t' <<<"$reopen_output")" "$(grep $'^time\t' <<<"$reopen_output")"

Actual output (sandboxed run):

cd81d77:  REPRO reopen: rate	0W | time	
05f1edc:  REPRO reopen: rate	7.5W | time	3h 47m

Timelines (actual script, stubbed UPower at 0 W and clock, 12 V, 1 mAh steps, 7.5 W load)

Panel open 20 s (refresh every 5 s), closed, then reopened:

Closed for cd81d77 first 30 s after reopening 05f1edc
20 s 7.6W to 8W from the first refresh same
40 s 7.6W to 8.1W from the first refresh same
60 s 0W, no time, for refreshes at 0 to 25 s; 8.6W at 30 s 7.6W to 7.9W from the first refresh
300 s 0W, no time, for 0 to 25 s; 7.2W at 30 s 7.5W to 7.6W from the first refresh

Single invocations (the Super+Ctrl+Alt+B notification runs the script once):

Calls cd81d77 05f1edc
t=0, t=300 s 0W, 0W 0W, 7.6W
t=0, t=35 s 0W, 8.6W same

Periodic caller, 600 s at 7.5 W:

Interval cd81d77 calls with an estimate 05f1edc
30 s 20 of 21 20 of 21
45 s 13 of 14 13 of 14
50 s 0 of 13 12 of 13
60 s 0 of 11 10 of 11

The base branch never estimates. With the same fixture (UPower 0 W, sysfs
current -65 A at 12 V) the merge-base script d3cfd53 printed -780W with an
empty time on every call, because it uses any readable sysfs reading
(bin/omarchy-battery-status:50-57 at d3cfd53). So this is not a regression
against quattro; it narrows the fallback's benefit relative to 05f1edc.

Details

Verified:

  • Suspend 180 s, AC hold 180 s and a same-slot swap with 60 s absent now give 0W until the 30 s refresh, then within 15% of the actual rate (synthetic 10 W and 30 W loads).
  • Cache lines with a command substitution, 46abc or a missing voltage are dropped at 35 s old; no cache is written when neither OMARCHY_BATTERY_CACHE nor XDG_RUNTIME_DIR is set.
  • Time to full uses untruncated energy-full (9m in the new test), matching UPower's formula.
  • The full ./test/shell fails the same files at cd81d77 and the merge base; none involve this script.

Limit: Interruptions of 45 s or less are still measured across (40 s suspend at 10 W: 6.8W, within 15% after 80 s), so the comment's "can never borrow a reading" holds only for longer gaps.

Suggested change, other options: A background sampler would also keep history across closes. An AC hold or pack swap while the panel is closed leaves nothing a non-running script can observe, so each option has its own cost.

Optional test improvement: The identity and stale-cache tests seed samples older than 45 s, which the reset would discard anyway. Mutants without the identity check, with a 600 s window or without the voltage check pass the head test file; the block below catches each.

Reproducer: tests no longer isolate three cache guards at cd81d77

Reviewed head: cd81d771454f9c4349fb59d72ea5e6b7c7367c75.

1. Mutants that pass the unmodified test/shell.d/battery-status-test.sh

Each mutant is bin/omarchy-battery-status at cd81d77 with one change; the
test file is the one at cd81d77, run with bash test/shell.d/battery-status-test.sh.

Mutant Change Result
no identity check delete line 135 ([[ $sample_battery == "$native_path" && $sample_state == "$state" ]] || continue) exit 0, ok - battery status owns capacity and remaining calculations
600 s window maximum_window=120 becomes maximum_window=600 exit 0, same ok line
no window filter delete line 138 ((( now_ts - sample_ts <= maximum_window )) || continue) exit 0, same ok line
charge-only check line 137 checks only $sample_charge exit 0, same ok line

The same identity mutant applied to the 05f1edc script, run against the
05f1edc test file, fails:

not ok - battery status ignores samples from another battery
not ok - battery status ignores samples from another state

Why: the identity and stale-cache tests seed samples 60 s and 1060 s old
(1800000000, 1799999000 with the clock stubbed at 1800000060). The new
reset_gap=45 (line 148) discards any history whose newest sample is older
than 45 s, so these samples would be discarded even without the identity or
window check (at cd81d77 those checks, lines 135 and 138, still run first).

The non-numeric test (line 127) seeds a sample 5 s old, below the 30 s
minimum_window, so the estimate loop never evaluates it. Without the numeric
guard, its rate 0W assertion (line 129) still passes; only the carry-forward
check (line 130) fails:

not ok - battery status drops non-numeric cache samples

2. Test additions that do isolate them

Insert before the final rg check in test/shell.d/battery-status-test.sh
(reuses the file's wedge fixture: UPower 0 W, sysfs current -65 A,
charge_now 4600000, 12 V, date +%s = 1800000060):

# Identity samples 35s old, so the 45s gap reset cannot be what drops them.
printf 'BAT1 discharging 1800000025 4609000 12000000\n' >"$tmp_dir/other35.cache"
other35_output=$(OMARCHY_POWER_SUPPLY_PATH="$tmp_dir/wedge/power" OMARCHY_BATTERY_CACHE="$tmp_dir/other35.cache" PATH="$tmp_dir/wedge/bin:$PATH" "$ROOT/bin/omarchy-battery-status" --shell)
grep -Fx $'rate\t0W' <<<"$other35_output" >/dev/null || fail "battery status ignores a 35s-old sample from another battery" "$other35_output"
printf 'BAT0 charging 1800000025 4609000 12000000\n' >"$tmp_dir/state35.cache"
state35_output=$(OMARCHY_POWER_SUPPLY_PATH="$tmp_dir/wedge/power" OMARCHY_BATTERY_CACHE="$tmp_dir/state35.cache" PATH="$tmp_dir/wedge/bin:$PATH" "$ROOT/bin/omarchy-battery-status" --shell)
grep -Fx $'rate\t0W' <<<"$state35_output" >/dev/null || fail "battery status ignores a 35s-old sample from another state" "$state35_output"

# A sample chain longer than 120s; the reference must be the oldest sample inside 120s.
printf 'BAT0 discharging 1799999920 4620000 12000000\n' >"$tmp_dir/window.cache"
printf 'BAT0 discharging 1799999960 4610000 12000000\n' >>"$tmp_dir/window.cache"
printf 'BAT0 discharging 1800000000 4606000 12000000\n' >>"$tmp_dir/window.cache"
printf 'BAT0 discharging 1800000040 4602000 12000000\n' >>"$tmp_dir/window.cache"
window_output=$(OMARCHY_POWER_SUPPLY_PATH="$tmp_dir/wedge/power" OMARCHY_BATTERY_CACHE="$tmp_dir/window.cache" PATH="$tmp_dir/wedge/bin:$PATH" "$ROOT/bin/omarchy-battery-status" --shell)
grep -Fx $'rate\t4.3W' <<<"$window_output" >/dev/null || fail "battery status measures within the 120s maximum window" "$window_output"

# A sample old enough to reach the arithmetic, with its voltage missing.
printf 'BAT0 discharging 1800000025 4609000\n' >"$tmp_dir/novolt.cache"
novolt_output=$(OMARCHY_POWER_SUPPLY_PATH="$tmp_dir/wedge/power" OMARCHY_BATTERY_CACHE="$tmp_dir/novolt.cache" PATH="$tmp_dir/wedge/bin:$PATH" "$ROOT/bin/omarchy-battery-status" --shell)
grep -Fx $'rate\t0W' <<<"$novolt_output" >/dev/null || fail "battery status ignores a sample without a voltage" "$novolt_output"

3. Actual results (sandboxed runs, continue-on-failure copy of the test)

Script Failing assertions (rate printed)
cd81d77 unchanged none; stock run exits 0
no identity check 35s-old sample from another battery (rate 11.1W); from another state (rate 11.1W)
600 s window 120s maximum window (rate 6.2W)
no window filter 120s maximum window (rate 6.2W)
charge-only check sample without a voltage (rate 5.6W)
no numeric check drops non-numeric cache samples; sample without a voltage (rate 5.6W)

Expected values: 9000 uAh over 35 s at 12 V is 11.1 W; 10000 uAh over 100 s
is 4.3 W, 20000 uAh over 140 s is 6.2 W; a missing voltage halves the average
voltage, giving 5.6 W.

Note: Open PR #13111 still conflicts in both files.


Review information

Test scope: Source and sandbox tests (stubbed UPower and clock) at cd81d77; no hardware, suspend or rendered panel.

AI process: Opus 5.5 Medium coordination and synthesis, Opus 5.5 Xhigh technical review and final fact check, GPT 6 Sol Xhigh search for related issues, Opus 5.5 Medium editorial check.

Opt out: To stop receiving these reviews, reply to this comment saying so.

@Kristijan-K

Copy link
Copy Markdown
Author

Both findings valid, addressed in ba6ae6cd ("Keep charge history across ordinary panel closes").

1. The 45s reset also fired on ordinary panel closes

The critique was right, and my "0W for the first 30s after any gap" framing understated it: a script that only runs while the panel is open cannot tell a closed panel from a suspend, so a normal close counted as a gap. Reproduced at cd81d771 with the reviewer's fixture — samples 110s and 60s old, reopen now gave rate 0W / blank time versus 7.5W / 3h 47m at 05f1edc.

Fix: removed reset_gap entirely and kept maximum_window=120. That was the earlier review's validated suggestion, and it already bounds staleness on its own. The gap reset was the redundant half and the only thing breaking quick glances.

  • close ≤120s → estimates immediately on reopen
  • close >120s → no recent sample, so 0W for the first 30s (unavoidable without a background sampler; now documented in the code comment instead of the overstated "can never borrow")

2. Three tests no longer isolated their guards

Confirmed: removing the identity check left the suite passing. The identity/state seeds were 60s old and the stale seed 1060s old, so the gap reset discarded them before the guards mattered. Now that the reset is gone they isolate again, and I hardened them anyway:

  • identity and state samples moved to 35s old (inside the window, past the 30s minimum)
  • new sample chain 140s/100s/20s old to pin the 120s threshold
  • new missing-voltage sample (without the voltage check it averaged voltage as half, giving 5.6W)
  • new close/reopen pair: estimates after a short close, and does not after one longer than the window

Verified every guard is load-bearing with six mutants — identity removed, maximum_window=600, window filter removed, charge-only check, no numeric check, and youngest-sample reference. Each is caught by a named assertion.

./test/shell still fails only the same 5 pre-existing environment cases.

#13111 still conflicts in both files; the offer to rebase on whichever lands first stands.

@greptile-apps

greptile-apps Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5 · The PR appears safe to merge; no new actionable issues remain.RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; no new actionable issues remain.

Summary

Guards live battery readings and adds a charge-history fallback when UPower cannot supply a useful rate.

  • Battery status keeps implausible sysfs rates from taking over the displayed reading.
  • Battery status estimates power from recent charge changes when live readings are unavailable.
  • Battery status leaves an unknown zero cycle count off the panel.

No new actionable issues found. The earlier threads are addressed by separate temporary files, future-date checks, cycle-count tests, clearing history during observed holds, and a scratch cache for every test run.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Read UPower rate] --> B{Sysfs rate passes guards?}
  B -->|Yes| C[Use sysfs rate]
  B -->|No| D{UPower rate above 0.5W?}
  D -->|Yes| E[Keep UPower rate]
  D -->|No| F{Matching history spans 30–120 seconds?}
  F -->|Yes| G[Use charge-delta estimate if plausible]
  F -->|No| E
  C --> H[Format battery status]
  E --> H
  G --> H
Loading

Reviews (10) · Last reviewed commit: "Merge remote-tracking branch 'upstream/q..." · Reviewed by Greptile

Comment thread bin/omarchy-battery-status Resolved
Comment thread bin/omarchy-battery-status Resolved
Comment thread bin/omarchy-battery-status Resolved
@Kristijan-K

Copy link
Copy Markdown
Author

Thanks — all three greptile findings were valid, addressed in 85b13dcd ("Harden the charge cache against clock jumps and concurrent writes").

1. Concurrent cache writes can collide

Fair point: the panel polls every 5s and the low-battery notification can invoke the script independently, so two runs could interleave on the shared $rate_cache.tmp. The write now uses a per-process temp file ($rate_cache.$$.tmp) and the atomic rename publishes one complete cache; a losing run simply drops its sample, which is harmless. Verified with 60 concurrent invocations: no leftover temp files, no malformed lines, estimate still resolves.

2. Future samples never expire

Correct — a backwards wall-clock correction made now_ts - sample_ts negative, which passed the <= maximum_window check and let those lines be retained and rewritten indefinitely. The read loop now rejects sample_ts > now_ts. Added a test that a future-dated sample is neither used nor carried forward.

3. Cycle suppression lacks test coverage

Added both cases: sysfs cycle_count 0 with UPower N/A omits the cycles row, and a real count (7) is shown. (That behaviour came from an earlier commit and had no coverage.)

Both new guards were verified load-bearing by removing them and confirming the named assertions go red. ./test/shell still fails only the same 5 pre-existing environment cases.

@jandrusk

jandrusk commented Oct 8, 2026

Copy link
Copy Markdown

Linking related work so this can be compared:

The estimator adds a fair amount to omarchy-battery-status (cache file, 30–120 s window). It might be easier to review as two PRs: the plausibility guard and magnitude display first, then the estimator.

@omarchybot

Copy link
Copy Markdown
Collaborator

Looked at this at 85b13dc to classify it before verifying anything, and the classification is unsettled, so it has no class label and nothing was run on a worker yet.

Two models classified it separately: Claude Opus 5.5 read it as compatibility, a bug caused by hardware, since the core change keeps a bogus EC current_now (−65 A on the MSI Prestige 14 Flip AI+) from replacing UPower's sane rate and showing −1124 W. Codex Medium read it as enhancement, and the diff gives it grounds: beyond the plausibility guard, it adds a charge-history estimator with its own cache file and 30–120 s window, and derives remaining time when UPower omits it. Both are new behaviour rather than a correction of existing behaviour.

Two other things stand regardless of the classification: GitHub reports the branch as conflicting with quattro, and #13111 changes the same sysfs-rate block and test file with a different policy for high-but-plausible readings, so the maintainer has to choose between them. Splitting it the way the earlier comment suggests, the guard and magnitude display in one pull request and the estimator in another, would let the bug fix be classified and verified on its own.

This waits on the maintainer to decide what it is.

…s-sysfs-rate

# Conflicts:
#	bin/omarchy-battery-status
@Kristijan-K

Copy link
Copy Markdown
Author

Merged quattro at 087f73d8 (head 0f0c03b4), so the branch is mergeable again. The rebase removed more than it added: quattro had moved on in this exact file, and two of this PR's commits had become duplicates.

Dropped as duplicate

  • #15285 now works time left out of the draw shown beside it (energy / rate, charging counted to the charge limit), so the branch's own time_remaining derivation and format_hours are gone.
  • That also makes the untruncated-energy-full fix moot: upstream parses energy_full untruncated already.
  • #15326 routes durations through omarchy-i18n, so the branch's own formatting had to go with it.

Kept and reshaped

  • The plausibility guard now reads sysfs into sysfs_rate, validates it, and only then assigns power_rate_raw, so a rejected reading leaves UPower's rate in place — the value upstream's new time math then uses. power_now accepts a negative sign again, which upstream relies on for Apple Silicon.
  • Cycle count uses upstream's per-battery $battery_path/cycle_count read (not a BAT* glob) with the 0-vs-N/A suppression on top.
  • The charge-delta estimator is unchanged in policy (minimum_window=30, maximum_window=120, oldest in-window sample, battery+state identity, numeric and future-date validation, per-process temp file).

Tests rebuilt on upstream's fixtures. The old test file was written against fixtures quattro no longer has, so the auto-merge produced assertions pointing at a battery directory that does not exist. I rebuilt that section on the current macsmc-battery/CMB0 harness: guard cases (bogus -65A, plausible-but-high, non-numeric, sane negative), the estimator cases (estimate, short close, long close, window bound, oldest reference, sub-30s, non-numeric, missing voltage, foreign battery/state, stale, future), and cycle suppression. test/shell.d/battery-status-test.sh is 12/12 at 0f0c03b4, and battery-present, battery, power, power-present and power-no-battery pass. i18n-test.sh fails on da/menu.json mirrors the English catalog, which I reproduced on unmodified quattro at 087f73d8 — not from this PR. Tests were run with OMARCHY_PATH pointing at the checkout, since omarchy-i18n reads its catalog from there.

The PR body now covers the estimator, which it never did. If the estimator is what makes this hard to classify, say so and I will split it into its own PR; the guard and the cycle display stand alone as the bug fix. On #13111: still the same overlap in both files, and I will rebase on whichever lands first.

Comment thread bin/omarchy-battery-status Resolved
@Kristijan-K

Copy link
Copy Markdown
Author

Valid, and fixed in 57dfaeb5 — the history is now cleared when an observed state interrupts sampling.

The earlier attempt at this reset on elapsed time, which also fired when the panel was simply closed for more than the window, so a quick glance showed 0W for 30s. That is why it came out in ba6ae6cd. A state change is different from a gap: a closed panel runs no script, so nothing resets, while a hold at a charge limit runs the script and sees pending-charge/fully-charged. Those states do not sample, so the cache now goes rather than being measured across.

unknown clears it too, and so does anything else that is not charging or discharging, since sampling only happens in the two moving states. Concurrent runs still cannot corrupt each other: the clear is a plain rm and the writer publishes with an atomic rename.

Test added: seed two discharge samples, run once with state: pending-charge, and assert both that the rate is 0W (no estimate during the hold) and that no discharge lines survive in the cache. Removing the clear fails that assertion.

battery-status-test.sh is 13/13, and battery, battery-present, power, power-present and power-no-battery pass.

@omarchybot

Copy link
Copy Markdown
Collaborator

Classified again at 57dfaeb after the merge of quattro, and the classification is still unsettled, so it has no class label and nothing was run on a worker.

Claude Opus 5.5 read it as compatibility: the guard keeps a bogus EC current_now from replacing UPower's rate, and the charge-delta estimator works around UPower wedging at 0 W on that same hardware. Codex Medium, classifying separately, read it as enhancement, and the estimator is most of the diff: a cache file in $XDG_RUNTIME_DIR, a 30–120 s sample window, and a rate the script now computes itself when UPower and sysfs both fail. The two models do not agree, so it stays unclassified.

The merge cleared the conflict with quattro; GitHub now reports it mergeable. #13111 is still open and changes the same sysfs-rate block and test file with a different policy for high-but-plausible readings, so only one of the two can carry the guard. The split the author offered, the guard and cycle display on their own and the estimator separately, would let the bug fix be classified and verified by itself.

This waits on the maintainer: to decide what it is, whether to split it, and which of this and #13111 carries the guard.

…s-sysfs-rate

# Conflicts:
#	bin/omarchy-battery-status
#	test/shell.d/battery-status-test.sh
@Kristijan-K

Copy link
Copy Markdown
Author

Merged quattro again at 967bbdd7 (head 82f654e1): #16272 touched this file and took the negative-rate idle check, which this PR carried too. That duplicate is dropped in favour of upstream's line, and upstream's new "Fully charged"/partial-readings status line is kept as-is. No other hunk conflicted.

The test file needed a rebuild rather than a merge: #16272 added a full-battery case in the same place as the guard cases, so the two fixtures interleaved. The file is now upstream's at 967bbdd7 with the guard, estimator and cycle cases inserted before the final ownership check.

battery-status-test.sh is 14/14, and battery, battery-present, power, power-present, power-no-battery pass. Still mergeable. #13111 will hit the same #16272 conflict.

Nothing else changed: this still waits on the maintainer for what it is, whether to split it, and which of this and #13111 carries the guard.

Comment thread bin/omarchy-battery-status Resolved
@Kristijan-K

Copy link
Copy Markdown
Author

Right, and worse than cosmetic: fixed in 99d282c7.

The suite now exports a scratch OMARCHY_BATTERY_CACHE for every run, so no fixture can reach the real cache. It also points XDG_RUNTIME_DIR at scratch and seeds a history there, then asserts at the end that it is byte-identical — that turns "this test must not clear the developer's battery history" into an assertion rather than a convention. Removing the export fails it, because #16272's fully-charged fixture is exactly the run that would have cleared it.

That also removes the trap for future fixtures: any new test that hits a pending-charge/fully-charged state is now sandboxed by default, not by remembering to pass the variable.

battery-status-test.sh is 15/15.

@omarchybot

Copy link
Copy Markdown
Collaborator

Classified again at 99d282c after the merge of quattro and the test-cache commit, and the classification is still unsettled, so it has no class label and nothing was run on a worker.

Claude Opus 5.5 read it as compatibility, a bug caused by hardware: the guard stops a bogus EC current_now from replacing UPower's rate, and the cycle-count suppression hides a 0 the same EC reports. Codex Medium, classifying separately, read it as enhancement, because the charge-delta estimator, with its cache in $XDG_RUNTIME_DIR and its 30–120 s window, is new behaviour and is most of the diff. Since 57dfaeb only the test file changed, so nothing that changed decides the question either way.

#13111 is still open against the same sysfs-rate block. This still waits on the maintainer: to decide what it is, whether to split the estimator out as offered, and which of this and #13111 carries the guard.

…s-sysfs-rate

# Conflicts:
#	test/shell.d/battery-status-test.sh
@Kristijan-K

Copy link
Copy Markdown
Author

Merged quattro at bc220e70 (head 37dfb05b). The only conflict was #16334 removing the trailing source-text check ("battery status owns capacity and remaining calculations") from this test file; that block is gone here too, since it only grepped source. Everything else applied cleanly.

battery-status-test.sh is 14/14 (the removed check was one of the 15), and battery, battery-present, power, power-present, power-no-battery pass. Mergeable again.

@omarchybot

Copy link
Copy Markdown
Collaborator

Classified again at 37dfb05 after the merge of quattro at bc220e70. The classification is still unsettled, so it has no class label and nothing was run on a worker.

Claude Opus 5.5 read it as compatibility: a bug that the MSI's EC causes, fixed by the guard against a bogus current_now and the cycle-count suppression. Codex Medium, classifying separately, read it as enhancement, because most of the diff is the charge-delta estimator, which is new behaviour. Apart from the merge, the only change since 99d282c is that the source-grep check #16334 removed upstream is gone here too, so nothing new settles it.

What is new: the branch conflicts with quattro again, in bin/omarchy-battery-status. #17265 (merged 1 November) already takes the sysfs reading only when the read succeeds and returns a number, through read_sysfs_number, so that part of this PR is now upstream. #16278 also changed the AC-at-100% fallback in the same file. What this PR still adds on top of that is the magnitude and 3x-UPower plausibility guard, showing the rate as a magnitude, suppressing a cycle count of 0, and the estimator. #13111 is still open against the same block.

This waits on the author to resolve the conflict on top of read_sysfs_number, and on the maintainer to decide what it is, whether the estimator should be split out as offered, and which of this and #13111 carries the guard.

…s-sysfs-rate

# Conflicts:
#	bin/omarchy-battery-status
@Kristijan-K

Copy link
Copy Markdown
Author

Merged quattro at 3437cfb48 (head now 8f0c0ec05), so the branch is mergeable again.

Conflict was in bin/omarchy-battery-status only (test/shell.d/battery-status-test.sh auto-merged):

Verified:

  • test/shell.d/battery-status-test.sh 15/15, plus battery, battery-present, power, power-present, power-no-battery all pass.

Leaving the decision to the maintainer as requested: #13111 overlap in the sysfs-rate block stands, and I can split the guard+magnitude display from the estimator into its own PR if that makes classification easier.

@greptile-apps

greptile-apps Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Want your agent to iterate on Greptile's feedback? Try greploops.

@omarchybot omarchybot added the enhancement New feature or request label Nov 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants