From f2d89464548efd776240f286609779172671b159 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Mon, 9 Nov 2026 18:49:34 +0000 Subject: [PATCH 1/2] feat(ai): add --since, --until, and --by to cost report and roi Add time bounds and period grouping to the AI cost report and ROI commands. Users can filter ledger records by ISO date or timestamp with --since and --until. Users can group report and ROI summaries by day or week with --by. The sum of period rows matches the report of the full range. The fastmcp tool ai_cost_report accepts matching time range and grouping options. The --days flag remains supported as a shorthand for recent days. --- docs/CLI_REFERENCE.md | 22 +- docs/MCP_TOOLS.md | 4 +- docs/commands/ai.md | 22 +- .../.openspec.yaml | 2 + .../2193-add-since-until-and-by-to/design.md | 15 + .../proposal.md | 42 +++ .../specs/ai-spend-pricing/spec.md | 16 + .../2193-add-since-until-and-by-to/tasks.md | 50 +++ src/devops_cli/ai/spend/__init__.py | 2 + src/devops_cli/ai/spend/ledger.py | 135 ++++++-- src/devops_cli/ai/spend/models.py | 16 + src/devops_cli/commands/ai_cost.py | 210 ++++++++++++- ...the_tool_listing_matches_the_snapshot.json | 26 +- tests/ai/mcp/test_mcp_tool_argv.py | 21 ++ tests/ai/spend/test_ai_spend_cli.py | 288 ++++++++++++++++++ tests/ai/spend/test_ai_spend_ledger.py | 127 ++++++++ 16 files changed, 966 insertions(+), 32 deletions(-) create mode 100644 openspec/changes/2193-add-since-until-and-by-to/.openspec.yaml create mode 100644 openspec/changes/2193-add-since-until-and-by-to/design.md create mode 100644 openspec/changes/2193-add-since-until-and-by-to/proposal.md create mode 100644 openspec/changes/2193-add-since-until-and-by-to/specs/ai-spend-pricing/spec.md create mode 100644 openspec/changes/2193-add-since-until-and-by-to/tasks.md diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md index 7ccf88aa14..f8ee1571aa 100644 --- a/docs/CLI_REFERENCE.md +++ b/docs/CLI_REFERENCE.md @@ -5674,8 +5674,10 @@ devops ai cost [OPTIONS] COMMAND [ARGS]... | Option / Flag | Type | Default | Description | |---|---|---|---| -| `--by`, `-b` | `string` | `server` | Breakdown grouping dimension: server, model, provider, backend, stage, all. | +| `--by`, `-b` | `string` | `server` | Breakdown grouping dimension: server, model, provider, backend, stage, day, week, all. | | `--days`, `-d` | `integer` | - | Filter usage to the last N days (default: all lifetime). | +| `--since`, `-s` | `string` | - | Filter usage since ISO date or datetime (default: all lifetime). | +| `--until`, `-u` | `string` | - | Filter usage until ISO date or datetime (default: all lifetime). | | `--reference-model`, `-m` | `string` | - | Reference model for counterfactual pricing (default: the ai.reference_model setting). | | `--hardware-cost`, `-H` | `float` | - | Hardware purchase cost in USD to track pay-off against. | | `--format`, `-f` | `string` | `table` | Output format: table, json, yaml, markdown. | @@ -5693,8 +5695,10 @@ devops ai cost report [OPTIONS] | Option / Flag | Type | Default | Description | |---|---|---|---| -| `--by`, `-b` | `string` | `server` | Breakdown grouping dimension: server, model, provider, backend, stage, all. | +| `--by`, `-b` | `string` | `server` | Breakdown grouping dimension: server, model, provider, backend, stage, day, week, all. | | `--days`, `-d` | `integer` | - | Filter usage to the last N days (default: all lifetime). | +| `--since`, `-s` | `string` | - | Filter usage since ISO date or datetime (default: all lifetime). | +| `--until`, `-u` | `string` | - | Filter usage until ISO date or datetime (default: all lifetime). | | `--reference-model`, `-m` | `string` | - | Reference model for counterfactual pricing (default: the ai.reference_model setting). | | `--hardware-cost`, `-H` | `float` | - | Hardware purchase cost in USD to track pay-off against. | | `--format`, `-f` | `string` | `table` | Output format: table, json, yaml, prometheus. | @@ -5715,6 +5719,9 @@ devops ai cost roi [OPTIONS] | `--hardware-cost`, `-H` | `float` | - | Total hardware purchase cost in USD (e.g. 1599.0 for GPU/workstation). | | `--reference-model`, `-m` | `string` | - | Reference model for counterfactual pricing (default: the ai.reference_model setting). | | `--days`, `-d` | `integer` | - | Filter usage to the last N days (default: all lifetime). | +| `--since`, `-s` | `string` | - | Filter usage since ISO date or datetime (default: all lifetime). | +| `--until`, `-u` | `string` | - | Filter usage until ISO date or datetime (default: all lifetime). | +| `--by`, `-b` | `string` | - | Grouping period: day, week. | | `--format`, `-f` | `string` | `table` | Output format: table, json, yaml. | | `--json` | `boolean` | - | First-class alias for --format json. | @@ -5812,8 +5819,10 @@ devops ai spend [OPTIONS] COMMAND [ARGS]... | Option / Flag | Type | Default | Description | |---|---|---|---| -| `--by`, `-b` | `string` | `server` | Breakdown grouping dimension: server, model, provider, backend, stage, all. | +| `--by`, `-b` | `string` | `server` | Breakdown grouping dimension: server, model, provider, backend, stage, day, week, all. | | `--days`, `-d` | `integer` | - | Filter usage to the last N days (default: all lifetime). | +| `--since`, `-s` | `string` | - | Filter usage since ISO date or datetime (default: all lifetime). | +| `--until`, `-u` | `string` | - | Filter usage until ISO date or datetime (default: all lifetime). | | `--reference-model`, `-m` | `string` | - | Reference model for counterfactual pricing (default: the ai.reference_model setting). | | `--hardware-cost`, `-H` | `float` | - | Hardware purchase cost in USD to track pay-off against. | | `--format`, `-f` | `string` | `table` | Output format: table, json, yaml, markdown. | @@ -5831,8 +5840,10 @@ devops ai spend report [OPTIONS] | Option / Flag | Type | Default | Description | |---|---|---|---| -| `--by`, `-b` | `string` | `server` | Breakdown grouping dimension: server, model, provider, backend, stage, all. | +| `--by`, `-b` | `string` | `server` | Breakdown grouping dimension: server, model, provider, backend, stage, day, week, all. | | `--days`, `-d` | `integer` | - | Filter usage to the last N days (default: all lifetime). | +| `--since`, `-s` | `string` | - | Filter usage since ISO date or datetime (default: all lifetime). | +| `--until`, `-u` | `string` | - | Filter usage until ISO date or datetime (default: all lifetime). | | `--reference-model`, `-m` | `string` | - | Reference model for counterfactual pricing (default: the ai.reference_model setting). | | `--hardware-cost`, `-H` | `float` | - | Hardware purchase cost in USD to track pay-off against. | | `--format`, `-f` | `string` | `table` | Output format: table, json, yaml, prometheus. | @@ -5853,6 +5864,9 @@ devops ai spend roi [OPTIONS] | `--hardware-cost`, `-H` | `float` | - | Total hardware purchase cost in USD (e.g. 1599.0 for GPU/workstation). | | `--reference-model`, `-m` | `string` | - | Reference model for counterfactual pricing (default: the ai.reference_model setting). | | `--days`, `-d` | `integer` | - | Filter usage to the last N days (default: all lifetime). | +| `--since`, `-s` | `string` | - | Filter usage since ISO date or datetime (default: all lifetime). | +| `--until`, `-u` | `string` | - | Filter usage until ISO date or datetime (default: all lifetime). | +| `--by`, `-b` | `string` | - | Grouping period: day, week. | | `--format`, `-f` | `string` | `table` | Output format: table, json, yaml. | | `--json` | `boolean` | - | First-class alias for --format json. | diff --git a/docs/MCP_TOOLS.md b/docs/MCP_TOOLS.md index 97dc3aa6c2..b318c55d2b 100644 --- a/docs/MCP_TOOLS.md +++ b/docs/MCP_TOOLS.md @@ -244,8 +244,10 @@ Generate detailed spend and token report across backend services and servers. | Parameter | Type | Required | Default | Description | |---|---|---|---|---| -| `by` | `string` | No | `server` | Breakdown grouping dimension: server, model, provider, backend, stage, all. | +| `by` | `string` | No | `server` | Breakdown grouping dimension: server, model, provider, backend, stage, day, week, all. | | `days` | `integer` | No | - | Filter usage to the last N days (default: all lifetime). | +| `since` | `string` | No | - | Filter usage since ISO date or datetime (default: all lifetime). | +| `until` | `string` | No | - | Filter usage until ISO date or datetime (default: all lifetime). | | `reference_model` | `string` | No | - | Reference model for counterfactual pricing (default: the ai.reference_model setting). | | `hardware_cost` | `number` | No | - | Hardware purchase cost in USD to track pay-off against. | | `format_opt` | `string` | No | `table` | Output format: table, json, yaml, prometheus. | diff --git a/docs/commands/ai.md b/docs/commands/ai.md index 4d3c0a517f..a5aeca7cd8 100644 --- a/docs/commands/ai.md +++ b/docs/commands/ai.md @@ -2024,8 +2024,10 @@ devops ai cost [OPTIONS] COMMAND [ARGS]... | Option / Flag | Type | Default | Description | |---|---|---|---| -| `--by`, `-b` | `string` | `server` | Breakdown grouping dimension: server, model, provider, backend, stage, all. | +| `--by`, `-b` | `string` | `server` | Breakdown grouping dimension: server, model, provider, backend, stage, day, week, all. | | `--days`, `-d` | `integer` | - | Filter usage to the last N days (default: all lifetime). | +| `--since`, `-s` | `string` | - | Filter usage since ISO date or datetime (default: all lifetime). | +| `--until`, `-u` | `string` | - | Filter usage until ISO date or datetime (default: all lifetime). | | `--reference-model`, `-m` | `string` | - | Reference model for counterfactual pricing (default: the ai.reference_model setting). | | `--hardware-cost`, `-H` | `float` | - | Hardware purchase cost in USD to track pay-off against. | | `--format`, `-f` | `string` | `table` | Output format: table, json, yaml, markdown. | @@ -2043,8 +2045,10 @@ devops ai cost report [OPTIONS] | Option / Flag | Type | Default | Description | |---|---|---|---| -| `--by`, `-b` | `string` | `server` | Breakdown grouping dimension: server, model, provider, backend, stage, all. | +| `--by`, `-b` | `string` | `server` | Breakdown grouping dimension: server, model, provider, backend, stage, day, week, all. | | `--days`, `-d` | `integer` | - | Filter usage to the last N days (default: all lifetime). | +| `--since`, `-s` | `string` | - | Filter usage since ISO date or datetime (default: all lifetime). | +| `--until`, `-u` | `string` | - | Filter usage until ISO date or datetime (default: all lifetime). | | `--reference-model`, `-m` | `string` | - | Reference model for counterfactual pricing (default: the ai.reference_model setting). | | `--hardware-cost`, `-H` | `float` | - | Hardware purchase cost in USD to track pay-off against. | | `--format`, `-f` | `string` | `table` | Output format: table, json, yaml, prometheus. | @@ -2065,6 +2069,9 @@ devops ai cost roi [OPTIONS] | `--hardware-cost`, `-H` | `float` | - | Total hardware purchase cost in USD (e.g. 1599.0 for GPU/workstation). | | `--reference-model`, `-m` | `string` | - | Reference model for counterfactual pricing (default: the ai.reference_model setting). | | `--days`, `-d` | `integer` | - | Filter usage to the last N days (default: all lifetime). | +| `--since`, `-s` | `string` | - | Filter usage since ISO date or datetime (default: all lifetime). | +| `--until`, `-u` | `string` | - | Filter usage until ISO date or datetime (default: all lifetime). | +| `--by`, `-b` | `string` | - | Grouping period: day, week. | | `--format`, `-f` | `string` | `table` | Output format: table, json, yaml. | | `--json` | `boolean` | - | First-class alias for --format json. | @@ -2164,8 +2171,10 @@ devops ai spend [OPTIONS] COMMAND [ARGS]... | Option / Flag | Type | Default | Description | |---|---|---|---| -| `--by`, `-b` | `string` | `server` | Breakdown grouping dimension: server, model, provider, backend, stage, all. | +| `--by`, `-b` | `string` | `server` | Breakdown grouping dimension: server, model, provider, backend, stage, day, week, all. | | `--days`, `-d` | `integer` | - | Filter usage to the last N days (default: all lifetime). | +| `--since`, `-s` | `string` | - | Filter usage since ISO date or datetime (default: all lifetime). | +| `--until`, `-u` | `string` | - | Filter usage until ISO date or datetime (default: all lifetime). | | `--reference-model`, `-m` | `string` | - | Reference model for counterfactual pricing (default: the ai.reference_model setting). | | `--hardware-cost`, `-H` | `float` | - | Hardware purchase cost in USD to track pay-off against. | | `--format`, `-f` | `string` | `table` | Output format: table, json, yaml, markdown. | @@ -2183,8 +2192,10 @@ devops ai spend report [OPTIONS] | Option / Flag | Type | Default | Description | |---|---|---|---| -| `--by`, `-b` | `string` | `server` | Breakdown grouping dimension: server, model, provider, backend, stage, all. | +| `--by`, `-b` | `string` | `server` | Breakdown grouping dimension: server, model, provider, backend, stage, day, week, all. | | `--days`, `-d` | `integer` | - | Filter usage to the last N days (default: all lifetime). | +| `--since`, `-s` | `string` | - | Filter usage since ISO date or datetime (default: all lifetime). | +| `--until`, `-u` | `string` | - | Filter usage until ISO date or datetime (default: all lifetime). | | `--reference-model`, `-m` | `string` | - | Reference model for counterfactual pricing (default: the ai.reference_model setting). | | `--hardware-cost`, `-H` | `float` | - | Hardware purchase cost in USD to track pay-off against. | | `--format`, `-f` | `string` | `table` | Output format: table, json, yaml, prometheus. | @@ -2205,6 +2216,9 @@ devops ai spend roi [OPTIONS] | `--hardware-cost`, `-H` | `float` | - | Total hardware purchase cost in USD (e.g. 1599.0 for GPU/workstation). | | `--reference-model`, `-m` | `string` | - | Reference model for counterfactual pricing (default: the ai.reference_model setting). | | `--days`, `-d` | `integer` | - | Filter usage to the last N days (default: all lifetime). | +| `--since`, `-s` | `string` | - | Filter usage since ISO date or datetime (default: all lifetime). | +| `--until`, `-u` | `string` | - | Filter usage until ISO date or datetime (default: all lifetime). | +| `--by`, `-b` | `string` | - | Grouping period: day, week. | | `--format`, `-f` | `string` | `table` | Output format: table, json, yaml. | | `--json` | `boolean` | - | First-class alias for --format json. | diff --git a/openspec/changes/2193-add-since-until-and-by-to/.openspec.yaml b/openspec/changes/2193-add-since-until-and-by-to/.openspec.yaml new file mode 100644 index 0000000000..ca7e6273f6 --- /dev/null +++ b/openspec/changes/2193-add-since-until-and-by-to/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-09 diff --git a/openspec/changes/2193-add-since-until-and-by-to/design.md b/openspec/changes/2193-add-since-until-and-by-to/design.md new file mode 100644 index 0000000000..6c0d8dbe8a --- /dev/null +++ b/openspec/changes/2193-add-since-until-and-by-to/design.md @@ -0,0 +1,15 @@ +# Design + +## Decisions + +- **Use half-open intervals `[start, end)` for periods**: Each timestamp belongs to exactly one period. The sum of period columns equals the ungrouped range report. +- **Support `--days N` as short form of `--since`**: Maintains backward compatibility with existing scripts. +- **Normalize dates and datetimes to UTC ISO strings**: Parses ISO date and datetime inputs and sets UTC timezone when no offset is provided. +- **Model period outputs with `PeriodSpendSummary`**: Standardizes fields (`period`, `requests`, `local_tokens`, `actual_spend`, `local_cost_equivalent`, `cloud_spend_avoided`) across CLI JSON, YAML, and tables. +- **Generate FastMCP tool arguments dynamically**: Uses Typer option metadata so `ai_cost_report` automatically exposes `since`, `until`, and `by`. + +## Rejected alternatives + +- **Closed intervals `[start, end]`**: Boundary records would appear in multiple intervals and invalidate column sum totals. +- **Fixed calendar week boundaries (e.g. Monday-Sunday only)**: Custom arbitrary ranges such as `2026-10-01` to `2026-10-22` would split into partial weeks instead of three equal 7-day periods. +- **Separate CLI commands for grouped reporting**: Adds unnecessary command surface area; extending `--by` aligns with existing grouping parameters. diff --git a/openspec/changes/2193-add-since-until-and-by-to/proposal.md b/openspec/changes/2193-add-since-until-and-by-to/proposal.md new file mode 100644 index 0000000000..be929742d1 --- /dev/null +++ b/openspec/changes/2193-add-since-until-and-by-to/proposal.md @@ -0,0 +1,42 @@ +# Proposal + +## Why + +The `devops ai cost report` and `devops ai cost roi` commands accept `--days N` only. A user who needs metrics for a specific date range must copy the ledger database and delete records outside the range. The commands need explicit `--since` and `--until` parameters, and need `--by day` and `--by week` grouping. Closes #2193. + +## What Changes + +- Add `PeriodSpendSummary` in `src/devops_cli/ai/spend/models.py` to hold spend, token, and savings metrics for a single period. +- Update `SpendLedger` in `src/devops_cli/ai/spend/ledger.py` so queries filter with `since` and `until` timestamps. +- Add `get_period_report` in `SpendLedger` to calculate metrics grouped into day or week intervals. +- Update `devops ai cost report` and `devops ai cost roi` in `src/devops_cli/commands/ai_cost.py` to accept `--since`, `--until`, and `--by`. +- Expose `--since`, `--until`, and `--by` in the generated FastMCP tool `ai_cost_report`. +- Add tests for range filtering, weekly grouping, column sum equivalence, and MCP arguments. +- Regenerate documentation and FastMCP tool snapshots. + +## Capabilities + +### New Capabilities + +None. + +### Modified Capabilities + +- `ai-spend-pricing`: Spend report and ROI accept time range and period grouping. + +## Impact + +- Code: `src/devops_cli/ai/spend/models.py`, `src/devops_cli/ai/spend/ledger.py`, `src/devops_cli/commands/ai_cost.py` +- Documents: `docs/CLI_REFERENCE.md`, `docs/MCP_TOOLS.md`, `docs/commands/ai.md` +- Tests: `tests/ai/spend/test_ai_spend_ledger.py`, `tests/ai/spend/test_ai_spend_cli.py`, `tests/ai/mcp/test_mcp_tool_argv.py` + +## Feasibility + +- The `ai_spend_records` table indexes `timestamp`. +- The query conditions `WHERE (:since IS NULL OR timestamp >= :since) AND (:until IS NULL OR timestamp < :until)` filter rows in SQLite. +- Half-open intervals `[start, end)` partition the range so the sum of grouped rows equals the ungrouped report. +- The `ai_cost_report` tool generates dynamically from Click parameter metadata. + +## Existing Tool Considered + +The roadmap check evaluated `ccusage/ccusage`. That tool tracks only Claude and Anthropic usage. It does not read the local SQLite ledger or connect to DevOps CLI workflows. Building this feature in DevOps CLI costs approximately 25,000 tokens and 1 hour. diff --git a/openspec/changes/2193-add-since-until-and-by-to/specs/ai-spend-pricing/spec.md b/openspec/changes/2193-add-since-until-and-by-to/specs/ai-spend-pricing/spec.md new file mode 100644 index 0000000000..f19fa6fd2c --- /dev/null +++ b/openspec/changes/2193-add-since-until-and-by-to/specs/ai-spend-pricing/spec.md @@ -0,0 +1,16 @@ +## ADDED Requirements + +### Requirement: Spend report and ROI accept time range and period grouping +The `devops ai cost report` and `devops ai cost roi` commands SHALL accept `--since` and `--until` for ISO dates or datetimes (UTC unless an offset is specified), and SHALL accept `--by day` and `--by week` to return spend, token and savings summaries grouped by period. The `--days N` flag SHALL remain as a short form equivalent to `--since` set to `N` days before the current time. + +#### Scenario: Cost report grouped by week across a date range +- **WHEN** `devops ai cost report --since 2026-10-01 --until 2026-10-22 --by week --json` runs against a ledger +- **THEN** it outputs three period rows whose column sums equal the ungrouped report for the same date range + +#### Scenario: Cost ROI grouped by week +- **WHEN** `devops ai cost roi --since 2026-10-01 --until 2026-10-22 --by week --json` runs against a ledger +- **THEN** each period row contains requests, local tokens, actual spend, local cost equivalent, and cloud spend avoided + +#### Scenario: The MCP tool ai_cost_report accepts date range and grouping +- **WHEN** the MCP tool `ai_cost_report` is called with `since`, `until`, and `by` +- **THEN** it passes the options to the command line and returns the matching report diff --git a/openspec/changes/2193-add-since-until-and-by-to/tasks.md b/openspec/changes/2193-add-since-until-and-by-to/tasks.md new file mode 100644 index 0000000000..23b7c131ff --- /dev/null +++ b/openspec/changes/2193-add-since-until-and-by-to/tasks.md @@ -0,0 +1,50 @@ +# Tasks + +## 1. Spend ledger date range and period grouping + +Reads: `src/devops_cli/ai/spend/models.py`, `src/devops_cli/ai/spend/ledger.py`, `tests/ai/spend/test_ai_spend_ledger.py`. +Changes: `src/devops_cli/ai/spend/models.py`, `src/devops_cli/ai/spend/ledger.py`, `tests/ai/spend/test_ai_spend_ledger.py`. + +- [x] 1.1 In `tests/ai/spend/test_ai_spend_ledger.py`, add failing tests asserting `since` and `until` range filtering and `get_period_report` output for day and week grouping + - Verification: `$ uv run devops ci test tests/ai/spend/test_ai_spend_ledger.py` +- [x] 1.2 Add `PeriodSpendSummary` in `src/devops_cli/ai/spend/models.py`, and implement `since`, `until`, and `get_period_report` in `src/devops_cli/ai/spend/ledger.py` + - Verification: `$ uv run devops ci test tests/ai/spend/test_ai_spend_ledger.py` + +## 2. CLI commands for cost report and ROI + +Reads: `src/devops_cli/commands/ai_cost.py`, `tests/ai/spend/test_ai_spend_cli.py`. +Changes: `src/devops_cli/commands/ai_cost.py`, `tests/ai/spend/test_ai_spend_cli.py`. + +- [x] 2.1 In `tests/ai/spend/test_ai_spend_cli.py`, add failing tests for `devops ai cost report` and `devops ai cost roi` with `--since`, `--until`, `--by week`, and `--days` + - Verification: `$ uv run devops ci test tests/ai/spend/test_ai_spend_cli.py` +- [x] 2.2 Update `cost_report`, `cost_roi`, and `cost_default` in `src/devops_cli/commands/ai_cost.py` to accept `--since`, `--until`, and `--by day|week` + - Verification: `$ uv run devops ci test tests/ai/spend/test_ai_spend_cli.py` + +## 3. FastMCP tool ai_cost_report arguments and snapshot + +Reads: `tests/ai/mcp/test_mcp_tool_argv.py`, `tests/ai/mcp/test_mcp_tool_listing.py`. +Changes: `tests/ai/mcp/test_mcp_tool_argv.py`, `tests/ai/mcp/__snapshots__/test_mcp_tool_listing/test_the_tool_listing_matches_the_snapshot.json`. + +- [x] 3.1 In `tests/ai/mcp/test_mcp_tool_argv.py`, add a test verifying `ai_cost_report` passes `since`, `until`, and `by` + - Verification: `$ uv run devops ci test tests/ai/mcp/test_mcp_tool_argv.py` +- [x] 3.2 Update tool listing snapshot in `tests/ai/mcp/test_mcp_tool_listing.py` + - Verification: `$ uv run devops ci test tests/ai/mcp/test_mcp_tool_listing.py` + +## 4. Documentation updates + +Reads: `docs/MCP_TOOLS.md`, `docs/CLI_REFERENCE.md`, `docs/commands/ai.md`. +Changes: `docs/MCP_TOOLS.md`, `docs/CLI_REFERENCE.md`, `docs/commands/ai.md`. + +- [x] 4.1 Run `uv run devops docs generate --sync-readme` to regenerate documentation manuals + - Verification: `$ uv run devops ci docs` + +## Criteria + +- Criterion 1 (Weekly grouping column sums): group 2 +- Criterion 2 (Weekly grouping ROI output): group 2 +- Criterion 3 (--days short form equivalence): group 2 +- Criterion 4 (FastMCP tool ai_cost_report): group 3 + +## Workflow follow-up + +- Pending a person: review the diff in tuicr (`tuicr -r ..HEAD`). diff --git a/src/devops_cli/ai/spend/__init__.py b/src/devops_cli/ai/spend/__init__.py index 35acc0e326..a759ea4f37 100644 --- a/src/devops_cli/ai/spend/__init__.py +++ b/src/devops_cli/ai/spend/__init__.py @@ -8,6 +8,7 @@ LifetimeSpendReport, ModelPricing, ModelSpendSummary, + PeriodSpendSummary, ProviderSpendSummary, ServerSpendSummary, SpendRecord, @@ -28,6 +29,7 @@ "LifetimeSpendReport", "ModelPricing", "ModelSpendSummary", + "PeriodSpendSummary", "PricingRegistry", "ProviderSpendSummary", "ServerSpendSummary", diff --git a/src/devops_cli/ai/spend/ledger.py b/src/devops_cli/ai/spend/ledger.py index cc212f140a..a8023f0486 100644 --- a/src/devops_cli/ai/spend/ledger.py +++ b/src/devops_cli/ai/spend/ledger.py @@ -16,6 +16,7 @@ LifetimeSpendReport, ModelPricing, ModelSpendSummary, + PeriodSpendSummary, ProviderSpendSummary, ServerSpendSummary, SpendRecord, @@ -104,7 +105,7 @@ COALESCE(SUM(reasoning_tokens), 0) as r_tokens, COALESCE(SUM(cost_usd), 0.0) as s_cost FROM ai_spend_records -WHERE (:cutoff IS NULL OR timestamp >= :cutoff) +WHERE (:since IS NULL OR timestamp >= :since) AND (:until IS NULL OR timestamp < :until) GROUP BY stage_name ORDER BY s_cost DESC, t_tokens DESC; """ @@ -124,7 +125,7 @@ MIN(timestamp) as first_ts, MAX(timestamp) as last_ts FROM ai_spend_records -WHERE (:cutoff IS NULL OR timestamp >= :cutoff); +WHERE (:since IS NULL OR timestamp >= :since) AND (:until IS NULL OR timestamp < :until); """ _QUERY_SERVER_BREAKDOWN = """ @@ -142,7 +143,7 @@ MIN(timestamp) as f_seen, MAX(timestamp) as l_seen FROM ai_spend_records -WHERE (:cutoff IS NULL OR timestamp >= :cutoff) +WHERE (:since IS NULL OR timestamp >= :since) AND (:until IS NULL OR timestamp < :until) GROUP BY server, provider ORDER BY s_cost DESC, t_tokens DESC; """ @@ -161,7 +162,7 @@ COALESCE(SUM(completion_tokens), 0) as c_tokens, COALESCE(SUM(CASE WHEN request_type = :embedding THEN prompt_tokens ELSE 0 END), 0) as e_tokens FROM ai_spend_records -WHERE (:cutoff IS NULL OR timestamp >= :cutoff) +WHERE (:since IS NULL OR timestamp >= :since) AND (:until IS NULL OR timestamp < :until) GROUP BY server, provider, served_by, served_model; """ @@ -178,7 +179,7 @@ COALESCE(SUM(cost_usd), 0.0) as m_cost, COALESCE(SUM(CASE WHEN cached=1 THEN 1 ELSE 0 END), 0) as cached_count FROM ai_spend_records -WHERE (:cutoff IS NULL OR timestamp >= :cutoff) +WHERE (:since IS NULL OR timestamp >= :since) AND (:until IS NULL OR timestamp < :until) GROUP BY model, provider ORDER BY m_cost DESC, t_tokens DESC; """ @@ -191,7 +192,7 @@ COALESCE(SUM(cost_usd), 0.0) as p_cost, COUNT(DISTINCT CASE WHEN cached=0 THEN server END) as s_count FROM ai_spend_records -WHERE (:cutoff IS NULL OR timestamp >= :cutoff) +WHERE (:since IS NULL OR timestamp >= :since) AND (:until IS NULL OR timestamp < :until) GROUP BY provider ORDER BY p_cost DESC; """ @@ -207,7 +208,7 @@ COALESCE(SUM(reasoning_tokens), 0) as r_tokens, COALESCE(AVG(duration_seconds), 0.0) as mean_duration FROM ai_spend_records -WHERE served_by IS NOT NULL AND (:cutoff IS NULL OR timestamp >= :cutoff) +WHERE served_by IS NOT NULL AND (:since IS NULL OR timestamp >= :since) AND (:until IS NULL OR timestamp < :until) GROUP BY served_by ORDER BY req_count DESC, t_tokens DESC; """ @@ -216,7 +217,7 @@ _QUERY_DELETE_RECORDS = "DELETE FROM ai_spend_records;" -# Named parameters of the report queries: the date-range cutoff and the embedding request type. +# Named parameters of the report queries: the date-range bounds and the embedding request type. _QueryParams = dict[str, str | None] @@ -393,6 +394,30 @@ def _add_column(conn: sqlite3.Connection, add_column: str) -> None: _JOURNAL_MODE_LOCK = threading.Lock() +def _to_utc_datetime(val: str | datetime) -> datetime: + """Parse an ISO date or datetime string or normalize a datetime to UTC.""" + if isinstance(val, datetime): + dt = val if val.tzinfo is not None else val.replace(tzinfo=UTC) + return dt.astimezone(UTC) + clean = str(val).strip() + try: + dt = datetime.fromisoformat(clean) + except (ValueError, TypeError) as exc: + raise ValueError(f"Invalid ISO date or datetime: '{val}'") from exc + if dt.tzinfo is None: + dt = dt.replace(tzinfo=UTC) + else: + dt = dt.astimezone(UTC) + return dt + + +def _normalize_iso_timestamp(ts: str | datetime | None) -> str | None: + """Normalize a date, datetime, or ISO string to a UTC ISO-8601 string.""" + if ts is None: + return None + return _to_utc_datetime(ts).isoformat() + + class SpendLedger: """Persistent thread-safe SQLite ledger recording AI token spend across backends.""" @@ -517,15 +542,25 @@ def record_request( # Defensive logging: database failure must never crash user workflows return None - def _build_where_params(self, days: int | None) -> _QueryParams: - """The report queries' parameters: the cutoff of the date range, and the request type - whose prompt tokens they count as embedding tokens.""" - cutoff = ( - None - if days is None or days <= 0 - else (datetime.now(UTC) - timedelta(days=days)).isoformat() - ) - return {"cutoff": cutoff, "embedding": CONST_SPEND_REQUEST_TYPE_EMBEDDING} + def _build_where_params( + self, + days: int | None = None, + since: str | datetime | None = None, + until: str | datetime | None = None, + ) -> _QueryParams: + """The report queries' parameters: the since/until bounds of the date range, and the + request type whose prompt tokens they count as embedding tokens.""" + if since is None and days is not None and days > 0: + since = datetime.now(UTC) - timedelta(days=days) + + since_iso = _normalize_iso_timestamp(since) + until_iso = _normalize_iso_timestamp(until) + + return { + "since": since_iso, + "until": until_iso, + "embedding": CONST_SPEND_REQUEST_TYPE_EMBEDDING, + } @staticmethod def _resolve_hardware_cost(hardware_cost_usd: float | None = None) -> float: @@ -543,6 +578,8 @@ def _resolve_hardware_cost(hardware_cost_usd: float | None = None) -> float: def get_lifetime_report( self, days: int | None = None, + since: str | datetime | None = None, + until: str | datetime | None = None, group_by: str = "server", reference_model: str | None = None, hardware_cost_usd: float | None = None, @@ -553,7 +590,7 @@ def get_lifetime_report( `ai.reference_embedding_model`, every other token at `reference_model`. A cost equivalent is None when a reference model that prices its tokens has no price (#1672). """ - params = self._build_where_params(days) + params = self._build_where_params(days=days, since=since, until=until) with contextlib.closing(self._get_connection()) as conn: summary = self._query_overall_summary(conn, params) servers = self._query_server_breakdown(conn, params) @@ -614,6 +651,68 @@ def get_lifetime_report( summary.stages = stages return summary + def get_period_report( + self, + by: str = "week", + since: str | datetime | None = None, + until: str | datetime | None = None, + days: int | None = None, + reference_model: str | None = None, + ) -> list[PeriodSpendSummary]: + """Aggregate spend and token metrics broken down into day or week intervals (#2193).""" + if by not in ("day", "week"): + raise ValueError(f"Invalid period grouping '{by}'. Must be 'day' or 'week'.") + + if since is None and days is not None and days > 0: + since_dt = datetime.now(UTC) - timedelta(days=days) + elif since is not None: + since_dt = _to_utc_datetime(since) + else: + with contextlib.closing(self._get_connection()) as conn: + row = conn.execute( + "SELECT MIN(timestamp) as first_ts FROM ai_spend_records;" + ).fetchone() + if not row or not row["first_ts"]: + return [] + since_dt = _to_utc_datetime(row["first_ts"]) + + if until is not None: + until_dt = _to_utc_datetime(until) + else: + until_dt = datetime.now(UTC) + + if until_dt < since_dt: + raise ValueError("--until cannot be earlier than --since.") + + step = timedelta(days=1) if by == "day" else timedelta(days=7) + + periods: list[PeriodSpendSummary] = [] + cur = since_dt + while cur < until_dt: + nxt = min(cur + step, until_dt) + sub = self.get_lifetime_report( + since=cur, + until=nxt, + reference_model=reference_model, + ) + period_label = cur.strftime("%Y-%m-%d") + periods.append( + PeriodSpendSummary( + period=period_label, + requests=sub.total_requests, + local_tokens=sub.local_tokens, + actual_spend=sub.total_spend_usd, + actual_spend_usd=sub.total_spend_usd, + local_cost_equivalent=sub.local_cost_equivalent_usd, + local_cost_equivalent_usd=sub.local_cost_equivalent_usd, + cloud_spend_avoided=sub.counterfactual_savings_usd, + cloud_spend_avoided_usd=sub.counterfactual_savings_usd, + ) + ) + cur = nxt + + return periods + def _query_overall_summary( self, conn: sqlite3.Connection, params: _QueryParams ) -> LifetimeSpendReport: diff --git a/src/devops_cli/ai/spend/models.py b/src/devops_cli/ai/spend/models.py index c0f43dfb02..e7b06b9e48 100644 --- a/src/devops_cli/ai/spend/models.py +++ b/src/devops_cli/ai/spend/models.py @@ -212,3 +212,19 @@ class HardwarePayoffSummary(BaseModel): daily_savings_usd: float = 0.0 estimated_days_to_payoff: float | None = None reference_model: str + + +class PeriodSpendSummary(BaseModel): + """Spend, token, and savings metrics for a single time period (day or week).""" + + model_config = ConfigDict(extra="ignore") + + period: str + requests: int = 0 + local_tokens: int = 0 + actual_spend: float = 0.0 + actual_spend_usd: float = 0.0 + local_cost_equivalent: float | None = 0.0 + local_cost_equivalent_usd: float | None = 0.0 + cloud_spend_avoided: float | None = 0.0 + cloud_spend_avoided_usd: float | None = 0.0 diff --git a/src/devops_cli/commands/ai_cost.py b/src/devops_cli/commands/ai_cost.py index 077f62b97e..a906574592 100644 --- a/src/devops_cli/commands/ai_cost.py +++ b/src/devops_cli/commands/ai_cost.py @@ -2,13 +2,18 @@ from __future__ import annotations +from datetime import UTC, datetime from typing import Annotated import typer import yaml -from devops_cli.ai.spend import get_pricing_registry, get_spend_ledger -from devops_cli.ai.spend.models import HardwarePayoffSummary, LifetimeSpendReport +from devops_cli.ai.spend import SpendLedger, get_pricing_registry, get_spend_ledger +from devops_cli.ai.spend.models import ( + HardwarePayoffSummary, + LifetimeSpendReport, + PeriodSpendSummary, +) from devops_cli.config.constants import CONST_AI_BACKEND_HOST_UNKNOWN from devops_cli.core.cli import new_typer from devops_cli.dry_run import dry_run_class, is_dry_run @@ -278,6 +283,93 @@ def _render_stages_table(report: LifetimeSpendReport) -> None: print_table(title="AI Spend & Usage by Execution Stage", columns=cols, rows=rows) +def _validate_range_params( + days: int | None, since: str | None, until: str | None +) -> tuple[str | None, str | None]: + """Validate date range bounds and combinations.""" + if days is not None and since is not None: + raise typer.BadParameter("Cannot combine --days with --since.") + if since is not None: + try: + since_dt = datetime.fromisoformat(since.strip()) + except (ValueError, TypeError) as exc: + raise typer.BadParameter(f"Invalid ISO date or datetime: '{since}'.") from exc + else: + since_dt = None + + if until is not None: + try: + until_dt = datetime.fromisoformat(until.strip()) + except (ValueError, TypeError) as exc: + raise typer.BadParameter(f"Invalid ISO date or datetime: '{until}'.") from exc + else: + until_dt = None + + if since_dt is not None and until_dt is not None: + s_cmp = since_dt if since_dt.tzinfo is not None else since_dt.replace(tzinfo=UTC) + u_cmp = until_dt if until_dt.tzinfo is not None else until_dt.replace(tzinfo=UTC) + if u_cmp < s_cmp: + raise typer.BadParameter("--until cannot be earlier than --since.") + + return since, until + + +def _render_period_table(periods: list[PeriodSpendSummary], by: str) -> None: + """Render spend breakdown by period (day or week).""" + if not periods: + print_info("No spend records found for the given time range.") + return + + cols = [ + ("Period", "cyan"), + ("Requests", "blue"), + ("Local Tokens", "magenta"), + ("Actual Spend (USD)", "bold green"), + ("Hosted Equiv (USD)", "green"), + ("Cloud Spend Avoided (USD)", "bold green"), + ] + rows = [ + [ + p.period, + f"{p.requests:,}", + f"{p.local_tokens:,}", + f"${p.actual_spend:,.4f}", + _usd(p.local_cost_equivalent), + _usd(p.cloud_spend_avoided), + ] + for p in periods + ] + print_table(title=f"AI Spend & ROI by {by.capitalize()}", columns=cols, rows=rows) + + +def _handle_period_report( + ledger: SpendLedger, + by: str | None, + since: str | None, + until: str | None, + days: int | None, + reference_model: str | None, + eff_format: str, +) -> bool: + """Handle period breakdown output for day or week grouping.""" + if by not in ("day", "week"): + return False + periods = ledger.get_period_report( + by=by, + since=since, + until=until, + days=days, + reference_model=reference_model, + ) + if eff_format == "json": + write_stdout(format_json([r.model_dump() for r in periods])) + elif eff_format == "yaml": + write_stdout(yaml.dump([r.model_dump() for r in periods], sort_keys=False)) + else: + _render_period_table(periods, by) + return True + + def _render_report_tables(report: LifetimeSpendReport, by: str) -> None: """Dispatch table rendering based on grouping selection.""" _render_report_summary_table(report) @@ -306,7 +398,7 @@ def cost_default( typer.Option( "--by", "-b", - help="Breakdown grouping dimension: server, model, provider, backend, stage, all.", + help="Breakdown grouping dimension: server, model, provider, backend, stage, day, week, all.", ), ] = "server", days: Annotated[ @@ -317,6 +409,22 @@ def cost_default( help="Filter usage to the last N days (default: all lifetime).", ), ] = None, + since: Annotated[ + str | None, + typer.Option( + "--since", + "-s", + help="Filter usage since ISO date or datetime (default: all lifetime).", + ), + ] = None, + until: Annotated[ + str | None, + typer.Option( + "--until", + "-u", + help="Filter usage until ISO date or datetime (default: all lifetime).", + ), + ] = None, reference_model: Annotated[ str | None, typer.Option( @@ -353,10 +461,17 @@ def cost_default( if ctx.invoked_subcommand is not None: return + _validate_range_params(days, since, until) eff_format = "json" if json_flag else format_opt.lower() ledger = get_spend_ledger() + + if _handle_period_report(ledger, by, since, until, days, reference_model, eff_format): + return + report = ledger.get_lifetime_report( days=days, + since=since, + until=until, group_by=by, reference_model=reference_model, hardware_cost_usd=hardware_cost, @@ -385,7 +500,7 @@ def cost_report( typer.Option( "--by", "-b", - help="Breakdown grouping dimension: server, model, provider, backend, stage, all.", + help="Breakdown grouping dimension: server, model, provider, backend, stage, day, week, all.", ), ] = "server", days: Annotated[ @@ -396,6 +511,22 @@ def cost_report( help="Filter usage to the last N days (default: all lifetime).", ), ] = None, + since: Annotated[ + str | None, + typer.Option( + "--since", + "-s", + help="Filter usage since ISO date or datetime (default: all lifetime).", + ), + ] = None, + until: Annotated[ + str | None, + typer.Option( + "--until", + "-u", + help="Filter usage until ISO date or datetime (default: all lifetime).", + ), + ] = None, reference_model: Annotated[ str | None, typer.Option( @@ -429,10 +560,17 @@ def cost_report( ] = False, ) -> None: """Generate detailed spend and token report across backend services and servers.""" + _validate_range_params(days, since, until) eff_format = "json" if json_flag else format_opt.lower() ledger = get_spend_ledger() + + if _handle_period_report(ledger, by, since, until, days, reference_model, eff_format): + return + report = ledger.get_lifetime_report( days=days, + since=since, + until=until, group_by=by, reference_model=reference_model, hardware_cost_usd=hardware_cost, @@ -480,6 +618,30 @@ def cost_roi( help="Filter usage to the last N days (default: all lifetime).", ), ] = None, + since: Annotated[ + str | None, + typer.Option( + "--since", + "-s", + help="Filter usage since ISO date or datetime (default: all lifetime).", + ), + ] = None, + until: Annotated[ + str | None, + typer.Option( + "--until", + "-u", + help="Filter usage until ISO date or datetime (default: all lifetime).", + ), + ] = None, + by: Annotated[ + str | None, + typer.Option( + "--by", + "-b", + help="Grouping period: day, week.", + ), + ] = None, format_opt: Annotated[ str, typer.Option( @@ -497,10 +659,20 @@ def cost_roi( ] = False, ) -> None: """Monitor pay-off in value for local hardware purchases and local LLM savings.""" + _validate_range_params(days, since, until) + if by is not None and by not in ("day", "week"): + raise typer.BadParameter(f"Invalid grouping '{by}' for roi. Must be 'day' or 'week'.") + eff_format = "json" if json_flag else format_opt.lower() ledger = get_spend_ledger() + + if _handle_period_report(ledger, by, since, until, days, reference_model, eff_format): + return + report = ledger.get_lifetime_report( days=days, + since=since, + until=until, group_by="all", reference_model=reference_model, hardware_cost_usd=hardware_cost, @@ -540,6 +712,18 @@ def cost_payoff( int | None, typer.Option("--days", "-d"), ] = None, + since: Annotated[ + str | None, + typer.Option("--since", "-s"), + ] = None, + until: Annotated[ + str | None, + typer.Option("--until", "-u"), + ] = None, + by: Annotated[ + str | None, + typer.Option("--by", "-b"), + ] = None, format_opt: Annotated[ str, typer.Option("--format", "-f"), @@ -554,6 +738,9 @@ def cost_payoff( hardware_cost=hardware_cost, reference_model=reference_model, days=days, + since=since, + until=until, + by=by, format_opt=format_opt, json_flag=json_flag, ) @@ -574,6 +761,18 @@ def cost_payback( int | None, typer.Option("--days", "-d"), ] = None, + since: Annotated[ + str | None, + typer.Option("--since", "-s"), + ] = None, + until: Annotated[ + str | None, + typer.Option("--until", "-u"), + ] = None, + by: Annotated[ + str | None, + typer.Option("--by", "-b"), + ] = None, format_opt: Annotated[ str, typer.Option("--format", "-f"), @@ -588,6 +787,9 @@ def cost_payback( hardware_cost=hardware_cost, reference_model=reference_model, days=days, + since=since, + until=until, + by=by, format_opt=format_opt, json_flag=json_flag, ) diff --git a/tests/ai/mcp/__snapshots__/test_mcp_tool_listing/test_the_tool_listing_matches_the_snapshot.json b/tests/ai/mcp/__snapshots__/test_mcp_tool_listing/test_the_tool_listing_matches_the_snapshot.json index 8a8215a6bf..695d9e527a 100644 --- a/tests/ai/mcp/__snapshots__/test_mcp_tool_listing/test_the_tool_listing_matches_the_snapshot.json +++ b/tests/ai/mcp/__snapshots__/test_mcp_tool_listing/test_the_tool_listing_matches_the_snapshot.json @@ -205,7 +205,7 @@ "properties": { "by": { "default": "server", - "description": "Breakdown grouping dimension: server, model, provider, backend, stage, all.", + "description": "Breakdown grouping dimension: server, model, provider, backend, stage, day, week, all.", "type": "string" }, "days": { @@ -253,6 +253,30 @@ ], "default": null, "description": "Reference model for counterfactual pricing (default: the ai.reference_model setting)." + }, + "since": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Filter usage since ISO date or datetime (default: all lifetime)." + }, + "until": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Filter usage until ISO date or datetime (default: all lifetime)." } }, "type": "object" diff --git a/tests/ai/mcp/test_mcp_tool_argv.py b/tests/ai/mcp/test_mcp_tool_argv.py index c122709deb..519f1ba07f 100644 --- a/tests/ai/mcp/test_mcp_tool_argv.py +++ b/tests/ai/mcp/test_mcp_tool_argv.py @@ -459,3 +459,24 @@ def test_fastmcp_k8s_security_stream(mcp_dispatcher: DispatcherFake) -> None: assert "--simulate" in cmd assert "--severity" in cmd assert "Critical" in cmd + + +def test_fastmcp_ai_cost_report_range_and_by(mcp_dispatcher: DispatcherFake) -> None: + """Verify ai_cost_report forwards since, until, and by grouping to the CLI (#2193).""" + from devops_cli.ai.mcp.server import ai_cost_report + + mcp_dispatcher.answer("[]") + + res = ai_cost_report(since="2026-10-01", until="2026-10-22", by="week") + + cmd = list(mcp_dispatcher.last.argv) + assert res == "[]" + assert mcp_dispatcher.call_count == 1 + assert cmd[:6] == ["uv", "run", "devops", "ai", "cost", "report"] + assert "--since" in cmd + assert cmd[cmd.index("--since") + 1] == "2026-10-01" + assert "--until" in cmd + assert cmd[cmd.index("--until") + 1] == "2026-10-22" + assert "--by" in cmd + assert cmd[cmd.index("--by") + 1] == "week" + assert cmd[-2:] == ["--format", "json"] diff --git a/tests/ai/spend/test_ai_spend_cli.py b/tests/ai/spend/test_ai_spend_cli.py index fb747a5853..cb9238e6c5 100644 --- a/tests/ai/spend/test_ai_spend_cli.py +++ b/tests/ai/spend/test_ai_spend_cli.py @@ -331,3 +331,291 @@ def test_ai_cost_report_reasoning_share_columns( data = json.loads(res_json.stdout) assert data["total_reasoning_tokens"] == 250 assert any(b.get("reasoning_tokens") == 250 for b in data["backends"]) + + +def test_ai_cost_report_since_until_by_week_json( + cli: Callable[..., Any], mock_spend_env: SpendLedger +) -> None: + """Verify cost report with --since, --until, and --by week produces 3 rows whose sums equal + the ungrouped report of the range (#2193).""" + # Clear and seed test records across October 2026 + mock_spend_env.reset() + records = [ + # Week 1: 2026-10-01 to 2026-10-08 + ("2026-10-02T10:00:00+00:00", 1000, 500, 0.0001), + # Week 2: 2026-10-08 to 2026-10-15 + ("2026-10-10T14:00:00+00:00", 2000, 1000, 0.0002), + # Week 3: 2026-10-15 to 2026-10-22 + ("2026-10-20T16:00:00+00:00", 3000, 1500, 0.0003), + ] + for ts, prompt, comp, cost in records: + mock_spend_env.record_request( + provider="ollama", + server="localhost:11434", + model="llama3:8b", + prompt_tokens=prompt, + completion_tokens=comp, + cost_usd=cost, + timestamp=ts, + ) + + res = cli( + "ai", + "cost", + "report", + "--since", + "2026-10-01", + "--until", + "2026-10-22", + "--by", + "week", + "--json", + ) + assert res.exit_code == 0 + weekly_rows = json.loads(res.stdout) + assert len(weekly_rows) == 3 + assert [r["period"] for r in weekly_rows] == ["2026-10-01", "2026-10-08", "2026-10-15"] + assert [r["requests"] for r in weekly_rows] == [1, 1, 1] + + # Compare with ungrouped report for the same range + res_ungrouped = cli( + "ai", "cost", "report", "--since", "2026-10-01", "--until", "2026-10-22", "--json" + ) + assert res_ungrouped.exit_code == 0 + ungrouped = json.loads(res_ungrouped.stdout) + + assert sum(r["requests"] for r in weekly_rows) == ungrouped["total_requests"] + assert sum(r["local_tokens"] for r in weekly_rows) == ungrouped["local_tokens"] + assert round(sum(r["actual_spend"] for r in weekly_rows), 6) == round( + ungrouped["total_spend_usd"], 6 + ) + assert round(sum(r["local_cost_equivalent"] or 0.0 for r in weekly_rows), 6) == round( + ungrouped["local_cost_equivalent_usd"] or 0.0, 6 + ) + assert round(sum(r["cloud_spend_avoided"] or 0.0 for r in weekly_rows), 6) == round( + ungrouped["counterfactual_savings_usd"] or 0.0, 6 + ) + + +def test_ai_cost_roi_since_until_by_week_json( + cli: Callable[..., Any], mock_spend_env: SpendLedger +) -> None: + """Verify cost roi with --since, --until, and --by week returns expected columns and grouping (#2193).""" + mock_spend_env.reset() + mock_spend_env.record_request( + provider="ollama", + server="localhost:11434", + model="llama3:8b", + prompt_tokens=1000, + completion_tokens=500, + cost_usd=0.0001, + timestamp="2026-10-05T10:00:00+00:00", + ) + mock_spend_env.record_request( + provider="ollama", + server="localhost:11434", + model="llama3:8b", + prompt_tokens=2000, + completion_tokens=1000, + cost_usd=0.0002, + timestamp="2026-10-18T10:00:00+00:00", + ) + + res = cli( + "ai", + "cost", + "roi", + "--since", + "2026-10-01", + "--until", + "2026-10-22", + "--by", + "week", + "--json", + ) + assert res.exit_code == 0 + rows = json.loads(res.stdout) + assert len(rows) == 3 + for row in rows: + assert "requests" in row + assert "local_tokens" in row + assert "actual_spend" in row + assert "local_cost_equivalent" in row + assert "cloud_spend_avoided" in row + + assert [r["requests"] for r in rows] == [1, 0, 1] + + +def test_ai_cost_days_is_short_form_of_since( + cli: Callable[..., Any], mock_spend_env: SpendLedger +) -> None: + """Verify --days N is equivalent to --since set to N days ago (#2193).""" + from datetime import UTC, datetime, timedelta + + mock_spend_env.reset() + now = datetime.now(UTC) + mock_spend_env.record_request( + provider="ollama", + server="localhost:11434", + model="llama3:8b", + prompt_tokens=100, + completion_tokens=50, + cost_usd=0.0001, + timestamp=(now - timedelta(days=2)).isoformat(), + ) + mock_spend_env.record_request( + provider="ollama", + server="localhost:11434", + model="llama3:8b", + prompt_tokens=200, + completion_tokens=100, + cost_usd=0.0002, + timestamp=(now - timedelta(days=12)).isoformat(), + ) + + since_ts = (now - timedelta(days=7)).isoformat() + res_days = cli("ai", "cost", "report", "--days", "7", "--json") + res_since = cli("ai", "cost", "report", "--since", since_ts, "--json") + + assert res_days.exit_code == 0 + assert res_since.exit_code == 0 + data_days = json.loads(res_days.stdout) + data_since = json.loads(res_since.stdout) + assert data_days["total_requests"] == data_since["total_requests"] == 1 + + +def test_ai_cost_conflicting_days_and_since( + cli: Callable[..., Any], mock_spend_env: SpendLedger +) -> None: + """Verify combining --days and --since raises a usage error (#2193).""" + res = cli("ai", "cost", "report", "--days", "7", "--since", "2026-10-01") + assert res.exit_code == 2 + assert "Cannot combine --days with --since" in res.output + + +def test_ai_cost_report_and_roi_table_period_output( + cli: Callable[..., Any], mock_spend_env: SpendLedger +) -> None: + """Verify table format output with --by week for report and roi (#2193).""" + mock_spend_env.reset() + mock_spend_env.record_request( + provider="ollama", + server="localhost:11434", + model="llama3:8b", + prompt_tokens=1000, + completion_tokens=500, + cost_usd=0.0001, + timestamp="2026-10-05T10:00:00+00:00", + ) + + res_report = cli( + "ai", "cost", "report", "--since", "2026-10-01", "--until", "2026-10-22", "--by", "week" + ) + assert res_report.exit_code == 0 + assert "AI Spend & ROI by Week" in res_report.stdout + assert "Local Tokens" in res_report.stdout + assert "Cloud Spend Avoided" in res_report.stdout + + res_roi = cli( + "ai", "cost", "roi", "--since", "2026-10-01", "--until", "2026-10-22", "--by", "week" + ) + assert res_roi.exit_code == 0 + assert "AI Spend & ROI by Week" in res_roi.stdout + + +def test_ai_cost_range_validation_cli_errors( + cli: Callable[..., Any], mock_spend_env: SpendLedger +) -> None: + """Verify validation of malformed and inverted range parameters (#2193).""" + res_bad_since = cli("ai", "cost", "report", "--since", "not-a-date") + assert res_bad_since.exit_code == 2 + assert "Invalid ISO date or datetime" in res_bad_since.output + + res_bad_until = cli("ai", "cost", "report", "--until", "not-a-date") + assert res_bad_until.exit_code == 2 + assert "Invalid ISO date or datetime" in res_bad_until.output + + res_inverted = cli("ai", "cost", "report", "--since", "2026-10-20", "--until", "2026-10-10") + assert res_inverted.exit_code == 2 + assert "--until cannot be earlier than --since" in res_inverted.output + + res_bad_roi_by = cli("ai", "cost", "roi", "--by", "month") + assert res_bad_roi_by.exit_code == 2 + assert "Invalid grouping 'month' for roi" in res_bad_roi_by.output + + +def test_ai_cost_period_formats_and_aliases( + cli: Callable[..., Any], mock_spend_env: SpendLedger +) -> None: + """Verify period reports across output formats and command aliases (#2193).""" + mock_spend_env.reset() + # Empty period table output when no spend records exist + res_empty_table = cli("ai", "cost", "report", "--by", "day") + assert res_empty_table.exit_code == 0 + assert "No spend records found" in res_empty_table.stdout + + mock_spend_env.record_request( + provider="ollama", + server="localhost:11434", + model="llama3:8b", + prompt_tokens=500, + completion_tokens=250, + cost_usd=0.0001, + timestamp="2026-10-05T10:00:00+00:00", + ) + + # YAML format on report + res_yaml = cli( + "ai", + "cost", + "report", + "--since", + "2026-10-01", + "--until", + "2026-10-22", + "--by", + "week", + "--format", + "yaml", + ) + assert res_yaml.exit_code == 0 + assert "period: '2026-10-01'" in res_yaml.stdout or "period: 2026-10-01" in res_yaml.stdout + + # devops ai cost (cost_default) with period breakdown + res_default = cli( + "ai", "cost", "--since", "2026-10-01", "--until", "2026-10-22", "--by", "week", "--json" + ) + assert res_default.exit_code == 0 + assert len(json.loads(res_default.stdout)) == 3 + + # devops ai cost payoff with period breakdown + res_payoff = cli( + "ai", + "cost", + "payoff", + "--since", + "2026-10-01", + "--until", + "2026-10-22", + "--by", + "week", + "--json", + ) + assert res_payoff.exit_code == 0 + assert len(json.loads(res_payoff.stdout)) == 3 + + # devops ai cost payback with period breakdown + res_payback = cli( + "ai", + "cost", + "payback", + "--since", + "2026-10-01", + "--until", + "2026-10-22", + "--by", + "week", + "--json", + ) + assert res_payback.exit_code == 0 + assert len(json.loads(res_payback.stdout)) == 3 diff --git a/tests/ai/spend/test_ai_spend_ledger.py b/tests/ai/spend/test_ai_spend_ledger.py index 94ea66241e..a9d7997dda 100644 --- a/tests/ai/spend/test_ai_spend_ledger.py +++ b/tests/ai/spend/test_ai_spend_ledger.py @@ -1298,3 +1298,130 @@ def test_a_gateway_call_on_a_hosted_group_with_no_reply_name_is_priced_by_the_as "SELECT served_model, pricing_source, cost_usd FROM ai_spend_records" ).fetchone() assert (served, source, cost > 0) == expected + + +def test_spend_ledger_since_until_filtering(tmp_path: Path) -> None: + """Verify since and until bounds filter spend records (#2193).""" + ledger = SpendLedger(db_path=tmp_path / "filter_range.db") + + timestamps = [ + ("before-since", "2026-09-30T23:59:59+00:00"), + ("on-since", "2026-10-01T00:00:00+00:00"), + ("inside-range", "2026-10-10T12:00:00+00:00"), + ("inside-late", "2026-10-21T23:59:59+00:00"), + ("on-until", "2026-10-22T00:00:00+00:00"), + ("after-until", "2026-10-25T10:00:00+00:00"), + ] + for model_name, ts in timestamps: + ledger.record_request( + provider="ollama", + server="localhost:11434", + model=model_name, + prompt_tokens=100, + completion_tokens=50, + cost_usd=0.001, + timestamp=ts, + ) + + report = ledger.get_lifetime_report(since="2026-10-01", until="2026-10-22", group_by="model") + models = {m.model for m in report.models} + assert ( + report.total_requests, + "before-since" in models, + "on-since" in models, + "inside-range" in models, + "inside-late" in models, + "on-until" in models, + "after-until" in models, + ) == (3, False, True, True, True, False, False) + + +def test_spend_ledger_get_period_report_day_and_week(tmp_path: Path) -> None: + """Verify get_period_report breaks spend into day or week buckets (#2193).""" + ledger = SpendLedger(db_path=tmp_path / "periods.db") + + # Record 1 call in week 1, 1 call in week 2, 1 call in week 3 + ledger.record_request( + provider="ollama", + server="localhost:11434", + model="llama3:8b", + prompt_tokens=1000, + completion_tokens=500, + cost_usd=0.0001, + timestamp="2026-10-02T10:00:00+00:00", + ) + ledger.record_request( + provider="ollama", + server="localhost:11434", + model="llama3:8b", + prompt_tokens=2000, + completion_tokens=1000, + cost_usd=0.0002, + timestamp="2026-10-09T10:00:00+00:00", + ) + ledger.record_request( + provider="ollama", + server="localhost:11434", + model="llama3:8b", + prompt_tokens=3000, + completion_tokens=1500, + cost_usd=0.0003, + timestamp="2026-10-16T10:00:00+00:00", + ) + + weeks = ledger.get_period_report(by="week", since="2026-10-01", until="2026-10-22") + assert len(weeks) == 3 + assert [w.period for w in weeks] == ["2026-10-01", "2026-10-08", "2026-10-15"] + assert [w.requests for w in weeks] == [1, 1, 1] + + ungrouped = ledger.get_lifetime_report(since="2026-10-01", until="2026-10-22") + assert sum(w.requests for w in weeks) == ungrouped.total_requests + assert sum(w.local_tokens for w in weeks) == ungrouped.local_tokens + assert round(sum(w.actual_spend for w in weeks), 6) == round(ungrouped.total_spend_usd, 6) + assert round(sum(w.local_cost_equivalent or 0.0 for w in weeks), 6) == round( + ungrouped.local_cost_equivalent_usd or 0.0, 6 + ) + assert round(sum(w.cloud_spend_avoided or 0.0 for w in weeks), 6) == round( + ungrouped.counterfactual_savings_usd or 0.0, 6 + ) + + days = ledger.get_period_report(by="day", since="2026-10-01", until="2026-10-04") + assert len(days) == 3 + assert [d.period for d in days] == ["2026-10-01", "2026-10-02", "2026-10-03"] + assert [d.requests for d in days] == [0, 1, 0] + + +def test_spend_ledger_period_report_validation_and_defaults(tmp_path: Path) -> None: + """Verify get_period_report parameter validation and default boundaries (#2193).""" + from devops_cli.ai.spend.ledger import _to_utc_datetime + + with pytest.raises(ValueError, match="Invalid ISO date or datetime"): + _to_utc_datetime("not-an-iso-date") + + empty_ledger = SpendLedger(db_path=tmp_path / "empty.db") + assert empty_ledger.get_period_report(by="day") == [] + + with pytest.raises(ValueError, match="Invalid period grouping"): + empty_ledger.get_period_report(by="hour") + + with pytest.raises(ValueError, match="--until cannot be earlier than --since"): + empty_ledger.get_period_report(by="day", since="2026-10-20", until="2026-10-10") + + # Test days parameter without explicit since/until + days_report = empty_ledger.get_period_report(by="day", days=2) + assert len(days_report) >= 2 + + # Test populated ledger with default since and until (both None) + ledger = SpendLedger(db_path=tmp_path / "defaults.db") + ledger.record_request( + provider="ollama", + server="localhost:11434", + model="llama3:8b", + prompt_tokens=100, + completion_tokens=50, + cost_usd=0.0001, + timestamp=(datetime.now(UTC) - timedelta(days=2)).isoformat(), + ) + unbounded = ledger.get_period_report(by="day") + assert len(unbounded) >= 2 + assert sum(p.requests for p in unbounded) == 1 From cdb3b14d50ed3f463f4a1d340b726e13097da400 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Mon, 9 Nov 2026 18:51:04 +0000 Subject: [PATCH 2/2] chore(openspec): archive 2193-add-since-until-and-by-to --- .../.openspec.yaml | 0 .../design.md | 0 .../proposal.md | 0 .../specs/ai-spend-pricing/spec.md | 0 .../tasks.md | 0 openspec/specs/ai-spend-pricing/spec.md | 15 +++++++++++++++ 6 files changed, 15 insertions(+) rename openspec/changes/{2193-add-since-until-and-by-to => archive/2026-11-09-2193-add-since-until-and-by-to}/.openspec.yaml (100%) rename openspec/changes/{2193-add-since-until-and-by-to => archive/2026-11-09-2193-add-since-until-and-by-to}/design.md (100%) rename openspec/changes/{2193-add-since-until-and-by-to => archive/2026-11-09-2193-add-since-until-and-by-to}/proposal.md (100%) rename openspec/changes/{2193-add-since-until-and-by-to => archive/2026-11-09-2193-add-since-until-and-by-to}/specs/ai-spend-pricing/spec.md (100%) rename openspec/changes/{2193-add-since-until-and-by-to => archive/2026-11-09-2193-add-since-until-and-by-to}/tasks.md (100%) diff --git a/openspec/changes/2193-add-since-until-and-by-to/.openspec.yaml b/openspec/changes/archive/2026-11-09-2193-add-since-until-and-by-to/.openspec.yaml similarity index 100% rename from openspec/changes/2193-add-since-until-and-by-to/.openspec.yaml rename to openspec/changes/archive/2026-11-09-2193-add-since-until-and-by-to/.openspec.yaml diff --git a/openspec/changes/2193-add-since-until-and-by-to/design.md b/openspec/changes/archive/2026-11-09-2193-add-since-until-and-by-to/design.md similarity index 100% rename from openspec/changes/2193-add-since-until-and-by-to/design.md rename to openspec/changes/archive/2026-11-09-2193-add-since-until-and-by-to/design.md diff --git a/openspec/changes/2193-add-since-until-and-by-to/proposal.md b/openspec/changes/archive/2026-11-09-2193-add-since-until-and-by-to/proposal.md similarity index 100% rename from openspec/changes/2193-add-since-until-and-by-to/proposal.md rename to openspec/changes/archive/2026-11-09-2193-add-since-until-and-by-to/proposal.md diff --git a/openspec/changes/2193-add-since-until-and-by-to/specs/ai-spend-pricing/spec.md b/openspec/changes/archive/2026-11-09-2193-add-since-until-and-by-to/specs/ai-spend-pricing/spec.md similarity index 100% rename from openspec/changes/2193-add-since-until-and-by-to/specs/ai-spend-pricing/spec.md rename to openspec/changes/archive/2026-11-09-2193-add-since-until-and-by-to/specs/ai-spend-pricing/spec.md diff --git a/openspec/changes/2193-add-since-until-and-by-to/tasks.md b/openspec/changes/archive/2026-11-09-2193-add-since-until-and-by-to/tasks.md similarity index 100% rename from openspec/changes/2193-add-since-until-and-by-to/tasks.md rename to openspec/changes/archive/2026-11-09-2193-add-since-until-and-by-to/tasks.md diff --git a/openspec/specs/ai-spend-pricing/spec.md b/openspec/specs/ai-spend-pricing/spec.md index 4ba114fd56..b31c75edf5 100644 --- a/openspec/specs/ai-spend-pricing/spec.md +++ b/openspec/specs/ai-spend-pricing/spec.md @@ -267,3 +267,18 @@ When `pricing_overrides.json` and `ai.price_overrides` both price the same model #### Scenario: A hand price is removed - **WHEN** a person sets a hand price for `qwen3.8:27b` and then removes it - **THEN** the price of `qwen3.8:27b` is the price of the setting again. + +### Requirement: Spend report and ROI accept time range and period grouping +The `devops ai cost report` and `devops ai cost roi` commands SHALL accept `--since` and `--until` for ISO dates or datetimes (UTC unless an offset is specified), and SHALL accept `--by day` and `--by week` to return spend, token and savings summaries grouped by period. The `--days N` flag SHALL remain as a short form equivalent to `--since` set to `N` days before the current time. + +#### Scenario: Cost report grouped by week across a date range +- **WHEN** `devops ai cost report --since 2026-10-01 --until 2026-10-22 --by week --json` runs against a ledger +- **THEN** it outputs three period rows whose column sums equal the ungrouped report for the same date range + +#### Scenario: Cost ROI grouped by week +- **WHEN** `devops ai cost roi --since 2026-10-01 --until 2026-10-22 --by week --json` runs against a ledger +- **THEN** each period row contains requests, local tokens, actual spend, local cost equivalent, and cloud spend avoided + +#### Scenario: The MCP tool ai_cost_report accepts date range and grouping +- **WHEN** the MCP tool `ai_cost_report` is called with `since`, `until`, and `by` +- **THEN** it passes the options to the command line and returns the matching report