Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/0-requirements.ja.md
Original file line number Diff line number Diff line change
Expand Up @@ -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_TOKENS`)で決める。この pipeline が embed する内容の「1 token あたりの文字数」は桁で変わる — ASCII のソースで約 3、CJK の散文で約 1 — ため、件数が call を縛れるのは「どの patch も安い側である」と仮定した場合だけである。その仮定を破る commit は chunk 全体を失敗させ、vector が載らなかった commit は diff watermark が留まる対象(issue #178)なので、その commit を飛ばすのではなく surface がそこで恒久的に停止していた。しかも毎 cron 同じ commit で同じ結果になる決定論的な失敗で、同じログに同居する一過性の subrequest 超過とはそこで性質が分かれる(issue #236)。天井は 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` としてそのエラーから記録し、予算はその半分に置く。半分にしているのは効く方向の誤差が 1 つだけだからで、`estimateEmbeddingTokens` は近似であり、真値より小さく出た推定こそが call を天井の向こうへ送って stall を再現する。同時に天井から離しすぎない — batch が 1 つ増えるごとに subrequest を 2 つ消費し、この worker は既に invocation 予算を超過しているため。単独で予算を超える input はそのまま単独で送る — さらに削るのは truncate 軸(`MAX_EMBEDDING_INPUT_CHARS`)の仕事であり、落とせばその file が索引から消えるため
- 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 個(`<s>` … `</s>`)を課金すれば、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 見積りが立っている床である

**索引欠落の修復.** 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` 指定で越えられる。

Expand Down
2 changes: 1 addition & 1 deletion docs/0-requirements.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 an estimated token budget (`MAX_EMBEDDING_BATCH_TOKENS`), not on a file count. Characters per token vary by an order of magnitude across what this pipeline embeds — roughly 3 for ASCII source, roughly 1 for CJK prose — so N inputs bound a call only where every patch is assumed to be the cheap kind. A commit that broke the assumption failed its whole chunk, and a commit whose vectors never landed is one the diff watermark holds on (issue #178), so the surface stalled there permanently instead of passing it by — deterministically, on the same commit every cron tick, which is what separated it from the transient subrequest overruns sharing the log (issue #236). 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 budget is half of it. The halving covers the one error direction that matters — `estimateEmbeddingTokens` approximates, and an estimate landing under the true count is what puts a call over the ceiling and reproduces the stall — while staying near enough the ceiling to keep the batch count down, since every extra batch spends two subrequests on an invocation budget this worker already overruns. An input whose own estimate 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
- 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 (`<s>` … `</s>`) 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

**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.

Expand Down
59 changes: 55 additions & 4 deletions src/pipeline/embed-diff.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { describe, it, expect, vi } from "vitest";
import type { Env } from "../types.js";
import { processAndUpsertCommitDiff, type GitHubCommitDetail } from "./embed-diff.js";
import { estimateEmbeddingTokens, MAX_EMBEDDING_BATCH_TOKENS } from "./embedding.js";
import {
MAX_EMBEDDING_BATCH_CHARS,
SPECIAL_TOKENS_PER_INPUT,
WORKERS_AI_BATCH_CONTEXT_LIMIT,
} from "./embedding.js";
import { diffVectorId } from "./vector-id.js";

const REPO = "acme/widgets";
Expand Down Expand Up @@ -66,7 +70,19 @@ function mkStore() {
} as unknown as DurableObjectStub;
}

describe("embed-diff: the batch axis is the token budget, not the file count", () => {
/** A patch of the shape the ceiling rejected: dense punctuation, short identifiers,
* a `+` on every line — where bge-m3 splits far finer than an ASCII prose ratio. */
function mkDiffPatch(chars: number): string {
const line = "+ const value = obj?.[key] ?? { a: 1, b: [2, 3] };\n";
return line.repeat(Math.ceil(chars / line.length)).slice(0, chars);
}

/** 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);
}

describe("embed-diff: the batch axis is the character 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();
Expand Down Expand Up @@ -104,8 +120,7 @@ describe("embed-diff: the batch axis is the token 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) {
const total = call.reduce((sum, text) => sum + estimateEmbeddingTokens(text), 0);
expect(total).toBeLessThanOrEqual(MAX_EMBEDDING_BATCH_TOKENS);
expect(callCharge(call)).toBeLessThanOrEqual(MAX_EMBEDDING_BATCH_CHARS);
}
}

Expand All @@ -114,6 +129,42 @@ describe("embed-diff: the batch axis is the token budget, not the file count", (
expect(new Set(upsertedIds.flat()).size).toBe(20);
});

it("splits the 18-file commit shape that an estimated budget let through", async () => {
// The payload that kept failing after #237 shipped: 18 files of ordinary diff
// patch, no single one of them oversized. bge-m3 tokenizes a patch at roughly
// 1.4 characters per token — `+`/`-` prefixes, indentation, punctuation and
// short identifiers all split small — so the retired estimator's ASCII ratio of
// 3 came in about 2.1x under the truth, judged the whole commit to fit one
// 30000-token batch, and handed the endpoint 60678 tokens against a ceiling of
// 60000. The chunk failed whole, and the diff watermark held on the commit.
const { env, aiCalls, upsertedIds } = mkEnv();
const commit = mkCommit(Array.from({ length: 18 }, () => mkDiffPatch(4700)));

const result = await processAndUpsertCommitDiff(env, mkStore(), REPO, commit);

const allInputs = aiCalls.flat();
// The fixture is only a regression test while it stays in the failing zone: over
// the ceiling as one call, yet inside the budget the estimator would have
// computed for it — roughly 85200 ASCII characters, which its ratio of 3 read as
// about 28400 tokens against the 30000 that #237 set. The second assertion
// divides the charge rather than the bare character sum, which overstates the
// estimator's figure by the special tokens and so errs toward failing. Both
// halves are asserted, so a later edit to the patch size cannot quietly move the
// fixture out of the shape it reproduces.
expect(callCharge(allInputs)).toBeGreaterThan(WORKERS_AI_BATCH_CONTEXT_LIMIT);
expect(Math.ceil(callCharge(allInputs) / 3)).toBeLessThanOrEqual(30000);

expect(aiCalls.length).toBeGreaterThan(1);
for (const call of aiCalls) {
expect(callCharge(call)).toBeLessThanOrEqual(MAX_EMBEDDING_BATCH_CHARS);
}

// Splitting is only the fix if every file still lands.
expect(result.embedded).toBe(18);
expect(result.failed).toBe(0);
expect(new Set(upsertedIds.flat()).size).toBe(18);
});

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
Expand Down
Loading
Loading