diff --git a/README.md b/README.md
index 7903e1e..d9732d8 100644
--- a/README.md
+++ b/README.md
@@ -34,9 +34,9 @@ that specific device and motherboard (`magc6735_65u_1_m0`, firmware branch `P45`
-Unmodified framebuffer captures from the device: the boot screen and settings
-with the charge limit. `~80%` is an estimate based on open-circuit voltage,
-not an independently calibrated state of charge. The original interface is in Dutch.
+These earlier framebuffer captures show the boot screen and charge-limit settings.
+The `~80%` label in the screenshot comes from the voltage-based interface
+that preceded the HW-CAR fuel gauge. The original interface is in Dutch.
[Screenshot provenance and limitations](docs/SCREENSHOTS.md).
## Why this project?
@@ -55,10 +55,11 @@ malicious behavior. [A short history](docs/HISTORY.md).
## What works now?
-Status: **22 November 2026** (separating the historical 2–5 November v9 baseline,
-later v10c/B5 device checks, and source-only hardening/Rust tooling). “Yes” means
-demonstrated on this device; [the detailed status](docs/STATUS.md) describes the
-exact tests and limitations.
+On **23 November 2026**, all six Rust programs in B5's `/usr/libexec/i14-rs/`
+and its soak sampler matched the ARM64 musl release hashes. All 12 default
+OpenRC services and four supervised Rust daemons were running. The hardware
+probe passed 8/8 checks. Earlier tests still supply the evidence for several
+features below. [Dated checks and limitations](docs/STATUS.md).
| Component | Working | Notes |
| --- | --- | --- |
@@ -66,17 +67,25 @@ exact tests and limitations.
| Display and touch controls | Yes | Custom framebuffer interface and on-screen keyboard |
| On-device terminal | Historical / disabled in hardened DNS image | Exercised in the 2–5 Nov v9 baseline; disabled in the hardened DNS image on `main` (see [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md)) |
| Wi-Fi and SSH | Yes | On-screen network selection and SSH key authentication |
-| USB management and rescue mode | Yes | USB networking (`172.16.42.1`) and rescue mode; hardened source restricts normal USB management to SSH keys and uses locally activated, authenticated serial rescue |
-| Backup DNS | Yes | Tested on UDP/TCP port 53, with DNS-over-TLS and DNSSEC; verify Unbound security advisories before exposing to LAN clients (see [SECURITY.md](SECURITY.md)) |
+| USB management and rescue mode | Yes | USB networking and rescue mode; hardened source restricts normal USB management to SSH keys and uses locally activated, authenticated serial rescue |
+| Backup DNS | Local health check passed | B5 answered `i14-health.invalid` with `192.0.2.1`. Keep the candidate DNS client list empty until the installed Unbound security gaps are fixed. [Security policy](SECURITY.md). |
| Brightness, screen timeout, PIN and power menu | Yes | Implemented and exercised on the device |
| Charging and configurable charge limit | Partially | Charging works; BCCT pause/resume tested, full calibration/charge-band acceptance still pending |
+| Battery gauge and home-screen ETA | Deployed on B5 | The HW-CAR coulomb counter tracks remaining charge. The UI estimates time to the charge limit or time left on discharge. |
| CPU control with the screen off | Yes | Downclocking works; energy savings have not been established |
-| Rust userspace & host tools | Source / host-verified | 12-crate workspace (`rust/`) with offline backup verifier (`i14-verify-backup`) and ARM64 musl builds; full on-device migration acceptance open |
+| Rust userspace & host tools | Phone binaries verified on B5 | The UI, charge guard, CPU controller and netwatch ran under OpenRC supervision. Paired Rust/Python performance measurements remain open. |
| Bluetooth | Partially | Radio and scanning work; pairing and device use are not implemented |
| Audio, camera, GPS, calls and mobile data | Not verified | No complete, accepted Linux support |
| Modern mainline kernel | Partially | Earlier native boot demonstrated; not a complete replacement for 3.18 |
| Docker | No | Not supported by the current kernel |
-| Multi-day reliability / recovery from an empty battery | Partially | Acceptance window B passed for its measured version; 48-hour Soak C and nearly-empty recovery remain open |
+| Multi-day reliability / recovery from an empty battery | Partially | Window B passed for its measured version. Soak C collector commissioning passed on 23 November. The uninterrupted 48-hour window and post-soak H3 measurements remain open. Nearly-empty recovery is on owner hold. |
+
+On 23 November the gauge reported `gauge_mode: "hw_car"`, remaining charge
+(`q_rem_mah`) and estimated full capacity (`q_full_mah`). Both snapshots
+reported `anchored: false`. The UI shows `~N%` until the gauge records an
+anchor, then `N%`. Replaying those snapshots on the host produced discharge
+ETAs. The SSH check did not observe the screen. Two-cycle C13 calibration
+remains open.
## How does it work?
@@ -117,6 +126,7 @@ Building requires additional tools and files from the device itself.
- [History and suspicious preinstalled software](docs/HISTORY.md)
- [Screenshots and provenance](docs/SCREENSHOTS.md)
- [Development environment and build limitations](docs/DEVELOPMENT.md)
+- [Offline DNS and power soak correlator](docs/SOAK-CORRELATE.md)
- [Rootfs trial and rollback](docs/ROOTFS-SWAP-ROLLBACK.md)
- [K70 recovery-timing analyzer](docs/K70-RECOVERY-TIMING.md)
- [Security policy](SECURITY.md)
diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md
index 0b8d3ea..89df2f0 100644
--- a/docs/DEVELOPMENT.md
+++ b/docs/DEVELOPMENT.md
@@ -24,6 +24,11 @@ python3 -B initramfs/test-usb-network.py
python3 -B initramfs/test-display-packaging.py
```
+The rootfs builder uses `rootfs/make-android-props.py` to write the Android 6
+property area for the MediaTek Wi-Fi tools. With Cargo available, the Python
+host suite builds `i14-make-android-props` and compares the two writers'
+output bytes, path handling and exit codes in temporary directories.
+
For the Rust workspace (pinned to Rust `1.98.1` in `rust/rust-toolchain.toml`
and `rust/mise.toml`; see [rust/README.md](../rust/README.md)):
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 988d3d7..45101f2 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -1,14 +1,15 @@
# I14 Linux Roadmap & Acceptance Gates
This roadmap summarizes the active engineering milestones and remaining device
-acceptance gates as of 22 November 2026. The near-term goal is a maintained
+acceptance gates as of 23 November 2026. The near-term goal is a maintained
source baseline on `main`, verified offline backup tooling, and measured
acceptance of one production Alpine image on the stock 3.18.19 kernel. Linux 7
mainline bring-up is a separate track with its own recovery gate.
Window B was accepted for its measured version. `B5` is the latest recorded
-restoration baseline. Python remains in the image alongside the Rust workspace
-for parity comparisons and recovery.
+restoration baseline. On 23 November, all seven deployed ARM64 musl binaries
+matched the release hashes, and the hardware probe passed 8/8 checks. Python
+remains in the image for parity comparisons and recovery.
## 1. Source baseline & host verification
@@ -20,6 +21,14 @@ for parity comparisons and recovery.
`rust/crates/i14-tools`) covering SHA-256 manifests, primary/backup GPT
headers and entry arrays, and all 23 partition lengths. File integrity checks
and physical restore remain separate acceptance criteria.
+- PR #3 added offline rootfs trial staging and verification
+ ([swap tool](../scripts/i14-rootfs-swap.py)), Soak C observer/export/receive
+ checks, C13 launcher deadlines, M0 host timing anchors and fastboot
+ diagnostic parity.
+- The [offline DNS/power correlator](SOAK-CORRELATE.md) processed 199/199
+ usable intervals from 200 real B5 power samples with synthetic DNS answers.
+ The Rust `i14-make-android-props` host tool matched the Python writer's
+ 128 KiB output byte-for-byte.
## 2. Stock-kernel device acceptance items
@@ -28,13 +37,24 @@ partition, image hash, source revision and rollback status. Never read
`current_cmd` during charging tests (reading it disables charging). Keep
firmware dumps, images, credentials and raw captures outside Git.
+### Security-hardened stock boot image and rootfs
+
+Deploy and accept the new boot image and rootfs together. Verify locally
+activated, authenticated USB rescue, the fail-closed dual-stack firewall and
+private settings permissions (`0700` directory, `0600` files). B5 answered the
+local DNS health query on 23 November. Its installed `unbound-1.25.2-r2` lacks
+the fixes for CVE-2026-81634 and CVE-2026-96405. Keep `dns-clients.conf`
+empty for acceptance until the candidate package manifest confirms both fixes.
+[Build and package requirements](DEVELOPMENT.md).
+
### Unattended collector & 48-hour Soak C (H2/H3)
The [H1, Soak C and H3 execution sequence](verification/H1-SOAK-C.md) lists
the commissioning steps, commands and evidence required for these gates.
-- Commission a phone-local collector and export path with bounded retention and
- clean process teardown before starting a 48-hour acceptance window.
+- Commissioning passed on B5 on 23 November. Root `crond` completed a bounded
+ capture, the original crontab was restored byte-for-byte and no collector or
+ lock remained. The receiver verified all 18 streamed files (9,715,485 bytes).
- Freeze exact boot/rootfs identity, runtime hashes, sampler and probe settings,
and audit conditions 0–5 (`scripts/i14-window-audit.py`), then run 48
uninterrupted hours and record the verdict plus read-only Rust CPU/memory
@@ -53,15 +73,19 @@ the commissioning steps, commands and evidence required for these gates.
`5,167,890,432` bytes while keeping the active `B5` image, historical
rollback copy and trial records intact.
- Current disposition remains `KEEP_B5 / R_DEFERRED_INTEGRITY` until a fresh
- candidate image, pre-Unbound `root.key` carry proof, automatic rollback
- rehearsal (`docs/ROOTFS-SWAP-ROLLBACK.md`), and full restoration verification
+ candidate image, pre-Unbound `root.key` carry proof, [automatic rollback
+ rehearsal](ROOTFS-SWAP-ROLLBACK.md), and full restoration verification
are accepted.
-### Battery calibration (C13)
+### Battery calibration (C13) and the 80% charge band
+- B5 reported `gauge_mode: "hw_car"` and `anchored: false` on 23 November.
+ The capacity estimate still needs calibration.
- Verify userdata free space, log retention budget and unattended supervision
(`scripts/i14-calibration-launch.py`) before running a bounded two-cycle
calibration campaign (fit on cycle 1, independent holdout on cycle 2).
+- Verify a full natural stop/resume cycle at an unchanged 80% limit and
+ hysteresis after the guard crashes inside the band.
See the [C13 and production charge-band sequence](C13-READINESS.md).
### Nearly-empty recovery (D)
diff --git a/docs/SOAK-CORRELATE.md b/docs/SOAK-CORRELATE.md
new file mode 100644
index 0000000..7297cba
--- /dev/null
+++ b/docs/SOAK-CORRELATE.md
@@ -0,0 +1,44 @@
+# Correlate DNS failures with sampled power
+
+Use the offline correlator to find which DNS checks failed and whether the phone reported external power around each unplanned failure. Run it on the host with existing log files and Python 3.10 or newer.
+
+```sh
+python3 -B scripts/i14-soak-correlate.py \
+ --dns dns.csv.1 --dns dns.csv \
+ --power samples.jsonl.1 --power samples.jsonl \
+ --maintenance maintenance.txt \
+ --dns-max-gap-seconds 360 --power-max-gap-seconds 180
+```
+
+Supply rotations oldest first. Choose gap limits for the recording cadence and the delay you consider acceptable. Both limits are required. You can omit power and maintenance inputs.
+
+## What to read in the report
+
+The command writes one JSON object with schema `i14-soak-correlate/1`. Start with `coverage.status` and `coverage.gaps`. Coverage spans the first through the last DNS observation. A single observation gives incomplete coverage. Between successive observations, the tool subtracts planned maintenance and reports each remaining gap strictly longer than the DNS limit.
+
+`dns` counts passed, planned-failure and unplanned-failure observations. A probe with several failed checks counts once. `unplanned_failures` lists each such observation's UTC time, failed check names, and `external_power`. The totals by power state appear in `unplanned_by_power_state`.
+
+| Exit | Meaning | Output |
+| --- | --- | --- |
+| 0 | DNS coverage complete and all failures, if any, were planned | JSON on stdout |
+| 1 | DNS coverage complete with at least one unplanned failure | JSON on stdout |
+| 2 | DNS coverage incomplete | JSON on stdout, including observed failures |
+| 2 | Invalid arguments or input | Diagnostic on stderr, empty stdout |
+
+## Input files
+
+- **DNS CSV** comes from `scripts/i14-dns-soak.py`. Each file needs its recorder header and one physical line per probe. The five expected results in order are `NOERROR`, `NOERROR`, `NOERROR`, `NOERROR+AD`, and `SERVFAIL`. A different nonempty answer counts as a failure. Each latency must be an unsigned decimal integer between zero and 2⁶³−1 milliseconds.
+- **Power JSONL** uses the top-level fields in the soak sampler's `samples.jsonl`. Each line needs a numeric POSIX `epoch`, a nonempty string `boot_id`, and numeric nonnegative `uptime_seconds`. The numeric `usb_online` and `ac_online` fields can each be 0, 1, null or absent. Other fields, including the sampler's own DNS check, are ignored. Duplicate JSON keys and nonstandard JSON constants invalidate a sample.
+- **Maintenance** takes one `START END [reason]` per line. Blank lines and lines starting with `#` are allowed. Both endpoints are inclusive. Touching or overlapping windows merge. A point window splits a gap at that instant and exempts only a failure recorded at that instant.
+
+All inputs use UTF-8. Each DNS or power file can contain up to 16 MiB, each maintenance file up to 1 MiB. At least one DNS observation is required. DNS and maintenance timestamps use a date and time with seconds, optionally a fraction through nanoseconds and a UTC offset. A missing offset means UTC. Use `T` between date and time in the whitespace-delimited maintenance file.
+
+Each input stream must be chronological across rotations. Adjacent identical observations at one instant collapse. A different DNS answer or latency at the same instant, conflicting power fields, or a timestamp moving backwards produces an error. Power comparisons use the five fields above and treat absent and null online flags alike. Time comparisons use integer nanoseconds.
+
+## Interpreting power
+
+A failure at time `t` uses the left sample of the adjacent interval `[a, b)` containing `t`. Both samples must share a boot ID. Elapsed wall time and uptime must each increase by at most the selected power gap and agree within two seconds. Either online flag equal to 1 yields `online`. Two zeros yield `offline`.
+
+An `unknown` state includes a `power_reason` naming the missing evidence, such as a reboot, clock disagreement, or absent online flags. The last power sample cannot establish an interval on its own. The clocks of both recorders must already be aligned. Power changes between samples can go unseen, and a matching time alone cannot establish why DNS failed.
+
+The JSON contains file counts, timestamps and check names. File errors include the supplied path and, when available, the line number.
diff --git a/docs/STATUS.md b/docs/STATUS.md
index 5ced94c..71f9fe8 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -1,13 +1,10 @@
-# Current status — 22 November 2026
+# Current status — 23 November 2026
-This overview covers the Topiky/I14 device examined by this project. It separates
-the historical 2–5 November v9 runtime baseline ([runtime check](verification/2026-11-05-runtime.txt)),
-narrower later device measurements (13 November v10c capture, 18 November
-userdata cleanup, and 19 November UI maintenance), and source/host-tooling
-milestones integrated on `main` through 22 November 2026.
-Window B was accepted for its measured version; the 48-hour Soak C test remains
-open. Source merges, host tests, and CI builds do not establish that a change
-has been deployed to or accepted on the phone.
+The latest device check covered the v10c/B5 installation on 23 November. The
+[2–5 November v9 runtime check](verification/2026-11-05-runtime.txt) remains
+the baseline for features outside that check. Window B passed for its measured
+version. Soak C collector commissioning passed on B5. The uninterrupted
+48-hour window and post-soak H3 measurements remain open.
## Current installation (latest recorded device state)
@@ -27,7 +24,38 @@ has been deployed to or accepted on the phone.
full-image hash; the prior full B5 content hash is therefore historical and
does not describe every currently installed UI file.
-## Source and host-tooling milestones on `main` (not yet device-accepted)
+### 23 November B5 verification
+
+- **Installed binaries.** All six programs in `/usr/libexec/i14-rs/`
+ (`i14-battery-guard`, `i14-cpufreq`, `i14-netwatch`, `i14-reboot-bootloader`,
+ `i14-splash`, `i14-ui`) and `/mnt/data/media/0/i14-linux/soak/i14-soak-sample-rs`
+ matched the ARM64 musl release SHA-256 hashes. The build used `9d3d781`,
+ whose Rust sources match the `main` merge `fb00a71`. Three binaries needed
+ replacement. The `.pre-20261123` rollback copies of `i14-cpufreq`, `i14-splash`
+ and `i14-ui` matched their pre-deployment hashes.
+- **Services and DNS.** All 12 default OpenRC services reported `[ started ]`.
+ All four supervised Rust daemons were running the verified binaries.
+ `i14-probe` passed 8/8 checks on hardware. Local Unbound answered
+ `i14-health.invalid` with `192.0.2.1`. The installed `unbound-1.25.2-r2`
+ lacks the fixes for CVE-2026-81634 and CVE-2026-96405. Keep
+ `dns-clients.conf` empty for acceptance until the candidate manifest
+ confirms both fixes. [Package details](DEVELOPMENT.md).
+- **Battery gauge and home-screen ETA.** PR #2 merged on 22 November and was
+ deployed on B5. Both 23 November snapshots reported `gauge_mode: "hw_car"`.
+ The hardware coulomb counter tracked remaining charge (`q_rem_mah`) against
+ an estimated full capacity (`q_full_mah`). Both reported `anchored: false`,
+ so the UI keeps the estimate marker (`~N%`) until the gauge records an
+ anchor, then displays `N%`. Bounded two-cycle C13 calibration remains open.
+ The home screen estimates time to the charge limit or time remaining on
+ discharge. Replaying the two snapshots on the host produced discharge ETAs.
+ The SSH check did not observe or photograph the screen.
+- **Soak C commissioning.** Root `crond` ran a bounded capture (`PASS`, exit 0).
+ The original root crontab was restored byte-for-byte, with no collector
+ process or lock left behind. [The phase exporter](../scripts/i14-soak-phase-export.py)
+ streamed the capture with `--stream`, and [the receiver](../scripts/i14-soak-receive.py)
+ verified all 18 files (9,715,485 bytes) against their hashes.
+
+## Source and host-tooling milestones
- **Security hardening in source** (PR #11): locally activated, authenticated
USB rescue; normal USB management restricted to SSH keys; fail-closed
@@ -42,6 +70,16 @@ has been deployed to or accepted on the phone.
Linux 7 recovery timing analysis, offline raw-data audit for acceptance
window B (`scripts/i14-window-audit.py`), and bounded C13 battery calibration
tools.
+- **Acceptance tooling on main** (PR #3) added offline rootfs trial staging and
+ rollback verification, paired H1 sample checks, the Soak C observer and
+ streaming export/receiver, C13 launcher storage and deadline checks, M0
+ host timing anchors, and matching fastboot installer diagnostics.
+- **Additional host tools.** The [offline DNS/power correlator](../scripts/i14-soak-correlate.py)
+ processed 200 recorded B5 power samples with 199/199 usable intervals in a
+ smoke test using synthetic DNS answers. [Correlator guide](SOAK-CORRELATE.md).
+ The Rust `i14-make-android-props`
+ writer in `rust/crates/i14-tools` produced a byte-identical 128 KiB property
+ area for the same input as [the Python writer](../rootfs/make-android-props.py).
- **CI and host-test hardening**: `.github/workflows/ci.yml` runs Python
lint/tests, boot-install and initramfs tests, Rust formatting/Clippy/tests,
and ARM64 musl builds on GitHub-hosted `ubuntu-latest`, with deterministic UI
@@ -50,8 +88,7 @@ has been deployed to or accepted on the phone.
## Features (historical 2–5 November v9 baseline)
The table below reflects the 2–5 November v9 runtime baseline and has not been
-fully re-verified end to end after the v10c/B5 updates. Window B was later
-accepted for its measured version; the 48-hour Soak C test remains open.
+fully re-verified end to end after the v10c/B5 updates. The later B5 checks are recorded above.
| Component | Working | Notes |
| --- | --- | --- |
@@ -69,7 +106,7 @@ accepted for its measured version; the 48-hour Soak C test remains open.
| Bluetooth | Partially | Radio and classic/BLE scanning tested; pairing, audio and file transfer are not implemented |
| Charging | Yes, on 3.18 | Demonstrated in Linux and in the custom powered-off charging mode |
| Charge limit | Partially | BCCT stop/resume actuator, guard crash, clean stop and actual reboot tested. A full unchanged 80% charge-band cycle and hysteresis after a crash inside the band remain open |
-| Battery gauge | Estimate only | `~N%` uses estimated open-circuit voltage and a generic stock profile. No calibrated capacity or exact state of charge; the earlier raw 100% reading was unreliable |
+| Battery gauge | Voltage estimate on v9 | The v9 display used an open-circuit voltage estimate. B5 now runs the HW-CAR gauge described above. |
| CPU control | Yes | Downclocking to 299 MHz at idle with screen off, higher clocks under activity. A/B/A testing did not establish energy savings |
| Automatic startup after charging | Partially | Return from custom charging mode tested with substantial charge remaining. An actual nearly-empty → charging → unattended Linux cycle was skipped at the owner's request and remains unproven |
| Audio | Not verified as a user feature | DMA playback test had no underruns; audible output, mixer routing and Bluetooth audio have not been demonstrated |
@@ -80,12 +117,12 @@ accepted for its measured version; the 48-hour Soak C test remains open.
## Priorities
-1. Verify device baseline and deploy/accept the security-hardened stock-kernel image; keep the DNS client list empty until the candidate build manifest confirms the applicable Unbound fixes (see [DEVELOPMENT.md](DEVELOPMENT.md)).
+1. Deploy and accept the hardened stock boot image and rootfs together (authenticated USB rescue, fail-closed firewall, settings directory `0700` and files `0600`). Keep the DNS client list empty until the candidate build manifest confirms the applicable Unbound fixes (see [DEVELOPMENT.md](DEVELOPMENT.md)).
2. Complete paired H1 Rust/Python performance measurements and resolve the new rootfs candidate (R), currently in `KEEP_B5 / R_DEFERRED_INTEGRITY`, with carry and automatic rollback verification.
-3. Commission unattended collection and run the uninterrupted 48-hour Soak C test (H2/H3) on one frozen software version (Window B was accepted for its measured version; Soak C remains open).
-4. Run a full natural charge-band cycle, bounded C13 battery calibration (rechecking free space first, as a 3 GiB R staging image can drop userdata below the 2 GiB floor again), and crash-in-band hysteresis checks.
+3. Run the uninterrupted 48-hour Soak C window on one frozen version, then collect the read-only H3 Rust measurements.
+4. Run a full natural 80% charge-band cycle, bounded two-cycle C13 battery calibration (rechecking free space first, as a 3 GiB R staging image can drop userdata below the 2 GiB floor again), and crash-in-band hysteresis checks.
5. Keep nearly-empty → charging → unattended Linux recovery (D) on hold until explicit new owner direction reopens it.
-6. Continue Linux 7 mainline recovery (M0) and charging work as a separate track; do not attribute 3.18 results to it.
+6. Linux 7 mainline recovery (M0) remains a separate track. The recorded return took 70.6 s against a 40 s limit.
See [the roadmap](ROADMAP.md) for the full entry gates and closure criteria.
diff --git a/rust/README.md b/rust/README.md
index fd7cc46..9fd622f 100644
--- a/rust/README.md
+++ b/rust/README.md
@@ -16,7 +16,7 @@ image integration and device acceptance.
| `i14-soak` | the minute soak sampler (`i14-soak-sample`, run from cron on userdata) |
| `i14-util` | small phone tools: `i14-reboot-bootloader` (reboot into fastboot) |
| `i14-charge` | prepared, not in the boot image: `i14-charge-wait`, the power-off charging loop of the initramfs |
-| `i14-tools` | host tool for the Mac: `i14-build-boot` with the authenticated rescue overlay |
+| `i14-tools` | host tools for boot images (`i14-build-boot`), firmware backups (`i14-verify-backup`) and Android properties (`i14-make-android-props`) |
| `i14-fastboot` | host tools for the Mac: `i14-fastboot`, `i14-install-boot` (= `scripts/fastboot_usb.py`, `install_boot_usb.py`); USB via `nusb` |
The rootfs builder on `main` still installs the existing services. The plan for
@@ -50,6 +50,15 @@ shasum -a 256 target/aarch64-unknown-linux-musl/release/i14-probe
`Cargo.lock` pins dependency versions. Two clean builds of `i14-probe` on the
same Mac gave the same hash.
+## Write the Android property area
+
+From `rust/`, run the host writer with an output path. It creates parent
+directories and writes the 128 KiB bionic property area used by the Wi-Fi tools.
+
+```sh
+mise exec -- cargo run --locked -p i14-tools --bin i14-make-android-props -- ./android-properties
+```
+
## Verify a firmware backup offline
The checker streams SHA-256 over the phase-0 and userdata manifests, checks
diff --git a/rust/crates/i14-tools/src/bin/i14-make-android-props.rs b/rust/crates/i14-tools/src/bin/i14-make-android-props.rs
new file mode 100644
index 0000000..ec88a46
--- /dev/null
+++ b/rust/crates/i14-tools/src/bin/i14-make-android-props.rs
@@ -0,0 +1,279 @@
+//! i14-make-android-props OUTPUT: write a minimal Android 6 (bionic) property area,
+//! the standard-library-only Rust port of rootfs/make-android-props.py. The two CLIs
+//! write byte-identical 128 KiB areas; tests/test_i14_linux.py (RustPropsWriter) checks
+//! that parity by compiling and running both against temporary paths.
+
+use std::cmp::Ordering;
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::process::exit;
+
+/// The four fixed properties, in insertion order (parity with PROPS in the Python CLI).
+const PROPS: [(&str, &str); 4] = [
+ ("service.wcn.driver.ready", "yes"),
+ ("persist.mtk.wcn.combo.chipid", "0x0321"),
+ ("service.wcn.coredump.mode", "0"),
+ ("ro.build.type", "user"),
+];
+const SIZE: usize = 128 * 1024;
+const HEADER: usize = 128;
+const MAGIC: u32 = 0x504F_5250;
+const VERSION: u32 = 0xFC6E_D0AB;
+const VALUE_MAX: usize = 92;
+
+/// The property area after the 128-byte header: a trie of prop_bt nodes plus prop_info
+/// records, allocated from offset 0 and zero-padded to the full size on output.
+struct Area {
+ data: Vec,
+ used: usize,
+}
+
+impl Area {
+ fn new() -> Self {
+ let mut area = Area {
+ data: vec![0; SIZE - HEADER],
+ used: 0,
+ };
+ area.node(b"").expect("root node fits"); // root
+ area
+ }
+
+ fn alloc(&mut self, size: usize) -> Result {
+ let off = self.used;
+ let end = off + ((size + 3) & !3);
+ if end > self.data.len() {
+ return Err("property area full".to_string());
+ }
+ self.used = end;
+ Ok(off)
+ }
+
+ fn node(&mut self, name: &[u8]) -> Result {
+ let off = self.alloc(20 + name.len() + 1)?;
+ self.data[off] = u8::try_from(name.len()).expect("name fits in u8");
+ self.data[off + 20..off + 20 + name.len()].copy_from_slice(name);
+ Ok(off)
+ }
+
+ /// Field 0=prop 1=left 2=right 3=children of the node at `off` (little-endian u32).
+ fn field(&self, off: usize, index: usize) -> u32 {
+ u32::from_le_bytes(
+ self.data[off + 4 + 4 * index..off + 8 + 4 * index]
+ .try_into()
+ .unwrap(),
+ )
+ }
+
+ fn set_field(&mut self, off: usize, index: usize, value: u32) {
+ self.data[off + 4 + 4 * index..off + 8 + 4 * index].copy_from_slice(&value.to_le_bytes());
+ }
+
+ /// Find or add `name` among the children of `parent` (a binary tree: shorter names
+ /// first, then byte order; smaller goes left), like bionic's find_prop_bt.
+ fn child(&mut self, parent: usize, name: &[u8]) -> Result {
+ let mut cur = self.field(parent, 3) as usize;
+ if cur == 0 {
+ let new = self.node(name)?;
+ self.set_field(parent, 3, new as u32);
+ return Ok(new);
+ }
+ loop {
+ let cmp = {
+ let other = &self.data[cur + 20..cur + 20 + self.data[cur] as usize];
+ name.len().cmp(&other.len()).then_with(|| name.cmp(other))
+ };
+ if cmp == Ordering::Equal {
+ return Ok(cur);
+ }
+ let side = if cmp == Ordering::Less { 1 } else { 2 };
+ let next = self.field(cur, side) as usize;
+ if next == 0 {
+ let new = self.node(name)?;
+ self.set_field(cur, side, new as u32);
+ return Ok(new);
+ }
+ cur = next;
+ }
+ }
+
+ fn add(&mut self, key: &str, value: &str) -> Result<(), String> {
+ if value.len() >= VALUE_MAX {
+ return Err(format!("value too long: {key}"));
+ }
+ let mut cur = 0;
+ for part in key.as_bytes().split(|&b| b == b'.') {
+ cur = self.child(cur, part)?;
+ }
+ let info = self.alloc(4 + VALUE_MAX + key.len() + 1)?;
+ self.data[info..info + 4].copy_from_slice(&((value.len() as u32) << 24).to_le_bytes());
+ self.data[info + 4..info + 4 + value.len()].copy_from_slice(value.as_bytes());
+ self.data[info + 4 + VALUE_MAX..info + 4 + VALUE_MAX + key.len()]
+ .copy_from_slice(key.as_bytes());
+ self.set_field(cur, 0, info as u32);
+ Ok(())
+ }
+
+ fn into_bytes(self) -> Vec {
+ let mut out = Vec::with_capacity(SIZE);
+ out.extend_from_slice(
+ &u32::try_from(self.used)
+ .expect("used fits in u32")
+ .to_le_bytes(),
+ );
+ out.extend_from_slice(&0u32.to_le_bytes()); // header serial
+ out.extend_from_slice(&MAGIC.to_le_bytes());
+ out.extend_from_slice(&VERSION.to_le_bytes());
+ out.resize(HEADER, 0);
+ out.extend_from_slice(&self.data);
+ out
+ }
+}
+
+fn build() -> Result, String> {
+ let mut area = Area::new();
+ for (key, value) in PROPS {
+ area.add(key, value)?;
+ }
+ Ok(area.into_bytes())
+}
+
+const USAGE: &str = "Usage: i14-make-android-props [--] OUTPUT";
+
+fn help() -> ! {
+ println!("{USAGE}\n\nWrite the minimal Android 6 property area used by the MediaTek Wi-Fi tools.\n\nOptions:\n -h, --help Print this help");
+ exit(0);
+}
+
+fn usage_error(message: &str) -> ! {
+ eprintln!("{USAGE}\n{message}");
+ exit(2);
+}
+
+/// argparse in the reference Python 3.13 uses Unicode decimal digits in its
+/// negative-number regex. Each entry is the zero in a Unicode 15.1 decimal block.
+fn decimal_digit(c: char) -> bool {
+ const ZEROS: &[u32] = &[
+ 0x30, 0x660, 0x6f0, 0x7c0, 0x966, 0x9e6, 0xa66, 0xae6, 0xb66, 0xbe6, 0xc66, 0xce6, 0xd66,
+ 0xde6, 0xe50, 0xed0, 0xf20, 0x1040, 0x1090, 0x17e0, 0x1810, 0x1946, 0x19d0, 0x1a80, 0x1a90,
+ 0x1b50, 0x1bb0, 0x1c40, 0x1c50, 0xa620, 0xa8d0, 0xa900, 0xa9d0, 0xa9f0, 0xaa50, 0xabf0,
+ 0xff10, 0x104a0, 0x10d30, 0x11066, 0x110f0, 0x11136, 0x111d0, 0x112f0, 0x11450, 0x114d0,
+ 0x11650, 0x116c0, 0x11730, 0x118e0, 0x11950, 0x11c50, 0x11d50, 0x11da0, 0x11f50, 0x16a60,
+ 0x16ac0, 0x16b50, 0x1d7ce, 0x1d7d8, 0x1d7e2, 0x1d7ec, 0x1d7f6, 0x1e140, 0x1e2f0, 0x1e4f0,
+ 0x1e950, 0x1fbf0,
+ ];
+ let code = c as u32;
+ ZEROS.iter().any(|&zero| (zero..zero + 10).contains(&code))
+}
+
+fn is_negative_number(body: &[u8]) -> bool {
+ let Ok(text) = std::str::from_utf8(body) else {
+ return false;
+ };
+ // The reference regex's '$' also matches before a final newline.
+ let text = text.strip_suffix('\n').unwrap_or(text);
+ match text.split_once('.') {
+ Some((whole, fraction)) => {
+ !fraction.is_empty()
+ && whole.chars().all(decimal_digit)
+ && fraction.chars().all(decimal_digit)
+ }
+ None => !text.is_empty() && text.chars().all(decimal_digit),
+ }
+}
+
+fn output_arg() -> PathBuf {
+ let mut output = None;
+ let mut options = true;
+ let mut extra = false;
+ for arg in std::env::args_os().skip(1) {
+ if options {
+ match arg.as_encoded_bytes() {
+ b"--" => {
+ options = false;
+ continue;
+ }
+ [b'-', b'-', name @ ..] if b"help".starts_with(name) => help(),
+ [b'-', b'-', tail @ ..]
+ if tail
+ .split(|&b| b == b'=')
+ .next()
+ .is_some_and(|prefix| b"help".starts_with(prefix)) =>
+ {
+ usage_error("Help takes no argument.");
+ }
+ [b'-', b'=', ..] => usage_error("Ambiguous option."),
+ [b'-', b'h', rest @ ..] => {
+ // argparse processes a cluster of short options before showing help.
+ match rest.iter().find(|&&b| b != b'h') {
+ Some(b'=' | b'-') => usage_error("Help takes no argument."),
+ _ => help(),
+ }
+ }
+ [b'-', body @ ..]
+ if !body.is_empty() && !body.contains(&b' ') && !is_negative_number(body) =>
+ {
+ extra = true;
+ continue;
+ }
+ _ => {}
+ }
+ }
+ if output.is_some() {
+ extra = true;
+ } else {
+ output = Some(arg);
+ }
+ }
+ if extra {
+ usage_error("Expected one output path. Use -- before paths beginning with '-'.");
+ }
+ let output = output.unwrap_or_else(|| usage_error("Missing output path."));
+ // pathlib drops trailing slashes and redundant "." components before writing.
+ Path::new(&output).components().collect()
+}
+
+fn main() {
+ let output = output_arg();
+ let blob = build().unwrap_or_else(|error| {
+ eprintln!("i14-make-android-props: {error}");
+ exit(1);
+ });
+ let result = output
+ .parent()
+ .map_or(Ok(()), fs::create_dir_all)
+ .and_then(|()| fs::write(&output, blob));
+ if let Err(error) = result {
+ eprintln!("i14-make-android-props: {}: {error}", output.display());
+ exit(1);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn children_share_nodes_and_sort_by_length_then_bytes() {
+ let mut area = Area::new();
+ let root_child = area.child(0, b"bb").unwrap();
+ let short = area.child(0, b"z").unwrap();
+ let equal_length = area.child(0, b"cc").unwrap();
+ let used = area.used;
+ assert_eq!(area.child(0, b"bb").unwrap(), root_child);
+ assert_eq!(area.used, used);
+ assert_eq!(area.field(root_child, 1) as usize, short);
+ assert_eq!(area.field(root_child, 2) as usize, equal_length);
+ }
+
+ #[test]
+ fn allocations_are_aligned_and_bounded() {
+ let mut area = Area::new();
+ let offset = area.alloc(5).unwrap();
+ assert_eq!(offset % 4, 0);
+ assert_eq!(area.used, offset + 8);
+ let remaining = area.data.len() - area.used;
+ area.alloc(remaining).unwrap();
+ assert!(area.alloc(1).is_err());
+ assert_eq!(area.used, area.data.len());
+ }
+}
diff --git a/scripts/i14-soak-correlate.py b/scripts/i14-soak-correlate.py
new file mode 100755
index 0000000..15a6e97
--- /dev/null
+++ b/scripts/i14-soak-correlate.py
@@ -0,0 +1,469 @@
+#!/usr/bin/env python3
+"""Correlate recorded I14 DNS and power samples offline. See docs/SOAK-CORRELATE.md."""
+import argparse
+import bisect
+import datetime
+import json
+import re
+import sys
+from decimal import Decimal, DecimalException, Inexact, localcontext
+from itertools import pairwise
+from typing import NamedTuple
+
+CHECKS = ("health_udp", "health_tcp", "example_udp", "signed_ad", "bogus")
+EXPECTED = ("NOERROR", "NOERROR", "NOERROR", "NOERROR+AD", "SERVFAIL")
+HEADER = ["time", "health_udp", "ms", "health_tcp", "ms", "example_udp", "ms",
+ "signed_ad", "ms", "bogus", "ms"]
+MAX_LATENCY_MS = 2 ** 63 - 1
+MAX_DNS_BYTES = 16 * 1024 * 1024 # inclusive byte cap per DNS CSV file
+MAX_POWER_BYTES = 16 * 1024 * 1024 # inclusive byte cap per power JSONL file
+MAX_MAINTENANCE_BYTES = 1024 * 1024 # inclusive byte cap on the maintenance file
+INTEGER_RE = re.compile(r"[0-9]+")
+# Match one complete recorder field, allowing doubled quotes in quoted fields.
+CSV_FIELD = re.compile(r'(?:[^",\r\n]*|"[^"\r\n]*(?:""[^"\r\n]*)*")(?=,|\Z)')
+ISO_TIME = re.compile(
+ r"([0-9]{4}-[0-9]{2}-[0-9]{2}[T ][0-9]{2}:[0-9]{2}:[0-9]{2})"
+ r"(?:\.([0-9]{1,9}))?(Z|[+-](?:[01][0-9]|2[0-3]):[0-5][0-9])?"
+)
+EPOCH = datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc)
+NS = 10**9
+SCHEMA = "i14-soak-correlate/1"
+NOTES = [
+ "Correlation of sampled DNS and power logs only: neither an SLA nor proof of physical"
+ " power state, boot events or causation.",
+ "Coverage gaps are missing monitoring evidence between the first and last DNS"
+ " observation; they never count as DNS failures.",
+ "external_power is the left sample of a qualified adjacent same-boot interval [a,b);"
+ " missing or conflicting power telemetry never changes a DNS outcome, only the state"
+ " becomes unknown with a power_reason.",
+]
+
+
+class InvalidInput(Exception):
+ """Malformed input file; the message carries the path/line diagnostic."""
+
+
+class Parser(argparse.ArgumentParser):
+ """Argument parser whose diagnostics are one physical line on stderr, exit 2, no stdout."""
+
+ def error(self, message):
+ sys.stderr.write(f"invalid input: {visible(message)}\n")
+ sys.exit(2)
+
+
+def visible(text):
+ """Escape non-printable characters so a diagnostic stays one physical line."""
+ return "".join(c if c.isprintable() else c.encode("unicode_escape").decode("ascii") for c in text)
+
+
+class Dns(NamedTuple):
+ time: int
+ answers: tuple[str, ...]
+ latencies: tuple[int, ...]
+
+
+class Power(NamedTuple):
+ time: int
+ boot: str
+ uptime: int
+ usb: int | None
+ ac: int | None
+
+
+def input_lines(path, limit):
+ """Bound even a single unterminated line by the bytes remaining in this file."""
+ try:
+ with open(path, "rb") as stream:
+ remaining = limit
+ line_no = 0
+ while raw := stream.readline(remaining + 1):
+ remaining -= len(raw)
+ if remaining < 0:
+ raise InvalidInput(f"{path}: file is larger than the {limit}-byte input cap")
+ line_no += 1
+ try:
+ yield line_no, raw.decode("utf-8").removesuffix("\n").removesuffix("\r")
+ except UnicodeDecodeError:
+ raise InvalidInput(f"{path}:{line_no}: not valid UTF-8") from None
+ except OSError as exc:
+ raise InvalidInput(f"{path}: cannot read file: {exc.strerror}") from None
+
+
+def parse_time(text):
+ match = ISO_TIME.fullmatch(text)
+ if not match:
+ raise ValueError
+ whole, fraction, zone = match.groups()
+ delta = datetime.datetime.fromisoformat(whole + (zone if zone and zone != "Z" else "+00:00")).astimezone(EPOCH.tzinfo) - EPOCH
+ return (delta.days * 86400 + delta.seconds) * NS + int((fraction or "").ljust(9, "0"))
+
+
+def iso_z(t):
+ seconds, ns = divmod(t, NS)
+ stamp = (EPOCH + datetime.timedelta(seconds=seconds)).replace(tzinfo=None)
+ fraction = f".{ns:09d}".rstrip("0") if ns else ""
+ return stamp.isoformat() + fraction + "Z"
+
+
+def seconds_number(ns):
+ return ns // NS if ns % NS == 0 else ns / NS
+
+
+def nanoseconds(value):
+ # Trap rounding so adjacent observations cannot silently become duplicates.
+ if type(value) not in (int, Decimal):
+ raise ValueError
+ value = Decimal(value)
+ if not value.is_finite() or (value and abs(value.adjusted()) > 1000):
+ raise ValueError
+ with localcontext() as ctx:
+ ctx.traps[Inexact] = True
+ return int(value.scaleb(9).to_integral_exact())
+
+
+def append_ordered(records, record, where, kind, previous_name):
+ if records and record.time <= records[-1].time:
+ if record.time < records[-1].time:
+ raise InvalidInput(f"{where}: earlier than the previous {previous_name}")
+ if record != records[-1]:
+ raise InvalidInput(f"{where}: conflicting {kind} records at the same timestamp")
+ else:
+ records.append(record)
+
+
+def csv_fields(line, where):
+ if '"' not in line and "\r" not in line:
+ return line.split(",", len(HEADER))
+ fields = []
+ start = 0
+ while len(fields) <= len(HEADER):
+ match = CSV_FIELD.match(line, start)
+ if not match:
+ raise InvalidInput(f"{where}: malformed CSV quoting")
+ field = match[0]
+ if field.startswith('"'):
+ field = field[1:-1].replace('""', '"')
+ fields.append(field)
+ if match.end() == len(line):
+ break
+ start = match.end() + 1
+ return fields
+
+
+def load_dns(paths):
+ records = []
+ for path in paths:
+ lines = input_lines(path, MAX_DNS_BYTES)
+ header = next(lines, None)
+ if header is None:
+ raise InvalidInput(f"{path}: empty file")
+ if csv_fields(header[1], f"{path}:1") != HEADER:
+ raise InvalidInput(f"{path}:1: unsupported header")
+ for ln, line in lines:
+ where = f"{path}:{ln}"
+ fields = csv_fields(line, where)
+ if len(fields) != len(HEADER):
+ raise InvalidInput(f"{where}: expected 11 fields")
+ try:
+ t = parse_time(fields[0])
+ except (ValueError, OverflowError):
+ raise InvalidInput(f"{where}: invalid timestamp") from None
+ answers = tuple(fields[1::2])
+ latencies = []
+ for check, answer, raw in zip(CHECKS, answers, fields[2::2]):
+ if not answer.strip():
+ raise InvalidInput(f"{where}: empty answer for {check}")
+ digits = raw.lstrip("0") or "0"
+ if not INTEGER_RE.fullmatch(raw) or len(digits) > 19 or int(digits) > MAX_LATENCY_MS:
+ raise InvalidInput(f"{where}: invalid {check} latency")
+ latencies.append(int(digits))
+ append_ordered(records, Dns(t, answers, tuple(latencies)), where, "DNS", "observation")
+ if not records:
+ raise InvalidInput("no effective DNS observation in the --dns inputs")
+ return records
+
+
+def unique_keys(pairs):
+ row = dict(pairs)
+ if len(row) != len(pairs):
+ raise ValueError
+ return row
+
+
+def reject_constant(_):
+ raise ValueError
+
+
+def online_field(row, key):
+ value = row.get(key)
+ if value is None:
+ return None
+ if type(value) is bool or value not in (0, 1):
+ raise ValueError
+ return int(value)
+
+
+def load_power(paths):
+ records = []
+ for path in paths:
+ for ln, line in input_lines(path, MAX_POWER_BYTES):
+ where = f"{path}:{ln}"
+ try:
+ row = json.loads(line, parse_float=Decimal, parse_constant=reject_constant,
+ object_pairs_hook=unique_keys)
+ if not isinstance(row, dict):
+ raise ValueError
+ epoch = nanoseconds(row.get("epoch"))
+ uptime = nanoseconds(row.get("uptime_seconds"))
+ boot = row.get("boot_id")
+ if not (-62135596800 * NS <= epoch < 253402300800 * NS and uptime >= 0):
+ raise ValueError
+ if not isinstance(boot, str) or not boot.strip():
+ raise ValueError
+ record = Power(epoch, boot, uptime, online_field(row, "usb_online"), online_field(row, "ac_online"))
+ except (DecimalException, ValueError, RecursionError):
+ raise InvalidInput(f"{where}: invalid power record") from None
+ append_ordered(records, record, where, "power", "sample")
+ return records
+
+
+def load_maintenance(path):
+ windows = []
+ if path is not None:
+ for ln, line in input_lines(path, MAX_MAINTENANCE_BYTES):
+ line = line.strip()
+ if not line or line.startswith("#"):
+ continue
+ try:
+ first, last, *_ = line.split(None, 2)
+ start, end = parse_time(first), parse_time(last)
+ except (ValueError, OverflowError):
+ raise InvalidInput(f"{path}:{ln}: invalid maintenance window") from None
+ if start > end:
+ raise InvalidInput(f"{path}:{ln}: reversed maintenance window")
+ windows.append((start, end))
+ return windows
+
+
+def merge_windows(windows):
+ """Sort and merge unordered/overlapping (and touching) windows into a disjoint union."""
+ merged = []
+ for a, b in sorted(windows):
+ if merged and a <= merged[-1][1]:
+ merged[-1] = (merged[-1][0], max(merged[-1][1], b))
+ else:
+ merged.append((a, b))
+ return merged
+
+
+def make_membership(merged):
+ """Inclusive window membership test over merged (sorted, disjoint) windows."""
+ starts = [a for a, _ in merged]
+ ends = [b for _, b in merged]
+
+ def inside(t):
+ i = bisect.bisect_right(starts, t) - 1
+ return i >= 0 and t <= ends[i]
+
+ return inside
+
+
+def coverage_gaps(obs, merged, max_gap):
+ """Uncovered pieces strictly longer than max_gap between adjacent DNS observations.
+
+ For each adjacent pair the union of planned maintenance is subtracted from the open
+ interval between the samples; every remaining contiguous piece whose duration is
+ strictly greater than max_gap seconds is emitted as a gap. Equality passes.
+ """
+ gaps = []
+
+ def add_gap(start, end):
+ if end - start > max_gap:
+ gaps.append({"start_utc": iso_z(start), "end_utc": iso_z(end),
+ "duration_seconds": seconds_number(end - start)})
+
+ # Walk the two ordered timelines together. A window spanning the next
+ # observation stays current until its right endpoint has been consumed.
+ index = 0
+ for prev, cur in pairwise(obs):
+ edge = prev.time
+ while index < len(merged) and merged[index][0] < cur.time:
+ start, end = merged[index]
+ add_gap(edge, start)
+ edge = max(edge, end)
+ if end >= cur.time:
+ break
+ index += 1
+ add_gap(edge, cur.time)
+ return gaps
+
+
+def classify(obs, inside):
+ """Split observations into passed / planned-failure counts and unplanned failures."""
+ passed = planned = 0
+ unplanned = []
+ for o in obs:
+ failed = [c for c, want, got in zip(CHECKS, EXPECTED, o.answers) if got != want]
+ if not failed:
+ passed += 1
+ elif inside(o.time):
+ planned += 1
+ else:
+ unplanned.append({"t": o.time, "checks": failed})
+ return passed, planned, unplanned
+
+
+def left_power_state(sample):
+ usb, ac = sample.usb, sample.ac
+ if usb == 1 or ac == 1:
+ return "online"
+ if usb == 0 and ac == 0:
+ return "offline"
+ return "unknown"
+
+
+def analyse_power(samples, max_gap):
+ """Build the power-state lookup for DNS failure times.
+
+ An interval [a,b) between adjacent effective samples is qualified only when both
+ samples share one boot, the wall-clock and uptime deltas are each positive and
+ <= max_gap, and they disagree by at most 2 s. Returns (state_at, qualified_count);
+ state_at(t) yields (state, reason) with a stable reason label when unknown.
+ """
+ epochs = [sample.time for sample in samples]
+ reasons = []
+ for a, b in pairwise(samples):
+ wall = b.time - a.time
+ up = b.uptime - a.uptime
+ if a.boot != b.boot:
+ reason = "different_boot"
+ elif wall > max_gap:
+ reason = "wall_gap_exceeds_power_max_gap"
+ elif up <= 0:
+ reason = "uptime_not_increasing"
+ elif up > max_gap:
+ reason = "uptime_gap_exceeds_power_max_gap"
+ elif abs(wall - up) > 2 * NS:
+ reason = "wall_uptime_disagreement"
+ else:
+ reason = None
+ reasons.append(reason)
+
+ def state_at(t):
+ if not samples:
+ return "unknown", "no_power_samples"
+ i = bisect.bisect_right(epochs, t) - 1
+ if i < 0:
+ return "unknown", "before_first_power_sample"
+ if i == len(reasons):
+ return "unknown", "at_or_after_last_power_sample"
+ if reasons[i]:
+ return "unknown", reasons[i]
+ state = left_power_state(samples[i])
+ return state, "left_state_unknown" if state == "unknown" else None
+
+ return state_at, reasons.count(None)
+
+
+def correlate(dns_paths, power_paths, maintenance_path, dns_max_gap, power_max_gap):
+ """Load, validate and correlate the streams; returns (report dict, exit code)."""
+ obs = load_dns(dns_paths)
+ samples = load_power(power_paths)
+ windows = load_maintenance(maintenance_path)
+ merged = merge_windows(windows)
+ inside = make_membership(merged)
+ gaps = coverage_gaps(obs, merged, dns_max_gap)
+ passed, planned, unplanned = classify(obs, inside)
+ state_at, qualified_count = analyse_power(samples, power_max_gap)
+ failures = []
+ by_state = {"online": 0, "offline": 0, "unknown": 0}
+ for u in unplanned:
+ state, reason = state_at(u["t"])
+ by_state[state] += 1
+ entry = {"time_utc": iso_z(u["t"]), "checks": u["checks"], "external_power": state}
+ if state == "unknown":
+ entry["power_reason"] = reason
+ failures.append(entry)
+ complete = len(obs) > 1 and not gaps
+ if not complete:
+ code = 2
+ elif unplanned:
+ code = 1
+ else:
+ code = 0
+ report = {
+ "schema": SCHEMA,
+ "dns": {
+ "files": len(dns_paths),
+ "effective_observations": len(obs),
+ "first_utc": iso_z(obs[0].time),
+ "last_utc": iso_z(obs[-1].time),
+ "passed": passed,
+ "planned_failures": planned,
+ "unplanned_failures": len(unplanned),
+ },
+ "maintenance": {
+ "provided": maintenance_path is not None,
+ "windows": len(windows),
+ "merged_windows": len(merged),
+ "merged_seconds": seconds_number(sum(b - a for a, b in merged)),
+ },
+ "coverage": {
+ "max_gap_seconds": seconds_number(dns_max_gap),
+ "status": "complete" if complete else "incomplete",
+ "single_observation": len(obs) == 1,
+ "gaps": gaps,
+ },
+ "power": {
+ "files": len(power_paths),
+ "effective_samples": len(samples),
+ "max_gap_seconds": seconds_number(power_max_gap),
+ "qualified_intervals": qualified_count,
+ },
+ "unplanned_failures": failures,
+ "unplanned_by_power_state": by_state,
+ "exit_code": code,
+ "notes": list(NOTES),
+ }
+ return report, code
+
+
+def positive_gap(text):
+ try:
+ ns = nanoseconds(Decimal(text))
+ if ns <= 0:
+ raise ValueError
+ return ns
+ except (DecimalException, ValueError):
+ raise argparse.ArgumentTypeError("expected finite positive seconds with nanosecond precision") from None
+
+
+def main(argv=None):
+ p = Parser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ p.add_argument("--dns", action="append", required=True, metavar="CSV",
+ help="recorder DNS CSV, repeatable in acquisition/rotation order, at most 16 MiB each")
+ p.add_argument("--power", action="append", default=[], metavar="JSONL",
+ help="power JSONL stream, repeatable in acquisition/rotation order, at most 16 MiB each;"
+ " may be omitted or empty")
+ p.add_argument("--maintenance", metavar="FILE",
+ help="planned maintenance windows, one 'START END [reason]' per line, at most 1 MiB;"
+ " omitted means zero windows")
+ p.add_argument("--dns-max-gap-seconds", type=positive_gap, required=True, metavar="N",
+ help="required finite positive seconds; uncovered DNS intervals strictly longer than N"
+ " are coverage gaps")
+ p.add_argument("--power-max-gap-seconds", type=positive_gap, required=True, metavar="N",
+ help="required finite positive seconds; power intervals longer than N are not qualified"
+ " for correlation")
+ a = p.parse_args(argv)
+ try:
+ report, code = correlate(a.dns, a.power, a.maintenance,
+ a.dns_max_gap_seconds, a.power_max_gap_seconds)
+ except InvalidInput as e:
+ print(f"invalid input: {visible(str(e))}", file=sys.stderr)
+ return 2
+ sys.stdout.write(json.dumps(report, indent=2, sort_keys=True) + "\n")
+ return code
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/test_i14_linux.py b/tests/test_i14_linux.py
index 4946cd7..0436330 100644
--- a/tests/test_i14_linux.py
+++ b/tests/test_i14_linux.py
@@ -1,9 +1,12 @@
import gzip
import importlib.util
+import os
import pathlib
+import shutil
import struct
import subprocess
import sys
+import tempfile
import unittest
import zlib
@@ -108,6 +111,87 @@ def test_writer_matches_stock_ordering(self):
self.assertEqual(bionic_find(rebuilt, key), value)
+class RustPropsWriter(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cargo = shutil.which("cargo")
+ if cargo is None:
+ raise unittest.SkipTest("Rust property writer parity requires cargo")
+ workspace = ROOT / "rust"
+ binary = "i14-make-android-props"
+ # CI runs Python first. Cargo also refreshes an existing binary after edits.
+ subprocess.run([cargo, "build", "--locked", "-p", "i14-tools", "--bin", binary,
+ "--target-dir", "target"], cwd=workspace, check=True)
+ cls.rust = [workspace / "target/debug" / binary]
+ cls.python = [sys.executable, "-B", ROOT / "rootfs/make-android-props.py"]
+
+ def setUp(self):
+ tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(tmp.cleanup)
+ self.dirs = [pathlib.Path(tmp.name) / tag for tag in ("python", "rust")]
+ for directory in self.dirs:
+ directory.mkdir()
+
+ def run_both(self, args, status=None):
+ results = []
+ for command, cwd in zip((self.python, self.rust), self.dirs):
+ result = subprocess.run([*command, *args], cwd=cwd, capture_output=True, timeout=10)
+ results.append(result)
+ python, rust = results
+ self.assertEqual(rust.returncode, python.returncode, (rust.stderr, python.stderr))
+ if status is not None:
+ self.assertEqual(python.returncode, status, python.stderr)
+ return results
+
+ def test_property_area_and_paths(self):
+ props = load("props_oracle", "rootfs/make-android-props.py")
+ for args in (["nested/é/props"], ["trailing/"], ["dot/."], ["missing/../props"],
+ ["-"], ["-1"], ["-.5"], ["-١٢"], ["-file name"], ["--", "-h"], ["--", "--"]):
+ with self.subTest(args=args):
+ results = self.run_both(args, 0)
+ for result in results:
+ self.assertEqual((result.stdout, result.stderr), (b"", b""))
+ py, rs = [(directory / args[-1]).read_bytes() for directory in self.dirs]
+ self.assertEqual(rs, py)
+ self.assertEqual(len(rs), 128 * 1024)
+ for key, value in props.PROPS.items():
+ self.assertEqual(bionic_find(rs, key), value)
+
+ def test_overwrites_through_symlink(self):
+ for directory in self.dirs:
+ (directory / "old").write_bytes(b"x" * (128 * 1024 + 1))
+ (directory / "link").symlink_to("old")
+ self.run_both(["link"], 0)
+ py, rs = [(directory / "old").read_bytes() for directory in self.dirs]
+ self.assertEqual(rs, py)
+ self.assertEqual(len(rs), 128 * 1024)
+ self.assertTrue(all((directory / "link").is_symlink() for directory in self.dirs))
+
+ def test_non_utf8_path(self):
+ name = os.fsdecode(b"props-\xff")
+ python, rust = self.run_both([name])
+ # Some filesystems (including APFS) reject this byte sequence.
+ if python.returncode == 0:
+ py, rs = [(directory / name).read_bytes() for directory in self.dirs]
+ self.assertEqual(rs, py)
+ else:
+ self.assertEqual(python.returncode, 1, python.stderr)
+ self.assertTrue(rust.stderr)
+
+ def test_exit_codes(self):
+ for directory in self.dirs:
+ (directory / "blocker").touch()
+ for args, code in ((["--help"], 0), (["--hel"], 0), (["-hh"], 0), ([], 2),
+ (["--unknown"], 2), (["--help=value", "-h"], 2), (["-hh-"], 2),
+ (["-²"], 2), (["-=not a path"], 2), (["a", "b"], 2),
+ (["."], 1), (["blocker/sub/out"], 1)):
+ with self.subTest(args=args):
+ for result in self.run_both(args, code):
+ self.assertTrue(result.stderr if code else result.stdout)
+ self.assertEqual([sorted(p.name for p in d.iterdir()) for d in self.dirs],
+ [["blocker"], ["blocker"]])
+
+
class Scripts(unittest.TestCase):
def test_shell_syntax(self):
scripts = [ROOT / "initramfs/i14init", ROOT / "initramfs/i14charge", ROOT / "rootfs/build-alpine-rootfs.sh",
diff --git a/tests/test_i14_soak_correlate.py b/tests/test_i14_soak_correlate.py
new file mode 100644
index 0000000..b593861
--- /dev/null
+++ b/tests/test_i14_soak_correlate.py
@@ -0,0 +1,762 @@
+"""scripts/i14-soak-correlate.py: DNS soak vs power correlation on synthetic data only."""
+import contextlib
+import datetime
+import importlib.util
+import io
+import json
+import os
+import pathlib
+import subprocess
+import sys
+import tempfile
+import threading
+import unittest
+from unittest import mock
+
+ROOT = pathlib.Path(__file__).resolve().parents[1]
+SCRIPT = ROOT / "scripts/i14-soak-correlate.py"
+
+
+def load_script(path):
+ spec = importlib.util.spec_from_file_location(path.stem, path)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+correlate = load_script(SCRIPT)
+
+HEAD = "time,health_udp,ms,health_tcp,ms,example_udp,ms,signed_ad,ms,bogus,ms\n"
+GOOD = "NOERROR,3,NOERROR,14,NOERROR,60,NOERROR+AD,5,SERVFAIL,300\n"
+BAD_UDP = "SERVFAIL,5005,NOERROR,14,NOERROR,60,NOERROR+AD,5,SERVFAIL,300\n" # health_udp wrong
+BAD_TWO = "NOERROR,3,NOERROR,14,NOERROR,60,NOERROR,5,NOERROR,300\n" # signed_ad + bogus wrong
+BASE = "2026-11-04T00:00:00Z"
+OMIT = object()
+
+
+def ep(iso):
+ return datetime.datetime.fromisoformat(iso.replace("Z", "+00:00")).timestamp()
+
+
+def row(t, body=GOOD):
+ return f"{t},{body}"
+
+
+def power(iso, boot="boot-1", usb=1, ac=0, uptime=None, **extra):
+ e = ep(iso)
+ rec = {"epoch": e, "boot_id": boot, "uptime_seconds": e - ep(BASE) if uptime is None else uptime}
+ if usb is not OMIT:
+ rec["usb_online"] = usb
+ if ac is not OMIT:
+ rec["ac_online"] = ac
+ rec.update(extra)
+ return json.dumps(rec)
+
+
+class CorrelateCase(unittest.TestCase):
+ def setUp(self):
+ tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(tmp.cleanup)
+ self.dir = pathlib.Path(tmp.name)
+
+ def write(self, name, content):
+ p = self.dir / name
+ p.write_bytes(content.encode() if isinstance(content, str) else content)
+ return p
+
+ def dns_file(self, name, rows):
+ return self.write(name, HEAD + "".join(rows))
+
+ def argv(self, dns, power=(), maint=None, dns_gap=300, power_gap=180):
+ a = ["--dns-max-gap-seconds", str(dns_gap), "--power-max-gap-seconds", str(power_gap)]
+ for p in dns:
+ a += ["--dns", str(p)]
+ for p in power:
+ a += ["--power", str(p)]
+ if maint is not None:
+ a += ["--maintenance", str(maint)]
+ return a
+
+ def cli(self, dns, power=(), maint=None, dns_gap=300, power_gap=180):
+ return subprocess.run([sys.executable, "-B", str(SCRIPT)]
+ + self.argv(dns, power, maint, dns_gap, power_gap),
+ capture_output=True, text=True, timeout=120)
+
+ def go(self, dns, power=(), maint=None, dns_gap=300, power_gap=180):
+ rc, out, err = self.run_main(dns, power, maint, dns_gap, power_gap)
+ return rc, json.loads(out) if out else None, out, err
+
+ def run_main(self, dns, power=(), maint=None, dns_gap=300, power_gap=180):
+ out, err = io.StringIO(), io.StringIO()
+ with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
+ try:
+ code = correlate.main(self.argv(dns, power, maint, dns_gap, power_gap))
+ except SystemExit as e:
+ code = e.code if isinstance(e.code, int) else 2
+ return code, out.getvalue(), err.getvalue()
+
+ def assert_invalid(self, r, needle=None):
+ rc, rep, out, err = r
+ self.assertEqual(rc, 2)
+ self.assertEqual(out, "") # no stdout on invalid input
+ self.assertIsNone(rep)
+ self.assertEqual(err.count("\n"), 1) # one physical line per error
+ if needle:
+ self.assertIn(needle, err)
+ return err
+
+
+class HappyPath(CorrelateCase):
+ def test_clean_run_exit_0_with_full_schema(self):
+ dns = self.dns_file("dns.csv", [row("2026-11-04T21:00:00Z"), row("2026-11-04T21:01:00Z")])
+ p = self.write("p.jsonl", "\n".join(power(t) for t in
+ ("2026-11-04T21:00:00Z", "2026-11-04T21:01:00Z")) + "\n")
+ rc, rep, out, err = self.go([dns], [p])
+ self.assertEqual((rc, err), (0, ""))
+ self.assertEqual(rep["schema"], "i14-soak-correlate/1")
+ self.assertEqual(rep["dns"]["effective_observations"], 2)
+ self.assertEqual(rep["dns"]["first_utc"], "2026-11-04T21:00:00Z")
+ self.assertEqual(rep["dns"]["last_utc"], "2026-11-04T21:01:00Z")
+ self.assertEqual(rep["dns"]["passed"], 2)
+ self.assertEqual(rep["dns"]["planned_failures"], 0)
+ self.assertEqual(rep["dns"]["unplanned_failures"], 0)
+ self.assertEqual(rep["maintenance"], {"provided": False, "windows": 0,
+ "merged_windows": 0, "merged_seconds": 0})
+ self.assertEqual(rep["coverage"]["status"], "complete")
+ self.assertEqual(rep["coverage"]["gaps"], [])
+ self.assertEqual(rep["coverage"]["single_observation"], False)
+ self.assertEqual(rep["power"]["effective_samples"], 2)
+ self.assertEqual(rep["power"]["qualified_intervals"], 1)
+ self.assertEqual(rep["unplanned_failures"], [])
+ self.assertEqual(rep["unplanned_by_power_state"], {"online": 0, "offline": 0, "unknown": 0})
+ self.assertEqual(rep["exit_code"], 0)
+ self.assertTrue(any("neither an SLA nor proof" in n for n in rep["notes"]))
+
+ def test_unplanned_failure_exit_1_correlates_left_state_online(self):
+ dns = self.dns_file("dns.csv", [row("2026-11-04T21:00:00Z"), row("2026-11-04T21:00:30Z", BAD_UDP),
+ row("2026-11-04T21:01:00Z")])
+ p = self.write("p.jsonl", "\n".join(power(t) for t in
+ ("2026-11-04T21:00:00Z", "2026-11-04T21:00:30Z",
+ "2026-11-04T21:01:00Z")) + "\n")
+ rc, rep, out, err = self.go([dns], [p])
+ self.assertEqual(rc, 1)
+ self.assertEqual(rep["dns"]["passed"], 2)
+ self.assertEqual(rep["unplanned_failures"][0]["time_utc"], "2026-11-04T21:00:30Z")
+ self.assertEqual(rep["unplanned_failures"][0]["checks"], ["health_udp"])
+ self.assertEqual(rep["unplanned_failures"][0]["external_power"], "online")
+ self.assertNotIn("power_reason", rep["unplanned_failures"][0])
+ self.assertEqual(rep["unplanned_by_power_state"], {"online": 1, "offline": 0, "unknown": 0})
+
+ def test_all_failing_check_names_are_retained_in_order(self):
+ dns = self.dns_file("dns.csv", [row("2026-11-04T21:00:00Z", BAD_TWO), row("2026-11-04T21:01:00Z")])
+ rc, rep, out, err = self.go([dns])
+ self.assertEqual(rc, 1)
+ self.assertEqual(rep["unplanned_failures"][0]["checks"], ["signed_ad", "bogus"])
+
+ def test_planned_failure_inside_window_is_not_unplanned(self):
+ dns = self.dns_file("dns.csv", [row("2026-11-04T21:00:00Z"), row("2026-11-04T21:00:30Z", BAD_UDP),
+ row("2026-11-04T21:01:00Z")])
+ m = self.write("m.txt", "# planned\n2026-11-04T21:00:00 2026-11-04T21:01:00 reboot test\n")
+ rc, rep, out, err = self.go([dns], maint=m)
+ self.assertEqual(rc, 0)
+ self.assertEqual(rep["dns"]["planned_failures"], 1)
+ self.assertEqual(rep["dns"]["unplanned_failures"], 0)
+ self.assertEqual(rep["maintenance"]["windows"], 1)
+ self.assertEqual(rep["maintenance"]["merged_windows"], 1)
+ self.assertEqual(rep["maintenance"]["merged_seconds"], 60)
+
+ def test_output_is_deterministic(self):
+ dns = self.dns_file("dns.csv", [row("2026-11-04T21:00:00Z"), row("2026-11-04T21:00:30Z", BAD_UDP),
+ row("2026-11-04T21:01:00Z")])
+ p = self.write("p.jsonl", "\n".join(power(t, usb=0, ac=0) for t in
+ ("2026-11-04T21:00:00Z", "2026-11-04T21:00:30Z",
+ "2026-11-04T21:01:00Z")) + "\n")
+ m = self.write("m.txt", "2026-11-04T20:00:00Z 2026-11-04T20:30:00Z x\n")
+ a = self.cli([dns], [p], m)
+ b = self.cli([dns], [p], m)
+ self.assertEqual(a.stdout, b.stdout)
+ self.assertEqual(a.returncode, b.returncode)
+
+
+class Coverage(CorrelateCase):
+ def test_gap_strictly_greater_than_limit_emits_json_and_exit_2(self):
+ dns = self.dns_file("dns.csv", [row("2026-11-04T21:00:00Z"), row("2026-11-04T21:05:00Z", BAD_UDP)])
+ rc, rep, out, err = self.go([dns], dns_gap=299)
+ self.assertEqual(rc, 2)
+ self.assertIsNotNone(rep) # valid incomplete report still emits JSON
+ self.assertEqual(rep["coverage"]["status"], "incomplete")
+ self.assertEqual(rep["coverage"]["gaps"], [
+ {"start_utc": "2026-11-04T21:00:00Z", "end_utc": "2026-11-04T21:05:00Z",
+ "duration_seconds": 300}])
+ self.assertEqual(rep["dns"]["passed"], 1)
+ self.assertEqual(rep["unplanned_failures"][0]["checks"], ["health_udp"]) # failures still included
+ self.assertEqual(err, "")
+
+ def test_gap_equal_to_the_limit_passes(self):
+ dns = self.dns_file("dns.csv", [row("2026-11-04T21:00:00Z"), row("2026-11-04T21:05:00Z")])
+ rc, rep, out, err = self.go([dns], dns_gap=300)
+ self.assertEqual(rc, 0)
+ self.assertEqual(rep["coverage"]["status"], "complete")
+ self.assertEqual(rep["coverage"]["gaps"], [])
+
+ def test_a_gap_never_counts_as_a_dns_failure(self):
+ dns = self.dns_file("dns.csv", [row("2026-11-04T21:00:00Z"), row("2026-11-04T21:10:00Z")])
+ rc, rep, out, err = self.go([dns], dns_gap=300)
+ self.assertEqual(rc, 2)
+ self.assertEqual(rep["dns"]["passed"], 2)
+ self.assertEqual(rep["dns"]["unplanned_failures"], 0)
+ self.assertEqual(len(rep["coverage"]["gaps"]), 1)
+
+ def test_single_observation_is_incomplete_coverage(self):
+ dns = self.dns_file("dns.csv", [row("2026-11-04T21:00:00Z")])
+ rc, rep, out, err = self.go([dns])
+ self.assertEqual(rc, 2)
+ self.assertIsNotNone(rep)
+ self.assertEqual(rep["coverage"]["status"], "incomplete")
+ self.assertEqual(rep["coverage"]["single_observation"], True)
+ self.assertEqual(rep["coverage"]["gaps"], [])
+ self.assertEqual(rep["dns"]["effective_observations"], 1)
+
+ def test_maintenance_is_subtracted_from_the_open_interval(self):
+ dns = self.dns_file("dns.csv", [row("2026-11-04T21:00:00Z"), row("2026-11-04T21:10:00Z")])
+ m = self.write("m.txt", "2026-11-04T21:01:40 2026-11-04T21:08:20 maintenance\n")
+ rc, rep, out, err = self.go([dns], maint=m, dns_gap=150)
+ self.assertEqual(rc, 0)
+ self.assertEqual(rep["coverage"]["gaps"], []) # pieces are 100 s each
+ rc, rep, out, err = self.go([dns], maint=m, dns_gap=99.999)
+ self.assertEqual(rc, 2)
+ self.assertEqual(rep["coverage"]["gaps"], [
+ {"start_utc": "2026-11-04T21:00:00Z", "end_utc": "2026-11-04T21:01:40Z",
+ "duration_seconds": 100},
+ {"start_utc": "2026-11-04T21:08:20Z", "end_utc": "2026-11-04T21:10:00Z",
+ "duration_seconds": 100}])
+
+ def test_window_endpoints_are_inclusive_for_observation_membership(self):
+ dns = self.dns_file("dns.csv", [row("2026-11-04T21:00:00Z", BAD_UDP),
+ row("2026-11-04T21:00:30Z", BAD_UDP),
+ row("2026-11-04T21:01:00Z", BAD_UDP),
+ row("2026-11-04T21:02:00Z")])
+ m = self.write("m.txt", "2026-11-04T21:00:30Z 2026-11-04T21:01:00Z window\n")
+ rc, rep, out, err = self.go([dns], maint=m)
+ self.assertEqual(rc, 1)
+ self.assertEqual(rep["dns"]["planned_failures"], 2) # both endpoints inclusive
+ self.assertEqual(rep["dns"]["unplanned_failures"], 1) # 21:00:00 is outside
+
+ def test_unordered_overlapping_zoned_windows_are_merged(self):
+ dns = self.dns_file("dns.csv", [row("2026-11-04T21:00:00Z"), row("2026-11-04T22:00:00Z", BAD_UDP),
+ row("2026-11-04T23:00:00Z")])
+ m = self.write("m.txt", "# comment\n\n"
+ "2026-11-04T23:00:00+01:00 2026-11-04T23:30:00+01:00 later\n"
+ "2026-11-04T21:00:00Z 2026-11-04T22:10:00Z earlier\n")
+ rc, rep, out, err = self.go([dns], maint=m, dns_gap=3600)
+ self.assertEqual(rc, 0) # the bad 22:00Z sample is planned, coverage complete (equality passes)
+ self.assertEqual(rep["maintenance"]["windows"], 2)
+ self.assertEqual(rep["maintenance"]["merged_windows"], 1)
+ self.assertEqual(rep["maintenance"]["merged_seconds"], 5400) # 21:00Z..22:30Z
+ self.assertEqual(rep["dns"]["planned_failures"], 1)
+
+ def test_gaps_apply_only_between_first_and_last_observation(self):
+ dns = self.dns_file("dns.csv", [row("2026-11-04T21:00:00Z"), row("2026-11-04T21:01:00Z"),
+ row("2026-11-04T21:02:00Z")])
+ m = self.write("m.txt", "2026-11-04T23:00:00Z 2026-11-04T23:30:00Z far away\n")
+ rc, rep, out, err = self.go([dns], maint=m, dns_gap=300)
+ self.assertEqual(rc, 0)
+ self.assertEqual(rep["coverage"]["gaps"], [])
+
+ def test_fractional_durations(self):
+ dns = self.dns_file("dns.csv", [row("2026-11-04T21:00:00Z"),
+ row("2026-11-04T21:00:00.500000Z")])
+ rc, rep, out, err = self.go([dns], dns_gap=0.5)
+ self.assertEqual(rc, 0) # equality passes
+ rc, rep, out, err = self.go([dns], dns_gap=0.4)
+ self.assertEqual(rc, 2)
+ self.assertEqual(rep["coverage"]["gaps"][0]["duration_seconds"], 0.5)
+
+
+class Ordering(CorrelateCase):
+ def test_identical_records_at_one_instant_collapse_across_zones_and_files(self):
+ f1 = self.dns_file("dns.csv.1", [row("2026-11-04T21:00:00Z"), row("2026-11-04T22:00:00+01:00")])
+ f2 = self.dns_file("dns.csv", [row("2026-11-04T21:01:00Z")])
+ rc, rep, out, err = self.go([f1, f2])
+ self.assertEqual(rc, 0)
+ self.assertEqual(rep["dns"]["effective_observations"], 2) # 21:00Z twice collapsed
+
+ def test_conflicting_records_at_one_instant_fail_with_file_and_line(self):
+ f1 = self.dns_file("dns.csv.1", [row("2026-11-04T21:00:00Z")])
+ f2 = self.dns_file("dns.csv", [row("2026-11-04T21:00:00Z", GOOD.replace("NOERROR,3,", "NOERROR,4,"))])
+ err = self.assert_invalid(self.go([f1, f2]), "conflicting DNS records")
+ self.assertIn(f"{f2}:2:", err)
+ self.assertNotIn("NOERROR", err)
+
+ def test_backwards_timestamp_fails_even_across_rotation_files(self):
+ f1 = self.dns_file("dns.csv.1", [row("2026-11-04T21:00:00Z"), row("2026-11-04T21:01:00Z")])
+ f2 = self.dns_file("dns.csv", [row("2026-11-04T21:00:30Z")])
+ err = self.assert_invalid(self.go([f1, f2]), "earlier than the previous observation")
+ self.assertIn(f"{f2}:2:", err)
+
+ def test_rotation_files_form_one_stream(self):
+ f1 = self.dns_file("dns.csv.1", [row("2026-11-04T21:00:00Z"), row("2026-11-04T21:01:00Z")])
+ f2 = self.dns_file("dns.csv", [row("2026-11-04T21:02:00Z"), row("2026-11-04T21:03:00Z", BAD_UDP)])
+ rc, rep, out, err = self.go([f1, f2])
+ self.assertEqual(rc, 1)
+ self.assertEqual(rep["dns"]["effective_observations"], 4)
+ self.assertEqual(rep["dns"]["first_utc"], "2026-11-04T21:00:00Z")
+ self.assertEqual(rep["dns"]["last_utc"], "2026-11-04T21:03:00Z")
+ self.assertEqual(rep["dns"]["files"], 2)
+
+ def test_every_dns_file_needs_the_recorder_header(self):
+ f1 = self.dns_file("dns.csv.1", [row("2026-11-04T21:00:00Z")])
+ f2 = self.write("dns.csv", row("2026-11-04T21:01:00Z"))
+ self.assert_invalid(self.go([f1, f2]), "unsupported header")
+
+ def test_mixed_timezone_order_is_checked_after_utc_normalization(self):
+ dns = self.dns_file("dns.csv", [row("2026-11-04T22:00:00+01:00"), row("2026-11-04T21:00:30Z")])
+ rc, rep, out, err = self.go([dns])
+ self.assertEqual(rc, 0) # 21:00:00Z then 21:00:30Z
+ dns = self.dns_file("dns2.csv", [row("2026-11-04T21:00:30Z"), row("2026-11-04T22:00:00+01:00")])
+ self.assert_invalid(self.go([dns]), "earlier than the previous observation")
+
+
+class PowerCorrelation(CorrelateCase):
+ def dns_with_failure_at(self, *times):
+ rows = [row("2026-11-04T21:00:00Z")]
+ for t in times:
+ rows.append(row(t, BAD_UDP))
+ rows.append(row("2026-11-04T21:02:00Z"))
+ return self.dns_file("dns.csv", rows)
+
+ def power_file(self, specs):
+ return self.write("p.jsonl", "\n".join(json.dumps(s) if isinstance(s, dict) else s
+ for s in specs) + "\n")
+
+ def test_offline_and_unknown_left_states(self):
+ dns = self.dns_with_failure_at("2026-11-04T21:00:15Z", "2026-11-04T21:00:45Z")
+ p = self.power_file([power("2026-11-04T21:00:00Z", usb=0, ac=0),
+ power("2026-11-04T21:00:30Z", usb=OMIT, ac=None),
+ power("2026-11-04T21:01:00Z", usb=1, ac=0)])
+ rc, rep, out, err = self.go([dns], [p])
+ self.assertEqual(rc, 1)
+ online, unknown = rep["unplanned_failures"]
+ self.assertEqual(online["external_power"], "offline")
+ self.assertNotIn("power_reason", online)
+ self.assertEqual(unknown["external_power"], "unknown")
+ self.assertEqual(unknown["power_reason"], "left_state_unknown")
+ self.assertEqual(rep["unplanned_by_power_state"], {"online": 0, "offline": 1, "unknown": 1})
+
+ def test_intervals_are_half_open_left_state_wins(self):
+ dns = self.dns_with_failure_at("2026-11-04T21:00:15Z", "2026-11-04T21:00:30Z")
+ p = self.power_file([power("2026-11-04T21:00:00Z", usb=1, ac=0),
+ power("2026-11-04T21:00:30Z", usb=0, ac=0),
+ power("2026-11-04T21:01:00Z", usb=1, ac=0)])
+ rc, rep, out, err = self.go([dns], [p])
+ self.assertEqual(rc, 1)
+ first, second = rep["unplanned_failures"]
+ self.assertEqual(first["external_power"], "online") # [21:00:00, 21:00:30)
+ self.assertEqual(second["external_power"], "offline") # at 21:00:30 the next interval starts
+
+ def test_last_power_sample_has_no_interval(self):
+ dns = self.dns_file("dns.csv", [row("2026-11-04T21:00:00Z"), row("2026-11-04T21:00:30Z"),
+ row("2026-11-04T21:01:00Z", BAD_UDP)])
+ p = self.power_file([power("2026-11-04T21:00:00Z"), power("2026-11-04T21:00:30Z"),
+ power("2026-11-04T21:01:00Z")])
+ rc, rep, out, err = self.go([dns], [p])
+ self.assertEqual(rc, 1)
+ self.assertEqual(rep["unplanned_failures"][0]["external_power"], "unknown")
+ self.assertEqual(rep["unplanned_failures"][0]["power_reason"], "at_or_after_last_power_sample")
+
+ def test_before_first_power_sample(self):
+ dns = self.dns_file("dns.csv", [row("2026-11-04T21:00:00Z", BAD_UDP), row("2026-11-04T21:01:00Z")])
+ p = self.power_file([power("2026-11-04T21:00:30Z"), power("2026-11-04T21:01:00Z")])
+ rc, rep, out, err = self.go([dns], [p])
+ self.assertEqual(rc, 1)
+ self.assertEqual(rep["unplanned_failures"][0]["power_reason"], "before_first_power_sample")
+
+ def test_no_power_input_and_empty_power_file_are_allowed(self):
+ dns = self.dns_file("dns.csv", [row("2026-11-04T21:00:00Z", BAD_UDP), row("2026-11-04T21:01:00Z")])
+ rc, rep, out, err = self.go([dns])
+ self.assertEqual(rc, 1)
+ self.assertEqual(rep["power"]["effective_samples"], 0)
+ self.assertEqual(rep["unplanned_failures"][0]["power_reason"], "no_power_samples")
+ empty = self.write("empty.jsonl", "")
+ rc, rep, out, err = self.go([dns], [empty])
+ self.assertEqual(rc, 1)
+ self.assertEqual(rep["unplanned_failures"][0]["power_reason"], "no_power_samples")
+
+ def test_reboot_between_samples_disqualifies_the_interval(self):
+ dns = self.dns_with_failure_at("2026-11-04T21:00:15Z")
+ p = self.power_file([power("2026-11-04T21:00:00Z", boot="boot-1"),
+ power("2026-11-04T21:00:30Z", boot="boot-2"),
+ power("2026-11-04T21:01:00Z", boot="boot-2")])
+ rc, rep, out, err = self.go([dns], [p])
+ self.assertEqual(rc, 1) # the DNS failure still counts; only the power state is unknown
+ self.assertEqual(rep["unplanned_failures"][0]["power_reason"], "different_boot")
+ self.assertEqual(rep["power"]["qualified_intervals"], 1)
+
+ def test_wall_gap_boundary_against_power_max_gap(self):
+ dns = self.dns_with_failure_at("2026-11-04T21:01:00Z")
+ p = self.power_file([power("2026-11-04T21:00:00Z"), power("2026-11-04T21:05:00Z")])
+ rc, rep, out, err = self.go([dns], [p], power_gap=180)
+ self.assertEqual(rep["unplanned_failures"][0]["power_reason"], "wall_gap_exceeds_power_max_gap")
+ rc, rep, out, err = self.go([dns], [p], power_gap=300) # equality qualifies
+ self.assertEqual(rep["unplanned_failures"][0]["external_power"], "online")
+
+ def test_uptime_reset_and_uptime_gap(self):
+ dns = self.dns_with_failure_at("2026-11-04T21:00:15Z")
+ p = self.power_file([power("2026-11-04T21:00:00Z", uptime=100.0),
+ power("2026-11-04T21:00:30Z", uptime=50.0),
+ power("2026-11-04T21:01:00Z")])
+ rc, rep, out, err = self.go([dns], [p])
+ self.assertEqual(rep["unplanned_failures"][0]["power_reason"], "uptime_not_increasing")
+ p = self.power_file([power("2026-11-04T21:00:00Z", uptime=0.0),
+ power("2026-11-04T21:00:30Z", uptime=300.0),
+ power("2026-11-04T21:01:00Z")])
+ rc, rep, out, err = self.go([dns], [p], power_gap=180)
+ self.assertEqual(rep["unplanned_failures"][0]["power_reason"], "uptime_gap_exceeds_power_max_gap")
+
+ def test_wall_uptime_disagreement_boundary(self):
+ dns = self.dns_with_failure_at("2026-11-04T21:00:15Z")
+ p = self.power_file([power("2026-11-04T21:00:00Z", uptime=0.0),
+ power("2026-11-04T21:00:30Z", uptime=32.0),
+ power("2026-11-04T21:01:00Z")])
+ rc, rep, out, err = self.go([dns], [p])
+ self.assertEqual(rep["unplanned_failures"][0]["external_power"], "online") # |30-32| <= 2
+ p = self.power_file([power("2026-11-04T21:00:00Z", uptime=0.0),
+ power("2026-11-04T21:00:30Z", uptime=32.5),
+ power("2026-11-04T21:01:00Z")])
+ rc, rep, out, err = self.go([dns], [p])
+ self.assertEqual(rep["unplanned_failures"][0]["power_reason"], "wall_uptime_disagreement")
+
+ def test_missing_power_never_changes_a_dns_outcome(self):
+ dns = self.dns_file("dns.csv", [row("2026-11-04T21:00:00Z"), row("2026-11-04T21:01:00Z")])
+ p = self.power_file([power("2026-11-04T21:00:00Z", boot="a"),
+ power("2026-11-04T21:00:30Z", boot="b")]) # reboot, no qualified interval
+ rc, rep, out, err = self.go([dns], [p])
+ self.assertEqual(rc, 0) # all DNS passed: power gaps cannot fail the run
+
+
+class PowerStream(CorrelateCase):
+ def dns(self):
+ return self.dns_file("dns.csv", [row("2026-11-04T21:00:00Z"), row("2026-11-04T21:01:00Z")])
+
+ def test_null_and_omitted_online_fields_collapse_at_one_epoch(self):
+ a = {"epoch": ep("2026-11-04T21:00:00Z"), "boot_id": "b", "uptime_seconds": 10.0,
+ "usb_online": None}
+ b = {"epoch": ep("2026-11-04T21:00:00Z"), "boot_id": "b", "uptime_seconds": 10.0}
+ p1 = self.write("p.jsonl.1", json.dumps(a) + "\n")
+ p2 = self.write("p.jsonl", json.dumps(b) + "\n"
+ + power("2026-11-04T21:01:00Z") + "\n")
+ rc, rep, out, err = self.go([self.dns()], [p1, p2])
+ self.assertEqual(rc, 0)
+ self.assertEqual(rep["power"]["effective_samples"], 2) # one collapsed across rotation files
+
+ def test_conflicting_power_records_at_one_epoch_fail(self):
+ a = {"epoch": ep("2026-11-04T21:00:00Z"), "boot_id": "b", "uptime_seconds": 10.0, "usb_online": 1}
+ b = {"epoch": ep("2026-11-04T21:00:00Z"), "boot_id": "b", "uptime_seconds": 10.0, "usb_online": 0}
+ p = self.write("p.jsonl", json.dumps(a) + "\n" + json.dumps(b) + "\n")
+ self.assert_invalid(self.go([self.dns()], [p]), "conflicting power records")
+
+ def test_backwards_epoch_across_rotation_files_fails(self):
+ p1 = self.write("p.jsonl.1", power("2026-11-04T21:01:00Z") + "\n")
+ p2 = self.write("p.jsonl", power("2026-11-04T21:00:00Z") + "\n")
+ err = self.assert_invalid(self.go([self.dns()], [p1, p2]), "earlier than the previous sample")
+ self.assertIn(f"{p2}:1:", err)
+
+ def test_extra_power_fields_are_ignored(self):
+ p = self.write("p.jsonl", power("2026-11-04T21:00:00Z", capacity=88, dns={"ok": True},
+ services={"unbound": 0}) + "\n"
+ + power("2026-11-04T21:01:00Z") + "\n")
+ rc, rep, out, err = self.go([self.dns()], [p])
+ self.assertEqual(rc, 0)
+ self.assertEqual(rep["power"]["effective_samples"], 2)
+
+ def test_invalid_power_rows(self):
+ e = ep("2026-11-04T21:00:00Z")
+ bad_lines = [
+ "not json",
+ "[1, 2]",
+ '"text"',
+ "",
+ json.dumps({"boot_id": "b", "uptime_seconds": 1.0}),
+ json.dumps({"epoch": True, "boot_id": "b", "uptime_seconds": 1.0}),
+ '{"epoch": NaN, "boot_id": "b", "uptime_seconds": 1.0}',
+ '{"epoch": Infinity, "boot_id": "b", "uptime_seconds": 1.0}',
+ json.dumps({"epoch": 1e300, "boot_id": "b", "uptime_seconds": 1.0}),
+ json.dumps({"epoch": e, "boot_id": "", "uptime_seconds": 1.0}),
+ json.dumps({"epoch": e, "boot_id": 7, "uptime_seconds": 1.0}),
+ json.dumps({"epoch": e, "boot_id": "b"}),
+ json.dumps({"epoch": e, "boot_id": "b", "uptime_seconds": -1.0}),
+ json.dumps({"epoch": e, "boot_id": "b", "uptime_seconds": "1"}),
+ json.dumps({"epoch": e, "boot_id": "b", "uptime_seconds": True}),
+ json.dumps({"epoch": e, "boot_id": "b", "uptime_seconds": 1.0, "usb_online": 2}),
+ json.dumps({"epoch": e, "boot_id": "b", "uptime_seconds": 1.0, "usb_online": True}),
+ json.dumps({"epoch": e, "boot_id": "b", "uptime_seconds": 1.0, "ac_online": "1"}),
+ ]
+ for line in bad_lines:
+ with self.subTest(line=line[:40]):
+ p = self.write("p.jsonl", line + "\n")
+ err = self.assert_invalid(self.go([self.dns()], [p]))
+ if line.strip():
+ self.assertNotIn(line.strip()[:20], err) # no raw payload echoed
+
+ def test_non_utf8_power_file_is_invalid(self):
+ p = self.write("p.jsonl", b'{"epoch": 1, "boot_id": "b\xff", "uptime_seconds": 1}\n')
+ self.assert_invalid(self.go([self.dns()], [p]), "UTF-8")
+
+
+class DnsInvalid(CorrelateCase):
+ def dns(self):
+ return self.dns_file("dns.csv", [row("2026-11-04T21:00:00Z")])
+
+ def test_missing_and_empty_inputs(self):
+ self.assert_invalid(self.go([self.dir / "nope.csv"]), "cannot read file")
+ self.assert_invalid(self.go([self.write("e.csv", b"")]), "empty file")
+ self.assert_invalid(self.go([self.write("h.csv", HEAD.encode())]), "no effective DNS observation")
+
+ def test_bad_header_width_and_quoting(self):
+ self.assert_invalid(self.go([self.write("a.csv", "time,health_udp,ms\n" + row("2026-11-04T21:00:00Z"))]),
+ "unsupported header")
+ self.assert_invalid(self.go([self.dns_file("a.csv", [row("2026-11-04T21:00:00Z").rstrip("\n") + ",extra\n"])]),
+ "expected 11 fields")
+ self.assert_invalid(self.go([self.dns_file("a.csv", ["2026-11-04T21:00:00Z,NOERROR\n"])]),
+ "expected 11 fields")
+ self.assert_invalid(self.go([self.write("a.csv", HEAD + row("2026-11-04T21:00:00Z").replace(",300\n", ',"300\n'))]),
+ "malformed CSV")
+
+ def test_bad_timestamps(self):
+ for t in ("not-a-time", "2026-11-04", "2026-13-04T21:00:00Z", "0001-01-01T00:00:00+01:00"):
+ with self.subTest(t=t):
+ self.assert_invalid(self.go([self.dns_file("a.csv", [row(t)])]), "invalid timestamp")
+
+ def test_bad_answers(self):
+ self.assert_invalid(self.go([self.dns_file("a.csv", [row("2026-11-04T21:00:00Z", GOOD.replace(
+ "NOERROR,3,", ",3,"))])]), "empty answer for health_udp")
+ self.assert_invalid(self.go([self.dns_file("a.csv", [row("2026-11-04T21:00:00Z", GOOD.replace(
+ "NOERROR,3,", " ,3,"))])]), "empty answer")
+
+ def test_bad_latencies(self):
+ for bad in ("12.5", "-1", "+3", " 3", "1_0", "0x10", "1e3", "", "9" * 25):
+ with self.subTest(bad=bad):
+ body = GOOD.replace("NOERROR,3,", f"NOERROR,{bad},")
+ self.assert_invalid(self.go([self.dns_file("a.csv", [row("2026-11-04T21:00:00Z", body)])]),
+ "latency")
+
+ def test_latency_bounds_are_inclusive(self):
+ for good in ("0", str(2 ** 63 - 1)):
+ with self.subTest(good=good):
+ body = GOOD.replace("NOERROR,3,", f"NOERROR,{good},")
+ rc, rep, out, err = self.go([self.dns_file("a.csv", [row("2026-11-04T21:00:00Z", body),
+ row("2026-11-04T21:01:00Z")])])
+ self.assertEqual(rc, 0, err)
+
+ def test_non_utf8_and_payload_are_not_echoed(self):
+ raw = (HEAD + '2026-11-04T21:00:00Z,NOERROR,"3\nEVILPAYLOAD",NOERROR,14,NOERROR,60,NOERROR+AD,5,SERVFAIL,300\n').encode()
+ err = self.assert_invalid(self.go([self.write("a.csv", raw)]), "malformed CSV")
+ self.assertNotIn("EVILPAYLOAD", err)
+ self.assert_invalid(self.go([self.write("a.csv", HEAD.encode() + b"2026-11-04T21:00:00Z,\xff,3\n")]),
+ "UTF-8")
+
+ def test_maintenance_file_must_exist_when_supplied_and_reasons_are_not_echoed(self):
+ self.assert_invalid(self.go([self.dns()], maint=self.dir / "nope.txt"), "cannot read file")
+ m = self.write("m.txt", "2026-11-04T22:00:00Z 2026-11-04T21:00:00Z EVILREASON\n")
+ err = self.assert_invalid(self.go([self.dns()], maint=m), "reversed maintenance window")
+ self.assertNotIn("EVILREASON", err)
+ for content in ("2026-11-04T21:00:00Z\n", "nope 2026-11-04T22:00:00Z x\n"):
+ with self.subTest(content=content):
+ m = self.write("m.txt", content)
+ self.assert_invalid(self.go([self.dns()], maint=m))
+
+
+class Caps(CorrelateCase):
+ def test_caps_are_16_mib_dns_power_and_1_mib_maintenance(self):
+ self.assertEqual(correlate.MAX_DNS_BYTES, 16 * 1024 * 1024)
+ self.assertEqual(correlate.MAX_POWER_BYTES, 16 * 1024 * 1024)
+ self.assertEqual(correlate.MAX_MAINTENANCE_BYTES, 1024 * 1024)
+
+ def test_cap_is_per_file_inclusive_and_counted_from_bytes_read(self):
+ raw = (HEAD + row("2026-11-04T21:00:00Z")).encode()
+ raw2 = (HEAD + row("2026-11-04T21:01:00Z")).encode()
+ self.assertEqual(len(raw), len(raw2))
+ f1, f2 = self.write("a.csv", raw), self.write("b.csv", raw2)
+ with mock.patch.object(correlate, "MAX_DNS_BYTES", len(raw)):
+ code, out, err = self.run_main([f1, f2])
+ self.assertEqual(err, "") # two files, each exactly at the cap, are both fine
+ self.assertIn('"effective_observations": 2', out)
+ with mock.patch.object(correlate, "MAX_DNS_BYTES", len(raw) - 1):
+ code, out, err = self.run_main([f1])
+ self.assertEqual((code, out), (2, ""))
+ self.assertIn(f"larger than the {len(raw) - 1}-byte input cap", err)
+ # a pipe has no size metadata: the byte count alone must enforce the cap
+ fifo = self.dir / "pipe.csv"
+ os.mkfifo(fifo)
+ with mock.patch.object(correlate, "MAX_DNS_BYTES", len(raw)):
+ def feed():
+ with open(fifo, "wb") as f:
+ f.write(raw + b"x")
+ t = threading.Thread(target=feed)
+ t.start()
+ code, out, err = self.run_main([fifo])
+ t.join()
+ self.assertEqual((code, out), (2, ""))
+ self.assertIn("larger than the", err)
+
+ def test_power_and_maintenance_caps(self):
+ line = power("2026-11-04T21:00:00Z") + "\n"
+ dns = self.dns_file("dns.csv", [row("2026-11-04T21:00:00Z"), row("2026-11-04T21:01:00Z")])
+ p = self.write("p.jsonl", line.encode())
+ with mock.patch.object(correlate, "MAX_POWER_BYTES", len(line)):
+ code, out, err = self.run_main([dns], [p])
+ self.assertEqual(err, "")
+ with mock.patch.object(correlate, "MAX_POWER_BYTES", len(line) - 1):
+ code, out, err = self.run_main([dns], [p])
+ self.assertEqual((code, out), (2, ""))
+ self.assertIn("larger than the", err)
+ m = self.write("m.txt", b"2026-11-04T21:00:00Z 2026-11-04T21:01:00Z x\n")
+ with mock.patch.object(correlate, "MAX_MAINTENANCE_BYTES", m.stat().st_size):
+ code, out, err = self.run_main([dns], maint=m)
+ self.assertEqual(err, "")
+ with mock.patch.object(correlate, "MAX_MAINTENANCE_BYTES", m.stat().st_size - 1):
+ code, out, err = self.run_main([dns], maint=m)
+ self.assertEqual((code, out), (2, ""))
+ self.assertIn("larger than the", err)
+
+ def test_dns_cap_at_real_scale_is_inclusive(self):
+ prefix = HEAD + "2026-11-04T21:00:00Z,"
+ suffix = ",3,NOERROR,14,NOERROR,60,NOERROR+AD,5,SERVFAIL,300\n"
+ pad = correlate.MAX_DNS_BYTES - len(prefix.encode()) - len(suffix.encode())
+ raw = (prefix + "X" * pad + suffix).encode()
+ self.assertEqual(len(raw), correlate.MAX_DNS_BYTES)
+ dns = self.write("big.csv", raw)
+ rc, rep, out, err = self.go([dns])
+ self.assertEqual(err, "") # exactly 16 MiB is read, not rejected
+ self.assertIsNotNone(rep)
+ self.assertEqual(rep["dns"]["effective_observations"], 1)
+ dns = self.write("big2.csv", raw + b" ")
+ err = self.assert_invalid(self.go([dns]), "larger than the 16777216-byte input cap")
+ self.assertNotIn("XXXX", err)
+
+
+class Regressions(CorrelateCase):
+ def test_dns_writer_and_auditor_sample_schema(self):
+ writer = load_script(SCRIPT.with_name("i14-dns-soak.py"))
+ audit = load_script(SCRIPT.with_name("i14-window-audit.py"))
+ dns = self.dir / "dns.csv"
+ epoch = int(ep(BASE))
+ samples = []
+ times = [datetime.datetime.fromtimestamp(epoch + offset, datetime.timezone.utc)
+ for offset in (0, 60)]
+ with (mock.patch.object(writer, "SERVER", "offline.invalid"),
+ mock.patch.object(writer, "OUT", dns),
+ mock.patch.object(writer, "datetime") as clock,
+ mock.patch.object(writer, "query") as query):
+ clock.datetime.now.side_effect = times
+ for stamp, first_answer in zip(times, ("ERROR:TimeoutError", "NOERROR")):
+ query.side_effect = [first_answer + ",2", "NOERROR,1", "NOERROR,1",
+ "NOERROR+AD,1", "SERVFAIL,1"]
+ writer.main()
+ sample = {"epoch": int(stamp.timestamp()), "iso": stamp.isoformat(),
+ "boot_id": "00000000-0000-4000-8000-000000000001",
+ "uptime_seconds": stamp.timestamp() - epoch + 0.05,
+ "usb_online": 0, "ac_online": 1,
+ "dns": {"ok": True, "ms": 2}, "services": dict.fromkeys(audit.SERVICES, 0)}
+ self.assertEqual(audit.sample_problems(sample), [])
+ samples.append(json.dumps(sample))
+ path = self.write("samples.jsonl", "\n".join(samples))
+ rc, report, _, err = self.go([dns], [path])
+ self.assertEqual((rc, err), (1, ""))
+ self.assertEqual(report["dns"]["passed"], 1)
+ self.assertEqual(report["unplanned_by_power_state"]["online"], 1)
+ self.assertEqual(report["unplanned_failures"][0]["checks"], ["health_udp"])
+
+ def test_fractional_clock_boundaries(self):
+ dns = self.dns_file("dns.csv", [
+ row("2026-11-04T00:00:00.000000001Z", BAD_UDP),
+ row("2026-11-04T00:00:00.000000002Z"),
+ ])
+ epoch = int(ep(BASE))
+ samples = self.write("samples.jsonl", "\n".join(
+ f'{{"epoch":{epoch}.{fraction},"uptime_seconds":0.{fraction},'
+ '"boot_id":"sample","usb_online":1}' for fraction in ("000000001", "100000001")
+ ))
+ rc, report, _, err = self.go([dns], [samples], dns_gap="0.000000001", power_gap="0.1")
+ self.assertEqual((rc, err), (1, ""))
+ self.assertEqual(report["dns"]["effective_observations"], 2)
+ self.assertEqual(report["unplanned_by_power_state"]["online"], 1)
+
+ def test_malformed_and_valid_quoted_answers(self):
+ for answer, valid in (('NO"ERROR', False), ('"NO""ERROR,other"', True)):
+ with self.subTest(answer=answer):
+ dns = self.dns_file("dns.csv", [row(BASE, GOOD.replace("NOERROR,3", answer + ",3")),
+ row("2026-11-04T00:01:00Z")])
+ result = self.go([dns])
+ if valid:
+ self.assertEqual(result[1]["unplanned_failures"][0]["checks"], ["health_udp"])
+ else:
+ self.assert_invalid(result, "malformed CSV quoting")
+
+ def test_duplicate_keys_nonstandard_constants_and_excess_json_depth(self):
+ dns = self.dns_file("dns.csv", [row(BASE)])
+ for extra in ('"boot_id":"other"', '"ignored":NaN', '"ignored":' + "[" * 5000):
+ with self.subTest(extra=extra[:20]):
+ sample = power(BASE)[:-1] + "," + extra + "}"
+ path = self.write("samples.jsonl", sample)
+ err = self.assert_invalid(self.go([dns], [path]), f"{path}:1:")
+ self.assertNotIn(extra[:20], err)
+
+ def test_point_maintenance_splits_gap_and_covers_only_that_instant(self):
+ middle = "2026-11-04T00:01:00Z"
+ end = "2026-11-04T00:02:00Z"
+ maint = self.write("maintenance.txt", f"{middle} {middle} marker")
+ dns = self.dns_file("dns.csv", [row(BASE), row(end)])
+ rc, report, _, err = self.go([dns], maint=maint, dns_gap=60)
+ self.assertEqual((rc, err), (0, ""))
+ self.assertEqual(report["maintenance"]["merged_seconds"], 0)
+ dns = self.dns_file("dns.csv", [row(BASE, BAD_UDP), row(middle, BAD_UDP), row(end)])
+ rc, report, _, err = self.go([dns], maint=maint, dns_gap=60)
+ self.assertEqual((rc, err), (1, ""))
+ self.assertEqual(report["dns"]["planned_failures"], 1)
+
+
+class Cli(CorrelateCase):
+ def dns(self):
+ return self.dns_file("dns.csv", [row("2026-11-04T21:00:00Z"), row("2026-11-04T21:01:00Z")])
+
+ def test_required_flags(self):
+ dns = self.dns()
+ r = subprocess.run([sys.executable, "-B", str(SCRIPT), "--dns", str(dns),
+ "--power-max-gap-seconds", "180"], capture_output=True, text=True)
+ self.assertEqual(r.returncode, 2)
+ self.assertEqual(r.stdout, "")
+ r = subprocess.run([sys.executable, "-B", str(SCRIPT),
+ "--dns-max-gap-seconds", "300"], capture_output=True, text=True)
+ self.assertEqual(r.returncode, 2)
+ self.assertEqual(r.stdout, "")
+
+ def test_gap_limits_must_be_finite_positive(self):
+ dns = self.dns_file("dns.csv", [row("2026-11-04T21:00:00Z"), row("2026-11-04T21:00:00.500000Z")])
+ for bad in ("0", "-1", "nan", "inf", "-inf", "abc"):
+ with self.subTest(bad=bad):
+ r = subprocess.run([sys.executable, "-B", str(SCRIPT), "--dns", str(dns),
+ "--dns-max-gap-seconds", bad, "--power-max-gap-seconds", "180"],
+ capture_output=True, text=True)
+ self.assertEqual(r.returncode, 2)
+ self.assertEqual(r.stdout, "")
+ self.assertEqual(r.stderr.count("\n"), 1)
+ rc, rep, out, err = self.go([dns], dns_gap=0.5, power_gap=0.25)
+ self.assertEqual(rc, 0)
+ self.assertEqual(rep["coverage"]["max_gap_seconds"], 0.5)
+ self.assertEqual(rep["power"]["max_gap_seconds"], 0.25)
+
+ def test_repeatable_ordered_flags(self):
+ f1 = self.dns_file("dns.csv.1", [row("2026-11-04T21:00:00Z")])
+ f2 = self.dns_file("dns.csv", [row("2026-11-04T21:01:00Z")])
+ p1 = self.write("p.jsonl.1", power("2026-11-04T21:00:00Z") + "\n")
+ p2 = self.write("p.jsonl", power("2026-11-04T21:01:00Z") + "\n")
+ rc, rep, out, err = self.go([f1, f2], [p1, p2])
+ self.assertEqual(rc, 0)
+ self.assertEqual(rep["dns"]["files"], 2)
+ self.assertEqual(rep["power"]["files"], 2)
+ self.assertNotIn(str(self.dir), out)
+
+
+if __name__ == "__main__":
+ unittest.main()