Skip to content

feat(insights): cost tracking with tokenizer, subscription pricing (#803) - #938

Merged
Sinity merged 1 commit into
masterfrom
feature/feat/cost-tracking-803
May 7, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/feat/cost-tracking-803

Conversation

@Sinity

@Sinity Sinity commented May 7, 2026 •

Copy link
Copy Markdown
Owner

Token columns, cost models, credit pricing. 23 files.

Summary by CodeRabbit

Release Notes

New Features

  • Session cost computation with per-model token tracking and USD pricing estimates
  • Token estimation fallback for conversations with unavailable provider metrics
  • Subscription credit system with configurable pricing and tier support
  • Maintenance operations with preview and execution capabilities

Copilot AI review requested due to automatic review settings May 7, 2026 18:49
@Sinity
Sinity merged commit 3776ac3 into master May 7, 2026
@Sinity
Sinity deleted the feature/feat/cost-tracking-803 branch May 7, 2026 18:49
@coderabbitai

coderabbitai Bot commented May 7, 2026 •

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 2ed60952-d360-4069-8e0b-396b43488ae8

📥 Commits

Reviewing files that changed from the base of the PR and between 6488162 and fe22590.

📒 Files selected for processing (6)
  • polylogue/archive/semantic/cost_compute.py
  • polylogue/archive/semantic/cost_records.py
  • polylogue/archive/semantic/subscription_pricing.py
  • polylogue/archive/semantic/tokenizer.py
  • polylogue/cli/commands/maintenance.py
  • polylogue/maintenance/planner.py

📝 Walkthrough

Walkthrough

This PR introduces session cost computation infrastructure for tracking conversation message costs with provider-reported or heuristic token estimation, subscription-aware credit calculations, and maintenance CLI/backend APIs for database backfill operations across multiple modules.

Changes

Session Cost Tracking and Maintenance Infrastructure

Layer / File(s) Summary
Data Models and Type Definitions
polylogue/archive/semantic/cost_records.py, polylogue/archive/semantic/tokenizer.py, polylogue/archive/semantic/subscription_pricing.py
Typed Pydantic models and Literal type aliases define token provenance, cost confidence, cost basis, session cost breakdowns per model, aggregated session summaries, subscription tiers, and credit rate conversions with versioning metadata.
Token Estimation Fallback
polylogue/archive/semantic/tokenizer.py
Word-count-based token estimation derives input/output/cache token counts when provider metrics unavailable, with configurable divisors, ceiling rounding, and provenance/confidence tracking via TokenEstimate dataclass and helper functions.
Subscription Pricing and Credit Utilities
polylogue/archive/semantic/subscription_pricing.py
ModelCreditRate converts tokens to subscription credits per model using per-token divisors; SubscriptionTier catalog defines Claude Code plans; helpers get_credit_rate and compute_credit_cost enable credit/subscription-equivalent USD calculations.
Session Cost Computation
polylogue/archive/semantic/cost_compute.py
compute_session_cost orchestrates per-message iteration, derives model identifiers, sources tokens (provider-reported or estimated), groups by normalized model, calculates API/credit/subscription costs, aggregates totals, and produces SessionCostSummary with confidence/provenance and version snapshots.
Maintenance Backfill Planner
polylogue/maintenance/planner.py
BackfillKind and BackfillStatus enums, BackfillOperation dataclass model preview/run operations; preview_backfill resolves targets, queries archive-debt rows, computes estimates; execute_backfill dispatches work, routes safe/cleanup targets, aggregates results, handles errors, and serializes per-target outcomes.
Maintenance CLI Commands
polylogue/cli/commands/maintenance.py
Click command group with preview (target selection, preview cost/impact summary, per-target breakdown) and run subcommands (target selection, dry-run mode, execution status, per-target result summaries, elapsed time reporting, error logging to stderr).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

Suggested labels

type:refactor, area:storage, area:cli, area:pipeline, area:schema

Poem

🐰 Costs cascade through sessions now,
Token estimates, a fallback vow,
Credits convert with heuristic grace,
Maintenance commands keep pace,
Subscriptions tracked, no more mystery! ✨

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/cost-tracking-803

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.

@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: fe22590204

ℹ️ 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/cli/commands/maintenance.py Resolved
Comment thread polylogue/maintenance/planner.py Resolved
@Sinity
Sinity removed the request for review from Copilot May 7, 2026 19:10
Sinity added a commit that referenced this pull request May 7, 2026
Implements the trustworthy accounting substrate that #803 needs
before the user-facing subscription outlook can be built. The
previous cost-estimation path could not answer which model each
assistant turn used, how tokens broke down across input / output /
cached input / cache creation / reasoning / tools / multimodal,
which numbers were provider-reported facts vs tokenizer-derived
estimates, or what API-equivalent USD vs Claude Code subscription
credits were consumed.

- `archive/semantic/cost_compute.py`, `cost_records.py`,
  `subscription_pricing.py`: typed cost computation with per-model
  token classes, USD pricing estimates, subscription credit
  pricing, and explicit provenance fields distinguishing exact
  facts from estimates.
- `archive/semantic/tokenizer.py`: client-side tokenizer fallback
  when provider metrics are missing.
- `cli/commands/maintenance.py` and `maintenance/planner.py`:
  preview/execute hooks so cost recomputation is a maintenance
  operation, not a one-shot script.

Refs #803
Sinity added a commit that referenced this pull request May 7, 2026
Polylogue's cost work was geared toward API billing logs, but the
common local-chat/export use case has no provider-reported cost. The
primary product value is subscription-oriented: plan cycle, estimated
burn, quota/rate-limit pressure, model usage, anomaly detection, and
what consumed the user's practical allowance.

- Adds `polylogue/archive/semantic/outlook.py` and
  `subscription_models.py` defining `SubscriptionCycle` and the
  `UsageOutlookPayload` so cost data has a typed shape that can
  describe a plan cycle, not just per-API-call totals.
- Wires a `polylogue cost` CLI command via
  `cli/click_command_registration.py` and `cli/commands/cost.py` so
  the outlook surface is reachable from the user CLI without going
  through ad-hoc reporting scripts.

Builds on the cost-tracking substrate from #803 (PR #938) which
supplies model assignment, token classes, and cost basis.

Refs #870
Sinity added a commit that referenced this pull request May 7, 2026
Implements the trustworthy accounting substrate that #803 needs
before the user-facing subscription outlook can be built. The
previous cost-estimation path could not answer which model each
assistant turn used, how tokens broke down across input / output /
cached input / cache creation / reasoning / tools / multimodal,
which numbers were provider-reported facts vs tokenizer-derived
estimates, or what API-equivalent USD vs Claude Code subscription
credits were consumed.

- `archive/semantic/cost_compute.py`, `cost_records.py`,
  `subscription_pricing.py`: typed cost computation with per-model
  token classes, USD pricing estimates, subscription credit
  pricing, and explicit provenance fields distinguishing exact
  facts from estimates.
- `archive/semantic/tokenizer.py`: client-side tokenizer fallback
  when provider metrics are missing.
- `cli/commands/maintenance.py` and `maintenance/planner.py`:
  preview/execute hooks so cost recomputation is a maintenance
  operation, not a one-shot script.

Refs #803
Sinity added a commit that referenced this pull request May 7, 2026
Polylogue's cost work was geared toward API billing logs, but the
common local-chat/export use case has no provider-reported cost. The
primary product value is subscription-oriented: plan cycle, estimated
burn, quota/rate-limit pressure, model usage, anomaly detection, and
what consumed the user's practical allowance.

- Adds `polylogue/archive/semantic/outlook.py` and
  `subscription_models.py` defining `SubscriptionCycle` and the
  `UsageOutlookPayload` so cost data has a typed shape that can
  describe a plan cycle, not just per-API-call totals.
- Wires a `polylogue cost` CLI command via
  `cli/click_command_registration.py` and `cli/commands/cost.py` so
  the outlook surface is reachable from the user CLI without going
  through ad-hoc reporting scripts.

Builds on the cost-tracking substrate from #803 (PR #938) which
supplies model assignment, token classes, and cost basis.

Refs #870
@Sinity

Sinity commented Sep 30, 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.

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

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

  • 58.F031 / P1: fixed-already at the checked revision: polylogue/archive/semantic/cost_compute.py:412-413 accepts a present token object without requiring billable_tokens. _add_provider_reported_tokens reads input_tokens and output_tokens directly at lines 478-479, preserving provider-reported usage from TokenUsage.

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

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

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.

1 participant