From 5753a41c08cd20f6ae4b2ed91212a9a307ff2f12 Mon Sep 17 00:00:00 2001 From: Claude Lin & Lay Date: Sat, 15 Aug 2026 01:19:32 +0900 Subject: [PATCH] fix(pipeline): bound embed batches by UTF-8 byte count, not character count [pipeline, poller, docs, tests] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `planEmbeddingBatches` の予算軸を UTF-16 code unit から UTF-8 バイト数へ移した。 #242 が置いた前提「1 token は入力の 1 文字以上に対応する」は byte_fallback で 破れる。語彙に無い文字は UTF-8 バイト列へ分解されるため、3 バイトの日本語 1 文字が 最大 3 token になる。実測は 2026-08-15 00:30 JST の cron で、文字数で高々 60000 と 課金した batch に 68736 token が返った(1 文字あたり 1.146 token)。 バイト数はその分解より下にある。byte_fallback が tokenizer の作れる最も細かい 分解であり、1 token は入力の 1 バイト以上を必ず消費するので、batch の合計 UTF-8 バイト数を天井(60000)以下に保てば合計 token 数も天井以下になる。#241 が 求めた「校正しない、構成上正しい」性質はそのままに、軸を 1 つ下げただけである。 変更点: - `MAX_EMBEDDING_BATCH_CHARS` -> `MAX_EMBEDDING_BATCH_BYTES`、課金は `utf8ByteLength(input)`。`utf8ByteLength` は code unit から数えるので入力の 複製を確保しない。孤立サロゲートは `TextEncoder` が置く U+FFFD と同じ 3 バイト として数える(truncate が code unit 境界で切るため実際に発生しうる) - `SPECIAL_TOKENS_PER_INPUT` (2) -> `TOKEN_OVERHEAD_PER_INPUT` (3)。sentinel 2 個 (`` … ``)に加え、SentencePiece の語境界マーカーが先頭 piece に併合され ない場合、入力バイトを消費しない token として 1 個現れる。極小 input が多数並ぶ batch ではこれが積み上がるため、input ごとに課金する(#242 の判断を維持) - #240 の file 予算との整合: 1 batch の最小 file 数が 7 から 2 へ下がる (8000 文字 = 最大 24000 バイト、予算 60000)。按分は 2/2 = 1、固定 2 と合わせて worst case はちょうど 3 で、`DIFF_SUBREQUESTS_PER_FILE = 3` は変更不要。ただし 余裕は無くなったので、その不変条件を `poller.test.ts` の実行可能な assertion に した - 回帰テスト: 16 file の日本語 commit(文字数予算なら 1 call、実測で天井超過)が 分割されること、`utf8ByteLength` が `TextEncoder` と全幅で一致すること 残る前提は「NFKC 正規化が入力をバイト数で膨らませない」ことのみで、互換分解を持つ 文字(アラビア語の合字、CJK 組文字)が入力の大半を占める場合にのみ問題になる。 退けた 2 つの前提が通常の diff テキストで破れたのとは性質が異なるため、 コードと要件記述の両方に前提として明記した。 #244 --- docs/0-requirements.ja.md | 4 +- docs/0-requirements.md | 4 +- src/pipeline/embed-diff.test.ts | 52 ++++++++++-- src/pipeline/embed-diff.ts | 14 ++-- src/pipeline/embedding.test.ts | 142 +++++++++++++++++++++++--------- src/pipeline/embedding.ts | 140 ++++++++++++++++++++++--------- src/poller.test.ts | 23 ++++++ src/poller.ts | 18 ++-- 8 files changed, 296 insertions(+), 101 deletions(-) diff --git a/docs/0-requirements.ja.md b/docs/0-requirements.ja.md index 7014d5c..1b8e06c 100644 --- a/docs/0-requirements.ja.md +++ b/docs/0-requirements.ja.md @@ -190,7 +190,7 @@ commit diff poller は 2-phase 構成: 1 repo 1 run あたりの上限は、各 phase が 2 軸で持つ: commit 数 5 件と、file 数 `diffFileBudgetPerPhase`。`processAndUpsertCommitDiff` の upsert は `(repo, commit_sha, file_path)` で idempotent なので、webhook / 両 phase 間で overlap しても副作用はない。 -commit 数は phase の消費量を縛れない。1 file の index は worst case で 3 subrequest(D1 FTS mirror 書き込み、store row、および embed batch の按分——1 batch は 2 subrequest を使い、`MAX_EMBEDDING_INPUT_CHARS` が 1 input を 8000 文字に切る一方 batch 予算は 30000 token なので、1 batch は最低 3 file を載せる)であり、1 commit は最大 300 file を運ぶため、5 commits のコストは 2 桁の幅を持つ。実測された帰結: `POLL_REPOS` の末尾 repo にある 44 file の commit で、embed batch 3 本すべてが `Too many subrequests by single Worker invocation` で拒否された。同じ loop の手前にある repo は正常に index されていた。そして後述の不変条件がその commit で watermark を止める——token 軸が起こしたのとまったく同じ、毎 cron 決定論的に再現する停止が、file 軸で起きた(issue #238)。 +commit 数は phase の消費量を縛れない。1 file の index は worst case で 3 subrequest(D1 FTS mirror 書き込み、store row、および embed batch の按分——1 batch は 2 subrequest を使い、`MAX_EMBEDDING_INPUT_CHARS` が 1 input を 8000 文字=最大 24000 UTF-8 バイトに切る一方 batch 予算は 60000 バイトなので、1 batch は最低 2 file を載せる)であり、1 commit は最大 300 file を運ぶため、5 commits のコストは 2 桁の幅を持つ。実測された帰結: `POLL_REPOS` の末尾 repo にある 44 file の commit で、embed batch 3 本すべてが `Too many subrequests by single Worker invocation` で拒否された。同じ loop の手前にある repo は正常に index されていた。そして後述の不変条件がその commit で watermark を止める——token 軸が起こしたのとまったく同じ、毎 cron 決定論的に再現する停止が、file 軸で起きた(issue #238)。 そこで diff surface は invocation 予算のうち自分の取り分を明示する: `DIFF_SUBREQUEST_BUDGET_PER_RUN` = Cloudflare が許す 1000 のうち 900。diffs は専用 cron を持つので、この天井を docs / wiki / issue / release と共有はしていない。しかし `POLL_REPOS` の全 repo と両 phase では共有しており、上記の失敗を生んだのはそちらの共有である。`diffFileBudgetPerPhase` は宣言した取り分を `repoCount × 2` で割り、残りを file 数に換算する。literal を固定せず repo list から導出するのは意図的である: `POLL_REPOS` は通常の config commit で増える(issue #233 が 6 番目の repo を追加した)ため、その日の list に合わせた literal は次の追加で天井を超え、しかもその超過は原因となった変更ではなく loop が最後に到達した repo の失敗として現れる。repo list が長く予算を下回るところまで割った場合は 5 file の下限が効く——超過は次の cron が再試行するが、予算 0 は全 diff watermark を恒久的に止める。それはいま取り除こうとしている失敗そのものである。 @@ -255,7 +255,7 @@ Responsibilities: - metadata のみの経路(body は変わらず state / labels / milestone / assignees が変わった場合)では、mirror 書き込みの失敗を best-effort 扱いに**しない**。差分検出の基準を進めずに保持し、次の poll / webhook 配信で再試行させる。基準は IssueStore の record そのものなので、失敗した mirror を追い越して基準を進めると取り残しが恒久化する — state だけの変更は、embed 経路が待っている body 変更を二度と連れてこない(issue #209) - この経路の dense / sparse mirror は互いに独立して書く。vector が欠けている行(issue #210)でも sparse 側の state は更新される - commit diff は 1 commit 分の file リストを batch embed(Workers AI の `text: string[]` 対応を利用)し、batch ごとに 1 回の Vectorize upsert で N vector を書き込む -- batch の切れ目は file 件数でも token 数の推定でもなく、文字数予算(`MAX_EMBEDDING_BATCH_CHARS`)で決める。天井は bge-m3 の documented な per-input 上限 8192 token ではなく、1 call の input 全体を合算した endpoint 側の上限である。batch は合算され、拒否応答はその合計値を名指しする(`3030: Max context reached 85920 tokens but model supports only 60000`)。この値は非公開なので `WORKERS_AI_BATCH_CONTEXT_LIMIT` としてそのエラーから記録し、文字数予算はその天井そのものに置く。文字数が正しい単位である理由は、それが token 数の近似ではなく**上界**だからである。BPE / SentencePiece のいずれでも 1 token は入力の 1 文字以上に対応するので、各 input にその文字数と special token 2 個(`` … ``)を課金すれば、batch が天井の内側に収まることが無条件に成立する — 校正が要らず、payload の言語や記号密度にも依存しない。special token を 1 batch 固定の引当てではなく input ごとに課金するのは、batch の input 件数に上限が無く、極小 input が多数並ぶ場合に固定引当てでは足りなくなるためである。file 件数ではこれを表現できず、直前に置いていた推定でも表現できていなかった。推定は ASCII を 3 文字/token として読むが、bge-m3 が diff patch を割る密度は約 1.4 文字/token である — `+` / `-` 接頭、インデント、記号、短い識別子がいずれも細かく分割される — ため、肝心の surface で約 2.1x 楽観に振れ、実測 60678 / 64413 token の batch を「30000 token 予算に収まる」と判定して通していた(issue #241)。天井を超えた commit は chunk 全体を失敗させ、vector が載らなかった commit は diff watermark が留まる対象(issue #178)なので、その commit を飛ばすのではなく surface がそこで恒久的に停止する。しかも毎 cron 同じ commit で同じ結果になる決定論的な失敗で、同じログに同居する一過性の subrequest 超過とはそこで性質が分かれる(issue #236)。天井の下に margin は取らない — 構成上成立する上界に margin が買えるものは残っておらず、batch が 1 つ増えるごとに subrequest を 2 つ消費し、この worker は既に invocation 予算を超過しているためである。単独で予算を超える input はそのまま単独で送る — さらに削るのは truncate 軸(`MAX_EMBEDDING_INPUT_CHARS`)の仕事であり、落とせばその file が索引から消えるため。その truncate が 1 input を 8000 文字に抑えるので、payload の中身によらず 1 batch は最低 7 file を保持する。これが poller の per-file subrequest 見積りが立っている床である +- batch の切れ目は file 件数でも token 数の推定でも文字数でもなく、UTF-8 バイト数予算(`MAX_EMBEDDING_BATCH_BYTES`)で決める。天井は bge-m3 の documented な per-input 上限 8192 token ではなく、1 call の input 全体を合算した endpoint 側の上限である。batch は合算され、拒否応答はその合計値を名指しする(`3030: Max context reached 68736 tokens but model supports only 60000`)。この値は非公開なので `WORKERS_AI_BATCH_CONTEXT_LIMIT` としてそのエラーから記録し、バイト数予算はその天井そのものに置く。バイト数が正しい単位である理由は、それが token 数の近似ではなく**上界**だからである。tokenizer が作れる最も細かい分解が byte_fallback — 語彙に無い文字はその UTF-8 バイト列へ分解される — であり、それ以下には割れないので、1 token は入力の 1 バイト以上を必ず消費する。したがって各 input にその UTF-8 バイト数と `TOKEN_OVERHEAD_PER_INPUT` を課金すれば、batch は天井の内側に収まる。この overhead が 3 なのは、model が各 input を挟む sentinel 2 個(`` … ``)に加え、SentencePiece の語境界マーカーが先頭 piece に併合されない場合に単独の token として現れ、入力バイトを 1 つも消費しないためである。1 batch 固定の引当てではなく input ごとに課金するのは、batch の input 件数に上限が無く、極小 input が多数並ぶ場合(そのそれぞれが自分の 3 を持つ)に固定引当てでは足りなくなるためである。file 件数ではこれを表現できず、これ以前の 2 つの予算はいずれも実測に破られた前提の上に立っていた。1 つ目は token 数の推定で、ASCII を 3 文字/token として読むが bge-m3 が diff patch を割る密度は約 1.4 文字/token である — `+` / `-` 接頭、インデント、記号、短い識別子がいずれも細かく分割される — ため約 2.1x 楽観に振れ、実測 60678 / 64413 token の batch を「30000 token 予算に収まる」と判定して通していた(issue #241)。2 つ目は文字数で、「1 token は 1 文字以上に対応する」という前提に立っていたが、byte_fallback がまさにその前提を破る経路であり、3 バイトの日本語 1 文字が 3 token になりうる。実測では、文字数で高々 60000 と課金した batch に 68736 token が返った — 1 文字あたり 1.146 token である(issue #244)。バイト数はその両方の下にある。これより細かい分解が無いので、この軸が過小評価する payload は存在しない。残る前提は「tokenizer の NFKC 正規化が入力をバイト数で膨らませない」ことだけであり、これは互換分解を持つ文字(アラビア語の合字、CJK の組文字)を除いて成立する — 退けた 2 つの前提が通常の diff テキストで破れたのとは性質が異なり、こちらは入力の大半がその稀なブロックで占められている必要がある。天井を超えた commit は chunk 全体を失敗させ、vector が載らなかった commit は diff watermark が留まる対象(issue #178)なので、その commit を飛ばすのではなく surface がそこで恒久的に停止する。しかも毎 cron 同じ commit で同じ結果になる決定論的な失敗で、同じログに同居する一過性の subrequest 超過とはそこで性質が分かれる(issue #236)。天井の下に margin は取らない — 構成上成立する上界に margin が買えるものは残っておらず、batch が 1 つ増えるごとに subrequest を 2 つ消費し、この worker は既に invocation 予算を超過しているためである。単独で予算を超える input はそのまま単独で送る — さらに削るのは truncate 軸(`MAX_EMBEDDING_INPUT_CHARS`)の仕事であり、落とせばその file が索引から消えるため。その truncate が 1 input を 8000 文字=最大 24000 バイトに抑えるので、payload の中身によらず 1 batch は最低 2 file を保持する。これが poller の per-file subrequest 見積りが立っている床である。この床は文字数予算のときの 1/3 であり、日本語主体の commit はこれまで 1 call だったところが約 3 分割になる。増える subrequest は上界の代金であり、上の file 予算が 1 file あたりちょうど 3 subrequest としてすでに賄っている **索引欠落の修復.** watermark の修正は漏れを止めるだけで、既に空いた穴は埋まらない — 取り残された項目が再 fetch されるのは `updated_at` が動いたときだけで、閉じた履歴はもう動かない。`POST /admin/backfill-issue-index?repo=owner/repo`(installation guide 参照)が欠落そのものを走査する。repository の issue 番号空間は密かつ有界なので、`search_docs` に issue / PR 行が無い番号がそのまま欠落集合であり、数値 cursor が「どこまで走査したか」を厳密に表せる。同じ集合を時刻 cursor で辿ると、欠陥が突いた順序をそのまま持ち込むことになる。GitHub 側に既に無い番号(削除・transfer 済み)は 404 を返すので、retry せず計上のみ。取り込みは body-hash 判定を強制的に飛ばす: 候補はいずれも retrieval surface が欠けていると分かっている項目であり、hash が一致していると(embed 成功後に FTS5 mirror が失敗した行がこの状態になる)そのまま恒久的に skip されてしまうため。state 修復と違いこちらは embed を伴い、1 候補ごとに取り込み fan-out の全額がかかるので、呼び出し側が batch を跨いで sweep を進める。`dry_run=true` は予算を使わずに欠落量だけを測る。sweep は poller の watermark と同じ不変条件に従う: **取り込みそこねた最初の候補を cursor が追い越さない。** これにより 1 call の上限を大きく取りすぎたときの代償は 1 回分の無駄な呼び出しであって取りこぼしではなく、結果が「上限値が subrequest 予算をどれだけ正確に写しているか」に依存しなくなる(issue #216)。GitHub 側に既に無い番号は例外 — 誰が何回試しても取り込めないので、そこで止めると retry の境界にならず sweep が停止する。トレードオフは poller と同じで、恒久的に失敗する候補があると sweep は止まる。ただしそれは応答に現れる(`nextCursor` が渡した `cursor` と同じ値で返る)し、この endpoint は cron ではなく人間 / AI が駆動するので、詰まった番号を手動の `cursor` 指定で越えられる。 diff --git a/docs/0-requirements.md b/docs/0-requirements.md index 760d864..8b8d099 100644 --- a/docs/0-requirements.md +++ b/docs/0-requirements.md @@ -195,7 +195,7 @@ The commit-diff poller runs in two phases: Each phase is bounded on two axes per repo per run: at most 5 commits, and at most `diffFileBudgetPerPhase` files. Upserts through `processAndUpsertCommitDiff` are idempotent on `(repo, commit_sha, file_path)`, so overlap between webhook and either phase is safe. -A commit count does not bound what a phase spends. Each indexed file costs 3 subrequests worst case — the D1 FTS mirror write, the store row, and the amortised share of its embed batch (a batch spends 2 and holds at least 3 files, since `MAX_EMBEDDING_INPUT_CHARS` caps an input at 8000 characters against a 30000-token batch budget) — and one commit carries up to 300 files, so 5 commits span two orders of magnitude of cost. The measured consequence: a 44-file commit in the last repo of `POLL_REPOS` had all three of its embed batches rejected with `Too many subrequests by single Worker invocation` while the repos ahead of it in the loop indexed normally, and the invariant below then held its watermark on that commit — the same deterministic, cron-after-cron stall the token axis produced, on the file axis (issue #238). +A commit count does not bound what a phase spends. Each indexed file costs 3 subrequests worst case — the D1 FTS mirror write, the store row, and the amortised share of its embed batch (a batch spends 2 and holds at least 2 files, since `MAX_EMBEDDING_INPUT_CHARS` caps an input at 8000 characters, which is at most 24000 UTF-8 bytes, against the 60000-byte batch budget) — and one commit carries up to 300 files, so 5 commits span two orders of magnitude of cost. The measured consequence: a 44-file commit in the last repo of `POLL_REPOS` had all three of its embed batches rejected with `Too many subrequests by single Worker invocation` while the repos ahead of it in the loop indexed normally, and the invariant below then held its watermark on that commit — the same deterministic, cron-after-cron stall the token axis produced, on the file axis (issue #238). The diff surface therefore declares its share of the invocation ceiling explicitly: `DIFF_SUBREQUEST_BUDGET_PER_RUN` = 900 of the 1000 Cloudflare allows. The diffs cron is the surface's own invocation, so that ceiling is not shared with docs / wiki / issues / releases — but it *is* shared across every repo in `POLL_REPOS` and both phases, which is the sharing that produced the failure above. `diffFileBudgetPerPhase` divides the declared share by `repoCount × 2` and converts the remainder to files. Deriving it from the repo list rather than fixing a literal is deliberate: `POLL_REPOS` grows by ordinary config commits (issue #233 appended the sixth repo), and a literal sized against the list of the day overruns the ceiling on the next append, surfacing as failures on whichever repo the loop reaches last rather than on the change that caused them. A floor of 5 files holds under a repo list long enough to divide the budget below it — an overrun is retried by the next cron, whereas a budget of zero stalls every diff watermark permanently, which is the failure being removed. @@ -260,7 +260,7 @@ Responsibilities: - on the metadata-only path (state / labels / milestone / assignees changed, body did not) a failed mirror write is **not** best-effort: the diff baseline is held so the next poll or webhook delivery retries. The baseline is the IssueStore record itself, so advancing it past a failed mirror makes the miss permanent — a state-only change never brings the body change the embed path waits for (issue #209) - the dense and sparse mirrors on that path are written independently: a row with no vector (issue #210) still gets its sparse state updated - for commit diffs: batch-embed a commit's file list through Workers AI (`text: string[]`) and upsert each batch's N vectors in one `VECTORIZE.upsert` call -- batches are cut on a character budget (`MAX_EMBEDDING_BATCH_CHARS`), not on a file count and not on an estimate of the token count. The ceiling is the endpoint's aggregate context across a call's inputs, not bge-m3's documented 8192-token per-input maximum: the batch is summed, and the rejection names the sum (`3030: Max context reached 85920 tokens but model supports only 60000`). It is unpublished, so `WORKERS_AI_BATCH_CONTEXT_LIMIT` records it from that error, and the character budget is that ceiling. What makes characters the right unit is that they *dominate* the token count rather than approximating it: every token of a BPE or SentencePiece vocabulary spans at least one character of the input, so charging each input its length plus its two special tokens (`` … ``) puts the batch inside the ceiling unconditionally — no calibration, and no dependence on the payload's language or punctuation density. The special tokens are charged per input rather than as one flat reserve because nothing bounds a batch's input count, and many tiny inputs is where a flat reserve comes up short. A file count cannot express any of this, and neither could the estimate that preceded it: it read ASCII at 3 characters per token, while bge-m3 splits a diff patch nearer 1.4 — `+`/`-` prefixes, indentation, punctuation and short identifiers all tokenize small — so it ran about 2.1x optimistic on the one surface that mattered and passed 60678- and 64413-token batches as fitting a 30000-token budget (issue #241). A commit that goes over fails its whole chunk, and a commit whose vectors never landed is one the diff watermark holds on (issue #178), so the surface stalls there permanently instead of passing it by — deterministically, on the same commit every cron tick, which is what separates it from the transient subrequest overruns sharing the log (issue #236). No margin is held under the ceiling: a bound that holds by construction has nothing left for a margin to buy, and every extra batch spends two subrequests on an invocation budget this worker already overruns. An input whose own charge exceeds the budget is sent alone — cutting it down further is the truncation axis (`MAX_EMBEDDING_INPUT_CHARS`), and dropping it would lose the file from the index. That same truncation caps one input at 8000 characters, so a batch holds at least 7 files whatever the payload is made of, which is the floor the poller's per-file subrequest estimate rests on +- batches are cut on a UTF-8 byte budget (`MAX_EMBEDDING_BATCH_BYTES`), not on a file count, not on an estimated token count, and not on a character count. The ceiling is the endpoint's aggregate context across a call's inputs, not bge-m3's documented 8192-token per-input maximum: the batch is summed, and the rejection names the sum (`3030: Max context reached 68736 tokens but model supports only 60000`). It is unpublished, so `WORKERS_AI_BATCH_CONTEXT_LIMIT` records it from that error, and the byte budget is that ceiling. What makes bytes the right unit is that they *dominate* the token count rather than approximating it: byte fallback is the finest split the tokenizer can make — a character the vocabulary lacks is decomposed into the bytes of its UTF-8 encoding — so no token spans less than one byte of the input, and charging each input its byte length plus `TOKEN_OVERHEAD_PER_INPUT` puts the batch inside the ceiling. That overhead is 3: the two sentinels the model wraps around each input (`` … ``), plus the SentencePiece word-boundary marker, which is emitted as a token of its own where it does not merge into the first piece and so consumes no byte. It is charged per input rather than as one flat reserve because nothing bounds a batch's input count, and many tiny inputs — each carrying its own three — is where a flat reserve comes up short. A file count cannot express any of this, and the two budgets before this one each rested on a premise that measurement broke. The first estimated tokens, reading ASCII at 3 characters per token while bge-m3 splits a diff patch nearer 1.4 — `+`/`-` prefixes, indentation, punctuation and short identifiers all tokenize small — so it ran about 2.1x optimistic and passed 60678- and 64413-token batches as fitting a 30000-token budget (issue #241). The second charged characters, on the premise that a token spans at least one character; byte fallback is exactly the case that breaks it, since one 3-byte Japanese character can cost 3 tokens, and production answered a batch charged at most 60000 characters with 68736 tokens — 1.146 tokens per character (issue #244). Bytes sit below both: nothing splits finer, so no payload can be the one this underestimates. What is left assumed is that the tokenizer's NFKC normalization does not expand the input in bytes, which holds except for compatibility characters that decompose into several (Arabic ligatures, CJK square abbreviations) — a different class of exposure from the two retired premises, which broke on ordinary diff text, where this one needs an input made predominantly of one rare block. A commit that goes over fails its whole chunk, and a commit whose vectors never landed is one the diff watermark holds on (issue #178), so the surface stalls there permanently instead of passing it by — deterministically, on the same commit every cron tick, which is what separates it from the transient subrequest overruns sharing the log (issue #236). No margin is held under the ceiling: a bound that holds by construction has nothing left for a margin to buy, and every extra batch spends two subrequests on an invocation budget this worker already overruns. An input whose own charge exceeds the budget is sent alone — cutting it down further is the truncation axis (`MAX_EMBEDDING_INPUT_CHARS`), and dropping it would lose the file from the index. That same truncation caps one input at 8000 characters, which is at most 24000 bytes, so a batch holds at least 2 files whatever the payload is made of, which is the floor the poller's per-file subrequest estimate rests on. That floor is a third of what the character budget gave, so a Japanese commit now splits about three ways where it used to be one call; the extra subrequests are what the bound costs, and the file budget above already covers them at exactly 3 per file **Missing-entry repair.** The watermark fix stops the leak but does not fill the hole: a stranded item is only re-fetched when its `updated_at` moves, and closed history never moves again. `POST /admin/backfill-issue-index?repo=owner/repo` (see the installation guide) walks the gap directly — the repository's issue-number space is dense and bounded, so the numbers with no `search_docs` issue / PR row are exactly the missing set, and a numeric cursor states how far the sweep has reached. A timestamp cursor over the same set would reintroduce the ordering the defect exploited. Numbers GitHub no longer has (deleted or transferred) answer 404 and are counted rather than retried. The ingest is forced past the body-hash check: every candidate is known to be missing a retrieval surface, and a matching hash — which an embed whose FTS5 mirror failed leaves behind — would otherwise skip it permanently. Unlike the state repair this one embeds, so every candidate carries the full ingest fan-out and the caller drives the sweep one batch at a time; `dry_run=true` measures the gap without spending it. The sweep obeys the same invariant as the poller's watermark: **the cursor never advances past the first candidate a call failed to ingest**, so a per-call limit set too high costs a wasted call rather than a missed item, and the result does not depend on how accurately that limit models the subrequest budget (issue #216). A number GitHub no longer has is exempt — nothing will ever ingest it, so holding there would stall the sweep instead of bounding a retry. The tradeoff is the poller's: a candidate that fails on every attempt stops the sweep. Here that is visible rather than silent (`nextCursor` comes back equal to the `cursor` passed in), and because a human or an AI drives this endpoint rather than cron, stepping over the blocking number is a matter of passing the next `cursor` by hand. diff --git a/src/pipeline/embed-diff.test.ts b/src/pipeline/embed-diff.test.ts index 411be42..b7a5cd9 100644 --- a/src/pipeline/embed-diff.test.ts +++ b/src/pipeline/embed-diff.test.ts @@ -2,9 +2,10 @@ import { describe, it, expect, vi } from "vitest"; import type { Env } from "../types.js"; import { processAndUpsertCommitDiff, type GitHubCommitDetail } from "./embed-diff.js"; import { - MAX_EMBEDDING_BATCH_CHARS, - SPECIAL_TOKENS_PER_INPUT, + MAX_EMBEDDING_BATCH_BYTES, + TOKEN_OVERHEAD_PER_INPUT, WORKERS_AI_BATCH_CONTEXT_LIMIT, + utf8ByteLength, } from "./embedding.js"; import { diffVectorId } from "./vector-id.js"; @@ -79,10 +80,19 @@ function mkDiffPatch(chars: number): string { /** What the planner charges one Workers AI call. Upper-bounds its token count. */ function callCharge(texts: string[]): number { - return texts.reduce((sum, text) => sum + text.length + SPECIAL_TOKENS_PER_INPUT, 0); + return texts.reduce( + (sum, text) => sum + utf8ByteLength(text) + TOKEN_OVERHEAD_PER_INPUT, + 0, + ); } -describe("embed-diff: the batch axis is the character budget, not the file count", () => { +/** What the retired character budget charged the same call (#242). Kept in the + * tests only, to hold the regression fixtures inside the shape it passed. */ +function retiredCharCharge(texts: string[]): number { + return texts.reduce((sum, text) => sum + text.length + 2, 0); +} + +describe("embed-diff: the batch axis is the UTF-8 byte budget, not the file count", () => { it("still sends an ordinary commit as one call", async () => { // 30 files well past the retired count cap of 20, each a small patch. const { env, aiCalls } = mkEnv(); @@ -120,7 +130,7 @@ describe("embed-diff: the batch axis is the character budget, not the file count // Every call carrying more than one input stays inside the budget. for (const call of aiCalls) { if (call.length > 1) { - expect(callCharge(call)).toBeLessThanOrEqual(MAX_EMBEDDING_BATCH_CHARS); + expect(callCharge(call)).toBeLessThanOrEqual(MAX_EMBEDDING_BATCH_BYTES); } } @@ -156,7 +166,7 @@ describe("embed-diff: the batch axis is the character budget, not the file count expect(aiCalls.length).toBeGreaterThan(1); for (const call of aiCalls) { - expect(callCharge(call)).toBeLessThanOrEqual(MAX_EMBEDDING_BATCH_CHARS); + expect(callCharge(call)).toBeLessThanOrEqual(MAX_EMBEDDING_BATCH_BYTES); } // Splitting is only the fix if every file still lands. @@ -165,6 +175,36 @@ describe("embed-diff: the batch axis is the character budget, not the file count expect(new Set(upsertedIds.flat()).size).toBe(18); }); + it("splits the 16-file Japanese commit that a character budget let through", async () => { + // The payload that kept failing after #242 shipped: 16 files of Japanese-heavy + // patch, charged at most 60000 characters and sent as one call, answered with + // `Max context reached 68736 tokens but model supports only 60000` — 1.146 tokens + // per character. Byte fallback is what breaks the character premise: a character + // the vocabulary lacks is decomposed into its UTF-8 bytes, so one 3-byte + // character can cost 3 tokens where the budget charged it 1. + const { env, aiCalls, upsertedIds } = mkEnv(); + const commit = mkCommit(Array.from({ length: 16 }, () => "あ".repeat(3700))); + + const result = await processAndUpsertCommitDiff(env, mkStore(), REPO, commit); + + const allInputs = aiCalls.flat(); + // The fixture reproduces the shape only while it stays in the failing zone: one + // call under the retired character budget, over the ceiling in what it actually + // costs. Both halves are asserted, so a later edit to the patch size cannot + // quietly move it out of the shape it reproduces. + expect(retiredCharCharge(allInputs)).toBeLessThanOrEqual(WORKERS_AI_BATCH_CONTEXT_LIMIT); + expect(callCharge(allInputs)).toBeGreaterThan(WORKERS_AI_BATCH_CONTEXT_LIMIT); + + expect(aiCalls.length).toBeGreaterThan(1); + for (const call of aiCalls) { + expect(callCharge(call)).toBeLessThanOrEqual(MAX_EMBEDDING_BATCH_BYTES); + } + + expect(result.embedded).toBe(16); + expect(result.failed).toBe(0); + expect(new Set(upsertedIds.flat()).size).toBe(16); + }); + it("keeps each embed call paired with its own slice of files", async () => { // Vectors are matched to files by position, so a split has to cut the inputs // and the files on the same boundary. Reading each call's file paths back out diff --git a/src/pipeline/embed-diff.ts b/src/pipeline/embed-diff.ts index c342bfb..e11ae93 100644 --- a/src/pipeline/embed-diff.ts +++ b/src/pipeline/embed-diff.ts @@ -126,7 +126,7 @@ function normaliseFileStatus(status: string): DiffFileStatus { * take at most `options.maxFiles` of what remains. * 3. Build embedding inputs = commit message + file path + patch, truncated. * 4. Batch-embed inputs via Workers AI (chunked by `planEmbeddingBatches`, which - * splits on a character budget rather than a file count). + * splits on a UTF-8 byte budget rather than a file count). * 5. Upsert all vectors into Vectorize in the same chunks. * 6. Record DiffRecord rows into the Durable Object store for each indexed file. * @@ -196,14 +196,16 @@ export async function processAndUpsertCommitDiff( prepareDiffEmbeddingInput(commitMessage, f.filename, f.patch), ); - // Chunk on the character total of the inputs, not on how many files the commit + // Chunk on the UTF-8 byte total of the inputs, not on how many files the commit // touched. A file count bounds a call only if every patch is assumed to be // small, and a commit that breaks that assumption used to fail the whole chunk — // which the poller reads as an uningested commit and holds the diff watermark on, - // so the surface stalls there rather than skipping past it (#236). Characters - // rather than estimated tokens because the estimate ran about 2.1x low on diff - // patches, so the same two commits reported the same over-ceiling token counts - // before and after the estimated budget shipped — it never bound them (#241). + // so the surface stalls there rather than skipping past it (#236). Bytes rather + // than estimated tokens, which ran about 2.1x low on diff patches (#241), and + // rather than characters, which production measured at 1.146 tokens per character + // on non-ASCII content: byte fallback splits a character the vocabulary lacks into + // its UTF-8 bytes, so only bytes are below every split the tokenizer can make + // (#244). for (const { start, end } of planEmbeddingBatches(allInputs)) { const chunk = indexable.slice(start, end); const inputs = allInputs.slice(start, end); diff --git a/src/pipeline/embedding.test.ts b/src/pipeline/embedding.test.ts index b56eb28..3003db1 100644 --- a/src/pipeline/embedding.test.ts +++ b/src/pipeline/embedding.test.ts @@ -1,43 +1,86 @@ import { describe, it, expect } from "vitest"; import { planEmbeddingBatches, - MAX_EMBEDDING_BATCH_CHARS, + utf8ByteLength, + MAX_EMBEDDING_BATCH_BYTES, MAX_EMBEDDING_INPUT_CHARS, - SPECIAL_TOKENS_PER_INPUT, + TOKEN_OVERHEAD_PER_INPUT, WORKERS_AI_BATCH_CONTEXT_LIMIT, } from "./embedding.js"; -/** What the planner charges one batch: the inputs' characters plus their special - * tokens. An upper bound on the batch's true token count, not an estimate of it. */ +/** What the planner charges one batch: the inputs' UTF-8 bytes plus their per-input + * token overhead. An upper bound on the batch's true token count, not an estimate. */ function rangeCharge(inputs: string[], range: { start: number; end: number }): number { return inputs .slice(range.start, range.end) - .reduce((total, text) => total + text.length + SPECIAL_TOKENS_PER_INPUT, 0); + .reduce((total, text) => total + utf8ByteLength(text) + TOKEN_OVERHEAD_PER_INPUT, 0); } -describe("MAX_EMBEDDING_BATCH_CHARS", () => { +/** What the retired character budget charged the same inputs (#242): UTF-16 code + * units plus two special tokens. Kept in the tests only, to hold the regression + * fixtures inside the shape that budget passed and the endpoint rejected. */ +function retiredCharCharge(inputs: string[]): number { + return inputs.reduce((total, text) => total + text.length + 2, 0); +} + +describe("utf8ByteLength", () => { + const encoder = new TextEncoder(); + + it("agrees with TextEncoder on every width", () => { + // The count is derived from code units rather than by encoding, so the encoder + // is what it has to stay equal to. One case per UTF-8 width, plus the ill-formed + // input truncation can produce. + const samples = [ + "", + "plain ascii text", + "+ const value = obj?.[key] ?? { a: 1, b: [2, 3] };\n", + "é", // 2 bytes + "あ", // 3 bytes + "日本語のテキスト", // 3 bytes each + "🐈", // surrogate pair, 4 bytes + "mixed あ 🐈 text é", + "\uD83D", // lone high surrogate -> U+FFFD, 3 bytes + "\uDC08", // lone low surrogate -> U+FFFD, 3 bytes + "🐈".repeat(50).slice(0, 51), // pair cut in half by a code-unit slice + ]; + + for (const sample of samples) { + expect(utf8ByteLength(sample)).toBe(encoder.encode(sample).length); + } + }); + + it("charges non-ASCII more than its character count", () => { + // The whole reason the budget moved off characters: these two are the same + // length and not the same size. + expect(utf8ByteLength("あ".repeat(1000))).toBe(3000); + expect(utf8ByteLength("x".repeat(1000))).toBe(1000); + }); +}); + +describe("MAX_EMBEDDING_BATCH_BYTES", () => { it("does not exceed the endpoint's aggregate ceiling", () => { - // The whole guarantee rests on this: a token spans at least one character, so a - // batch charged under the ceiling *in characters* is under it in tokens too. - // Raise this above the ceiling and the bound stops holding by construction and - // goes back to being a calibration — the state #237 was in when the same two - // commits kept reporting the same over-ceiling token counts (#241). - expect(MAX_EMBEDDING_BATCH_CHARS).toBeLessThanOrEqual(WORKERS_AI_BATCH_CONTEXT_LIMIT); + // The whole guarantee rests on this: no token spans less than one UTF-8 byte of + // the input, byte fallback being the finest split there is, so a batch charged + // under the ceiling *in bytes* is under it in tokens too. Raise this above the + // ceiling and the bound stops holding by construction. + expect(MAX_EMBEDDING_BATCH_BYTES).toBeLessThanOrEqual(WORKERS_AI_BATCH_CONTEXT_LIMIT); }); - it("holds a batch of at least 7 maximal inputs", () => { + it("holds a batch of at least 2 maximal inputs", () => { // The floor the poller's DIFF_SUBREQUESTS_PER_FILE derivation reads off this - // constant: a batch's 2 subrequests amortise over this many files. Truncation - // caps one input at MAX_EMBEDDING_INPUT_CHARS, so the ratio of the two limits - // is the minimum file count, and it must not drop under what the poller assumes. + // constant: a batch's 2 subrequests amortise over this many files, and at 2 the + // per-file worst case is exactly the 3 the poller assumes. Truncation caps one + // input at MAX_EMBEDDING_INPUT_CHARS characters, and a UTF-16 code unit is at + // most 3 UTF-8 bytes, so that product is the largest input the planner can face. + const maxBytesPerInput = MAX_EMBEDDING_INPUT_CHARS * 3; const minInputsPerBatch = Math.floor( - MAX_EMBEDDING_BATCH_CHARS / (MAX_EMBEDDING_INPUT_CHARS + SPECIAL_TOKENS_PER_INPUT), + MAX_EMBEDDING_BATCH_BYTES / (maxBytesPerInput + TOKEN_OVERHEAD_PER_INPUT), ); - expect(minInputsPerBatch).toBeGreaterThanOrEqual(7); + expect(minInputsPerBatch).toBeGreaterThanOrEqual(2); - // Asserted through the planner as well, so the arithmetic above cannot drift - // away from the behaviour it describes. - const maximal = Array.from({ length: 20 }, () => "x".repeat(MAX_EMBEDDING_INPUT_CHARS)); + // Asserted through the planner as well, on the widest payload there is, so the + // arithmetic above cannot drift away from the behaviour it describes. + const maximal = Array.from({ length: 20 }, () => "あ".repeat(MAX_EMBEDDING_INPUT_CHARS)); expect(planEmbeddingBatches(maximal)[0].end).toBeGreaterThanOrEqual(minInputsPerBatch); }); }); @@ -53,9 +96,9 @@ describe("planEmbeddingBatches", () => { }); it("splits when the running total would overrun the budget", () => { - // Charge 11 each (9 characters + 2 special tokens) against a budget of 22. + // Charge 12 each (9 bytes + 3 overhead) against a budget of 24. const inputs = Array.from({ length: 5 }, () => "x".repeat(9)); - expect(planEmbeddingBatches(inputs, 22)).toEqual([ + expect(planEmbeddingBatches(inputs, 24)).toEqual([ { start: 0, end: 2 }, { start: 2, end: 4 }, { start: 4, end: 5 }, @@ -87,10 +130,10 @@ describe("planEmbeddingBatches", () => { } }); - it("charges the special tokens each input carries, not one flat reserve", () => { - // Many tiny inputs is the case a per-batch reserve gets wrong: 60 characters of - // text, but 120 special tokens on top. A planner charging text alone would fit - // all 60 in one call of 60 and hand the endpoint 180. + it("charges the per-input overhead each input carries, not one flat reserve", () => { + // Many tiny inputs is the case a per-batch reserve gets wrong: 60 bytes of text, + // but 180 tokens of overhead on top. A planner charging text alone would fit all + // 60 in one call of 60 and hand the endpoint 240. const inputs = Array.from({ length: 60 }, () => "x"); const ranges = planEmbeddingBatches(inputs, 60); @@ -100,17 +143,41 @@ describe("planEmbeddingBatches", () => { } }); - it("plans the same way for scripts of the same length", () => { - // The property the retired estimator did not have. It read ASCII at 3 characters - // per token and non-ASCII at 1, so the same character count planned differently - // by script — and the ASCII figure was the one that ran low on diff patches. A - // character bound is blind to what the characters are, which is why no payload - // can be the one it underestimates. + it("charges non-ASCII by what it costs, not by how long it reads", () => { + // The property the retired character budget did not have, and the reason it + // failed: it planned the same way for the same character count whatever the + // script, so a Japanese payload was charged a third of what it costs. The same + // count of Japanese characters must now be charged three times as much and split + // into more calls. const chars = 12000; const ascii = Array.from({ length: 12 }, () => "x".repeat(chars)); const cjk = Array.from({ length: 12 }, () => "あ".repeat(chars)); - expect(planEmbeddingBatches(cjk)).toEqual(planEmbeddingBatches(ascii)); + expect(utf8ByteLength(cjk[0])).toBe(3 * utf8ByteLength(ascii[0])); + expect(planEmbeddingBatches(cjk).length).toBeGreaterThan( + planEmbeddingBatches(ascii).length, + ); + }); + + it("splits the production shape a character budget passed whole", () => { + // 2026-08-15 cron, one commit of 16 Japanese-heavy files: the character budget + // charged the batch at most 60000 and sent it as one call, and the endpoint + // answered `Max context reached 68736 tokens but model supports only 60000` — + // 1.146 tokens per character, so a token had not spanned a character at all. + const inputs = Array.from({ length: 16 }, () => "あ".repeat(3700)); + + // The fixture is only a regression test while it stays in the failing zone: the + // retired character charge fits inside the budget it was measured against, so + // that budget would have sent all 16 as one call. + expect(retiredCharCharge(inputs)).toBeLessThanOrEqual(WORKERS_AI_BATCH_CONTEXT_LIMIT); + + const ranges = planEmbeddingBatches(inputs); + expect(ranges.length).toBeGreaterThan(1); + for (const range of ranges) { + expect(rangeCharge(inputs, range)).toBeLessThanOrEqual(MAX_EMBEDDING_BATCH_BYTES); + } + // Nothing is dropped on the way through the split. + expect(ranges[ranges.length - 1].end).toBe(16); }); it("gives an over-budget input a call of its own instead of stalling", () => { @@ -127,10 +194,11 @@ describe("planEmbeddingBatches", () => { it("admits any single truncated input under the default budget", () => { // Truncation caps an input at MAX_EMBEDDING_INPUT_CHARS, and the default budget // must take one of those alone — otherwise the planner hands the endpoint a - // single-input call it rejects, with nowhere further to split. + // single-input call it rejects, with nowhere further to split. Measured on the + // widest encoding a truncated input can reach: 3 bytes per code unit. const maximal = "あ".repeat(MAX_EMBEDDING_INPUT_CHARS); - expect(maximal.length + SPECIAL_TOKENS_PER_INPUT).toBeLessThanOrEqual( - MAX_EMBEDDING_BATCH_CHARS, + expect(utf8ByteLength(maximal) + TOKEN_OVERHEAD_PER_INPUT).toBeLessThanOrEqual( + MAX_EMBEDDING_BATCH_BYTES, ); expect(planEmbeddingBatches([maximal])).toEqual([{ start: 0, end: 1 }]); }); diff --git a/src/pipeline/embedding.ts b/src/pipeline/embedding.ts index b7036aa..5e4fc14 100644 --- a/src/pipeline/embedding.ts +++ b/src/pipeline/embedding.ts @@ -6,7 +6,15 @@ * `planEmbeddingBatches`; the helper does not split internally. */ -/** Maximum characters for embedding input (BGE-M3 context limit ~8192 tokens, conservative char limit) */ +/** Characters one embedding input is truncated to. + * + * A character cap, and only that. It was written against bge-m3's documented + * 8192-token per-input window on the reading that a token spans a character, which + * byte fallback breaks the same way it broke the batch budget below: 8000 + * characters of Japanese can decompose into far more tokens than that window holds. + * Whether the per-input axis needs a byte cap of its own is a separate question + * from the batch total this file bounds — the per-input window is enforced by the + * model, while the batch total is what the endpoint rejects outright. */ export const MAX_EMBEDDING_INPUT_CHARS = 8000; /** @@ -17,55 +25,107 @@ export const MAX_EMBEDDING_INPUT_CHARS = 8000; * 3030: Max context reached 85920 tokens but model supports only 60000 * * Unpublished, so this is read off the error rather than a docs page. Kept named - * because the character budget below is derived from it, and a budget whose - * reference is inlined reads as an arbitrary number the next time someone - * retunes it. + * because the byte budget below is derived from it, and a budget whose reference + * is inlined reads as an arbitrary number the next time someone retunes it. */ export const WORKERS_AI_BATCH_CONTEXT_LIMIT = 60000; /** - * Special tokens the model wraps around each input of a batch (`` … ``). + * Tokens one input of a batch costs beyond what its own bytes account for. + * + * Two are the sentinels the model wraps around each input (`` … ``). The + * third is the SentencePiece word-boundary marker: the tokenizer prefixes the text + * with `▁`, and where that marker does not merge into the first piece it is emitted + * as a token of its own, consuming no byte of the input. Three tokens per input is + * therefore what the byte count below cannot see. * - * The only part of a batch's token count that does not come from the input text, - * so it is the only part a character count cannot cover. It is charged per input - * rather than once per batch because the batch's input count is not bounded - * anywhere: a batch of many tiny inputs is where a single flat reserve would come - * up short, and that is exactly the case a fixed constant hides. + * Charged per input rather than once per batch because the batch's input count is + * not bounded anywhere: a batch of many tiny inputs is where a single flat reserve + * comes up short, and each of those inputs carries its own three. */ -export const SPECIAL_TOKENS_PER_INPUT = 2; +export const TOKEN_OVERHEAD_PER_INPUT = 3; /** - * Character budget for the inputs of one batched Workers AI embed call. + * UTF-8 bytes a string occupies. + * + * Counted off the UTF-16 code units rather than through `TextEncoder` so that + * measuring an input allocates no copy of it. A lone surrogate is charged 3 — the + * width of the U+FFFD that `TextEncoder` substitutes for it — so the count agrees + * with the encoder on ill-formed strings too, which matters because the truncation + * in `prepareDiffEmbeddingInput` cuts on a code-unit boundary and can leave one. + */ +export function utf8ByteLength(text: string): number { + let bytes = 0; + for (let i = 0; i < text.length; i++) { + const code = text.charCodeAt(i); + if (code < 0x80) { + bytes += 1; + } else if (code < 0x800) { + bytes += 2; + } else if (code >= 0xd800 && code <= 0xdbff && i + 1 < text.length) { + const low = text.charCodeAt(i + 1); + if (low >= 0xdc00 && low <= 0xdfff) { + // A well-formed pair is one code point above the BMP: 4 bytes for 2 units. + bytes += 4; + i++; + } else { + bytes += 3; + } + } else { + bytes += 3; + } + } + return bytes; +} + +/** + * UTF-8 byte budget for the inputs of one batched Workers AI embed call. + * + * The ceiling itself, in bytes, because bytes *dominate* tokens rather than + * approximating them: the finest split any of these tokenizers can make is one + * token per byte of the UTF-8 input — that is what byte fallback is — so for any + * input + * + * tokens(input) <= utf8ByteLength(input) + TOKEN_OVERHEAD_PER_INPUT * - * The ceiling itself, in characters, because characters *dominate* tokens rather - * than approximating them: every token of a BPE or SentencePiece vocabulary spans - * at least one character of the input, so for any input + * and a batch whose charged total stays inside this budget is inside the ceiling. + * No calibration and no per-payload measurement, which is the property the two + * budgets before this one were reaching for and missed: * - * tokens(input) <= input.length + SPECIAL_TOKENS_PER_INPUT + * - an estimated token count ran about 2.1x optimistic on diff patches and handed + * the endpoint 60678 and 64413 tokens against the ceiling; + * - a character count rested on "a token spans at least one character", which byte + * fallback breaks — a character outside the vocabulary is decomposed into its + * UTF-8 bytes, so one 3-byte Japanese character can cost 3 tokens. Production + * measured 68736 tokens on a batch charged at most 60000 characters, a ratio of + * 1.146 tokens per character. * - * and a batch whose charged total stays inside this budget is inside the ceiling - * unconditionally — no calibration, and no dependence on the payload's language or - * punctuation density. Which matters because the estimate this replaced was wrong - * by about 2.1x on the surface that actually failed: diff patches run near 1.4 - * characters per token, not the 3 an ASCII-prose ratio assumed, so batches judged - * to fit under a 30000-token budget reached 60678 and 64413 against the ceiling and - * failed their whole chunk. A commit whose vectors never landed is one the diff - * watermark holds on, so the surface stalled on the same commit every cron tick. + * Bytes are the floor under that decomposition: nothing splits finer, so no payload + * can be the one this underestimates the way the two above were. The bound assumes + * the tokenizer's NFKC normalization does not expand the input in bytes, which holds + * except for compatibility characters that decompose into several (Arabic ligatures, + * CJK square abbreviations). That is a different class of exposure from the two + * retired premises: those broke on ordinary diff text, this one needs an input made + * predominantly of one rare block. * * Equality with the ceiling is admissible: the rejections name counts strictly - * above it (`Max context reached 60678 tokens but model supports only 60000`), so + * above it (`Max context reached 68736 tokens but model supports only 60000`), so * 60000 is a supported count and not the first rejected one. * - * Sized in characters rather than under the ceiling by a margin because a margin - * is not free — every extra batch costs two subrequests (the AI call and its + * Held at the ceiling rather than under it by a margin because a margin is not free + * — every extra batch costs two subrequests (the AI call and its * `VECTORIZE.upsert`) against an invocation budget this worker already overruns, * and a bound that holds by construction has nothing left for a margin to buy. * - * `MAX_EMBEDDING_INPUT_CHARS` truncates one input to 8000 characters, so a batch - * holds at least 7 inputs however large each patch is. That floor is what the - * poller's per-file subrequest estimate rests on. + * `MAX_EMBEDDING_INPUT_CHARS` truncates one input to 8000 characters, which is at + * most 24000 bytes (3 per UTF-16 code unit is the widest UTF-8 gets; a surrogate + * pair is 4 bytes across 2 units), so a batch holds at least 2 inputs however large + * each patch is. That floor is what the poller's per-file subrequest estimate rests + * on, and it is a third of what the character budget gave — a batch of Japanese + * patches now splits about three ways where it used to be one call. The extra + * subrequests are the price of the bound actually holding. */ -export const MAX_EMBEDDING_BATCH_CHARS = WORKERS_AI_BATCH_CONTEXT_LIMIT; +export const MAX_EMBEDDING_BATCH_BYTES = WORKERS_AI_BATCH_CONTEXT_LIMIT; /** Half-open `[start, end)` index range over a caller's input array. */ export interface EmbeddingBatchRange { @@ -74,14 +134,12 @@ export interface EmbeddingBatchRange { } /** - * Split embedding inputs into batches whose character totals stay within - * `budgetChars`. + * Split embedding inputs into batches whose UTF-8 byte totals stay within + * `budgetBytes`. * - * Each input is charged its own length plus `SPECIAL_TOKENS_PER_INPUT`, which makes - * the charged total an upper bound on the batch's true token count rather than an - * estimate of it (see `MAX_EMBEDDING_BATCH_CHARS`). Length is counted in UTF-16 - * code units, so a surrogate pair costs two — one more than the code point it - * encodes, which errs on the side that keeps the bound. + * Each input is charged its own byte length plus `TOKEN_OVERHEAD_PER_INPUT`, which + * makes the charged total an upper bound on the batch's true token count rather + * than an estimate of it (see `MAX_EMBEDDING_BATCH_BYTES`). * * Index ranges are returned rather than the strings themselves so the caller can * slice its own parallel arrays (files, metadata) by the same boundaries — the @@ -97,18 +155,18 @@ export interface EmbeddingBatchRange { */ export function planEmbeddingBatches( inputs: string[], - budgetChars: number = MAX_EMBEDDING_BATCH_CHARS, + budgetBytes: number = MAX_EMBEDDING_BATCH_BYTES, ): EmbeddingBatchRange[] { const ranges: EmbeddingBatchRange[] = []; let start = 0; let total = 0; for (let i = 0; i < inputs.length; i++) { - const cost = inputs[i].length + SPECIAL_TOKENS_PER_INPUT; + const cost = utf8ByteLength(inputs[i]) + TOKEN_OVERHEAD_PER_INPUT; // Close the open range before an input that would overrun the budget. The // `i > start` guard is what keeps an oversized input in a batch of its own // instead of closing an empty range and looping on it forever. - if (i > start && total + cost > budgetChars) { + if (i > start && total + cost > budgetBytes) { ranges.push({ start, end: i }); start = i; total = 0; diff --git a/src/poller.test.ts b/src/poller.test.ts index dd717c0..388ce47 100644 --- a/src/poller.test.ts +++ b/src/poller.test.ts @@ -1,5 +1,10 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import type { Env } from "./types.js"; +import { + MAX_EMBEDDING_BATCH_BYTES, + MAX_EMBEDDING_INPUT_CHARS, + TOKEN_OVERHEAD_PER_INPUT, +} from "./pipeline/embedding.js"; // `pollDiffs` fans out to the commit-diff pipeline (GitHub detail fetch + Workers // AI embed + Vectorize + D1 + Store DO). The watermark contract under test is @@ -548,6 +553,24 @@ describe("poller: diffFileBudgetPerPhase", () => { } }); + it("charges a file no less than the batch axis costs it", () => { + // The 3 above is not a free parameter: 2 of it is fixed per file (the D1 FTS + // mirror write and the store row) and the third is a batch's 2 subrequests + // amortised over the files it holds. Moving the batch budget moves that floor — + // it was 7 files under a character budget and is 2 under a byte budget (#244), + // since truncation caps an input at MAX_EMBEDDING_INPUT_CHARS characters and a + // UTF-16 code unit is at most 3 UTF-8 bytes. At 2 the sum is exactly 3, so this + // holds without slack and a further tightening of the batch axis fails here + // rather than silently overrunning the invocation budget. + const maxBytesPerInput = MAX_EMBEDDING_INPUT_CHARS * 3; + const minFilesPerBatch = Math.floor( + MAX_EMBEDDING_BATCH_BYTES / (maxBytesPerInput + TOKEN_OVERHEAD_PER_INPUT), + ); + + expect(minFilesPerBatch).toBeGreaterThanOrEqual(1); + expect(2 + 2 / minFilesPerBatch).toBeLessThanOrEqual(3); + }); + it("shrinks the per-phase budget as repos are appended", () => { // The defect this replaces: a literal cap sized against the repo list of the // day, overrun silently by the next config commit that appends a repo. diff --git a/src/poller.ts b/src/poller.ts index 293aa04..b511448 100644 --- a/src/poller.ts +++ b/src/poller.ts @@ -206,13 +206,17 @@ const DIFF_SUBREQUEST_BUDGET_PER_RUN = 900; * * Two are fixed and per-file: the D1 FTS mirror write and the Store DO row. * The third is the amortised batch cost — a batch spends 2 (the Workers AI call - * and its `VECTORIZE.upsert`) and holds at least 7 files, because - * `MAX_EMBEDDING_INPUT_CHARS` caps one input at 8000 characters and - * `MAX_EMBEDDING_BATCH_CHARS` gives a batch 60000, whatever the payload is made - * of. That puts the true figure at 2.29 and under; 3 is it rounded to the safe - * side. The floor was 3 while the batch axis was an estimated token budget - * (#237); moving that axis to characters (#241) raised the floor and left this - * constant on the safe side of its own derivation, so it is unchanged. */ + * and its `VECTORIZE.upsert`) and holds at least 2 files, because + * `MAX_EMBEDDING_INPUT_CHARS` caps one input at 8000 characters, which is at most + * 24000 UTF-8 bytes, against the 60000 bytes `MAX_EMBEDDING_BATCH_BYTES` gives a + * batch. Two files per batch puts the amortised share at exactly 1, so the worst + * case is exactly 3 — no longer rounded up from 2.29 but met on the nose. + * + * That floor moved with the batch axis: 7 files while the budget was counted in + * characters (#241), 2 now that it is counted in UTF-8 bytes (#244), because a + * Japanese character is charged 3 bytes where it used to be charged 1. The + * constant is unchanged and the derivation still holds, but it holds without slack + * — a further tightening of the batch axis lands here rather than being absorbed. */ const DIFF_SUBREQUESTS_PER_FILE = 3; /** Per-phase subrequests that are not per-file: up to 5 commit detail fetches,