Repository navigation
feat(subscriptions): warn before the weekly limit, not after (abilityai/trinity-enterprise#434) - #2410
Conversation
…ai/trinity-enterprise#434) Alerts the operator when a subscription's 7-day window crosses a configurable threshold (default 75%), plus a fleet escalation when every subscription is saturated at once. Measuring the provider first deleted most of the specified design. A query against ent#433's history table shows `seven_day_resets_at` holding constant across five days of probes while utilization climbed 36->90, then stepping exactly +7 days: the weekly window is FIXED-with-reset, not rolling. So utilization is monotonic within a window, the specified hysteresis floor is dead code, and `resets_at` IS the window's identity — putting it in the alert id makes the id the whole state machine (edge-trigger, cross-worker dedup and re-arm via the sink's existing ON CONFLICT DO NOTHING), with no durable memo to leak, race, or clean up. `dashboard-grid-view.md` claimed these windows were rolling; that claim is corrected here. The threshold fires; the projection ranks. `projected_end = utilization_pct / fraction_of_window_elapsed` decides urgency from the operator's own burn rate rather than a configured time gap that is wrong for everyone — 75% at day 3 projects to 175% and is `high`, 75% with hours left projects to ~77% and is `low`. The alert is never withheld at the threshold. A new three-state `classify_headroom` (saturated | has_headroom | unassessable), because the binary pair cannot express "we could not tell". `_headroom_indicates_healthy` returns False for stale, rejected-token, transport error AND genuinely saturated, so #2396's docstring naming ent#434 as its consumer was wrong — the fleet escalation would have been blocked by exactly the condition it reports. Docstring corrected, body untouched (it feeds `resolve_rate_limited_now`; a behavioural edit there moves every LIMIT badge). Runs inside the existing #447 sweep, not a second loop — a second loop means a second lease over the same probe budget. Recovery probes FIRST so its zero-age snapshot is reused rather than floored out, in sibling try/excepts so an alert-path bug cannot stop the only mechanism that clears a stale LIMIT badge. Two false claims corrected on the way: the auto-refresh toggle no longer says probing happens "only while a dashboard is open" (untrue since #447), and the generic settings catch-all now runs `validate_ops_setting` — 20 ops keys previously accepted "abc" or "-40" verbatim there while `/ops/config` validated them. The fleet alert deliberately does NOT claim "auto-switch has nowhere to go": `select_best_alternative_subscription` reads no headroom at all, so that claim would be underived. Filed as #2409. Refs Abilityai/trinity-enterprise#434 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… the one real lever /validate-pr's config-packaging gate (#1056 class) caught both halves of a contradiction in the previous commit. `SAMPLE_INTERVAL_SECONDS` documented itself as "a constant, not an operator knob (#1644)" while reading `SUBSCRIPTION_SAMPLE_INTERVAL_SECONDS` from the environment — a var neither compose forwards. Since neither compose uses `env_file`, an unlisted var never reaches the container, so the read was inert AND contradicted its own comment. That combination is worse than either alone: it reads as configurable, is not, and invites a later "packaging fix" that creates exactly the knob the comment argues against. It is now literally a constant. `SUBSCRIPTION_SWEEP_CONCURRENCY` is the opposite case — genuinely fleet-size dependent, with no #1644 argument against it — so it is forwarded in both composes (prod launches standalone, so dev-only wiring would not carry) and documented in `.env.example`. Two tests pin the split. The first asserts on the CODE shape (`os.getenv("<name>"`), not the bare name: an unanchored match also hits the comment explaining the bug, which is the `debt:2026-08-24-source-regex-guard-governs-prose` trap where the previous fix degraded the prose to satisfy the regex. The guard now also asserts the comment SURVIVES. Refs Abilityai/trinity-enterprise#434 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…trinity-enterprise#434) /validate-pr's tiered-docs gate: ent#434 is a NEW CAPABILITY, and CLAUDE.md requires a `docs/memory/requirements/<area>.md` entry for one. The siblings set the precedent unambiguously — security.md already carries §20.5a (#471, the reading) and §20.5b (ent#433, the durable history) — so this is §20.5c and not a new area file. Records the things that must not be re-derived later: the OSS-core ruling and who made it, that the 7-day window was MEASURED fixed-with-reset rather than assumed (and what that deleted from the spec), why assessability needed a third state instead of the existing binary predicate, why the sample cadence reads no env var, and the claim the fleet escalation deliberately does not make. The requirements index maps areas to files rather than sections, and security.md is already listed, so it needs no row. Refs Abilityai/trinity-enterprise#434 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
…rs (review of #2410) Addresses dolho's review. C1 is the blocking one and it is real — reproduced before fixing. **C1 — the fleet alert could assert saturation over a partial denominator.** `fleet_verdict` correctly refuses the claim when any member is UNASSESSABLE, but its caller built the input as `{... for r in results if r.get("classification")}`. A member whose sampling raised carries `classification: None` BY DESIGN — that swallow is the isolation property protecting #447 — and a mid-cycle lease yield `break`s with `results` shorter than `subs`. Either way the blocking member was not UNASSESSABLE in the map, it was ABSENT, and absent members block nothing. On a 3-subscription instance that emitted "All 2 registered subscriptions are at or past 75%", with the per-subscription alerts suppressed by the fleet branch's early return, so the false claim was the only thing emitted. The map is now built from `subs`; a missing or None entry is UNASSESSABLE. That also makes the lease-yield path self-correcting. Three regression tests, including one that exercises a genuine partial sweep — my first attempt yielded the lease AFTER the final chunk, which drops nothing and passed against the unfixed code. The durable class is in learnings.md: a pure predicate can be right while its caller narrows the domain, and the narrowing looks like ordinary filtering. **I1 — the Settings control now exists.** The backend shipped with no client rendering `weekly_alert` at all, which left AC #1's "Settings-surfaced value" API-only and AC #4's "reports itself inactive ON THE SETTINGS SURFACE" reaching nobody — the exact #2217 failure this design cites throughout — while the toggle copy pointed at "the alert below". Threshold input + honest status line in SubscriptionsPanel.vue over BaseInput/BaseButton/InlineError. Decidable rules live in utils/headroomAlertSettings.js, not the SFC: vitest runs `environment: 'node'` with no mount harness, so a rule inside a component is one no test can reach (ent#392). 21 new frontend tests. **I2** the tier collapse at threshold >= 90 is now stated and pinned — measured, not assumed: at 90/95/99 only `crit` is reachable. **I3** the allowlist justification said "no agent input reaches any field" while the docstring I narrowed during /review admits agent-chosen names do; the docstring was right. **I4** `_env_int` degrades to the default with a WARNING instead of raising at import — the var is now advertised in .env.example, so a human types it (#1197). Proved with a real container import under a garbage value. **I5** the status read moved off the event loop, resolved once rather than twice so the toggle and the alert status cannot disagree. **I6** an unreadable subscription list is its own `count_unavailable` reason — `None == 0` is False, so it fell through every arm and reported `active: true`, claiming health from a failure in the one function whose job is naming why it is off. Refs Abilityai/trinity-enterprise#434 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Found by an operator testing the new control on a local instance: clicking Save
showed "Could not save the threshold. Check your connection and try again." The
connection was fine. The backend answered 200 to the identical request via curl.
The real cause was local and harmless — Vite hot-reloaded
`SubscriptionsPanel.vue` but not `stores/subscriptions.js` (no Trinity store
wires `acceptHMRUpdate`), so the new control was calling an action the live
Pinia instance did not have. The call threw a TypeError that never reached the
network, my catch swallowed it, and `e?.response?.data?.detail || <fallback>`
produced a confident diagnosis of something it had not observed. The operator
went looking for a network problem that did not exist.
`describeSaveFailure` now distinguishes what actually happened: the server's own
named reason, else a refusal with its status, else — and ONLY else — a genuine
no-response case, else a client-side failure that names itself and points at a
reload rather than the network.
Writing its tests surfaced a second latent bug in the same one-liner: FastAPI's
422 body is `{detail: [...]}`, an ARRAY, which is truthy — so a real validation
error would have rendered "[object Object]" into the banner. The type check on
`detail` closes that too.
Refs Abilityai/trinity-enterprise#434
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…#2280) CI's regression diff caught a genuine one: `test_2280_hosted_compose_parity` failed on all three head seeds and on none of the base seeds. `docker-compose.hosted.yml` landed on dev in #2280 while this branch was open — the pull-only twin of prod, with a guard asserting the two never drift except on build/image. This branch had already added `SUBSCRIPTION_SWEEP_CONCURRENCY` to dev and prod, so merging dev in produced exactly the drift that guard exists to catch. My own packaging check during /validate-pr had verified two compose files because the third did not exist when I ran it. Adds the var to the hosted compose and generalises my packaging test from "both composes" to the three STANDALONE deployment targets, with the exclusions named and justified: `gitea` and the two `override` files are overlays merged onto the base (`-f base -f overlay`) so they inherit its environment, `sibling` is the /verify-local harness, and `prod.enterprise` declares no backend environment block. Requiring the var in an overlay would be requiring it twice. A hardcoded list of three has the same rot the original two had, so a second test asserts no UNCLASSIFIED `docker-compose*.yml` exists — a genuinely new deployment target now fails loudly and must be classified deliberately rather than silently escaping the first list. Verified it fires by creating a fourth file. Also merges origin/dev (clean, no conflicts), which brings #2395 — the unit suite's 25→45 minute timeout headroom — so the shard that was cancelled twice on this PR should now be deterministic. Full local unit suite after the merge: 12637 passed, 1 failed — `test_1920`, which reproduces on a clean tree (it scans the private submodule; already a tracked follow-up). Refs Abilityai/trinity-enterprise#434 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
dolho
left a comment
There was a problem hiding this comment.
Re-review at a19dafe7
Independent pass: I re-derived each finding from the current source and re-ran my original repro rather than reading the commit subjects. C1 is fixed on both trigger paths, all six informational findings are addressed, and the new surface holds up.
C1 — the fleet claim over a partial denominator
Fixed at the right place. classifications is now built from subs — the roster — with a missing or None entry becoming UNASSESSABLE, so fleet_verdict gets the full membership it was always written to expect.
I re-ran the exact repro from my review (3 subscriptions, s3's sampling raises):
{'subscriptions': 3, 'alerts': {'fleet': False, 'subscriptions': 2},
'fleet_blocked_reason': 'unassessable_members'}
EMITTED: sub-headroom-s1-... | Subscription 'one' passed 75% of its weekly limit
EMITTED: sub-headroom-s2-... | Subscription 'two' passed 75% of its weekly limit
Better than the minimum I asked for: the false fleet claim is gone and the two genuine per-subscription alerts now fire, where before the early return suppressed them and the wrong claim was the only thing emitted.
I also checked the second trigger I named — the mid-cycle lease yield, which I could not exercise in the first review. Forcing the lease to drop after the first chunk:
{'probed': 4, 'subscriptions': 6, 'alerts': {'fleet': False, 'subscriptions': 4},
'fleet_blocked_reason': 'unassessable_members'}
Four of six swept, fleet claim blocked, the four real ones still alerted. Closed by construction rather than by a second patch, which is the right shape.
The informational six
| # | Verdict |
|---|---|
| I1 — copy promised a control that did not exist | fixed, properly. A real threshold control, a weekly_alert consumer, a store action, and the decidable parts in utils/headroomAlertSettings.js. "The alert below" is now true. |
I2 — TIER_WARN unreachable at threshold ≥ 90 |
documented, and argued rather than just noted — at 90%+ of a weekly window there is no gentle tier. Fair. |
| I3 — allowlist reason contradicted the module docstring | fixed — it now says agent-chosen names do reach the body but arrive sanitized and capped, and that it is the VOLUME an agent cannot drive. That is the accurate claim. |
I4 — unguarded int() at import |
fixed via _env_int, and the docstring names the exact reason ${VAR:-4} does not cover it (unset and empty, but not eight). |
| I5 — blocking calls on the event loop | fixed — the whole status build moved to asyncio.to_thread. |
I6 — active: true on an unreadable subscription list |
fixed with its own count_unavailable arm, and the comment says exactly why None == 0 let it fall through. |
The new surface
describeSaveFailure is a genuinely good addition and not one I asked for: the first version blamed the network for any thrown value, which sent an operator hunting a connection problem when the real cause was a stale store after HMR. Claiming an unobserved cause is worse than being vague, and the fix says so.
The SUBSCRIPTION_SWEEP_CONCURRENCY packaging catch is worth noting too — there are three deployment composes now, not two, because #2280 added the hosted twin while this branch was open. The parity guard caught it, which is the guard doing its job on a file that did not exist when the check was written.
One low finding, not blocking
INACTIVE_COPY has no guard tying it to the backend's reason set. All five reasons are covered today — I checked each one — but the parity test iterates Object.keys(INACTIVE_COPY), which is self-referential: it proves every key renders, not that every backend reason has a key. A sixth reason = "..." added to _weekly_alert_status_blocking would fail nothing.
The blast radius is small because the fallback is honest ('Inactive — this backend did not report a reason.') rather than silent or invented, which is why this is not blocking. If you want it closed, tests/unit/test_2086_model_catalog_parity.py is the in-repo precedent for a Python test validating a checked-in JS mirror.
Verification
118 pass across test_ent434, test_447, test_2396 and test_1677; 26 pass on the new headroomAlertSettings spec.
Verdict
Approving. The measurement that deleted the specified state machine was the right instinct in the first place, and the follow-up work fixed the one defect that mattered at its source rather than at the symptom.
Summary
seven_day_resets_atholding constant across five days of probes while utilization climbed 36→90, then stepping exactly +7 days. The weekly window is fixed-with-reset, not rolling — so utilization is monotonic within a window, the specified hysteresis floor is dead code, andresets_atis the window's identity.sub-headroom-{sid}-{reset-day}-{tier}— with edge-trigger, cross-worker dedup and re-arm falling out of the sink's existingON CONFLICT DO NOTHING. No durable memo to leak, race, or clean up ondelete_subscription.projected_end = utilization_pct / fraction_of_window_elapsedsets urgency from the operator's own burn rate rather than a configured time gap that is wrong for everyone: 75% at day 3 projects to 175% (high), 75% with hours left projects to ~77% (low). The alert is never withheld at the threshold.Evidence
Live
subscription_headroom_history, two windows:seven_day_resets_at2026-08-25T00:00:00Z2026-09-01T00:00:00Z(+7d exactly)Under a rolling window with continuous usage
resets_atwould have advanced. It did not move for five days.Three states, because two cannot express "we could not tell"
classify_headroom→saturated | has_headroom | unassessable._headroom_indicates_healthyreturnsFalsefor stale, rejected-token, transport error and a genuinely saturated subscription — so #2396's docstring naming ent#434 as its consumer was wrong: the fleet escalation would have been blocked by exactly the condition it exists to report. Docstring corrected, body untouched — it feedsresolve_rate_limited_now, so a behavioural edit there moves everyLIMITbadge (learnings 2026-08-25).The classifier keys on utilization, not window status:
allowed_warningis deliberately non-blocking (#2396), so a status-driven classifier would file a live 90% reading ashas_headroom.Where it runs
Inside the existing #447 sweep — not a second loop, which would mean a second lease over the same probe budget. Per subscription:
recover_probefirst, thenensure_reading+classify_headroom, in siblingtry/exceptblocks.Both orderings are load-bearing.
_probe_floor_okbounds probes at 60s/subscription, so whichever consumer probes first floors the other out — this way recovery's zero-age snapshot is reused rather than re-fetched; reversed,recover_probeanswers"floored"and #447 quietly stops working. The sibling split is the same argument in the failure direction.Two false claims corrected on the way
validate_ops_setting. 20 ops keys previously accepted"abc"or"-40"verbatim there while/ops/configvalidated them.What this deliberately does NOT claim
The fleet alert says what was measured, never "auto-switch has nowhere to go" —
select_best_alternative_subscriptionreads no headroom at all and will relocate agents onto a 99% subscription today. That is a real, separate bug: #2409 (P1), which consumes this classifier.Changes
services/subscription_headroom_alerts.pyservices/subscription_headroom_service.pyclassify_headroom(3-state),ensure_reading(one probe decision/sub/cycle),SAMPLE_INTERVAL_SECONDS; #2396 docstring correctedservices/subscription_recovery_service.pyrouters/subscriptions.pyPUT /settings/headroom-alert-threshold; auto-refresh GET carries the honestweekly_alertstatusrouters/settings.pyvalidate_ops_settingon the catch-allcanary/snapshot.py,operator_queue_service.py,test_1677_*SubscriptionsPanel.vuelearnings.md(×2)Test Plan
{probed, outcomes}return shape survives, which must pass in both states)test_1920private-submodule scan./cso --diff: no findings at the 8/10 gate; report atdocs/security-reports/cso-2026-08-26-ent434.mdCost
~24 probes/day/subscription (
max_tokens=1Haiku) — 4× less than a watched instance already spends through the 900s ambient refresh. Interval is a constant, not a knob (#1644); inherits #471's 60s floor and single-flight; stops entirely atthreshold_pct = 0.Residual
create_itemhas no UPDATE path, so a 75% row still reads 75% at 92% — the same residualretention_guarddocuments. The escalation is a separate, self-contained item.Refs abilityai/trinity-enterprise#434
🤖 Generated with Claude Code