BYOK custom models: incorrect tokenizer estimates can undercount context and break compaction

オープン
#5,618 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

評価

難易度
5/5
見積もり時間
1週間以上
初心者へのやさしさ
25/100
issue の種類
バグ
明瞭さ
おおむね明確
活発さ
停滞
技術スタック
javascript, python, rust, typescript
領域
ai, backend

調査の方向性

The report identifies Copilot CLI 1.0.118-2's native Rust runtime and provides a runnable SDK reproduction, but names no source files or tests. Start by locating the runtime's context token accounting and compaction request path, then run the supplied reproduction and compare its counts with the Inkling tokenizer. Done means estimates and request admission account for the custom tokenizer and compaction requests recover from context-limit errors.

索引モデルが issue の本文から書いたものです。

説明

area:context-memory area:models
Problem

Copilot's context estimate can substantially undercount input for an OpenAI-compatible BYOK model with a different tokenizer. Requests, including compaction requests, can exceed the provider's context limit while the displayed context still has free space.

Reproduced with Copilot CLI 1.0.118-2, native Rust runtime, Linux x64. The example is Inkling 2 Mini, served through an OpenAI-compatible chat-completions provider. The bundled SDK is used only as an isolated diagnostic harness. Other custom models require independent testing.

Minimal reproduction

Run the complete script in the expandable section below with the SDK and runtime bundled with CLI 1.0.118-2. It replaces the system prompt with 100 repetitions of a fixed sentence, disables tools and instruction discovery, and returns a synthetic response locally. No API key or model generation is needed.

Measurement for the same repeated text Tokens
Copilot contextInfo.systemTokens, including message overhead 2204
OpenAI o200k_base, text only 2200
Published Inkling tokenizer, text only 2600

The observed counts are consistent with OpenAI tokenization being used for this custom model. This is an inference from runtime measurements, not a source-confirmed tokenizer-dispatch implementation.

Impact

The discrepancy also occurs on complete rendered requests:

Synthetic request Copilot estimate Backend input
No tools 2240 2653
20 tool definitions 4867 6320

Schemas occur once. Independent checks against the published Inkling tokenizer match the backend's token IDs, distinguishing this from omitted/duplicated schemas or a major server tokenizer configuration error.

A separate controlled experiment shows that reported usage helps trigger blocking compaction, but the resulting compaction request can still overflow. It measured 10,179 input tokens against a simulated 10,000-token ceiling, then failed after one attempt with inputShrunk: false. Details and the simulation boundary are below.

Expected behavior

Use provider-appropriate tokenization or conservative/provider-calibrated accounting consistently for context display and request admission. Bound the complete compaction request, including its additional instructions, schemas, and output headroom; shrink or chunk its input on context rejection.

Complete runnable counting reproduction and reference tokenizer check

Save the following as repro.mjs. Use the SDK entry point and standalone runtime executable from the same CLI 1.0.118-2 installation:

COPILOT_SDK_ENTRY=/absolute/path/to/copilot-sdk/index.js \
COPILOT_RUNTIME_PATH=/absolute/path/to/prebuilds/linux-x64/copilot-runtime \
node repro.mjs

If using a separately installed compatible SDK, omit COPILOT_SDK_ENTRY to import @microsoft/copilot-sdk. The tested version is the SDK bundled with CLI 1.0.118-2; compatibility with other SDK versions is not assumed.

import { mkdtemp } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';

const { CopilotClient, RuntimeConnection, CopilotRequestHandler } =
  await import(process.env.COPILOT_SDK_ENTRY || '@microsoft/copilot-sdk');
const directory = await mkdtemp(join(tmpdir(), 'copilot-token-repro-'));
const sample = 'The quick brown fox jumps over the lazy dog. function foo(x) { return x * 2; }\n';

// Answer locally: no upstream HTTP call, API key, or model generation.
class FakeProvider extends CopilotRequestHandler {
  async sendRequest(request) {
    const data = await request.json();
    if (!data.stream) {
      return Response.json({
        id: 'local-repro', object: 'chat.completion', created: 1,
        model: data.model,
        choices: [{ index: 0, message: { role: 'assistant', content: 'OK' },
          finish_reason: 'stop' }],
      });
    }
    const chunk = {
      id: 'local-repro', object: 'chat.completion.chunk', created: 1,
      model: data.model,
      choices: [{ index: 0, delta: { role: 'assistant', content: 'OK' },
        finish_reason: null }],
    };
    const end = { ...chunk,
      choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] };
    return new Response(
      `data: ${JSON.stringify(chunk)}\n\ndata: ${JSON.stringify(end)}\n\ndata: [DONE]\n\n`,
      { headers: { 'content-type': 'text/event-stream' } },
    );
  }
}

const client = new CopilotClient({
  mode: 'empty',
  github: { useLoggedInUser: false },
  runtime: RuntimeConnection.forSpawnedStdio({
    baseDirectory: directory,
    ...(process.env.COPILOT_RUNTIME_PATH
      ? { path: process.env.COPILOT_RUNTIME_PATH } : {}),
  }),
  models: { requestHandler: new FakeProvider() },
});
try {
  const session = await client.createSession({
    model: 'Example/inkling-2-mini',
    inference: {
      capi: { enabled: false },
      providers: [{ name: 'Example', type: 'openai',
        wireApi: 'completions', baseUrl: 'http://127.0.0.1:1/v1' }],
      models: [{ provider: 'Example', id: 'inkling-2-mini',
        maxPromptTokens: 10000, maxOutputTokens: 512,
        maxContextWindowTokens: 11000 }],
    },
    tools: { availableTools: [] },
    instructions: { skipCustomInstructions: true },
    systemMessage: { mode: 'replace', content: sample.repeat(100) },
    workingDirectory: directory,
  });
  await session.sendAndWait({ prompt: 'hello' }, 30000);
  const { contextInfo } = await session.rpc.metadata.contextInfo({
    promptTokenLimit: 0, outputTokenLimit: 0,
  });
  console.log('Copilot systemTokens:', contextInfo.systemTokens);
  console.log('Reference Inkling text tokens: 2600 (before message overhead)');
} finally {
  await client.stop();
}

Observed output on the affected runtime:

Copilot systemTokens: 2204
Reference Inkling text tokens: 2600 (before message overhead)

Verify the reference count independently with pip install tokenizers tiktoken, then:

from urllib.request import urlretrieve
from tokenizers import Tokenizer
import tiktoken

revision = "c9d028302cd0f035fdf8e7e91f089a4ce94d2195"
urlretrieve(
    f"https://huggingface.co/thinkingmachines/Inkling-2-Mini/resolve/{revision}/tokenizer.json",
    "inkling-tokenizer.json",
)
reference = Tokenizer.from_file("inkling-tokenizer.json")
openai = tiktoken.get_encoding("o200k_base")
text = "The quick brown fox jumps over the lazy dog. function foo(x) { return x * 2; }\n"
print(len(openai.encode(text)))  # 22
print(len(reference.encode(text, add_special_tokens=False).ids))  # 26

The script uses a fresh temporary Copilot directory and a synthetic provider response. Its token totals come from the runtime's context-info API, not fabricated provider usage metadata.

Additional tokenizer fingerprint and backend validation

A distinguishing fingerprint, repeated 50 times:

fingerprint = "お誕生日おめでとうございます。你好,世界! antidisestablishmentarianism 😀🚀\n"

produces 1,200 tokens with o200k_base, 1,500 with cl100k_base, and 1,204 system tokens in Copilot's Inkling context info, including overhead.

Recounting the same session with model identifiers inkling-2-mini, gpt-4o, and gpt-5 gives identical counts; a Claude identifier gives different counts. The behavior is consistent with the custom model being counted using the OpenAI tokenizer. The private native tokenizer-dispatch implementation has not been source-audited.

The published Inkling tokenizer shares the o200k pre-tokenization regex but has a different vocabulary/merge-rank table. Matching the regex or exposing an OpenAI-compatible API does not make token counts compatible.

Additional public-text checks used llama.cpp b12627-225a5345b, /apply-template, and /tokenize:

Input OpenAI o200k Published Inkling llama.cpp
Model-card prose 16240 21331 21331
TypeScript SDK declarations 12769 15383 15383
Full synthetic tools request 4868 6320 6320

For these checks the published reference and backend token IDs were identical. One separate compaction-text sample differed by two backend tokens, which does not explain the systematic undercount.

Controlled compaction-overflow experiment and diagnostics

The standalone script above reproduces the counting mismatch. The following is supporting evidence from a separate captured-request/response-adapter experiment, not an additional claim about what that script executes.

Reported usage is not entirely ignored. Internal compaction predictions can use provider-reported input plus locally estimated growth, while contextInfo and session.usage_info continue exposing lower local totals.

A controlled harness used the following test limits, chosen to reproduce the problem with small requests:

{
  "maxPromptTokens": 9000,
  "maxOutputTokens": 512,
  "maxContextWindowTokens": 10000
}

A response adapter simulated the 10,000-token backend ceiling. Each captured request was independently rendered/tokenized by the actual Inkling backend before the adapter returned its measured usage or a context-limit error. No model inference was performed.

  1. The first ordinary request has a local count of 7067 and measured input of 8920. The adapter returns success with prompt_tokens: 8920.
  2. Send a small continue message.
  3. The runtime predicts 8952 = 8920 + 32, correctly triggering blocking compaction above its 95% threshold.
  4. The resulting compaction request measures 10179 tokens, exceeding the simulated 10,000-token ceiling.
  5. Compaction retains all 20 schemas, despite tool_choice: "none". Removing only schemas reduces the same request to 6512 tokens.
  6. The runtime records failureReason: "context_limit", attemptCount: 1, and inputShrunk: false, then proceeds with the ordinary request.
  7. That ordinary continuation measures 8959, succeeds, and the context display reports 7100. Compaction has not reduced history.

Relevant compaction diagnostics:

{
  "success": false,
  "failureReason": "context_limit",
  "summarizerProgress": {
    "attemptCount": 1,
    "inputTokensEstimate": 5536,
    "inputShrunk": false
  },
  "attemptMetrics": {
    "triggerThreshold": 0.95,
    "maxOutputTokens": 512,
    "failedRequestCount": 1,
    "failedRequestInputTokensEstimate": 5536
  }
}

The inputTokensEstimate field appears message-oriented; it is not being treated here as a documented complete-request count. The full rendered input was independently measured at 10,179.

This demonstrates a recovery failure before the ordinary conversation itself becomes too large. If ordinary requests subsequently exceed the backend ceiling as well, the failed compaction path cannot recover the session.

Related: microsoft/copilot-sdk#975, microsoft/copilot-sdk#1072, microsoft/copilot-sdk#2355. Originally filed as microsoft/copilot-sdk#2939; this CLI issue supersedes it.

主要言語
Python
スター
11.5k
フォーク
2k
平均マージ
6時間 34分
マージ済み PR(30日)
3

環境構築

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

github/copilot-cli のほかの issue

github/copilot-cli の issue をすべて見る

似ている issue

Python の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。