src/lib/routers/agent-log.ts getStats does db.select({ level, metadata }).from(agentLogs).where(eq(pipelineRunId, ...)) with no LIMIT, then loops over every row in JavaScript to count tool_calls, errors, and sum tokens. A busy 30-minute pipeline can produce 10,000+ log rows — all transferred and iterated in-process.
Category: database
File: src/lib/routers/agent-log.ts
Recommendation: Replace the JS aggregation loop with a single SQL query using COUNT(*) FILTER (WHERE level = 'tool_call') and COALESCE(SUM((metadata->>'totalInputTokens')::int), 0) aggregate FILTER clauses — the same pattern already used and proven in observabilityRouter.getSummary.
Estimated Improvement: Eliminates large payload transfer; aggregation done in Postgres in <5ms vs potentially seconds