mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-24 19:52:53 +08:00
feat(telemetry): split beacon sessions by harness, model and day (#4881)
## Description
After backfilling the Beacon corpus, six questions about Oct 19 – Nov 14
could not be answered from what the client sends:
1. **Which harness, for a quarter of sessions.** 228,441 of 933,044
schema-v2 sessions (36.2M turns) carry no client. 30.2M of those turns
came through `/v1/compress`.
2. **Tokens and savings per harness.** `clients` has turn counts only;
34,553 sessions mix harnesses and cannot be divided.
3. **Harness version.** Only the Headroom version is reported.
4. **Tokens and savings per model.** `models` is a list, so savings
cannot be priced.
5. **Real installs versus churned ids.** Linux proxies show 19,916
installs for about the traffic of 4,258 on macOS.
6. **Per-day figures.** Always-on proxies report one session that grows
for weeks (34% of savings sat in multi-day sessions).
## Type of Change
- [ ] Bug fix (non-breaking change that fixes an issue)
- [x] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)
## Changes Made
All client changes are in `headroom/telemetry/session.py`, from data the
outcome funnel and the HTTP middleware already have. No handler changes.
`schema_version` stays 2; the fields are additive.
| Field | Content |
|---|---|
| `client_usage` | Per-harness rows of `n, original, saved, tool_saved,
output, cache_read, cache_write, cache_write_inferred, cache_write_5m,
cache_write_1h, uncached`. Covers every turn: unclaimed turns are
`via_mcp`, `via_compress_api` or `unidentified`. |
| `model_usage` | The same columns per public model id; anything else
pools into `other`. |
| `client_versions` | `(client, version, n)` from the User-Agent, e.g.
`claude_code 2.1.311`. Request counts, not turns. |
| `install` | `age_days` (id file mtime), `container`, `ci`. |
| rollover | A session at least 12h old is closed by the first request
on a later UTC day (`ended: "rollover"`). Sessions that merely run past
midnight are untouched. |
- `clients` and `models` are unchanged.
- `deploy/beacon/worker.js` learns the new keys and their nested shapes.
- `headroom/proxy/auth_policy.py` gains
`client_version_from_user_agent`; `headroom/proxy/server.py` calls it
for every POST.
**Pricing a usage row (review feedback).** Every column is the raw
per-turn counter and sums to its session total. Where a provider reports
no write count, Headroom infers one as input minus cached; those are the
same tokens as `uncached`. `cache_write_inferred` is that part, so
billed input is `uncached + cache_read + (cache_write -
cache_write_inferred)`, the rule `CostTracker.record` applies, and
`cache_write_5m` / `cache_write_1h` give the TTL split.
`test_a_usage_row_prices_inferred_cache_writes_the_way_the_cost_tracker_does`
covers the 1000-not-2000 case.
**Privacy.**
- Harness names in the new fields are checked against a closed list
(`_KNOWN_CLIENTS`), because `classify_client` returns the caller's
`X-Client` header as typed. Unknown names become `other`. The existing
`clients` field has the same gap and is not changed here.
- A version is sent only if it directly follows a known harness prefix
and is one to three numeric parts.
- The Worker holds the new string leaves to a slug or version pattern;
its test asserts injected text, hostnames and wrong types are dropped.
## Testing
- [x] Unit tests pass (`pytest`) — the suites listed below, not the
whole repository
- [x] Linting passes (`ruff check .`) — on the changed files
- [ ] Type checking passes (`mypy headroom`) — 8 errors in
`headroom/cache/prefix_tracker.py` and `headroom/ccr/mcp_server.py`,
identical on `main`
- [x] New tests added for new functionality
- [x] Manual testing performed
### Test Output
```text
$ python -m pytest tests/test_beacon_schema_v2.py tests/test_telemetry_session_selfcheck.py \
tests/test_telemetry.py tests/test_beacon_gzip.py tests/test_auth_policy.py tests/test_header_isolation.py -q
============================= 165 passed in 11.75s =============================
$ node deploy/beacon/test-rollup.mjs
ok
$ ruff check <changed files> && ruff format --check <changed files>
All checks passed!
```
Not run: the full Python suite. 3 tests in
`tests/test_proxy_telemetry_env.py` fail the same way on `main` without
this change.
## Real Behavior Proof
- Environment: macOS (darwin arm64), Python 3.12.13, this branch's proxy
(`service.version 0.45.0-dev`) with an isolated
`HEADROOM_WORKSPACE_DIR`, `HEADROOM_BEACON=on`,
`HEADROOM_TELEMETRY_ENDPOINT=http://127.0.0.1:8791/v1/logs`. Receiver:
this branch's `deploy/beacon/worker.js` `fetch()` served by a 30-line
Node HTTP listener with the R2 binding replaced by a directory.
Providers: Anthropic `claude-haiku-4-5-20251001` and OpenAI
`gpt-4o-mini`, live.
- Exact command / steps:
1. `node receiver.mjs deploy/beacon/worker.js ./r2 8791`
2. `headroom proxy --port 8799` (from this branch)
3. Four POSTs through the proxy: two `/v1/messages` with `User-Agent:
claude-cli/2.1.311 (external, cli)`, one `/v1/messages` with
`User-Agent: curl/8.4.0`, one `/v1/chat/completions` with `User-Agent:
codex-cli/0.45.0`.
4. `kill -INT` the proxy so it sends its closing report.
- Observed result: the three Anthropic calls returned 200 (the second
and third were served by Headroom's response cache); the OpenAI call
returned 429 from the provider (account quota). The receiver logged
`POST /v1/logs -> 204` and stored one object,
`sessions/dt=2026-11-15/hh=15/<uuid>.json`. Its new fields, as stored
after the allowlist:
```json
"session": {"seq": 0, "duration_s": 5, "turns": 4, "ended": "shutdown", "final": true}
"tokens": {"original": 28, "input": 28, "output": 4, "saved": 0, "cache_read": 0, "cache_write": 14, "uncached": 28}
"clients": [{"client": "claude", "n": 1}, {"client": "claude_code", "n": 2}, {"client": "codex", "n": 1}]
"client_usage": [
{"client": "claude", "n": 1, "original": 0, "saved": 0, "tool_saved": 0, "output": 0, "cache_read": 0, "cache_write": 0, "cache_write_inferred": 0, "cache_write_5m": 0, "cache_write_1h": 0, "uncached": 0},
{"client": "claude_code", "n": 2, "original": 14, "saved": 0, "tool_saved": 0, "output": 4, "cache_read": 0, "cache_write": 0, "cache_write_inferred": 0, "cache_write_5m": 0, "cache_write_1h": 0, "uncached": 14},
{"client": "codex", "n": 1, "original": 14, "saved": 0, "tool_saved": 0, "output": 0, "cache_read": 0, "cache_write": 14, "cache_write_inferred": 14, "cache_write_5m": 0, "cache_write_1h": 0, "uncached": 14}]
"model_usage": [
{"model": "claude-haiku-4-5-20251001", "n": 3, "original": 14, "output": 4, "cache_write": 0, "cache_write_inferred": 0, "uncached": 14, "...": "other columns 0"},
{"model": "gpt-4o-mini", "n": 1, "original": 14, "output": 0, "cache_write": 14, "cache_write_inferred": 14, "uncached": 14, "...": "other columns 0"}]
"client_versions": [{"client": "claude_code", "version": "2.1.311", "n": 2}, {"client": "codex", "version": "0.45.0", "n": 1}]
"install": {"age_days": 0, "container": false, "ci": false}
```
Both tables' `n` sum to `session.turns` (4) and `original` to
`tokens.original` (28). The OpenAI row is the reviewed case:
`cache_write` 14 is entirely inferred, and `uncached + cache_read +
(cache_write - cache_write_inferred)` is 14, not 28. Nothing from the
User-Agent beyond harness and version reached the stored object.
- Not tested:
- The Worker on Cloudflare itself (Workers runtime, real R2).
`worker.js` ran under Node.
- A successful OpenAI turn, a Responses API turn with a reported write,
and Anthropic turns with cache reads or 5m/1h writes (covered by unit
tests only).
- `via_compress_api`, `via_mcp` and `unidentified` labels, a session
mixing harnesses on one model, and the 12-hour rollover (unit tests
only).
- Codex over WebSocket, which never passes the HTTP middleware and so
reports no version.
- gzip transport (`HEADROOM_BEACON_GZIP=1`) and a heartbeat (`ended:
"active"`); only the closing report was observed.
- Linux, Windows, containers and CI.
## Runtime Rollout Safety
- Rollout-managed feature(s): none; the beacon is not behind a rollout
channel.
- Minimum rollout channel: n/a
- Stable/default behavior changed: yes, for installs with the beacon on
(the default). The session report carries four more keys (about 5 KB
more per report for a typical session with gzip off), and a session at
least 12 hours old now ends at the first request on a later UTC day, so
always-on installs report about one session per day instead of one that
grows for weeks. No request-path behaviour changes.
- Kill switch / disable path: `HEADROOM_BEACON=off`,
`HEADROOM_TELEMETRY=off`, `DO_NOT_TRACK=1` or offline mode disable all
of it, as before. Server side, removing a key from `ALLOWED_KEYS` in
`deploy/beacon/worker.js` drops that field for every install without a
client release.
- Unsafe override required: no
- Qualification impact: none known.
- Rollback path: revert this PR. Rows already stored keep the extra
keys; readers use `union_by_name`.
- Deploy order: the Worker must be deployed before a client release that
sends these fields, or they are dropped on arrival. Production is still
the 2026-10-08 Worker build.
## 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 — none
made; `docs/content/docs/security-model.mdx` and `api-reference.mdx`
describe beacon fields and have not been updated
- [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 — for the
suites listed under Testing
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)
## Additional Notes
- `client_versions` misses WebSocket sessions.
- `/v1/compress` traffic is now visible but still not attributed to the
integration that called it.
- Tool-call kinds, tool-definition size, compaction and subagent turns
are not included: they need the request body in each handler and a
privacy design for tool names.
- An earlier review suggested splitting rollover into its own PR since
it changes what a session row means; it is kept here.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Co-authored-by: JD Davis <mxjerrett@gmail.com>
This commit is contained in:
co-authored by
Claude Fable 5.2
JD Davis
parent
00436a8b11
commit
ac932eb7c4
@@ -430,6 +430,14 @@ if (dir) {
|
||||
full.errors = { count: 1, by_status: { 429: 1 } };
|
||||
full.strata = [{ dim: 'arm', value: 'treatment', n: 2 }];
|
||||
full.config = [{ key: 'mode', value: 'token' }];
|
||||
const usage = {
|
||||
n: 2, original: 9, saved: 3, tool_saved: 1, output: 2, cache_read: 4, cache_write: 1,
|
||||
cache_write_inferred: 0, cache_write_5m: 1, cache_write_1h: 0, uncached: 4,
|
||||
};
|
||||
full.client_usage = [{ client: 'claude_code', ...usage }, { client: 'via_compress_api', ...usage }];
|
||||
full.model_usage = [{ model: 'claude-haiku-4-5', ...usage }];
|
||||
full.client_versions = [{ client: 'claude_code', version: '2.1.311', n: 2 }];
|
||||
full.install = { age_days: 12, container: false, ci: false };
|
||||
full.routing = { decisions: 3, by_model: [{ model: 'claude-haiku-4-5', n: 3 }], min_prefix: 1024 };
|
||||
|
||||
/** One OTLP record through fetch(); returns what would be written to R2. */
|
||||
@@ -471,6 +479,11 @@ if (dir) {
|
||||
injected.session.ended = { nested: 'object where a slug belongs' };
|
||||
injected.routing.note = 'free text with spaces';
|
||||
injected.trajectory.kinds = 'see attached transcript';
|
||||
injected.client_usage[0].prompt = 'x'; // unknown key in a usage row
|
||||
injected.client_usage[1].client = 'Acme Corp Billing'; // not a harness slug
|
||||
injected.client_versions[0].version = '2.1.311-host.internal'; // not a release number
|
||||
injected.install.hostname = 'build-7';
|
||||
injected.install.age_days = 'twelve';
|
||||
const hostile = [...resourceAttrs.filter((a) => a.key !== 'headroom.stack'),
|
||||
{ key: 'headroom.stack', value: any({ cwd: '/home/me' }) }];
|
||||
const { resource: badResource, ...dropped } = await store(injected, hostile);
|
||||
@@ -478,6 +491,9 @@ if (dir) {
|
||||
const expected = structuredClone(full);
|
||||
delete expected.session.ended;
|
||||
delete expected.trajectory.kinds;
|
||||
delete expected.client_usage[1].client;
|
||||
delete expected.client_versions[0].version;
|
||||
delete expected.install.age_days;
|
||||
expected.config.push({ key: 'endpoint' });
|
||||
expected.strata.push({ dim: 'arm', n: 1 });
|
||||
assert.deepEqual(dropped, expected, 'a nested field outside the allowlist was stored');
|
||||
|
||||
@@ -101,6 +101,17 @@ const ALLOWED_KEYS = [
|
||||
// Allowlisted, slug-validated configuration, so the corpus can tell
|
||||
// "compression underperformed" from "compression was switched off".
|
||||
'config',
|
||||
// The session's tokens split by harness and by model. `clients` and `models`
|
||||
// only say who took part, so a session that mixed two could not be divided
|
||||
// or priced. `client_usage` covers every turn: traffic with no identified
|
||||
// harness is a row of its own instead of a gap.
|
||||
'client_usage',
|
||||
'model_usage',
|
||||
// The harness's own release, numeric parts only.
|
||||
'client_versions',
|
||||
// Age of the install id in days, and whether it runs in a container or CI
|
||||
// job: separates a returning user from an id minted on every run.
|
||||
'install',
|
||||
];
|
||||
|
||||
// Resource attributes we keep. Same rule: allowlist, not denylist.
|
||||
@@ -130,6 +141,16 @@ const MAP = Symbol('map');
|
||||
const mapOf = (spec) => ({ [MAP]: spec });
|
||||
const nums = (...keys) => Object.fromEntries(keys.map((k) => [k, 'num']));
|
||||
|
||||
// A harness name: the client only sends ones from a closed list, so hold the
|
||||
// field to that shape instead of the wider 'str'.
|
||||
const SLUG = /^[a-z][a-z0-9_]{0,31}$/;
|
||||
// One turn-and-token row of `client_usage` / `model_usage`: _USAGE_FIELDS in
|
||||
// session.py.
|
||||
const USAGE = nums(
|
||||
'n', 'original', 'saved', 'tool_saved', 'output', 'cache_read', 'cache_write',
|
||||
'cache_write_inferred', 'cache_write_5m', 'cache_write_1h', 'uncached'
|
||||
);
|
||||
|
||||
const NESTED = {
|
||||
schema_version: 'num',
|
||||
session: {
|
||||
@@ -187,6 +208,10 @@ const NESTED = {
|
||||
errors: { count: 'num', by_status: mapOf('num') },
|
||||
strata: [{ dim: 'str', value: 'str', n: 'num' }],
|
||||
config: [{ key: 'str', value: 'str' }],
|
||||
client_usage: [{ client: SLUG, ...USAGE }],
|
||||
model_usage: [{ model: 'str', ...USAGE }],
|
||||
client_versions: [{ client: SLUG, version: /^\d{1,4}(?:\.\d{1,4}){0,2}$/, n: 'num' }],
|
||||
install: { age_days: 'num', container: 'bool', ci: 'bool' },
|
||||
};
|
||||
|
||||
// A key allowed at the top but given no shape would be dropped in full. Fail
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import enum
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@@ -120,6 +121,27 @@ def classify_client_signals(signals: AuthSignals, *, default: str | None = None)
|
||||
return default
|
||||
|
||||
|
||||
# Up to three numeric parts, and nothing numeric after them: a date stamp or a
|
||||
# four-part number is not cut down into a release that never existed.
|
||||
_UA_VERSION_RE = re.compile(r"\d{1,4}(?:\.\d{1,4}){0,2}(?![.\d])")
|
||||
|
||||
|
||||
def client_version_from_user_agent(user_agent: str) -> tuple[str, str] | None:
|
||||
"""``(harness, version)`` from a User-Agent such as ``claude-cli/2.1.311``.
|
||||
|
||||
Only the numeric release that directly follows a known harness prefix in
|
||||
:data:`CLIENT_UA_MAP` is returned, so nothing else in the header can ride
|
||||
along. ``None`` when the harness is unknown or carries no numeric version.
|
||||
"""
|
||||
ua_lower = user_agent.lower()
|
||||
for needle, name in CLIENT_UA_MAP:
|
||||
at = ua_lower.find(needle)
|
||||
if at >= 0:
|
||||
match = _UA_VERSION_RE.match(ua_lower, at + len(needle))
|
||||
return (name, match.group(0)) if match else None
|
||||
return None
|
||||
|
||||
|
||||
def is_codex_responses_path(path: str) -> bool:
|
||||
"""Return True for OpenAI Responses endpoints and their subpaths."""
|
||||
return any(root == path or path.startswith(root + "/") for root in CODEX_RESPONSES_PATHS)
|
||||
|
||||
@@ -124,6 +124,7 @@ from headroom.providers.registry import (
|
||||
from headroom.proxy import runtime_env
|
||||
from headroom.proxy.audit import is_auditable_path, record_admin_action
|
||||
from headroom.proxy.auth_mode import CLIENT_UA_MAP, should_stamp_codex_client
|
||||
from headroom.proxy.auth_policy import client_version_from_user_agent
|
||||
from headroom.proxy.background_compression import BackgroundCompressor
|
||||
from headroom.proxy.budget_basis_policy import resolve_estimated_basis_policy
|
||||
from headroom.proxy.buffered_ccr_response import DEFAULT_BUFFERED_CCR_GRACE_SECONDS
|
||||
@@ -222,6 +223,7 @@ from headroom.subscription.tracker import (
|
||||
)
|
||||
from headroom.telemetry import get_telemetry_collector
|
||||
from headroom.telemetry.beacon import beacon_off_reason, is_beacon_enabled, is_telemetry_enabled
|
||||
from headroom.telemetry.session import record_client_version
|
||||
from headroom.telemetry.toin import get_toin
|
||||
from headroom.transforms import (
|
||||
CacheAligner,
|
||||
@@ -4461,6 +4463,17 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
|
||||
proxy.metrics.record_stack(stack)
|
||||
except Exception:
|
||||
logger.debug("record_stack failed", exc_info=True)
|
||||
if method == "POST":
|
||||
# The harness's own release, for the anonymous beacon. Every route,
|
||||
# not only /v1/: Gemini, Bedrock and ChatGPT-auth Codex live
|
||||
# elsewhere. Only the middleware sees the User-Agent; nothing but a
|
||||
# known harness name and a numeric version leaves this call.
|
||||
try:
|
||||
harness = client_version_from_user_agent(headers.get("user-agent", ""))
|
||||
if harness:
|
||||
record_client_version(*harness)
|
||||
except Exception:
|
||||
logger.debug("record_client_version failed", exc_info=True)
|
||||
try:
|
||||
response = await call_next(request)
|
||||
except asyncio.CancelledError:
|
||||
|
||||
@@ -91,6 +91,23 @@ type and its arithmetic, and the folding for the new signals is isolated in
|
||||
counted in ``errors`` and deliberately NOT folded into ``failures``, which
|
||||
has been 5xx-only in every row of the corpus and must stay that way.
|
||||
|
||||
Later additions, same version (they are additive too, and a reader tells
|
||||
them apart by presence):
|
||||
|
||||
* ``client_usage`` / ``model_usage`` — the session's tokens split by harness
|
||||
and by model. ``clients`` and ``models`` only say who took part; a session
|
||||
that mixed two harnesses, or Haiku with Opus, could not be divided or priced.
|
||||
``client_usage`` covers every turn, so traffic with no identified harness is
|
||||
a visible row instead of a silent gap.
|
||||
* ``client_versions`` — the harness's own release (``claude-code 2.1.311``).
|
||||
Harness releases change request shape far more often than Headroom does.
|
||||
* ``install`` — how old this install id is, and whether it lives in a
|
||||
container or CI job. Separates a returning user from an id that is minted
|
||||
fresh on every run.
|
||||
* A session that is at least half a day old is closed by the first request on
|
||||
a later UTC day (``ended: "rollover"``), so an always-on proxy reports about
|
||||
one row per day instead of a single total that grows for weeks.
|
||||
|
||||
Everything added is a counter, a ratio, or a slug from a vocabulary that is
|
||||
closed in code. Two things are still refused on principle: anything derived
|
||||
from prompt or file content (which is why ``turn_id`` and TOIN's
|
||||
@@ -347,6 +364,80 @@ _WASTE_KEYS = (
|
||||
_STRATUM_TREATMENT = "output_shaper:stratum:"
|
||||
_STRATUM_CONTROL = "output_shaper:control:"
|
||||
|
||||
# Per-turn token columns of `client_usage` and `model_usage`, in order. `n` is
|
||||
# turns. Every column is the raw per-turn counter, so each sums to its session
|
||||
# total.
|
||||
#
|
||||
# To price a row, do what `CostTracker.record` does: where a provider reports
|
||||
# no write count, Headroom infers one as input minus cached, and those are the
|
||||
# same tokens as `uncached`, never billed as a write. `cache_write_inferred`
|
||||
# is that part, so billed input is
|
||||
# uncached + cache_read + (cache_write - cache_write_inferred)
|
||||
# and `cache_write_5m` / `cache_write_1h` split the billed writes by TTL, which
|
||||
# changes their rate.
|
||||
_USAGE_FIELDS = (
|
||||
"n",
|
||||
"original",
|
||||
"saved",
|
||||
"tool_saved",
|
||||
"output",
|
||||
"cache_read",
|
||||
"cache_write",
|
||||
"cache_write_inferred",
|
||||
"cache_write_5m",
|
||||
"cache_write_1h",
|
||||
"uncached",
|
||||
)
|
||||
# Rows per usage table before the rest pool into "other". A session rarely
|
||||
# sees more than three harnesses or five models; every row is eleven numbers on
|
||||
# a payload that is re-sent every five minutes, and `_fit_to_wire` cannot shed
|
||||
# these rows, so the cap is what bounds them.
|
||||
MAX_USAGE_ROWS = 8
|
||||
MAX_CLIENT_VERSIONS = 16
|
||||
# Every harness name `client_usage` and `client_versions` may carry. The value
|
||||
# comes from `classify_client`, which returns the caller's own `X-Client`
|
||||
# header when one is sent, so a shape check alone would put whatever a caller
|
||||
# typed there on the wire with token volumes attached. Names outside this set
|
||||
# pool into "other". Mirrors `CLIENT_UA_MAP` in headroom/proxy/auth_policy.py
|
||||
# and `_KNOWN_WRAP_AGENTS` in context.py; duplicated because this package does
|
||||
# not import `headroom.proxy` (see `record_stack`), and a test holds them equal.
|
||||
_KNOWN_CLIENTS = frozenset(
|
||||
{
|
||||
"aider",
|
||||
"anthropic_cli",
|
||||
"antigravity",
|
||||
"claude",
|
||||
"claude_code",
|
||||
"claude_vscode",
|
||||
"codex",
|
||||
"copilot",
|
||||
"cursor",
|
||||
"droid",
|
||||
"grok_build",
|
||||
"omp",
|
||||
"openclaw",
|
||||
"opencode",
|
||||
"strands",
|
||||
"zed",
|
||||
}
|
||||
)
|
||||
# Labels for turns no harness claimed, so `client_usage` sums to
|
||||
# `session.turns`. Measured on the corpus: a quarter of sessions carried no
|
||||
# harness at all, and most of those turns came through /v1/compress.
|
||||
_CLIENT_VIA_MCP = "via_mcp"
|
||||
_CLIENT_VIA_COMPRESS = "via_compress_api"
|
||||
_CLIENT_UNIDENTIFIED = "unidentified"
|
||||
# A harness release as it appears in a User-Agent: up to three numeric parts.
|
||||
# Anything else (a build hash, a hostname) is not a version and is not sent.
|
||||
_VERSION_RE = re.compile(r"^\d{1,4}(?:\.\d{1,4}){0,2}$")
|
||||
# A session at least this old is closed by the first request on a later UTC
|
||||
# day. Long enough that an afternoon of work running past midnight UTC stays
|
||||
# one session; short enough that the pieces of an always-on proxy, which start
|
||||
# a few seconds after midnight, are old enough to close at the next one. The
|
||||
# first piece can therefore span two dates; every later one is a single day.
|
||||
ROLLOVER_MIN_AGE_S = 12 * 3600.0
|
||||
_INSTALL_AGE_CAP_DAYS = 9999
|
||||
|
||||
# Environment variables whose values may be reported, by name. An allowlist,
|
||||
# never a dump of the environment: a variable absent from this tuple cannot
|
||||
# reach the wire whatever it holds, and every value that does is put through
|
||||
@@ -412,6 +503,10 @@ _staged_shapes: dict[tuple[str, str], list[int]] = {}
|
||||
# tool-output shape slug -> [events, tokens_in, tokens_out]. The structural
|
||||
# descriptor only — never TOIN's `structure_hash`. See `record_tool_shape`.
|
||||
_staged_tool_shapes: dict[str, list[int]] = {}
|
||||
# (harness, version) -> requests. Staged because only the HTTP middleware sees
|
||||
# the User-Agent, and it runs before any outcome exists. See
|
||||
# `record_client_version`.
|
||||
_staged_client_versions: dict[tuple[str, str], int] = {}
|
||||
|
||||
|
||||
def _pct(numerator: float, denominator: float) -> float:
|
||||
@@ -471,6 +566,76 @@ def _bump(counter: dict[str, int], key: str, *, cap: int = MAX_SHAPES) -> None:
|
||||
counter[key] = counter.get(key, 0) + 1
|
||||
|
||||
|
||||
def _tool_saved(tags: Any) -> int:
|
||||
"""Tool-schema tokens saved on one turn. These live only in tags — see the
|
||||
same arithmetic in emit_request_outcome, which feeds the local dashboard."""
|
||||
total = 0
|
||||
if isinstance(tags, dict):
|
||||
for tag in ("tool_search_deferred_tokens", "turn_hook_tools_saved_tokens"):
|
||||
try:
|
||||
total += int(tags.get(tag, 0) or 0)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return total
|
||||
|
||||
|
||||
def _add_usage(table: dict[str, list[int]], key: str, values: tuple[int, ...]) -> None:
|
||||
"""Add one turn to a usage table. Past the cap, new keys pool into "other".
|
||||
|
||||
Pooled rather than dropped, unlike `_bump`: these tables exist to split the
|
||||
session's totals, and a split that silently loses turns stops adding up.
|
||||
"""
|
||||
if key not in table and len(table) >= MAX_USAGE_ROWS:
|
||||
key = "other"
|
||||
row = table.setdefault(key, [0] * len(values))
|
||||
for index, value in enumerate(values):
|
||||
row[index] += value
|
||||
|
||||
|
||||
def _known_client(value: Any) -> str:
|
||||
"""A harness name from `_KNOWN_CLIENTS`, else "other"."""
|
||||
slug = _client_slug(value)
|
||||
return slug if slug in _KNOWN_CLIENTS else "other"
|
||||
|
||||
|
||||
def _usage_rows(label: str, table: dict[str, list[int]]) -> list[dict[str, Any]]:
|
||||
return [
|
||||
{label: key, **dict(zip(_USAGE_FIELDS, row, strict=True))}
|
||||
for key, row in sorted(table.items())
|
||||
]
|
||||
|
||||
|
||||
def _install_facts() -> dict[str, Any]:
|
||||
"""Age of this install id and where it is running. Three closed values.
|
||||
|
||||
The corpus could not tell a user who came back from an id minted fresh on
|
||||
every container start: Linux proxies showed five times the installs of
|
||||
macOS for the same traffic. `age_days` is how long ago the id file was
|
||||
written, so it needs no new state and resets with the id. It is 0 when no
|
||||
id is kept on disk (stateless mode, or a file that could not be written),
|
||||
which is what an id minted per run looks like.
|
||||
"""
|
||||
from headroom import paths
|
||||
|
||||
age_days = 0
|
||||
if not paths.process_is_stateless():
|
||||
try:
|
||||
written = _install_id_path().stat().st_mtime
|
||||
except OSError:
|
||||
pass # no id file: age stays 0
|
||||
else:
|
||||
age_days = min(max(int((time.time() - written) // 86400), 0), _INSTALL_AGE_CAP_DAYS)
|
||||
return {
|
||||
"age_days": age_days,
|
||||
"container": bool(
|
||||
os.environ.get("KUBERNETES_SERVICE_HOST")
|
||||
or os.path.exists("/.dockerenv")
|
||||
or os.path.exists("/run/.containerenv")
|
||||
),
|
||||
"ci": os.environ.get("CI", "").strip().lower() in ("1", "true", "yes"),
|
||||
}
|
||||
|
||||
|
||||
def _turn_kind(*, cached: bool, status: int, passthrough: bool, attempted: int, saved: int) -> str:
|
||||
"""Classify one turn into the closed `_TURN_KINDS` alphabet.
|
||||
|
||||
@@ -769,6 +934,10 @@ class _Session:
|
||||
strata_turn_kind: dict[str, int] = field(default_factory=dict)
|
||||
strata_input_bucket: dict[str, int] = field(default_factory=dict)
|
||||
strata_tools: dict[str, int] = field(default_factory=dict)
|
||||
# label -> one count per `_USAGE_FIELDS` column.
|
||||
client_usage: dict[str, list[int]] = field(default_factory=dict)
|
||||
model_usage: dict[str, list[int]] = field(default_factory=dict)
|
||||
client_versions: dict[tuple[str, str], int] = field(default_factory=dict)
|
||||
|
||||
def observe(self, name: str, value: float) -> None:
|
||||
"""Record one sample into a named histogram."""
|
||||
@@ -1184,6 +1353,23 @@ class _Session:
|
||||
"config": [
|
||||
{"key": key, "value": value} for key, value in sorted(_config_snapshot().items())
|
||||
],
|
||||
# The session's tokens split by harness and by model. Each table's
|
||||
# `n` sums to `session.turns` and each token column to its total in
|
||||
# `tokens`, so either one divides the session without residue.
|
||||
# `clients` and `models` above are left exactly as they were.
|
||||
"client_usage": _usage_rows("client", self.client_usage),
|
||||
"model_usage": _usage_rows("model", self.model_usage),
|
||||
# Requests by harness release. Counted at the HTTP layer, so `n` is
|
||||
# requests, not turns: it includes ones that never became a turn,
|
||||
# and a request that lands just before a session closes is counted
|
||||
# in whichever session folds next. WebSocket sessions never pass
|
||||
# that layer and are absent. Read it as "which releases, roughly
|
||||
# how much", not as a split of the session.
|
||||
"client_versions": [
|
||||
{"client": client, "version": version, "n": count}
|
||||
for (client, version), count in sorted(self.client_versions.items())
|
||||
],
|
||||
"install": _install_facts(),
|
||||
}
|
||||
|
||||
|
||||
@@ -1223,6 +1409,17 @@ class SessionAggregator:
|
||||
if live is not None and now - live.last_seen >= self._idle_s:
|
||||
pending.append(live.payload("idle"))
|
||||
live = None
|
||||
# An always-on proxy never goes idle, so its one session grew
|
||||
# for weeks and a day's activity could only be recovered by
|
||||
# differencing heartbeats. Closing at the day boundary makes
|
||||
# each row one day's work.
|
||||
if (
|
||||
live is not None
|
||||
and now - live.started >= ROLLOVER_MIN_AGE_S
|
||||
and now // 86400 != live.started // 86400
|
||||
):
|
||||
pending.append(live.payload("rollover"))
|
||||
live = None
|
||||
if live is None:
|
||||
live = _Session(
|
||||
sid=secrets.token_hex(8),
|
||||
@@ -1345,14 +1542,9 @@ def _fold(sess: _Session, outcome: Any, now: float, source: str = "proxy") -> No
|
||||
# problem, not a compression problem, and the two are indistinguishable
|
||||
# from the token counts alone.
|
||||
tags = get("tags", None) or {}
|
||||
tool_saved = _tool_saved(tags)
|
||||
if isinstance(tags, dict):
|
||||
# Tool-schema savings live only in tags — see the same arithmetic in
|
||||
# emit_request_outcome, which feeds the local dashboard.
|
||||
for tag in ("tool_search_deferred_tokens", "turn_hook_tools_saved_tokens"):
|
||||
try:
|
||||
sess.tool_saved_tokens += int(tags.get(tag, 0) or 0)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
sess.tool_saved_tokens += tool_saved
|
||||
for tag in _REASON_TAGS:
|
||||
if tag in tags:
|
||||
key = f"{tag.removesuffix('_reason')}:{_safe_slug(tags[tag])}"
|
||||
@@ -1377,7 +1569,7 @@ def _fold(sess: _Session, outcome: Any, now: float, source: str = "proxy") -> No
|
||||
# `_fold` before the caller's heartbeat check and costs a whole emission,
|
||||
# which is a v1 consequence for a v2 fault.
|
||||
try:
|
||||
_fold_extra(sess, get, now, prev_seen, tags, status)
|
||||
_fold_extra(sess, get, now, prev_seen, tags, status, source, tool_saved)
|
||||
except Exception:
|
||||
logger.debug("telemetry: v2 fold failed", exc_info=True)
|
||||
|
||||
@@ -1389,6 +1581,8 @@ def _fold_extra(
|
||||
prev_seen: float | None,
|
||||
tags: Any,
|
||||
status: int,
|
||||
source: str = "proxy",
|
||||
tool_saved: int = 0,
|
||||
) -> None:
|
||||
"""Fold the schema-v2 signals. Additive by construction.
|
||||
|
||||
@@ -1409,6 +1603,42 @@ def _fold_extra(
|
||||
passthrough = is_dict_tags and "passthrough_reason" in tags
|
||||
cached = bool(get("from_response_cache", False))
|
||||
|
||||
# -- usage by harness and by model --------------------------------------
|
||||
# The same per-turn quantities `_fold` adds to the session totals, so each
|
||||
# table sums back to them. First in this function for that reason: a fault
|
||||
# in a section below must not leave a turn counted in `tokens` and missing
|
||||
# here.
|
||||
cache_write = int(get("cache_write_tokens") or 0)
|
||||
turn = (
|
||||
1,
|
||||
original,
|
||||
saved,
|
||||
tool_saved,
|
||||
int(get("output_tokens") or 0),
|
||||
int(get("cache_read_tokens") or 0),
|
||||
cache_write,
|
||||
cache_write if get("cache_inferred", False) else 0,
|
||||
int(get("cache_write_5m_tokens") or 0),
|
||||
int(get("cache_write_1h_tokens") or 0),
|
||||
int(get("uncached_input_tokens") or 0),
|
||||
)
|
||||
client = get("client", None)
|
||||
if client:
|
||||
label = _known_client(client)
|
||||
elif source == "mcp":
|
||||
label = _CLIENT_VIA_MCP
|
||||
elif get("provider", "") == "compress":
|
||||
label = _CLIENT_VIA_COMPRESS
|
||||
else:
|
||||
label = _CLIENT_UNIDENTIFIED
|
||||
_add_usage(sess.client_usage, label, turn)
|
||||
# A model id no public registry vouches for can carry an org name (see
|
||||
# `_public_model`), so it is pooled, never sent.
|
||||
_add_usage(sess.model_usage, _public_model(str(get("model", "") or "")) or "other", turn)
|
||||
for version_key, count in _drain_staged_client_versions().items():
|
||||
if version_key in sess.client_versions or len(sess.client_versions) < MAX_CLIENT_VERSIONS:
|
||||
sess.client_versions[version_key] = sess.client_versions.get(version_key, 0) + count
|
||||
|
||||
# -- distributions ------------------------------------------------------
|
||||
sess.observe("turn_tokens", original)
|
||||
sess.observe("overhead_ms", float(get("overhead_ms", 0.0) or 0.0))
|
||||
@@ -2176,6 +2406,37 @@ class BeaconCompressionObserver:
|
||||
record_compression(strategy, original_tokens, compressed_tokens)
|
||||
|
||||
|
||||
def record_client_version(client: Any, version: Any) -> None:
|
||||
"""Beacon entry point for one request's harness release.
|
||||
|
||||
Called from the proxy's HTTP middleware, the only place that sees the
|
||||
User-Agent. Both parts are validated here rather than trusted: the harness
|
||||
must slug cleanly and the version must be numeric, so a User-Agent that
|
||||
carries anything else contributes nothing.
|
||||
"""
|
||||
from headroom.telemetry.beacon import is_beacon_enabled
|
||||
|
||||
if not is_beacon_enabled():
|
||||
return
|
||||
slug, text = _known_client(client), str(version or "")
|
||||
if slug == "other" or not _VERSION_RE.match(text):
|
||||
return
|
||||
key = (slug, text)
|
||||
with _staged_lock:
|
||||
if key in _staged_client_versions or len(_staged_client_versions) < MAX_CLIENT_VERSIONS:
|
||||
_staged_client_versions[key] = _staged_client_versions.get(key, 0) + 1
|
||||
|
||||
|
||||
def _drain_staged_client_versions() -> dict[tuple[str, str], int]:
|
||||
"""Take every staged (harness, version) request count."""
|
||||
with _staged_lock:
|
||||
if not _staged_client_versions:
|
||||
return {}
|
||||
drained = dict(_staged_client_versions)
|
||||
_staged_client_versions.clear()
|
||||
return drained
|
||||
|
||||
|
||||
def _drain_staged_strategies() -> dict[str, list[int]]:
|
||||
"""Take everything staged since the last drain. Caller merges it."""
|
||||
with _staged_lock:
|
||||
|
||||
@@ -12,7 +12,9 @@ from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -84,6 +86,10 @@ V2_TOP = {
|
||||
"errors",
|
||||
"strata",
|
||||
"config",
|
||||
"client_usage",
|
||||
"model_usage",
|
||||
"client_versions",
|
||||
"install",
|
||||
}
|
||||
|
||||
|
||||
@@ -135,11 +141,13 @@ def _clean_staging():
|
||||
S._staged_stacks.clear()
|
||||
S._staged_shapes.clear()
|
||||
S._staged_tool_shapes.clear()
|
||||
S._staged_client_versions.clear()
|
||||
yield
|
||||
S._staged_strategies.clear()
|
||||
S._staged_stacks.clear()
|
||||
S._staged_shapes.clear()
|
||||
S._staged_tool_shapes.clear()
|
||||
S._staged_client_versions.clear()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -900,7 +908,252 @@ def test_the_worst_case_body_actually_sent_fits_the_oldest_receiver():
|
||||
for index in range(600)
|
||||
]
|
||||
payload = emit(*outcomes)
|
||||
# The usage tables and versions cannot be shed, so fill them to their caps
|
||||
# with nine-digit counters: the body must still fit.
|
||||
big = dict.fromkeys(S._USAGE_FIELDS, 987_654_321)
|
||||
names = sorted(S._KNOWN_CLIENTS)
|
||||
payload["client_usage"] = [{"client": names[i], **big} for i in range(S.MAX_USAGE_ROWS + 1)]
|
||||
payload["model_usage"] = [
|
||||
{"model": f"claude-opus-4-8-2026010{i}", **big} for i in range(S.MAX_USAGE_ROWS + 1)
|
||||
]
|
||||
payload["client_versions"] = [
|
||||
{"client": names[i % len(names)], "version": f"1234.1234.{1000 + i}", "n": 987_654_321}
|
||||
for i in range(S.MAX_CLIENT_VERSIONS)
|
||||
]
|
||||
saved = payload["tokens"]["saved"]
|
||||
sent = S._fit_to_wire(payload, S.resource_attributes(), compress=False)
|
||||
assert len(sent) <= 64 * 1024, f"sent {len(sent):,} B, over the 64KB receiver cap"
|
||||
assert payload["tokens"]["saved"] == saved, "trimming cost a v1 counter"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# usage by harness and model, harness versions, install facts, daily rollover
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_usage_tables_split_the_session_totals_without_residue():
|
||||
"""`client_usage` and `model_usage` exist to divide a mixed session, so each
|
||||
must add back up to the session: every turn lands in exactly one row,
|
||||
including the turns no harness claimed."""
|
||||
|
||||
class Codex(Outcome):
|
||||
client = "codex"
|
||||
model = "gpt-4o-mini"
|
||||
tags = {"tool_search_deferred_tokens": 70}
|
||||
|
||||
class Gateway(Outcome):
|
||||
client = None
|
||||
provider = "compress"
|
||||
model = "ft:gpt-4o:acme-corp:internal-bot:abc123"
|
||||
|
||||
class Anonymous(Outcome):
|
||||
client = None
|
||||
|
||||
payload = emit(Outcome(), Outcome(), Codex(), Gateway(), Anonymous())
|
||||
by_client = {r["client"]: r for r in payload["client_usage"]}
|
||||
assert {name: r["n"] for name, r in by_client.items()} == {
|
||||
"claude_code": 2,
|
||||
"codex": 1,
|
||||
"via_compress_api": 1,
|
||||
"unidentified": 1,
|
||||
}
|
||||
assert by_client["codex"]["tool_saved"] == 70
|
||||
for table in ("client_usage", "model_usage"):
|
||||
rows = payload[table]
|
||||
assert sum(r["n"] for r in rows) == payload["session"]["turns"], table
|
||||
for column, total in (
|
||||
("original", "original"),
|
||||
("saved", "saved"),
|
||||
("tool_saved", "tool_saved"),
|
||||
("output", "output"),
|
||||
("cache_read", "cache_read"),
|
||||
("cache_write", "cache_write"),
|
||||
("uncached", "uncached"),
|
||||
):
|
||||
assert sum(r[column] for r in rows) == payload["tokens"][total], (table, column)
|
||||
assert sum(r["cache_write_5m"] for r in rows) == payload["cache"]["write_5m"], table
|
||||
assert sum(r["cache_write_1h"] for r in rows) == payload["cache"]["write_1h"], table
|
||||
# A fine-tune id carries an org name: pooled, never sent.
|
||||
assert "acme" not in json.dumps(payload)
|
||||
assert {r["model"] for r in payload["model_usage"]} == {"gpt-4o", "gpt-4o-mini", "other"}
|
||||
|
||||
|
||||
def test_a_usage_row_prices_inferred_cache_writes_the_way_the_cost_tracker_does():
|
||||
"""Where a provider reports no write count, Headroom infers one as input
|
||||
minus cached. Those are the same tokens as `uncached` and are never billed
|
||||
as a write, so a row has to say how much of its `cache_write` is inferred
|
||||
or a reader double-counts them: 1000 billed tokens would price as 2000."""
|
||||
|
||||
class InferredWrite(Outcome):
|
||||
provider = "openai"
|
||||
model = "gpt-4o"
|
||||
provider_input_tokens = 1000
|
||||
cache_read_tokens = 0
|
||||
cache_write_tokens = 1000
|
||||
cache_write_5m_tokens = 0
|
||||
cache_write_1h_tokens = 0
|
||||
uncached_input_tokens = 1000
|
||||
cache_inferred = True
|
||||
|
||||
class ReportedWrite(Outcome):
|
||||
model = "gpt-4o-mini" # cache_write 100 = 80 at 5m + 20 at 1h, all billed
|
||||
|
||||
def billed_input(row: dict[str, Any]) -> int:
|
||||
return (
|
||||
row["uncached"] + row["cache_read"] + row["cache_write"] - row["cache_write_inferred"]
|
||||
)
|
||||
|
||||
rows = {r["model"]: r for r in emit(InferredWrite(), ReportedWrite())["model_usage"]}
|
||||
assert billed_input(rows["gpt-4o"]) == 1000
|
||||
assert rows["gpt-4o"]["cache_write_inferred"] == 1000
|
||||
assert billed_input(rows["gpt-4o-mini"]) == 400 + 500 + 100
|
||||
assert (rows["gpt-4o-mini"]["cache_write_5m"], rows["gpt-4o-mini"]["cache_write_1h"]) == (
|
||||
80,
|
||||
20,
|
||||
)
|
||||
|
||||
|
||||
def test_an_mcp_turn_is_labelled_not_dropped():
|
||||
payload = emit(
|
||||
S._McpCompression(
|
||||
original_tokens=800, attempted_input_tokens=800, optimized_tokens=200, tokens_saved=600
|
||||
),
|
||||
source="mcp",
|
||||
)
|
||||
assert [(r["client"], r["n"], r["saved"]) for r in payload["client_usage"]] == [
|
||||
("via_mcp", 1, 600)
|
||||
]
|
||||
|
||||
|
||||
def test_usage_tables_pool_overflow_instead_of_losing_turns():
|
||||
table: dict[str, list[int]] = {}
|
||||
for index in range(S.MAX_USAGE_ROWS + 9):
|
||||
S._add_usage(table, f"model{index}", (1, 10))
|
||||
assert len(table) == S.MAX_USAGE_ROWS + 1
|
||||
assert table["other"] == [9, 90]
|
||||
assert sum(row[0] for row in table.values()) == S.MAX_USAGE_ROWS + 9
|
||||
|
||||
|
||||
def test_a_caller_supplied_client_name_never_reaches_the_usage_tables(beacon_on):
|
||||
"""`classify_client` returns the caller's `X-Client` header as typed, so the
|
||||
name is checked against a closed list, not just for shape."""
|
||||
|
||||
class Named(Outcome):
|
||||
client = "acme-corp-billing"
|
||||
|
||||
S.record_client_version("acme-corp-billing", "1.2.3")
|
||||
payload = emit(Named(), Outcome())
|
||||
assert [(r["client"], r["n"]) for r in payload["client_usage"]] == [
|
||||
("claude_code", 1),
|
||||
("other", 1),
|
||||
]
|
||||
assert payload["client_versions"] == []
|
||||
|
||||
|
||||
def test_the_known_client_list_covers_every_harness_the_proxy_can_name():
|
||||
from headroom.proxy.auth_policy import CLIENT_UA_MAP
|
||||
from headroom.telemetry.context import _KNOWN_WRAP_AGENTS
|
||||
|
||||
named = {S._client_slug(name) for _, name in CLIENT_UA_MAP} | set(_KNOWN_WRAP_AGENTS)
|
||||
assert named <= S._KNOWN_CLIENTS, sorted(named - S._KNOWN_CLIENTS)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("user_agent", "expected"),
|
||||
[
|
||||
("claude-cli/2.1.311 (external, cli)", ("claude-code", "2.1.311")),
|
||||
("Corp-Wrapper/9 codex-cli/0.45.0-alpha.3", ("codex", "0.45.0")),
|
||||
("claude-cli/dev-build", None),
|
||||
("curl/8.4.0", None),
|
||||
# Over-long or four-part numbers are not releases; never cut one down.
|
||||
("claude-cli/20261115", None),
|
||||
("claude-cli/1.2.3456789", None),
|
||||
("claude-cli/10.0.3.7", None),
|
||||
],
|
||||
)
|
||||
def test_user_agent_version_parser(user_agent, expected):
|
||||
from headroom.proxy.auth_policy import client_version_from_user_agent
|
||||
|
||||
assert client_version_from_user_agent(user_agent) == expected
|
||||
|
||||
|
||||
def test_only_a_numeric_release_of_a_known_harness_is_staged(beacon_on):
|
||||
S.record_client_version("claude-code", "2.1.311")
|
||||
S.record_client_version("claude-code", "2.1.311")
|
||||
S.record_client_version("claude-code", "2.1.311-internal.example.com")
|
||||
payload = emit(Outcome())
|
||||
assert payload["client_versions"] == [{"client": "claude_code", "version": "2.1.311", "n": 2}]
|
||||
|
||||
|
||||
def test_install_facts_report_age_and_ephemerality(tmp_path, monkeypatch):
|
||||
id_file = tmp_path / "install_id"
|
||||
id_file.write_text("a" * 32)
|
||||
ten_days_ago = time.time() - 10 * 86400 - 60
|
||||
os.utime(id_file, (ten_days_ago, ten_days_ago))
|
||||
monkeypatch.setattr(S, "_install_id_path", lambda: id_file)
|
||||
monkeypatch.delenv("HEADROOM_STATELESS", raising=False)
|
||||
monkeypatch.setenv("CI", "true")
|
||||
facts = emit(Outcome())["install"]
|
||||
assert facts["age_days"] == 10 and facts["ci"] is True
|
||||
assert set(facts) == {"age_days", "container", "ci"}
|
||||
|
||||
# Stateless: the id is random per process, so there is no age to report.
|
||||
monkeypatch.setenv("HEADROOM_STATELESS", "1")
|
||||
facts = emit(Outcome())["install"]
|
||||
assert facts["age_days"] == 0
|
||||
|
||||
|
||||
def test_a_long_running_session_is_closed_at_the_utc_day_boundary():
|
||||
"""An always-on proxy never idles, so its session used to grow for weeks.
|
||||
It now ends at the day boundary; a session that merely runs past midnight
|
||||
is left whole."""
|
||||
day = 86400.0
|
||||
rows: list[dict[str, Any]] = []
|
||||
agg = S.SessionAggregator(rows.append, idle_s=10 * day, flush_s=100 * day)
|
||||
start = 20 * day + 3600.0 # 01:00 UTC
|
||||
agg.record(Outcome(), now=start)
|
||||
agg.record(Outcome(), now=start + 22 * 3600.0) # 23:00, same day
|
||||
assert rows == []
|
||||
agg.record(Outcome(), now=21 * day + 5.0) # just past midnight, 23h old
|
||||
assert [(r["session"]["ended"], r["session"]["turns"]) for r in rows] == [("rollover", 2)]
|
||||
agg.record(Outcome(), now=22 * day + 5.0) # the next piece closes a day later
|
||||
assert [r["session"]["ended"] for r in rows] == ["rollover", "rollover"]
|
||||
assert rows[0]["session"]["id"] != rows[1]["session"]["id"]
|
||||
|
||||
# A clock that steps backwards must not close anything.
|
||||
agg.record(Outcome(), now=21 * day + 5.0)
|
||||
assert len(rows) == 2
|
||||
|
||||
# Started at 20:00 UTC and still going at 01:00: five hours old, untouched.
|
||||
rows.clear()
|
||||
evening = S.SessionAggregator(rows.append, idle_s=10 * day, flush_s=100 * day)
|
||||
evening.record(Outcome(), now=30 * day + 20 * 3600.0)
|
||||
evening.record(Outcome(), now=31 * day + 3600.0)
|
||||
assert rows == []
|
||||
|
||||
|
||||
def test_the_proxy_reports_the_harness_release_it_was_called_by(beacon_on):
|
||||
"""The wiring, end to end: a real request's User-Agent reaches the payload
|
||||
as a harness and a release, and nothing else from the header does."""
|
||||
from tests.test_header_isolation import _make_anthropic_app
|
||||
|
||||
client, _ = _make_anthropic_app()
|
||||
response = client.post(
|
||||
"/v1/messages",
|
||||
headers={
|
||||
"x-api-key": "test-key",
|
||||
"anthropic-version": "2023-06-01",
|
||||
"user-agent": "claude-cli/2.1.311 (external, cli) host-a.internal",
|
||||
},
|
||||
json={
|
||||
"model": "claude-sonnet-4-6",
|
||||
"max_tokens": 16,
|
||||
"messages": [{"role": "user", "content": "hi"}],
|
||||
},
|
||||
)
|
||||
assert response.status_code == 200, response.text
|
||||
rows: list[dict[str, Any]] = []
|
||||
S.get_session_aggregator().flush_all(emit=rows.append)
|
||||
assert rows[-1]["client_versions"] == [{"client": "claude_code", "version": "2.1.311", "n": 1}]
|
||||
assert rows[-1]["client_usage"][0]["client"] == "claude_code"
|
||||
assert "host-a" not in json.dumps(rows[-1])
|
||||
|
||||
Reference in New Issue
Block a user