Skip to content

Epic (1/2): Store AI Usage Metrics (Cost, Model, Turns) in Redis for Dashboard Aggregation #72

Closed

Description

@integry

This is Part 1 of the AI Stats Dashboard Epic.

Before we can display AI resource consumption statistics (cost, model usage, token/turn counts) on the dashboard, we must first persist this discrete data in Redis when a job completes.

Currently, detailed metrics like claudeCostUsd, claudeModel, and claudeNumTurns are calculated in src/worker.js and included in the final Pino log entry, but they are not passed back to the queue completion handler or stored in Redis for aggregation. The existing system:activity:log list only stores a generic completion message, not the quantitative metrics we need.

Goal

Modify the BullMQ worker event handlers in src/queue/taskQueue.js to extract detailed AI metrics from the job's return value (from processGitHubIssueJob) and store them in a new Redis Sorted Set for time-based querying.

Implementation Steps

  1. Analyze src/worker.js: Confirm that the processGitHubIssueJob function returns an object that includes the claudeResult (which contains claudeCostUsd, model, finalResult.num_turns, executionTime, etc.). The current implementation logs this, so the data is available within the worker process. Ensure this comprehensive result object is what the worker processor returns on success.

  2. Modify src/queue/taskQueue.js - worker.on('completed', ...) handler:

    • Inside this handler, access the result object returned by the job processor.
    • Extract the key AI metrics from result.claudeResult (e.g., cost, model, turns, execution time).
    • Define a new JSON object aiMetrics containing this data, plus timestamp, status (success), issue number, and repo name.
    • Create a new Redis key for this data: metrics:ai:log:v1.
    • Use await metricsRedis.zadd() to add the JSON.stringified aiMetrics object to this Sorted Set. Use the job's start timestamp (job.timestamp) as the score for the sorted set. This enables efficient time-range queries.
    • Also, ensure the repoFullName logic correctly handles the job data structure to populate active:repositories (this logic seems adjacent and must be preserved).
  3. Modify src/queue/taskQueue.js - worker.on('failed', ...) handler:

    • Inside this handler, create a similar aiMetrics object.
    • Set status: 'failed', cost: 0, and extract any available metadata (like modelName from job.data).
    • Add this failure record to the same sorted set (metrics:ai:log:v1) using its job.timestamp as the score. This ensures our stats (like success/failure rates) are accurate.

This issue only covers storing the data. A follow-up issue will cover the API endpoint and frontend panel creation.

Activity

  1. integry commented on Sep 16, 2025

    @integry
    OwnerAuthor

    Here is the suggested implementation diff for src/queue/taskQueue.js to capture the AI metrics in Redis:

    --- a/src/queue/taskQueue.js
    +++ b/src/queue/taskQueue.js
    @@ -80,10 +80,11 @@
             await metricsRedis.set('metrics:jobs:avgTime', newAvg.toFixed(2));
             
             // Track active repository
    -        if (job.data?.repository) {
    -            await metricsRedis.sadd('active:repositories', job.data.repository);
    +        const repoFullName = job.data?.repository || (job.data?.repoOwner && job.data?.repoName ? `${job.data.repoOwner}/${job.data.repoName}` : null);
    +        if (repoFullName) {
    +            await metricsRedis.sadd('active:repositories', repoFullName);
             }
             
             // Log activity
    @@ -91,12 +92,31 @@
                 id: `activity-${Date.now()}-${job.id}`,
                 type: job.name === 'processGitHubIssue' ? 'issue_processed' : 'pr_processed',
                 timestamp: new Date().toISOString(),
    -            repository: job.data?.repository,
    +            repository: repoFullName,
                 issueNumber: job.data?.issueNumber,
                 description: `Successfully processed ${job.name === 'processGitHubIssue' ? 'issue' : 'PR'} #${job.data?.issueNumber || 'unknown'}`,
                 status: 'success'
             };
    +
    +        // Store detailed AI metrics in a Sorted Set for time-based querying
    +        if (result?.claudeResult) {
    +            const cost = result.claudeResult.claudeCostUsd || result.claudeResult.costUsd || result.claudeResult.finalResult?.cost_usd || 0;
    +            const aiMetrics = {
    +                timestamp: job.timestamp, // Use job start time
    +                cost: typeof cost === 'string' ? parseFloat(cost) : cost,
    +                model: result.claudeResult.model || job.data?.modelName || 'unknown',
    +                turns: result.claudeResult.claudeNumTurns || result.claudeResult.finalResult?.num_turns || 0,
    +                executionTimeMs: result.claudeResult.executionTime || 0,
    +                issueNumber: job.data?.number,
    +                repo: repoFullName,
    +                status: 'success',
    +                correlationId: job.data?.correlationId || result.correlationId,
    +            };
    +            // Use timestamp as score for the sorted set
    +            await metricsRedis.zadd('metrics:ai:log:v1', job.timestamp, JSON.stringify(aiMetrics));
    +        }
    +
             await metricsRedis.lpush('system:activity:log', JSON.stringify(activity));
             await metricsRedis.ltrim('system:activity:log', 0, 999); // Keep last 1000 activities
             
    @@ -120,13 +140,32 @@
             await metricsRedis.incr('metrics:jobs:failed');
             await metricsRedis.incr(`metrics:daily:${dateKey}:failed`);
             
    +        // Log failed AI metrics to sorted set for complete statistics
    +        const repoFullName = job?.data?.repository || (job?.data?.repoOwner && job?.data?.repoName ? `${job.data.repoOwner}/${job.data.repoName}` : null);
    +        const aiMetrics = {
    +            timestamp: job.timestamp,
    +            cost: 0, // Failed jobs may still incur cost, but we log 0 for aggregation logic
    +            model: job.data?.modelName || 'unknown',
    +            turns: 0,
    +            executionTimeMs: (job.finishedOn ? job.finishedOn : Date.now()) - (job.timestamp || Date.now()),
    +            issueNumber: job.data?.number,
    +            repo: repoFullName,
    +            status: 'failed',
    +            correlationId: job.data?.correlationId,
    +            error: err.message.substring(0, 100), // Log snippet of error
    +        };
    +        // Use timestamp as score
    +        if (job.timestamp) { // Ensure timestamp exists
    +             await metricsRedis.zadd('metrics:ai:log:v1', job.timestamp, JSON.stringify(aiMetrics));
    +        }
    +
             // Log activity
             const activity = {
                 id: `activity-${Date.now()}-${job?.id || 'unknown'}`,
                 type: 'error',
                 timestamp: new Date().toISOString(),
    -            repository: job?.data?.repository,
    +            repository: repoFullName,
                 issueNumber: job?.data?.issueNumber,
                 description: `Failed to process ${job?.name === 'processGitHubIssue' ? 'issue' : 'PR'} #${job?.data?.issueNumber || 'unknown'}: ${err.message}`,
                 status: 'error'
  2. propr-dev commented on Sep 18, 2025

    @propr-dev
    Contributor

    🤖 AI processing has started for this issue using claude-opus-4-20250514 model.

    I'll analyze the problem and work on a solution. This may take a few minutes.

    Processing Details:

    • Model: claude-opus-4-20250514
    • Branch: ai-fix/72-epic-1-2-store-ai-usage-m-20250918-1511-claude-opus-4-20250514-8lx
    • Base Branch: main
    • Worktree: issue-72-20250918-1511-claude-opus-4-20250514-8lx
  3. added a commit that references this issue on Sep 18, 2025
  4. added a commit that references this issue on Sep 18, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions