Skip to main content
Back to all articles
AI Engineering 10 min readUpdated October 28, 2026

Building Token Admission Checks for Model Migrations

Model migrations need fresh, request-bound token evidence. Build admission checks, compare recounts by workload segment, reserve generation budgets, and reconcile estimates with actual usage.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#tokenization#model-migration#context-engineering#llm-evaluation#typescript#python#cost-optimization
On this page

A token budget is meaningful only when its measurement matches the runtime receiving the request.

For a production application, that runtime includes more than the visible prompt. It includes the selected model, message representation, tools, document or image inputs, output configuration, and any context carried forward from earlier turns.

Changing the model can change the measurement even when the text stays the same. Changing the request adapter can change it again. I would therefore make fresh counting part of admission and release evidence, rather than keep one cached token number attached to a document forever.

This article uses a hypothetical maintenance-document assistant. It answers questions from multilingual manuals, diagrams, and recent equipment observations. The examples are implementation sketches; no migration benchmarks or incidents are claimed.

Record what was actually counted

Suppose the assistant retrieves a manual section and records tokenCount: 2400 on the chunk. That value is useful only if its counting context is known.

Was it measured with a local text tokenizer or a provider endpoint? Which encoding or model was used? Did it include message wrappers? Were the document images included? Has the text changed since then?

I would store the chunk's immutable content identity separately from measurements of that content. A count can then carry its counter version and runtime scope.

The tiktoken project provides encoding-specific and model-mapped text tokenization. That is useful for local text analysis, but applying a tokenizer to concatenated strings does not by itself reproduce a provider's complete multimodal request accounting.

For request admission, prefer a counting adapter that understands the target API. If a local approximation is necessary, label its scope and calibrate its error against actual requests. Do not silently present an approximation as a complete count.

Count the assembled request

Counting retrieved paragraphs before assembly misses costs added by system instructions, tool definitions, schema descriptions, history, and the request format itself.

The boundary I want is:

  1. select an eligible runtime profile;
  2. assemble the request for that profile;
  3. obtain a count for the supported input;
  4. evaluate the applicable limits and budget policy;
  5. send that same request representation.

If retrieval, tools, or generation settings change after counting, repeat the admission check.

Claude's token-counting documentation explicitly treats the returned count as an estimate and documents unsupported combinations accepted by generation. A counting adapter should expose those limitations instead of deleting unsupported features and declaring the smaller request safe.

Gemini's token guide separately documents input counting and response usage, including non-text modalities. A text-only estimate is not enough evidence for a request containing diagrams or audio.

An unsupported request can follow a separately reviewed estimation policy, use another eligible runtime, or wait for a compatible path. The important behavior is to preserve the distinction between supported counting, partial estimation, and missing evidence.

Represent limits in the provider adapter

There is no single output parameter with identical semantics across all models and APIs.

A provider may impose separate input and output limits, a shared context window, or additional rules around reasoning and retained context. Some APIs may adjust an output allowance rather than reject a request in the way an application expects.

Normalize those rules into a runtime profile. Have the adapter calculate a conservative input allowance for the exact requested generation configuration. Keep a task's quality limit separate from the API's advertised window.

The existing effective-context-limit design addresses how much context remains useful. A migration can satisfy an API limit and still lose answer quality because relevant evidence is crowded out or positioned differently.

A margin for counting uncertainty is another field. Set it from observed error and operational risk. A round number chosen without measurement may be too small for some modalities and wastefully large for others.

Bind count evidence to the request being admitted

The TypeScript sketch below checks a normalized request plan and a count receipt. Its input allowance has already been calculated by the provider adapter for the requested output and reasoning settings.

TypeScript
type AdmissionPlan = {  profileVersion: string;  counterVersion: string;  requestDigest: string;  inputAllowance: number;  generationRequested: number;  generationLimit: number;  uncertaintyMargin: number;};​type CountReceipt = {  profileVersion: string;  counterVersion: string;  requestDigest: string;  inputTokens: number;  fullInputCovered: boolean;  expiresAtMs: number;};​function admissionRejections(  plan: AdmissionPlan,  count: CountReceipt,  nowMs: number,): string[] {  const reasons: string[] = [];  const values = [    plan.inputAllowance, plan.generationRequested,    plan.generationLimit, plan.uncertaintyMargin,    count.inputTokens, count.expiresAtMs, nowMs,  ];  if (values.some(value => !Number.isSafeInteger(value) || value < 0)) {    return ["invalid-numeric-evidence"];  }  if (    plan.profileVersion !== count.profileVersion ||    plan.counterVersion !== count.counterVersion ||    plan.requestDigest !== count.requestDigest  ) {    reasons.push("measurement-mismatch");  }  if (!count.fullInputCovered) reasons.push("incomplete-count");  if (count.expiresAtMs <= nowMs) reasons.push("expired-count");  if (    plan.generationRequested < 1 ||    plan.generationRequested > plan.generationLimit  ) {    reasons.push("unsupported-generation-budget");  }  if (    plan.inputAllowance < plan.uncertaintyMargin ||    count.inputTokens > plan.inputAllowance - plan.uncertaintyMargin  ) {    reasons.push("input-budget-exceeded");  }  return reasons;}

This function assumes validated objects from trusted services. It does not authenticate the counter, build the request digest, or prove that the uncertainty margin is adequate.

The digest should bind the immutable request representation and relevant resolved asset versions. A mutable file URL is not an immutable input snapshot. If a provider resolves an asset differently at generation time, an identical URL string does not establish identical content.

The runtime profile must identify the model and API configuration being used. If the provider exposes an immutable revision, bind it. If it exposes only a moving alias, record that limitation, expire measurements conservatively, and repeat validation when observed behavior changes.

The generation path should verify that it is sending the admitted request. Allowing a helper to append tool schemas afterward defeats the check.

A migration needs a distribution of recounts

A single percentage change across all requests hides the cases most likely to break.

For the maintenance assistant, I would stratify by language, document type, image count, tool-schema size, conversation depth, and proximity to the input allowance. Include currently successful requests close to the boundary, as well as ordinary short requests.

Use the same logical case under both runtimes, rendered through each runtime's own adapter. Record both renderings. This compares the actual deployment alternatives, rather than pretending two providers consume identical serialized requests.

A Python report can preserve the distinction between the average change and newly rejected cases:

Python
from dataclasses import dataclassfrom collections import defaultdict​@dataclass(frozen=True)class Recount:    case_id: str    segment: str    baseline_input: int    candidate_input: int    baseline_allowance: int    candidate_allowance: int​def summarize_migration(rows: list[Recount]) -> dict[str, dict]:    if not rows:        raise ValueError("A migration report needs cases")    if len({row.case_id for row in rows}) != len(rows):        raise ValueError("Case IDs must be unique")​    groups: dict[str, list[Recount]] = defaultdict(list)    for row in rows:        values = (            row.baseline_input, row.candidate_input,            row.baseline_allowance, row.candidate_allowance,        )        if any(type(value) is not int or value < 0 for value in values):            raise ValueError("Counts and allowances must be nonnegative integers")        groups[row.segment].append(row)​    report = {}    for segment, cases in groups.items():        baseline = sum(row.baseline_input for row in cases)        candidate = sum(row.candidate_input for row in cases)        newly_over_budget = [            row.case_id for row in cases            if row.baseline_input <= row.baseline_allowance            and row.candidate_input > row.candidate_allowance        ]        report[segment] = {            "cases": len(cases),            "baseline_input": baseline,            "candidate_input": candidate,            "aggregate_ratio": candidate / baseline if baseline else None,            "newly_over_budget": newly_over_budget,        }    return report

Here, allowances are the effective budgets after output reservation, task policy, and uncertainty margin. The function does not derive them from a provider's marketing window.

The aggregate ratio weights cases by their input-token totals. It describes this sample, not a universal tokenizer multiplier. A segment with no baseline tokens receives no ratio rather than an invented denominator.

Keep case-level results for diagnosis and add headroom distributions, rejection rates, and production traffic weights in the real report. If related requests share a document or session, account for that dependence when estimating uncertainty.

The release gate should have explicit rules for required segments and critical cases. A favorable overall ratio cannot compensate for every long multilingual request becoming inadmissible.

Token counts and monetary budgets need separate evidence

A different tokenizer does not establish a higher bill. Prices, cache treatment, output length, reasoning, tool use, retries, and completed-work rate can all change.

Use recounted input to plan reservations, but compare complete workflow economics. Measure how much useful work finishes within the approved budget.

The tenant budget ledger should reserve against the selected runtime and settle from reported usage. Store the pricing version separately from raw token counters. Otherwise a pricing update can look like measurement drift.

Normalize provider usage before pricing it. Cached input can be a subset of total input, and reasoning may overlap another reported category. Summing every usage field is not a reliable billing calculation.

Input preflight also cannot predict the actual generated output. Reserve a conservative supported generation budget, bound retries, and reconcile ambiguous calls. Do not mark missing usage as zero spend.

Cache eligibility must be revalidated

A count receipt cached by the application is different from a provider's prompt cache.

An application count cache avoids repeating measurement work. Its key must bind model profile, counter version, input representation, relevant assets, and scope. A provider prompt cache reuses processing state under its own rules.

A preflight count is not proof that generation will receive a cache hit. During a model migration, check cache eligibility, observed reuse, and cold-path economics separately. The target might already have a reusable compatible prefix; it might also miss while the source remains warm.

The workflow routing article covers that decision. This migration gate supplies the model-specific input measurements that the router should consume.

Do not expand a prompt with unnecessary material merely to cross a cache threshold. Evaluate quality and total cost together, and keep the uncached path viable.

Rebuild context deliberately when a request no longer fits

An admission failure is a useful signal if it leads to a controlled repair path.

For the maintenance assistant, first retain instructions and the latest authoritative observations. Reduce redundant passages, retrieve a narrower section, or move large intermediate data behind artifact references. Split a document-analysis job when the task supports it.

After rebuilding, recount and rerun the answer-quality contract. Removing an apparently low-value passage can remove the only evidence for a safety instruction or equipment identifier.

Never trim authorization scope, business constraints, or unresolved approval state to recover a few tokens. Keep those controls outside model-generated summaries where possible.

A larger window is another option only when the runtime is eligible and the task remains effective at that size. The model-upgrade eval gate still needs to test behavior after the change.

Model migration token-count admission workflow

*The assembled request is counted for the selected model, matched to its evidence digest and budget, then executed only after admission passes.*

The rebuild loop also needs a maximum number of attempts. An application should not keep compacting and recounting indefinitely.

Observe measurement drift after release

Record count source, counter version, runtime profile, request-assembly version, input estimate, applicable allowance, reserved generation budget, and rejection reason.

After generation, compare the estimate with the provider's reported input usage under a documented normalization. Some reported counts include provider-added components that do not map directly to billed content. Interpret discrepancies through the adapter before changing the safety margin.

Useful metrics include:

  • admission rejection rate by runtime and workload segment;
  • remaining headroom near the context boundary;
  • preflight failures and unsupported-count paths;
  • estimate-to-reported-input error distribution;
  • counting latency and cache-hit rate for count receipts;
  • retries and incomplete generations;
  • spend per attempted and successfully completed workflow;
  • cold and reused-prefix token usage.

Counts and version identifiers generally provide enough aggregation context. Keep private manuals, tool arguments, and raw prompts in controlled diagnostic storage. Even digests can reveal equality or enable guessing of low-entropy content, so protect fingerprints and use scoped keyed hashing when appropriate.

Failure cases I would include in the migration gate

The request changed after counting. Alter a tool schema or append a history turn and ensure the old receipt no longer admits the request.

The model profile changed. A fallback must obtain compatible evidence instead of reusing the primary model's count.

Partial input was counted. Unsupported server tools or an unresolved document must not become a confident full-input receipt.

A long session grows differently. Evaluate late turns and retained context, not only the first prompt.

A narrow traffic segment expands sharply. Keep per-segment rejection evidence instead of relying on an average.

The receipt expired. Refresh evidence under the active counter and profile.

The counter is unavailable. Apply an explicit reviewed degradation policy rather than guessing and labeling the guess verified.

Usage is delayed or missing. Preserve the reservation and reconcile it according to policy.

A request fits but quality regresses. Admission and semantic evaluation must both pass.

Repeated repairs lose evidence. Bound rebuilding and test that important identifiers, constraints, and citations survive.

Scale the controls to the workload

For short, bounded text requests far from the context limit, a validated local estimator and periodic reconciliation may be enough. Counting every request remotely can add latency and another dependency.

For variable multimodal inputs, large tool contracts, or sessions close to their allowance, stronger preflight evidence is easier to justify. Cache measurements for immutable inputs where safe, and use selective counting based on documented risk.

The engineering goal is to make a runtime migration a visible change in measurement, admission, and economics. Each deployed request should be admitted using evidence that describes the input and model actually used.

Primary references

Provider details were checked on October 13, 2026. Exact limits, supported inputs, generation controls, and accounting fields should be verified for the deployed model and API.

KEEP READING

Related engineering notes