mirror of
https://github.com/kuhyx/testsAndMisc.git
synced 2026-11-24 13:06:17 +01:00
Compare commits
No commits in common. "325d5a8baa8fc6789a388d7ae89fca2abe4f2f1f" and "de4b26613585f9a25df40c9faf7cb06270431d02" have entirely different histories.
325d5a8baa
...
de4b266135
@ -1,359 +1,399 @@
|
||||
# Next session: make the push gate fast, then close the coverage holes
|
||||
# Next session: the last 2 untested `fixes/lib` libs
|
||||
|
||||
> **Paste this whole file into a fresh Claude session opened in `~/testsAndMisc`.**
|
||||
> It is self-contained. Do not go looking for the previous session's context.
|
||||
|
||||
There are **two jobs** here. Do them in order — job 1 is small and makes job 2
|
||||
bearable, because job 2 involves many commits.
|
||||
## The job
|
||||
|
||||
---
|
||||
`linux_configuration/scripts/single_use/fixes/lib/` has 22 libs. **Two still
|
||||
have no tests.** Write them, to 100% line coverage, and take each one off
|
||||
`meta/shell-coverage-allowlist.txt`.
|
||||
|
||||
# JOB 1: get `git push` under 10 seconds
|
||||
| lines | lib | entry script | harness |
|
||||
| ----- | ---------------------- | --------------------------- | ----------------------------------------- |
|
||||
| 215 | `ubuntu_perf_fixes.sh` | `fix_ubuntu_performance.sh` | `ubuntu_perf_harness.sh` — ALREADY EXISTS |
|
||||
| 180 | `nvidia_config.sh` | `nvidia_troubleshoot.sh` | needs a new one |
|
||||
|
||||
## What is slow
|
||||
**Do `ubuntu_perf_fixes.sh` first** — its harness already exists and already
|
||||
exports `JOURNALD_CONF_DIR` and `UNDO_DIR`, so you extend rather than build.
|
||||
|
||||
`git push` currently takes **~130 seconds**. Nearly all of it is the
|
||||
`ci-mirror` pre-push hook (`meta/scripts/ci_mirror.sh`), which deliberately
|
||||
re-runs CI locally so a red push cannot reach GitHub. It does four things
|
||||
inside a fresh `git worktree` checkout of HEAD:
|
||||
Allowlist is at **86** entries — count with `grep -vc '^#'`, since the file
|
||||
also holds comment lines.
|
||||
|
||||
| stage | what it costs |
|
||||
| ----------------------------------------- | ------------------------------------- |
|
||||
| venv install from `requirements.txt` | ~0s when cached, ~40s on a change |
|
||||
| `pre-commit run --all-files` | the bulk of it |
|
||||
| `pytest_changed_packages.py` in that venv | seconds to minutes, package-dependent |
|
||||
| `run_shell_test_gate` (the shell suites) | ~40s+ |
|
||||
## What the previous session finished
|
||||
|
||||
For comparison: **pre-commit is already fast — 4.8s measured.** Do not touch
|
||||
it. The whole problem is pre-push.
|
||||
Allowlist **91 -> 86**, six commits. Five libs cleared:
|
||||
|
||||
## The target, and the honest tradeoff
|
||||
| lib | coverage |
|
||||
| ------------------------- | ------------------- |
|
||||
| `arch_cpu.sh` | **57/57 = 100.00%** |
|
||||
| `arch_hardware.sh` | **94/94 = 100.00%** |
|
||||
| `thorium_repairs.sh` | **75/75 = 100.00%** |
|
||||
| `hosts_guard_migrate.sh` | **81/81 = 100.00%** |
|
||||
| `hosts_guard_rollback.sh` | **65/65 = 100.00%** |
|
||||
|
||||
The user asked for **under 10 seconds, ideally ~10s or less, total**.
|
||||
`arch_sysctl.sh` has 23 green assertions but is NOT cleared — see the
|
||||
quarantine section below.
|
||||
|
||||
**Be straight with them about this:** a clean-venv install plus `--all-files`
|
||||
plus two test suites cannot fit in 10s. Something must actually be given up.
|
||||
The decision is theirs, so **measure first, then present the options and their
|
||||
real costs, then implement the one they pick.**
|
||||
## Everything you need already exists — do NOT build a new harness
|
||||
|
||||
### Step 1 — measure each stage separately
|
||||
`fixes/lib/tests/` is a working suite: **28 test files, all green, all
|
||||
shellcheck-clean with zero suppressions.** Layers:
|
||||
|
||||
Do this before proposing anything. Numbers, not guesses:
|
||||
- `run_all.sh` — the runner. **The subject the gate measures through.**
|
||||
- `lib_test_core.sh` — shared primitives. Read it first. **240 lines, close to
|
||||
the 250-line cap: the next helper added here forces a split.**
|
||||
- `_t_eq` / `_t_contains` / `_t_lacks` / `_t_pass` / `_t_fail`
|
||||
- `_t_stub NAME BODY`, plus `_t_stub_stdin` (body from a quoted heredoc),
|
||||
`_t_stub_cat NAME FIXTURE`, `_t_stub_writes NAME ARGNUM CONTENT`. Use
|
||||
these instead of `_t_stub foo '...$1...'`, which trips SC2016 every time.
|
||||
- **`_t_run FUNC [ARG...]`** — runs FUNC in the CURRENT shell, puts combined
|
||||
output in `$out`, returns its status. **Use this, never `out="$(func)"`:**
|
||||
command substitution forks a subshell and kcov then does not register the
|
||||
sourced lib at all (measured: 0 lines via `$( )`, 54 via a direct call).
|
||||
- `_t_unstub NAME...` (runs `hash -r`; deleting the file alone does nothing)
|
||||
- **`_t_hide TOOL...`** — rebuilds PATH from symlinks to every real binary
|
||||
EXCEPT the named ones. It KEEPS `$FAKE_BIN` on PATH, so **`_t_unstub` the
|
||||
tool first** or the harness's own default stub still satisfies `has_cmd`
|
||||
and the "not installed" branch never runs. The farm is cached by tool
|
||||
list; it symlinks ~13.5k binaries and rebuilding it per call cost enough
|
||||
runtime to blow a jail timeout.
|
||||
- `_t_calls` / `_t_reset_calls` — what the stubs recorded.
|
||||
- **Five family harnesses**: `bt_harness.sh`, `arch_perf_harness.sh`,
|
||||
`arch_desktop_harness.sh`, `ubuntu_perf_harness.sh`, `thorium_harness.sh`,
|
||||
`hosts_guard_harness.sh`. Each sources the core, sources the real
|
||||
`scripts/lib/common.sh`, and redefines the helpers that live in the **entry
|
||||
script** rather than any lib.
|
||||
|
||||
**To add a family:** copy `thorium_harness.sh`'s shape (~124 lines). jscpd
|
||||
already excludes `**/lib/tests/**`, so shared test setup carries no
|
||||
duplication risk.
|
||||
|
||||
## The loop, per lib
|
||||
|
||||
```bash
|
||||
cd /home/kuhy/testsAndMisc
|
||||
SP=$(mktemp -d); git worktree add --detach --quiet "$SP/co" HEAD
|
||||
# 1. write tests/test_<lib>.sh, chmod +x it
|
||||
# 2. run the suite bare first -- much faster than the jail
|
||||
bash linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh
|
||||
|
||||
time (cd "$SP/co" && SKIP=pytest-coverage pre-commit run --all-files)
|
||||
time (cd "$SP/co" && python meta/scripts/pytest_changed_packages.py)
|
||||
time bash linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh
|
||||
|
||||
git worktree remove --force "$SP/co"
|
||||
```
|
||||
|
||||
Then find which individual pre-commit hooks dominate `--all-files`:
|
||||
|
||||
```bash
|
||||
cd "$SP/co" && for h in $(grep -oP '(?<=id: ).*' .pre-commit-config.yaml | sort -u); do
|
||||
s=$(date +%s%N); SKIP='' pre-commit run "$h" --all-files >/dev/null 2>&1
|
||||
printf '%6d ms %s\n' $(( ($(date +%s%N)-s)/1000000 )) "$h"
|
||||
done | sort -rn | head -15
|
||||
```
|
||||
|
||||
### Step 2 — the options, in the order I would try them
|
||||
|
||||
1. **Only check what changed.** The single biggest win and the least loss.
|
||||
`--all-files` is the expensive part; `pre-commit run --from-ref
|
||||
origin/main --to-ref HEAD` checks the pushed range instead. The clean
|
||||
worktree already guarantees you are checking committed content.
|
||||
Similarly, only run a shell suite when the push touches shell files.
|
||||
2. **Parallelise the stages.** `pre-commit --all-files`, pytest and the shell
|
||||
gate are independent. Run them concurrently and wait. Roughly the cost of
|
||||
the slowest rather than the sum. **Note:** two coverage jails must never run
|
||||
at once (see the warning in job 2), so if the shell gate is jailed, keep it
|
||||
serial with respect to any other jail.
|
||||
3. **Cache on tree state.** Skip the whole mirror when
|
||||
`git rev-parse HEAD:` (the tree hash) matches the last green run, recorded
|
||||
in a dotfile. A re-push of an unchanged tree then costs ~0s.
|
||||
4. **Move ci-mirror off pre-push entirely.** Pre-push drops to ~5s. The cost
|
||||
is real and must be stated plainly: **a red push can then reach GitHub**,
|
||||
and CI catches it minutes later instead of the hook catching it instantly.
|
||||
The repo's `refuse-red-ci` hook already blocks the NEXT commit on a red
|
||||
baseline, so this is less dangerous than it sounds — but it is a genuine
|
||||
change in guarantees, not a free win.
|
||||
|
||||
Options 1-3 are optimisations that keep the guarantee. Option 4 trades the
|
||||
guarantee for speed. **1+2+3 together may well reach ~10s; try them before
|
||||
proposing 4.** If they land at, say, 25s, say so honestly rather than reaching
|
||||
for 4 without asking.
|
||||
|
||||
### Step 3 — prove it
|
||||
|
||||
```bash
|
||||
time git push # the number that matters
|
||||
```
|
||||
|
||||
And prove the gate still catches things: deliberately break something
|
||||
(a failing assertion in a shell test), confirm the push is refused, then
|
||||
revert. A fast gate that no longer gates is worse than a slow one.
|
||||
|
||||
## Do not
|
||||
|
||||
- Do not weaken or delete a test to make a gate faster.
|
||||
- Do not add `--no-verify` anywhere, or suggest it. It is forbidden by the
|
||||
user's rules.
|
||||
- Do not touch pre-commit's 4.8s — it is already at target.
|
||||
|
||||
---
|
||||
|
||||
# JOB 2: actually get the repo to 100% coverage
|
||||
|
||||
The user asked to "make the repo truly 100% test covered". Be careful with
|
||||
that phrasing: **it is a large campaign, not one task.** Scope it, report the
|
||||
real size, and then work through it. Do not report it done until it is.
|
||||
|
||||
## Where things actually stand
|
||||
|
||||
### Shell: `meta/shell-coverage-allowlist.txt` has **84 exempt libs**
|
||||
|
||||
```bash
|
||||
grep -vc '^#' meta/shell-coverage-allowlist.txt # 84
|
||||
```
|
||||
|
||||
Each line is a shell library allowed to sit below 100% line coverage. The
|
||||
just-finished campaign took this from 91 to 84 by clearing seven libs in
|
||||
`fixes/lib`. The remaining 84 are the job.
|
||||
|
||||
### ~12 gated libs OUTSIDE `fixes/lib` fail the gate RIGHT NOW
|
||||
|
||||
`check_shell_coverage.sh` is **not wired into pre-commit**, so these have been
|
||||
failing silently. Confirmed pre-existing (verified against an earlier commit —
|
||||
they are not caused by recent work):
|
||||
|
||||
```
|
||||
lib/common_packages.sh FAIL
|
||||
periodic_background/digital_wellbeing/lib/ms_override_mgr.sh FAIL
|
||||
periodic_background/digital_wellbeing/lib/ms_scripts.sh FAIL
|
||||
periodic_background/lib/periodic_browser.sh FAIL
|
||||
single_use/utils/lib/analyze_repo_symbols.sh FAIL
|
||||
single_use/utils/lib/bl9000_backup.sh FAIL
|
||||
single_use/utils/lib/download_media.sh FAIL
|
||||
single_use/utils/lib/idle_inhibit.sh FAIL
|
||||
single_use/utils/lib/offline_index.sh FAIL
|
||||
single_use/utils/lib/steam_api.sh FAIL
|
||||
single_use/utils/lib/steam_report.sh FAIL
|
||||
```
|
||||
|
||||
`hosts_protect_custom.sh` and `hosts_protect_unblock.sh` PASS.
|
||||
|
||||
**Start here.** These are worse than an exemption: they are libs the gate
|
||||
believes it is checking and which do not meet the bar. `single_use/utils/lib/`
|
||||
is most of the list and shares one `tests/` directory, so one harness covers
|
||||
several.
|
||||
|
||||
### Python: `python_pkg/` is 25 packages at `fail_under = 100`
|
||||
|
||||
Branch coverage is already enforced at 100% by `meta/pyproject.toml`, so this
|
||||
is likely in decent shape. **Verify before assuming** — and note the user's
|
||||
standing rule: never exclude a package from coverage, write the tests.
|
||||
|
||||
```bash
|
||||
timeout 1800 python -m pytest python_pkg --cov=python_pkg --cov-report=term-missing -q 2>&1 | tail -30
|
||||
```
|
||||
|
||||
### Other languages
|
||||
|
||||
`billsplit/` (Dart), `reverse_survivors/`, `poker-stakes/` (TS) have their own
|
||||
CI. Check their gates before claiming anything about them.
|
||||
|
||||
## Report the real scope first
|
||||
|
||||
Before writing a single test, produce a count: N shell libs exempt, M gated
|
||||
libs failing, Python status, other languages. Give the user that number and a
|
||||
suggested order. "100% covered" spans several days of work; they should see
|
||||
the shape before you spend it.
|
||||
|
||||
## The order I would work in
|
||||
|
||||
1. The ~12 gated-but-failing shell libs (worst: the gate is lying today).
|
||||
2. Wire `check_shell_coverage.sh` into pre-commit so it cannot rot again —
|
||||
**but only after 1**, or every commit is blocked. Mind job 1: this hook is
|
||||
jailed and slow, so scope it to changed files.
|
||||
3. The 84 allowlist entries, cheapest first.
|
||||
4. Python, if the run above shows gaps.
|
||||
|
||||
---
|
||||
|
||||
# How to do shell coverage work here (read before starting job 2)
|
||||
|
||||
## The suite and its harnesses
|
||||
|
||||
`linux_configuration/scripts/single_use/fixes/lib/tests/` is the reference
|
||||
suite: **30 test files, 645 assertions, all green, zero suppressions, 37s.**
|
||||
Copy its shape. Layers:
|
||||
|
||||
- `run_all.sh` — the runner, and the subject the gate measures through.
|
||||
- `lib_test_core.sh` (194 lines) — assertions and stubs.
|
||||
- `lib_test_path.sh` (67 lines) — `_t_hide` and the PATH shim farm.
|
||||
- Six family harnesses, one per entry script.
|
||||
|
||||
Key primitives:
|
||||
|
||||
- `_t_eq` / `_t_contains` / `_t_lacks`
|
||||
- `_t_stub NAME BODY`, plus `_t_stub_stdin` (quoted heredoc), `_t_stub_cat`,
|
||||
`_t_stub_writes`. Use these rather than `_t_stub foo '...$1...'`, which
|
||||
trips SC2016 every time.
|
||||
- **`_t_run FUNC [ARG...]`** — runs FUNC in the CURRENT shell, output in
|
||||
`$out`. **Never `out="$(func)"`:** command substitution forks a subshell and
|
||||
kcov then does not register the sourced lib at all (measured: 0 lines via
|
||||
`$( )`, 54 via a direct call).
|
||||
- **`_t_hide TOOL...`** — makes a tool genuinely unfindable. It KEEPS
|
||||
`$FAKE_BIN` on PATH, so **`_t_unstub` the tool first** or the harness's own
|
||||
default stub still satisfies `has_cmd` and the branch never runs.
|
||||
- `_t_unstub` (runs `hash -r`; deleting the file alone does nothing).
|
||||
|
||||
## Production seams
|
||||
|
||||
Most libs write to `/etc`. The idiom is an override **defaulting to the real
|
||||
path**, so production behaviour is byte-identical:
|
||||
|
||||
```bash
|
||||
local dropin="${SYSCTL_DROPIN_DIR:-/etc/sysctl.d}/99-performance-tuning.conf"
|
||||
```
|
||||
|
||||
Reuse existing names — `SYSTEMD_UNIT_DIR`, `JOURNALD_CONF_DIR`,
|
||||
`UDEV_RULES_DIR`, `SYSCTL_DROPIN_DIR` — and grep the entry script before
|
||||
picking one; a collision is silent.
|
||||
|
||||
**Watch for globals ASSIGNED inside a function** (`XORG_CONF="/etc/..."` with
|
||||
no `local`). Exporting from the harness does not survive the assignment; the
|
||||
default must live at the assignment itself.
|
||||
|
||||
After the first run, `ls -la` the real paths and confirm the mtimes did not
|
||||
move.
|
||||
|
||||
## The measurement loop
|
||||
|
||||
```bash
|
||||
# 1. write the tests, chmod +x
|
||||
# 2. run bare first -- far faster than the jail
|
||||
bash <suite>/run_all.sh
|
||||
|
||||
# 3. measure through the RUNNER, in a detached worktree
|
||||
# 3. then measure through the runner, in a detached worktree
|
||||
timeout 900s bash meta/scripts/shell_coverage_jail.sh --timeout 600s \
|
||||
--subject <suite>/run_all.sh --measure <lib>.sh --min 1 \
|
||||
--fail-on-case-error -- ""
|
||||
--subject linux_configuration/scripts/single_use/fixes/lib/tests/run_all.sh \
|
||||
--measure <lib>.sh --min 1 --fail-on-case-error -- ""
|
||||
|
||||
# 4. close the gap, repeat until 100.00%
|
||||
```
|
||||
|
||||
Then the three-step bar to clear an exemption:
|
||||
**Always measure through `run_all.sh`, never a single test file.**
|
||||
**Always pass `--timeout 600s`** — see the timeout section below.
|
||||
|
||||
1. 100.00% through `run_all.sh`.
|
||||
2. Again at `--min 100`, so a shortfall is a non-zero exit.
|
||||
3. Delete the allowlist line, **then** run
|
||||
`bash meta/scripts/check_shell_coverage.sh <lib>` and confirm exit 0.
|
||||
Running it before deleting proves nothing — it passes via the exemption.
|
||||
## The bar for taking a lib off the allowlist
|
||||
|
||||
## Traps that cost real hours last session
|
||||
1. Measure 100.00% through `run_all.sh`.
|
||||
2. **Measure again at `--min 100`** so a shortfall is a non-zero exit.
|
||||
3. Remove the line from `meta/shell-coverage-allowlist.txt`, then run the gate
|
||||
with **the line already deleted** and confirm exit 0:
|
||||
```bash
|
||||
bash meta/scripts/check_shell_coverage.sh <path to lib>.sh
|
||||
# expect: "every checked shell library meets the coverage bar"
|
||||
```
|
||||
Running it BEFORE deleting the line proves nothing — it passes via the
|
||||
exemption.
|
||||
|
||||
- **Verify an edit landed.** A seam edit reported success, was measured, and
|
||||
never reached the commit; ci-mirror caught it only because it runs from a
|
||||
clean checkout. **After editing, `grep` the file for what you just wrote.**
|
||||
- **Run the suite from a clean checkout before pushing.** It catches exactly
|
||||
the above:
|
||||
```bash
|
||||
SP=$(mktemp -d); git worktree add --detach "$SP/c" HEAD
|
||||
bash "$SP/c/<suite>/run_all.sh"; git worktree remove --force "$SP/c"
|
||||
```
|
||||
- **NEVER run two coverage jails at once.** Every false FAIL last session was
|
||||
CPU contention — a jail plus another jail, or a jail plus `run_all.sh`.
|
||||
Libs "failed" a sweep and passed solo. While a sweep runs, do zero-CPU work.
|
||||
- **Another agent may be committing to this repo concurrently.** The jail
|
||||
fingerprints `git status --porcelain` and aborts with "a write escaped the
|
||||
jail" on THEIR edits. Measure in a detached worktree, and re-check a
|
||||
transient gate failure before believing it.
|
||||
- **Adding a test file can break an ALREADY-CLEARED lib.** Unexplained:
|
||||
`test_arch_sysctl.sh` made kcov stop registering `bt_audio.sh` entirely
|
||||
("instrumented no lines"), turning the gate red. Ruled out: `export out`,
|
||||
the `_t_hide` cache, and runtime (still fails at a 600s timeout). The file
|
||||
is quarantined as `arch_sysctl_quarantined_cases.sh`, outside the
|
||||
`test_*.sh` glob, with 23 still-green assertions.
|
||||
**After adding any test file, re-measure an already-cleared lib** —
|
||||
`bt_audio.sh` is the canary.
|
||||
- **`shfmt` reformats staged shell files**, moving the denominator and
|
||||
invalidating a measurement. Run `shfmt -l` first and land reformats
|
||||
separately.
|
||||
- **The 250-line cap aborts commits**, and a task notification can report
|
||||
"completed (exit code 0)" for a commit that actually failed. Check.
|
||||
- **Stage narrowly.** A `git add` of a directory swept another agent's
|
||||
untracked file into a commit and broke the push.
|
||||
- **`mapfile` is bash-only**; the tool shell is zsh. Wrap in `bash -c`.
|
||||
- **`git stash` is blocked** — even `git stash list` inside a compound
|
||||
command trips the guard. Use a detached worktree.
|
||||
- **Do not pipe jail output through `grep 'lines ='`** — that hides the
|
||||
`warn: case timed out` line, which is the diagnosis you need.
|
||||
- **Do not `pgrep -f <thing>` in a wait loop** — the loop's own command line
|
||||
matches, so it never exits.
|
||||
## NEW: the case timeout is now the binding constraint on suite size
|
||||
|
||||
## The coverage instrument
|
||||
`meta/scripts/lib/shell_coverage_bar.sh` now passes **`--timeout 600s`** to the
|
||||
jail. The jail's own default is 120s, and this suite outgrew it: **98s bare**
|
||||
at 28 test files, and kcov instrumentation roughly doubles that.
|
||||
|
||||
`coverage = (PS4-traced | kcov hits) & (kcov line set - continuation lines)`
|
||||
The failure mode is nasty and worth recognising instantly: the jail prints a
|
||||
correct percentage AND a timeout warning, and `--fail-on-case-error` turns that
|
||||
into a failed gate. It looked like this:
|
||||
|
||||
```
|
||||
warn: case timed out after 120s:
|
||||
bt_audio.sh: 127/127 lines = 100.00%
|
||||
Error: 1 case(s) exited non-zero
|
||||
```
|
||||
|
||||
A lib measuring a perfect 100% was failing the gate. If you add enough test
|
||||
files to approach 600s instrumented, raise it again — the flag is a hang
|
||||
catcher, not a performance budget. The cost is that a genuine hang now takes
|
||||
10 minutes per pass to surface.
|
||||
|
||||
## NEVER run two coverage jails at once
|
||||
|
||||
Every false `FAIL` in the previous session came from CPU contention: two jails,
|
||||
or a jail plus `bash run_all.sh`, and one of them times out. `bt_pairing.sh`,
|
||||
`bt_audio.sh` and `bt_report.sh` each "failed" a sweep and then passed solo.
|
||||
|
||||
When a sweep is running, do **zero-CPU work only** — write docs, read source.
|
||||
Do not run the suite, the gate, or another jail.
|
||||
|
||||
## NEW: adding a test file can break an ALREADY-CLEARED lib
|
||||
|
||||
This is the most important operational lesson of the session, and it is
|
||||
**unexplained**.
|
||||
|
||||
Adding `test_arch_sysctl.sh` to the suite made kcov stop registering
|
||||
`bt_audio.sh` entirely — "kcov instrumented no lines" — for a lib that is off
|
||||
the allowlist at 127/127. That turned the gate red on `main`. Bisected:
|
||||
|
||||
- `a2b23521` (before) — bt_audio 127/127
|
||||
- `afe6ac3a` (shfmt reformat) — bt_audio 127/127
|
||||
- `7c14cfca` (the file lands) — bt_audio "instrumented no lines"
|
||||
|
||||
Removing that one file restores 127/127 with every other new test file still
|
||||
present. Ruled out, each by reverting it alone in a throwaway worktree:
|
||||
`export out`, the `_t_hide` cache, and **runtime** (it still fails at a 600s
|
||||
timeout with no timeout warning, so it is NOT the timeout issue above).
|
||||
|
||||
**Therefore: after adding any test file to this suite, re-measure an
|
||||
already-cleared lib, not just your new one.** `bt_audio.sh` is the right canary
|
||||
— it is the one that broke, it is gated, and it sorts late in the glob.
|
||||
|
||||
## The quarantined file
|
||||
|
||||
`tests/arch_sysctl_quarantined_cases.sh` holds **23 green assertions** for
|
||||
`arch_sysctl.sh`. It is deliberately OUTSIDE the `test_*.sh` glob `run_all.sh`
|
||||
iterates, because of the contagion above. Run it directly:
|
||||
|
||||
```bash
|
||||
bash linux_configuration/scripts/single_use/fixes/lib/tests/arch_sysctl_quarantined_cases.sh
|
||||
```
|
||||
|
||||
`arch_sysctl.sh` stays on the allowlist. It has never measured through the jail
|
||||
anyway — it reports "instrumented no lines" on its own too, like `nc_php.sh`.
|
||||
Its header records what to re-verify before un-quarantining it.
|
||||
|
||||
## The instrument
|
||||
|
||||
Coverage = `(PS4-traced lines | kcov hits) & (kcov line set - continuation lines)`
|
||||
|
||||
`continuation_lines()` in `meta/scripts/lib/shell_coverage_lines.py` excludes
|
||||
lines kcov instruments but bash attributes no statement to: multi-line quoted
|
||||
arguments, multi-line array literals, `} |` / `} >>file`, and (added last
|
||||
session) `done >file` / `done <file`.
|
||||
lines kcov instruments but bash attributes no statement to:
|
||||
|
||||
If you touch it: the acceptance pair is `dot_resolver_install.sh` = 39/39 and
|
||||
`rpi_nc_ca.sh` = 73/73 through `features/lib/tests/run_all.sh` **with its
|
||||
`jail_args` file**. And audit any new predicate by printing every newly
|
||||
excluded line **with its text, across the WHOLE repo** — scoping that audit to
|
||||
one directory last session undercounted the blast radius by 35x (2 lines vs
|
||||
~75).
|
||||
- continuation lines of a multi-line **quoted** argument;
|
||||
- **multi-line array literal** elements and the closing paren (`_ARRAY_OPEN`);
|
||||
- **a closing brace plus an operator** — `} |`, `} >>file` (`_CLOSING_BRACE_OP`);
|
||||
- **NEW: a loop terminator plus a redirect** — `done >file`, `done <file`,
|
||||
`done | cmd` (`_LOOP_END_OP`). bash attributes the redirected compound
|
||||
statement to the loop's OPENING line. Reproduced minimally: in a
|
||||
three-iteration loop ending `done >"$1"`, the body reports hits=3 and the
|
||||
`done` line hits=0. This took `hosts_guard_rollback.sh` 97.01% -> 100%.
|
||||
The redirect is REQUIRED by the pattern — a bare `done` stays in the
|
||||
denominator, so genuinely uncovered loops are still caught.
|
||||
|
||||
A lib already at 100% cannot regress from excluding more lines. Over-exclusion
|
||||
is the only real risk.
|
||||
Acceptance test if you touch it: `dot_resolver_install.sh` = 39/39 and
|
||||
`rpi_nc_ca.sh` = 73/73, **through `features/lib/tests/run_all.sh` WITH the
|
||||
`jail_args` file beside it** (that suite refuses to run bare, and `mapfile` is
|
||||
bash-only — wrap in `bash -c`). And **no lib's percentage may go DOWN**.
|
||||
|
||||
### Known-unfixed artifact
|
||||
A lib already at 100.00% **cannot** regress from excluding more lines
|
||||
(`covered_set = (executed|traced) & denominator`). Over-exclusion is the only
|
||||
real risk. Audit any new predicate by printing every newly-excluded line **with
|
||||
its text** — and **grep the WHOLE repo, not just `fixes/lib`**. `_LOOP_END_OP`
|
||||
looked like it touched 2 lines when scoped to `fixes/lib`; repo-wide it touches
|
||||
~75, of which 14 are in gated non-exempt libs.
|
||||
|
||||
`bt_adapter.sh` is capped at 98.55% (68/69) by line 97: the opening line of a
|
||||
backslash-continued **assignment**, which bash attributes to the LAST line of
|
||||
the run. A backslash-continued plain **command** is attributed to its first
|
||||
line and covers normally. Find them with:
|
||||
### The one known-unfixed artifact
|
||||
|
||||
`bt_adapter.sh` sits at **98.55% (68/69), still exempt**, capped by line 97:
|
||||
the opening line of a backslash-continued **assignment**
|
||||
(`result=$(dbus-send ... \`). bash attributes that statement to the LAST line
|
||||
of the run, so the opening line can never be covered.
|
||||
|
||||
**The predicate is narrower than "has a backslash".** A backslash-continued
|
||||
plain **command** (`apply_fix "..." \`) is attributed to its **FIRST** line and
|
||||
covers normally. Only the assignment flavour caps a lib:
|
||||
|
||||
```bash
|
||||
grep -nE '^[[:space:]]*(local[[:space:]]+)?[A-Za-z_][A-Za-z0-9_]*=.*\\$' <lib>
|
||||
```
|
||||
|
||||
### Libs that do not measure at all
|
||||
Across all 22 libs that matches only `bt_adapter.sh` (1) and `bt_audio.sh` (2),
|
||||
and bt_audio still reached 100%. **Neither remaining lib matches it**, so it
|
||||
does not block this job.
|
||||
|
||||
`arch_sysctl.sh` and `nc_php.sh` both report "kcov instrumented no lines" on
|
||||
every version of the instrument. Treat as unverified; they stay exempt.
|
||||
## Work the jail in a detached worktree
|
||||
|
||||
---
|
||||
The jail fingerprints `git status --porcelain` and aborts with "a write escaped
|
||||
the jail" if the tree changes **during** a run — it compares a delta, so a
|
||||
pre-existing dirty file is fine but any concurrent write is not. **A `git mv`
|
||||
you have not committed yet also trips it.**
|
||||
|
||||
Use a throwaway worktree and **copy one-way, INTO it, never out**:
|
||||
|
||||
```bash
|
||||
SP=/tmp/claude-.../scratchpad
|
||||
git worktree add --detach "$SP/cov" HEAD
|
||||
cp <files> "$SP/cov/<same paths>" # never the reverse
|
||||
```
|
||||
|
||||
Copying _out_ of the worktree is how an earlier session silently reverted its
|
||||
own uncommitted harness edit, twice.
|
||||
|
||||
## Production bugs keep turning up. Expect more.
|
||||
|
||||
Three so far, all dead branches no test could cover without noticing:
|
||||
|
||||
- `bt_audio.sh:21` — `timeout 3 _run_as_user wpctl status`. `timeout` is a
|
||||
binary and cannot invoke a shell function, so it always returned 127.
|
||||
- `arch_perf_report.sh:36,65` — journal-size regex required a space before the
|
||||
unit (`4.2 G`), but `journalctl` prints `305.5M`.
|
||||
- `arch_hardware.sh` — **the same regex bug again**, found this session. The
|
||||
vacuum was unreachable; a multi-gigabyte journal would never be trimmed.
|
||||
|
||||
**When a branch looks untestable, check whether it is actually reachable in
|
||||
production before writing a test around it.** The user's standing answer is
|
||||
"fix it in this commit".
|
||||
|
||||
## Traps that cost real time
|
||||
|
||||
- **`shfmt` runs on every staged shell file and WILL reformat your lib**,
|
||||
moving the denominator and invalidating a measurement taken minutes earlier.
|
||||
Run `shfmt -l <libs>` FIRST and land any reformat as its own commit.
|
||||
- **The 250-line cap aborts the commit**, and a task notification can report
|
||||
"completed (exit code 0)" for a commit that actually failed. Every test file
|
||||
for a lib this size has needed splitting into two. `lib_test_core.sh` is at
|
||||
240 — the next helper added there forces a split.
|
||||
- **A stub must consume what the real tool consumes.** A `bluetoothctl` stub
|
||||
that read one line and exited closed the pipe, so the writing block took
|
||||
SIGPIPE partway through.
|
||||
- **`_t_stub` already records the invocation** into `$DEV/calls`. A custom body
|
||||
that also records double-counts every call.
|
||||
- **Check the argument position before writing a stub.** `pacman -Qi <pkg>`
|
||||
puts the package in `$2`, not `$3`; two assertions passed for the wrong
|
||||
reason until that was fixed.
|
||||
- **A function that appends to a global array must not be called inside `$( )`.**
|
||||
- **A top-level stub function SHADOWS the subject's own** for every later
|
||||
assertion. Put redefinitions in a subshell, and bind them with
|
||||
`eval '_real_name() { _my_recorder "$@"; }'` so shellcheck still sees the
|
||||
recorder as called (SC2329).
|
||||
- **Do not `pgrep -f <thing>` in a wait loop** — the loop's own command line
|
||||
matches, so it never exits. It also makes `pgrep -c` report a phantom match.
|
||||
- **`--fail-on-case-error` or you are flying blind.** The jail suppresses the
|
||||
suite's stdout, so assertions fail invisibly without it.
|
||||
- **Do not pipe jail output through `grep 'lines ='`** — that filter hides the
|
||||
`warn: case timed out` line, which is exactly the diagnosis you need.
|
||||
- **`mapfile` is bash-only**; the Bash tool's shell is zsh. Wrap in `bash -c`.
|
||||
- **`git stash` is blocked by a hook** — even a bare `git stash list` inside a
|
||||
compound command trips the guard. Use a detached worktree.
|
||||
- **Stage narrowly.** A `git add` of a directory swept another agent's
|
||||
untracked file into a commit and broke the push on a prettier check.
|
||||
- **Commits exceed a 2-minute foreground timeout.** Background them and
|
||||
**check the result**.
|
||||
- **Two-strike rule.** Two failed attempts at the same thing -> stop, document,
|
||||
keep the working state.
|
||||
|
||||
## Rules that will bite you
|
||||
|
||||
- **No suppressions, ever.** Fix SC2016/SC2034/SC2329/C901 at the source. When
|
||||
three arrays in `hosts_guard_harness.sh` tripped SC2034 because only the
|
||||
libs read them, the fix was a `_t_table` helper the tests actually call —
|
||||
bash cannot export an array.
|
||||
- **Never weaken an assertion to move a number.** One asserted
|
||||
`_t_lacks ... "hosts-guard.path="` against a line reading
|
||||
`hosts-guard.path=absent`; the fix was `grep -c '=$'`, not deletion.
|
||||
- **Every commit touching code needs evidence** in
|
||||
`docs/superpowers/evidence/<slug>-<date>.json` (validate with
|
||||
`python3 meta/scripts/validate_evidence.py <file>`), **plus a contract** in
|
||||
`docs/superpowers/contracts/` once **>=4 code files** are staged. `.sh`
|
||||
counts; so does the allowlist.
|
||||
- **Put the MEASURED number in it**, never a rounded or hoped-for one. A
|
||||
`"result": "fail"` entry is legitimate and `validate_evidence.py` accepts it.
|
||||
- **New test files need the exec bit** — `chmod +x` the working tree.
|
||||
- Work directly on `main`. Branch creation is blocked.
|
||||
|
||||
## Seams: what each remaining lib needs
|
||||
|
||||
Neither lib can be tested without redirecting its writes. The established
|
||||
idiom is an override **defaulting to the real path**, so production behaviour
|
||||
is byte-identical:
|
||||
|
||||
```bash
|
||||
local dropin="${SYSCTL_DROPIN_DIR:-/etc/sysctl.d}/99-performance-tuning.conf"
|
||||
```
|
||||
|
||||
Reuse the names already in use elsewhere rather than inventing parallel ones:
|
||||
`SYSTEMD_UNIT_DIR`, `JOURNALD_CONF_DIR`, `UDEV_RULES_DIR`, `SYSCTL_DROPIN_DIR`.
|
||||
Grep the entry script for a name before picking it — a collision is silent.
|
||||
|
||||
- **`ubuntu_perf_fixes.sh`** (4 seams): `/etc/sysctl.d/99-performance-tuning.conf`,
|
||||
`/etc/systemd/system/nvidia-persistence.service`,
|
||||
`/etc/systemd/system/nvidia-persistence-mode.service`, `/etc/default/earlyoom`.
|
||||
At 215 lines, check `wc -l` after patching — seam comments run 3-4 lines each.
|
||||
- **`nvidia_config.sh`** (3+ seams): `XORG_CONF`, `XORG_CONF_D`, `PROFILE_FILE`
|
||||
(`/etc/profile`). **Check whether these are `local` or plain globals** — if
|
||||
they are assigned inside a function, a harness `export` will not survive the
|
||||
assignment and they still need the `${VAR:-default}` form.
|
||||
|
||||
Verify containment after the first run: `ls -la` the real paths and confirm
|
||||
the mtimes did not change.
|
||||
|
||||
## PRE-EXISTING: ~12 gated libs OUTSIDE fixes/lib already fail the gate
|
||||
|
||||
`check_shell_coverage.sh` is **not wired into pre-commit**, so a lib can sit
|
||||
below the bar indefinitely without anything going red. Measured this session,
|
||||
and confirmed by re-running at an earlier commit that these are **not** caused
|
||||
by the `_LOOP_END_OP` instrument change:
|
||||
|
||||
```
|
||||
lib/common_packages.sh FAIL (pre-existing)
|
||||
periodic_background/digital_wellbeing/lib/ms_override_mgr.sh FAIL
|
||||
periodic_background/digital_wellbeing/lib/ms_scripts.sh FAIL
|
||||
periodic_background/lib/periodic_browser.sh FAIL (pre-existing)
|
||||
single_use/utils/lib/analyze_repo_symbols.sh FAIL
|
||||
single_use/utils/lib/bl9000_backup.sh FAIL
|
||||
single_use/utils/lib/download_media.sh FAIL
|
||||
single_use/utils/lib/idle_inhibit.sh FAIL
|
||||
single_use/utils/lib/offline_index.sh FAIL
|
||||
single_use/utils/lib/steam_api.sh FAIL (pre-existing)
|
||||
single_use/utils/lib/steam_report.sh FAIL
|
||||
```
|
||||
|
||||
`hosts_protect_custom.sh` and `hosts_protect_unblock.sh` PASS.
|
||||
|
||||
This is a separate, larger job than the `fixes/lib` campaign — `utils/lib/`
|
||||
alone is most of it. **Do not fold it into this task without asking**; it is
|
||||
listed here so the next session recognises these as known and pre-existing
|
||||
rather than something it just broke.
|
||||
|
||||
## Finish with a serial sweep
|
||||
|
||||
Once both libs are committed, run **one** sweep over every off-allowlist lib in
|
||||
`fixes/lib`, serially, with nothing else running:
|
||||
|
||||
```bash
|
||||
for lib in bt_report bt_pairing bt_audio arch_perf_report arch_perf_probes \
|
||||
arch_perf_fixes ubuntu_perf_more arch_cpu arch_hardware \
|
||||
thorium_repairs hosts_guard_migrate hosts_guard_rollback \
|
||||
ubuntu_perf_fixes nvidia_config; do
|
||||
printf '%-24s ' "$lib.sh"
|
||||
timeout 900 bash meta/scripts/check_shell_coverage.sh \
|
||||
"linux_configuration/scripts/single_use/fixes/lib/$lib.sh" \
|
||||
>/dev/null 2>&1 && echo PASS || echo "*** FAIL ***"
|
||||
done
|
||||
```
|
||||
|
||||
At ~2 min/lib that is ~30 minutes. Background it and poll the log, but do not
|
||||
fill the gap with anything that forks.
|
||||
|
||||
## State as of 2026-08-23
|
||||
|
||||
- Allowlist **84** (was 91 at the start of the previous session).
|
||||
- `fixes/lib` cleared: `arch_cpu` 57/57, `arch_hardware` 94/94,
|
||||
`thorium_repairs` 75/75, `hosts_guard_migrate` 81/81,
|
||||
`hosts_guard_rollback` 65/65, `ubuntu_perf_fixes` 81/81,
|
||||
`nvidia_config` 76/76.
|
||||
- The `fixes/lib` suite: 30 files, 645 assertions, 37s, zero suppressions.
|
||||
- Three production bugs were found by writing tests, all dead branches:
|
||||
`bt_audio.sh:21` (`timeout` cannot invoke a shell function),
|
||||
`arch_perf_report.sh:36,65` and `arch_hardware.sh` (journal-size regex
|
||||
demanded a space before the unit, but `journalctl` prints `305.5M`, so the
|
||||
vacuum was unreachable). **Expect more. When a branch looks untestable,
|
||||
check whether it is reachable in production first** — the user's standing
|
||||
answer is "fix it in this commit".
|
||||
Allowlist **86**, down from 91. The `fixes/lib/tests` suite is 28 test files
|
||||
plus 6 harnesses and the core, ~470 assertions, all green, all shellcheck-clean
|
||||
with zero suppressions. Suite runtime **98s bare**.
|
||||
|
||||
Still exempt and measured by an older session; **all predate the instrument
|
||||
fixes and may now measure higher — re-measure before writing any test**:
|
||||
Still exempt and measured by an earlier session, **all predate the instrument
|
||||
fixes and may now measure higher — re-measure before writing a single test**:
|
||||
`dwm_config.sh` 98.48%, `pacman_hook_stall_setup.sh` 96.30%,
|
||||
`aw_autostart.sh` 97.56%, `rpi_nc_install.sh` 96.59%,
|
||||
`transcribe_pkgmgr.sh` 98.00%, `clean_audio_filters.sh` 91.40%,
|
||||
`transcribe_deps.sh` 92.31%.
|
||||
|
||||
`rpi_nc_ca.sh` (73/73) and `dot_resolver_install.sh` (39/39) are already at
|
||||
100% and can come off the allowlist whenever you want, by the three-step bar.
|
||||
That is two free entries.
|
||||
`rpi_nc_ca.sh` (73/73) and `dot_resolver_install.sh` (39/39) are at 100% and
|
||||
could come off the allowlist whenever you want, by the three-step bar.
|
||||
|
||||
`nc_php.sh` does not measure at all — "kcov instrumented no lines", on every
|
||||
version of the instrument. Same bucket as `arch_sysctl.sh`; treat as unverified.
|
||||
|
||||
@ -1,22 +0,0 @@
|
||||
{
|
||||
"title": "Teach the endurain importer to skip runs already in Endurain, and pin the adb fallback to one device",
|
||||
"objective": "RunnerUp can now upload to Endurain directly as well as via the WebDAV inbox, and the two paths cannot see each other: the same run lands twice (activities 14 and 15, identical start time, distances differing only by tcx/gpx rounding). Add a third dedupe check that asks Endurain what it already holds, and fix the adb fallback, which fails on every call the moment a second device is attached.",
|
||||
"acceptance_criteria": [
|
||||
"A run already present in Endurain is moved to processed/ without being uploaded again, even when the local ledger has never seen it.",
|
||||
"A failed or unauthorised remote query returns None and falls back to the existing ledger dedupe. None is never read as 'no matching activity exists', because that would upload a duplicate on every transport hiccup.",
|
||||
"Start times are compared with a tolerance: the file for activity 15 embeds 21:51:04Z while Endurain stored 21:51:05Z, so exact equality misses the very duplicate that motivated this work.",
|
||||
"Export filenames are parsed as LOCAL wall-clock time; RunnerUp_2026-08-14-00-58-45_Running resolves to 2026-08-13 22:58:45 UTC, not 2026-08-14.",
|
||||
"With several adb devices attached and no serial pinned, the phone fallback is skipped with a warning naming the attached serials and the env var, instead of failing every call with 'more than one device/emulator'.",
|
||||
"ENDURAIN_ADB_SERIAL selects the device when set; a pinned serial that is not attached is refused rather than silently ignored.",
|
||||
"Every adb invocation carries -s <serial>; no serial is hardcoded, since this repo is public.",
|
||||
"The five package modules keep 100% branch coverage with no lint suppressions and no coverage exclusions.",
|
||||
"The phone-side files are never written, moved or deleted: screen-locker reads the same directory as its unlock gate."
|
||||
],
|
||||
"out_of_scope": [
|
||||
"Deleting duplicates that already exist. This work prevents new ones; clearing the 14/15 collision needs session credentials and is the user's action.",
|
||||
"Granting the API key the activities:read scope. Both existing keys hold activities:upload only, so the remote check is inert until that changes; the fail-closed path is what ships working today.",
|
||||
"Changing the WebDAV inbox, the dufs config, or RunnerUp's own uploader.",
|
||||
"Recording the returned activity_id in the ledger. It is null on every existing entry, which is cosmetic and unrelated."
|
||||
],
|
||||
"verifier": ".venv/bin/python -m pytest python_pkg/endurain_import/tests/ -q (expects 85 passed), plus --cov=python_pkg.endurain_import showing 100% with zero missed branches on all five modules, plus .venv/bin/python -m ruff check python_pkg/endurain_import/, plus systemctl --user start endurain-import.service with two devices attached showing the named-serials warning rather than 'more than one device/emulator'."
|
||||
}
|
||||
@ -1,71 +0,0 @@
|
||||
{
|
||||
"intent": "Stop the endurain importer duplicating runs that RunnerUp uploaded to Endurain directly, and stop its adb fallback silently failing whenever more than one device is attached.",
|
||||
"scope": [
|
||||
"python_pkg/endurain_import/sources.py — adb device selection",
|
||||
"python_pkg/endurain_import/ledger.py — start time parsed from the export filename",
|
||||
"python_pkg/endurain_import/upload.py — recent-activity query and start-time comparison",
|
||||
"python_pkg/endurain_import/__main__.py — orchestration wiring",
|
||||
"Non-goal: deleting duplicates that already exist. This prevents new ones; it never deletes.",
|
||||
"Non-goal: changing the WebDAV inbox or the phone-side files (screen-locker reads the same directory)."
|
||||
],
|
||||
"changes": [
|
||||
"sources.py: replaced phone_attached() with attached_serials() + resolve_serial(). The old check returned true when ANY device was in the 'device' state, after which every bare adb call failed with 'more than one device/emulator' as a warning on a path nobody watches. The serial is now threaded into every _adb() call as -s. Ambiguity is resolved by configuration (ENDURAIN_ADB_SERIAL), never by guessing: several devices and no pin means the fallback is skipped outright.",
|
||||
"ledger.py: added activity_start(), which parses the run's start time out of the RunnerUp export filename. RunnerUp names exports in LOCAL wall-clock time, so the value is read in the local zone and returned as UTC; reading it as UTC directly shifts a late-evening run onto the wrong day (RunnerUp_2026-08-14-00-58-45 is 2026-08-13 22:58 UTC).",
|
||||
"upload.py: added EndurainClient.recent_start_times(), which fetches one page of recent activities and returns their start times, plus already_present() which compares with a +/-120s tolerance. Endurain exposes no query-by-start-time endpoint, so existence is decided client-side. The tolerance exists because the recorded value is not the one in the file: a run whose export embeds 21:51:04Z was stored by Endurain as 21:51:05Z, which exact equality would miss.",
|
||||
"upload.py: recent_start_times() returns None (not an empty list) for a transport failure, an auth failure, or an unparseable body, so a failed lookup can never be read as 'no matching activity exists'.",
|
||||
"__main__.py: _process() gained a third dedupe check against remote_starts, queried once per run rather than per file. A None result falls back to the existing digest/activity-key ledger checks, which is the previous behaviour. A run matched remotely is recorded in the ledger so the next run skips it without needing the query."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "systemctl --user start endurain-import.service && journalctl --user -u endurain-import.service -n 5",
|
||||
"result": "pass",
|
||||
"evidence": "Ran against the live service with two devices genuinely attached (Pixel 6a 23181JEGR08034 over USB, BL9000 over 192.168.1.131:5555). Logged: '2 devices attached (23181JEGR08034, 192.168.1.131:5555); set ENDURAIN_ADB_SERIAL to choose one. Skipping the phone fallback rather than pulling from an arbitrary device.' Before this change the same situation produced 'could not list /sdcard/Documents/RunnerUp: adb: more than one device/emulator'."
|
||||
},
|
||||
{
|
||||
"command": "python -c 'from python_pkg.endurain_import import sources; sources.resolve_serial()' under three real device configurations",
|
||||
"result": "pass",
|
||||
"evidence": "Two devices attached, no env: None + warning naming both serials. ENDURAIN_ADB_SERIAL=23181JEGR08034: returned '23181JEGR08034'. ENDURAIN_ADB_SERIAL=NOPE123: None + warning that the pinned device is not attached."
|
||||
},
|
||||
{
|
||||
"command": "python -c 'from python_pkg.endurain_import.ledger import activity_start' on real export filenames",
|
||||
"result": "pass",
|
||||
"evidence": "RunnerUp_2026-08-22-23-51-04_Running.tcx -> 2026-08-22 21:51:04+00:00 (DB holds 21:51:05, inside tolerance). RunnerUp_Pixel_6a_2026-08-22-23-51-04_Running.gpx -> identical instant, confirming the device model is stripped. RunnerUp_2026-08-14-00-58-45_Running.tcx -> 2026-08-13 22:58:45+00:00, the day-boundary case. garbage.tcx and RunnerUp_2026-13-45-99-99-99_Running.tcx -> None."
|
||||
},
|
||||
{
|
||||
"command": "python -c 'from python_pkg.endurain_import.upload import already_present' at the tolerance boundary",
|
||||
"result": "pass",
|
||||
"evidence": "1s skew (the real 14/15 collision) -> True. 120s -> True. 121s -> False. Unrelated run -> False. Empty known list -> False."
|
||||
},
|
||||
{
|
||||
"command": "python -c 'EndurainClient(...).recent_start_times(1)' against the running server with both API keys",
|
||||
"result": "pass",
|
||||
"evidence": "Both keys returned None and logged 'could not list recent activities: 401 (the API key needs the activities:read scope for duplicate detection)'. Confirmed against the DB: both keys hold scopes [\"activities:upload\"] only. The fail-closed path is therefore exercised end to end; the positive path is covered by unit tests until the scope is granted."
|
||||
},
|
||||
{
|
||||
"command": ".venv/bin/python -m pytest python_pkg/endurain_import/tests/ -q",
|
||||
"result": "pass",
|
||||
"evidence": "85 passed."
|
||||
},
|
||||
{
|
||||
"command": ".venv/bin/python -m pytest python_pkg/endurain_import/tests/ --cov=python_pkg.endurain_import --cov-report=term-missing",
|
||||
"result": "pass",
|
||||
"evidence": "__init__.py, __main__.py (92 stmts, 20 branches), ledger.py (74/12), sources.py (77/30), upload.py (93/20) all at 100% with zero missed branches. No lint suppressions added."
|
||||
},
|
||||
{
|
||||
"command": ".venv/bin/python -m ruff check python_pkg/endurain_import/",
|
||||
"result": "pass",
|
||||
"evidence": "All checks passed."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"The remote check is inert until the Endurain API key is granted the activities:read scope. Until then recent_start_times() returns None every run and dedupe falls back to the ledger, which is exactly the previous behaviour — no regression, but no new protection either.",
|
||||
"A pre-existing duplicate (activities 14 and 15 share a start time) makes Endurain's own get_activity_by_start_time raise MultipleResultsFound, which 500s an upload of THAT run. Other runs are unaffected. This change does not delete duplicates; the collision has to be cleared in the UI.",
|
||||
"The +/-120s tolerance would collapse two genuinely distinct runs starting within two minutes of each other into one. Judged not a real scenario for a running log; the alternative (exact match) demonstrably misses the real 1s recording skew.",
|
||||
"resolve_serial() now refuses to pull when several devices are attached and no serial is pinned. That is a deliberate behaviour change: the fallback stops silently rather than pulling from an arbitrary device. Set ENDURAIN_ADB_SERIAL to restore pulling."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit; the importer returns to phone_attached() and ledger-only dedupe.",
|
||||
"After rollback confirm: systemctl --user start endurain-import.service exits 0, and the ledger at ~/.local/state/endurain-import/ledger.json is unchanged (this change never rewrites existing entries).",
|
||||
"No data migration is involved — the ledger format is unchanged and no server state is written by the new code path (it only issues GETs)."
|
||||
]
|
||||
}
|
||||
@ -3,15 +3,11 @@
|
||||
Run from a systemd user timer. Configuration comes from the environment:
|
||||
|
||||
ENDURAIN_URL base URL (default http://127.0.0.1:8085)
|
||||
ENDURAIN_API_KEY API key with activities:upload (required) and
|
||||
activities:read (optional; enables detection of
|
||||
runs RunnerUp uploaded to Endurain directly)
|
||||
ENDURAIN_API_KEY API key with the activities:upload scope (required)
|
||||
ENDURAIN_INBOX WebDAV inbox (default ~/cloud/RunnerUp)
|
||||
ENDURAIN_STATE ledger directory (default ~/.local/state/endurain-import)
|
||||
ENDURAIN_BULK_DIR bulk_import dir for files the server rejected
|
||||
ENDURAIN_NO_ADB set to 1 to disable the phone fallback
|
||||
ENDURAIN_ADB_SERIAL which phone to pull from when several are attached
|
||||
ENDURAIN_USER_ID Endurain user whose activities are checked (default 1)
|
||||
|
||||
Exit status is 0 only when every file was accounted for; anything left in an
|
||||
ambiguous state exits non-zero so the timer surfaces it rather than logging
|
||||
@ -25,7 +21,6 @@ import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sys
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import requests
|
||||
|
||||
@ -33,27 +28,17 @@ from python_pkg.endurain_import.ledger import (
|
||||
Entry,
|
||||
Ledger,
|
||||
activity_key,
|
||||
activity_start,
|
||||
file_digest,
|
||||
now_iso,
|
||||
)
|
||||
from python_pkg.endurain_import.sources import inbox_files, pull_from_phone
|
||||
from python_pkg.endurain_import.upload import (
|
||||
EndurainClient,
|
||||
Outcome,
|
||||
SupportsUpload,
|
||||
already_present,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from datetime import datetime
|
||||
from python_pkg.endurain_import.upload import EndurainClient, Outcome, SupportsUpload
|
||||
|
||||
_logger = logging.getLogger("endurain_import")
|
||||
|
||||
_DEFAULT_URL = "http://127.0.0.1:8085"
|
||||
_DEFAULT_INBOX = Path.home() / "cloud" / "RunnerUp"
|
||||
_DEFAULT_STATE = Path.home() / ".local" / "state" / "endurain-import"
|
||||
_DEFAULT_USER_ID = 1
|
||||
|
||||
|
||||
def _configure_logging() -> None:
|
||||
@ -98,40 +83,18 @@ def _process(
|
||||
ledger: Ledger,
|
||||
processed_dir: Path,
|
||||
bulk_dir: Path | None,
|
||||
remote_starts: list[datetime] | None = None,
|
||||
) -> str:
|
||||
"""Import one file. Returns one of: skipped, imported, rejected, ambiguous."""
|
||||
digest = file_digest(path)
|
||||
key = activity_key(path)
|
||||
# Three dedupe checks, cheapest first. The digest catches the identical
|
||||
# file arriving twice; the activity key catches the SAME RUN arriving as
|
||||
# both .gpx and .tcx, whose bytes differ and which Endurain would
|
||||
# otherwise import as two separate activities.
|
||||
known_locally = digest in ledger or ledger.has_activity(key)
|
||||
# The third check asks Endurain itself, which is the only way to see a run
|
||||
# this importer never handled -- RunnerUp's own uploader writes straight to
|
||||
# the server and leaves no trace in the ledger. ``remote_starts`` is None
|
||||
# when that question could not be answered, and None must never be read as
|
||||
# "nothing matches": the local checks then decide alone.
|
||||
start = activity_start(path)
|
||||
known_remotely = (
|
||||
remote_starts is not None
|
||||
and start is not None
|
||||
and already_present(start, remote_starts)
|
||||
)
|
||||
if known_locally or known_remotely:
|
||||
# Two independent dedupe checks. The digest catches the identical file
|
||||
# arriving twice; the activity key catches the SAME RUN arriving as both
|
||||
# .gpx and .tcx, whose bytes differ and which Endurain would otherwise
|
||||
# import as two separate activities.
|
||||
if digest in ledger or ledger.has_activity(key):
|
||||
processed_dir.mkdir(parents=True, exist_ok=True)
|
||||
shutil.move(str(path), str(processed_dir / path.name))
|
||||
if known_remotely and not known_locally:
|
||||
# Record it so the next run skips without needing the query again.
|
||||
ledger.record(Entry(digest, key, path.name, None, now_iso()))
|
||||
_logger.info(
|
||||
"%s is already in Endurain (uploaded outside this importer); "
|
||||
"moved to processed/",
|
||||
path.name,
|
||||
)
|
||||
else:
|
||||
_logger.info("%s already imported; moved to processed/", path.name)
|
||||
_logger.info("%s already imported; moved to processed/", path.name)
|
||||
return "skipped"
|
||||
|
||||
result = client.upload(path)
|
||||
@ -190,21 +153,9 @@ def main() -> int:
|
||||
_logger.info("nothing to import (ledger holds %d file(s))", len(ledger))
|
||||
return 0
|
||||
|
||||
# One query per run, not per file: the page is a snapshot of what Endurain
|
||||
# already holds, and every file in this pass is compared against it.
|
||||
user_id = int(os.environ.get("ENDURAIN_USER_ID", _DEFAULT_USER_ID))
|
||||
remote_starts = client.recent_start_times(user_id)
|
||||
if remote_starts is None:
|
||||
_logger.warning(
|
||||
"duplicate detection against Endurain is unavailable; falling "
|
||||
"back to the local ledger only"
|
||||
)
|
||||
|
||||
counts = {"skipped": 0, "imported": 0, "rejected": 0, "ambiguous": 0}
|
||||
for path in pending:
|
||||
counts[
|
||||
_process(path, client, ledger, processed_dir, bulk_dir, remote_starts)
|
||||
] += 1
|
||||
counts[_process(path, client, ledger, processed_dir, bulk_dir)] += 1
|
||||
|
||||
_logger.info(
|
||||
"done: %(imported)d imported, %(skipped)d already known, "
|
||||
|
||||
@ -21,8 +21,6 @@ if TYPE_CHECKING:
|
||||
_CHUNK = 1 << 20
|
||||
# "RunnerUp", <timestamp>, <sport> -- the minimum for a parseable export name.
|
||||
_MIN_NAME_PARTS = 3
|
||||
# <yyyy>-<mm>-<dd>-<HH>-<MM>-<SS> once split on "-".
|
||||
_STAMP_FIELDS = 6
|
||||
|
||||
|
||||
class LedgerCorruptError(RuntimeError):
|
||||
@ -50,37 +48,6 @@ def activity_key(path: Path) -> str:
|
||||
return stem
|
||||
|
||||
|
||||
def activity_start(path: Path) -> datetime | None:
|
||||
"""Parse the run's start time out of a RunnerUp export filename.
|
||||
|
||||
RunnerUp names exports with LOCAL wall-clock time
|
||||
(RunnerUp_2026-08-14-00-58-45_Running is 00:58 local, 22:58 UTC the day
|
||||
before), so the value is interpreted in the local zone and returned as
|
||||
UTC. Reading it as UTC directly would shift a late-evening run onto the
|
||||
wrong day and defeat the comparison it feeds.
|
||||
"""
|
||||
key = activity_key(path)
|
||||
parts = key.split("_")
|
||||
if len(parts) < _MIN_NAME_PARTS:
|
||||
return None
|
||||
fields = parts[-2].split("-")
|
||||
if len(fields) != _STAMP_FIELDS:
|
||||
return None
|
||||
try:
|
||||
naive = datetime(
|
||||
int(fields[0]),
|
||||
int(fields[1]),
|
||||
int(fields[2]),
|
||||
int(fields[3]),
|
||||
int(fields[4]),
|
||||
int(fields[5]),
|
||||
tzinfo=datetime.now().astimezone().tzinfo,
|
||||
)
|
||||
except ValueError:
|
||||
return None
|
||||
return naive.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def file_digest(path: Path) -> str:
|
||||
"""Return the SHA-256 of ``path``, read incrementally."""
|
||||
digest = hashlib.sha256()
|
||||
|
||||
@ -14,7 +14,6 @@ unlocks the PC; nothing here may delete, move, or rewrite those files.
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
from typing import TYPE_CHECKING
|
||||
@ -28,16 +27,6 @@ _logger = logging.getLogger(__name__)
|
||||
PHONE_EXPORT_DIR = "/sdcard/Documents/RunnerUp"
|
||||
ACTIVITY_SUFFIXES = (".tcx", ".gpx", ".fit")
|
||||
_ADB_TIMEOUT = 60
|
||||
# Pins which phone to pull from when more than one device is attached.
|
||||
# Without it every adb call fails with "more than one device/emulator" --
|
||||
# silently, as a warning on a path nobody watches -- the moment a second
|
||||
# device shows up. Left unset, the single attached device is used.
|
||||
ADB_SERIAL_ENV = "ENDURAIN_ADB_SERIAL"
|
||||
# Pins which phone to pull from when more than one device is attached. Without
|
||||
# it every adb call fails with "more than one device/emulator" -- silently, as
|
||||
# a warning on the fallback path -- the moment a second device (a spare handset,
|
||||
# an emulator) shows up. Left unset the single attached device is used.
|
||||
ADB_SERIAL_ENV = "ENDURAIN_ADB_SERIAL"
|
||||
# Resolved at call time so a missing adb is reported as "no device" rather than
|
||||
# crashing the whole import run.
|
||||
_ADB_BIN = shutil.which("adb") or "adb"
|
||||
@ -59,17 +48,11 @@ def inbox_files(inbox: Path) -> list[Path]:
|
||||
return sorted(found, key=lambda p: p.stat().st_mtime)
|
||||
|
||||
|
||||
def _adb(args: list[str], serial: str | None = None) -> tuple[bool, str]:
|
||||
"""Run an adb command, returning (ok, output).
|
||||
|
||||
``serial`` is threaded into the argv as ``-s`` so every call targets one
|
||||
named device. Omitting it is only correct for ``devices`` itself, which is
|
||||
what resolves the serial in the first place.
|
||||
"""
|
||||
prefix = ["-s", serial] if serial else []
|
||||
def _adb(args: list[str]) -> tuple[bool, str]:
|
||||
"""Run an adb command, returning (ok, output)."""
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
[_ADB_BIN, *prefix, *args],
|
||||
[_ADB_BIN, *args],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=_ADB_TIMEOUT,
|
||||
@ -80,54 +63,15 @@ def _adb(args: list[str], serial: str | None = None) -> tuple[bool, str]:
|
||||
return proc.returncode == 0, proc.stdout + proc.stderr
|
||||
|
||||
|
||||
def attached_serials() -> list[str]:
|
||||
"""Return the serials of every device in the 'device' state."""
|
||||
def phone_attached() -> bool:
|
||||
"""True when exactly one adb device is in the 'device' state."""
|
||||
ok, out = _adb(["devices"])
|
||||
if not ok:
|
||||
return []
|
||||
serials = []
|
||||
for line in out.splitlines()[1:]:
|
||||
if "\t" not in line:
|
||||
continue
|
||||
serial, state = line.split("\t", 1)
|
||||
if state.strip() == "device":
|
||||
serials.append(serial.strip())
|
||||
return serials
|
||||
|
||||
|
||||
def resolve_serial() -> str | None:
|
||||
"""Pick the phone to pull from, or None when the choice is not clear.
|
||||
|
||||
Ambiguity is resolved by configuration, never by guessing: with several
|
||||
devices attached and no ``ENDURAIN_ADB_SERIAL`` set, this returns None so
|
||||
the fallback is skipped outright. The alternative -- letting bare adb pick
|
||||
-- is what produced "more than one device/emulator" as a warning on a path
|
||||
nobody watches.
|
||||
"""
|
||||
pinned = os.environ.get(ADB_SERIAL_ENV, "").strip()
|
||||
serials = attached_serials()
|
||||
if pinned:
|
||||
if pinned in serials:
|
||||
return pinned
|
||||
_logger.warning(
|
||||
"%s=%s is set but that device is not attached (attached: %s)",
|
||||
ADB_SERIAL_ENV,
|
||||
pinned,
|
||||
", ".join(serials) or "none",
|
||||
)
|
||||
return None
|
||||
if not serials:
|
||||
return None
|
||||
if len(serials) > 1:
|
||||
_logger.warning(
|
||||
"%d devices attached (%s); set %s to choose one. Skipping the "
|
||||
"phone fallback rather than pulling from an arbitrary device.",
|
||||
len(serials),
|
||||
", ".join(serials),
|
||||
ADB_SERIAL_ENV,
|
||||
)
|
||||
return None
|
||||
return serials[0]
|
||||
return False
|
||||
states = [
|
||||
line.split("\t")[1].strip() for line in out.splitlines()[1:] if "\t" in line
|
||||
]
|
||||
return "device" in states
|
||||
|
||||
|
||||
def pull_from_phone(inbox: Path) -> list[Path]:
|
||||
@ -137,12 +81,11 @@ def pull_from_phone(inbox: Path) -> list[Path]:
|
||||
left alone; content-level deduplication happens later against the ledger,
|
||||
so a name collision here is not authoritative either way.
|
||||
"""
|
||||
serial = resolve_serial()
|
||||
if serial is None:
|
||||
_logger.info("no adb device selected; skipping phone fallback")
|
||||
if not phone_attached():
|
||||
_logger.info("no adb device attached; skipping phone fallback")
|
||||
return []
|
||||
|
||||
ok, out = _adb(["shell", "ls", PHONE_EXPORT_DIR], serial)
|
||||
ok, out = _adb(["shell", "ls", PHONE_EXPORT_DIR])
|
||||
if not ok:
|
||||
_logger.warning("could not list %s: %s", PHONE_EXPORT_DIR, out.strip())
|
||||
return []
|
||||
@ -159,7 +102,7 @@ def pull_from_phone(inbox: Path) -> list[Path]:
|
||||
if target.exists():
|
||||
continue
|
||||
staged = inbox / f".{name}.partial"
|
||||
ok, err = _adb(["pull", f"{PHONE_EXPORT_DIR}/{name}", str(staged)], serial)
|
||||
ok, err = _adb(["pull", f"{PHONE_EXPORT_DIR}/{name}", str(staged)])
|
||||
if not ok:
|
||||
_logger.warning("adb pull failed for %s: %s", name, err.strip())
|
||||
staged.unlink(missing_ok=True)
|
||||
|
||||
@ -1,71 +0,0 @@
|
||||
"""Shared fixtures for the endurain_import orchestration tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from python_pkg.endurain_import.upload import Result
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def inbox(tmp_path: Path) -> Path:
|
||||
path = tmp_path / "inbox"
|
||||
path.mkdir()
|
||||
return path
|
||||
|
||||
|
||||
def _file(inbox: Path, name: str = "RunnerUp_ts_Running.tcx") -> Path:
|
||||
path = inbox / name
|
||||
path.write_text("<xml/>")
|
||||
return path
|
||||
|
||||
|
||||
class _StubMainClient:
|
||||
"""Stands in for EndurainClient across a whole main() run."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
result: Result,
|
||||
*,
|
||||
reachable: bool = True,
|
||||
remote: list[datetime] | None = None,
|
||||
) -> None:
|
||||
self._result = result
|
||||
self._reachable = reachable
|
||||
self._remote = remote
|
||||
self.uploads = 0
|
||||
|
||||
def about(self) -> dict[str, object]:
|
||||
if not self._reachable:
|
||||
message = "connection refused"
|
||||
raise OSError(message)
|
||||
return {"version": "test"}
|
||||
|
||||
def recent_start_times(self, _user_id: int) -> list[datetime] | None:
|
||||
return self._remote
|
||||
|
||||
def upload(self, _path: Path) -> Result:
|
||||
self.uploads += 1
|
||||
return self._result
|
||||
|
||||
|
||||
def _env(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, inbox: Path, **extra: str
|
||||
) -> None:
|
||||
monkeypatch.setenv("ENDURAIN_API_KEY", "k")
|
||||
monkeypatch.setenv("ENDURAIN_INBOX", str(inbox))
|
||||
monkeypatch.setenv("ENDURAIN_STATE", str(tmp_path / "state"))
|
||||
monkeypatch.setenv("ENDURAIN_NO_ADB", "1")
|
||||
for key, value in extra.items():
|
||||
monkeypatch.setenv(key, value)
|
||||
|
||||
|
||||
def _patch_client(monkeypatch: pytest.MonkeyPatch, client: _StubMainClient) -> None:
|
||||
import python_pkg.endurain_import.__main__ as mod
|
||||
|
||||
monkeypatch.setattr(mod, "EndurainClient", lambda *_a, **_k: client)
|
||||
@ -1,119 +0,0 @@
|
||||
"""Which phone the adb fallback pulls from.
|
||||
|
||||
Ambiguity is settled by configuration, never by guessing: the old check
|
||||
returned true for ANY attached device, after which every call failed with
|
||||
"more than one device/emulator" as a warning on a path nobody watches.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.endurain_import import sources
|
||||
|
||||
|
||||
def _devices(*serials: str) -> str:
|
||||
body = "".join(f"{s}\tdevice\n" for s in serials)
|
||||
return f"List of devices attached\n{body}"
|
||||
|
||||
|
||||
def test_single_device_is_selected_without_configuration(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
monkeypatch.delenv(sources.ADB_SERIAL_ENV, raising=False)
|
||||
monkeypatch.setattr(sources, "_adb", lambda _a, _s=None: (True, _devices("ONE")))
|
||||
assert sources.resolve_serial() == "ONE"
|
||||
|
||||
|
||||
def test_no_devices_resolves_to_none(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.delenv(sources.ADB_SERIAL_ENV, raising=False)
|
||||
monkeypatch.setattr(sources, "_adb", lambda _a, _s=None: (True, _devices()))
|
||||
assert sources.resolve_serial() is None
|
||||
|
||||
|
||||
def test_several_devices_without_a_pin_is_refused(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""Two devices must not silently become 'adb picks whichever it likes'."""
|
||||
monkeypatch.delenv(sources.ADB_SERIAL_ENV, raising=False)
|
||||
monkeypatch.setattr(
|
||||
sources, "_adb", lambda _a, _s=None: (True, _devices("ONE", "TWO"))
|
||||
)
|
||||
assert sources.resolve_serial() is None
|
||||
|
||||
|
||||
def test_pinned_serial_wins_when_several_are_attached(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
monkeypatch.setenv(sources.ADB_SERIAL_ENV, "TWO")
|
||||
monkeypatch.setattr(
|
||||
sources, "_adb", lambda _a, _s=None: (True, _devices("ONE", "TWO"))
|
||||
)
|
||||
assert sources.resolve_serial() == "TWO"
|
||||
|
||||
|
||||
def test_pinned_serial_that_is_absent_resolves_to_none(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
monkeypatch.setenv(sources.ADB_SERIAL_ENV, "GONE")
|
||||
monkeypatch.setattr(sources, "_adb", lambda _a, _s=None: (True, _devices("ONE")))
|
||||
assert sources.resolve_serial() is None
|
||||
|
||||
|
||||
def test_blank_pin_falls_back_to_the_single_device(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
monkeypatch.setenv(sources.ADB_SERIAL_ENV, " ")
|
||||
monkeypatch.setattr(sources, "_adb", lambda _a, _s=None: (True, _devices("ONE")))
|
||||
assert sources.resolve_serial() == "ONE"
|
||||
|
||||
|
||||
def test_devices_output_without_tabs_is_ignored(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
monkeypatch.delenv(sources.ADB_SERIAL_ENV, raising=False)
|
||||
monkeypatch.setattr(
|
||||
sources,
|
||||
"_adb",
|
||||
lambda _a, _s=None: (True, "List of devices attached\n* daemon started *\n"),
|
||||
)
|
||||
assert sources.attached_serials() == []
|
||||
|
||||
|
||||
def test_serial_is_passed_to_every_adb_call(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
"""Without -s, a second attached device breaks every call with a warning."""
|
||||
seen: list[list[str]] = []
|
||||
|
||||
def _adb(args: list[str], serial: str | None = None) -> tuple[bool, str]:
|
||||
seen.append(["-s", serial or "", *args])
|
||||
if args[0] == "shell":
|
||||
return True, "RunnerUp_ts_Running.tcx\n"
|
||||
Path(args[2]).write_text("pulled")
|
||||
return True, ""
|
||||
|
||||
monkeypatch.setattr(sources, "resolve_serial", lambda: "PIXEL")
|
||||
monkeypatch.setattr(sources, "_adb", _adb)
|
||||
assert len(sources.pull_from_phone(tmp_path)) == 1
|
||||
assert all(call[1] == "PIXEL" for call in seen)
|
||||
|
||||
|
||||
def test_adb_builds_argv_with_the_serial(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
captured: dict[str, list[str]] = {}
|
||||
|
||||
class _Proc:
|
||||
returncode = 0
|
||||
stdout = "ok"
|
||||
stderr = ""
|
||||
|
||||
def _run(argv: list[str], **_kwargs: object) -> _Proc:
|
||||
captured["argv"] = argv
|
||||
return _Proc()
|
||||
|
||||
monkeypatch.setattr(subprocess, "run", _run)
|
||||
sources._adb(["shell", "ls"], "PIXEL")
|
||||
assert captured["argv"][1:4] == ["-s", "PIXEL", "shell"]
|
||||
@ -2,13 +2,11 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.endurain_import import ledger
|
||||
from python_pkg.endurain_import.ledger import (
|
||||
Entry,
|
||||
Ledger,
|
||||
@ -95,40 +93,3 @@ def test_non_dict_ledger_is_ignored(tmp_path: Path) -> None:
|
||||
path = tmp_path / "l.json"
|
||||
path.write_text("[]")
|
||||
assert len(Ledger(path)) == 0
|
||||
|
||||
|
||||
def test_activity_start_reads_local_wall_time() -> None:
|
||||
"""RunnerUp names exports in local time, so 00:58 is the previous day UTC."""
|
||||
parsed = ledger.activity_start(Path("RunnerUp_2026-08-14-00-58-45_Running.tcx"))
|
||||
assert parsed is not None
|
||||
assert parsed.tzinfo is not None
|
||||
expected = datetime(
|
||||
2026, 8, 14, 0, 58, 45, tzinfo=datetime.now().astimezone().tzinfo
|
||||
).astimezone(timezone.utc)
|
||||
assert parsed == expected
|
||||
|
||||
|
||||
def test_activity_start_ignores_the_device_model() -> None:
|
||||
plain = ledger.activity_start(Path("RunnerUp_2026-08-22-23-51-04_Running.tcx"))
|
||||
with_model = ledger.activity_start(
|
||||
Path("RunnerUp_Pixel_6a_2026-08-22-23-51-04_Running.gpx")
|
||||
)
|
||||
assert plain == with_model
|
||||
|
||||
|
||||
def test_activity_start_of_an_unparseable_name_is_none() -> None:
|
||||
assert ledger.activity_start(Path("whatever.tcx")) is None
|
||||
|
||||
|
||||
def test_activity_start_rejects_a_non_timestamp() -> None:
|
||||
assert ledger.activity_start(Path("RunnerUp_notatimestamp_Running.tcx")) is None
|
||||
|
||||
|
||||
def test_activity_start_rejects_an_impossible_date() -> None:
|
||||
assert (
|
||||
ledger.activity_start(Path("RunnerUp_2026-13-45-99-99-99_Running.tcx")) is None
|
||||
)
|
||||
|
||||
|
||||
def test_activity_start_rejects_wrong_field_count() -> None:
|
||||
assert ledger.activity_start(Path("RunnerUp_2026-08-22_Running.tcx")) is None
|
||||
|
||||
@ -7,15 +7,56 @@ from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from python_pkg.endurain_import.__main__ import _route_rejected, main
|
||||
from python_pkg.endurain_import.tests.conftest import (
|
||||
_env,
|
||||
_file,
|
||||
_patch_client,
|
||||
_StubMainClient,
|
||||
)
|
||||
from python_pkg.endurain_import.upload import Outcome, Result
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def inbox(tmp_path: Path) -> Path:
|
||||
path = tmp_path / "inbox"
|
||||
path.mkdir()
|
||||
return path
|
||||
|
||||
|
||||
def _file(inbox: Path, name: str = "RunnerUp_ts_Running.tcx") -> Path:
|
||||
path = inbox / name
|
||||
path.write_text("<xml/>")
|
||||
return path
|
||||
|
||||
|
||||
class _StubMainClient:
|
||||
"""Stands in for EndurainClient across a whole main() run."""
|
||||
|
||||
def __init__(self, result: Result, *, reachable: bool = True) -> None:
|
||||
self._result = result
|
||||
self._reachable = reachable
|
||||
|
||||
def about(self) -> dict[str, object]:
|
||||
if not self._reachable:
|
||||
message = "connection refused"
|
||||
raise OSError(message)
|
||||
return {"version": "test"}
|
||||
|
||||
def upload(self, _path: Path) -> Result:
|
||||
return self._result
|
||||
|
||||
|
||||
def _env(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, inbox: Path, **extra: str
|
||||
) -> None:
|
||||
monkeypatch.setenv("ENDURAIN_API_KEY", "k")
|
||||
monkeypatch.setenv("ENDURAIN_INBOX", str(inbox))
|
||||
monkeypatch.setenv("ENDURAIN_STATE", str(tmp_path / "state"))
|
||||
monkeypatch.setenv("ENDURAIN_NO_ADB", "1")
|
||||
for key, value in extra.items():
|
||||
monkeypatch.setenv(key, value)
|
||||
|
||||
|
||||
def _patch_client(monkeypatch: pytest.MonkeyPatch, client: _StubMainClient) -> None:
|
||||
import python_pkg.endurain_import.__main__ as mod
|
||||
|
||||
monkeypatch.setattr(mod, "EndurainClient", lambda *_a, **_k: client)
|
||||
|
||||
|
||||
def test_main_returns_one_when_unreachable(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, inbox: Path
|
||||
) -> None:
|
||||
|
||||
@ -1,111 +0,0 @@
|
||||
"""Skipping runs Endurain already holds.
|
||||
|
||||
RunnerUp's own uploader writes straight to the server and leaves no ledger
|
||||
trace, so the server is the only place these runs are visible.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.endurain_import.__main__ import main
|
||||
from python_pkg.endurain_import.tests.conftest import (
|
||||
_env,
|
||||
_file,
|
||||
_patch_client,
|
||||
_StubMainClient,
|
||||
)
|
||||
from python_pkg.endurain_import.upload import Outcome, Result
|
||||
|
||||
# The name encodes 23:51:04 LOCAL time; the UTC instant depends on the zone,
|
||||
# so these derive it the same way production does rather than hardcoding it.
|
||||
_RUN_NAME = "RunnerUp_2026-08-22-23-51-04_Running.tcx"
|
||||
|
||||
|
||||
def _run_start() -> datetime:
|
||||
return datetime(
|
||||
2026, 8, 22, 23, 51, 4, tzinfo=datetime.now().astimezone().tzinfo
|
||||
).astimezone(timezone.utc)
|
||||
|
||||
|
||||
def test_run_already_in_endurain_is_skipped_not_reuploaded(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, inbox: Path
|
||||
) -> None:
|
||||
"""RunnerUp's own uploader leaves no ledger trace; only the server knows."""
|
||||
_env(monkeypatch, tmp_path, inbox)
|
||||
_file(inbox, _RUN_NAME)
|
||||
client = _StubMainClient(Result(Outcome.OK, 1, "ok"), remote=[_run_start()])
|
||||
_patch_client(monkeypatch, client)
|
||||
assert main() == 0
|
||||
assert client.uploads == 0
|
||||
assert (inbox / "processed" / _RUN_NAME).exists()
|
||||
|
||||
|
||||
def test_remote_skip_is_recorded_so_the_next_run_needs_no_query(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, inbox: Path
|
||||
) -> None:
|
||||
_env(monkeypatch, tmp_path, inbox)
|
||||
_file(inbox, _RUN_NAME)
|
||||
_patch_client(
|
||||
monkeypatch,
|
||||
_StubMainClient(Result(Outcome.OK, 1, "ok"), remote=[_run_start()]),
|
||||
)
|
||||
assert main() == 0
|
||||
assert _RUN_NAME in (tmp_path / "state" / "ledger.json").read_text()
|
||||
|
||||
|
||||
def test_a_genuinely_new_run_still_uploads(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, inbox: Path
|
||||
) -> None:
|
||||
"""The remote check must not become a blanket refusal to upload."""
|
||||
_env(monkeypatch, tmp_path, inbox)
|
||||
_file(inbox, _RUN_NAME)
|
||||
other = datetime(2026, 1, 1, tzinfo=timezone.utc)
|
||||
client = _StubMainClient(Result(Outcome.OK, 7, "ok"), remote=[other])
|
||||
_patch_client(monkeypatch, client)
|
||||
assert main() == 0
|
||||
assert client.uploads == 1
|
||||
|
||||
|
||||
def test_unavailable_query_falls_back_to_the_ledger(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, inbox: Path
|
||||
) -> None:
|
||||
"""A failed lookup must not read as 'nothing exists' -- nor block imports."""
|
||||
_env(monkeypatch, tmp_path, inbox)
|
||||
_file(inbox, _RUN_NAME)
|
||||
client = _StubMainClient(Result(Outcome.OK, 1, "ok"), remote=None)
|
||||
_patch_client(monkeypatch, client)
|
||||
assert main() == 0
|
||||
assert client.uploads == 1
|
||||
|
||||
|
||||
def test_unparseable_filename_falls_back_to_the_ledger(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, inbox: Path
|
||||
) -> None:
|
||||
"""No timestamp in the name means the remote check cannot apply."""
|
||||
_env(monkeypatch, tmp_path, inbox)
|
||||
_file(inbox, "mystery.tcx")
|
||||
client = _StubMainClient(Result(Outcome.OK, 1, "ok"), remote=[_run_start()])
|
||||
_patch_client(monkeypatch, client)
|
||||
assert main() == 0
|
||||
assert client.uploads == 1
|
||||
|
||||
|
||||
def test_user_id_is_configurable(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, inbox: Path
|
||||
) -> None:
|
||||
_env(monkeypatch, tmp_path, inbox, ENDURAIN_USER_ID="7")
|
||||
_file(inbox, _RUN_NAME)
|
||||
seen: list[int] = []
|
||||
|
||||
class _Recording(_StubMainClient):
|
||||
def recent_start_times(self, user_id: int) -> list[datetime] | None:
|
||||
seen.append(user_id)
|
||||
return []
|
||||
|
||||
_patch_client(monkeypatch, _Recording(Result(Outcome.OK, 1, "ok")))
|
||||
assert main() == 0
|
||||
assert seen == [7]
|
||||
@ -1,139 +0,0 @@
|
||||
"""Asking Endurain what it already holds.
|
||||
|
||||
A failed lookup must return None, never an empty list: read as "nothing
|
||||
matches" it would upload a duplicate on every transport hiccup.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from python_pkg.endurain_import import upload
|
||||
|
||||
|
||||
class _Resp:
|
||||
def __init__(self, status: int, payload: object, *, bad_json: bool = False) -> None:
|
||||
self.status_code = status
|
||||
self._payload = payload
|
||||
self._bad_json = bad_json
|
||||
|
||||
def json(self) -> object:
|
||||
if self._bad_json:
|
||||
message = "not json"
|
||||
raise ValueError(message)
|
||||
return self._payload
|
||||
|
||||
|
||||
def _client_with_get(
|
||||
monkeypatch: pytest.MonkeyPatch, result: object
|
||||
) -> upload.EndurainClient:
|
||||
client = upload.EndurainClient("http://x", "k")
|
||||
|
||||
def _get(*_a: object, **_k: object) -> object:
|
||||
if isinstance(result, Exception):
|
||||
raise result
|
||||
return result
|
||||
|
||||
monkeypatch.setattr(client._session, "get", _get)
|
||||
return client
|
||||
|
||||
|
||||
def test_recent_start_times_parses_offsets(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
client = _client_with_get(
|
||||
monkeypatch,
|
||||
_Resp(200, [{"start_time": "2026-08-22T23:51:05+02:00"}]),
|
||||
)
|
||||
times = client.recent_start_times(1)
|
||||
assert times is not None
|
||||
assert times[0] == datetime(2026, 8, 22, 21, 51, 5, tzinfo=timezone.utc)
|
||||
|
||||
|
||||
def test_recent_start_times_treats_naive_as_utc(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
client = _client_with_get(
|
||||
monkeypatch, _Resp(200, [{"start_time": "2026-08-22T21:51:05"}])
|
||||
)
|
||||
times = client.recent_start_times(1)
|
||||
assert times == [datetime(2026, 8, 22, 21, 51, 5, tzinfo=timezone.utc)]
|
||||
|
||||
|
||||
def test_recent_start_times_accepts_zulu(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
client = _client_with_get(
|
||||
monkeypatch, _Resp(200, [{"start_time": "2026-08-22T21:51:05Z"}])
|
||||
)
|
||||
times = client.recent_start_times(1)
|
||||
assert times == [datetime(2026, 8, 22, 21, 51, 5, tzinfo=timezone.utc)]
|
||||
|
||||
|
||||
def test_unparseable_entries_are_dropped_not_fatal(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
client = _client_with_get(
|
||||
monkeypatch,
|
||||
_Resp(
|
||||
200,
|
||||
[
|
||||
{"start_time": "nonsense"},
|
||||
{"start_time": None},
|
||||
{"start_time": ""},
|
||||
{"no_start_time": 1},
|
||||
"not-a-dict",
|
||||
{"start_time": "2026-08-22T21:51:05Z"},
|
||||
],
|
||||
),
|
||||
)
|
||||
assert client.recent_start_times(1) == [
|
||||
datetime(2026, 8, 22, 21, 51, 5, tzinfo=timezone.utc)
|
||||
]
|
||||
|
||||
|
||||
def test_auth_failure_is_unknown_not_empty(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""401 must not read as 'no activities exist' -- that would duplicate."""
|
||||
client = _client_with_get(monkeypatch, _Resp(401, None))
|
||||
assert client.recent_start_times(1) is None
|
||||
|
||||
|
||||
def test_transport_failure_is_unknown(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
client = _client_with_get(monkeypatch, requests.ConnectionError("down"))
|
||||
assert client.recent_start_times(1) is None
|
||||
|
||||
|
||||
def test_non_json_body_is_unknown(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
client = _client_with_get(monkeypatch, _Resp(200, None, bad_json=True))
|
||||
assert client.recent_start_times(1) is None
|
||||
|
||||
|
||||
def test_non_list_body_is_unknown(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
client = _client_with_get(monkeypatch, _Resp(200, {"detail": "nope"}))
|
||||
assert client.recent_start_times(1) is None
|
||||
|
||||
|
||||
def test_already_present_tolerates_recording_skew() -> None:
|
||||
"""The file said 21:51:04Z; Endurain stored 21:51:05Z. Same run."""
|
||||
start = datetime(2026, 8, 22, 21, 51, 4, tzinfo=timezone.utc)
|
||||
known = [datetime(2026, 8, 22, 21, 51, 5, tzinfo=timezone.utc)]
|
||||
assert upload.already_present(start, known)
|
||||
|
||||
|
||||
def test_already_present_rejects_a_different_run() -> None:
|
||||
start = datetime(2026, 8, 22, 21, 51, 4, tzinfo=timezone.utc)
|
||||
known = [datetime(2026, 8, 22, 19, 0, 0, tzinfo=timezone.utc)]
|
||||
assert not upload.already_present(start, known)
|
||||
|
||||
|
||||
def test_tolerance_boundary_is_inclusive() -> None:
|
||||
start = datetime(2026, 8, 22, 21, 51, 4, tzinfo=timezone.utc)
|
||||
inside = [datetime(2026, 8, 22, 21, 53, 4, tzinfo=timezone.utc)]
|
||||
outside = [datetime(2026, 8, 22, 21, 53, 5, tzinfo=timezone.utc)]
|
||||
assert upload.already_present(start, inside)
|
||||
assert not upload.already_present(start, outside)
|
||||
|
||||
|
||||
def test_already_present_against_nothing_is_false() -> None:
|
||||
assert not upload.already_present(
|
||||
datetime(2026, 8, 22, 21, 51, 4, tzinfo=timezone.utc), []
|
||||
)
|
||||
@ -49,42 +49,40 @@ def test_inbox_is_ordered_oldest_first(tmp_path: Path) -> None:
|
||||
]
|
||||
|
||||
|
||||
def test_attached_serials_parses_adb_devices(
|
||||
def test_phone_attached_parses_adb_devices(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
monkeypatch.setattr(
|
||||
sources,
|
||||
"_adb",
|
||||
lambda _a, _s=None: (True, "List of devices attached\nABC123\tdevice\n"),
|
||||
lambda _a: (True, "List of devices attached\nABC123\tdevice\n"),
|
||||
)
|
||||
assert sources.attached_serials() == ["ABC123"]
|
||||
assert sources.phone_attached()
|
||||
|
||||
|
||||
def test_unauthorised_device_is_not_listed(
|
||||
def test_phone_unauthorised_is_not_attached(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
monkeypatch.setattr(
|
||||
sources,
|
||||
"_adb",
|
||||
lambda _a, _s=None: (True, "List of devices attached\nABC123\tunauthorized\n"),
|
||||
lambda _a: (True, "List of devices attached\nABC123\tunauthorized\n"),
|
||||
)
|
||||
assert sources.attached_serials() == []
|
||||
assert not sources.phone_attached()
|
||||
|
||||
|
||||
def test_pull_skips_when_no_device(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
monkeypatch.setattr(sources, "resolve_serial", lambda: None)
|
||||
monkeypatch.setattr(sources, "phone_attached", lambda: False)
|
||||
assert sources.pull_from_phone(tmp_path) == []
|
||||
|
||||
|
||||
def test_pull_ignores_already_present_files(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
monkeypatch.setattr(sources, "resolve_serial", lambda: "ABC123")
|
||||
monkeypatch.setattr(
|
||||
sources, "_adb", lambda _a, _s=None: (True, "RunnerUp_ts_Running.tcx\n")
|
||||
)
|
||||
monkeypatch.setattr(sources, "phone_attached", lambda: True)
|
||||
monkeypatch.setattr(sources, "_adb", lambda _a: (True, "RunnerUp_ts_Running.tcx\n"))
|
||||
(tmp_path / "RunnerUp_ts_Running.tcx").write_text("already here")
|
||||
assert sources.pull_from_phone(tmp_path) == []
|
||||
|
||||
@ -93,9 +91,9 @@ def test_failed_pull_leaves_no_partial_file(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
"""A half-transferred file must never look like a complete activity."""
|
||||
monkeypatch.setattr(sources, "resolve_serial", lambda: "ABC123")
|
||||
monkeypatch.setattr(sources, "phone_attached", lambda: True)
|
||||
|
||||
def _adb(args: list[str], _serial: str | None = None) -> tuple[bool, str]:
|
||||
def _adb(args: list[str]) -> tuple[bool, str]:
|
||||
if args[0] == "shell":
|
||||
return True, "RunnerUp_ts_Running.tcx\n"
|
||||
return False, "pull failed"
|
||||
@ -139,27 +137,27 @@ def test_adb_returns_output_on_success(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
assert out == "out"
|
||||
|
||||
|
||||
def test_no_serials_when_adb_fails(
|
||||
def test_phone_attached_false_when_adb_fails(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
monkeypatch.setattr(sources, "_adb", lambda _a, _s=None: (False, "boom"))
|
||||
assert sources.attached_serials() == []
|
||||
monkeypatch.setattr(sources, "_adb", lambda _a: (False, "boom"))
|
||||
assert not sources.phone_attached()
|
||||
|
||||
|
||||
def test_pull_reports_unlistable_directory(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
monkeypatch.setattr(sources, "resolve_serial", lambda: "ABC123")
|
||||
monkeypatch.setattr(sources, "_adb", lambda _a, _s=None: (False, "no such dir"))
|
||||
monkeypatch.setattr(sources, "phone_attached", lambda: True)
|
||||
monkeypatch.setattr(sources, "_adb", lambda _a: (False, "no such dir"))
|
||||
assert sources.pull_from_phone(tmp_path) == []
|
||||
|
||||
|
||||
def test_successful_pull_moves_into_place(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
monkeypatch.setattr(sources, "resolve_serial", lambda: "ABC123")
|
||||
monkeypatch.setattr(sources, "phone_attached", lambda: True)
|
||||
|
||||
def _adb(args: list[str], _serial: str | None = None) -> tuple[bool, str]:
|
||||
def _adb(args: list[str]) -> tuple[bool, str]:
|
||||
if args[0] == "shell":
|
||||
return True, "RunnerUp_ts_Running.tcx\nnotes.txt\n"
|
||||
Path(args[2]).write_text("pulled")
|
||||
|
||||
@ -14,7 +14,6 @@ rejected" and "might have been committed" decides whether a retry is safe:
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from enum import Enum
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Any, Protocol
|
||||
@ -27,15 +26,6 @@ if TYPE_CHECKING:
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
UPLOAD_PATH = "/api/v1/activities/create/upload"
|
||||
# Endurain exposes no "does this run exist" query, so existence is decided by
|
||||
# fetching a recent page and comparing start times client-side.
|
||||
RECENT_PATH = "/api/v1/activities/user/{user_id}/page_number/1/num_records/{n}"
|
||||
_RECENT_RECORDS = 50
|
||||
# Start times are compared with a tolerance because the recorded value is not
|
||||
# the one in the file: a run whose export embeds 21:51:04Z was stored by
|
||||
# Endurain as 21:51:05Z. Two genuinely distinct runs starting inside two
|
||||
# minutes of each other is not a real scenario, so the window is generous.
|
||||
_START_TOLERANCE_SECONDS = 120
|
||||
# The API key goes in X-API-Key. Endurain's own OpenAPI schema declares the
|
||||
# APIKeyHeader security scheme as name "X-Client-Type", which is wrong --
|
||||
# verified against the running server: X-API-Key with a bad key returns
|
||||
@ -58,10 +48,6 @@ class SupportsUpload(Protocol):
|
||||
"""Upload one activity file and report what happened."""
|
||||
... # pragma: no cover - structural typing only, never executed
|
||||
|
||||
def recent_start_times(self, user_id: int) -> list[datetime] | None:
|
||||
"""Return recent activity start times, or None if unknowable."""
|
||||
... # pragma: no cover - structural typing only, never executed
|
||||
|
||||
|
||||
class Outcome(Enum):
|
||||
"""What happened to one upload attempt."""
|
||||
@ -96,42 +82,6 @@ class EndurainClient:
|
||||
body: dict[str, Any] = resp.json()
|
||||
return body
|
||||
|
||||
def recent_start_times(self, user_id: int) -> list[datetime] | None:
|
||||
"""Return start times of recent activities, or None if unknowable.
|
||||
|
||||
None means "the question could not be answered" -- a transport failure,
|
||||
an auth failure, or a body that did not parse. It is deliberately not
|
||||
an empty list: callers must not read a failed lookup as "no matching
|
||||
activity exists" and upload on the strength of it.
|
||||
"""
|
||||
url = f"{self._base}{RECENT_PATH}".format(user_id=user_id, n=_RECENT_RECORDS)
|
||||
try:
|
||||
resp = self._session.get(url, timeout=30)
|
||||
except requests.RequestException as exc:
|
||||
_logger.warning("could not list recent activities: %s", exc)
|
||||
return None
|
||||
if resp.status_code >= _HTTP_BAD_REQUEST:
|
||||
_logger.warning(
|
||||
"could not list recent activities: %s (the API key needs the "
|
||||
"activities:read scope for duplicate detection)",
|
||||
resp.status_code,
|
||||
)
|
||||
return None
|
||||
try:
|
||||
body = resp.json()
|
||||
except ValueError:
|
||||
_logger.warning("recent activities response was not JSON")
|
||||
return None
|
||||
if not isinstance(body, list):
|
||||
_logger.warning("recent activities response was not a list")
|
||||
return None
|
||||
return [
|
||||
parsed
|
||||
for item in body
|
||||
if isinstance(item, dict)
|
||||
and (parsed := _parse_start(item.get("start_time"))) is not None
|
||||
]
|
||||
|
||||
def upload(self, path: Path) -> Result:
|
||||
"""Upload one activity file."""
|
||||
try:
|
||||
@ -170,26 +120,3 @@ def _activity_id(resp: requests.Response) -> int | None:
|
||||
if isinstance(value, int):
|
||||
return value
|
||||
return None
|
||||
|
||||
|
||||
def _parse_start(raw: object) -> datetime | None:
|
||||
"""Parse an Endurain start_time into an aware UTC datetime."""
|
||||
if not isinstance(raw, str) or not raw:
|
||||
return None
|
||||
try:
|
||||
parsed = datetime.fromisoformat(raw.replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
return None
|
||||
# Endurain returns local-offset timestamps; a naive value is read as UTC
|
||||
# so the comparison below never comes down to the reader's timezone.
|
||||
if parsed.tzinfo is None:
|
||||
parsed = parsed.replace(tzinfo=timezone.utc)
|
||||
return parsed.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def already_present(start: datetime, known: list[datetime]) -> bool:
|
||||
"""True when ``start`` matches a known activity within the tolerance."""
|
||||
return any(
|
||||
abs((start - other).total_seconds()) <= _START_TOLERANCE_SECONDS
|
||||
for other in known
|
||||
)
|
||||
|
||||
Loading…
Reference in New Issue
Block a user