Metadata-Version: 2.5
Name: quner
Version: 0.1.14
Summary: Linux power-control daemon with guarded, workload-specific CPU calibration.
Project-URL: Homepage, https://github.com/Arcane-Fly/quner
Author-email: Braden Lang <braden.lang77@gmail.com>
License: MIT
License-File: LICENSE
Keywords: cpufreq,efficiency,laptop,nvidia,power-management,rapl,systemd
Classifier: Environment :: No Input/Output (Daemon)
Classifier: Intended Audience :: End Users/Desktop
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: System :: Hardware
Classifier: Topic :: System :: Power (UPS)
Requires-Python: >=3.10
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == 'dev'
Provides-Extra: nvml
Requires-Dist: nvidia-ml-py; extra == 'nvml'
Description-Content-Type: text/markdown

# quner

**Portable Linux power-control daemon.** It can switch CPU governor profiles
between idle and heavy compute. A measured work-per-joule optimum requires a
representative workload and controlled calibration; this host deployment has
not completed that calibration.

The daemon also stores an operator-selected work type (`general-dev` by
default, or `qig-compute`) separately from its idle/training load detector.
Selecting a type does not start a benchmark or claim a new optimum. A matching
calibration is applied only during training load after an explicit, guarded
measurement succeeds; the idle low-power policy and thermal override retain
priority.

`quner` probes what levers your host exposes (CPU governor, Intel RAPL package
power, NVIDIA power-cap). An explicit CPU-only calibration request can compare
operating points for a representative workload. The installed timer skips
until all workload inputs are configured and fresh host activity checks pass.
Absent levers are reported, and controls are reversible.

## Work types on the local development checkout

```bash
quner work-types                       # JSON: selection, known types, exact-cache status
sudo quner select-work-type general-dev # persist the default type; no benchmark
sudo quner select-work-type qig-compute # switch the requested type
sudo quner calibrate-selected           # explicit guarded CPU-only measurement
sudo quner calibrate-selected --desktop # opt in to measured desktop background
quner status                            # requested/applied revision and live readbacks
```

`general-dev` compiles a captured, fixed Python source corpus; successful
compiled files are the work units. `qig-compute` contracts a captured local
`qig-compute` development source with a fixed 16-site Bell-pair QFI fixture;
each output must match the analytic matrix before it counts. Both run as the
non-root operator in a bounded systemd cgroup, with one CPU thread per numeric
library and GPU use disabled. QIG's editable source is probed as that operator,
then captured into a root-owned read-only snapshot for the run. The cache key
binds the host, work type, load class, recipe, content, and runtime. Old
unlabeled cache entries are never treated as work-type calibrations. A changed
local source tree or runtime invalidates a previous calibration.

These fixed tasks measure **those tasks only**. They do not establish an energy
benefit for every development activity or QIG job. Calibration refuses when
CPU/GPU activity, thermal state, telemetry, or containment is unsafe. A saved
result is restored first and becomes active only on a later matching daemon
tick; `selection_pending` and `applied_revision` distinguish that state in
`/run/quner/status.json`. On this host, install from the reviewed local
development checkout, not a PyPI release, so the installed bytes match the
validated recipe and current QIG source.

The existing timer skips by default. To let it retry the selected known recipe
on its normal schedule, an operator can put `QUNER_RETUNE_SELECTED=1` in the
root-owned `/etc/quner/retune.conf`. Every retry still requires the complete
quiet-host, temperature, GPU, memory and containment checks; a refusal does
not publish a calibration. The explicit `quner tune --command ...` path remains
available for manual experiments, but its legacy cache is not consumed as a
typed work-type calibration.

**Recommended — install system-wide so `root`/`sudo` finds it directly:**

```bash
sudo pipx --global install quner     # or: sudo pip install quner
sudo quner install                    # just works — drops the service + timer
quner doctor                          # what levers this host exposes
sudo quner selftest                   # transient, auto-reverting proof
```

**Alternative — per-user pipx install:**

```bash
pipx install quner
quner doctor
sudo "$(which quner)" install         # see note below
```

> **Why `sudo "$(which quner)"` for a per-user install?** `pipx` puts the binary
> in your **user** `~/.local/bin`, which isn't on `root`'s `PATH` — so a bare
> `sudo quner` gives `command not found`. `sudo "$(which quner)"` (or
> `sudo env "PATH=$PATH" quner …`) runs the binary you installed. **After that
> first install, quner drops a `/usr/local/bin/quner` launcher**, so plain
> `sudo quner …` works from then on (`uninstall` removes it).
>
> **PATH note:** `pipx ensurepath` appends to `~/.bashrc`, which only a **login**
> shell sources — open a new *login* shell / re-login (a plain terminal tab or a
> non-interactive `ssh host 'cmd'` may not pick it up). The system-wide install
> above avoids this entirely.

The efficiency principle derives from QIG experiment **EXP-132** (work-per-joule
peaks at an interior operating point). That result does not establish this
host's optimum; it must be measured with a representative workload.

> Savings depend on a representative measured workload. The default service
> controls the CPU governor; it does not claim a measured energy benefit.

## Safety model

- **Reversible service.** Installation snapshots the prior governor / RAPL /
  current GPU cap once to `/var/lib/quner/rollback.json`; uninstall and the
  service's stop hook restore it. `quner apply --restore` reverts on demand.
- **Calibration guarded by fresh activity.** The timer needs an explicit
  foreground command, fixed positive work units, target profile (`idle` or
  `training`), operator user, working directory, timeout and CPU-only contract
  in `/etc/quner/retune.conf`. The guard requires repeated quiet CPU samples,
  subtracts the dedicated systemd benchmark cgroup's CPU accounting, and
  checks every physical PCI GPU, memory headroom/pressure and CPU-package
  temperature throughout the sweep. On this host, read-only i915 engine-busy
  PMU counters and NVIDIA utilization/client queries must both show quiet;
  Strict calibration remains the default: Intel activity defers calibration even when NVIDIA reports 0%. NVIDIA's
  utilization query has reporting granularity and is not proof of literal
  zero engine work. Missing telemetry, PMU gaps or ambiguous cgroup ownership
  abort. No driver, sysctl or desktop display setting is changed. The current host
  has no configured representative workload, so its timer still skips. A
  measured result is restored first and then saved for the requested profile;
  the daemon applies it on a later matching tick. A shared hardware lock keeps
  daemon ticks out of sweeps, and failures restore the exact starting controls.
  The contained worker handshake uses a controller-owned parent with traversal
  permission only, an operator-group nonce directory and an operator-owned
  mode0600 result file. Controller umask0077 remains supported. Symlinked,
  foreign-owned or writable handshake paths fail before permissions are changed;
  marker access errors report immediately rather than looking like a timeout.
- **Contextual desktop CPU calibration.** `calibrate-selected --desktop` uses
  the captured known CPU recipe with displays and ordinary applications left
  running. Protocol `desktop-cpu-v4` observes identified rendering, including
  sustained browser GPU activity; it does not classify rendering as idle or
  interpret engine busy time as spare compute capacity. Engine timing, counter
  integrity, every shared client's ownership, zero other-engine activity and
  zero NVIDIA compute remain mandatory. Unknown or foreign active clients,
  changed ownership, missing telemetry and thermal limits still stop the run.
  The full process/descriptor census remains fresh on every check, using
  lightweight directory entries and explicitly closed files rather than
  constructing thousands of path objects. Ownership, roles and protected paths
  are still checked per DRM descriptor, with no cross-call attribution cache.
  CPU activity is observed over four-second windows against the online logical
  CPU inventory, reserving one logical CPU of average headroom for the captured
  single-thread recipe. Owned cgroup CPU is subtracted. Observation waits up to
  30 seconds for a stable window within the 300-second overall runtime bound;
  ordinary CPU activity and individual scheduling spikes are not quiet-host
  failures. CPU half-window demand must differ by at most ten percentage points.
  All package/GPU power limits remain at their starting values.

  Desktop entry first snapshots the original controls and resolves the target
  policy. A hot machine can then passively cool in verified powersave before
  measurement eligibility is assessed. This entry-only phase observes finite
  temperatures above the benchmark limit while all memory, CPU capacity, GPU
  ownership, telemetry and cancellation checks remain active. No worker, trial
  or energy measurement can start in that phase. The phase clears on every
  exit; ordinary temperature checks must pass before any benchmark. Entry and
  peak observed temperatures are recorded, and every failure restores the exact
  original controls. Kernel thermal management remains enabled and unchanged.

  Before each trial, verified powersave conditioning waits up to 30 seconds
  for four seconds of stable thermal headroom and schedulable CPU capacity.
  General development recipe v2 is a short compilation burst: exactly 64 passes
  over six captured Python modules (384 validated parse/compile operations),
  with a five-degree margin below the hard temperature limit. The unchanged
  1024-evaluation QIG batch retains a ten-degree margin. At the default 85°C
  hard limit these targets are 80°C and 75°C respectively. These are fixed
  engineering preconditions, not guarantees that a busy laptop will cool enough.
  Missing sensors, reaching the hard limit during measurement eligibility or
  a trial, cancellation or a bounded cooling wait failure stop the run and restore the original controls. No application is
  stopped. The overall runtime remains capped at 300 seconds.

  Conditioning precedes the trial's energy interval. Trial records distinguish
  the conditioned temperature from the actual pre-work temperature after the
  candidate governor settles. Workload energy includes contained startup and
  measured background and safety-observer work within that interval; the
  development result describes burst compilation,
  not sustained compute efficiency. Recipe v2 has a distinct work count and
  identity from the earlier 256-pass workload; it is never selected adaptively
  per governor. Context and cache validation bind the actual work type, release,
  workload scope and its fixed conditioning regime.

  Each governor receives at least three counterbalanced trials. CPU, render and
  scheduling-pressure means are compared across repeats of the same governor,
  with respective maximum differences of ten, 15 and 15 percentage points.
  They are not matched across governors: background execution can itself respond
  to a governor change. Throughput and work per measured joule must each have
  no more than 10% observed spread within a governor. The reference is the target
  profile's valid cached policy or default, resolved before changing hardware;
  the initial idle governor is only the state to restore afterward. A candidate
  can replace that reference only if its worst measured efficiency exceeds the
  reference's best, with worst throughput at least 95% of the reference's best.
  These are observed ranges, not confidence intervals or isolated causal claims.

  A distinct `assessment=inconclusive-thermal` can return an incomplete
  comparison when a candidate exceeds the measurement limit during verified
  governor settlement, before an energy sampler or worker starts. Only a finite
  typed temperature breach after successful application and governor readback
  qualifies. That candidate is excluded from later attempts; bounded powersave
  recovery retains prior completed CPU accounting and all nonthermal checks.
  The 85°C measurement limit is unchanged. Thermal failures before application,
  during energy sampling or in a worker, missing sensors, ownership failures,
  cancellation and cleanup errors still abort the entire run.

  Every remaining candidate in the recorded plan must complete at least three
  positive, thermally safe trials. Earlier valid rows from a subsequently
  excluded candidate remain aligned with their background observations, but
  cannot establish a completed comparison. If no feasible candidate completes
  the required trials, the run refuses. The partial result records the target
  reference, actual candidate plan and typed exclusions (state, temperature,
  limit, phase and verified application/cleanup); it has no chosen state, no
  saved policy and no comparative improvement or repeatability acceptance.
  Existing cache bytes remain unchanged. A full ordinary safety check still runs
  before exact restoration. After restoration, only this partial diagnostic
  skips measurement-eligibility checks: no further measurement or policy write
  occurs. Selection, recipe, context and candidate-plan checks still apply;
  `restoration_verified=true` requires exact restore/readback, while
  `post_restore_measurement_eligibility=not-asserted-partial-diagnostic` makes
  clear that the restored original policy is not newly certified as fit to run
  a benchmark. Full comparisons retain all post-restoration safety checks.
  It is a useful measurement record,
  not a calibrated policy or constrained optimum.

  Valid but noisy measurements return `status=inconclusive` and
  `assessment=inconclusive-background`, with the real measurements, reference
  and detailed reason. They keep existing cache bytes and target policy unchanged;
  `chosen_state` is null and `saved_for_profile` is false. Reliable results report
  `improved-observed` or `retained-reference`. A completed assessment does not
  promise a speedup. Cancellation and all safety failures still restore the
  exact starting controls and never publish a result.

  Energy includes available CPU-package/GPU counters and measured desktop
  background. It excludes dock/monitor/wall-plug energy. Schema-4 cache identity
  binds v4, Quner release, client ownership, display topology, unchanged power limits, CPU
  inventory and the observation policy. Earlier desktop protocols are rejected.
  Trial background summaries accompany the record; matching configuration does
  not guarantee identical future workload demand. CLI calibration remains strict
  by default. The optional `QUNER_RETUNE_SELECTED=1` timer route uses desktop mode
  for the validated selected recipe; an unconfigured timer skips and arbitrary
  command retunes retain strict guards.
- **Desktop power controls.** When Quner is the sole governor writer,
  `power-profiles-daemon` is masked on this host. GNOME/powerprofilesctl mode
  selection is therefore unavailable; original service state is backed up for
  rollback. Quner does not control fans or replace kernel thermal management.
- **Fail-loud.** A lever the host doesn't expose is reported `unavailable`, never
  silently no-op'd. `quner doctor` shows exactly what's controllable.
- **Dry-run on direct profile controls.** `apply`, `profile`, `prime` and
  installation commands expose dry-run. Calibration requires a real workload
  and does not accept a synthetic dry-run result as measurement.
- **Inspectable / testable.** All hardware paths are env-overridable
  (`QUNER_SYSFS_ROOT`, `QUNER_NVIDIA_SMI`, `QUNER_STATE_DIR`, …), so the real
  code runs against a fake tree with zero host impact — see `sandbox/run_sandbox.sh`.
- **reverse-PRIME is opt-in.** The one reboot-level change never fires on install
  or in the daemon; only via `quner prime enable` (dry-run first, reboot-gated,
  with a TTY recovery path).

## Validation ladder

1. **Sandbox** (`bash sandbox/run_sandbox.sh`) — proves ~all code with the real
   `/sys` byte-identical before/after. Safe to run anywhere.
2. **`quner selftest`** — transient, auto-reverting proof the levers move on
   *your* hardware (2-second governor flip, RAPL/GPU set-to-current, restore).
3. **`sudo quner install`** — apply the governor profile continuously.

See `docs/design/` for the full design.
