All files / src/apps/user/pages/evaluation Benchmark.tsx

98.55% Statements 68/69
86.95% Branches 80/92
100% Functions 31/31
100% Lines 59/59

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330                                                                                        11x   11x 45x 45x   22x         11x       7x 18x 12x 12x 7x         11x 28x 10x 17x 10x     11x 4x 5x 5x   11x 1x               11x 6x                 11x 7x             11x 3x           2x                   11x 14x           11x     9x 9x 9x 9x 9x   9x                                                                             3x                                                                                               11x 24x 24x 24x 24x     24x 4x   24x 24x 24x 24x   24x 12x 12x 9x   3x                                                   4x 4x 4x 4x                                                                                                          
/**
 * The platform benchmark (`GET /evaluations/benchmark`): CHAINR Bot and every
 * built-in model, scored by CHAIN-R on every gold dataset.
 *
 * The bot runs again when a deploy changes the pipeline it answers through,
 * at most once a month (on the release then live), and each model when a
 * dataset's cases or the judge change. It is the same for every user: a
 * baseline to put one's own agents beside (Evaluate), and the bot's record
 * month by month.
 *
 * Two views of one query: a gold dataset's page shows every target on that
 * dataset (`DatasetBenchmark`); CHAINR Bot's page shows the bot on every
 * dataset, with its place among the models and its trend, and its average and
 * risk across them all beside each maker's strongest model (`BotBenchmark`).
 */
 
import { Skeleton } from "@/components/detail";
import {
  BenchmarkDataset,
  BenchmarkResult,
  BenchmarkRow,
  BenchmarkTarget,
  PlatformBenchmark,
} from "@/objects/Evaluation";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { useQuery } from "@tanstack/react-query";
import { CheckCircle2, Gauge, XCircle } from "lucide-react";
import React from "react";
import { Link } from "react-router-dom";
import {
  EmptyBlock,
  ErrorNote,
  ScoreBadge,
  SectionCard,
  datasetHref,
  formatCost,
  formatScore,
  formatSpread,
  formatTimestamp,
} from "./components";
import { QualitySummary, botStanding, riskPoints, riskSentence } from "./RiskReturn";
import RiskReturnChart from "./RiskReturnChart";
 
export const BOT_KEY = "chainr-bot";
 
export const usePlatformBenchmark = (datasetId?: string) => {
  const { getApiHandler } = useApiHandler();
  return useQuery<PlatformBenchmark | null>({
    queryKey: [QUERY_KEYS.GET.PLATFORM_BENCHMARK, datasetId ?? "all"],
    queryFn: () => getApiHandler().evaluation_router.benchmark(datasetId),
  });
};
 
/** Where `targetKey` stands among the rows with a score: 1-based, or null. */
export const rankOf = (
  dataset: BenchmarkDataset,
  targetKey: string,
): { position: number; of: number } | null => {
  const scored = dataset.rows
    .filter((r) => typeof r.latest?.score === "number")
    .sort((a, b) => (b.latest?.score ?? 0) - (a.latest?.score ?? 0));
  const index = scored.findIndex((r) => r.target_key === targetKey);
  return index < 0 ? null : { position: index + 1, of: scored.length };
};
 
/** The model that graded the bot's newest results — one judge for the
 *  whole benchmark, so the first found speaks for it. */
export const benchmarkJudge = (datasets: BenchmarkDataset[]): string | null =>
  datasets
    .flatMap((d) => d.rows)
    .map((r) => r.latest?.judge)
    .find((j): j is string => typeof j === "string" && j.length > 0) ?? null;
 
/** The scores of a run history, oldest first, the unscored left out. */
export const scoreTrend = (history: BenchmarkResult[]): number[] =>
  history
    .map((h) => h.score)
    .filter((s): s is number => typeof s === "number");
 
const ordinal = (n: number) =>
  n % 10 === 1 && n % 100 !== 11
    ? `${n}st`
    : n % 10 === 2 && n % 100 !== 12
      ? `${n}nd`
      : n % 10 === 3 && n % 100 !== 13
        ? `${n}rd`
        : `${n}th`;
 
const Verdict: React.FC<{ result: BenchmarkResult | null }> = ({ result }) =>
  !result ? null : result.passed ? (
    <CheckCircle2
      className="size-4 text-green-600 dark:text-green-400"
      aria-label="Passes"
    />
  ) : (
    <XCircle className="size-4 text-red-500 dark:text-red-400" aria-label="Below pass mark" />
  );
 
const Status: React.FC<{ row: BenchmarkRow }> = ({ row }) =>
  row.status === "current" ? null : (
    <span className="text-[10px] px-1.5 py-0.5 rounded-full bg-gray-100 dark:bg-gray-800 text-gray-500 dark:text-gray-400">
      {row.status === "running" ? "Running" : "Not yet run"}
    </span>
  );
 
/** Small bars, oldest left: a trend without a chart library. */
export const TrendBars: React.FC<{ scores: number[] }> = ({ scores }) =>
  scores.length < 2 ? null : (
    <span
      className="inline-flex items-end gap-0.5 h-5"
      aria-label={`Trend: ${scores.map(formatScore).join(", ")}`}
    >
      {scores.slice(-12).map((score, i) => (
        <span
          key={i}
          className="w-1.5 rounded-sm bg-indigo-400 dark:bg-indigo-500"
          style={{ height: `${Math.max(10, Math.round(score * 100))}%` }}
        />
      ))}
    </span>
  );
 
/** Why there is nothing to show yet, depending on where this runs. */
export const notRunYet = (data: PlatformBenchmark | null | undefined) =>
  data?.enabled
    ? "No results yet — CHAIN-R runs the benchmark at most once a month, on the release then live."
    : "The platform benchmark runs on CHAIN-R's deployed environments, at most once a month.";
 
// ─── A gold dataset: every target ────────────────────────────────────────────
 
export const DatasetBenchmark: React.FC<{ datasetId: string }> = ({
  datasetId,
}) => {
  const query = usePlatformBenchmark(datasetId);
  const data: PlatformBenchmark | null | undefined = query.data;
  const dataset = data?.datasets.find((d) => d.dataset_id === datasetId);
  const rows = dataset?.rows ?? [];
  const anyResult = rows.some((r) => r.latest);
 
  return (
    <SectionCard
      icon={Gauge}
      title="Platform benchmark"
      subtitle={
        dataset
          ? `CHAINR Bot and each maker's strongest model, run by CHAIN-R · pass mark ${formatScore(dataset.pass_mark)}`
          : "CHAINR Bot and each maker's strongest model, run by CHAIN-R"
      }
    >
      {query.isLoading ? (
        <Skeleton className="h-16 w-full" />
      ) : query.isError ? (
        <ErrorNote message="Could not load the benchmark." />
      ) : !anyResult ? (
        <EmptyBlock icon={Gauge} message={notRunYet(data)} />
      ) : (
        <div className="overflow-x-auto">
          <table className="w-full text-xs">
            <thead>
              <tr className="text-left text-[10px] uppercase tracking-wide text-gray-400 dark:text-gray-500">
                <th className="py-1.5 pr-2 font-medium">Model or agent</th>
                <th className="py-1.5 pr-2 font-medium">Score</th>
                <th className="py-1.5 pr-2 font-medium" title="How far a typical answer lands from the score">
                  Spread
                </th>
                <th className="py-1.5 pr-2 font-medium" title="What one answer cost, grading left out">
                  Per answer
                </th>
                <th className="py-1.5 pr-2 font-medium">Passes</th>
                <th className="py-1.5 pr-2 font-medium">Pass rate</th>
                <th className="py-1.5 pr-2 font-medium" title="The whole run, grading included">
                  Run cost
                </th>
                <th className="py-1.5 pr-2 font-medium">Evaluated</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100 dark:divide-gray-700">
              {rows.map((row) => (
                <tr key={row.experiment_id}>
                  <td className="py-2 pr-2 min-w-[10rem]">
                    <span className="flex items-center gap-1.5">
                      <span
                        className={
                          row.target_key === BOT_KEY
                            ? "font-medium text-gray-900 dark:text-gray-100"
                            : "text-gray-800 dark:text-gray-200"
                        }
                      >
                        {row.name}
                      </span>
                      <Status row={row} />
                    </span>
                  </td>
                  <td className="py-2 pr-2">
                    <ScoreBadge value={row.latest?.score} />
                  </td>
                  <td className="py-2 pr-2 tabular-nums whitespace-nowrap text-gray-600 dark:text-gray-300">
                    {formatSpread(row.latest?.answer_sd) || "—"}
                  </td>
                  <td className="py-2 pr-2 tabular-nums whitespace-nowrap text-gray-600 dark:text-gray-300">
                    {formatCost(row.latest?.cost_per_answer_usd)}
                  </td>
                  <td className="py-2 pr-2">
                    <Verdict result={row.latest} />
                  </td>
                  <td className="py-2 pr-2 tabular-nums text-gray-600 dark:text-gray-300">
                    {row.latest ? formatScore(row.latest.pass_rate) : "—"}
                  </td>
                  <td className="py-2 pr-2 tabular-nums text-gray-600 dark:text-gray-300">
                    {row.latest ? formatCost(row.latest.cost_usd) : "—"}
                  </td>
                  <td className="py-2 pr-2 whitespace-nowrap text-gray-500 dark:text-gray-400">
                    {row.latest ? formatTimestamp(row.latest.evaluated_at) : "—"}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </SectionCard>
  );
};
 
// ─── CHAINR Bot: every dataset ───────────────────────────────────────────────
 
export const BotBenchmark: React.FC = () => {
  const query = usePlatformBenchmark();
  const data: PlatformBenchmark | null | undefined = query.data;
  const datasets = data?.datasets ?? [];
  const targets: BenchmarkTarget[] = data?.targets ?? [];
  // Every gold dataset the bot is benchmarked on, results or not, so the
  // ones still to run read as still to run — not as datasets it skipped.
  const withBot = datasets.filter((d) =>
    d.rows.some((r) => r.target_key === BOT_KEY),
  );
  const botTarget = targets.find((t) => t.target_key === BOT_KEY);
  const points = riskPoints(targets, BOT_KEY);
  const standing = botStanding(targets, BOT_KEY);
  const judge = benchmarkJudge(datasets);
 
  if (query.isLoading) return <Skeleton className="h-16 w-full" />;
  Iif (query.isError) return <ErrorNote message="Could not load the benchmark." />;
  if (!withBot.some((d) => d.rows.some((r) => r.target_key === BOT_KEY && r.latest)))
    return <EmptyBlock icon={Gauge} message={notRunYet(data)} />;
 
  return (
    <div className="space-y-4">
      {botTarget?.quality && (
        <div className="space-y-1">
          <div className="flex items-center gap-2 flex-wrap">
            <span className="text-xs font-medium text-gray-700 dark:text-gray-300">
              Across the gold datasets
            </span>
            <QualitySummary quality={botTarget.quality} />
          </div>
          <p className="text-xs text-gray-500 dark:text-gray-400">
            {riskSentence(botTarget.quality)}
          </p>
          {standing && (
            <p className="text-xs text-gray-500 dark:text-gray-400">{standing}</p>
          )}
          {judge && (
            <p className="text-xs text-gray-400 dark:text-gray-500">
              Graded by <span className="font-mono">{judge}</span>
            </p>
          )}
        </div>
      )}
      {points.length >= 2 && <RiskReturnChart points={points} />}
      <ul className="divide-y divide-gray-100 dark:divide-gray-700">
      {withBot.map((dataset) => {
        const bot = dataset.rows.find((r) => r.target_key === BOT_KEY);
        const latest = bot?.latest ?? null;
        const rank = rankOf(dataset, BOT_KEY);
        return (
          <li
            key={dataset.dataset_id}
            className="flex flex-col sm:flex-row sm:items-center gap-2 py-2.5"
          >
            <div className="min-w-0 flex-1">
              <Link
                to={datasetHref(dataset.dataset_id)}
                className="text-sm font-medium text-gray-900 dark:text-gray-100 hover:underline"
              >
                {dataset.dataset_name}
              </Link>
              <div className="text-xs text-gray-500 dark:text-gray-400">
                pass mark {formatScore(dataset.pass_mark)}
                {rank && rank.of > 1
                  ? ` · ${ordinal(rank.position)} of ${rank.of} with each maker's strongest model`
                  : ""}
                {latest?.agent_version != null
                  ? ` · release v${latest.agent_version}`
                  : ""}
              </div>
            </div>
            <div className="flex items-center gap-3 shrink-0">
              {bot && !latest ? (
                <Status row={bot} />
              ) : (
                <>
                  {/* A run for this release replacing the result shown. */}
                  {bot && <Status row={bot} />}
                  <TrendBars scores={scoreTrend(dataset.bot_history)} />
                  <ScoreBadge value={latest?.score} />
                  <span className="text-xs tabular-nums text-gray-500 dark:text-gray-400">
                    {formatSpread(latest?.answer_sd)}
                  </span>
                  {latest?.cost_per_answer_usd != null && (
                    <span
                      className="text-xs tabular-nums text-gray-500 dark:text-gray-400"
                      title="What one answer cost, grading left out"
                    >
                      {formatCost(latest.cost_per_answer_usd)}/answer
                    </span>
                  )}
                  <Verdict result={latest} />
                </>
              )}
            </div>
          </li>
        );
      })}
      </ul>
    </div>
  );
};