Measuring Cost per Accepted Answer: A Node.js Benchmark for StepFun Step 5's 53% Claim

Measuring Cost per Accepted Answer: A Node.js Benchmark for StepFun Step 5's 53% Claim

pr0h0••27 min read•ai
AI Usage (85%)
On this page

The Claim to Test: Fewer Output Tokens Are Not Necessarily Cheaper Accepted Answers

Measuring cost per accepted answer is the difference between a token-efficiency headline and a routing decision. This article shows how to build a Node.js benchmark for StepFun Step 5's reported 53% output-token reduction: matched prompts, explicit acceptance checks, retry accounting, and a ledger that reports CPAA, acceptance rate, and time to accepted answer. Before writing any code, here's what I can verify: a Superpower Daily item dated 2026-12-03 says StepFun released Step 5 and claims stronger results with 53% fewer output tokens. That's it. That's the whole verified surface.

What's missing matters more. The item doesn't name a baseline model, task set, evaluation dates, output ceiling, sample size, quality margin, or pricing. A 53% reduction is a ratio; without the denominator it's just a number. The right response isn't to argue with it. It's to build the measurement you'd need to care.

Source Boundary: What the StepFun Step 5 53% Output-Token Claim Does and Does Not Establish

I'm keeping a hard line between what I read and what I expect. This is exactly the kind of claim that turns into "53% cheaper" in a slide deck.

StatementStatus
StepFun released Step 5 and claims 53% fewer output tokens alongside stronger resultsReported by Superpower Daily, dated 2026-12-03, in a single-sentence item. Secondary reporting; I have not seen the vendor's release note.
The comparison baseline modelUnknown. The item does not name it.
The evaluation tasks, prompt set, sample size, decoding settingsUnknown. Not described.
Whether 53% is an aggregate token ratio or a mean of per-task reductionsUnknown.
Step 5's model identifier, endpoint, parameter support, context limitsUnknown to me. Must come from the vendor's API reference, not from inference.
Step 5's prices, cached-input pricing, reasoning-token billingUnknown to me. Must come from the vendor's pricing page.
Anything about Step 5's measured behaviour in this postNot measured. Every number below is either hypothetical arithmetic or synthetic fixture output, labelled as such.

That list of unknowns isn't an attack on StepFun. Vendors often publish a headline efficiency number with the baseline in an appendix. The problem is engineers route traffic off headlines.

Technical Position: Measure Cost per Accepted Answer, Not Output-Token Reduction Alone

My position up front: output-token reduction is a proxy metric, and a weak one. It's cheap to produce, easy to misread, and rewards a model that says less. The metric I route on is cost per accepted answer (CPAA), reported next to acceptance rate and time to acceptance.

Three mechanisms turn a token win into a cost loss:

  1. Shorter answers that fail validation push work into a second call. A 53% shorter first response that fails a schema check can cost more than the verbose one that passed.
  2. Repair calls have worse input-to-output ratios. A repair prompt carries the original input, the failed output, and validator feedback. Input tokens grow while output tokens shrink—wrong direction if output is priced high relative to input.
  3. Aggregate token ratios get polluted by retries. Per-call reduction can stay at 53% while run-level reduction is much smaller because you made more calls.

None of this says Step 5 is worse. It says the published claim isn't enough to conclude it's better. The gap is closable with a few hundred lines of Node.js.

Scope: A Reproducible Node.js Benchmark Design, Not a Vendor Evaluation Replication

This article is a harness design with runnable code, plus synthetic fixture output proving the harness does the accounting it claims. It is not a reproduction of StepFun's evaluation, and I won't present it as one. Where a real Step 5 adapter would go, I define a contract and a config check that refuses to run until verified identifiers and prices are supplied.

Turn the 53% Claim into Explicit, Testable Hypotheses

Define Output-Token Reduction Precisely: Aggregate Ratio vs. Mean per-Task Ratio

Two defensible definitions, and they disagree:

Aggregate ratio      R_agg = 1 - (Σ output tokens, candidate) / (Σ output tokens, baseline)
Mean per-task ratio  R_mean = mean over tasks of (1 - out_candidate_i / out_baseline_i)

R_agg is total-token-weighted. A handful of tasks that generate 4,000-token answers dominate it. R_mean gives every task equal weight, so a case where the candidate emits 3 tokens instead of 12 counts as much as a case where both emit 2,000. If a vendor reports one number without saying which, it's ambiguous by up to the variance in your task mix.

There's a third, sneakier version: computing the ratio over successful attempts only. That quietly excuses tasks where the short answer failed and got retried. Reject it.

Report Four Separate Outcomes: Tokens, Quality, CPAA, and Time to Accepted Answer

Treat these as four independent report rows, never collapsed into a single score:

OutcomeUnitWhy it is separate
Output-token reductionratio, R_agg and R_meanThe vendor's claim. Says nothing about cost.
Quality preservationacceptance rate under a fixed validatorThe gate. A cheaper model that misses the bar is not cheaper.
Cost per accepted answerUSD per accepted taskThe routing decision. Includes all failed spend.
Time to an accepted answerp50/p95 milliseconds, plus terminal-failure durationsSeparate because a short answer that arrives fast and fails twice is slow.

Require a Named Baseline, Exact Model IDs, Dates, and a Quality Margin Before Comparing

The harness should refuse to run without these. Before any paid request:

  • baselineModel and candidateModel must be exact API identifiers, not marketing names.
  • evaluationDate must be recorded, because prices and snapshots move.
  • qualityMargin must be predeclared as an absolute acceptance-rate delta you'd accept, e.g. -0.02 for "no worse than 2 points below baseline."
  • pricingSnapshot must carry a source URL and a retrieval date.

If the vendor's baseline is undisclosed, your baseline is your incumbent production model. That's the more useful comparison anyway.

Define the Accounting Boundary Before Writing the Node.js Runner

Calculate CPAA as Total Attributed Spend Divided by Tasks Accepted Within the Retry Budget

CPAA = Σ_attempts cost(attempt)  /  |{ tasks accepted within the retry budget }|

The numerator spans every attempt of every task, including tasks that never succeeded. The denominator counts tasks, not attempts, not calls. It's the only definition that survives contact with a production retry policy.

Include Failed Attempts, Repairs, Verification, and Tool Charges in CPAA

If a model accepts nothing, CPAA isn't $0.00. It's undefined, and the spend is a total loss. Returning zero turns a catastrophic config into a winning leaderboard row—a bug I've seen in real dashboards.

If your pipeline bills a separate verification model, judge call, or tool invocation, that's part of CPAA. If it isn't attributable per task, keep it in a separate line item instead of pretending it's free.

Keep Provider-Billed Token Categories Separate and Avoid Double-Counting

The normalization question that bites: does input_tokens include cached tokens or exclude them? Does output_tokens include reasoning tokens, or are they billed separately? Providers differ, and some change this between API versions. Never guess. Encode the answer in the adapter and assert it in a fixture test.

// cost.mjs
// Assumes the adapter has already normalized usage so that
// usage.input_tokens INCLUDES cached tokens, and reasoning tokens
// are NOT already counted inside output_tokens.
// Both assumptions are provider-specific. Verify before use.
export function costUsd(usage, price) {
  for (const field of ["input_tokens", "output_tokens"]) {
    if (typeof usage[field] !== "number") {
      throw new Error(`usage field missing, refusing to assume zero: ${field}`);
    }
  }

  const cached = usage.cached_input_tokens ?? 0;
  const reasoning = usage.reasoning_tokens ?? 0;
  const uncachedInput = Math.max(usage.input_tokens - cached, 0);

  if (cached > usage.input_tokens) {
    throw new Error("cached tokens exceed total input tokens: adapter bug or bad assumption");
  }

  return (
    uncachedInput * price.inputPerMTok +
    cached * price.cachedInputPerMTok +
    usage.output_tokens * price.outputPerMTok +
    reasoning * price.reasoningPerMTok
  ) / 1e6;
}

Note the failure mode: ?? 0 for optional categories, but a hard throw for required ones. Missing usage is not zero usage.

Worked Example: A 53% Output-Token Reduction With Higher CPAA

Everything in this subsection is arithmetic on invented numbers. It demonstrates the outcome is possible, not that it happens with Step 5.

Setup: 200 tasks, hypothetical price set P1 = $1.00 per 1M input tokens, $8.00 per 1M output tokens. Baseline averages 1,200 input tokens and 800 output tokens per call and accepts 180/200 on the first attempt. The candidate emits 53% fewer output tokens per call (376), accepts 120/200 on the first attempt, and 80 tasks take one repair attempt with 1,500 input tokens and 376 output tokens; 20 of those repairs succeed.

LineBaselineCandidate
Tasks200200
Calls200280
Accepted first attempt180120
Accepted after repair180140
Acceptance rate90.0%70.0%
Total input tokens240,000360,000
Total output tokens160,000105,280
Aggregate output ratio R_agg—−34.2%, not −53%
Per-call output ratio—−53.0%
Spend$1.520$1.202
Cost per accepted answer$0.00844$0.00859

The candidate produced 34% fewer output tokens across the run and still cost 1.7% more per accepted answer. Two things happened: the per-call 53% shrank to a run-level 34% because of extra calls, and the accepted-task count fell by 22%.

Sensitivity flips this, which is the point of running sensitivity at all:

Price set (input / output per 1M)Baseline CPAACandidate CPAAWinner
P1: $1.00 / $8.00$0.00844$0.00859Baseline, by 1.7%
P2: $1.00 / $2.00$0.00311$0.00408Baseline, by 31%
P3: $0.25 / $8.00$0.00744$0.00666Candidate, by 10.6%

Under P2, cheap output makes repair-input overhead dominate and the candidate loses badly. Under P3, cheap input makes the output saving dominate and the candidate wins. The sign of the answer depends on a pricing ratio you can't infer from the token claim. That's the strongest argument for measuring CPAA directly.

Build a Versioned Task Corpus with Deterministic Acceptance Checks

Create JSONL Cases for Extraction, Transformation, and Code Repair

{"id":"extract-001","family":"structured-extraction","weight":1,"prompt":"Return the invoice fields as JSON matching schema v3. Output JSON only.","input":{"kind":"fixture","path":"fixtures/invoice-001.txt"},"validator":"invoice-schema-v3","acceptanceRule":"all-fields-exact"}
{"id":"transform-004","family":"constrained-transformation","weight":1,"prompt":"Convert the record to the legacy CSV row format. No prose.","input":{"kind":"inline","value":"{...}"},"validator":"csv-row-v1","acceptanceRule":"exact-string"}
{"id":"js-repair-014","family":"code-repair","weight":2,"prompt":"Fix the failing function. Return only the function body.","input":{"kind":"fixture","path":"fixtures/slugify-broken.js"},"validator":"js-repair-v2","acceptanceRule":"unit-tests-pass"}

weight is predeclared and lets you reweight families without editing cases. acceptanceRule exists so nobody "improves" the validator mid-run and calls it the same benchmark.

Implement Validators That Reject Plausible but Incorrect Answers

The validator is load-bearing. A lax validator manufactures a fake acceptance-rate win, and it'll do so in the direction of whichever model produces more plausible-sounding prose.

// validators/js-repair-v2.mjs


export async function validate(text, task) {
  const code = extractFenceOrRaw(text);
  if (!code) return { ok: false, reason: "empty-output" };

  // Never run model-generated code in the harness process.
  const result = await runInSandbox(code, task.testsPath, { timeoutMs: 5000 });

  if (result.timedOut) return { ok: false, reason: "sandbox-timeout" };
  if (result.exitCode !== 0) {
    return { ok: false, reason: "tests-failed", detail: truncate(result.stderr, 2000) };
  }
  return { ok: true };
}

Design the tests to catch the plausible-but-wrong answer. For a slugify repair, include a case with a trailing dash, a case with Unicode combining marks, and a case that would pass if the model hardcoded the fixture input. That last one is the one people forget, and it's the one that rewards memorization over capability.

Split Dev and Eval Cases, Hash the Corpus, and Predeclare Weights

// corpus/hash.mjs



export function corpusHash(path) {
  const lines = readFileSync(path, "utf8")
    .split("\n")
    .filter(Boolean)
    .map((line) => JSON.stringify(JSON.parse(line))) // canonical field order
    .sort();
  return createHash("sha256").update(lines.join("\n")).digest("hex");
}

corpusHash goes in the run manifest. If two runs report different hashes, they aren't comparable and nobody should put them in the same table. Keep the held-out set strictly separate: iterate prompts on dev.jsonl, report on eval.jsonl, and don't look at eval failures before the run is frozen.

Document Task Count, Repetitions, Input Sizes, and Limitations

My suggested default: 150 dev cases, 200 eval cases, 1 repetition per case for the headline run and 3 repetitions for a stability check on a 40-case subsample. State input size distribution (median and p95 input tokens) because repair overhead scales with it.

📝

This workload can establish whether this extraction/transformation/repair mix, under this retry policy, at this price snapshot, produces cheaper accepted answers. It cannot establish general model quality, long-horizon agentic competence, multilingual ability, or performance on tasks outside the three families. Write that limitation into the report, not the appendix.

Make the Node.js Experiment Reproducible

Lay Out the Harness: Cases, Config, Adapters, Validators, Runner, Ledger, Report

bench/
  cases/dev.jsonl
  cases/eval.jsonl
  benchmark.config.json
  adapters/base-contract.md
  adapters/baseline.<provider>.mjs
  adapters/candidate.stepfun.mjs
  validators/index.mjs
  lib/corpus-hash.mjs
  lib/cost.mjs
  lib/ledger.mjs
  runner.mjs
  report.mjs
  out/<runId>/ledger.jsonl
  out/<runId>/manifest.json
  out/<runId>/report.md
test/
  fixtures.test.mjs
  accounting.test.mjs

Record the Run Manifest: Versions, Hashes, Models, Prices, and Seed

{
  "runId": "2026-12-08T10-00Z-a1",
  "nodeVersion": "v22.x",
  "lockfileSha256": "…",
  "corpusHash": "…",
  "configHash": "…",
  "seed": 20261208,
  "evaluationDate": "2026-12-08",
  "baselineModel": "<exact-id-from-verified-docs>",
  "candidateModel": "<exact-id-from-verified-docs>",
  "endpoint": "<from-verified-docs>",
  "pricingSnapshot": {
    "retrievedAt": "2026-12-08",
    "sourceUrl": "<verified-pricing-page>",
    "inputPerMTok": null,
    "outputPerMTok": null
  }
}

The null prices are deliberate. The config check fails on nulls, which is the mechanism that stops me from shipping invented Step 5 pricing into a report.

Provide Install, Fixture-Test, Benchmark, and Report Commands

npm ci
npm run test:fixtures
npm run check:config -- --config benchmark.config.json
npm run bench -- --config benchmark.config.json --cases cases/eval.jsonl --seed 20261208
npm run report -- --run out/2026-12-08T10-00Z-a1

One detail worth enforcing: redact the API key from every log line by construction, not by remembering. Build the adapter so the key is read inside the transport function and never enters a request-description object the logger serializes.

Implement Provider Adapters Without Inventing Step 5 API Details

Define a Shared JavaScript Adapter Contract for Text, Usage, Billing, and Timing

// adapters/base-contract.md — the shape every adapter must return
// {
//   text: string,
//   rawUsage: object | null,        // verbatim provider payload
//   usage: {
//     input_tokens: number,         // includes cached, per adapter normalization
//     cached_input_tokens: number,  // 0 if the provider has no cache
//     output_tokens: number,        // excludes separately billed reasoning
//     reasoning_tokens: number      // 0 only if the provider confirms none billed
//   },
//   finishReason: "stop" | "length" | "content_filter" | "tool_call" | "unknown",
//   requestId: string | null,
//   timings: { requestMs: number }
// }

rawUsage exists so that six weeks later you can answer "did the provider change what output_tokens means?" without rerunning the suite.

Populate Step 5 Details Only From Verified Documentation and Fail Config Checks

// lib/config-check.mjs
const REQUIRED = [
  "baselineModel", "candidateModel", "endpoint",
  "pricingSnapshot.inputPerMTok", "pricingSnapshot.outputPerMTok",
  "pricingSnapshot.sourceUrl", "pricingSnapshot.retrievedAt"
];

export function checkConfig(config) {
  const missing = REQUIRED.filter((path) => {
    const value = path.split(".").reduce((o, k) => o?.[k], config);
    return value === undefined || value === null || value === "";
  });

  if (missing.length) {
    throw new Error(
      `config incomplete, refusing to spend money: ${missing.join(", ")}\n` +
      `Fill these from verified provider documentation only.`
    );
  }
}

I'm not providing a Step 5 adapter here because I don't have verified Step 5 identifiers, parameter support, or prices. An invented adapter is worse than no adapter: it looks runnable. The check:config step above is the honest placeholder.

Preserve Raw Usage, Distinguish Missing From Zero, and Reconcile Against Billing

if (raw.usage == null) {
  record.usageSource = "missing";   // NOT zero
  record.costUsd = null;
} else {
  record.usageSource = "provider";
  record.costUsd = costUsd(normalize(raw.usage), price);
}

Any attempt with usageSource: "missing" must be excluded from cost totals and reported as a coverage gap. A benchmark that quietly assumes zero cost for 8% of calls produces a cost figure that's 8%+ too optimistic, and it'll be too optimistic in the direction of whichever model returns usage less reliably.

Run Matched Prompts Under Explicit Resource Controls

Send Matched Prompts and Record Unavoidable Provider Differences

Perfect matching isn't achievable across providers, so record the mismatch instead of pretending it away:

{
  "promptParity": {
    "instructionText": "identical",
    "inputFixture": "identical",
    "chatTemplate": "provider-managed",
    "systemPromptSupport": { "baseline": true, "candidate": true },
    "unsupportedParams": ["top_k"],
    "defaultTemperatureDisclosed": { "baseline": false, "candidate": false }
  }
}

If one provider doesn't support a parameter you set on the other, that's a finding about comparability, and it belongs in the report header.

Fix Sampling, Tools, Timeouts, and Output Ceilings; Equal Caps Aren't Equal Compute

Set the same maxOutputTokens on both sides for fairness in the ceiling sense, then note the asymmetry: a model that spends a large share of its budget on hidden reasoning tokens can hit a 1,000-token cap having generated far more underlying compute than a model that emits 1,000 visible tokens directly. Equal caps bound output, not cost. If the provider bills reasoning separately, that spend appears in the ledger and nowhere in the visible text—which is exactly why reasoning is its own billing category in the adapter contract.

Disable tools entirely for the first comparison. Tool availability adds a branch per task and turns a token benchmark into an agent benchmark.

Randomize Pair Order, Bound Concurrency, and Separate Warm-Up Traffic

Randomized order matters when a provider rate-limits per minute: running all baseline traffic first and all candidate traffic second means one model absorbed a cold cache and the other didn't. Interleave at the task level with a seeded shuffle, hold concurrency to a small fixed number, and send a fixed number of warm-up requests per model that are logged but excluded from aggregates.

Log Truncation, Refusal, Transport Errors, and Timeouts as Distinct Outcomes

finishReason=length        -> outcome "truncated",  counts as not accepted
finishReason=content_filter-> outcome "refused",    counts as not accepted
ECONNRESET / 5xx           -> outcome "transport_error", retried by transport policy only
AbortError after timeoutMs -> outcome "timeout",    counts as not accepted

Dropping these is the single most common way a benchmark flatters a model with shorter outputs, because truncated answers are short. A truncation rate that differs between models will move token totals more than any prompt change.

Make Acceptance and Retry Policies Part of the Benchmark

Implement the Attempt State Machine: Request, Validate, Accept, Repair, Stop

// runner.mjs (abbreviated)


export async function runTask({ task, adapter, validator, policy }) {
  const attempts = [];
  let feedback = null;

  for (let n = 1; n <= policy.maxAttempts; n++) {
    const started = performance.now();
    let response;

    try {
      response = await adapter.complete({
        prompt: task.prompt,
        input: task.input,
        repairFeedback: feedback,
        timeoutMs: policy.timeoutMs,
      });
    } catch (err) {
      attempts.push(makeRecord({
        task, n, response: null,
        totalMs: performance.now() - started,
        outcome: classifyError(err), // transport_error | timeout | auth_error
      }));
      break; // transport failures are not repaired with prompt changes
    }

    const validationStarted = performance.now();
    const verdict = await validator(response.text, task);
    const validationMs = performance.now() - validationStarted;

    attempts.push(makeRecord({
      task, n, response, validationMs,
      totalMs: performance.now() - started,
      outcome: verdict.ok ? "accepted" : "rejected",
    }));

    if (verdict.ok) return { accepted: true, attempts };

    feedback = policy.repairTemplate(verdict);
    if (n < policy.maxAttempts && policy.retryDelayMs) {
      await new Promise((r) => setTimeout(r, policy.retryDelayMs));
    }
  }

  return { accepted: false, attempts };
}

Note that a transport error breaks the loop rather than consuming a repair attempt. Conflating the two inflates apparent quality by letting prompt-level repair soak up infrastructure noise.

Apply the Same Repair Template and Feedback Rules to Both Models

// policy.js
export function repairTemplate(verdict) {
  return [
    "Your previous response failed validation.",
    `Reason: ${verdict.reason}`,
    verdict.detail ? `Detail: ${verdict.detail}` : "",
    "Return only the corrected output. No explanation.",
  ].filter(Boolean).join("\n");
}

One template, both models, same truncation of verdict.detail, same attempt cap. If the template differs per model, the benchmark measures your prompting skill.

Separate Application Retries From Transport Retries and Instrument SDK Retries

Most SDKs retry on 429 and 5xx by default, and the retried request is a real billable request. If your ledger only records what your code called, the SDK's hidden call is free in your accounting and paid on your invoice.

const client = new ProviderClient({
  apiKey: process.env.PROVIDER_API_KEY,
  maxRetries: 0,          // or a value the ledger can observe
});

If a client library allows an onRetry hook, log it as a synthetic attempt with its own cost. Otherwise set retries to zero and implement them yourself so every attempt reaches the ledger.

Run Single-Attempt and Fixed-Retry Comparisons to Expose Shifted Work

Two configurations, same corpus, same seed:

ConfigmaxAttemptsWhat it tells you
strict-single1Raw first-response quality and raw per-call token economics
product-policy3What your application will actually pay

If a model's acceptance rate jumps much more from strict-single to product-policy than its competitor's, its first answers were weaker and the repair loop is doing the heavy lifting. That's real, billable work, whether or not the repair loop appears in the vendor's baseline.

Measure Latency and Preserve an Auditable Attempt Ledger

Use Node.js Monotonic Timers for Request, Validation, Retry, and Total Durations

performance.now() from node:perf_hooks is monotonic and unaffected by wall-clock adjustments, which matters on a cloud VM where NTP can step the clock mid-run. Date.now() can't be used for duration measurement.



const marks = [];
const t0 = performance.now();
const response = await adapter.complete({ /* ... */ });
marks.push({ phase: "request", ms: performance.now() - t0 });
const t1 = performance.now();
const verdict = await validator(response.text, task);
marks.push({ phase: "validate", ms: performance.now() - t1 });
const totalMs = performance.now() - t0;

Measure Time to First Token Only When Comparable; Report Time to Accepted Answer

TTFT is a UX metric. Time to accepted answer is an engineering metric. They can move in opposite directions: a model that starts streaming fast but needs a repair has excellent TTFT and terrible time to accepted answer.

Only compare TTFT between two models if both support streaming on the same transport. If one doesn't, report ttftMs: null for that model with a note—never 0, and never silently substituted with total request time.

Write One JSONL Attempt Record With Usage, Cost, Timing, and Outcome

{"runId":"2026-12-08T10-00Z-a1","taskId":"js-repair-014","family":"code-repair","weight":2,"attempt":2,"model":"<verified-id>","requestId":"req_abc123","usageSource":"provider","rawUsage":{"input_tokens":1500,"output_tokens":376},"usage":{"input_tokens":1500,"cached_input_tokens":0,"output_tokens":376,"reasoning_tokens":null},"priceSetId":"P1","costUsd":0.004508,"timings":{"requestMs":1840,"validateMs":12,"retryDelayMs":250,"totalMs":2102},"validation":{"validator":"js-repair-v2","passed":true},"outcome":"accepted","finishReason":"stop"}

"reasoning_tokens": null means the provider didn't report the field. That's different from 0, and the reporting layer must not coerce it. Same for costUsd: null when usage is missing.

Report Accepted-Task Percentiles Alongside Failure Rates and Terminal Durations

time to accepted answer, p50 / p95, accepted tasks only   → 2,100 ms / 5,800 ms
terminal-failure duration, p50 / p95, failed tasks only   → 6,300 ms / 9,100 ms
acceptance rate                                            → 70.0%
terminal failure rate                                      → 30.0%

Reporting only the first row is how a 30% failure rate becomes invisible. The second row is where the money and user frustration actually went.

Test the Harness Before Sending Paid Requests

Use Deterministic Mock Adapters for Malformed Output, Timeouts, and Missing Usage

A mock adapter that replays a scripted sequence per task is enough:

// test/mocks.mjs
export function scriptedAdapter(scripts) {
  const cursor = new Map();
  return {
    async complete({ task }) {
      const i = cursor.get(task.id) ?? 0;
      cursor.set(task.id, i + 1);
      const step = scripts[task.id][Math.min(i, scripts[task.id].length - 1)];
      if (step.kind === "timeout") {
        const err = new Error("aborted"); err.name = "AbortError"; throw err;
      }
      return {
        text: step.text,
        rawUsage: step.usage ?? null,
        usage: step.usage ?? null,
        finishReason: step.finishReason ?? "stop",
        requestId: `mock-${task.id}-${i}`,
        timings: { requestMs: 1 },
      };
    },
  };
}

Add Accounting Assertions for Retries, Failed Spend, Cached Tokens, and Zero Acceptance

// test/accounting.test.mjs




test("repair attempts are charged to the original task", () => {
  const ledger = [
    { taskId: "t1", outcome: "rejected", costUsd: 0.002 },
    { taskId: "t1", outcome: "accepted", costUsd: 0.003 },
    { taskId: "t2", outcome: "rejected", costUsd: 0.004 },
    { taskId: "t2", outcome: "accepted", costUsd: 0.001 },
  ];
  const r = costPerAcceptedAnswer(ledger);
  assert.equal(r.acceptedCount, 2);
  assert.ok(Math.abs(r.spendUsd - 0.010) < 1e-9);
  assert.ok(Math.abs(r.cpaaUsd - 0.005) < 1e-9);
});

test("zero accepted answers is unbounded, not zero", () => {
  const ledger = [{ taskId: "t1", outcome: "rejected", costUsd: 0.5 }];
  const r = costPerAcceptedAnswer(ledger);
  assert.equal(r.cpaaUsd, null);
  assert.equal(r.spendUsd, 0.5);
  assert.equal(r.note, "unbounded");
});

test("cached tokens are not billed at the uncached rate", () => {
  const price = { inputPerMTok: 1, cachedInputPerMTok: 0.25, outputPerMTok: 8, reasoningPerMTok: 8 };
  const usage = { input_tokens: 1_000_000, cached_input_tokens: 800_000, output_tokens: 0, reasoning_tokens: 0 };
  const cost = costUsd(usage, price);
  assert.ok(Math.abs(cost - 0.4) < 1e-9); // 200k * 1 + 800k * 0.25
});

Show Expected Fixture Output and Label It as Synthetic Harness Output

$ npm run test:fixtures

✔ malformed JSON is recorded as rejected, not retried as transport (11.2ms)
✔ truncated output is counted as not accepted (3.4ms)
✔ timeout produces a terminal-failure duration (5.1ms)
✔ missing usage yields costUsd null, excluded from spend totals (2.8ms)
✔ repair attempt is charged to the original task (4.0ms)
✔ zero accepted answers reports cost as unbounded (1.9ms)
✔ cached tokens are not billed at the uncached rate (2.2ms)
✔ success after repair counts one accepted task, two attempts (3.6ms)

ℹ tests 8
ℹ pass 8
ℹ fail 0

That output is from mock adapters with hardcoded prices. It proves the accounting behaves as specified. It says nothing about Step 5.

Sandbox Generated-Code Validation With Resource Limits and No Secrets

Node's docs are explicit that node:vm is not a security mechanism and must not be used to run untrusted code—model output is untrusted code. Run validation in a separate child process with an empty environment, a hard wall-clock timeout, no network namespace if you can get one, and a read-only filesystem mount. A container per validation batch is the cheapest defensible option.

⚠️

Never import() or eval() model-generated JavaScript inside the harness. One working prompt-injection or accidental fetch to a local metadata endpoint can exfiltrate the same API keys the benchmark is trying to save money on.

Analyze Paired Results Without Overstating the Evidence

Produce a Fixed Comparison Table From the Ledger

The report should be a fixed schema, generated from the ledger, not assembled by hand. Every row in the earlier hypothetical table maps to a report.mjs computation over ledger.jsonl.

Calculate Paired Task-Level Intervals by Resampling Whole Tasks

The resampling unit is the task, carrying all of its attempts, because attempts within a task are correlated. Resampling individual attempts understates variance and produces intervals that are too narrow.

// lib/bootstrap.mjs
function mulberry32(seed) {
  return function () {
    seed |= 0; seed = (seed + 0x6D2B79F5) | 0;
    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

export function bootstrapDeltaCpaa(perTask, { iterations = 10_000, seed = 20261208 } = {}) {
  const rand = mulberry32(seed);
  const n = perTask.length;
  const deltas = [];

  for (let i = 0; i < iterations; i++) {
    let baseSpend = 0, baseAcc = 0, candSpend = 0, candAcc = 0;
    for (let j = 0; j < n; j++) {
      const t = perTask[Math.floor(rand() * n)];
      baseSpend += t.baseSpend; candSpend += t.candSpend;
      baseAcc += t.baseAccepted; candAcc += t.candAccepted;
    }
    if (baseAcc === 0 || candAcc === 0) continue; // undefined, not zero
    deltas.push(candSpend / candAcc - baseSpend / baseAcc);
  }

  deltas.sort((a, b) => a - b);
  const q = (p) => deltas[Math.floor(p * (deltas.length - 1))];
  return { p2_5: q(0.025), p50: q(0.5), p97_5: q(0.975), n: deltas.length };
}

At 200 tasks the interval will be wide. Report it anyway. A point estimate of a 1.7% difference on 200 tasks with a 70% acceptance rate is almost certainly not distinguishable from zero. Saying so is more useful than rounding to "Step 5 is 1.7% more expensive."

Show All-Attempt Token Totals and Break Results Down by Family and Failure

A per-family table usually shows the claim is family-dependent:

FamilyR_aggBaseline acc.Candidate acc.Δ CPAA
structured extraction−51%94%88%+2.1%
constrained transformation−58%90%82%+0.4%
code repair (weight 2)−22%84%52%+18.7%

The headline 53% can be real for extraction and transformation while the code-repair family—the one you actually care about—barely benefits. If I had one reporting recommendation, it's this: never accept a single aggregate token number without a per-family breakdown.

Run Pricing, Cache, Retry, and Task-Mix Sensitivity Checks Against a Frozen Config

Vary one axis at a time against the frozen primary config: price sets P1/P2/P3, cache hit rate at 0%/50%/80%, maxAttempts at 1/2/3, and task mix recomputed with each family weighted to 100%. Report the sign of Δ CPAA per scenario. A claim that flips sign under plausible pricing isn't robust, and the sensitivity table is the cheapest way to say so.

Interpret the Outcome and Set a Deployment Gate

Distinguish Token Wins From Quality, Latency, and Genuine CPAA Wins

The four interpretable outcomes:

PatternReading
Fewer tokens, acceptance falls below the floorToken win, product regression. Do not ship.
Lower CPAA, p95 time to accepted answer exceeds budgetCost win, UX regression. Ship only if the latency budget is renegotiable.
Lower CPAA, acceptance at or above floor, latency within budgetGenuine savings. Ship behind a fallback.
Lower CPAA only under one price setFragile. Re-run when prices move.

Only the third row is a routing decision. The first row is the trap a headline "53% fewer output tokens" is designed to hide, and it's the one I'd expect from a model optimizing for brevity.

Set the Acceptance Floor, Cost Improvement, Latency Budget, and Failure Ceiling Before Routing

Write the gate before the run:

{
  "gate": {
    "acceptanceFloorAbsolute": 0.85,
    "maxAcceptanceDeltaVsBaseline": -0.02,
    "minCpaaImprovement": 0.10,
    "maxP95TimeToAcceptedMs": 8000,
    "maxTerminalFailureRate": 0.05,
    "maxTruncationRate": 0.02
  }
}

If the candidate clears all six, route a small share of traffic. If it clears five, you have a decision to make with your product owner, and now you can make it with numbers instead of a vendor slide.

Keep a Baseline Fallback and Rerun the Held-Out Suite When Anything Changes

Invalidate the run—not just note it—when any of these change: model snapshot identifier, price sheet, prompt templates, validator version, corpus hash, retry policy, or output ceiling. Store the baseline's ledger alongside the candidate's so the comparison is always recomputable from records rather than a stale summary. The baseline fallback isn't optional; it's the control group.

Evidence and Further Reading

Unresolved as of this writing, none of which I'm willing to guess at:

  • The name and version of the baseline model in StepFun's comparison.
  • The task suite, prompt templates, and decoding settings used for the 53% figure.
  • Whether 53% is R_agg or R_mean, and whether it was computed over successful attempts only.
  • Step 5's exact API model identifier, endpoint, supported parameters, and context limits.
  • Step 5's token pricing, including any cached-input discount and reasoning-token billing rules.
  • Whether the quality comparison used the same validator or a human rater, and at what agreement level.

Add Verified StepFun Release, API, and Pricing References When Available

I'm deliberately not linking a StepFun release note, API reference, or pricing page here because I couldn't verify the exact URLs for the Step 5 announcement. The three documents to retrieve before running anything paid are: the release note (baseline and evaluation method), the API reference (model identifier and parameter support), and the pricing page (per-1M input, cached-input, output, and reasoning rates). Paste them into benchmark.config.json with a retrieval date. When verified links exist, they belong in this section replacing this paragraph.

To restate the boundary one final time: the tables in the accounting section are hypothetical arithmetic on invented prices; the validation output is from mock adapters; nothing in this post is a measurement of StepFun Step 5. The harness is real, and it's designed so that when real identifiers and prices do arrive, the first thing it does is refuse to run until they're verified.

Share this post

More posts

Loading comments…