Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 106 additions & 0 deletions apps/web/src/app/api/cron/leaderboard-usage-rollup/route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import { NextRequest } from 'next/server';

jest.mock('@kilocode/web-shared/lib/config.server', () => ({ CRON_SECRET: 'cron-secret' }));
jest.mock('@/lib/leaderboard-usage-rollup', () => ({
buildLeaderboardUsageDays: jest.fn(),
}));
const mockSentryLog = jest.fn();
jest.mock('@kilocode/web-shared/lib/utils.server', () => ({
sentryLogger: jest.fn(() => mockSentryLog),
logExceptInTest: jest.fn(),
warnExceptInTest: jest.fn(),
}));

import type { LeaderboardUsageBuildSummary } from '@/lib/leaderboard-usage-rollup';
import { buildLeaderboardUsageDays } from '@/lib/leaderboard-usage-rollup';
import { logExceptInTest, warnExceptInTest } from '@kilocode/web-shared/lib/utils.server';
import { GET, maxDuration } from './route';

const mockBuild = jest.mocked(buildLeaderboardUsageDays);

function request(secret: string): NextRequest {
return new NextRequest('http://localhost:3000/api/cron/leaderboard-usage-rollup', {
headers: { authorization: `Bearer ${secret}` },
});
}

function summary(overrides: Partial<LeaderboardUsageBuildSummary> = {}) {
return {
built: [
{ usageDate: '2026-11-09', rows: 42, durationMs: 9_000, slices: 96, slowestSliceMs: 300 },
],
remaining: [],
unsettled: [],
emptyDays: [],
stoppedBy: null,
yesterdayBuilt: true,
replicaLagMs: 120,
durationMs: 9_500,
...overrides,
} satisfies LeaderboardUsageBuildSummary;
}

function loggedLine(logger: jest.Mock): unknown {
const [line] = logger.mock.calls[0] as [string];
return JSON.parse(line);
}

describe('GET /api/cron/leaderboard-usage-rollup', () => {
beforeEach(() => {
jest.clearAllMocks();
jest.useRealTimers();
mockBuild.mockResolvedValue(summary());
});

test('rejects invalid cron authorization', async () => {
const response = await GET(request('wrong-secret'));

expect(response.status).toBe(401);
expect(mockBuild).not.toHaveBeenCalled();
});

test('builds within a deadline inside the function duration and logs the summary', async () => {
const before = Date.now();
const response = await GET(request('cron-secret'));

expect(response.status).toBe(200);
await expect(response.json()).resolves.toMatchObject({
success: true,
summary: { built: [{ usageDate: '2026-11-09', rows: 42 }], remaining: [] },
});
const [options] = mockBuild.mock.calls[0];
expect(options.deadline).toBeGreaterThan(before);
expect(options.deadline).toBeLessThan(before + maxDuration * 1000);
expect(loggedLine(jest.mocked(logExceptInTest))).toEqual({
type: 'leaderboard_usage_rollup',
...summary(),
yesterdayMissing: false,
});
expect(warnExceptInTest).not.toHaveBeenCalled();
expect(mockSentryLog).not.toHaveBeenCalled();
});

test('logs a warning when a built day was empty', async () => {
mockBuild.mockResolvedValue(summary({ emptyDays: ['2026-11-09'] }));

await GET(request('cron-secret'));

expect(loggedLine(jest.mocked(warnExceptInTest))).toMatchObject({
emptyDays: ['2026-11-09'],
});
expect(logExceptInTest).not.toHaveBeenCalled();
});

test.each([
{ now: '2026-11-10T02:20:00.000Z', warned: false },
{ now: '2026-11-10T03:20:00.000Z', warned: true },
])('warns when yesterday is still missing at 03:00 UTC ($now)', async ({ now, warned }) => {
jest.useFakeTimers({ now: new Date(now), doNotFake: ['nextTick', 'setImmediate'] });
mockBuild.mockResolvedValue(summary({ built: [], yesterdayBuilt: false }));

await GET(request('cron-secret'));

const logger = jest.mocked(warned ? warnExceptInTest : logExceptInTest);
expect(loggedLine(logger)).toMatchObject({ yesterdayMissing: warned });
});
});
63 changes: 63 additions & 0 deletions apps/web/src/app/api/cron/leaderboard-usage-rollup/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { NextResponse } from 'next/server';

import { db, readDb } from '@kilocode/web-shared/lib/drizzle';
import { CRON_SECRET } from '@kilocode/web-shared/lib/config.server';
import { isCronAuthorizationValid } from '@/lib/cron-auth';
import { buildLeaderboardUsageDays } from '@/lib/leaderboard-usage-rollup';
import {
logExceptInTest,
sentryLogger,
warnExceptInTest,
} from '@kilocode/web-shared/lib/utils.server';

if (!CRON_SECRET) {
throw new Error('CRON_SECRET is not configured in environment variables');
}

export const maxDuration = 800;

// Leaves room for the day in progress to finish inside `maxDuration`.
const BUILD_BUDGET_MS = 500_000;

// Yesterday settles at 01:00 UTC; still missing two hours later means runs are failing.
const YESTERDAY_MISSING_AFTER_UTC_HOUR = 3;

/**
* Hourly build of `leaderboard_usage_daily` for the public leaderboard routes.
* Each run fills the days in the leaderboard window that have no rollup yet, so
* a new day lands within an hour of UTC midnight and a failed run is retried by
* the next one.
*/
export async function GET(request: Request) {
const authHeader = request.headers.get('authorization');
if (!isCronAuthorizationValid(authHeader, CRON_SECRET)) {
sentryLogger(
'cron',
'warning'
)(
'SECURITY: Invalid leaderboard-usage-rollup CRON authorization attempt: ' +
(authHeader ? 'Invalid authorization header' : 'Missing authorization header')
);
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}

const now = new Date();
const summary = await buildLeaderboardUsageDays({
readDb,
db,
now,
deadline: Date.now() + BUILD_BUDGET_MS,
});

// Console only: these logs are for investigating, not alerting.
const yesterdayMissing =
!summary.yesterdayBuilt && now.getUTCHours() >= YESTERDAY_MISSING_AFTER_UTC_HOUR;
const log = summary.emptyDays.length > 0 || yesterdayMissing ? warnExceptInTest : logExceptInTest;
log(JSON.stringify({ type: 'leaderboard_usage_rollup', ...summary, yesterdayMissing }));

return NextResponse.json({
success: true,
summary,
timestamp: new Date().toISOString(),
});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
import { cleanupDbForTest } from '@kilocode/web-shared/lib/drizzle';
import { redisClient } from '@kilocode/web-shared/lib/redis';
import { resolveOpenRouterModelAlias } from '@kilocode/web-shared/lib/ai-gateway/providers/gateway-models-cache';
import { insertLeaderboardUsage, utcDaysAgo } from '@/tests/helpers/leaderboard-usage.helper';
import { GET } from './route';

jest.mock('@sentry/nextjs', () => ({ captureException: jest.fn() }));

jest.mock('@kilocode/web-shared/lib/redis', () => ({
redisClient: {
get: jest.fn(),
set: jest.fn(),
},
}));

// Without the in-process cache, every GET reads the rows the test inserted.
jest.mock('@kilocode/web-shared/lib/cached-fetch', () => ({
createCachedFetch:
<T>(fetcher: () => Promise<T>, _ttlMs: number, fallback: T) =>
async () => {
try {
return await fetcher();
} catch {
return fallback;
}
},
}));

jest.mock('@kilocode/web-shared/lib/ai-gateway/providers/gateway-models-cache', () => ({
resolveOpenRouterModelAlias: jest.fn(),
}));

describe('GET /api/public/leaderboard-model-provider-usage', () => {
beforeEach(async () => {
await cleanupDbForTest();
jest.mocked(redisClient.get).mockReset().mockResolvedValue(null);
jest.mocked(redisClient.set).mockReset().mockResolvedValue('OK');
jest
.mocked(resolveOpenRouterModelAlias)
.mockReset()
.mockImplementation(async model => model);
});

test('answers 502 while the rollup has no rows in the window', async () => {
await insertLeaderboardUsage([{ usage_date: utcDaysAgo(0) }]);

const response = await GET();

expect(response.status).toBe(502);
});

test('sums the window per model and inference provider before calculating ratios', async () => {
await insertLeaderboardUsage([
{
usage_date: utcDaysAgo(1),
requested_model: 'synthetic/alias-test-model',
inference_provider: 'Particle AI',
cost_microdollars: 6_000_000,
input_tokens: 4_000_000,
output_tokens: 2_000_000,
cache_hit_tokens: 1_000_000,
request_count: 30,
},
{
usage_date: utcDaysAgo(7),
requested_model: 'synthetic/alias-test-model',
inference_provider: 'particle',
cost_microdollars: 18_000_000,
input_tokens: 4_000_000,
output_tokens: 2_000_000,
cache_hit_tokens: 1_000_000,
request_count: 70,
},
{
usage_date: utcDaysAgo(8),
requested_model: 'synthetic/alias-test-model',
inference_provider: 'particle',
input_tokens: 100_000_000,
},
]);

const response = await GET();

expect(response.status).toBe(200);
expect(response.headers.get('Access-Control-Allow-Origin')).toBe('*');
expect(await response.json()).toEqual([
{
model: 'alias-test-model',
provider: 'Particle AI',
sumTokens: 12_000_000,
costPerRequest: 0.24,
costPerMillionTokens: 2,
cacheRatio: 0.25,
errorRate: 0,
percentageOfModel: 100,
},
]);
expect(redisClient.get).not.toHaveBeenCalled();
expect(redisClient.set).not.toHaveBeenCalled();
});

test('keeps Claude Platform on AWS separate from Amazon Bedrock for the same model', async () => {
await insertLeaderboardUsage([
{ requested_model: 'synthetic/model', inference_provider: 'claudeaws' },
{ requested_model: 'synthetic/model', inference_provider: 'bedrock' },
]);

const response = await GET();

expect(await response.json()).toEqual([
expect.objectContaining({
model: 'model',
provider: 'Amazon Bedrock',
sumTokens: 12_000_000,
percentageOfModel: 50,
}),
expect.objectContaining({
model: 'model',
provider: 'Claude Platform on AWS',
sumTokens: 12_000_000,
percentageOfModel: 50,
}),
]);
});

test('beautifies the Meituan inference provider', async () => {
await insertLeaderboardUsage([
{ requested_model: 'meituan/longcat-flash-chat', inference_provider: 'meituan' },
]);

const response = await GET();

expect(await response.json()).toEqual([
expect.objectContaining({ model: 'longcat-flash-chat', provider: 'Meituan LongCat' }),
]);
});

test('resolves latest aliases to their current gateway target', async () => {
jest
.mocked(resolveOpenRouterModelAlias)
.mockImplementation(async model =>
model === '~deepseek/deepseek-pro-latest' ? 'deepseek/deepseek-v4-pro-0813' : model
);
await insertLeaderboardUsage([
{
requested_model: '~deepseek/deepseek-pro-latest',
model: 'deepseek-v4-pro',
inference_provider: 'deepseek',
input_tokens: 5_000_000,
output_tokens: 1_000_000,
},
{
requested_model: 'deepseek/deepseek-v4-pro-0813',
inference_provider: 'deepseek',
input_tokens: 5_000_000,
output_tokens: 1_000_000,
},
]);

const response = await GET();

expect(await response.json()).toEqual([
expect.objectContaining({
model: 'deepseek-v4-pro-0813',
provider: 'DeepSeek',
sumTokens: 12_000_000,
}),
]);
});

test('excludes BYOK, private custom models, mercury-edit and rows without output', async () => {
await insertLeaderboardUsage([
{ requested_model: 'acme/kept' },
{ requested_model: 'acme/user-byok', is_user_byok: true },
{ provider: 'custom', requested_model: 'private/model' },
{ provider: 'custom', requested_model: 'reflection/beam-free' },
{ provider: 'custom', requested_model: null, model: 'reflection/beam-free' },
{ requested_model: 'inception/mercury-edit' },
{ requested_model: 'acme/no-output', output_tokens: 0 },
]);

const response = await GET();

expect(
((await response.json()) as { model: string }[]).map(usage => usage.model).sort()
).toEqual(['beam-free', 'kept']);
});
});
Loading
Loading