mirror of
https://github.com/kuhyx/testsAndMisc.git
synced 2026-11-24 12:26:18 +01:00
Compare commits
8 Commits
325d5a8baa
...
5ba2cbd476
| Author | SHA1 | Date | |
|---|---|---|---|
| 5ba2cbd476 | |||
| 8ab15446fd | |||
| 0b6df7b003 | |||
| 04cc5fa23e | |||
| 76b1d74388 | |||
| 7540512875 | |||
| 58b4cef85a | |||
| ff3ea99a16 |
@ -0,0 +1,21 @@
|
||||
{
|
||||
"title": "Scope the pre-push CI mirror to the push range, and make its pytest stage actually run",
|
||||
"objective": "Take `git push` from ~130s to seconds by checking what the push changed rather than the whole tree, while repairing the python test stage, which returned success without executing a single test.",
|
||||
"acceptance_criteria": [
|
||||
"ci_mirror.sh passes the changed paths to pytest_changed_packages.py, so the stage runs the suite instead of short-circuiting on empty argv.",
|
||||
"A push whose range contains a failing python test is refused with exit 1.",
|
||||
"A push whose range touches a lib/tests suite with a failing assertion is refused with exit 1, and the suite fails bare first so the gate is not the only evidence.",
|
||||
"The green-tree cache is NOT written when the gate fails, so a red run cannot poison the short-circuit.",
|
||||
"An unknown range, or a change to .pre-commit-config.yaml / meta/scripts/ / requirements.txt / .githooks/, forces a full --all-files sweep.",
|
||||
"A change under scripts/lib/ or to a suite's lib_test_core.sh / lib_test_path.sh selects every lib/tests suite, not just the enclosing one.",
|
||||
"Repo-wide hooks (file-length-cap --all, no-binaries, check-python-location) still run on every push.",
|
||||
"No test is weakened or deleted, no --no-verify is added to any script, and pre-commit's own 4.8s commit-stage run is untouched.",
|
||||
"All three scripts are shellcheck-clean, shfmt-clean and within the 250-line cap."
|
||||
],
|
||||
"out_of_scope": [
|
||||
"Moving ci-mirror off pre-push (option 4 in the handoff): the user chose to keep the guarantee that a red push cannot reach GitHub.",
|
||||
"Changing the coverage bar or the jail instrument.",
|
||||
"Touching the pre-commit hook stage, already measured at 4.8s."
|
||||
],
|
||||
"verifier": "With PRE_COMMIT_FROM_REF/PRE_COMMIT_TO_REF pinned to a probe commit: `bash meta/scripts/ci_mirror.sh` exits 0 on a green range and 1 on a range containing a deliberately broken python assertion or shell assertion; `time` on a docs-only, python and shell range reports 7.6s / 25.3s / 43.6s against a ~130s baseline; `shellcheck -x`, `shfmt -l` and `check_file_length.sh --all` are clean."
|
||||
}
|
||||
@ -0,0 +1,19 @@
|
||||
{
|
||||
"title": "endurain importer dedupe via postgres",
|
||||
"objective": "Give the importer a working answer to 'does Endurain already hold this run?', now that the HTTP route cannot provide one: API keys are upload-only and the activities read endpoint is JWT-only, so the existing check always returned None and every pass relied on the local ledger alone.",
|
||||
"acceptance_criteria": [
|
||||
"A run Endurain already holds is skipped even when the local ledger is empty, and the activity count does not grow.",
|
||||
"The same run IS imported when the fallback is disabled, proving the check is what blocks it.",
|
||||
"A dead or renamed container yields None (ledger fallback), while a user with no activities yields an empty list; the two are never conflated.",
|
||||
"The journal distinguishes which backend answered, so a DB-sourced pass is not mistaken for a ledger-only one.",
|
||||
"Verified in the real systemd unit, not only from an interactive shell.",
|
||||
"100% branch coverage on the new and changed modules, with no lint suppressions added.",
|
||||
"No test touches the real postgres container."
|
||||
],
|
||||
"out_of_scope": [
|
||||
"Removing or replacing the HTTP lookup - it stays first in the chain so the supported path resumes working by itself if Endurain widens the API-key scope allow-list.",
|
||||
"Exposing a postgres host port or adding a database driver dependency.",
|
||||
"Patching Endurain's own source or forging scopes in users_api_keys to work around the upload-only allow-list."
|
||||
],
|
||||
"verifier": "pre-commit + python_pkg/endurain_import/tests + a real systemctl --user run with journal inspection"
|
||||
}
|
||||
@ -0,0 +1,30 @@
|
||||
{
|
||||
"intent": "Make test_passes_store_and_repo_root pass in any checkout, not only one whose directory happens to be named 'testsAndMisc'.",
|
||||
"scope": [
|
||||
"python_pkg/archwiki_rag/tests/test_reindex.py",
|
||||
"Non-goal: changing reindex.py production behaviour"
|
||||
],
|
||||
"changes": [
|
||||
"Replaced the hardcoded assertion env['PYTHONPATH'].endswith('testsAndMisc') with an exact comparison against the repo root the code itself computes, Path(reindex.__file__).resolve().parents[2].",
|
||||
"The assertion is strengthened, not weakened: exact equality replaces a suffix match."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "python -m pytest python_pkg/archwiki_rag/tests/test_reindex.py -q",
|
||||
"result": "pass",
|
||||
"evidence": "19 passed, run both in /home/kuhy/testsAndMisc and in a worktree at /tmp/meas-gIJ1/co"
|
||||
},
|
||||
{
|
||||
"command": "python meta/scripts/pytest_changed_packages.py <paths> in a clean worktree",
|
||||
"result": "pass",
|
||||
"evidence": "2101 passed, TOTAL coverage 100.00% (7082 stmts, 1742 branches, 0 missing)"
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"None material: the test now asserts against the same expression the source uses, so a genuine PYTHONPATH regression still fails it."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit",
|
||||
"Re-run the archwiki_rag test module; it will pass again in ~/testsAndMisc but resume failing in any differently-named checkout"
|
||||
]
|
||||
}
|
||||
@ -0,0 +1,47 @@
|
||||
{
|
||||
"intent": "Cut the pre-push gate from ~130s to seconds by checking the push range instead of the whole tree, and make the pytest stage actually run -- it had been silently executing zero tests on every push.",
|
||||
"scope": [
|
||||
"meta/scripts/ci_mirror.sh",
|
||||
"meta/scripts/ci_mirror_range.sh (new)",
|
||||
"meta/scripts/ci_mirror_shell.sh (new, split for the 250-line cap)",
|
||||
"Non-goal: weakening any check. The guarantee that a red push cannot reach GitHub is preserved."
|
||||
],
|
||||
"changes": [
|
||||
"FIX: ci_mirror.sh invoked pytest_changed_packages.py with no arguments; that script returns 0 on empty argv, so the pre-push python stage ran zero tests and reported success. It is now passed the changed paths and genuinely runs.",
|
||||
"Scope pre-commit to the push range via PRE_COMMIT_FROM_REF/PRE_COMMIT_TO_REF, which the pre-push hook already resolves from the refs git supplies. Repo-wide hooks (file-length-cap --all, no-binaries, check-python-location) are always_run in the config and still sweep the tree.",
|
||||
"Force a full sweep when the range is unknown or when the gate's own machinery changed (.pre-commit-config.yaml, meta/scripts/, requirements.txt, .githooks/).",
|
||||
"Run only the lib/tests suites whose tree the push touched; a change under scripts/lib/ or a suite's lib_test_core.sh/lib_test_path.sh fans out to all suites.",
|
||||
"Run pre-commit and pytest concurrently; keep the shell/jail gate serial to avoid the CPU-contention false failures documented in the handoff.",
|
||||
"Short-circuit on a tree hash matching the last green run, recorded in .ci-mirror-venv/ (already gitignored, so invisible to git status and jail fingerprints)."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "PRE_COMMIT_FROM_REF/TO_REF set; time bash meta/scripts/ci_mirror.sh",
|
||||
"result": "pass",
|
||||
"evidence": "docs-only push 7.6s; python push 25.3s (now including a 22s pytest stage that never previously ran); single shell suite 43.6s; all-suites widening 52s; unchanged-tree re-push 0.005s. Baseline was ~130s."
|
||||
},
|
||||
{
|
||||
"command": "Deliberately broke a python assertion, committed, ran the gate",
|
||||
"result": "pass",
|
||||
"evidence": "Gate exit 1, reported the failing test, and did NOT write the green-tree cache. Reverted."
|
||||
},
|
||||
{
|
||||
"command": "Deliberately broke _t_eq in utils/lib/tests/test_study_doc_lookup.sh at a pinned range",
|
||||
"result": "pass",
|
||||
"evidence": "Suite failed bare (exit 1) first; gate then exit 1 with 'lib/tests suite failed: .../utils/lib/tests/run_all.sh'. Reverted."
|
||||
},
|
||||
{
|
||||
"command": "shellcheck -x and shfmt -l on all three scripts; check_file_length.sh --all",
|
||||
"result": "pass",
|
||||
"evidence": "shellcheck clean, shfmt clean, all files within the 250-line cap (232/78/119)."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"Scoping means a hook no longer re-checks files outside the push range. Mitigated by the gate-widening rule and by keeping repo-wide hooks always_run.",
|
||||
"The green-tree cache could mask a gate change; mitigated because the cache key is the whole-repo tree hash, so any gate edit invalidates it."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit; ci_mirror.sh returns to --all-files on every push (~130s) and the pytest stage returns to silently running nothing.",
|
||||
"Delete .ci-mirror-venv/.last-green-tree if a stale cache is ever suspected."
|
||||
]
|
||||
}
|
||||
61
docs/superpowers/evidence/endurain-db-dedupe-2026-08-23.json
Normal file
61
docs/superpowers/evidence/endurain-db-dedupe-2026-08-23.json
Normal file
@ -0,0 +1,61 @@
|
||||
{
|
||||
"intent": "Stop the importer re-uploading runs RunnerUp already sent to Endurain, by reading start times from postgres when the HTTP API cannot answer. Endurain API keys are upload-only (scope allow-list is frozenset({'activities:upload'}) and the activities read route is mounted JWT-only), so the existing HTTP dedupe check could never succeed and every pass fell back to the local ledger alone.",
|
||||
"scope": [
|
||||
"python_pkg/endurain_import/db_lookup.py (new): postgres reader + known_start_times orchestration",
|
||||
"python_pkg/endurain_import/__main__.py: delegates dedupe to known_start_times; new env vars documented",
|
||||
"python_pkg/endurain_import/upload.py: 401 warning reworded, it is no longer the end of the story",
|
||||
"python_pkg/endurain_import/tests/: new test_db_lookup.py, two DB-fallback cases, conftest isolation",
|
||||
"Non-goal: removing the HTTP path. It is tried first so the supported route starts working by itself if Endurain ever widens the scope allow-list.",
|
||||
"Non-goal: exposing a postgres host port or adding a psycopg dependency. Reads go through docker exec, which is how the container is already reachable."
|
||||
],
|
||||
"changes": [
|
||||
"EndurainDatabase.recent_start_times shells out to `docker exec -i <container> psql -At` and parses one timestamp per line, reusing upload._parse_start so both backends normalise to UTC identically.",
|
||||
"The query is fed on stdin with -v bindings (uid/lim) rather than -c, because psql only substitutes -v variables in scripts it reads; user_id never reaches the SQL string. ON_ERROR_STOP=1 makes a SQL error a non-zero exit rather than silently empty output.",
|
||||
"None vs [] is the load-bearing distinction: a dead container, OSError, timeout or non-zero exit yields None ('could not ask', fall back to the ledger), while an empty result set yields [] ('this user has no activities'). Conflating them would re-upload everything on any docker hiccup.",
|
||||
"known_start_times chains HTTP -> postgres -> None and logs which backend answered, so a DB-sourced pass is distinguishable from a ledger-only one in the journal.",
|
||||
"The subprocess runner is injected (default _run) so every failure branch is reachable in unit tests without monkeypatching subprocess globally.",
|
||||
"conftest._env sets ENDURAIN_NO_DB=1 by default so no test can shell out to the real postgres container; the two tests that exercise the fallback opt in and stub EndurainDatabase."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "systemctl --user start endurain-import.service && journalctl --user -u endurain-import.service",
|
||||
"result": "pass",
|
||||
"evidence": "pulled 5 file(s) from the phone / could not list recent activities over HTTP: 401 / duplicate detection: 4 activity start time(s) via the database / done: 0 imported, 5 already known, 0 rejected, 0 ambiguous. Confirms the fallback answers in the real systemd deployment path, not just an interactive shell."
|
||||
},
|
||||
{
|
||||
"command": "ENDURAIN_INBOX=<tmp> ENDURAIN_STATE=<empty> python -m python_pkg.endurain_import (known-duplicate TCX, empty ledger)",
|
||||
"result": "pass",
|
||||
"evidence": "'RunnerUp_2026-08-22-23-51-04_Running.tcx is already in Endurain (uploaded outside this importer); moved to processed/', activities count stayed at 4. With an empty ledger only the DB check could have caught this, so it proves the feature rather than the ledger."
|
||||
},
|
||||
{
|
||||
"command": "same run with ENDURAIN_NO_DB=1 (negative control)",
|
||||
"result": "pass",
|
||||
"evidence": "'imported RunnerUp_2026-08-22-23-51-04_Running.tcx' - the same file WAS uploaded with the fallback disabled, proving the DB check is what blocked it. The duplicate this created (activity id 16) was deleted afterwards; activities is back to 4 rows with 0 duplicate start_times."
|
||||
},
|
||||
{
|
||||
"command": "python -m pytest python_pkg/endurain_import/tests/ --cov=python_pkg.endurain_import",
|
||||
"result": "pass",
|
||||
"evidence": "98 passed. db_lookup.py 52 stmts 0 miss 8 branch 0 partial 100%; __main__.py 91 stmts 0 miss 18 branch 0 partial 100%."
|
||||
},
|
||||
{
|
||||
"command": "pre-commit run --files <changed files>",
|
||||
"result": "pass",
|
||||
"evidence": "ruff, ruff format, mypy, pylint, bandit, codespell, 250-line cap and pytest-coverage all pass. No noqa/type-ignore/nosec suppressions were added; the three the first draft carried were removed by fixing the underlying typing instead."
|
||||
},
|
||||
{
|
||||
"command": "systemd-run --user --wait docker exec endurain-postgres psql ...",
|
||||
"result": "pass",
|
||||
"evidence": "exit 0 with rows returned, checked BEFORE writing the module: docker access works from the systemd user manager, not only from an interactive shell."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"Couples the importer to the postgres container name and to docker exec being available to the systemd user manager. Both are verified above; a change to either degrades to None and the ledger, which is the pre-existing behaviour, not a new failure.",
|
||||
"Reads Endurain's schema directly, so an upstream rename of activities.start_time or activities.user_id would break the fallback. It fails closed (non-zero exit -> None -> ledger), so the failure mode is 'no extra dedupe', never a wrong answer.",
|
||||
"The importer's postgres access is read-only by construction (a single SELECT), but it does run as a superuser inside the container; nothing constrains it beyond the statement itself."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit. __main__.py returns to calling client.recent_start_times directly and db_lookup.py disappears.",
|
||||
"Or set ENDURAIN_NO_DB=1 in the unit for a no-deploy disable, which restores ledger-only dedupe without touching code.",
|
||||
"After either, run the service and confirm 'duplicate detection ... falling back to the local ledger only' plus a clean 'done:' line, and check `SELECT start_time, count(*) FROM activities GROUP BY start_time HAVING count(*)>1` still returns no rows."
|
||||
]
|
||||
}
|
||||
@ -13,6 +13,9 @@ Environment=ENDURAIN_URL=http://127.0.0.1:8085
|
||||
Environment=ENDURAIN_INBOX=/home/kuhy/cloud/RunnerUp
|
||||
Environment=ENDURAIN_STATE=/home/kuhy/.local/state/endurain-import
|
||||
Environment=ENDURAIN_BULK_DIR=/var/opt/endurain/backend/data/activity_files/bulk_import
|
||||
# Two adb devices are usually attached (USB phone + a network target), and the
|
||||
# importer refuses to guess between them. Pin the phone explicitly.
|
||||
Environment=ENDURAIN_ADB_SERIAL=23181JEGR08034
|
||||
# The API key is read from a mode-600 file rather than embedded here: systemd
|
||||
# unit files are world-readable.
|
||||
ExecStart=/usr/bin/bash -c 'ENDURAIN_API_KEY="$(cat /home/kuhy/testsAndMisc/endurain/.api_key)" /home/kuhy/testsAndMisc/.venv/bin/python -m python_pkg.endurain_import'
|
||||
|
||||
@ -16,7 +16,17 @@
|
||||
# the clean venv's python routes coverage through the venv.
|
||||
#
|
||||
# Wired as the pre-push hook; a red result blocks the push before CI sees it.
|
||||
# Escape hatch: `git push --no-verify`.
|
||||
#
|
||||
# SCOPE (2026-08-23): this gate used to run `--all-files` plus every shell
|
||||
# suite on every push, costing ~130s. It now checks the PUSH RANGE:
|
||||
# * pre-commit runs over the pushed files, not the whole tree. Repo-wide
|
||||
# hooks are `always_run`/`--all` in the config and still sweep everything.
|
||||
# * only the lib/tests suites whose tree the push touched are run.
|
||||
# * pytest runs only when the push touches Python -- but then runs the WHOLE
|
||||
# suite, because the coverage bar is whole-repo.
|
||||
# * a tree hash identical to the last green run short-circuits the lot.
|
||||
# Any change to the gate's own machinery or to .pre-commit-config.yaml forces
|
||||
# a full sweep, so a new rule cannot land while only checking its own diff.
|
||||
# ============================================================================
|
||||
|
||||
set -euo pipefail
|
||||
@ -28,6 +38,16 @@ ROOT="$(git rev-parse --show-toplevel)"
|
||||
readonly ROOT
|
||||
cd "$ROOT"
|
||||
|
||||
# shellcheck source=meta/scripts/ci_mirror_range.sh
|
||||
source "$ROOT/meta/scripts/ci_mirror_range.sh"
|
||||
# shellcheck source=meta/scripts/ci_mirror_shell.sh
|
||||
source "$ROOT/meta/scripts/ci_mirror_shell.sh"
|
||||
|
||||
# Records the tree hash of the last fully-green run; see tree_cache_*.
|
||||
readonly GREEN_CACHE="$ROOT/.ci-mirror-venv/.last-green-tree"
|
||||
|
||||
LOGDIR=""
|
||||
|
||||
readonly VENV_DIR="$ROOT/.ci-mirror-venv"
|
||||
readonly HASH_FILE="$VENV_DIR/.requirements.sha256"
|
||||
readonly REQ_PATH="$ROOT/$REQUIREMENTS_FILE"
|
||||
@ -75,6 +95,9 @@ ensure_venv() {
|
||||
CHECKOUT=""
|
||||
|
||||
cleanup_checkout() {
|
||||
if [[ -n "$LOGDIR" && -d "$LOGDIR" ]]; then
|
||||
rm -rf "$LOGDIR"
|
||||
fi
|
||||
if [[ -n "$CHECKOUT" && -d "$CHECKOUT" ]]; then
|
||||
git -C "$ROOT" worktree remove --force "$CHECKOUT" >/dev/null 2>&1 || true
|
||||
rm -rf "$CHECKOUT"
|
||||
@ -103,115 +126,106 @@ run_gates_in_clean_worktree() {
|
||||
git -C "$ROOT" worktree add --detach --quiet "$CHECKOUT" HEAD ||
|
||||
fail "could not create the clean worktree"
|
||||
|
||||
local paths
|
||||
paths="$(changed_paths)"
|
||||
|
||||
local scope_args=(--all-files)
|
||||
if ! needs_full_sweep "$paths"; then
|
||||
scope_args=(--from-ref "$PRE_COMMIT_FROM_REF" --to-ref "$PRE_COMMIT_TO_REF")
|
||||
log "scoped to the push range ($(grep -c . <<<"$paths") file(s) changed)"
|
||||
else
|
||||
log "full sweep (no push range, or the gate's own config changed)"
|
||||
fi
|
||||
|
||||
# The three stages are independent, so they run concurrently and the gate
|
||||
# costs the slowest rather than the sum. Output goes to per-stage files and
|
||||
# is replayed on failure: interleaved live output from three stages is
|
||||
# unreadable, and the diagnosis is what makes a red gate actionable.
|
||||
local logdir
|
||||
logdir="$(mktemp -d -t ci-mirror-logs-XXXXXX)"
|
||||
LOGDIR="$logdir"
|
||||
|
||||
# Skip pytest-coverage here: it is a pre-commit-stage hook that would run
|
||||
# in the system env (not our clean venv) and duplicate the pytest run below.
|
||||
log "pre-commit run --all-files (mirrors the pre-commit workflow)"
|
||||
(cd "$CHECKOUT" && SKIP=pytest-coverage pre-commit run --all-files) ||
|
||||
fail "pre-commit --all-files"
|
||||
log "pre-commit (mirrors the pre-commit workflow)"
|
||||
(cd "$CHECKOUT" && SKIP=pytest-coverage pre-commit run "${scope_args[@]}") \
|
||||
>"$logdir/precommit.log" 2>&1 &
|
||||
local pc_pid=$!
|
||||
|
||||
log "changed-packages pytest in the clean venv (OOM-safe runner)"
|
||||
(cd "$CHECKOUT" && "$VENV_DIR/bin/python" meta/scripts/pytest_changed_packages.py) ||
|
||||
run_python_gate "$paths" >"$logdir/pytest.log" 2>&1 &
|
||||
local py_pid=$!
|
||||
|
||||
# The shell gate is NOT backgrounded alongside the others when it contains a
|
||||
# jailed suite: two coverage jails, or a jail racing a busy CPU, produce
|
||||
# false failures (measured repeatedly). It runs after the parallel pair.
|
||||
local pc_rc=0 py_rc=0
|
||||
wait "$pc_pid" || pc_rc=$?
|
||||
wait "$py_pid" || py_rc=$?
|
||||
|
||||
if ((pc_rc != 0)); then
|
||||
cat "$logdir/precommit.log" >&2
|
||||
fail "pre-commit (scoped run)"
|
||||
fi
|
||||
if ((py_rc != 0)); then
|
||||
cat "$logdir/pytest.log" >&2
|
||||
fail "pytest_changed_packages (clean requirements.txt venv)"
|
||||
fi
|
||||
|
||||
run_shell_test_gate
|
||||
run_shell_test_gate "$paths"
|
||||
}
|
||||
|
||||
# Mirror the shell-tests workflow's side-effect-free half.
|
||||
# Run the whole python suite, but only when the push touches Python.
|
||||
#
|
||||
# Without this, ci-mirror covered the pre-commit and python-tests workflows but
|
||||
# not Shell tests, so a shell change could pass every local gate and still go
|
||||
# red on push — which is exactly what happened repeatedly during the
|
||||
# 250-line-cap campaign: three separate test files asserted on code that a
|
||||
# split had moved, and each was only caught after the push.
|
||||
#
|
||||
# The Arch-container half of that workflow is deliberately NOT mirrored: it
|
||||
# needs an Arch userland running as root to touch /etc, which is what the
|
||||
# disposable container provides and a developer machine must not.
|
||||
# A suite that writes to real system paths declares it with a `jail_args` file
|
||||
# beside its run_all.sh, holding the --bind/--seed-* flags it needs. Such a
|
||||
# suite REFUSES to run bare -- that guard is what stops a test run from
|
||||
# rewriting the developer's own /etc -- so invoking it directly fails the gate.
|
||||
#
|
||||
# Fails closed: a marker present but empty is a mistake, not a licence to skip.
|
||||
run_jailed_suite() {
|
||||
local runner="$1"
|
||||
local args_file="$CHECKOUT/${runner%/run_all.sh}/jail_args"
|
||||
|
||||
local jail_args=()
|
||||
while IFS= read -r arg; do
|
||||
jail_args+=("$arg")
|
||||
done < <(grep -v '^#\|^$' "$args_file" || true)
|
||||
|
||||
if [[ ${#jail_args[@]} -eq 0 ]]; then
|
||||
fail "jail_args is present but empty: $args_file"
|
||||
fi
|
||||
|
||||
# --min 0: this gate asks "did the assertions pass?", not "is the lib at
|
||||
# 100%?". Without it the jail measures the runner itself against its
|
||||
# default --min 100 and fails the push on a number no one asked for.
|
||||
# The coverage bar is check_shell_coverage.sh's job, per-lib and --measure'd.
|
||||
# Output is captured, not discarded: on success it is noise, but on failure
|
||||
# it holds the `warn: case exited` line and the suite's own FAIL: lines.
|
||||
# Without this the gate reports only "suite failed" and cannot be diagnosed.
|
||||
local out
|
||||
if ! out="$(cd "$CHECKOUT" && bash meta/scripts/shell_coverage_jail.sh \
|
||||
--subject "$runner" "${jail_args[@]}" \
|
||||
--min 0 --fail-on-case-error -- "" 2>&1)"; then
|
||||
printf '%s\n' "$out" >&2
|
||||
fail "jailed lib/tests suite failed: $runner"
|
||||
# NOTE: pytest_changed_packages.py returns 0 immediately when given no
|
||||
# arguments (it is normally a pre-commit hook fed staged paths). Invoking it
|
||||
# bare -- as this gate did until 2026-08-23 -- therefore ran ZERO tests and
|
||||
# reported success on every push. The changed paths are passed explicitly so
|
||||
# the stage actually executes.
|
||||
run_python_gate() {
|
||||
local paths="$1"
|
||||
if ! touches_python "$paths" && ! needs_full_sweep "$paths"; then
|
||||
log "no Python in the push range — skipping pytest"
|
||||
return 0
|
||||
fi
|
||||
log "whole python_pkg suite in the clean venv (OOM-safe runner)"
|
||||
local args=()
|
||||
while IFS= read -r f; do
|
||||
[[ -n "$f" ]] && args+=("$f")
|
||||
done <<<"$paths"
|
||||
# A full sweep has no range; hand it a sentinel so the runner does not
|
||||
# short-circuit on empty argv.
|
||||
((${#args[@]} == 0)) && args=(--all)
|
||||
(cd "$CHECKOUT" && "$VENV_DIR/bin/python" meta/scripts/pytest_changed_packages.py "${args[@]}")
|
||||
}
|
||||
|
||||
run_shell_test_gate() {
|
||||
log "lib/tests suites (mirrors the shell-tests workflow)"
|
||||
local runners=()
|
||||
while IFS= read -r runner; do
|
||||
runners+=("$runner")
|
||||
done < <(cd "$CHECKOUT" && find . -path ./node_modules -prune -o \
|
||||
-path '*/lib/tests/run_all.sh' -print | sort)
|
||||
# Short-circuit a re-push of a tree that already passed.
|
||||
#
|
||||
# Keyed on the whole-repo tree hash of HEAD, so it self-invalidates when
|
||||
# anything in the tree changes -- including the gate's own scripts. A rebase
|
||||
# that lands the identical tree, or a retried push after a network failure,
|
||||
# then costs nothing. The record lives inside .ci-mirror-venv/ (already
|
||||
# gitignored) so it never shows up in `git status` or a jail fingerprint.
|
||||
tree_is_known_green() {
|
||||
local head_tree stored
|
||||
head_tree="$(git -C "$ROOT" rev-parse 'HEAD^{tree}')"
|
||||
[[ -f "$GREEN_CACHE" ]] || return 1
|
||||
stored="$(cat "$GREEN_CACHE")"
|
||||
[[ "$head_tree" == "$stored" ]]
|
||||
}
|
||||
|
||||
if [[ ${#runners[@]} -eq 0 ]]; then
|
||||
fail "no lib/tests/run_all.sh found — the discovery glob is wrong"
|
||||
fi
|
||||
|
||||
local runner
|
||||
for runner in "${runners[@]}"; do
|
||||
if [[ -f "$CHECKOUT/${runner%/run_all.sh}/jail_args" ]]; then
|
||||
run_jailed_suite "$runner"
|
||||
else
|
||||
(cd "$CHECKOUT" && "$runner" >/dev/null) ||
|
||||
fail "lib/tests suite failed: $runner"
|
||||
fi
|
||||
done
|
||||
|
||||
log "side-effect-free shell tests (mirrors the shell-tests workflow)"
|
||||
# Parsed OUT of the workflow rather than duplicated here. A hardcoded copy
|
||||
# drifts the moment someone adds a test to the workflow, and a mirror that
|
||||
# silently checks less than CI is worse than no mirror: it reports safe.
|
||||
# The awk range is the shell-tests job's `tests=( ... )` array, taking the
|
||||
# first one only — the second belongs to the Arch container job, which is
|
||||
# deliberately not mirrored.
|
||||
local shell_tests=()
|
||||
while IFS= read -r shell_test; do
|
||||
shell_tests+=("$shell_test")
|
||||
done < <(awk '/^ *tests=\(/{n++} n==1 && /^ *test_.*\.sh *$/{gsub(/ /,"");print} n==1 && /^ *\)/{exit}' \
|
||||
"$CHECKOUT/.github/workflows/shell-tests.yml")
|
||||
|
||||
if [[ ${#shell_tests[@]} -eq 0 ]]; then
|
||||
fail "could not parse the test list out of shell-tests.yml"
|
||||
fi
|
||||
|
||||
local shell_test
|
||||
for shell_test in "${shell_tests[@]}"; do
|
||||
(cd "$CHECKOUT" && bash "linux_configuration/tests/$shell_test" >/dev/null 2>&1) ||
|
||||
fail "shell test failed: $shell_test"
|
||||
done
|
||||
record_tree_green() {
|
||||
git -C "$ROOT" rev-parse 'HEAD^{tree}' >"$GREEN_CACHE" 2>/dev/null || true
|
||||
}
|
||||
|
||||
main() {
|
||||
require_file
|
||||
if tree_is_known_green; then
|
||||
log "this exact tree already passed the full gate — nothing to redo"
|
||||
exit 0
|
||||
fi
|
||||
ensure_venv
|
||||
run_gates_in_clean_worktree
|
||||
record_tree_green
|
||||
log "all CI gates passed locally — safe to push"
|
||||
}
|
||||
|
||||
|
||||
78
meta/scripts/ci_mirror_range.sh
Normal file
78
meta/scripts/ci_mirror_range.sh
Normal file
@ -0,0 +1,78 @@
|
||||
# shellcheck shell=bash
|
||||
# ============================================================================
|
||||
# ci_mirror_range.sh — resolve WHAT a push must re-check.
|
||||
#
|
||||
# Sourced by ci_mirror.sh. Splits out of it to stay under the 250-line cap.
|
||||
#
|
||||
# The push range arrives as PRE_COMMIT_FROM_REF/PRE_COMMIT_TO_REF, which
|
||||
# pre-commit exports because the pre-push hook passes --from-ref/--to-ref
|
||||
# resolved from the refs git feeds it on stdin. Those are the REMOTE's actual
|
||||
# shas, so unlike `origin/main` they cannot go stale and silently widen or
|
||||
# empty the range.
|
||||
# ============================================================================
|
||||
|
||||
# Files whose change invalidates any narrower scope: the gate's own machinery
|
||||
# and the hook definitions. Editing a hook must re-check the whole repo, or the
|
||||
# new rule only ever sees the handful of files in the same push.
|
||||
readonly GATE_WIDENING_RE='^(\.pre-commit-config\.yaml|meta/scripts/|meta/pyproject\.toml|requirements\.txt|linux_configuration/\.githooks/)'
|
||||
|
||||
# Shared shell foundations. A change here can affect every suite, so it fans
|
||||
# out to all of them rather than to the suite that happens to contain it.
|
||||
readonly SHELL_WIDENING_RE='^linux_configuration/scripts/lib/|/tests/lib_test_(core|path)\.sh$'
|
||||
|
||||
# Emit the paths in the push range, one per line. Empty output means "no range
|
||||
# known", which callers must treat as "check everything", never as "nothing".
|
||||
changed_paths() {
|
||||
if [[ -z "${PRE_COMMIT_FROM_REF:-}" || -z "${PRE_COMMIT_TO_REF:-}" ]]; then
|
||||
return 0
|
||||
fi
|
||||
git -C "$ROOT" diff --name-only \
|
||||
"$PRE_COMMIT_FROM_REF" "$PRE_COMMIT_TO_REF" 2>/dev/null || true
|
||||
}
|
||||
|
||||
# True when the whole repo must be swept: no known range, or a gate file moved.
|
||||
needs_full_sweep() {
|
||||
local paths="$1"
|
||||
[[ -z "$paths" ]] && return 0
|
||||
grep -qE "$GATE_WIDENING_RE" <<<"$paths" && return 0
|
||||
return 1
|
||||
}
|
||||
|
||||
# True when the push touches Python at all. The pytest stage is all-or-nothing
|
||||
# by design (whole-repo 100% branch coverage), so this is a run/skip decision,
|
||||
# not a subset one.
|
||||
touches_python() {
|
||||
grep -qE '\.py$|^requirements\.txt$' <<<"$1"
|
||||
}
|
||||
|
||||
# Map changed paths to the lib/tests suites that must run.
|
||||
#
|
||||
# Printing nothing means no shell suite needs to run. A shared-foundation
|
||||
# change prints every suite instead of just the enclosing one.
|
||||
select_shell_suites() {
|
||||
local paths="$1" all_suites="$2"
|
||||
if ! grep -qE '\.(sh|bash)$|/tests/' <<<"$paths"; then
|
||||
return 0
|
||||
fi
|
||||
if grep -qE "$SHELL_WIDENING_RE" <<<"$paths"; then
|
||||
printf '%s\n' "$all_suites"
|
||||
return 0
|
||||
fi
|
||||
|
||||
# A suite covers the entry scripts in its PARENT directory as well as its
|
||||
# own lib/, so the parent is the right scope -- but match it
|
||||
# non-recursively. `scripts/lib/tests` has parent
|
||||
# `linux_configuration/scripts`, which is a prefix of every other suite's
|
||||
# path; a recursive match there would fire it on every shell push.
|
||||
# `[^/]+$` keeps a path in the parent itself, while the second alternative
|
||||
# picks up the suite's own lib/ and tests/ at any depth.
|
||||
local suite parent
|
||||
while IFS= read -r suite; do
|
||||
[[ -z "$suite" ]] && continue
|
||||
parent="${suite%/lib/tests/run_all.sh}"
|
||||
parent="${parent#./}"
|
||||
if grep -qE "^${parent}/([^/]+$|lib/)" <<<"$paths"; then
|
||||
printf '%s\n' "$suite"
|
||||
fi
|
||||
done <<<"$all_suites"
|
||||
}
|
||||
119
meta/scripts/ci_mirror_shell.sh
Normal file
119
meta/scripts/ci_mirror_shell.sh
Normal file
@ -0,0 +1,119 @@
|
||||
# shellcheck shell=bash
|
||||
# ============================================================================
|
||||
# ci_mirror_shell.sh — the shell half of the CI mirror.
|
||||
#
|
||||
# Sourced by ci_mirror.sh. Splits out of it to stay under the 250-line cap.
|
||||
# Provides run_shell_test_gate, which mirrors the shell-tests workflow, and
|
||||
# run_jailed_suite, which wraps a suite that declares a jail_args file.
|
||||
#
|
||||
# Uses ci_mirror.sh's CHECKOUT/fail/log and ci_mirror_range.sh's
|
||||
# select_shell_suites / needs_full_sweep.
|
||||
# ============================================================================
|
||||
|
||||
# Mirror the shell-tests workflow's side-effect-free half.
|
||||
#
|
||||
# Without this, ci-mirror covered the pre-commit and python-tests workflows but
|
||||
# not Shell tests, so a shell change could pass every local gate and still go
|
||||
# red on push — which is exactly what happened repeatedly during the
|
||||
# 250-line-cap campaign: three separate test files asserted on code that a
|
||||
# split had moved, and each was only caught after the push.
|
||||
#
|
||||
# The Arch-container half of that workflow is deliberately NOT mirrored: it
|
||||
# needs an Arch userland running as root to touch /etc, which is what the
|
||||
# disposable container provides and a developer machine must not.
|
||||
# A suite that writes to real system paths declares it with a `jail_args` file
|
||||
# beside its run_all.sh, holding the --bind/--seed-* flags it needs. Such a
|
||||
# suite REFUSES to run bare -- that guard is what stops a test run from
|
||||
# rewriting the developer's own /etc -- so invoking it directly fails the gate.
|
||||
#
|
||||
# Fails closed: a marker present but empty is a mistake, not a licence to skip.
|
||||
run_jailed_suite() {
|
||||
local runner="$1"
|
||||
local args_file="$CHECKOUT/${runner%/run_all.sh}/jail_args"
|
||||
|
||||
local jail_args=()
|
||||
while IFS= read -r arg; do
|
||||
jail_args+=("$arg")
|
||||
done < <(grep -v '^#\|^$' "$args_file" || true)
|
||||
|
||||
if [[ ${#jail_args[@]} -eq 0 ]]; then
|
||||
fail "jail_args is present but empty: $args_file"
|
||||
fi
|
||||
|
||||
# --min 0: this gate asks "did the assertions pass?", not "is the lib at
|
||||
# 100%?". Without it the jail measures the runner itself against its
|
||||
# default --min 100 and fails the push on a number no one asked for.
|
||||
# The coverage bar is check_shell_coverage.sh's job, per-lib and --measure'd.
|
||||
# Output is captured, not discarded: on success it is noise, but on failure
|
||||
# it holds the `warn: case exited` line and the suite's own FAIL: lines.
|
||||
# Without this the gate reports only "suite failed" and cannot be diagnosed.
|
||||
local out
|
||||
if ! out="$(cd "$CHECKOUT" && bash meta/scripts/shell_coverage_jail.sh \
|
||||
--subject "$runner" "${jail_args[@]}" \
|
||||
--min 0 --fail-on-case-error -- "" 2>&1)"; then
|
||||
printf '%s\n' "$out" >&2
|
||||
fail "jailed lib/tests suite failed: $runner"
|
||||
fi
|
||||
}
|
||||
|
||||
run_shell_test_gate() {
|
||||
local paths="$1"
|
||||
local all_runners
|
||||
all_runners="$(cd "$CHECKOUT" && find . -path ./node_modules -prune -o \
|
||||
-path '*/lib/tests/run_all.sh' -print | sort)"
|
||||
|
||||
if [[ -z "$all_runners" ]]; then
|
||||
fail "no lib/tests/run_all.sh found — the discovery glob is wrong"
|
||||
fi
|
||||
|
||||
local selected
|
||||
if needs_full_sweep "$paths"; then
|
||||
selected="$all_runners"
|
||||
else
|
||||
selected="$(select_shell_suites "$paths" "$all_runners")"
|
||||
fi
|
||||
|
||||
if [[ -z "$selected" ]]; then
|
||||
log "no shell files in the push range — skipping the lib/tests suites"
|
||||
else
|
||||
log "lib/tests suites (mirrors the shell-tests workflow)"
|
||||
fi
|
||||
|
||||
local runners=()
|
||||
while IFS= read -r runner; do
|
||||
[[ -n "$runner" ]] && runners+=("$runner")
|
||||
done <<<"$selected"
|
||||
|
||||
local runner
|
||||
for runner in "${runners[@]}"; do
|
||||
if [[ -f "$CHECKOUT/${runner%/run_all.sh}/jail_args" ]]; then
|
||||
run_jailed_suite "$runner"
|
||||
else
|
||||
(cd "$CHECKOUT" && "$runner" >/dev/null) ||
|
||||
fail "lib/tests suite failed: $runner"
|
||||
fi
|
||||
done
|
||||
|
||||
log "side-effect-free shell tests (mirrors the shell-tests workflow)"
|
||||
# Parsed OUT of the workflow rather than duplicated here. A hardcoded copy
|
||||
# drifts the moment someone adds a test to the workflow, and a mirror that
|
||||
# silently checks less than CI is worse than no mirror: it reports safe.
|
||||
# The awk range is the shell-tests job's `tests=( ... )` array, taking the
|
||||
# first one only — the second belongs to the Arch container job, which is
|
||||
# deliberately not mirrored.
|
||||
local shell_tests=()
|
||||
while IFS= read -r shell_test; do
|
||||
shell_tests+=("$shell_test")
|
||||
done < <(awk '/^ *tests=\(/{n++} n==1 && /^ *test_.*\.sh *$/{gsub(/ /,"");print} n==1 && /^ *\)/{exit}' \
|
||||
"$CHECKOUT/.github/workflows/shell-tests.yml")
|
||||
|
||||
if [[ ${#shell_tests[@]} -eq 0 ]]; then
|
||||
fail "could not parse the test list out of shell-tests.yml"
|
||||
fi
|
||||
|
||||
local shell_test
|
||||
for shell_test in "${shell_tests[@]}"; do
|
||||
(cd "$CHECKOUT" && bash "linux_configuration/tests/$shell_test" >/dev/null 2>&1) ||
|
||||
fail "shell test failed: $shell_test"
|
||||
done
|
||||
}
|
||||
@ -143,7 +143,8 @@ class TestRunReindex:
|
||||
|
||||
env = mock_run.call_args.kwargs["env"]
|
||||
assert env["KNOWLEDGE_RAG_DIR"] == "/store"
|
||||
assert env["PYTHONPATH"].endswith("testsAndMisc")
|
||||
expected_root = Path(reindex.__file__).resolve().parents[2]
|
||||
assert env["PYTHONPATH"] == str(expected_root)
|
||||
|
||||
@patch(f"{MOD}.subprocess.run")
|
||||
def test_prepends_to_existing_pythonpath(self, mock_run: MagicMock) -> None:
|
||||
|
||||
@ -3,15 +3,22 @@
|
||||
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 activities:upload (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)
|
||||
ENDURAIN_NO_DB set to 1 to disable the postgres dedupe fallback
|
||||
ENDURAIN_PG_CONTAINER postgres container name (default endurain-postgres)
|
||||
|
||||
Duplicate detection asks Endurain what it already holds, so a run RunnerUp
|
||||
uploaded directly is not imported a second time. The HTTP API is tried first,
|
||||
but API keys cannot read activities (the scope allow-list is upload-only and
|
||||
the read route is JWT-only), so in practice the postgres fallback is what
|
||||
answers. If both are unavailable the local ledger alone decides, which is the
|
||||
behaviour this importer had before either check existed.
|
||||
|
||||
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
|
||||
@ -29,6 +36,7 @@ from typing import TYPE_CHECKING
|
||||
|
||||
import requests
|
||||
|
||||
from python_pkg.endurain_import.db_lookup import known_start_times
|
||||
from python_pkg.endurain_import.ledger import (
|
||||
Entry,
|
||||
Ledger,
|
||||
@ -190,15 +198,10 @@ 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.
|
||||
# One query per run, not per file: the result 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"
|
||||
)
|
||||
remote_starts = known_start_times(client, user_id)
|
||||
|
||||
counts = {"skipped": 0, "imported": 0, "rejected": 0, "ambiguous": 0}
|
||||
for path in pending:
|
||||
|
||||
183
python_pkg/endurain_import/db_lookup.py
Normal file
183
python_pkg/endurain_import/db_lookup.py
Normal file
@ -0,0 +1,183 @@
|
||||
"""Duplicate detection that reads Endurain's database directly.
|
||||
|
||||
Endurain's API keys cannot answer "what do you already hold": the key scope
|
||||
allow-list is ``{"activities:upload"}`` (enforced twice, deliberately), and the
|
||||
activities read route is mounted JWT-only, so a key fails at *authentication*
|
||||
before any scope check. Verified against v0.19.0; upstream documents no plan to
|
||||
widen it.
|
||||
|
||||
That leaves the database. The postgres container publishes no host port, so
|
||||
this goes through ``docker exec`` rather than a TCP client -- no new dependency,
|
||||
no compose change, and no port exposed to the host just to read four rows.
|
||||
|
||||
This is a *fallback*, not a replacement: :mod:`__main__` asks the HTTP API first
|
||||
so that the supported path starts working by itself if Endurain ever grants the
|
||||
scope.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Sequence
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
from typing import TYPE_CHECKING, Protocol
|
||||
|
||||
from python_pkg.endurain_import.upload import _parse_start
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
class SupportsRecentStartTimes(Protocol):
|
||||
"""The lookup surface :func:`known_start_times` needs from a client."""
|
||||
|
||||
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
|
||||
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
_CONTAINER_ENV = "ENDURAIN_PG_CONTAINER"
|
||||
_NO_DB_ENV = "ENDURAIN_NO_DB"
|
||||
_DEFAULT_CONTAINER = "endurain-postgres"
|
||||
_DB_USER = "endurain"
|
||||
_DB_NAME = "endurain"
|
||||
# Mirrors the HTTP path's page size so both backends answer the same question.
|
||||
_RECENT_RECORDS = 50
|
||||
_TIMEOUT = 30
|
||||
|
||||
# -At: tuples only, unaligned -- one bare timestamp per line, no header or
|
||||
# padding to strip. The query goes in on stdin rather than via -c because psql
|
||||
# only substitutes -v variables in scripts it reads, never inside -c; that
|
||||
# keeps user_id out of the SQL string instead of formatting it in.
|
||||
_QUERY = (
|
||||
"SELECT start_time FROM activities "
|
||||
"WHERE user_id = :uid ORDER BY start_time DESC LIMIT :lim;"
|
||||
)
|
||||
|
||||
Runner = Callable[[Sequence[str], str], "subprocess.CompletedProcess[str]"]
|
||||
|
||||
|
||||
def _run(argv: Sequence[str], stdin: str) -> subprocess.CompletedProcess[str]:
|
||||
"""Execute ``argv``, feeding ``stdin``, and capture its output.
|
||||
|
||||
Split out so tests can inject a stub: the real call is unreachable in a
|
||||
unit test, and the branches around its result are exactly what needs
|
||||
covering.
|
||||
"""
|
||||
return subprocess.run(
|
||||
list(argv),
|
||||
input=stdin,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=_TIMEOUT,
|
||||
check=False,
|
||||
)
|
||||
|
||||
|
||||
class EndurainDatabase:
|
||||
"""Reads recent activity start times straight out of postgres."""
|
||||
|
||||
def __init__(self, container: str | None = None, runner: Runner = _run) -> None:
|
||||
"""Build a reader for ``container``, executing through ``runner``."""
|
||||
self._container = container or os.environ.get(
|
||||
_CONTAINER_ENV, _DEFAULT_CONTAINER
|
||||
)
|
||||
self._run = runner
|
||||
|
||||
def recent_start_times(self, user_id: int) -> list[datetime] | None:
|
||||
"""Return recent activity start times, or None if unknowable.
|
||||
|
||||
None means the question could not be answered -- the container is gone,
|
||||
psql failed, or the call timed out. An empty list is a real answer
|
||||
("this user has no activities") and callers may act on it; None must
|
||||
only ever mean "fall back". Conflating the two would let a docker
|
||||
failure read as "nothing is stored" and re-upload everything.
|
||||
"""
|
||||
argv = [
|
||||
"docker",
|
||||
"exec",
|
||||
"-i",
|
||||
self._container,
|
||||
"psql",
|
||||
"-U",
|
||||
_DB_USER,
|
||||
"-d",
|
||||
_DB_NAME,
|
||||
"-At",
|
||||
"-v",
|
||||
"ON_ERROR_STOP=1",
|
||||
"-v",
|
||||
f"uid={int(user_id)}",
|
||||
"-v",
|
||||
f"lim={_RECENT_RECORDS}",
|
||||
]
|
||||
try:
|
||||
proc = self._run(argv, _QUERY)
|
||||
except (OSError, subprocess.SubprocessError) as exc:
|
||||
_logger.warning("could not read activities from the database: %s", exc)
|
||||
return None
|
||||
if proc.returncode != 0:
|
||||
_logger.warning(
|
||||
"could not read activities from the database: psql exited %s (%s)",
|
||||
proc.returncode,
|
||||
(proc.stderr or "").strip()[:200] or "no stderr",
|
||||
)
|
||||
return None
|
||||
return _parse_rows(proc.stdout)
|
||||
|
||||
|
||||
def _parse_rows(stdout: str) -> list[datetime]:
|
||||
"""Turn psql's one-timestamp-per-line output into datetimes.
|
||||
|
||||
Unparsable lines are dropped rather than failing the lookup: a row this
|
||||
function cannot read is one fewer duplicate it can catch, which is the
|
||||
safe direction -- the ledger still guards the upload.
|
||||
"""
|
||||
return [
|
||||
parsed
|
||||
for line in stdout.splitlines()
|
||||
if (stripped := line.strip()) and (parsed := _parse_start(stripped)) is not None
|
||||
]
|
||||
|
||||
|
||||
def known_start_times(
|
||||
client: SupportsRecentStartTimes, user_id: int
|
||||
) -> list[datetime] | None:
|
||||
"""Ask Endurain what it already holds, HTTP first then postgres.
|
||||
|
||||
Returns None only when *neither* backend could answer, which the caller
|
||||
must read as "unknown" rather than "nothing stored" -- an empty list is a
|
||||
real answer and means this user genuinely has no activities.
|
||||
|
||||
The HTTP path is tried first even though it cannot currently succeed, so
|
||||
that the supported route starts working on its own if Endurain ever widens
|
||||
the API-key scope allow-list.
|
||||
"""
|
||||
starts = client.recent_start_times(user_id)
|
||||
if starts is not None:
|
||||
_logger.info(
|
||||
"duplicate detection: %d activity start time(s) via the API", len(starts)
|
||||
)
|
||||
return starts
|
||||
|
||||
if os.environ.get(_NO_DB_ENV) == "1":
|
||||
_logger.warning(
|
||||
"duplicate detection against Endurain is unavailable and the "
|
||||
"database fallback is disabled; falling back to the local ledger only"
|
||||
)
|
||||
return None
|
||||
|
||||
starts = EndurainDatabase().recent_start_times(user_id)
|
||||
if starts is None:
|
||||
_logger.warning(
|
||||
"duplicate detection against Endurain is unavailable; falling "
|
||||
"back to the local ledger only"
|
||||
)
|
||||
return None
|
||||
_logger.info(
|
||||
"duplicate detection: %d activity start time(s) via the database", len(starts)
|
||||
)
|
||||
return starts
|
||||
@ -61,6 +61,12 @@ def _env(
|
||||
monkeypatch.setenv("ENDURAIN_INBOX", str(inbox))
|
||||
monkeypatch.setenv("ENDURAIN_STATE", str(tmp_path / "state"))
|
||||
monkeypatch.setenv("ENDURAIN_NO_ADB", "1")
|
||||
# Off by default so no test ever shells out to the real postgres container:
|
||||
# the DB fallback runs whenever the stubbed HTTP lookup returns None, and a
|
||||
# test that reached the live database would pass or fail on this machine's
|
||||
# actual activity rows. Tests that want it set ENDURAIN_NO_DB="0" and stub
|
||||
# EndurainDatabase explicitly.
|
||||
monkeypatch.setenv("ENDURAIN_NO_DB", "1")
|
||||
for key, value in extra.items():
|
||||
monkeypatch.setenv(key, value)
|
||||
|
||||
|
||||
119
python_pkg/endurain_import/tests/test_db_lookup.py
Normal file
119
python_pkg/endurain_import/tests/test_db_lookup.py
Normal file
@ -0,0 +1,119 @@
|
||||
"""Reading Endurain's activity start times straight out of postgres.
|
||||
|
||||
The load-bearing distinction is None vs []: None means "could not ask" and
|
||||
must send the caller back to the ledger, while [] is a real answer meaning
|
||||
this user has no activities. Swapping them would upload a duplicate every
|
||||
time docker hiccuped, which is the bug the dedupe check exists to prevent.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
from datetime import datetime, timezone
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.endurain_import import db_lookup
|
||||
|
||||
|
||||
def _proc(
|
||||
returncode: int = 0, stdout: str = "", stderr: str = ""
|
||||
) -> subprocess.CompletedProcess[str]:
|
||||
return subprocess.CompletedProcess(
|
||||
args=["docker"], returncode=returncode, stdout=stdout, stderr=stderr
|
||||
)
|
||||
|
||||
|
||||
def _db_returning(
|
||||
result: subprocess.CompletedProcess[str] | Exception,
|
||||
captured: dict[str, object] | None = None,
|
||||
) -> db_lookup.EndurainDatabase:
|
||||
def _runner(argv: Sequence[str], stdin: str) -> subprocess.CompletedProcess[str]:
|
||||
if captured is not None:
|
||||
captured["argv"] = list(argv)
|
||||
captured["stdin"] = stdin
|
||||
if isinstance(result, Exception):
|
||||
raise result
|
||||
return result
|
||||
|
||||
return db_lookup.EndurainDatabase(runner=_runner)
|
||||
|
||||
|
||||
def test_parses_rows_into_utc() -> None:
|
||||
db = _db_returning(_proc(stdout="2026-08-22 23:51:05+02\n2026-08-19 19:10:06+02\n"))
|
||||
assert db.recent_start_times(1) == [
|
||||
datetime(2026, 8, 22, 21, 51, 5, tzinfo=timezone.utc),
|
||||
datetime(2026, 8, 19, 17, 10, 6, tzinfo=timezone.utc),
|
||||
]
|
||||
|
||||
|
||||
def test_empty_table_is_an_answer_not_a_failure() -> None:
|
||||
"""No rows means "nothing stored" -- callers may act on it."""
|
||||
assert _db_returning(_proc(stdout="")).recent_start_times(1) == []
|
||||
|
||||
|
||||
def test_nonzero_exit_is_unknown() -> None:
|
||||
"""A dead container must not read as "no activities exist"."""
|
||||
db = _db_returning(_proc(returncode=1, stderr="No such container"))
|
||||
assert db.recent_start_times(1) is None
|
||||
|
||||
|
||||
def test_nonzero_exit_without_stderr_is_unknown() -> None:
|
||||
"""Covers the empty-stderr branch of the failure message."""
|
||||
assert _db_returning(_proc(returncode=2)).recent_start_times(1) is None
|
||||
|
||||
|
||||
def test_subprocess_error_is_unknown() -> None:
|
||||
db = _db_returning(subprocess.TimeoutExpired(cmd="docker", timeout=30))
|
||||
assert db.recent_start_times(1) is None
|
||||
|
||||
|
||||
def test_os_error_is_unknown() -> None:
|
||||
"""docker missing from PATH raises OSError, not a SubprocessError."""
|
||||
assert _db_returning(OSError("no docker")).recent_start_times(1) is None
|
||||
|
||||
|
||||
def test_unparseable_rows_are_dropped_not_fatal() -> None:
|
||||
db = _db_returning(_proc(stdout="not a timestamp\n2026-08-22 23:51:05+02\n\n"))
|
||||
assert db.recent_start_times(1) == [
|
||||
datetime(2026, 8, 22, 21, 51, 5, tzinfo=timezone.utc)
|
||||
]
|
||||
|
||||
|
||||
def test_query_is_parameterised_and_user_id_coerced() -> None:
|
||||
"""user_id reaches psql as a -v binding, never spliced into the SQL."""
|
||||
captured: dict[str, object] = {}
|
||||
_db_returning(_proc(stdout=""), captured).recent_start_times(7)
|
||||
argv = captured["argv"]
|
||||
assert isinstance(argv, list)
|
||||
assert "uid=7" in argv
|
||||
assert "ON_ERROR_STOP=1" in argv
|
||||
# The statement itself carries no interpolated id.
|
||||
assert "7" not in str(captured["stdin"])
|
||||
assert ":uid" in str(captured["stdin"])
|
||||
|
||||
|
||||
def test_container_name_defaults_and_overrides() -> None:
|
||||
assert db_lookup.EndurainDatabase()._container == "endurain-postgres"
|
||||
assert db_lookup.EndurainDatabase(container="other")._container == "other"
|
||||
|
||||
|
||||
def test_container_name_from_environment(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setenv(db_lookup._CONTAINER_ENV, "from-env")
|
||||
assert db_lookup.EndurainDatabase()._container == "from-env"
|
||||
|
||||
|
||||
def test_default_runner_executes_subprocess(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""The real _run is otherwise unreachable in a unit test."""
|
||||
seen: dict[str, object] = {}
|
||||
|
||||
def _fake_run(argv: object, **kwargs: object) -> subprocess.CompletedProcess[str]:
|
||||
seen["argv"] = argv
|
||||
seen["input"] = kwargs.get("input")
|
||||
return _proc(stdout="")
|
||||
|
||||
monkeypatch.setattr(subprocess, "run", _fake_run)
|
||||
assert db_lookup._run(["docker", "true"], "SELECT 1;").returncode == 0
|
||||
assert seen["argv"] == ["docker", "true"]
|
||||
assert seen["input"] == "SELECT 1;"
|
||||
@ -109,3 +109,44 @@ def test_user_id_is_configurable(
|
||||
_patch_client(monkeypatch, _Recording(Result(Outcome.OK, 1, "ok")))
|
||||
assert main() == 0
|
||||
assert seen == [7]
|
||||
|
||||
|
||||
def _patch_database(
|
||||
monkeypatch: pytest.MonkeyPatch, result: list[datetime] | None
|
||||
) -> None:
|
||||
"""Stand in for the postgres reader; never touches a real container."""
|
||||
from python_pkg.endurain_import import db_lookup
|
||||
|
||||
class _StubDatabase:
|
||||
def recent_start_times(self, _user_id: int) -> list[datetime] | None:
|
||||
return result
|
||||
|
||||
monkeypatch.setattr(db_lookup, "EndurainDatabase", _StubDatabase)
|
||||
|
||||
|
||||
def test_database_fallback_catches_what_the_api_cannot(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, inbox: Path
|
||||
) -> None:
|
||||
"""API keys cannot read activities, so postgres answers instead."""
|
||||
_file(inbox, _RUN_NAME)
|
||||
client = _StubMainClient(Result(Outcome.OK, 1, "uploaded"), remote=None)
|
||||
_env(monkeypatch, tmp_path, inbox, ENDURAIN_NO_DB="0")
|
||||
_patch_client(monkeypatch, client)
|
||||
_patch_database(monkeypatch, [_run_start()])
|
||||
|
||||
assert main() == 0
|
||||
assert client.uploads == 0
|
||||
|
||||
|
||||
def test_database_failure_falls_back_to_the_ledger(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, inbox: Path
|
||||
) -> None:
|
||||
"""Both backends unknown must not block the import."""
|
||||
_file(inbox, _RUN_NAME)
|
||||
client = _StubMainClient(Result(Outcome.OK, 1, "uploaded"), remote=None)
|
||||
_env(monkeypatch, tmp_path, inbox, ENDURAIN_NO_DB="0")
|
||||
_patch_client(monkeypatch, client)
|
||||
_patch_database(monkeypatch, None)
|
||||
|
||||
assert main() == 0
|
||||
assert client.uploads == 1
|
||||
|
||||
@ -112,8 +112,8 @@ class EndurainClient:
|
||||
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)",
|
||||
"could not list recent activities over HTTP: %s (API keys "
|
||||
"cannot read activities; the database fallback answers instead)",
|
||||
resp.status_code,
|
||||
)
|
||||
return None
|
||||
|
||||
Loading…
Reference in New Issue
Block a user