# Cloud Master Statistical Engine — portable module, API v1

## Independent development boundary

`bin/cm_stat_engine.py` is a standalone, Python standard-library-only calculation module. It imports no Cloud Master or Linux adapters, uses no filesystem, sockets, subprocesses, threads, credentials or external model. It contains no UI, alerts or infrastructure actions. The host adapter is `bin/cm_workload_linux.py`; the collector supplies observations and is responsible for permission policy, identity mapping, timestamps, sanitization and publishing. The browser is presentation only. `ENGINE_API_VERSION = 1` identifies the current compatible contract; `ENGINE_METHOD_REVISION = 4` identifies the revised analytical method. The engine is shipped together with Cloud Master for now. Do not fork the same algorithm into the browser.

A future separate repository can start by copying the engine, its pure-engine fixtures and this contract. Maintain an independent API version, deterministic replay fixtures, release provenance and explicit compatibility checks before distributing as a dependency. Cloud Master should pin a reviewed version rather than fetching arbitrary analytics code at runtime. No package publishing or repository split was performed in this release.

## Contract

- `WorkloadIntelligence()` creates a private, single-writer, in-memory engine instance. `clear()` erases learned state. Create a new instance for a new stream; do not share state across hosts. No implicit persistence.
- `observe(now, totals, workloads, local_totals=None)`: monotonic seconds; host `some` PSI cumulative microseconds keyed by `cpu`, `memory`, `io`; mapping of stable private workload identifiers to numeric `cpu_percent`, `memory_used_bytes`, `memory_limit_bytes`, `block_input_bytes`, `block_output_bytes`; optional per-workload map of same cumulative PSI counters. CPU can exceed 100%. Missing data is absent or `None`, not zero. IDs are opaque to the engine, which returns them to the trusted adapter, never directly to a client.
- `capacity_forecasts(now, values)`: fixed caller-owned resource keys mapped to `(measured_use, reference_capacity, minimum_growth)` in consistent units. Cloud Master supplies exactly two keys (`host_memory`, `root_storage`). Returns only sufficiently supported extrapolations; caller should keep the key set fixed and bounded.
- `event_findings(now, events)`: bounded recent ordered list of `(start_monotonic, end_monotonic, before_host_totals, after_host_totals)`. Cloud Master passes at most eight actual transfer attempts. Reports interval PSI and, if at least 3 valid preceding intervals spanning 15 s exist, a time-weighted preceding baseline from the prior 120 s excluding other recorded transfer windows.
- `baseline`, `forecast`, and `_finding` are deterministic calculation helpers; underscore-prefixed members are internal. No thread safety is promised; Cloud Master invokes analysis on the collector thread, passes copies of the event log, and isolates optional disk sampling.

## Methods and scope

- Five-minute, max-128-observation windows per resource and up to 64 workloads. Missing/reset counters and long gaps break relevant evidence. Baselines use a median and median absolute deviation with a minimum physical range; three consecutive readings above the robust band mark sustained elevation; the two previous candidate readings are excluded from reference training, requiring at least 12 earlier observations spanning 45 seconds. Baseline adapts to changing activity and is not long-term seasonal learning.
- Container PSI uses the same kernel `some` delta formula as host PSI, but local values are not host values. Local and paired host PSI summaries use measured interval durations; low and peak are interval extrema and the average is duration-weighted. Whole intervals only, with explicit covered seconds. The adapter checks exact 64-hex-ID systemd libpod scopes under the current non-root user's cgroup-v2 service, in user.slice or app.slice; missing, ambiguous or unsupported layouts report unavailable. No recursive discovery or new privileges. A local PSI observation describes contention experienced by a group, not who caused it.
- Cross-workload associations compare another workload's resource activity to the target workload's local PSI, restricting analysis to observations with similar measured target demand. Every 15 seconds, at most eight mature workloads per resource are considered and at most two findings per target are returned. Positive correlation, cohort contrast, three disjoint time-block contrasts and a linear-detrending screen apply. This is not causal attribution: shared causes, scheduling, demand measured imperfectly and serial dependence remain possible. No intervention or health severity changes.
- Capacity trends require at least 12 observations over 60 s, positive and consistent slopes in both halves, time/value correlation >= .90, meaningful growth, current use at least half the reference capacity, and projected crossing in the next hour. Changing reference capacity resets its evidence. Host available memory is used only when kernel reported; root filesystem usage is a rounded utilization percentage. A runtime-reported memory limit is not necessarily a dedicated allocation or guarantee of effective headroom. Forecasts additionally require a chronological half-window holdout MAE less than 80% of the last-value benchmark MAE. Two half-window slopes define conditional growth scenarios, not confidence or prediction intervals. Forecasts are conditional straight-line projections; they cannot predict sudden allocations, reclamation, OOM, quotas or policy changes.
- Transfer attempts are instrumented at the coordinator on either configured provider, using monotonic boundaries and kernel stall totals. A completed attempt may have failed or included preparation; it is not necessarily a successful speed test. Event evidence remains visible for at most five minutes, even if its worker was removed before normal sampling. Baseline comparison is optional, not inferred from unrelated measurements. No event history persists across process restart. Network-source revocation suppresses publication.
- `workload_disk=true` is independent opt-in, false by default. One background rootless local Podman `container inspect --size` with a fixed numeric-only template per minute, max eight-second command timeout, one worker thread, up to 180-second cache. On large inventories rotation may leave many workloads unavailable; this deliberately prioritizes low load. SizeRw and SizeRootFs describe runtime-reported writable and rootfs sizes, not unique physical allocated blocks. Shared image layers can overlap; bind mounts, volumes, logs outside the rootfs and storage-driver overhead are not included. No scanning arbitrary mount paths; no extra privileges. The scan itself can consume I/O and is therefore off by default.

## Security and verification

Existing `[features]` source controls are prerequisites. `workload_intelligence=false` removes per-workload and system findings; `network=false` removes transfer observations; `workload_disk=false` suppresses cached sizes immediately at publisher and browser boundaries. Stale health snapshots suppress derived data. No full identifiers, cgroup paths, runtime names or private matrices are published. A peer is exposed only as an unambiguous four-character suffix in the running inventory. Existing delivered data cannot be recalled. Statistics are advisory only and do not drive notifications, health orb or actions. Linux/Podman tests are fixtures except the real collector process and local HTTPS tests; actual Pi scope paths, runtime disk sizes and performance must be verified separately.

References: Linux PSI https://docs.kernel.org/accounting/psi.html ; Podman size fields https://docs.podman.io/en/latest/markdown/podman-container-inspect.1.html ; prior competitive references in WORKLOAD_INTELLIGENCE.md. No comparative performance claims without measured competitor benchmarks.

See `STATISTICAL_METHODS.md` for mathematical definitions, screening thresholds, interpretation, limitations and reproducible fixtures.

### Method revision 3 — continuity
A missing target or source activity observation, invalid target local PSI, or changed memory reference capacity invalidates cached peer findings immediately, even between 15-second peer recomputations. Changed memory capacity also resets the host-pressure association window. Peer sources do not require their own local PSI. Evidence must rebuild after a break.

### Method revision 4 — explicit averaging
`sampled_summary(rows, now, window=300)` is a pure helper for chronological monotonic `(timestamp, value-or-None)` streams. Returns `None` if no valid samples; otherwise `samples`, `min`, `max`, arithmetic `avg`, interpolated `time_avg` (null without adjacent coverage), `observed_seconds`, `intervals`. Caller bounds history, enforces timestamp uniqueness and separates denominator regimes. Gap cap 15 seconds; whole adjacent intervals only. Collector preserves the existing avg field; new keys are additive. Forecast results add `holdout_improvement_percent`, computed before rounding from the existing MAE ratio, not a confidence score. API v1 retained. See STATISTICAL_METHODS.md for formulas and limitations.

### Method revision 5 — duration-weighted cohorts
Production findings add `cohort_weighting`, `low_activity_samples`, `high_activity_samples`, `low_activity_seconds`, `high_activity_seconds`, and `stall_difference_points`. Durations are measured coverage, not elapsed span; quartile cutoff ties are included. Three-column internal fixture inputs use sample weighting and null duration fields. API v1 retained. See STATISTICAL_METHODS.md.
