Commit Graph
1 Commits
Author SHA1 Message Date
Tejas ChopraandClaude Opus 5.5 65a219877c test(telemetry): move the 530-line session.demo() self-check out of the shipped module (#4106)
## Description

`headroom/telemetry/session.py` ended with `def demo()`, about 530 lines
of `assert` statements, plus `if __name__ == "__main__": demo()`. It was
a self-check that only ran by hand, with `python -m
headroom.telemetry.session`.

It shipped in every wheel and made up about 20% of the module, yet no
test or CI job ran it. A regression it would catch went unnoticed.

This PR moves it, almost verbatim, into
`tests/test_telemetry_session_selfcheck.py` as one test. CI now runs it,
and the product module loses 535 lines.

Evidence that nothing else used it: `rg -n 'demo\(|python -m
headroom.telemetry.session' headroom docs wiki scripts .github` has no
hits for this module. The org's consumer repos do not reference `demo`
either.

Refs #4136

## Type of Change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [x] Code refactoring (no functional changes)

## Changes Made

- `headroom/telemetry/session.py`: delete `demo()` and the `__main__`
guard. No other line changes.
- `tests/test_telemetry_session_selfcheck.py` (new):
`test_session_selfcheck(monkeypatch)` holds the demo body. Every
assertion is the same. Only three mechanical changes:
- The manual `os.environ` save and restore blocks become
`monkeypatch.context()` with `setenv` and `delenv`.
- `globals()["_aggregator"] = ...` becomes `mp.setattr(S, "_aggregator",
...)`, so the swap is undone automatically.
- An `isolated_session` fixture does all the setup and cleanup, so
cleanup runs even when an assertion fails:
- It points `HOME`, `HEADROOM_CONFIG_DIR` and `HEADROOM_WORKSPACE_DIR`
at `tmp_path`. `resource_attributes()` mints and persists an install id,
and the test must not write `~/.headroom/config/install_id` in the
developer's real home.
- It resets the memoised `_install_id` and `_aggregator` through
monkeypatch.
    - It clears the four module staging dicts before and after the test.
- It switches the beacon on (`HEADROOM_BEACON=on`, with `DO_NOT_TRACK`
and `HEADROOM_OFFLINE` cleared). `tests/conftest.py` turns the beacon
off for every test, and the staging helpers are no-ops while it is off.
The demo had relied on the ambient environment.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [ ] Manual testing performed

### Test Output

```text
# before the move, on origin/main:
$ python -c "from headroom.telemetry import session; session.demo()"
ok
# after the move, the new test plus the beacon tests that share module state, in both orders:
$ pytest -q -p no:cacheprovider tests/test_telemetry_session_selfcheck.py tests/test_beacon_schema_v2.py tests/test_beacon_gzip.py tests/test_stateless_writers.py tests/test_outcome_dual_ruler_funnel.py tests/test_telemetry.py tests/test_telemetry_context.py
148 passed in 17.50s
# same files, reverse order:
148 passed in 10.91s
# hermeticity: run with an empty HOME, then look for an install id there
$ HOME=<empty dir> pytest -q -p no:cacheprovider tests/test_telemetry_session_selfcheck.py && find <empty dir> -name install_id
1 passed in 2.01s
(no install_id found)
# cleanup on failure: forced an AssertionError mid-test, then ran a probe test that checks the staging dicts are empty and _install_id/_aggregator are None
1 failed (forced), 1 passed (probe)
$ uvx ruff@0.16.8 check headroom/telemetry/session.py tests/test_telemetry_session_selfcheck.py
All checks passed!
$ python -m mypy headroom/telemetry/session.py --ignore-missing-imports
Success: no issues found in 1 source file
```

## Real Behavior Proof

- Environment: macOS, Python 3.12.13, this branch checked out in a
worktree, repo .venv; temp HOME and HEADROOM_WORKSPACE_DIR, offline.
- Exact command / steps: (1) The shared smoke harness `smoke.sh
<worktree>`: it starts a real proxy from this checkout against a local
fake upstream and sends one Anthropic and one OpenAI request with a
compressible tool result. (2) A direct command on this PR's own path:
`python -m headroom.telemetry.session; echo exit=$?; python -c "import
headroom.telemetry.session as s; print('demo' in vars(s))";
HOME=$TMP/home pytest -q tests/test_telemetry_session_selfcheck.py; find
$TMP/home -name install_id | wc -l`.
- Observed result: Both requests return 200 and `/stats` shows savings,
with only the expected offline-mode warnings in proxy.log. The direct
command's output is below.
- Not tested: Nothing at runtime changes; no product code path called
demo().

```text
$ bash smoke.sh <worktree>
branch: cleanup/core-misc-session-selfcheck @ 2016e7e8
health: 200
POST /v1/messages        -> HTTP200 smoke-ok
POST /v1/chat/completions -> HTTP200 smoke-ok
stats: requests=2 failed=0 tokens_saved=13574 savings_percent=99.82
proxy.log WARNING/ERROR lines ($SMOKE_TMP/ws/logs/proxy-49318.log):
   2 headroom.proxy - WARNING - event=proxy_offline_mode air-gap active — every connection Headroom initiates is refused (telemetry, update check, license reporter, model/tokenizer/binary/dataset downloads, remote Kompress, OTLP/Langfuse export, Copilot auth, subscription polling, OpenAI embedders, Headroom Cloud compression). Still allowed on purpose: forwarding your requests to the upstream you configured, operator-configured local endpoints, loopback health probes.
   2 headroom.transforms.kompress_compressor - WARNING - Kompress: 'onnx/kompress-int8-wo.onnx' for chopratejas/kompress-v2-base is not cached and HEADROOM_OFFLINE forbids fetching it (HEADROOM_OFFLINE is set: refusing outbound network access for HuggingFace download of chopratejas/kompress-v2-base/onnx/kompress-int8-wo.onnx to huggingface.co. Unset HEADROOM_OFFLINE, or turn off the feature that needs this connection.). Compression falls back to the non-ML path.
   4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch found no usable file for chopratejas/kompress-v2-base
   4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch refused for chopratejas/kompress-v2-base (HEADROOM_OFFLINE is set): HEADROOM_OFFLINE is set: refusing outbound network access for HuggingFace download of chopratejas/kompress-v2-base/onnx/kompress-int8-wo.onnx to huggingface.co. Unset HEADROOM_OFFLINE, or turn off the feature that needs this connection.
(smoke dir: $SMOKE_TMP)

$ python -m headroom.telemetry.session; echo exit=$?; python -c "import headroom.telemetry.session as s; print('demo' in vars(s))"; HOME=$TMP/home pytest -q tests/test_telemetry_session_selfcheck.py; find $TMP/home -name install_id | wc -l
exit=0
False
============================== 1 passed in 7.48s ===============================
install_id files in temp HOME: 0
```

## Runtime Rollout Safety

- Rollout-managed feature(s): None.
- Minimum rollout channel: N/A; a dev-only self-check moves into tests.
- Stable/default behavior changed: No. No product code path called
`demo()`.
- Kill switch / disable path: N/A.
- Unsafe override required: No.
- Qualification impact: None.
- Rollback path: Revert this commit.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Screenshots (if applicable)

N/A

## Additional Notes

Part of maintainer-requested cleanup #4136 (dead code, duplication,
debuggability), split into small PRs for review.

The test is one long function on purpose: this PR is a move, not a
rewrite. Some of its assertions probably overlap
`tests/test_beacon_schema_v2.py`. Pruning that overlap can be a
follow-up.

Other modules have the same shipped `_demo()` pattern:
`cache/ttl_observations.py`, `transforms/thinking_compactor.py` and
`transforms/cold_prefix.py`. They are outside this PR's scope.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 08:59:51 -07:00