P0 security: - PRV_Gateway_Client: remove response body from RuntimeException (HTTP status only) - PRV_Capture_Writer: allowlist-only write (prompt/response text, never headers/auth) - Mandatory capture order: can_afford → probe → persist_result → update_row_cost → write_meta → capture_io - capture_io last and wrapped in swallowing try/catch New tables (SCHEMA_VERSION 3): - prv_call_meta: cost/metadata per call, kept indefinitely - prv_call_io: rendered prompt + raw response, pruned on retention window (default 90d) New classes: - PRV_Call_Meta_Table, PRV_Call_Io_Table: table schema + dbDelta - PRV_Capture_Writer: metadata + I/O write; security allowlist enforced - PRV_Prune_Cron: daily prv_daily_prune cron deletes aged prv_call_io rows only - PRV_Cost_Rollup_Query: MTD summary, model breakdown, drill-down, projection - PRV_Call_Log_Query: paginated + filtered call-log query + per-call I/O fetch - PRV_Costs_Page + PRV_Costs_Renderer: Costs admin sub-page (cap progress, bento, model table, drill-down) - PRV_Call_Log_Page + PRV_Call_Log_Table_Renderer: Call Log admin sub-page (filter bar, paginated table, WCAG AA pagination) - PRV_Call_Drawer_Renderer: non-modal complementary drawer (5 states: Normal/Pruned/Legacy/Failed/Loading) - PRV_Call_Drawer_Script: inline JS for drawer (300-line split from renderer) - PRV_Call_Detail_Ajax: wp_ajax_prv_call_detail AJAX handler - PRV_Admin_Page_Css: CSS provider (300-line split from PRV_Admin_Page) - PRV_Probe_Run_Executor: inner probe loop (300-line split from PRV_Probe_Runner) Updated: - PRV_Probe_Result: tokens_in/tokens_out params + getters - Both providers: report tokens_in/tokens_out from usage.prompt_tokens/completion_tokens - PRV_Probe_Runner: slimmed to lock+UUID+delegation; injects PRV_Capture_Writer - PRV_Config: get_io_retention_days(); PRV_IO_RETENTION_DEFAULT_DAYS constant - PRV_Upgrader/Activator/Deactivator/Plugin: register new tables, cron, pages, AJAX - Settings: retention days field + save in controller - uninstall.php: DROP both new tables, clear prv_daily_prune cron - Subnav 4-tab strip (Dashboard | Costs | Call Log | Settings) on all pages - ARCHITECTURE.md, CHANGELOG.md, CONTEXT.md, CONVENTIONS.md updated Tests: - test-capture-writer.php: write_meta, write_io, P0 security (401 record has no key/Bearer/sk-or-) - test-cost-audit.php: MTD reconciliation, projection, prune, forced capture_io exception, table drops Agent-Session: peptiderepo-geomonitor-v0.3.0-cost-audit
206 lines
5.5 KiB
PHP
206 lines
5.5 KiB
PHP
<?php
|
|
/**
|
|
* Cost rollup queries for the Costs admin page (v0.3.0).
|
|
*
|
|
* @package PrVision
|
|
*/
|
|
|
|
declare(strict_types=1);
|
|
|
|
/**
|
|
* Executes cost rollup queries across run / peptide / intent / model / call.
|
|
*
|
|
* All queries are bounded (LIMIT/OFFSET) and parameterised via $wpdb->prepare.
|
|
* The MTD total from this class reconciles to PRV_Cost_Ledger::get_month_to_date_usd()
|
|
* because both sum cost_usd on prv_call_meta filtered by current calendar month.
|
|
*
|
|
* Who triggers: PRV_Costs_Page::render_page().
|
|
* Dependencies: $wpdb, PRV_Call_Meta_Table, PRV_Config.
|
|
*
|
|
* @see class-prv-call-meta-table.php — Source table.
|
|
* @see class-prv-cost-ledger.php — MTD total (reconciliation reference).
|
|
* @see class-prv-costs-page.php — Consumer of rollup data.
|
|
* @package PrVision
|
|
*/
|
|
class PRV_Cost_Rollup_Query {
|
|
|
|
/**
|
|
* Rows per page for the drill-down table.
|
|
*/
|
|
const PAGE_SIZE = 50;
|
|
|
|
/**
|
|
* Fetch MTD totals: total cost, total calls, avg cost/call for the month.
|
|
*
|
|
* Side effects: Database read.
|
|
*
|
|
* @return array{total_cost: float, total_calls: int, avg_cost: float}
|
|
*/
|
|
public function get_mtd_summary(): array {
|
|
global $wpdb;
|
|
|
|
$table = PRV_Call_Meta_Table::get_table_name();
|
|
$month = gmdate( 'Y-m' );
|
|
|
|
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
|
|
$row = $wpdb->get_row(
|
|
$wpdb->prepare(
|
|
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
|
"SELECT COALESCE(SUM(cost_usd),0) AS total_cost, COUNT(*) AS total_calls
|
|
FROM {$table}
|
|
WHERE DATE_FORMAT(captured_at, %s) = %s",
|
|
'%Y-%m',
|
|
$month
|
|
),
|
|
ARRAY_A
|
|
);
|
|
|
|
$total_cost = (float) ( $row['total_cost'] ?? 0.0 );
|
|
$total_calls = (int) ( $row['total_calls'] ?? 0 );
|
|
$avg_cost = $total_calls > 0 ? $total_cost / $total_calls : 0.0;
|
|
|
|
return array(
|
|
'total_cost' => $total_cost,
|
|
'total_calls' => $total_calls,
|
|
'avg_cost' => $avg_cost,
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Fetch per-model MTD cost breakdown, ordered by cost descending.
|
|
*
|
|
* Side effects: Database read.
|
|
*
|
|
* @return array<int, array{model: string, calls: int, mtd_cost: float, cost_per_call: float}>
|
|
*/
|
|
public function get_model_breakdown(): array {
|
|
global $wpdb;
|
|
|
|
$table = PRV_Call_Meta_Table::get_table_name();
|
|
$month = gmdate( 'Y-m' );
|
|
|
|
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
|
|
$rows = $wpdb->get_results(
|
|
$wpdb->prepare(
|
|
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
|
"SELECT model,
|
|
COUNT(*) AS calls,
|
|
COALESCE(SUM(cost_usd),0) AS mtd_cost
|
|
FROM {$table}
|
|
WHERE DATE_FORMAT(captured_at, %s) = %s
|
|
GROUP BY model
|
|
ORDER BY mtd_cost DESC
|
|
LIMIT 50",
|
|
'%Y-%m',
|
|
$month
|
|
),
|
|
ARRAY_A
|
|
);
|
|
|
|
$result = array();
|
|
foreach ( (array) $rows as $row ) {
|
|
$calls = (int) $row['calls'];
|
|
$mtd_cost = (float) $row['mtd_cost'];
|
|
$result[] = array(
|
|
'model' => (string) $row['model'],
|
|
'calls' => $calls,
|
|
'mtd_cost' => $mtd_cost,
|
|
'cost_per_call' => $calls > 0 ? $mtd_cost / $calls : 0.0,
|
|
);
|
|
}
|
|
return $result;
|
|
}
|
|
|
|
/**
|
|
* Fetch cost drill-down by aggregation level (run/peptide/intent/model).
|
|
*
|
|
* Side effects: Database read.
|
|
*
|
|
* @param string $level One of: run, peptide, intent, model.
|
|
* @param int $offset Pagination offset.
|
|
*
|
|
* @return array<int, array<string, mixed>> Rows appropriate for the level.
|
|
*/
|
|
public function get_drill_down( string $level, int $offset = 0 ): array {
|
|
global $wpdb;
|
|
|
|
$table = PRV_Call_Meta_Table::get_table_name();
|
|
$month = gmdate( 'Y-m' );
|
|
$page_size = self::PAGE_SIZE;
|
|
$offset = max( 0, $offset );
|
|
|
|
$allowed_levels = array( 'run', 'peptide', 'intent', 'model' );
|
|
if ( ! in_array( $level, $allowed_levels, true ) ) {
|
|
$level = 'run';
|
|
}
|
|
|
|
switch ( $level ) {
|
|
case 'peptide':
|
|
$group_col = 'peptide_slug';
|
|
break;
|
|
case 'intent':
|
|
$group_col = 'intent_label';
|
|
break;
|
|
case 'model':
|
|
$group_col = 'model';
|
|
break;
|
|
default:
|
|
$group_col = 'run_id';
|
|
}
|
|
|
|
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
|
|
$rows = $wpdb->get_results(
|
|
$wpdb->prepare(
|
|
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
|
"SELECT {$group_col} AS group_key,
|
|
COUNT(*) AS calls,
|
|
COALESCE(SUM(cost_usd),0) AS total_cost,
|
|
MIN(captured_at) AS first_at,
|
|
MAX(captured_at) AS last_at
|
|
FROM {$table}
|
|
WHERE DATE_FORMAT(captured_at, %s) = %s
|
|
GROUP BY {$group_col}
|
|
ORDER BY total_cost DESC
|
|
LIMIT %d OFFSET %d",
|
|
'%Y-%m',
|
|
$month,
|
|
$page_size,
|
|
$offset
|
|
),
|
|
ARRAY_A
|
|
);
|
|
|
|
$result = array();
|
|
foreach ( (array) $rows as $row ) {
|
|
$result[] = array(
|
|
'group_key' => (string) $row['group_key'],
|
|
'calls' => (int) $row['calls'],
|
|
'total_cost' => (float) $row['total_cost'],
|
|
'first_at' => (string) $row['first_at'],
|
|
'last_at' => (string) $row['last_at'],
|
|
);
|
|
}
|
|
return $result;
|
|
}
|
|
|
|
/**
|
|
* Compute the linear month-end projection from MTD spend and days elapsed.
|
|
*
|
|
* Side effects: None.
|
|
*
|
|
* @param float $mtd_cost MTD cost in USD.
|
|
*
|
|
* @return float Projected full-month cost.
|
|
*/
|
|
public function project_month_end( float $mtd_cost ): float {
|
|
$days_in_month = (int) gmdate( 't' );
|
|
$day_of_month = (int) gmdate( 'j' );
|
|
|
|
if ( $day_of_month < 1 ) {
|
|
return $mtd_cost;
|
|
}
|
|
|
|
return $mtd_cost * ( $days_in_month / $day_of_month );
|
|
}
|
|
}
|