Download src/app/api/analytics/__tests__/judge-dimensions.test.ts from NAP1320/RotNot: direct link, hf CLI and curl.
- Browser
- Download file 16.7 kB
-
https://huggingface.co/spaces/NAP1320/RotNot/resolve/main/src/app/api/analytics/__tests__/judge-dimensions.test.ts
- Command line
-
hf download hf://spaces/NAP1320/RotNot/src/app/api/analytics/__tests__/judge-dimensions.test.ts
-
curl -L -o judge-dimensions.test.ts https://huggingface.co/spaces/NAP1320/RotNot/resolve/main/src/app/api/analytics/__tests__/judge-dimensions.test.ts
16.7 kB
| /** | |
| * Tests for GET /api/analytics/judge-dimensions | |
| * | |
| * Covers: | |
| * API key guard | |
| * - returns 503 when LANGSMITH_API_KEY is not set | |
| * - does NOT call langsmithClient when key is missing | |
| * Response shape | |
| * - returns 200 with { dimensions, alerts } keys | |
| * - dimensions contains an entry for every DIMENSION_ID | |
| * - each dimension entry has { avg, trend } fields | |
| * - alerts is an array | |
| * Score aggregation β avg calculation | |
| * - avg is 0 when no feedback in the current period | |
| * - avg is computed correctly over multiple scores | |
| * - avg is rounded to 2 decimal places | |
| * - denormalises: feedback scores (0-1) are multiplied by 10 | |
| * - ignores feedback keys that are not in DIMENSION_IDS | |
| * - ignores feedback entries with non-numeric score | |
| * Trend calculation | |
| * - trend is 0 when there is no prior period data | |
| * - trend is positive when current avg > prior avg | |
| * - trend is negative when current avg < prior avg | |
| * - trend is 0 when prior and current are identical | |
| * - trend is rounded to 2 decimal places | |
| * Alerts | |
| * - no alert when drop is exactly -10% (boundary β not > 10%) | |
| * - alert fires when drop is > 10% | |
| * - alert message contains the dimension id | |
| * - alert message contains the percentage drop | |
| * - no alert when prior avg is 0 (no prior data) | |
| * - multiple dimensions can fire alerts in the same response | |
| * Error handling | |
| * - returns 500 if langsmithClient.listRuns throws | |
| */ | |
| import { describe, it, expect, vi, beforeEach } from "vitest"; | |
| import { NextRequest } from "next/server"; | |
| import { DIMENSION_IDS } from "@/lib/debate/judge"; | |
| // --------------------------------------------------------------------------- | |
| // Helpers | |
| // --------------------------------------------------------------------------- | |
| type FeedbackEntry = { key: string; score: number | null | undefined }; | |
| type RunEntry = { id: string }; | |
| /** | |
| * Build a mock async generator from an array. | |
| */ | |
| async function* makeAsyncGen<T>(items: T[]): AsyncGenerator<T> { | |
| for (const item of items) { | |
| yield item; | |
| } | |
| } | |
| // --------------------------------------------------------------------------- | |
| // Mocks | |
| // --------------------------------------------------------------------------- | |
| // listRuns and listFeedback are configured per-test via these maps | |
| let mockRunsByPeriod: RunEntry[][] = [[], []]; // [currentPeriod, priorPeriod] | |
| let mockFeedbackByRunId: Map<string, FeedbackEntry[]> = new Map(); | |
| // Track call order so we can distinguish current vs prior period calls | |
| let listRunsCallIndex = 0; | |
| const mockListRuns = vi.fn(); | |
| const mockListFeedback = vi.fn(); | |
| vi.mock("@/lib/langsmith", () => ({ | |
| langsmithClient: { | |
| listRuns: (...args: unknown[]) => mockListRuns(...args), | |
| listFeedback: (...args: unknown[]) => mockListFeedback(...args), | |
| }, | |
| })); | |
| beforeEach(() => { | |
| vi.resetModules(); | |
| mockListRuns.mockClear(); | |
| mockListFeedback.mockClear(); | |
| mockRunsByPeriod = [[], []]; | |
| mockFeedbackByRunId = new Map(); | |
| listRunsCallIndex = 0; | |
| // Default: return the correct period's runs in call order | |
| mockListRuns.mockImplementation(() => { | |
| const idx = listRunsCallIndex++; | |
| const runs = mockRunsByPeriod[idx] ?? []; | |
| return makeAsyncGen(runs); | |
| }); | |
| // Default: return any registered feedback for the given runId | |
| mockListFeedback.mockImplementation( | |
| ({ runIds }: { runIds: string[] }) => { | |
| const feedbacks = mockFeedbackByRunId.get(runIds[0]) ?? []; | |
| return makeAsyncGen(feedbacks); | |
| }, | |
| ); | |
| }); | |
| // --------------------------------------------------------------------------- | |
| // Import the handler after mocks are set up | |
| // --------------------------------------------------------------------------- | |
| async function callGET(env: Record<string, string | undefined> = {}) { | |
| // Dynamically import to pick up the latest mock state | |
| const { GET } = await import("../judge-dimensions/route"); | |
| const req = new NextRequest("http://localhost/api/analytics/judge-dimensions"); | |
| const saved: Record<string, string | undefined> = {}; | |
| for (const [k, v] of Object.entries(env)) { | |
| saved[k] = process.env[k]; | |
| if (v === undefined) { | |
| delete process.env[k]; | |
| } else { | |
| process.env[k] = v; | |
| } | |
| } | |
| try { | |
| const res = await GET(req); | |
| return res; | |
| } finally { | |
| for (const [k, v] of Object.entries(saved)) { | |
| if (v === undefined) { | |
| delete process.env[k]; | |
| } else { | |
| process.env[k] = v; | |
| } | |
| } | |
| } | |
| } | |
| // --------------------------------------------------------------------------- | |
| // API key guard | |
| // --------------------------------------------------------------------------- | |
| describe("API key guard", () => { | |
| it("returns 503 when LANGSMITH_API_KEY is not set", async () => { | |
| const res = await callGET({ LANGSMITH_API_KEY: undefined }); | |
| expect(res.status).toBe(503); | |
| }); | |
| it("returns error body when key is missing", async () => { | |
| const res = await callGET({ LANGSMITH_API_KEY: undefined }); | |
| const body = await res.json(); | |
| expect(body).toHaveProperty("error"); | |
| }); | |
| it("does not call listRuns when LANGSMITH_API_KEY is missing", async () => { | |
| await callGET({ LANGSMITH_API_KEY: undefined }); | |
| expect(mockListRuns).not.toHaveBeenCalled(); | |
| }); | |
| }); | |
| // --------------------------------------------------------------------------- | |
| // Response shape | |
| // --------------------------------------------------------------------------- | |
| describe("Response shape", () => { | |
| it("returns 200 when key is present", async () => { | |
| const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); | |
| expect(res.status).toBe(200); | |
| }); | |
| it("response has dimensions and alerts keys", async () => { | |
| const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); | |
| const body = await res.json(); | |
| expect(body).toHaveProperty("dimensions"); | |
| expect(body).toHaveProperty("alerts"); | |
| }); | |
| it("dimensions contains an entry for every DIMENSION_ID", async () => { | |
| const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); | |
| const body = await res.json(); | |
| for (const dimId of DIMENSION_IDS) { | |
| expect(body.dimensions).toHaveProperty(dimId); | |
| } | |
| }); | |
| it("each dimension entry has avg and trend fields", async () => { | |
| const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); | |
| const body = await res.json(); | |
| for (const dimId of DIMENSION_IDS) { | |
| const entry = body.dimensions[dimId]; | |
| expect(entry).toHaveProperty("avg"); | |
| expect(entry).toHaveProperty("trend"); | |
| expect(typeof entry.avg).toBe("number"); | |
| expect(typeof entry.trend).toBe("number"); | |
| } | |
| }); | |
| it("alerts is an array", async () => { | |
| const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); | |
| const body = await res.json(); | |
| expect(Array.isArray(body.alerts)).toBe(true); | |
| }); | |
| }); | |
| // --------------------------------------------------------------------------- | |
| // Score aggregation | |
| // --------------------------------------------------------------------------- | |
| describe("Score aggregation", () => { | |
| it("avg is 0 when there are no runs in the current period", async () => { | |
| // no runs in either period β defaults to empty arrays | |
| const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); | |
| const body = await res.json(); | |
| for (const dimId of DIMENSION_IDS) { | |
| expect(body.dimensions[dimId].avg).toBe(0); | |
| } | |
| }); | |
| it("computes avg correctly over multiple scores (denormalised 0-10)", async () => { | |
| const dimId = DIMENSION_IDS[0]; // "flaw-detection" | |
| mockRunsByPeriod = [ | |
| [{ id: "run-1" }, { id: "run-2" }], | |
| [], | |
| ]; | |
| // run-1: score 0.7 (β 7 after Γ10), run-2: score 0.9 (β 9 after Γ10) | |
| mockFeedbackByRunId.set("run-1", [{ key: dimId, score: 0.7 }]); | |
| mockFeedbackByRunId.set("run-2", [{ key: dimId, score: 0.9 }]); | |
| const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); | |
| const body = await res.json(); | |
| // avg = (7 + 9) / 2 = 8.0 | |
| expect(body.dimensions[dimId].avg).toBe(8.0); | |
| }); | |
| it("rounds avg to 2 decimal places", async () => { | |
| const dimId = DIMENSION_IDS[0]; | |
| // Three scores: 0.1 β 1, 0.2 β 2, 0.3 β 3: avg = 6/3 = 2.0 β rounded fine | |
| // Use values that would produce a repeating decimal: 1/3 β 0.333... | |
| // 0.1 β 1, 0.2 β 2, 0.4 β 4: avg = 7/3 β 2.333... β rounds to 2.33 | |
| mockRunsByPeriod = [[{ id: "r1" }, { id: "r2" }, { id: "r3" }], []]; | |
| mockFeedbackByRunId.set("r1", [{ key: dimId, score: 0.1 }]); | |
| mockFeedbackByRunId.set("r2", [{ key: dimId, score: 0.2 }]); | |
| mockFeedbackByRunId.set("r3", [{ key: dimId, score: 0.4 }]); | |
| const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); | |
| const body = await res.json(); | |
| // avg = (1 + 2 + 4) / 3 = 7/3 β 2.333... β 2.33 | |
| expect(body.dimensions[dimId].avg).toBe(2.33); | |
| }); | |
| it("ignores feedback keys that are not in DIMENSION_IDS", async () => { | |
| const dimId = DIMENSION_IDS[0]; | |
| mockRunsByPeriod = [[{ id: "run-x" }], []]; | |
| mockFeedbackByRunId.set("run-x", [ | |
| { key: "unknown-dimension", score: 0.9 }, | |
| { key: dimId, score: 0.5 }, | |
| ]); | |
| const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); | |
| const body = await res.json(); | |
| // Only the valid dimension score (0.5 β 5) should be counted | |
| expect(body.dimensions[dimId].avg).toBe(5.0); | |
| // The unknown key should not appear in the response | |
| expect(body.dimensions).not.toHaveProperty("unknown-dimension"); | |
| }); | |
| it("ignores feedback entries with null or undefined score", async () => { | |
| const dimId = DIMENSION_IDS[0]; | |
| mockRunsByPeriod = [[{ id: "run-null" }], []]; | |
| mockFeedbackByRunId.set("run-null", [ | |
| { key: dimId, score: null }, | |
| { key: dimId, score: undefined }, | |
| ] as FeedbackEntry[]); | |
| const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); | |
| const body = await res.json(); | |
| // All null/undefined scores ignored β avg stays 0 | |
| expect(body.dimensions[dimId].avg).toBe(0); | |
| }); | |
| }); | |
| // --------------------------------------------------------------------------- | |
| // Trend calculation | |
| // --------------------------------------------------------------------------- | |
| describe("Trend calculation", () => { | |
| it("trend is 0 when there is no prior period data", async () => { | |
| const dimId = DIMENSION_IDS[0]; | |
| mockRunsByPeriod = [[{ id: "run-cur" }], []]; // prior period empty | |
| mockFeedbackByRunId.set("run-cur", [{ key: dimId, score: 0.8 }]); | |
| const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); | |
| const body = await res.json(); | |
| expect(body.dimensions[dimId].trend).toBe(0); | |
| }); | |
| it("trend is positive when current avg is higher than prior", async () => { | |
| const dimId = DIMENSION_IDS[0]; | |
| mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]]; | |
| // current: 0.8 β 8, prior: 0.4 β 4 => trend = (8-4)/4 * 100 = 100% | |
| mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.8 }]); | |
| mockFeedbackByRunId.set("pri", [{ key: dimId, score: 0.4 }]); | |
| const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); | |
| const body = await res.json(); | |
| expect(body.dimensions[dimId].trend).toBeGreaterThan(0); | |
| expect(body.dimensions[dimId].trend).toBeCloseTo(100, 0); | |
| }); | |
| it("trend is negative when current avg is lower than prior", async () => { | |
| const dimId = DIMENSION_IDS[0]; | |
| mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]]; | |
| // current: 0.4 β 4, prior: 0.8 β 8 => trend = (4-8)/8 * 100 = -50% | |
| mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.4 }]); | |
| mockFeedbackByRunId.set("pri", [{ key: dimId, score: 0.8 }]); | |
| const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); | |
| const body = await res.json(); | |
| expect(body.dimensions[dimId].trend).toBeLessThan(0); | |
| expect(body.dimensions[dimId].trend).toBeCloseTo(-50, 0); | |
| }); | |
| it("trend is 0 when prior and current averages are equal", async () => { | |
| const dimId = DIMENSION_IDS[0]; | |
| mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]]; | |
| mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.7 }]); | |
| mockFeedbackByRunId.set("pri", [{ key: dimId, score: 0.7 }]); | |
| const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); | |
| const body = await res.json(); | |
| expect(body.dimensions[dimId].trend).toBe(0); | |
| }); | |
| it("trend is rounded to 2 decimal places", async () => { | |
| const dimId = DIMENSION_IDS[0]; | |
| // current: 0.7 β 7, prior: 0.6 β 6 => trend = (7-6)/6 * 100 β 16.666...% β 16.67 | |
| mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]]; | |
| mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.7 }]); | |
| mockFeedbackByRunId.set("pri", [{ key: dimId, score: 0.6 }]); | |
| const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); | |
| const body = await res.json(); | |
| expect(body.dimensions[dimId].trend).toBe(16.67); | |
| }); | |
| }); | |
| // --------------------------------------------------------------------------- | |
| // Alerts | |
| // --------------------------------------------------------------------------- | |
| describe("Alerts", () => { | |
| it("no alert when current period has no data (prior avg = 0)", async () => { | |
| const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); | |
| const body = await res.json(); | |
| expect(body.alerts).toHaveLength(0); | |
| }); | |
| it("no alert when drop is exactly -10% (boundary β strictly > 10% required)", async () => { | |
| const dimId = DIMENSION_IDS[0]; | |
| // prior avg = 10, current avg = 9 β drop = exactly 10% β NO alert | |
| mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]]; | |
| mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.9 }]); | |
| mockFeedbackByRunId.set("pri", [{ key: dimId, score: 1.0 }]); | |
| const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); | |
| const body = await res.json(); | |
| expect(body.alerts).toHaveLength(0); | |
| }); | |
| it("fires alert when drop is greater than 10%", async () => { | |
| const dimId = DIMENSION_IDS[0]; | |
| // prior avg = 10, current avg = 8 β drop = 20% β alert | |
| mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]]; | |
| mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.8 }]); | |
| mockFeedbackByRunId.set("pri", [{ key: dimId, score: 1.0 }]); | |
| const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); | |
| const body = await res.json(); | |
| expect(body.alerts.length).toBeGreaterThanOrEqual(1); | |
| }); | |
| it("alert message contains the dimension id", async () => { | |
| const dimId = DIMENSION_IDS[0]; // "flaw-detection" | |
| mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]]; | |
| mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.8 }]); | |
| mockFeedbackByRunId.set("pri", [{ key: dimId, score: 1.0 }]); | |
| const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); | |
| const body = await res.json(); | |
| expect(body.alerts.some((a: string) => a.includes(dimId))).toBe(true); | |
| }); | |
| it("alert message contains the percentage drop magnitude", async () => { | |
| const dimId = DIMENSION_IDS[0]; | |
| // prior = 10, current = 8 β 20% drop | |
| mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]]; | |
| mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.8 }]); | |
| mockFeedbackByRunId.set("pri", [{ key: dimId, score: 1.0 }]); | |
| const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); | |
| const body = await res.json(); | |
| const alert: string = body.alerts.find((a: string) => a.includes(dimId)); | |
| expect(alert).toContain("20.0%"); | |
| }); | |
| it("multiple dimensions can fire alerts in the same response", async () => { | |
| // Both dim 0 and dim 1 drop >10% | |
| const dim0 = DIMENSION_IDS[0]; | |
| const dim1 = DIMENSION_IDS[1]; | |
| mockRunsByPeriod = [[{ id: "cur0" }, { id: "cur1" }], [{ id: "pri0" }, { id: "pri1" }]]; | |
| // Use separate call tracking via IDs | |
| mockFeedbackByRunId.set("cur0", [{ key: dim0, score: 0.7 }]); | |
| mockFeedbackByRunId.set("cur1", [{ key: dim1, score: 0.6 }]); | |
| mockFeedbackByRunId.set("pri0", [{ key: dim0, score: 1.0 }]); | |
| mockFeedbackByRunId.set("pri1", [{ key: dim1, score: 1.0 }]); | |
| const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); | |
| const body = await res.json(); | |
| expect(body.alerts.length).toBeGreaterThanOrEqual(2); | |
| }); | |
| }); | |
| // --------------------------------------------------------------------------- | |
| // Error handling | |
| // --------------------------------------------------------------------------- | |
| describe("Error handling", () => { | |
| it("returns 500 if listRuns throws", async () => { | |
| mockListRuns.mockImplementationOnce(() => { | |
| throw new Error("LangSmith API error"); | |
| }); | |
| const res = await callGET({ LANGSMITH_API_KEY: "test-key" }); | |
| expect(res.status).toBe(500); | |
| }); | |
| }); | |