Skip to content

feat: subscription usage observability + live headroom — 5h/7d windows, per-agent breakdown, pressure badges (#471) - #2316

Merged
vybe merged 10 commits into
devfrom
feature/471-subscription-usage
Aug 19, 2026
Merged

vybe merged 10 commits into
devfrom
feature/471-subscription-usage

Conversation

@trinity-ability

@trinity-ability trinity-ability commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Data-layer fixes first: failure events recorded BEFORE the auto-switch enabled gate (opted-out operators previously had permanently-zero observability); failure_kind persisted on subscription_rate_limit_events (the table conflated auth failures with 429s — dual-track migration, SQLite + Alembic 0040 (re-parented onto dev's 0039_operator_queue_addressed_to at merge)); SUB-004 dedup — a modern turn writes both an execution row and (for /chat + persisted /task) a cost-bearing chat message, so executions are now the sole cost/context/turn source (verified live: one $0.0687 turn previously reported as $0.137).
  • Live headroom (services/subscription_headroom_service.py): actual 5h/7d utilization % + reset times from the anthropic-ratelimit-unified-* headers of a max_tokens=1 micro-ping probe. Established empirically with a real stored setup token: GET /api/oauth/usage is 403-scope-dead for sk-ant-oat01- tokens (the closed-PR Show Claude subscription usage without metered cost #2170 mechanism); the header channel works. Click-to-refresh + default-ON ambient refresh behind a Settings toggle (15-min floor, demand-driven, single-flighted, fail-closed to observed-only when Redis is unreachable, stale-while-revalidate on the dashboard path). Every reading carries source: anthropic|observed + snapshot age; the DB-derived arm is always populated (the Show Claude subscription usage without metered cost #2170 inversion).
  • Surfaces: Settings subscriptions section extracted to SubscriptionsPanel.vue (partial feat(settings): complete tab refactor — extract remaining 4 tabs + URL rewrite on fallback #717/refactor: decompose oversized Vue views (Settings 3061 lines, MobileAdmin, Agents, AgentDetail, ...) #1030 paydown) with usage windows, failure-event warnings, live gauge + Refresh, lazy per-agent breakdown (cost-ranked — model-weighted by construction, resolving the 2026-07-28 model-mix research item); GET /api/agents/subscription-pressure batch endpoint (pure-DB visible set via the shared ent#384 helper, AgentAuthStatus vocabulary, explicit response_model) feeding AgentTile chips + AgentListPanel badges; Tier 0 ≈ API-equivalent cost relabel on AgentHeader + fleet surfaces, with the Step-0 zeros-fork (honest dash when cost is structurally unreported).

Rulings recorded at the build gate (2026-08-19, on-issue)

OSS-core by explicit decision (visibility free, governance paid — ent#166). Tier 4 auto-assign cut (SUB-003 covers the reactive per-agent case; bulk proactive migration is a real gap — filing separately). MCP tools + ~/.trinity/usage.json stay in trinity-enterprise#351. Ambient probing default-ON by operator ruling with cost disclosure on the toggle.

Test Plan

Release notes needed

Operators will see tiny platform-initiated messages (~1 token) in the Anthropic console when live headroom is enabled (default ON; Settings → Integrations toggle turns it off).

Fixes #471

🤖 Generated with Claude Code

claude added 7 commits August 19, 2026 14:05
…, Settings panel, pressure badges (#471)

Data layer: failure events recorded BEFORE the auto-switch enabled gate
(opted-out operators previously got a permanently-zero count); failure_kind
persisted (dual-track migration — the table conflated auth failures with
429s); iso_cutoff() in SUB-004's window queries (Invariant #16).

Headroom: services/subscription_headroom_service.py reads real 5h/7d
utilization + reset times from the anthropic-ratelimit-unified-* headers of
a minimal probe (verified against a stored setup token 2026-08-19; the
/api/oauth/usage endpoint is 403-scope-dead for setup tokens — the #2170
mechanism). Click-to-refresh + default-ON ambient refresh behind a Settings
toggle; 15-min floor; single-flighted; fail-closed to observed-only when
Redis is down. Every reading carries source: anthropic|observed + age; the
DB-derived block is always populated (the #2170 inversion).

Surfaces: Settings subscriptions section extracted to SubscriptionsPanel.vue
(partial #717/#1030 paydown) with usage windows, per-agent breakdown (ranked
by cost — model-weighted by construction), failure-event warnings, headroom
gauge + refresh; GET /api/agents/subscription-pressure batch endpoint
(pure-DB visible set via the shared ent#384 helper; AgentAuthStatus
vocabulary) feeding tile chips + list badges; Tier 0 ≈ API-equivalent cost
relabel on AgentHeader + fleet surfaces.

OSS-core by decision; Tier 4 auto-assign cut (SUB-003 covers the reactive
case; bulk migration filed separately); MCP tools stay in ent#351.

Fixes #471

Co-Authored-By: Claude Fable 5 <[email protected]>
…e-revalidate on the batch path, zeros-fork, snapshot TTL

- _read_snapshot returns (redis_ok, snapshot): an unreachable Redis no longer
  reads as 'no snapshot' (client object != reachable server), so ambient
  probing stays off during a Redis outage — the storm is closed for real
- pressure_states uses get_headroom(wait=False): ambient refreshes spawn as
  strong-ref background tasks; the 60s dashboard poll never blocks behind
  N x probe-timeout; probe timeout 30s -> 15s
- AgentHeader zeros-fork: subscription-funded agents whose lifetime cost is
  never reported render an honest dash, not a meaningless approx-USD 0.00
- headroom snapshots get a 7d TTL (self-clean after subscription delete)
- regression pins for both fail-closed behaviors; learnings entry added

Co-Authored-By: Claude Fable 5 <[email protected]>
… live probe)

utc_now_iso() emits microseconds; the seconds-only strptime made every
snapshot age None — read as 'refresh due' on every poll (only the 60s
in-process floor held) and 'never fresh' for the gauge and the provider
limited-verdict. fromisoformat with Z-normalization; regression-pinned.

Co-Authored-By: Claude Fable 5 <[email protected]>
… live in the demo)

A modern turn writes BOTH a schedule_executions row and (for /chat +
persisted /task, chat_persistence_service:104) a cost-bearing chat_messages
row; SUB-004's chat+exec SUM counted that turn's cost twice — verified live:
one sync-chat turn reported $0.137 for a $0.0687 run. Executions are the
canonical run record (status-as-projection #1082), so windows and the
per-agent breakdown now take cost/context/turn-count from executions only;
chat_messages contributes only output_tokens (which executions don't carry).
Pre-#1483 chat rows without paired executions fall outside any rolling
window. Realistic paired-row seeds + explicit counted-once pins.

Co-Authored-By: Claude Fable 5 <[email protected]>
…endpoint, SUB-004 dedup, Tier 0 relabel

Co-Authored-By: Claude Fable 5 <[email protected]>
…039→0040

dev merged 0039_operator_queue_addressed_to (ent#364, #2300) after this branch
was cut, forking the Alembic version-line (two heads off 0038_portal_chat_state
— upgrade head would apply zero revisions on PostgreSQL). rl_events_failure_kind
is renamed to 0040 with down_revision = 0039_operator_queue_addressed_to; the
SQLite MIGRATIONS registry keeps both entries in the same order. Doc references
updated (subscription-auto-switch.md, subscription-usage-tracking.md).

Verified: check_alembic_heads PASS (41 revisions, 1 head); schema-parity +
alembic guard suites 71 passed; test_471 + pingpong 55 passed.

Co-Authored-By: Claude Fable 5 <[email protected]>
@vybe vybe added the ui PR touches the frontend UI — triggers Playwright e2e tests label Aug 19, 2026
claude added 2 commits August 19, 2026 15:23
…he pollution linter

The tmp_db fixture popped db.connection/db.subscriptions bare to force a
re-import against the tmp DB path; the lint gate requires monkeypatch.delitem
(raising=False) so the original modules are restored at teardown. Verified:
tests/lint_sys_modules.py OK (no new violations), suite 26 passed.

Co-Authored-By: Claude Fable 5 <[email protected]>
…t the module edge

#471 extracted the pure-DB visible_agent_names into
services/agent_service/helpers.py (second consumer: the subscription-pressure
batch endpoint), so the guard's module-import ban on the skills router became
stale — it was a proxy written when the helper lived in the router and a
sentinel could not fire. The guard now pins what actually protects the
endpoint: the router's alias IS the shared helper (identity assert, so a local
re-implementation cannot dodge the source asserts), the helper reads
db.get_all_agent_metadata, and neither helper nor router references the
Docker-derived accessible_agent_names. Behavioural asserts unchanged.

Co-Authored-By: Claude Fable 5 <[email protected]>

@vybe vybe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Validated: all 4 required contexts green, full pytest matrix green on head and base, pg-migrations + schema-parity + prod-image-smoke pass. Fixes #471 resolves same-repo so status auto-promotion fires on merge. Approving for merge.

The #471 guard added in 059b0ab asserted `router_mod._visible_agent_names
is helpers.visible_agent_names`. That passes in isolation and failed on all
three full-suite seed orders (head 12345/67890/99999), while base stayed
green — a deterministic new failure, not a flake.

Cause: `router_mod` is the module object bound at ITS import, but the
`from services.agent_service import helpers` inside the test resolves at call
time. The suite contains tests that purge `sys.modules` (the reason CI
carries a dedicated sys.modules-pollution lint), after which `helpers` is
re-imported from the same path under the same key — so `is` compares two
distinct function objects. The CI failure shows exactly that: two
`visible_agent_names` at different addresses, both from
`src/backend/services/agent_service/helpers.py`.

Pin the ORIGIN instead (`__module__` + `__qualname__`). That is stable across
re-import and still defeats what identity was there to defeat: a router-local
`def _visible_agent_names` reads `routers.skills` and fails the assert
(verified by negative control — "got routers.skills._visible_agent_names").

Test-only; no product change.
@vybe

vybe commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

Merge was blocked by a real regression diff failure, not the cancelled base seed — flagging it here since it was invisible in the per-job conclusions.

All six pytest seed jobs reported success, but the head XMLs each carried Fail: 1; the gate is regression diff, which correctly flagged:

❌ New failures introduced by HEAD (1)
- [F] test_384_skill_assignments_read::test_access_set_is_db_derived_not_docker_derived

Deterministic on all three head orders (12345/67890/99999), green on base — a genuine new failure. It passed in isolation (12/12), which is what made it look like flake.

Cause — the guard added in 059b0ab asserted object identity:

assert router_mod._visible_agent_names is _helpers.visible_agent_names

router_mod is the module object bound at its import, while the from services.agent_service import helpers inside the test resolves at call time. The suite contains tests that purge sys.modules (the reason CI carries a dedicated sys.modules-pollution lint); after a purge, helpers is re-imported from the same path under the same key, so is compares two distinct function objects. The CI output shows exactly that — two visible_agent_names at different addresses, both from src/backend/services/agent_service/helpers.py.

Reproduced deterministically: with a purge between import and assert, the identity assert is False while the origin assert is True.

Fix (f8b2920, test-only) — pin the origin (__module__ + __qualname__) instead. Stable across re-import, and it still defeats what identity was there to defeat: a router-local def _visible_agent_names reads routers.skills. Verified by negative control — swapping the import for a local re-implementation fails with got routers.skills._visible_agent_names.

The product refactor itself is sound: one definition (services/agent_service/helpers.py:206), two consumers (routers/skills.py, routers/agents.py).

@vybe
vybe merged commit 01ef4b8 into dev Aug 19, 2026
34 of 36 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ui PR touches the frontend UI — triggers Playwright e2e tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants