\pset pager off
\pset tuples_only on
\pset fieldsep '\t'
-- 最近 3 天该类流式终止错误按天
SELECT 'daily', (created_at AT TIME ZONE 'Asia/Shanghai')::date AS day, count(*)
FROM ops_error_logs
WHERE created_at >= TIMESTAMPTZ '2026-05-09 00:00:00+08' AND created_at < TIMESTAMPTZ '2026-05-12 12:00:00+08'
  AND error_message = 'Upstream stream ended without a terminal response event'
GROUP BY 2 ORDER BY 2;
-- 昨日按小时
SELECT 'hour', to_char(date_trunc('hour', created_at AT TIME ZONE 'Asia/Shanghai'), 'YYYY-MM-DD HH24:00') AS hour, count(*)
FROM ops_error_logs
WHERE created_at >= TIMESTAMPTZ '2026-05-11 00:00:00+08' AND created_at < TIMESTAMPTZ '2026-05-12 00:00:00+08'
  AND error_message = 'Upstream stream ended without a terminal response event'
GROUP BY 2 ORDER BY 2;
-- 昨日按账号/组/模型/路径
SELECT 'dim', count(*) AS n, coalesce(group_id,0), coalesce(account_id,0), coalesce(model,''), coalesce(request_path,''), coalesce(error_phase,''), coalesce(error_owner,''), coalesce(status_code,0), coalesce(upstream_status_code,0)
FROM ops_error_logs
WHERE created_at >= TIMESTAMPTZ '2026-05-11 00:00:00+08' AND created_at < TIMESTAMPTZ '2026-05-12 00:00:00+08'
  AND error_message = 'Upstream stream ended without a terminal response event'
GROUP BY 3,4,5,6,7,8,9,10 ORDER BY n DESC LIMIT 50;
-- 样本
SELECT 'sample', id, to_char(created_at AT TIME ZONE 'Asia/Shanghai','YYYY-MM-DD HH24:MI:SS'), request_id, user_id, api_key_id, group_id, account_id, model, request_path, stream, duration_ms, time_to_first_token_ms, upstream_latency_ms, left(coalesce(upstream_errors::text,''),300)
FROM ops_error_logs
WHERE created_at >= TIMESTAMPTZ '2026-05-11 00:00:00+08' AND created_at < TIMESTAMPTZ '2026-05-12 00:00:00+08'
  AND error_message = 'Upstream stream ended without a terminal response event'
ORDER BY created_at LIMIT 20;
