From a21fd07203ee54a33655ca79e4daa5faec43f3f4 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Thu, 29 Oct 2026 18:53:14 +0100 Subject: [PATCH] fix(llm): embedding requests within the model's token budget bge-multilingual-gemma2 takes 8192 tokens; on prod (16 and 22 Oct, 7 each) a batch of 16 code chunks came to ~51k and was refused, so the repo's embedding build failed (backlog t26). Chunks are capped at 2048 estimated tokens, but at 4 chars per token, which undercounts code, and 16 of them went into one request. embed() now plans batches by input count (16) and an estimated token budget (7000 per request, 3 bytes per token), and cuts a single text that would not fit alone at a char boundary (the head keeps the context header and signature). Order is kept across batches. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KYcAAeTw22GE9QPzDM8yc4 --- compliance-agent/src/llm/embedding.rs | 81 ++++++++++++++++++++++++++- 1 file changed, 78 insertions(+), 3 deletions(-) diff --git a/compliance-agent/src/llm/embedding.rs b/compliance-agent/src/llm/embedding.rs index 3ebe62d..a7d79f3 100644 --- a/compliance-agent/src/llm/embedding.rs +++ b/compliance-agent/src/llm/embedding.rs @@ -29,6 +29,53 @@ const EMBED_BATCH_SIZE: usize = 16; // The bge backend takes at most 25 inputs per request. const _: () = assert!(EMBED_BATCH_SIZE <= 25); +/// Token budget of one embedding request. bge-multilingual-gemma2 takes 8192 +/// tokens; on prod a batch of 16 code chunks came to ~51k and was refused, so a +/// request now carries only as many inputs as fit, and one input never more. +const EMBED_MAX_REQUEST_TOKENS: usize = 7000; + +/// Conservative bytes per token: code tokenizes denser than prose (the chunker's +/// own estimate of 4 chars per token undercounts it). +const EMBED_BYTES_PER_TOKEN: usize = 3; + +fn estimated_tokens(text: &str) -> usize { + text.len().div_ceil(EMBED_BYTES_PER_TOKEN) +} + +/// Shorten `text` (at a char boundary) so it fits a request on its own. The +/// head of a chunk carries its context header and signature, which is what +/// retrieval needs. +fn fit_text(mut text: String) -> String { + let max_bytes = EMBED_MAX_REQUEST_TOKENS * EMBED_BYTES_PER_TOKEN; + if text.len() > max_bytes { + let mut cut = max_bytes; + while !text.is_char_boundary(cut) { + cut -= 1; + } + text.truncate(cut); + } + text +} + +/// Split `texts` into consecutive batches of at most [`EMBED_BATCH_SIZE`] +/// inputs and [`EMBED_MAX_REQUEST_TOKENS`] estimated tokens, keeping order. +fn plan_batches(texts: &[String]) -> Vec> { + let mut out = Vec::new(); + let (mut start, mut tokens) = (0, 0); + for (i, t) in texts.iter().enumerate() { + let n = estimated_tokens(t); + if i > start && (i - start == EMBED_BATCH_SIZE || tokens + n > EMBED_MAX_REQUEST_TOKENS) { + out.push(start..i); + (start, tokens) = (i, 0); + } + tokens += n; + } + if start < texts.len() { + out.push(start..texts.len()); + } + out +} + // ── Embedding implementation ─────────────────────────────────── impl LlmClient { @@ -37,14 +84,15 @@ impl LlmClient { } /// Generate embeddings for a batch of texts, chunking into backend-sized - /// requests and preserving input order across chunks. + /// requests (input count and token budget) and preserving input order. pub async fn embed(&self, texts: Vec) -> Result>, AgentError> { if texts.is_empty() { return Ok(Vec::new()); } + let texts: Vec = texts.into_iter().map(fit_text).collect(); let mut out = Vec::with_capacity(texts.len()); - for chunk in texts.chunks(EMBED_BATCH_SIZE) { - out.extend(self.embed_batch(chunk.to_vec()).await?); + for range in plan_batches(&texts) { + out.extend(self.embed_batch(texts[range].to_vec()).await?); } Ok(out) } @@ -119,6 +167,33 @@ mod tests { assert!(out.is_empty()); } + #[test] + fn batches_respect_count_and_token_budget() { + // 40 short texts: count-bound, 16 + 16 + 8 + let short: Vec = (0..40).map(|i| format!("fn f{i}() {{}}")).collect(); + let b = plan_batches(&short); + assert_eq!(b, vec![0..16, 16..32, 32..40]); + + // 8 KiB code chunks (~2731 tokens each): two per request, never three + let big: Vec = (0..5).map(|_| "x".repeat(8192)).collect(); + let b = plan_batches(&big); + assert_eq!(b, vec![0..2, 2..4, 4..5]); + for r in &b { + let tokens: usize = big[r.clone()].iter().map(|t| estimated_tokens(t)).sum(); + assert!(tokens <= EMBED_MAX_REQUEST_TOKENS, "{r:?}: {tokens}"); + } + } + + #[test] + fn oversized_text_is_cut_to_fit_alone_at_a_char_boundary() { + let long = "ä".repeat(30_000); // 60 000 bytes, 2 bytes per char + let cut = fit_text(long); + assert!(estimated_tokens(&cut) <= EMBED_MAX_REQUEST_TOKENS); + assert!(cut.chars().all(|c| c == 'ä')); + assert_eq!(plan_batches(&[cut.clone(), "y".into()]), vec![0..1, 1..2]); + assert_eq!(fit_text("short".into()), "short"); + } + #[tokio::test] async fn no_embed_model_makes_no_request() { let mut llm = client(); -- 2.54.1