Skip to content

feat(cost): cycle outlook engine (#1137) - #1160

Merged
Sinity merged 1 commit into
masterfrom
feature/feat/cost-cycle-outlook-engine
May 17, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/feat/cost-cycle-outlook-engine

Conversation

@Sinity

@Sinity Sinity commented May 17, 2026

Copy link
Copy Markdown
Owner

Summary

Pure projection engine that turns a typed SubscriptionPlan (#1132) plus a per-day usage sequence into a frozen CycleOutlook record 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.py shows a static --plan rollup 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 (frozen pydantic.BaseModels, extra="forbid").
  • build_cycle_outlook(plan, daily_usage, *, now, method=linear) returns None for plans without a cycle_anchor_day — surfaces must show "no cycle window" rather than fabricate one.
  • Quota pressure and overage rows only emit when the plan declares both quota and quota_basis; otherwise QuotaPressureMissing(reason='no_quota_configured') and overage_rows = ().
  • Projection method is an explicit tag and re-exposed on the outlook. linear and eom-naive extrapolate from elapsed-day burn; trailing-7d-mean adds the cycle-to-date sum to the trailing-window mean over the remaining days only (preserves historical baseline).
  • A day is "expected" only once now has crossed the next midnight — a partial day in progress is not a coverage gap, but its usage still contributes to cycle-to-date.
  • Confidence = plan.confidence * coverage_ratio, bounded in [0, 1].
  • Breach day uses the realized running total when usage actually crosses quota in-cycle; falls back to linear extrapolation from current burn when only projected to breach before cycle end.

Topology projection regenerated to register the new substrate file (docs/plans/topology-target.yaml, docs/topology-status.md).

Verification

nix develop -c pytest tests/unit/cost/test_outlook.py -q   # 15 passed
nix develop -c mypy polylogue/cost/outlook.py tests/unit/cost/test_outlook.py  # 0 errors
nix develop -c ruff check polylogue/cost/outlook.py tests/unit/cost/test_outlook.py  # All checks passed
nix develop -c devtools verify --quick                      # exit_code: 0

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.

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.
@coderabbitai

coderabbitai Bot commented May 17, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Sinity has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 37 minutes and 24 seconds before requesting another review.

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 6bbc70f3-8820-40df-ad40-6ec5a5ec12ee

📥 Commits

Reviewing files that changed from the base of the PR and between 96c6b99 and d59d7ae.

📒 Files selected for processing (4)
  • docs/plans/topology-target.yaml
  • docs/topology-status.md
  • polylogue/cost/outlook.py
  • tests/unit/cost/test_outlook.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/cost-cycle-outlook-engine

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@Sinity
Sinity merged commit e843c16 into master May 17, 2026
3 checks passed
@Sinity
Sinity deleted the feature/feat/cost-cycle-outlook-engine branch May 17, 2026 04:57

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment thread polylogue/cost/outlook.py Resolved
Comment thread polylogue/cost/outlook.py
Comment on lines +230 to +233
end_day = window.end.date()
for row in usage:
if row.day < start_day or row.day > end_day:
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Sinity added a commit that referenced this pull request May 17, 2026
## 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
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 62.F015 / P1: fixed-already at the checked revision: Quota pressure receives grouped.get(primary_basis_key or "", {}) at polylogue/cost/outlook.py:393. The unrelated-basis fallback remains confined to coverage, so USD-only observations cannot create a breach day against a credits quota.

Only the rows listed above are dispositioned. Held findings remain open.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(cost): cycle outlook engine — burn, projection, quota pressure, overage

1 participant