Repository navigation
feat(cost): cycle outlook engine (#1137) - #1160
Conversation
Pure-function projection from typed SubscriptionPlan (#1132) + per-day usage to a frozen CycleOutlook record: cycle window, basis-keyed cycle-to-date, burn rate, projected end-of-cycle total, quota pressure (or QuotaPressureMissing reason='no_quota_configured' when the plan carries no quota), overage rows (actual + projected with metered cost), explicit projection method tag (linear / trailing-7d-mean / eom-naive), coverage ratio with missing-day list, and confidence bounded by plan confidence * coverage. No I/O; #1136 wires daily-usage sourcing, surfaces consume from there.
|
Warning Rate limit exceeded
You’ve run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (4)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d59d7ae655
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| end_day = window.end.date() | ||
| for row in usage: | ||
| if row.day < start_day or row.day > end_day: | ||
| continue |
There was a problem hiding this comment.
Exclude cycle end date from grouped usage
cycle_for defines billing windows as half-open [start, end), but _group_by_basis currently accepts row.day == end_day because it only filters row.day > end_day. Any usage recorded on the end date (which is the next cycle boundary day) is incorrectly counted into the current cycle, inflating cycle-to-date totals/projections and potentially triggering spurious overage output.
Useful? React with 👍 / 👎.
## Summary Wires the typed `CycleOutlook` engine from #1137 (PR #1160) through the user surfaces: a new `polylogue cost outlook` CLI subcommand, a new `cost_outlook` MCP tool, and a new `Polylogue.cost_outlook(...)` async facade method. ## Problem AC of #1138: "cost outlook surface in CLI / MCP / web reader" and "CLI JSON contracts are deterministic; plain output clearly labels estimates and uncertainty". The existing `polylogue cost` rendered a flat per-plan rollup over `compute_usage_outlook` and there was no MCP tool exposing the new typed cycle outlook (only `cost_rollups` and `session_costs` were available). Subscription-equivalent and API-equivalent figures could collapse into one unlabelled `cost` number, and a plan without a `cycle_anchor_day` had no way to be surfaced as "no cycle window" rather than fabricated. ## Solution - `polylogue/cli/commands/cost.py`: converted `cost` to a `click.Group`. New `cost outlook --plan <name> --method {linear,trailing-7d-mean,eom-naive} --format {plain,json}` renders the typed `CycleOutlook`. JSON output is canonical and exercised by contract tests. Plain output prefixes USD figures with `~`, labels the USD basis as `USD (API-equivalent)`, labels quota figures by their basis (`credits` / `tokens` / etc.), surfaces `QuotaPressureMissing` as `Quota pressure: not configured`, and always prints the "subscription quota math is non-authoritative" caveat. The legacy flat rollup is preserved as `cost rollup` for the #803 cost-tracking pipeline. - `polylogue/cli/click_command_registration.py`: `cost` registered as a lazy group via `_GROUP_ATTRS`. - `polylogue/mcp/server_insight_tools.py`: new `cost_outlook(plan, method)` special tool. `PlanLookupError`, unknown `ProjectionMethod`, and "no cycle anchor" surface as typed error envelopes (`code` = `not_found` / `invalid_argument` / `no_cycle_window`, with `tool` and `detail` fields populated). - `polylogue/api/insights.py`: new `Polylogue.cost_outlook(plan_name, *, now=None, method=...)` async method. Resolves plans via `polylogue.cost.plans.resolve_plan(name, user_rows=load_polylogue_config().subscription_plans)`, fetches materialized `SessionCostInsight`s, folds them to daily USD usage via the new `polylogue.cost.aggregation.session_costs_to_daily_usd` helper, and projects through `build_cycle_outlook`. - `polylogue/cost/aggregation.py` (new): pure-function bridge aggregating `SessionCostInsight` -> per-day USD `DailyUsage` rows. Skips rows without a parseable `created_at` or with non-positive `total_usd` so coverage stays honest. Output is deterministically sorted for stable snapshots. - Tool wiring: `cost_outlook` added to `EXPECTED_TOOL_NAMES` (tests/infra/mcp.py), classified as `single_object` in `TOOL_CONTRACT` (tests/unit/mcp/test_envelope_contracts.py), added to MCP tool-schema witness, registered in topology projection. ## Verification Local commands actually run on this branch: - `pytest tests/unit/cli/test_cost_outlook_cli.py tests/unit/mcp/test_cost_outlook_tool.py -q` -> `13 passed`. - `pytest tests/unit/cli/ tests/unit/mcp/ tests/unit/cost/ tests/unit/api/ -q --ignore=tests/integration` -> `1408 passed` (4 pre-existing failures in `tests/unit/cli/test_check.py` and `tests/unit/cli/test_terminal_snapshots.py::test_check_output_snapshot` are inherited dirty baseline unrelated to this scope; confirmed by running them against `git stash`'d HEAD). - `devtools verify --quick` -> `exit_code: 0`, all gates green including `mypy --strict`, `ruff`, `render-all --check`, `verify-topology`, `verify-manifests`, `verify-witness-lifecycle`. - `pytest tests/unit/cli/test_json_envelope_contract.py::TestCostJsonContract tests/unit/mcp/test_tool_schema_witness.py -q` -> `5 passed` (legacy contract migrated to `cost rollup --format json`, MCP tool-schema witness regenerated for the new tool). ## Acceptance criteria - [x] `polylogue cost outlook --plan ... --format json` emits the full `CycleOutlook` payload deterministically; snapshot/contract tests pinned in `test_cost_outlook_cli.py::TestCostOutlookJsonContract`. - [x] Plain output labels estimates and uncertainty; quota basis and "not configured" cases surfaced explicitly (`TestCostOutlookPlainContract`). - [x] MCP `cost_outlook` tool returns the same typed payload as the CLI with parameter validation; tool-contract tests in `test_cost_outlook_tool.py`. - [x] Subscription-equivalent and API-equivalent fields never merge into one unlabelled `cost` number on any surface (verified by both CLI plain renderer test and MCP contract test against a mixed `credits` + `usd` payload). - [x] Unknown / unpriced / estimated rows are visible in both surfaces with an explicit reason (`QuotaPressureMissing` serialisation, `no_cycle_window` error envelope, plain "not configured" line). - [x] `devtools render-all --check` clean (CLI reference, verification catalog, topology projection, test-quality workflow regenerated). - [x] Docs caveat: plain renderer prints "Subscription quota math is non-authoritative; vendor pricing and quotas change without notice."; CHANGELOG entry under `Unreleased`. ## Non-goals (intentionally deferred) - Web reader cost panel — tracked separately under #1122. - Dashboard / TUI cost surface — out of scope per the issue body (#848 etc.). - Dedicated `polylogue insights cost` page in `docs/insights.md` — the new CLI subcommand is fully documented by `devtools render-cli-reference` output and the help text; a curated narrative page can land as a follow-up if the renderings prove insufficient. Closes #1138
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
Summary
Pure projection engine that turns a typed
SubscriptionPlan(#1132) plus a per-day usage sequence into a frozenCycleOutlookrecord covering cycle window, basis-keyed cycle-to-date totals, burn rate, projected end-of-cycle total, quota pressure, overage rows, projection method tag, coverage ratio, missing-day list, and confidence band.Problem
#1137 carries forward #870 ACs (cycle range, basis, confidence, missing-data coverage, projection method, quota forecasting, overage detection) for the subscription cost surface. Today
cli/commands/cost.pyshows a static--planrollup with an anomaly multiplier but no cycle, no projection, no overage. The pure projection substrate is the missing prerequisite for #1136 / surface child PRs.Solution
New
polylogue/cost/outlook.py(no I/O, no storage):CycleOutlook,CycleWindow,QuotaPressure,QuotaPressureMissing,OverageRow,DailyUsage,ProjectionMethod(frozenpydantic.BaseModels,extra="forbid").build_cycle_outlook(plan, daily_usage, *, now, method=linear)returnsNonefor plans without acycle_anchor_day— surfaces must show "no cycle window" rather than fabricate one.quotaandquota_basis; otherwiseQuotaPressureMissing(reason='no_quota_configured')andoverage_rows = ().linearandeom-naiveextrapolate from elapsed-day burn;trailing-7d-meanadds the cycle-to-date sum to the trailing-window mean over the remaining days only (preserves historical baseline).nowhas crossed the next midnight — a partial day in progress is not a coverage gap, but its usage still contributes to cycle-to-date.plan.confidence * coverage_ratio, bounded in[0, 1].Topology projection regenerated to register the new substrate file (
docs/plans/topology-target.yaml,docs/topology-status.md).Verification
Tests cover the AC list: linear projection fixture, missing-day coverage drop, plan-without-quota, plan-with-quota crossing threshold mid-cycle (realized breach), projected-only breach, multi-basis cycle, zero-usage cycle, end-of-cycle boundary, trailing-mean method tagging, frozen-model rejection.
Closes #1137. Ref #870, #995.