Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(metrics): honor providers and mark partial cost estimates (#7283)

LearningCircuited4bbaea1d23
diff --git a/changelog.d/+provider-cost-calculation.bugfix.md b/changelog.d/+provider-cost-calculation.bugfix.md
new file mode 100644
index 0000000000..1e11886793
--- /dev/null
+++ b/changelog.d/+provider-cost-calculation.bugfix.md
@@ -0,0 +1,3 @@
+Honor the selected provider in pricing and cost endpoints and use each saved token record's provider when calculating research costs. Synchronous and asynchronous calculations now share provider-scoped cached prices and the same static fallback, including zero model fees for local providers.
+
+Research cost summaries now include a provider breakdown and explicit counts of calls and tokens whose price is unknown, while retaining the existing model totals. The dashboard marks estimates as partial when prices are missing or the existing 1,000-call limit excludes older usage, and its per-research average uses the number of research sessions.
diff --git a/src/local_deep_research/metrics/pricing/cost_calculator.py b/src/local_deep_research/metrics/pricing/cost_calculator.py
index 1c36e13476..4faa99b90b 100644
--- a/src/local_deep_research/metrics/pricing/cost_calculator.py
+++ b/src/local_deep_research/metrics/pricing/cost_calculator.py
@@ -134,6 +134,7 @@ class CostCalculator:
"prompt_cost": 0.0,
"completion_cost": 0.0,
"total_cost": 0.0,
+ "pricing_used": None,
"error": "Cost calculation failed",
}
)
@@ -141,24 +142,22 @@ class CostCalculator:
return results
def calculate_cost_sync(
- self, model_name: str, prompt_tokens: int, completion_tokens: int
+ self,
+ model_name: str,
+ prompt_tokens: int,
+ completion_tokens: int,
+ provider: Optional[str] = None,
) -> Dict[str, float]:
"""
- Synchronous cost calculation using cached pricing only.
- Fallback for when async is not available.
+ Synchronous cost calculation using provider-scoped cache entries and
+ the same static fallback as the async path. No network I/O is used.
"""
# Use cached pricing only
- pricing = self.cache.get_model_pricing(model_name)
+ cache_key = f"{provider}:{model_name}" if provider else model_name
+ pricing = self.cache.get_model_pricing(cache_key)
if not pricing:
- # Use static fallback with exact matching only
fetcher = PricingFetcher()
- # Try exact match
- pricing = fetcher.static_pricing.get(model_name)
- if not pricing:
- # Try exact match without provider prefix
- if "/" in model_name:
- model_only = model_name.split("/")[-1]
- pricing = fetcher.static_pricing.get(model_only)
+ pricing = fetcher.get_static_model_pricing(model_name, provider)
# If no pricing found, return zero cost
if not pricing:
@@ -184,53 +183,94 @@ class CostCalculator:
async def get_research_cost_summary(
self, usage_records: List[Dict[str, Any]]
) -> Dict[str, Any]:
- """
- Get cost summary for research session(s).
+ """Get cost summary for research session(s).
+
+ ``model_breakdown`` retains totals grouped by model name.
+ ``provider_breakdown`` lists each distinct model/provider pair;
+ separate fields keep names containing separators unambiguous and
+ allow the summary to be serialized as JSON.
+
+ Cost totals cover only successfully priced usage; the existing
+ averages divide those totals by all calls/tokens. ``unpriced_calls``
+ and ``unpriced_tokens`` identify incomplete totals. A known zero
+ price (for example, Ollama) is fully priced.
"""
costs = await self.calculate_batch_costs(usage_records)
+ return summarize_costs(costs)
+
+
+def summarize_costs(costs: List[Dict[str, Any]]) -> Dict[str, Any]:
+ """Aggregate calculated usage records from either pricing path."""
+ total_cost = sum(c["total_cost"] for c in costs)
+ total_prompt_cost = sum(c["prompt_cost"] for c in costs)
+ total_completion_cost = sum(c["completion_cost"] for c in costs)
+
+ total_prompt_tokens = sum(c["prompt_tokens"] for c in costs)
+ total_completion_tokens = sum(c["completion_tokens"] for c in costs)
+ total_tokens = total_prompt_tokens + total_completion_tokens
+
+ # Keep the existing model totals and a separate provider breakdown.
+ model_costs = {}
+ provider_costs = {}
+ unpriced_calls = 0
+ unpriced_tokens = 0
+ for cost in costs:
+ model = cost["model_name"]
+ if model not in model_costs:
+ model_costs[model] = {
+ "total_cost": 0.0,
+ "prompt_tokens": 0,
+ "completion_tokens": 0,
+ "calls": 0,
+ }
- total_cost = sum(c["total_cost"] for c in costs)
- total_prompt_cost = sum(c["prompt_cost"] for c in costs)
- total_completion_cost = sum(c["completion_cost"] for c in costs)
-
- total_prompt_tokens = sum(r["prompt_tokens"] for r in usage_records)
- total_completion_tokens = sum(
- r["completion_tokens"] for r in usage_records
- )
- total_tokens = total_prompt_tokens + total_completion_tokens
-
- # Model breakdown
- model_costs = {}
- for cost in costs:
- model = cost["model_name"]
- if model not in model_costs:
- model_costs[model] = {
- "total_cost": 0.0,
- "prompt_tokens": 0,
- "completion_tokens": 0,
- "calls": 0,
- }
-
- model_costs[model]["total_cost"] += cost["total_cost"]
- model_costs[model]["prompt_tokens"] += cost["prompt_tokens"]
- model_costs[model]["completion_tokens"] += cost["completion_tokens"]
- model_costs[model]["calls"] += 1
+ provider = cost.get("provider")
+ key = (model, provider)
+ if key not in provider_costs:
+ provider_costs[key] = {
+ "model_name": model,
+ "provider": provider,
+ "total_cost": 0.0,
+ "prompt_tokens": 0,
+ "completion_tokens": 0,
+ "calls": 0,
+ "unpriced_calls": 0,
+ "unpriced_tokens": 0,
+ }
- return {
- "total_cost": round(total_cost, 6),
- "prompt_cost": round(total_prompt_cost, 6),
- "completion_cost": round(total_completion_cost, 6),
- "total_tokens": total_tokens,
- "prompt_tokens": total_prompt_tokens,
- "completion_tokens": total_completion_tokens,
- "total_calls": len(usage_records),
- "model_breakdown": model_costs,
- "avg_cost_per_call": (
- round(total_cost / len(usage_records), 6)
- if usage_records
- else 0.0
- ),
- "cost_per_token": (
- round(total_cost / total_tokens, 8) if total_tokens > 0 else 0.0
- ),
- }
+ for bucket in (model_costs[model], provider_costs[key]):
+ bucket["total_cost"] += cost["total_cost"]
+ bucket["prompt_tokens"] += cost["prompt_tokens"]
+ bucket["completion_tokens"] += cost["completion_tokens"]
+ bucket["calls"] += 1
+
+ if cost.get("pricing_used") is None:
+ tokens = cost["prompt_tokens"] + cost["completion_tokens"]
+ unpriced_calls += 1
+ unpriced_tokens += tokens
+ provider_costs[key]["unpriced_calls"] += 1
+ provider_costs[key]["unpriced_tokens"] += tokens
+
+ for bucket in provider_costs.values():
+ bucket["total_cost"] = round(bucket["total_cost"], 6)
+
+ return {
+ "total_cost": round(total_cost, 6),
+ "prompt_cost": round(total_prompt_cost, 6),
+ "completion_cost": round(total_completion_cost, 6),
+ "total_tokens": total_tokens,
+ "prompt_tokens": total_prompt_tokens,
+ "completion_tokens": total_completion_tokens,
+ "total_calls": len(costs),
+ "model_breakdown": model_costs,
+ "provider_breakdown": list(provider_costs.values()),
+ "pricing_complete": unpriced_calls == 0,
+ "unpriced_calls": unpriced_calls,
+ "unpriced_tokens": unpriced_tokens,
+ "avg_cost_per_call": round(total_cost / len(costs), 6)
+ if costs
+ else 0.0,
+ "cost_per_token": (
+ round(total_cost / total_tokens, 8) if total_tokens > 0 else 0.0
+ ),
+ }
diff --git a/src/local_deep_research/metrics/pricing/pricing_fetcher.py b/src/local_deep_research/metrics/pricing/pricing_fetcher.py
index cd5ccd4f88..260b3785b3 100644
--- a/src/local_deep_research/metrics/pricing/pricing_fetcher.py
+++ b/src/local_deep_research/metrics/pricing/pricing_fetcher.py
@@ -64,6 +64,12 @@ class PricingFetcher:
self, model_name: str, provider: str = None
) -> Optional[Dict[str, float]]:
"""Get pricing for a specific model and provider."""
+ return self.get_static_model_pricing(model_name, provider)
+
+ def get_static_model_pricing(
+ self, model_name: str, provider: Optional[str] = None
+ ) -> Optional[Dict[str, float]]:
+ """Resolve provider-aware fallback pricing without network I/O."""
# Normalize inputs
model_name = model_name.lower() if model_name else ""
provider = normalize_provider(provider) or ""
diff --git a/src/local_deep_research/web/routers/metrics.py b/src/local_deep_research/web/routers/metrics.py
index dc61ea263e..2cf9bb8513 100644
--- a/src/local_deep_research/web/routers/metrics.py
+++ b/src/local_deep_research/web/routers/metrics.py
@@ -1892,11 +1892,9 @@ def api_model_pricing(
# Use synchronous approach with cached/static pricing
calculator = CostCalculator()
- pricing = calculator.cache.get_model_pricing(
- model_name
- ) or calculator.calculate_cost_sync(model_name, 1000, 1000).get(
- "pricing_used", {}
- )
+ pricing = calculator.calculate_cost_sync(
+ model_name, 1000, 1000, provider=provider
+ ).get("pricing_used", {})
return {
"status": "success",
@@ -1939,6 +1937,10 @@ async def api_cost_calculation(
return JSONResponse(
{"error": "model_name is required"}, status_code=400
)
+ if provider is not None and not isinstance(provider, str):
+ return JSONResponse(
+ {"error": "provider must be a string"}, status_code=400
+ )
from ...metrics.pricing.cost_calculator import CostCalculator
import asyncio as _asyncio
@@ -1951,6 +1953,7 @@ async def api_cost_calculation(
model_name,
prompt_tokens,
completion_tokens,
+ provider=provider,
)
return {
@@ -1978,6 +1981,11 @@ def api_research_costs(
):
"""Get cost analysis for a specific research session."""
try:
+ from ...metrics.pricing.cost_calculator import (
+ CostCalculator,
+ summarize_costs,
+ )
+
with get_user_db_session(username) as session:
# Get token usage records for this research
usage_records = (
@@ -1990,7 +1998,7 @@ def api_research_costs(
return {
"status": "success",
"research_id": research_id,
- "total_cost": 0.0,
+ **summarize_costs([]),
"message": "No token usage data found for this research session",
}
@@ -2001,7 +2009,7 @@ def api_research_costs(
{
"model_name": record.model_name,
"provider": getattr(
- record, "provider", None
+ record, "model_provider", None
), # Handle both old and new records
"prompt_tokens": record.prompt_tokens,
"completion_tokens": record.completion_tokens,
@@ -2009,8 +2017,6 @@ def api_research_costs(
}
)
- from ...metrics.pricing.cost_calculator import CostCalculator
-
# Use synchronous calculation for research costs
calculator = CostCalculator()
costs = []
@@ -2019,26 +2025,14 @@ def api_research_costs(
record["model_name"],
record["prompt_tokens"],
record["completion_tokens"],
+ provider=record["provider"],
)
costs.append({**record, **cost_data})
- total_cost = sum(c["total_cost"] for c in costs)
- total_prompt_tokens = sum(r["prompt_tokens"] for r in usage_data)
- total_completion_tokens = sum(
- r["completion_tokens"] for r in usage_data
- )
-
- cost_summary = {
- "total_cost": round(total_cost, 6),
- "total_tokens": total_prompt_tokens + total_completion_tokens,
- "prompt_tokens": total_prompt_tokens,
- "completion_tokens": total_completion_tokens,
- }
-
return {
"status": "success",
"research_id": research_id,
- **cost_summary,
+ **summarize_costs(costs),
}
except Exception:
@@ -2056,6 +2050,11 @@ def api_cost_analytics(
):
"""Get cost analytics across all research sessions."""
try:
+ from ...metrics.pricing.cost_calculator import (
+ CostCalculator,
+ summarize_costs,
+ )
+
period = request.query_params.get("period", "30d")
with get_user_db_session(username) as session:
@@ -2075,10 +2074,10 @@ def api_cost_analytics(
"status": "success",
"period": period,
"overview": {
- "total_cost": 0.0,
- "total_tokens": 0,
- "prompt_tokens": 0,
- "completion_tokens": 0,
+ **summarize_costs([]),
+ "avg_cost_per_research": 0.0,
+ "total_matching_calls": 0,
+ "usage_truncated": False,
},
"top_expensive_research": [],
"research_count": 0,
@@ -2105,7 +2104,7 @@ def api_cost_analytics(
{
"model_name": record.model_name,
"provider": getattr(
- record, "provider", None
+ record, "model_provider", None
), # Handle both old and new records
"prompt_tokens": record.prompt_tokens,
"completion_tokens": record.completion_tokens,
@@ -2114,8 +2113,6 @@ def api_cost_analytics(
}
)
- from ...metrics.pricing.cost_calculator import CostCalculator
-
# Use synchronous calculation
calculator = CostCalculator()
@@ -2126,52 +2123,37 @@ def api_cost_analytics(
record["model_name"],
record["prompt_tokens"],
record["completion_tokens"],
+ provider=record["provider"],
)
costs.append({**record, **cost_data})
- total_cost = sum(c["total_cost"] for c in costs)
- total_prompt_tokens = sum(r["prompt_tokens"] for r in usage_data)
- total_completion_tokens = sum(
- r["completion_tokens"] for r in usage_data
- )
-
- cost_summary = {
- "total_cost": round(total_cost, 6),
- "total_tokens": total_prompt_tokens + total_completion_tokens,
- "prompt_tokens": total_prompt_tokens,
- "completion_tokens": total_completion_tokens,
- }
+ cost_summary = summarize_costs(costs)
+ cost_summary["total_matching_calls"] = record_count
+ cost_summary["usage_truncated"] = record_count > len(costs)
# Group by research_id for per-research costs
research_costs: dict[str, Any] = {}
- for record in usage_data:
+ for record in costs:
rid = record["research_id"]
if rid not in research_costs:
research_costs[rid] = []
research_costs[rid].append(record)
# Calculate cost per research
- research_summaries = {}
- for rid, records in research_costs.items():
- research_total: float = 0
- for record in records:
- cost_data = calculator.calculate_cost_sync(
- record["model_name"],
- record["prompt_tokens"],
- record["completion_tokens"],
- )
- research_total += cost_data["total_cost"]
- research_summaries[rid] = {
- "total_cost": round(research_total, 6)
- }
+ research_summaries = {
+ rid: summarize_costs(records)
+ for rid, records in research_costs.items()
+ }
+ cost_summary["avg_cost_per_research"] = (
+ round(cost_summary["total_cost"] / len(research_summaries), 6)
+ if research_summaries
+ else 0.0
+ )
# Top expensive research sessions
top_expensive = sorted(
- [
- (rid, data["total_cost"])
- for rid, data in research_summaries.items()
- ],
- key=lambda x: x[1],
+ research_summaries.items(),
+ key=lambda x: x[1]["total_cost"],
reverse=True,
)[:10]
@@ -2180,8 +2162,14 @@ def api_cost_analytics(
"period": period,
"overview": cost_summary,
"top_expensive_research": [
- {"research_id": rid, "total_cost": cost}
- for rid, cost in top_expensive
+ {
+ "research_id": rid,
+ "total_cost": data["total_cost"],
+ "pricing_complete": data["pricing_complete"],
+ "unpriced_calls": data["unpriced_calls"],
+ "unpriced_tokens": data["unpriced_tokens"],
+ }
+ for rid, data in top_expensive
],
"research_count": len(research_summaries),
}
diff --git a/src/local_deep_research/web/templates/pages/metrics.html b/src/local_deep_research/web/templates/pages/metrics.html
index a6f0a6c24d..9d750d700f 100644
--- a/src/local_deep_research/web/templates/pages/metrics.html
+++ b/src/local_deep_research/web/templates/pages/metrics.html
@@ -179,6 +179,7 @@
<i class="fas fa-chevron-down" id="cost-expand-icon"></i>
</div>
</div>
+ <p id="cost-pricing-warning" class="ldr-status-warning" role="status" hidden></p>
<div class="ldr-metric-details" id="cost-details" style="display: none;">
<div class="ldr-cost-breakdown">
<div class="ldr-breakdown-section">
@@ -1410,6 +1411,9 @@
}
// Display cost data in the dashboard
function displayCostData(costData) {
+ const warning = document.getElementById('cost-pricing-warning');
+ warning.hidden = true;
+ warning.textContent = '';
if (!costData || !costData.overview) {
// No cost data available, show dashes
document.getElementById('total-cost').textContent = '-';
@@ -1421,10 +1425,22 @@
return;
}
const overview = costData.overview;
+ const incompleteReasons = [];
+ if (overview.pricing_complete === false) {
+ const calls = overview.unpriced_calls;
+ incompleteReasons.push(`Prices unavailable for ${formatNumber(calls)} call${calls === 1 ? '' : 's'} (${formatNumber(overview.unpriced_tokens)} tokens).`);
+ }
+ if (overview.usage_truncated) {
+ incompleteReasons.push(`Showing ${formatNumber(overview.total_calls)} of ${formatNumber(overview.total_matching_calls)} calls.`);
+ }
+ if (incompleteReasons.length) {
+ warning.textContent = `Partial estimate. ${incompleteReasons.join(' ')}`;
+ warning.hidden = false;
+ }
// Main cost display
document.getElementById('total-cost').textContent = formatCurrency(overview.total_cost);
// Cost breakdown details
- document.getElementById('avg-cost-per-research').textContent = formatCurrency(overview.avg_cost_per_call);
+ document.getElementById('avg-cost-per-research').textContent = formatCurrency(overview.avg_cost_per_research);
document.getElementById('avg-cost-per-token').textContent = formatCurrency(overview.cost_per_token);
document.getElementById('total-input-cost').textContent = formatCurrency(overview.prompt_cost);
document.getElementById('total-output-cost').textContent = formatCurrency(overview.completion_cost);
@@ -1590,12 +1606,7 @@
document.getElementById('total-output-tokens').textContent = '0';
document.getElementById('total-all-tokens').textContent = '0';
// Reset cost breakdown details
- document.getElementById('total-cost').textContent = '-';
- document.getElementById('avg-cost-per-research').textContent = '-';
- document.getElementById('avg-cost-per-token').textContent = '-';
- document.getElementById('total-input-cost').textContent = '-';
- document.getElementById('total-output-cost').textContent = '-';
- document.getElementById('total-cost-breakdown').textContent = '-';
+ displayCostData(null);
// Reset rate limiting metrics
document.getElementById('rate-limit-success-rate').textContent = '-';
document.getElementById('avg-wait-time').textContent = '-';
diff --git a/tests/js/pages/metrics-dashboard-runtime.test.js b/tests/js/pages/metrics-dashboard-runtime.test.js
index c7497e48d2..3dcc59baed 100644
--- a/tests/js/pages/metrics-dashboard-runtime.test.js
+++ b/tests/js/pages/metrics-dashboard-runtime.test.js
@@ -2,6 +2,7 @@
* Runtime contracts for the metrics dashboard's inline FastAPI consumers.
*/
+import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { compileTemplateHarness } from '../helpers/template-harness.js';
@@ -531,3 +532,128 @@ it('renders unavailable secondary analytics on HTTP and network failures', async
expect(displayCostData).toHaveBeenCalledWith(null);
expect(displayRateLimitingData).toHaveBeenCalledWith(null);
});
+
+function costRenderer() {
+ const source = readFileSync(TEMPLATE_PATH, 'utf8');
+ const start = source.lastIndexOf('<div', source.indexOf('id="cost-toggle-btn"'));
+ const end = source.indexOf('<!-- Charts Section -->', start);
+ if (start < 0 || end < 0) throw new Error('Cost card markup not found');
+ // Parse only this card so the DOM emulator cannot load page assets.
+ const parsed = new window.DOMParser().parseFromString(
+ source.slice(start, end), 'text/html',
+ );
+ document.body.appendChild(
+ document.importNode(parsed.getElementById('cost-toggle-btn'), true),
+ );
+ return compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: [
+ 'displayCostData', 'showEmptyState', 'formatNumber', 'formatCurrency',
+ ],
+ dependencies: { showEmptyChartsAndTables: vi.fn() },
+ returnExpression: '({ displayCostData, showEmptyState })',
+ });
+}
+
+function costOverview(overrides = {}) {
+ return {
+ total_cost: 0.09,
+ prompt_cost: 0.03,
+ completion_cost: 0.06,
+ avg_cost_per_research: 0.045,
+ avg_cost_per_call: 0.03,
+ cost_per_token: 0.000018,
+ pricing_complete: true,
+ unpriced_calls: 0,
+ unpriced_tokens: 0,
+ usage_truncated: false,
+ total_calls: 3,
+ total_matching_calls: 3,
+ ...overrides,
+ };
+}
+
+it('renders partial pricing and the actual per-research cost average', () => {
+ const runtime = costRenderer();
+
+ runtime.displayCostData({ overview: costOverview({
+ pricing_complete: false, unpriced_calls: 1, unpriced_tokens: 1500,
+ }) });
+
+ expect(document.getElementById('total-cost').textContent).toBe('$0.0900');
+ expect(document.getElementById('total-input-cost').textContent).toBe('$0.0300');
+ expect(document.getElementById('total-output-cost').textContent).toBe('$0.0600');
+ expect(document.getElementById('avg-cost-per-research').textContent).toBe('$0.0450');
+ const warning = document.getElementById('cost-pricing-warning');
+ expect(warning.hidden).toBe(false);
+ expect(warning.textContent).toBe(
+ 'Partial estimate. Prices unavailable for 1 call (1,500 tokens).',
+ );
+});
+
+it('distinguishes unpriced zero cost from known free usage and clears stale warnings', () => {
+ const runtime = costRenderer();
+ const unknown = costOverview({
+ total_cost: 0, pricing_complete: false, unpriced_calls: 2, unpriced_tokens: 30,
+ });
+ runtime.displayCostData({ overview: unknown });
+ expect(document.getElementById('total-cost').textContent).toBe('$0.000000');
+ const warning = document.getElementById('cost-pricing-warning');
+ expect(warning.hidden).toBe(false);
+ expect(warning.textContent).toContain('2 calls (30 tokens)');
+
+ runtime.displayCostData({ overview: costOverview({ total_cost: 0 }) });
+ expect(document.getElementById('total-cost').textContent).toBe('$0.000000');
+ expect(warning.hidden).toBe(true);
+ expect(warning.textContent).toBe('');
+
+ runtime.displayCostData({ overview: unknown });
+ runtime.displayCostData(null);
+ expect(warning.hidden).toBe(true);
+ expect(warning.textContent).toBe('');
+ for (const id of [
+ 'total-cost', 'avg-cost-per-research', 'avg-cost-per-token',
+ 'total-input-cost', 'total-output-cost', 'total-cost-breakdown',
+ ]) {
+ expect(document.getElementById(id).textContent).toBe('-');
+ }
+});
+
+it.each([0, 2])('marks capped usage as partial with %i unpriced calls', unpriced => {
+ const runtime = costRenderer();
+
+ runtime.displayCostData({ overview: costOverview({
+ usage_truncated: true, total_calls: 1000, total_matching_calls: 1500,
+ pricing_complete: unpriced === 0, unpriced_calls: unpriced, unpriced_tokens: 40,
+ }) });
+
+ const warning = document.getElementById('cost-pricing-warning');
+ expect(warning.hidden).toBe(false);
+ expect(warning.textContent).toContain('Partial estimate.');
+ expect(warning.textContent).toContain('Showing 1,000 of 1,500 calls.');
+ if (unpriced) expect(warning.textContent).toContain('Prices unavailable for 2 calls');
+ else expect(warning.textContent).not.toContain('Prices unavailable');
+});
+
+it('clears partial cost warnings when the selected period has no research', () => {
+ const runtime = costRenderer();
+ for (const id of [
+ 'loading', 'metrics-content', 'total-tokens', 'total-researches',
+ 'avg-response-time', 'success-rate', 'avg-input-tokens', 'avg-output-tokens',
+ 'avg-total-tokens', 'total-input-tokens', 'total-output-tokens', 'total-all-tokens',
+ 'rate-limit-success-rate', 'avg-wait-time', 'engines-tracked',
+ ]) {
+ const node = document.createElement('div');
+ node.id = id;
+ document.body.appendChild(node);
+ }
+ runtime.displayCostData({ overview: costOverview({
+ pricing_complete: false, unpriced_calls: 1, unpriced_tokens: 50,
+ }) });
+
+ runtime.showEmptyState();
+
+ expect(document.getElementById('total-cost').textContent).toBe('-');
+ expect(document.getElementById('cost-pricing-warning').hidden).toBe(true);
+ expect(document.getElementById('cost-pricing-warning').textContent).toBe('');
+});
diff --git a/tests/metrics/test_cost_summary_attribution.py b/tests/metrics/test_cost_summary_attribution.py
new file mode 100644
index 0000000000..ce4f8a34d3
--- /dev/null
+++ b/tests/metrics/test_cost_summary_attribution.py
@@ -0,0 +1,266 @@
+"""Cost summaries preserve provider attribution and missing-pricing signals."""
+
+import copy
+import json
+from unittest.mock import AsyncMock
+
+import pytest
+
+from local_deep_research.metrics.pricing.cost_calculator import CostCalculator
+from local_deep_research.metrics.pricing.pricing_fetcher import PricingFetcher
+
+
+def calculator():
+ calculator = CostCalculator()
+ # Static prices only: no HTTP session is created.
+ calculator.pricing_fetcher = PricingFetcher()
+ return calculator
+
+
+def usage(model, provider, prompt=1_000, completion=500):
+ return {
+ "model_name": model,
+ "provider": provider,
+ "prompt_tokens": prompt,
+ "completion_tokens": completion,
+ }
+
+
[email protected]("reverse", [False, True])
+async def test_mixed_usage_keeps_model_totals_and_provider_spend(
+ calculator, reverse
+):
+ records = [
+ usage("gpt-4", "openai"),
+ usage("gpt-4", "openai", 200, 100),
+ usage("gpt-4", "ollama"),
+ usage("unknown-model", "openai", 700, 300),
+ ]
+ if reverse:
+ records.reverse()
+ before = copy.deepcopy(records)
+
+ summary = await calculator.get_research_cost_summary(records)
+
+ assert records == before
+ assert summary["total_cost"] == 0.072
+ assert summary["total_calls"] == 4
+ assert summary["total_tokens"] == 4_300
+ assert summary["prompt_tokens"] == 2_900
+ assert summary["completion_tokens"] == 1_400
+ assert summary["avg_cost_per_call"] == 0.018
+ assert summary["cost_per_token"] == 0.00001674
+ assert summary["pricing_complete"] is False
+ assert summary["unpriced_calls"] == 1
+ assert summary["unpriced_tokens"] == 1_000
+ assert summary["model_breakdown"] == {
+ "gpt-4": {
+ "total_cost": pytest.approx(0.072),
+ "prompt_tokens": 2_200,
+ "completion_tokens": 1_100,
+ "calls": 3,
+ },
+ "unknown-model": {
+ "total_cost": 0.0,
+ "prompt_tokens": 700,
+ "completion_tokens": 300,
+ "calls": 1,
+ },
+ }
+ providers = {
+ (row["model_name"], row["provider"]): row
+ for row in summary["provider_breakdown"]
+ }
+ assert set(providers) == {
+ ("gpt-4", "openai"),
+ ("gpt-4", "ollama"),
+ ("unknown-model", "openai"),
+ }
+ assert providers[("gpt-4", "openai")] == {
+ "model_name": "gpt-4",
+ "provider": "openai",
+ "total_cost": 0.072,
+ "prompt_tokens": 1_200,
+ "completion_tokens": 600,
+ "calls": 2,
+ "unpriced_calls": 0,
+ "unpriced_tokens": 0,
+ }
+ assert providers[("gpt-4", "ollama")]["total_cost"] == 0.0
+ assert providers[("gpt-4", "ollama")]["unpriced_calls"] == 0
+ assert providers[("unknown-model", "openai")]["unpriced_calls"] == 1
+ assert providers[("unknown-model", "openai")]["unpriced_tokens"] == 1_000
+ assert json.loads(json.dumps(summary)) == summary
+
+
+ "records,complete,unpriced_calls,unpriced_tokens",
+ [
+ ([], True, 0, 0),
+ ([usage("gpt-4", "openai", 0, 0)], True, 0, 0),
+ ([usage("unknown-model", "ollama")], True, 0, 0),
+ ([usage("unknown-model", "openai", 0, 0)], False, 1, 0),
+ ([usage("unknown-model", "openai")], False, 1, 1_500),
+ ],
+ ids=["empty", "zero-tokens", "known-free", "unpriced-zero", "unpriced"],
+)
+async def test_zero_cost_distinguishes_known_free_from_unknown_pricing(
+ calculator, records, complete, unpriced_calls, unpriced_tokens
+):
+ summary = await calculator.get_research_cost_summary(records)
+
+ assert summary["total_cost"] == 0.0
+ assert summary["pricing_complete"] is complete
+ assert summary["unpriced_calls"] == unpriced_calls
+ assert summary["unpriced_tokens"] == unpriced_tokens
+ assert summary["total_calls"] == len(records)
+ if records:
+ (row,) = summary["provider_breakdown"]
+ assert row["calls"] == 1
+ assert row["unpriced_calls"] == unpriced_calls
+ assert row["unpriced_tokens"] == unpriced_tokens
+ else:
+ assert summary["model_breakdown"] == {}
+ assert summary["provider_breakdown"] == []
+
+
+async def test_provider_prices_stay_separate_when_both_are_paid(calculator):
+ calculator.cache.set_model_pricing(
+ "openai:shared-model", {"prompt": 0.01, "completion": 0.02}
+ )
+ calculator.cache.set_model_pricing(
+ "openrouter:shared-model", {"prompt": 0.03, "completion": 0.04}
+ )
+ records = [
+ usage("shared-model", "openai", 1_000, 1_000),
+ usage("shared-model", "openrouter", 1_000, 1_000),
+ usage("shared-model", "openai", 500, 500),
+ ]
+
+ summary = await calculator.get_research_cost_summary(records)
+
+ by_provider = {r["provider"]: r for r in summary["provider_breakdown"]}
+ assert set(by_provider) == {"openai", "openrouter"}
+ assert by_provider["openai"]["total_cost"] == 0.045
+ assert by_provider["openai"]["calls"] == 2
+ assert by_provider["openrouter"]["total_cost"] == 0.07
+ assert by_provider["openrouter"]["calls"] == 1
+ assert summary["total_cost"] == 0.115
+ assert summary["total_tokens"] == 5_000
+ assert summary["pricing_complete"] is True
+
+
+async def test_missing_provider_remains_separate_from_explicit_names(
+ calculator,
+):
+ records = [usage("gpt-4", p) for p in (None, None, "", "null")]
+ del records[0]["provider"]
+
+ summary = await calculator.get_research_cost_summary(records)
+
+ # JSON object keys would turn None into "null" and collide with a name.
+ rows = json.loads(json.dumps(summary))["provider_breakdown"]
+ assert len(rows) == 3
+ by_provider = {row["provider"]: row for row in rows}
+ assert set(by_provider) == {None, "", "null"}
+ assert by_provider[None]["calls"] == 2
+ assert by_provider[None]["total_cost"] == 0.12
+ assert by_provider[""]["calls"] == 1
+ assert by_provider["null"]["calls"] == 1
+ assert summary["pricing_complete"] is True
+
+
+async def test_provider_breakdown_does_not_concatenate_identity_fields(
+ calculator,
+):
+ pairs = [("b:c", "a"), ("c", "a:b"), ("c", None), ("c", "null")]
+ summary = await calculator.get_research_cost_summary(
+ [usage(model, provider) for model, provider in pairs]
+ )
+
+ rows = json.loads(json.dumps(summary))["provider_breakdown"]
+ assert len(rows) == 4
+ assert {(r["model_name"], r["provider"]) for r in rows} == set(pairs)
+ assert all(r["calls"] == 1 for r in rows)
+ assert summary["unpriced_calls"] == 4
+ assert summary["unpriced_tokens"] == 6_000
+
+
+async def test_multiple_models_at_one_provider_keep_distinct_rows(calculator):
+ summary = await calculator.get_research_cost_summary(
+ [usage("gpt-4", "openai"), usage("gpt-4o-mini", "openai")]
+ )
+
+ by_model = {r["model_name"]: r for r in summary["provider_breakdown"]}
+ assert set(by_model) == {"gpt-4", "gpt-4o-mini"}
+ assert by_model["gpt-4"]["total_cost"] == 0.06
+ assert by_model["gpt-4o-mini"]["total_cost"] == 0.00045
+ assert summary["total_cost"] == 0.06045
+
+
+async def test_calculation_failure_clears_stale_input_pricing(
+ calculator, monkeypatch
+):
+ monkeypatch.setattr(
+ calculator,
+ "get_model_pricing",
+ AsyncMock(side_effect=RuntimeError("pricing lookup failed")),
+ )
+ record = usage("gpt-4", "openai")
+ record["pricing_used"] = {"prompt": 9.0, "completion": 9.0}
+
+ (cost,) = await calculator.calculate_batch_costs([record])
+ summary = await calculator.get_research_cost_summary([record])
+
+ assert cost["error"] == "Cost calculation failed"
+ assert cost["pricing_used"] is None
+ assert summary["total_cost"] == 0.0
+ assert summary["pricing_complete"] is False
+ assert summary["unpriced_calls"] == 1
+ assert summary["unpriced_tokens"] == 1_500
+ assert summary["provider_breakdown"][0]["unpriced_calls"] == 1
+ assert record["pricing_used"] == {"prompt": 9.0, "completion": 9.0}
+
+
+async def test_partial_pricing_within_one_provider_bucket(
+ calculator, monkeypatch
+):
+ monkeypatch.setattr(
+ calculator,
+ "get_model_pricing",
+ AsyncMock(side_effect=[{"prompt": 0.03, "completion": 0.06}, None]),
+ )
+ summary = await calculator.get_research_cost_summary(
+ [usage("gpt-4", "openai"), usage("gpt-4", "openai", 100, 50)]
+ )
+
+ (row,) = summary["provider_breakdown"]
+ assert row["calls"] == 2
+ assert row["total_cost"] == 0.06
+ assert row["prompt_tokens"] == 1_100
+ assert row["completion_tokens"] == 550
+ assert row["unpriced_calls"] == summary["unpriced_calls"] == 1
+ assert row["unpriced_tokens"] == summary["unpriced_tokens"] == 150
+ assert summary["pricing_complete"] is False
+
+
+async def test_caller_error_metadata_does_not_hide_valid_pricing(calculator):
+ record = usage("gpt-4", "openai")
+ record["error"] = "an unrelated caller annotation"
+
+ summary = await calculator.get_research_cost_summary([record])
+
+ assert summary["total_cost"] == 0.06
+ assert summary["pricing_complete"] is True
+ assert summary["unpriced_calls"] == 0
+ assert summary["unpriced_tokens"] == 0
diff --git a/tests/metrics/test_provider_pricing_contracts.py b/tests/metrics/test_provider_pricing_contracts.py
new file mode 100644
index 0000000000..4e80c5e126
--- /dev/null
+++ b/tests/metrics/test_provider_pricing_contracts.py
@@ -0,0 +1,375 @@
+"""Provider-aware prices through both calculators and the HTTP cost routes."""
+
+from contextlib import contextmanager
+from unittest.mock import MagicMock
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from local_deep_research.database.models.metrics import TokenUsage
+from local_deep_research.metrics.pricing.cost_calculator import CostCalculator
+from local_deep_research.metrics.pricing.pricing_fetcher import PricingFetcher
+from local_deep_research.web.routers import metrics
+
+
[email protected]("provider", ["ollama", "lmstudio", "llamacpp"])
[email protected]("model", ["gpt-4", "unknown-local-model"])
+def test_local_provider_prices_are_free_even_for_a_paid_model_name(
+ provider, model
+):
+ result = CostCalculator().calculate_cost_sync(model, 1000, 1000, provider)
+
+ assert result["pricing_used"] == {"prompt": 0.0, "completion": 0.0}
+ assert result["total_cost"] == 0.0
+ assert "error" not in result
+
+
[email protected]("provider", [None, "openai", "ollama", "LM Studio"])
[email protected]("model", ["gpt-4", "openai/GPT-4", "unknown-model"])
+async def test_sync_and_async_use_the_same_static_fallback(provider, model):
+ calculator = CostCalculator()
+ calculator.pricing_fetcher = PricingFetcher()
+
+ asynchronous = await calculator.calculate_cost(model, 1000, 500, provider)
+ # Clear the cache so this exercises both fallback implementations.
+ calculator.cache.clear()
+ synchronous = calculator.calculate_cost_sync(model, 1000, 500, provider)
+
+ assert synchronous == asynchronous
+
+
+async def test_sync_reads_async_cached_prices_only_for_the_selected_provider():
+ calculator = CostCalculator()
+ calculator.pricing_fetcher = PricingFetcher()
+ calculator.pricing_fetcher.static_pricing["cache-only-model"] = {
+ "prompt": 0.01,
+ "completion": 0.02,
+ }
+ resolved = await calculator.calculate_cost(
+ "cache-only-model", 1000, 500, "openai"
+ )
+ calculator.pricing_fetcher = None
+
+ assert (
+ calculator.calculate_cost_sync("cache-only-model", 1000, 500, "openai")
+ == resolved
+ )
+ assert resolved["total_cost"] == 0.02
+ for other_provider in (None, "openrouter"):
+ result = calculator.calculate_cost_sync(
+ "cache-only-model", 1000, 500, other_provider
+ )
+ assert result["pricing_used"] is None
+ assert result["error"] == "No pricing data available for this model"
+
+
+def test_provider_cache_entries_do_not_override_each_other_or_legacy_prices():
+ calculator = CostCalculator()
+ calculator.cache.set_model_pricing(
+ "gpt-4", {"prompt": 0.5, "completion": 0.5}
+ )
+ calculator.cache.set_model_pricing(
+ "openai:gpt-4", {"prompt": 0.01, "completion": 0.02}
+ )
+ calculator.cache.set_model_pricing(
+ "openrouter:gpt-4", {"prompt": 0.03, "completion": 0.04}
+ )
+
+ for provider, expected in (
+ (None, 1.0),
+ ("openai", 0.03),
+ ("openrouter", 0.07),
+ ("ollama", 0.0),
+ ):
+ result = calculator.calculate_cost_sync("gpt-4", 1000, 1000, provider)
+ assert result["total_cost"] == expected
+
+
+def client():
+ app = FastAPI()
+ app.include_router(metrics.router)
+ app.dependency_overrides[metrics.require_auth] = lambda: "alice"
+ with TestClient(app) as test_client:
+ yield test_client
+
+
+ "provider,expected", [("openai", 0.09), ("ollama", 0.0), (None, 0.09)]
+)
+def test_http_calculation_honors_the_requested_provider(
+ client, provider, expected
+):
+ response = client.post(
+ "/metrics/api/cost-calculation",
+ json={
+ "model_name": "gpt-4",
+ "provider": provider,
+ "prompt_tokens": 1000,
+ "completion_tokens": 1000,
+ },
+ )
+
+ assert response.status_code == 200
+ result = response.json()
+ assert result["provider"] == provider
+ assert result["total_cost"] == expected
+ assert "error" not in result
+
+
[email protected]("provider", [123, True, [], {}])
+def test_http_calculation_rejects_non_string_providers(client, provider):
+ response = client.post(
+ "/metrics/api/cost-calculation",
+ json={"model_name": "gpt-4", "provider": provider},
+ )
+
+ assert response.status_code == 400
+ assert response.json() == {"error": "provider must be a string"}
+
+
+ "provider,expected", [("openai", 0.03), ("ollama", 0.0)]
+)
+def test_http_model_pricing_honors_the_requested_provider(
+ client, provider, expected
+):
+ response = client.get(
+ "/metrics/api/pricing/gpt-4", params={"provider": provider}
+ )
+
+ assert response.status_code == 200
+ assert response.json()["pricing"]["prompt"] == expected
+
+
+def saved_usage(monkeypatch):
+ records = [
+ TokenUsage(
+ research_id="research-paid",
+ model_name="gpt-4",
+ model_provider="openai",
+ prompt_tokens=1000,
+ completion_tokens=1000,
+ timestamp=1.0,
+ ),
+ TokenUsage(
+ research_id="research-local",
+ model_name="gpt-4",
+ model_provider="ollama",
+ prompt_tokens=1000,
+ completion_tokens=1000,
+ timestamp=1.0,
+ ),
+ ]
+ session = MagicMock()
+ query = session.query.return_value
+ query.filter.return_value = query
+ query.all.return_value = records
+ query.count.return_value = len(records)
+
+ @contextmanager
+ def open_session(username):
+ assert username == "alice"
+ yield session
+
+ monkeypatch.setattr(metrics, "get_user_db_session", open_session)
+ monkeypatch.setattr(metrics, "get_time_filter_condition", lambda *a: None)
+ return query, records
+
+
+def test_research_costs_read_the_saved_model_provider(client, saved_usage):
+ query, records = saved_usage
+ query.all.return_value = [records[1]]
+
+ response = client.get("/metrics/api/research-costs/research-local")
+
+ assert response.status_code == 200
+ result = response.json()
+ assert result["total_cost"] == 0.0
+ assert result["total_tokens"] == 2000
+ assert "message" not in result
+
+
+def test_cost_analytics_preserves_paid_and_local_provider_totals(
+ client, saved_usage
+):
+ response = client.get("/metrics/api/cost-analytics?period=all")
+
+ assert response.status_code == 200
+ result = response.json()
+ assert result["overview"]["total_cost"] == 0.09
+ assert result["top_expensive_research"] == [
+ {
+ "research_id": "research-paid",
+ "total_cost": 0.09,
+ "pricing_complete": True,
+ "unpriced_calls": 0,
+ "unpriced_tokens": 0,
+ },
+ {
+ "research_id": "research-local",
+ "total_cost": 0.0,
+ "pricing_complete": True,
+ "unpriced_calls": 0,
+ "unpriced_tokens": 0,
+ },
+ ]
+
+
+def test_research_costs_preserve_unknown_pricing(client, saved_usage):
+ _, records = saved_usage
+ records[1].model_name = "unknown-model"
+ records[1].model_provider = "openai"
+ records[1].research_id = records[0].research_id
+
+ response = client.get("/metrics/api/research-costs/research-paid")
+
+ assert response.status_code == 200
+ result = response.json()
+ assert result["total_cost"] == 0.09
+ assert result["prompt_cost"] == 0.03
+ assert result["completion_cost"] == 0.06
+ assert result["pricing_complete"] is False
+ assert result["unpriced_calls"] == 1
+ assert result["unpriced_tokens"] == 2000
+ assert len(result["provider_breakdown"]) == 2
+
+
+def test_cost_analytics_marks_each_research_price_independently(
+ client, saved_usage
+):
+ query, records = saved_usage
+ records.append(
+ TokenUsage(
+ research_id="research-paid",
+ model_name="unknown-model",
+ model_provider="openai",
+ prompt_tokens=1000,
+ completion_tokens=500,
+ timestamp=1.0,
+ )
+ )
+ query.count.return_value = len(records)
+
+ response = client.get("/metrics/api/cost-analytics?period=all")
+
+ assert response.status_code == 200
+ result = response.json()
+ assert result["overview"]["total_cost"] == 0.09
+ assert result["overview"]["pricing_complete"] is False
+ assert result["overview"]["unpriced_calls"] == 1
+ assert result["overview"]["unpriced_tokens"] == 1500
+ assert result["overview"]["total_tokens"] == 5500
+ assert result["overview"]["avg_cost_per_research"] == 0.045
+ assert result["overview"]["avg_cost_per_call"] == 0.03
+ assert result["overview"]["usage_truncated"] is False
+ assert result["overview"]["total_matching_calls"] == 3
+ assert result["top_expensive_research"] == [
+ {
+ "research_id": "research-paid",
+ "total_cost": 0.09,
+ "pricing_complete": False,
+ "unpriced_calls": 1,
+ "unpriced_tokens": 1500,
+ },
+ {
+ "research_id": "research-local",
+ "total_cost": 0.0,
+ "pricing_complete": True,
+ "unpriced_calls": 0,
+ "unpriced_tokens": 0,
+ },
+ ]
+
+
+def test_cost_analytics_averages_researches_without_repricing_calls(
+ client, saved_usage, monkeypatch
+):
+ query, records = saved_usage
+ records.append(
+ TokenUsage(
+ research_id="research-paid",
+ model_name="gpt-4",
+ model_provider="openai",
+ prompt_tokens=500,
+ completion_tokens=500,
+ timestamp=1.0,
+ )
+ )
+ query.count.return_value = len(records)
+ price = CostCalculator.calculate_cost_sync
+ priced_calls = []
+
+ def record_price(self, model, prompt, completion, provider=None):
+ priced_calls.append((model, prompt, completion, provider))
+ return price(self, model, prompt, completion, provider)
+
+ monkeypatch.setattr(CostCalculator, "calculate_cost_sync", record_price)
+
+ response = client.get("/metrics/api/cost-analytics?period=all")
+
+ assert response.status_code == 200
+ result = response.json()
+ assert len(priced_calls) == 3
+ assert result["research_count"] == 2
+ assert result["overview"]["total_cost"] == 0.135
+ assert result["overview"]["avg_cost_per_research"] == 0.0675
+ assert result["overview"]["avg_cost_per_call"] == 0.045
+ assert result["overview"]["prompt_cost"] == 0.045
+ assert result["overview"]["completion_cost"] == 0.09
+ assert result["overview"]["pricing_complete"] is True
+
+
[email protected]("analytics", [False, True])
+def test_empty_cost_results_keep_the_populated_summary_shape(
+ client, saved_usage, analytics
+):
+ query, _ = saved_usage
+ endpoint = (
+ "/metrics/api/cost-analytics?period=all"
+ if analytics
+ else "/metrics/api/research-costs/research-paid"
+ )
+ populated_response = client.get(endpoint)
+ assert populated_response.status_code == 200
+ populated = populated_response.json()
+ query.count.return_value = 0
+ query.all.return_value = []
+
+ empty_response = client.get(endpoint)
+
+ assert empty_response.status_code == 200
+ empty = empty_response.json()
+ if analytics:
+ empty, populated = empty["overview"], populated["overview"]
+ else:
+ assert empty.pop("message")
+ assert set(empty) == set(populated)
+ assert empty["total_cost"] == 0.0
+ assert empty["pricing_complete"] is True
+ assert empty["unpriced_calls"] == 0
+ assert empty["unpriced_tokens"] == 0
+ assert empty["provider_breakdown"] == []
+
+
+def test_cost_analytics_marks_the_existing_row_cap_as_partial(
+ client, saved_usage
+):
+ query, records = saved_usage
+ query.count.return_value = 1500
+ query.order_by.return_value.limit.return_value.all.return_value = records
+
+ response = client.get("/metrics/api/cost-analytics?period=all")
+
+ assert response.status_code == 200
+ overview = response.json()["overview"]
+ assert overview["total_cost"] == 0.09
+ assert overview["pricing_complete"] is True
+ assert overview["usage_truncated"] is True
+ assert overview["total_calls"] == 2
+ assert overview["total_matching_calls"] == 1500
+ query.order_by.return_value.limit.assert_called_once_with(1000)
diff --git a/tests/metrics/test_token_counting_attribution.py b/tests/metrics/test_token_counting_attribution.py
index 568e24ea6c..f0e9e0c02a 100644
--- a/tests/metrics/test_token_counting_attribution.py
+++ b/tests/metrics/test_token_counting_attribution.py
@@ -1251,17 +1251,6 @@ def test_pricing_falls_back_to_model_name_when_provider_has_no_entry():
assert result["total_cost"] == 0.09
- strict=True,
- reason=(
- "SYNC AND ASYNC COST PATHS DISAGREE. calculate_cost caches under "
- "'model:{provider}:{model}' (cost_calculator.py:37,50) while "
- "calculate_cost_sync reads PricingCache.get_model_pricing(model), "
- "i.e. 'model:{model}', and takes no provider argument at all. A "
- "model priced successfully by the async path a moment earlier comes "
- "back from the sync path as 'No pricing data available'."
- ),
-)
def test_sync_cost_path_sees_pricing_the_async_path_just_resolved():
calculator = offline_calculator()
@@ -1270,22 +1259,13 @@ def test_sync_cost_path_sees_pricing_the_async_path_just_resolved():
)
assert resolved["pricing_used"] == {"prompt": 0.0, "completion": 0.0}
- from_sync = calculator.calculate_cost_sync("llama3.3:70b", 1_000, 1_000)
+ from_sync = calculator.calculate_cost_sync(
+ "llama3.3:70b", 1_000, 1_000, provider="ollama"
+ )
assert from_sync["pricing_used"] == {"prompt": 0.0, "completion": 0.0}
assert "error" not in from_sync
- strict=True,
- reason=(
- "THE 'NO PRICING' SIGNAL IS DROPPED BY THE SUMMARY. "
- "calculate_batch_costs attaches an 'error' key to every record it "
- "could not price, but get_research_cost_summary only sums "
- "total_cost. A research session whose spend is partly unpriced is "
- "reported as a smaller-but-confident dollar figure with nothing to "
- "distinguish it from a fully-priced one."
- ),
-)
def test_cost_summary_preserves_the_unpriced_signal():
calculator = offline_calculator()
records = [
@@ -1309,21 +1289,11 @@ def test_cost_summary_preserves_the_unpriced_signal():
summary = asyncio.run(calculator.get_research_cost_summary(records))
assert summary["total_cost"] == 0.075 # only the priced record
- # ...but nothing in the summary says a million tokens went unpriced.
- assert any(
- key in summary for key in ("error", "errors", "unpriced_calls")
- ), f"summary has no unpriced-usage indicator: {sorted(summary)}"
+ assert summary["pricing_complete"] is False
+ assert summary["unpriced_calls"] == 1
+ assert summary["unpriced_tokens"] == 1_000_000
- strict=True,
- reason=(
- "COST SUMMARY COLLAPSES PROVIDERS. get_research_cost_summary keys "
- "model_breakdown by cost['model_name'] alone, so the same model name "
- "billed at two different provider rates merges into one bucket and "
- "per-provider spend cannot be recovered."
- ),
-)
def test_cost_summary_separates_the_same_model_across_providers():
calculator = offline_calculator()
records = [
@@ -1344,10 +1314,16 @@ def test_cost_summary_separates_the_same_model_across_providers():
summary = asyncio.run(calculator.get_research_cost_summary(records))
# The paid call alone: 1.5*0.03 + 0.5*0.06 = 0.075
assert summary["total_cost"] == 0.075
- assert len(summary["model_breakdown"]) == 2, (
- "paid and free calls for the same model name merged into one bucket: "
- f"{summary['model_breakdown']}"
- )
+ # Preserve existing model totals; provider attribution is additive.
+ assert summary["model_breakdown"]["gpt-4"]["calls"] == 2
+ by_provider = {
+ row["provider"]: row for row in summary["provider_breakdown"]
+ }
+ assert set(by_provider) == {"openai", "ollama"}
+ assert by_provider["openai"]["total_cost"] == 0.075
+ assert by_provider["ollama"]["total_cost"] == 0.0
+ assert all(row["calls"] == 1 for row in by_provider.values())
+ assert summary["pricing_complete"] is True
# ==========================================================================
diff --git a/tests/theme_tests/test_accent_ink_contrast.py b/tests/theme_tests/test_accent_ink_contrast.py
index e67f482478..bb6ff847f7 100644
--- a/tests/theme_tests/test_accent_ink_contrast.py
+++ b/tests/theme_tests/test_accent_ink_contrast.py
@@ -1025,8 +1025,8 @@ DYNAMIC_INLINE_STYLES = {
),
None,
),
- # metrics.html L974: an inline ternary of two literals.
- ("templates/pages/metrics.html", 974, "color"): (
+ # metrics.html L975: an inline ternary of two literals.
+ ("templates/pages/metrics.html", 975, "color"): (
"item.success_status === 'success' ? 'green' : 'red'",
("green", "red"),
None,
@@ -1281,7 +1281,7 @@ def test_inline_style_scan_finds_the_known_expressions():
("templates/pages/journal_quality.html", 831, "background"),
("static/js/components/context-overflow.js", 574, "background"),
("static/js/components/details.js", 716, "color"),
- ("templates/pages/metrics.html", 974, "color"),
+ ("templates/pages/metrics.html", 975, "color"),
} <= set(found), sorted(found)
expanded = {
_allow_key(name, selector)
diff --git a/tests/web/routers/test_metrics_endpoint_edge_branches.py b/tests/web/routers/test_metrics_endpoint_edge_branches.py
index d50dfd5b52..8ae9e3cf3f 100644
--- a/tests/web/routers/test_metrics_endpoint_edge_branches.py
+++ b/tests/web/routers/test_metrics_endpoint_edge_branches.py
@@ -292,7 +292,7 @@ def test_cost_analytics_aggregates_records_by_research(
records = [
SimpleNamespace(
model_name="model-a",
- provider="provider",
+ model_provider="provider",
prompt_tokens=100,
completion_tokens=25,
research_id="r1",
@@ -300,7 +300,7 @@ def test_cost_analytics_aggregates_records_by_research(
),
SimpleNamespace(
model_name="model-a",
- provider="provider",
+ model_provider="provider",
prompt_tokens=50,
completion_tokens=25,
research_id="r1",
@@ -319,9 +319,22 @@ def test_cost_analytics_aggregates_records_by_research(
calculator = MagicMock()
# Keyed by prompt_tokens so the fake is independent of how many times the
# endpoint recomputes each record.
- costs = {100: {"total_cost": 0.25}, 50: {"total_cost": 0.10}}
+ costs = {
+ 100: {
+ "total_cost": 0.25,
+ "prompt_cost": 0.20,
+ "completion_cost": 0.05,
+ "pricing_used": {"prompt": 2.0, "completion": 2.0},
+ },
+ 50: {
+ "total_cost": 0.10,
+ "prompt_cost": 0.08,
+ "completion_cost": 0.02,
+ "pricing_used": {"prompt": 1.6, "completion": 0.8},
+ },
+ }
calculator.calculate_cost_sync.side_effect = (
- lambda _model, prompt, _completion: costs[prompt]
+ lambda _model, prompt, _completion, *, provider: costs[prompt]
)
mocker.patch(
"local_deep_research.metrics.pricing.cost_calculator.CostCalculator",
@@ -330,7 +343,7 @@ def test_cost_analytics_aggregates_records_by_research(
result = metrics.api_cost_analytics(_request(), username="alice")
- assert result["overview"] == {
+ expected_totals = {
"total_cost": 0.35,
# Recomputed as prompt + completion rather than read from the stored
# TokenUsage.total_tokens column. This pins CURRENT behaviour, not
@@ -340,15 +353,23 @@ def test_cost_analytics_aggregates_records_by_research(
"prompt_tokens": 150,
"completion_tokens": 50,
}
+ assert {
+ key: result["overview"][key] for key in expected_totals
+ } == expected_totals
+ assert result["overview"]["pricing_complete"] is True
+ assert result["overview"]["unpriced_calls"] == 0
assert result["top_expensive_research"] == [
- {"research_id": "r1", "total_cost": 0.35}
+ {
+ "research_id": "r1",
+ "total_cost": 0.35,
+ "pricing_complete": True,
+ "unpriced_calls": 0,
+ "unpriced_tokens": 0,
+ }
]
assert result["research_count"] == 1
- # The overall pass and the per-research pass each price every record
- # (metrics.py:2109-2116 and :2142-2149). That duplication is an
- # implementation detail, so assert only the floor: collapsing the two
- # passes into one must not have to touch this test.
- assert calculator.calculate_cost_sync.call_count >= len(records)
+ # Reuse each calculated price for the overall and per-research totals.
+ assert calculator.calculate_cost_sync.call_count == len(records)
# record_count (2) stayed under the 1000-row cap at metrics.py:2076, so
# the endpoint took the unlimited ``query.all()`` branch.
query.limit.assert_not_called()
diff --git a/tests/web/routers/test_metrics_error_and_shape_recovery.py b/tests/web/routers/test_metrics_error_and_shape_recovery.py
index 3b5fe975c3..06e8936841 100644
--- a/tests/web/routers/test_metrics_error_and_shape_recovery.py
+++ b/tests/web/routers/test_metrics_error_and_shape_recovery.py
@@ -563,7 +563,9 @@ class TestPricing:
from local_deep_research.web.routers.metrics import api_model_pricing
calculator = MagicMock()
- calculator.cache.get_model_pricing.return_value = {"input": 0.03}
+ calculator.calculate_cost_sync.return_value = {
+ "pricing_used": {"input": 0.03}
+ }
with patch(COST_CALCULATOR, return_value=calculator):
result = api_model_pricing(
_request("provider=openai"), "gpt-4", username="alice"
@@ -607,7 +609,7 @@ class TestResearchCosts:
record = Mock()
record.model_name = "gpt-4"
- record.provider = "openai"
+ record.model_provider = "openai"
record.prompt_tokens = 100
record.completion_tokens = 50
record.timestamp = "2024-01-01T00:00:00"
@@ -617,7 +619,12 @@ class TestResearchCosts:
record,
]
calculator = MagicMock()
- calculator.calculate_cost_sync.return_value = {"total_cost": 0.005}
+ calculator.calculate_cost_sync.return_value = {
+ "total_cost": 0.005,
+ "prompt_cost": 0.003,
+ "completion_cost": 0.002,
+ "pricing_used": {"prompt": 0.03, "completion": 0.04},
+ }
with (
_db_patch(session),
diff --git a/tests/web/routers/test_metrics_rate_limit_and_cost_endpoints.py b/tests/web/routers/test_metrics_rate_limit_and_cost_endpoints.py
index 89ed41f019..881e116669 100644
--- a/tests/web/routers/test_metrics_rate_limit_and_cost_endpoints.py
+++ b/tests/web/routers/test_metrics_rate_limit_and_cost_endpoints.py
@@ -189,7 +189,7 @@ class TestCostCalculation:
# total_tokens is computed here, not by the calculator.
assert result["total_tokens"] == 300
calculator.calculate_cost_sync.assert_called_once_with(
- "gpt-4", 100, 200
+ "gpt-4", 100, 200, provider="openai"
)
def test_omitted_token_counts_default_to_zero_rather_than_none(self):