Skip to content

fix(token_counter): bound base64 PDF counting and price drawing-heavy pages by their text - #47613

Open
mateo-berri wants to merge 27 commits into
mainfrom
litellm_bound_pdf_token_count
Open

mateo-berri wants to merge 27 commits into
mainfrom
litellm_bound_pdf_token_count

Conversation

@mateo-berri

@mateo-berri mateo-berri commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Description

Counting tokens from a base64 PDF read every page's full text, so one dense page could occupy a worker for minutes and block other token counts. Oversized pages now use bounded pypdf text samples, including Type0 and Identity-H fonts. The counter also memoizes textless Form XObject subtrees, caps lazy scans, uses a single-pass closure scanner with real ET tracking that repairs dangling escapes and continues past unclosed text, and treats NUL as PDF whitespace

Details

TLDR

Problem this solves:

  • Dense PDFs could occupy a worker for minutes
  • Vector drawings could be counted far above their text

How it solves it:

  • Samples at most 16 evenly spaced pages
  • Prices oversized pages with bounded pypdf text extraction
  • Memoizes and skips textless Form XObject subtrees
  • Caps lazy scans and closes samples using real ET tracking
  • Repairs dangling escapes and keeps sampling after unclosed text
  • Treats NUL as PDF whitespace

User Flow

Before: a developer sends a PDF and their token count hangs, and an engineering drawing PDF gets rejected for size

  1. They send POST http://localhost:4000/utils/token_counter with a one-page base64 PDF holding about 16M characters of text
  2. The call takes about 4 minutes, and other token counts on that worker wait behind it
  3. With fix(token_counter): bound the cost of pricing a base64 PDF #45677 alone, a 20-page vector drawing PDF counts at 3.4M tokens, so pre-call checks reject it

After: dense PDFs return quickly without holding other token counts

  1. They send the same POST http://localhost:4000/utils/token_counter with the dense PDF
  2. The 16 MB PDF returns 4,014,043 tokens in about 1.3 seconds, while a delayed tiny request returns 12 tokens
  3. The 20-page vector drawing returns 30,895 tokens instead of the previous 3.4M estimate

Relevant issues

Fixes #45676
Supersedes #45677

Affected release

Regression in v1.106.0-dev.3 from #45301, shipped in v1.106.0

Linear ticket

Resolves LIT-9408

Pre-Submission checklist

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/unit/<your_test_file>.py -v
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Screenshots / Proof of Fix

Setup

The raw API proof uses POST /utils/token_counter for token counts and POST /v1/chat/completions for one real provider call. PDF token-count requests use a text block and a file block with file.file_data set to a data:application/pdf;base64,... URL. The chat payload uses model=gemini-flash-lite and max_tokens=50

gemini/gemini-3.5-flash-lite is the latest chat-capable Gemini Flash-Lite entry in model_prices_and_context_window.json. The newer gemini-3.8-flash-lite-tts entry is for audio speech

The sanitized proxy config was:

model_list:
  - model_name: gemini-flash-lite
    litellm_params:
      model: gemini/gemini-3.5-flash-lite
      api_key: os.environ/GEMINI_API_KEY
general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
router_settings:
  disable_cooldowns: true

No database URL was configured. Both proxies used --num_workers 1, with DATABASE_URL and DIRECT_URL unset

Payloads were generated with:

python3 make_payloads.py

The generator copies the PDF builders from bench.py and bench_vector.py without importing those scripts. Payloads are in payloads/

Before used wt-main at 7e8be61fa04c253fb950b2d146a6b169472d232. Its import check resolved to wt-main/litellm/__init__.py. The first five Before results below are retained from the earlier run. After the stall test left PID 44198 consuming CPU, that proxy was stopped and restarted cleanly as PID 53007. The missing chat case was run on that restart, with the same base SHA and import path. Health returned 200

After used wt-fix at 658ca5c9a90d3f3dcf4556853a72e1815911660e, confirmed by git rev-parse HEAD. Its import check resolved to wt-fix/litellm/__init__.py. After ran on port 4002, and health returned 200

$MASTER_KEY was read from the corresponding proxy process environment for each curl. The Gemini credential and master key were not printed or written to this report

The Before proxy log is live-main-proxy-clean.log. The After proxy log is live-after-proxy-658ca5c9.log

After response JSON and curl metadata are in /home/ubuntu/lit9408/live-after-658ca5c9-*.json and /home/ubuntu/lit9408/live-after-658ca5c9-*.meta

Before (7e8be61)

tiny_text

  1. Command:

    timeout 400 curl -sS -o live-before-rerun-tiny_text.json -w "status=%{http_code} time_total=%{time_total}s\n" -H "Authorization: Bearer $MASTER_KEY" -H "Content-Type: application/json" -d @payloads/tiny_text.json http://127.0.0.1:4001/utils/token_counter
  2. Output: status=200 time_total=0.169368s, curl_exit=0, total_tokens=12, model_used=gemini-3.5-flash-lite, tokenizer_type=openai_tokenizer

vector_20

  1. Command:

    timeout 400 curl -sS -o live-before-rerun-vector_20.json -w "status=%{http_code} time_total=%{time_total}s\n" -H "Authorization: Bearer $MASTER_KEY" -H "Content-Type: application/json" -d @payloads/vector_20.json http://127.0.0.1:4001/utils/token_counter
  2. Output: status=200 time_total=3.317411s, curl_exit=0, total_tokens=30895, model_used=gemini-3.5-flash-lite, tokenizer_type=openai_tokenizer

text_500

  1. Command:

    timeout 400 curl -sS -o live-before-rerun-text_500.json -w "status=%{http_code} time_total=%{time_total}s\n" -H "Authorization: Bearer $MASTER_KEY" -H "Content-Type: application/json" -d @payloads/text_500.json http://127.0.0.1:4001/utils/token_counter
  2. Output: status=200 time_total=6.313796s, curl_exit=0, total_tokens=1670015, model_used=gemini-3.5-flash-lite, tokenizer_type=openai_tokenizer

form_xobject

  1. Command:

    timeout 400 curl -sS -o live-before-rerun-form_xobject.json -w "status=%{http_code} time_total=%{time_total}s\n" -H "Authorization: Bearer $MASTER_KEY" -H "Content-Type: application/json" -d @payloads/form_xobject.json http://127.0.0.1:4001/utils/token_counter
  2. Output: status=200 time_total=37.570648s, curl_exit=0, total_tokens=491549, model_used=gemini-3.5-flash-lite, tokenizer_type=openai_tokenizer

stall test

  1. Four dense requests ran in the background. After a two-second delay, the tiny request ran, then all four dense requests were awaited

    timeout 400 curl -sS -o live-before-rerun-dense_16M-1.json -w "status=%{http_code} time_total=%{time_total}s\n" -H "Authorization: Bearer $MASTER_KEY" -H 'Content-Type: application/json' -d @payloads/dense_16M.json http://127.0.0.1:4001/utils/token_counter > live-before-rerun-dense_16M-1.meta 2>&1 &
    timeout 400 curl -sS -o live-before-rerun-dense_16M-2.json -w "status=%{http_code} time_total=%{time_total}s\n" -H "Authorization: Bearer $MASTER_KEY" -H 'Content-Type: application/json' -d @payloads/dense_16M.json http://127.0.0.1:4001/utils/token_counter > live-before-rerun-dense_16M-2.meta 2>&1 &
    timeout 400 curl -sS -o live-before-rerun-dense_16M-3.json -w "status=%{http_code} time_total=%{time_total}s\n" -H "Authorization: Bearer $MASTER_KEY" -H 'Content-Type: application/json' -d @payloads/dense_16M.json http://127.0.0.1:4001/utils/token_counter > live-before-rerun-dense_16M-3.meta 2>&1 &
    timeout 400 curl -sS -o live-before-rerun-dense_16M-4.json -w "status=%{http_code} time_total=%{time_total}s\n" -H "Authorization: Bearer $MASTER_KEY" -H 'Content-Type: application/json' -d @payloads/dense_16M.json http://127.0.0.1:4001/utils/token_counter > live-before-rerun-dense_16M-4.meta 2>&1 &
    sleep 2
    timeout 400 curl -sS -o live-before-rerun-stall-tiny_text.json -w "status=%{http_code} time_total=%{time_total}s\n" -H "Authorization: Bearer $MASTER_KEY" -H 'Content-Type: application/json' -d @payloads/tiny_text.json http://127.0.0.1:4001/utils/token_counter
    wait
  2. The tiny curl and all four dense curls exited 124 at their timeout 400 limits. No HTTP status, time_total, or token count was returned. The dense .meta files are empty

real chat completion with vector_20

  1. Command:

    timeout 400 curl -sS -o live-before-chat-vector_20.json -w "status=%{http_code} time_total=%{time_total}s\n" -H "Authorization: Bearer $MASTER_KEY" -H 'Content-Type: application/json' -d @payloads/vector_20_chat.json http://127.0.0.1:4001/v1/chat/completions
  2. Output: status=200 time_total=20.676302s, curl_exit=0, usage.prompt_tokens=10406

After (658ca5c)

tiny_text

  1. Command:

    timeout 400 curl -sS -o live-after-658ca5c9-tiny_text.json -w "status=%{http_code} time_total=%{time_total}s\n" -H "Authorization: Bearer $MASTER_KEY" -H 'Content-Type: application/json' -d @payloads/tiny_text.json http://127.0.0.1:4002/utils/token_counter > live-after-658ca5c9-tiny_text.meta 2>&1
  2. Output: status=200 time_total=0.176362s, curl_exit=0, total_tokens=12, model_used=gemini-3.5-flash-lite, tokenizer_type=openai_tokenizer

vector_20

  1. Command:

    timeout 400 curl -sS -o live-after-658ca5c9-vector_20.json -w "status=%{http_code} time_total=%{time_total}s\n" -H "Authorization: Bearer $MASTER_KEY" -H 'Content-Type: application/json' -d @payloads/vector_20.json http://127.0.0.1:4002/utils/token_counter > live-after-658ca5c9-vector_20.meta 2>&1
  2. Output: status=200 time_total=0.195980s, curl_exit=0, total_tokens=30895, model_used=gemini-3.5-flash-lite, tokenizer_type=openai_tokenizer

text_500

  1. Command:

    timeout 400 curl -sS -o live-after-658ca5c9-text_500.json -w "status=%{http_code} time_total=%{time_total}s\n" -H "Authorization: Bearer $MASTER_KEY" -H 'Content-Type: application/json' -d @payloads/text_500.json http://127.0.0.1:4002/utils/token_counter > live-after-658ca5c9-text_500.meta 2>&1
  2. Output: status=200 time_total=0.235155s, curl_exit=0, total_tokens=1670015, model_used=gemini-3.5-flash-lite, tokenizer_type=openai_tokenizer

form_xobject

  1. Command:

    timeout 400 curl -sS -o live-after-658ca5c9-form_xobject.json -w "status=%{http_code} time_total=%{time_total}s\n" -H "Authorization: Bearer $MASTER_KEY" -H 'Content-Type: application/json' -d @payloads/form_xobject.json http://127.0.0.1:4002/utils/token_counter > live-after-658ca5c9-form_xobject.meta 2>&1
  2. Output: status=200 time_total=0.328970s, curl_exit=0, total_tokens=491549, model_used=gemini-3.5-flash-lite, tokenizer_type=openai_tokenizer

stall test

  1. Four dense requests ran in the background. After a two-second delay, the tiny request ran, then all four dense requests were awaited

    timeout 400 curl -sS -o live-after-658ca5c9-dense_16M-1.json -w "status=%{http_code} time_total=%{time_total}s\n" -H "Authorization: Bearer $MASTER_KEY" -H 'Content-Type: application/json' -d @payloads/dense_16M.json http://127.0.0.1:4002/utils/token_counter > live-after-658ca5c9-dense_16M-1.meta 2>&1 &
    P1=$!
    timeout 400 curl -sS -o live-after-658ca5c9-dense_16M-2.json -w "status=%{http_code} time_total=%{time_total}s\n" -H "Authorization: Bearer $MASTER_KEY" -H 'Content-Type: application/json' -d @payloads/dense_16M.json http://127.0.0.1:4002/utils/token_counter > live-after-658ca5c9-dense_16M-2.meta 2>&1 &
    P2=$!
    timeout 400 curl -sS -o live-after-658ca5c9-dense_16M-3.json -w "status=%{http_code} time_total=%{time_total}s\n" -H "Authorization: Bearer $MASTER_KEY" -H 'Content-Type: application/json' -d @payloads/dense_16M.json http://127.0.0.1:4002/utils/token_counter > live-after-658ca5c9-dense_16M-3.meta 2>&1 &
    P3=$!
    timeout 400 curl -sS -o live-after-658ca5c9-dense_16M-4.json -w "status=%{http_code} time_total=%{time_total}s\n" -H "Authorization: Bearer $MASTER_KEY" -H 'Content-Type: application/json' -d @payloads/dense_16M.json http://127.0.0.1:4002/utils/token_counter > live-after-658ca5c9-dense_16M-4.meta 2>&1 &
    P4=$!
    sleep 2
    timeout 400 curl -sS -o live-after-658ca5c9-stall-tiny_text.json -w "status=%{http_code} time_total=%{time_total}s\n" -H "Authorization: Bearer $MASTER_KEY" -H 'Content-Type: application/json' -d @payloads/tiny_text.json http://127.0.0.1:4002/utils/token_counter > live-after-658ca5c9-stall-tiny_text.meta 2>&1
    wait "$P1"
    wait "$P2"
    wait "$P3"
    wait "$P4"
  2. Tiny during stall: status=200 time_total=0.007067s, curl_exit=0, total_tokens=12. Dense calls: 1, status=200 time_total=1.323424s, curl_exit=0, total_tokens=4014043; 2, status=200 time_total=1.326001s, curl_exit=0, total_tokens=4014043; 3, status=200 time_total=1.324115s, curl_exit=0, total_tokens=4014043; 4, status=200 time_total=1.325838s, curl_exit=0, total_tokens=4014043

real chat completion with vector_20

  1. Command:

    timeout 400 curl -sS -o live-after-658ca5c9-chat-vector_20.json -w "status=%{http_code} time_total=%{time_total}s\n" -H "Authorization: Bearer $MASTER_KEY" -H 'Content-Type: application/json' -d @payloads/vector_20_chat.json http://127.0.0.1:4002/v1/chat/completions > live-after-658ca5c9-chat-vector_20.meta 2>&1
  2. Output: status=200 time_total=6.390040s, curl_exit=0, usage.prompt_tokens=10406, usage.completion_tokens=46

Summary

Case Before status / tokens / seconds After status / tokens / seconds
tiny_text 200 / 12 / 0.169368s 200 / 12 / 0.176362s
vector_20 200 / 30,895 / 3.317411s 200 / 30,895 / 0.195980s
text_500 200 / 1,670,015 / 6.313796s 200 / 1,670,015 / 0.235155s
form_xobject 200 / 491,549 / 37.570648s 200 / 491,549 / 0.328970s
stall test Tiny and four dense calls timed out at 400s / no tokens or time_total Tiny 200 / 12 / 0.007067s; dense calls 200 / 4,014,043 each / 1.323424s, 1.326001s, 1.324115s, 1.325838s
real chat completion 200 / usage.prompt_tokens=10406 / 20.676302s 200 / usage.prompt_tokens=10406 / 6.390040s

Both proxy processes were stopped after all requests. Ports 4001 and 4002 were no longer listening

SDK timing

SDK timing with litellm.token_counter(model="gemini/gemini-3.5-flash-lite"), tokens / seconds

PDF main #45677 this PR (658ca5c)
200 text pages 668,015 / 2.41 668,015 / 0.25 668,015 / 0.28
500 text pages 1,670,015 / 5.82 1,670,015 / 0.37 1,670,015 / 0.23
1 page, 16M chars 4,014,707 / 236.48 18,001,578 / 0.02 4,014,043 / 0.32
1 page vector drawing 1,559 / 0.41 172,213 / 0.20 1,559 / 0.18
20 page vector drawing 30,895 / 4.25 3,443,975 / 0.01 30,895 / 0.13

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • The counter samples 16 evenly spaced pages, so text on unsampled pages can be missed
  • Pre-call token reservations can undercount sampled PDFs, while post-call usage bills real tokens

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

Link to Devin session: https://app.devin.ai/sessions/a4dfaf6f2db049179745dd05c2ff0ba0
Open in Devin Desktop: https://app.devin.ai/desktop/session/a4dfaf6f2db049179745dd05c2ff0ba0?variant=devin
Requested by: @mateo-berri

Bugbot summary

[!NOTE]
Medium Risk
Changes PDF token estimation logic in a complex, performance-sensitive code path; bounded page sampling and operand scaling can diverge from provider-billed usage on edge-case PDFs.

Overview
Replaces unbounded full-page PDF text extraction in token_counter with a bounded PDF pricing pipeline so dense or drawing-heavy documents no longer stall token counting and no longer blow up estimates on vector-only pages.

For long documents, totals are extrapolated from at most 16 evenly spaced pages while keeping separate OpenAI vs Claude page pricing (rendering/image tokens still apply on the Claude path). Oversized page streams are parsed with capped regex scans: inline images are stripped, Form XObject trees are walked with memoization and depth limits, and text is priced from 64 KiB-bounded samples extracted via synthetic pypdf pages, then scaled by decoded string-operand bytes instead of calling extract_text() on the whole stream. Shared form content is scanned once per page, but each draw still uses its inherited Resources context.

Adds extensive unit and CodSpeed benchmark coverage for pathological PDFs (nested/cyclic forms, huge literals, unterminated operators, Identity-H text, etc.).

Reviewed by Cursor Bugbot for commit 45f04df. Bugbot is set up for automated code reviews on this repo. Configure here.

Current follow-up

The update at 45f04dfb05c8c16da02b9999f3b5b891048ab3e2 keeps provider-specific PDF pricing while sharing bounded text sampling across the supported page types

The focused counter and PDF workload run passed 555 tests with one skip. The main update retained the existing deep-form behavior and passed make check without lint or type-count growth

A separate in-process comparison used native compressed documents against main. Ordinary document counts agreed, and both pricing modes kept the text sent for counting within the existing sample limit. Empty and malformed inputs retained their fallback behavior

Repeated forms also retain the resources of each drawing context. Four focused cases fail with the earlier walk and pass with the update, while an unchanged repeat case stays green

Live QA is excluded from this follow-up by request. The earlier provider proof above remains tied to 658ca5c9a90d3f3dcf4556853a72e1815911660e and is not a new-tip live verification claim

Current review status

Repeated drawings of the same form reuse one content scan per page. Each drawing still uses its own fonts and nested forms when calculating totals

The adjacent native-document test covers zero, two and eight drawing contexts, including equal-content streams with separate identities. With the earlier collector, the two populated scan-count cases fail while the empty case and four context-pricing controls pass

Bot reviews and required CI remain separate gates

RachelHuangZW and others added 3 commits October 9, 2026 17:23
Pricing an inline PDF parsed and text-extracted every page on the token
count path, so its cost grew with page count and, superlinearly, with a
single page's content stream. A small compressed upload could hold one of
the four token-count slots for seconds to minutes, stalling every other
request that needs a count on that worker

Text is now extracted from at most EXTRAPOLATION_SAMPLES evenly spaced pages
and scaled to the page count, and a page whose content stream exceeds
PDF_PAGE_MAX_EXACT_CONTENT_BYTES is priced at one token per content byte
instead of being extracted. Every page's rendering tokens are still counted
… pages

Pricing a page list now lives in _price_pdf_pages, which takes any object
shaped like a pypdf page. The bounded-work tests pass fake pages and count
extract_text calls, so extracting every page and sampling afterwards fails
them, as does extracting a page before checking its content size
…s, not every content byte

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@devin-ai-integration

Copy link
Copy Markdown
Contributor

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@litereview

litereview Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

✅ code-review

5/5 · Ready for human review

Scope: full · Full PR review.

No correctness findings.

I re-checked the two earlier findings marked fixed against this head. Both fixes still hold.

Checks and execution details
  • Passed · Real testing evidence (required): Not applicable: no LLM translation changes in the scoped paths. The PR changes litellm/litellm_core_utils/token_counter.py, pyproject.toml, uv.lock, tests/benchmarks/... and tests/unit/.... None of these files is under litellm/llms/** or litellm/litellm_core_utils/prompt_templates/**.

  • Passed · Compatibility requirements (required): No public signature changes. token_counter and _count_inline_pdf_tokens keep their signatures. Unparseable PDFs still return None and fall back to image pricing. Two estimate changes apply:

  • Documents over 16 pages now extrapolate from 16 evenly spaced pages.

  • Pages whose content, including invoked Form XObjects, exceeds 64 KiB are priced by scaling a bounded text sample by decoded string-operand bytes.

The PR states both changes as intended fixes for a regression (#45676). They change estimate values, not a supported input, configuration, default or persisted format. The new pypdf entry goes only into the benchmarks dependency group. No breaking marker is needed.

  • Passed · Changed behavior and result consistency (required): I traced the path from _count_file_tokens and _count_document_tokens through _count_opaque_document_tokens, _count_inline_pdf_tokens, _price_pdf_pages, _pdf_page_text_tokens, _pdf_page_content_metrics, _pdf_bounded_text_samples and _pdf_extract_sample_text.

I stress-tested adversarial content streams with a len/4 counter, via /tmp/stress.py. Each result below is the count, the largest count-function input and the elapsed time:

  • 3.4 MB BI with no ID: 1536, 11 chars, 0.29 s.
  • 2 MB of unclosed (: 601495, 65515 chars, 0.44 s.
  • 8 MB of 200k BT objects: 901534, 29484 chars, 0.2 s.
  • 6.3 MB of escaped literals: 376534, 0.8 s.
  • 7.2 MB of vector-only ops: 1535, 0.31 s.
  • Deeply nested ((: bounded, 0.24 s.
  • 5.2 MB BT with no ET: 1534, 0.11 s.
  • Inline image with no EI: bounded, 0.17 s.
  • Comment lines containing (: 1534.

One case returned None: a malformed hex string &lt;4142 &lt;4142.... The base branch's extract_text also raises on that input (Invalid hexadecimal character), so this is not a regression. Well-formed hex Tj gives 61534.

Repository standards: I read the root AGENTS.md/CONTRIBUTING.md and tests/AGENTS.md/tests/unit/AGENTS.md. The new code uses the repo's Final and *-ok annotation conventions. Ruff reports issues in the test file only on pre-existing lines (714–930: prints, an unused AsyncMock); the PR's hunks do not add them.

  • Passed · Unit tests: tests/unit/litellm_core_utils/test_token_counter.py (optional): Ran .venv/bin/python -m pytest tests/unit/litellm_core_utils/test_token_counter.py -q -n 4: 273 passed, 1 skipped, in 21.4 s.
  • Passed · Benchmarks: tests/benchmarks/test_token_counter_pdf_benchmarks.py (optional): Ran .venv/bin/python -m pytest tests/benchmarks/test_token_counter_pdf_benchmarks.py -q: 14 passed in 6.0 s.

View review · Reviewed 658ca5c9a90d

operands, which no byte-level tokenizer undercuts."""
contents: Final = page.get_contents()
content: Final = contents.get_data() if contents is not None else b""
if len(content) > PDF_PAGE_MAX_EXACT_CONTENT_BYTES:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium · Dense PDF page drawn through a Form XObject still blocks token counting

  1. Start with a one-page base64 PDF whose content stream is just /Fm1 Do. All of the page's text sits inside the referenced Form XObject. PDF generators commonly use this layout for stamped, merged and imposed pages.
  2. A caller sends that PDF to /utils/token_counter, or through any request that runs pre-call token counting.
  3. _pdf_page_text_tokens compares only page.get_contents().get_data() against PDF_PAGE_MAX_EXACT_CONTENT_BYTES. Here that stream is 7 bytes, so the code calls page.extract_text(). pypdf then walks the whole XObject, and count_function tokenizes the full text.
  4. A 9.7 MB XObject took 23.9 s in one count slot, with a single 7.8M-character tokenizer call. Time grows with size: 0.27 s at 152 KB, 2.9 s at 2.4 MB and 7.7 s at 4.9 MB. Several such uploads can fill the worker's count slots again, the same stall [Bug]: Counting tokens for a base64 PDF has no cost bound, so a few uploads stall every token count on the worker #45676 reports.

Smallest fix: measure the page's total content size, including Form XObject streams the page references (recursively), before choosing exact extraction. Price oversized pages by string-operand bytes across those streams too, and add a regression test that builds a PDF with an XObject.

Evidence

Reproducer: /tmp/xo.py builds a one-page PDF with /Contents = /Fm1 Do, plus a Form XObject holding N lines like (Revenue grew ...) Tj 0 -1 Td. It calls _count_inline_pdf_tokens(PDF_DATA_URL_PREFIX + b64, counting_fn) and records the longest string passed to the count function.

Output on this checkout (pypdf 6.19.0):

2000   form bytes 152000   tokens 123534   max count input 122000   secs 0.27
8000   form bytes 608000   tokens 489534   max count input 488000   secs 0.4
32000  form bytes 2432000  tokens 1953534  max count input 1952000  secs 2.88
64000  form bytes 4864000  tokens 3905534  max count input 3904000  secs 7.65
128000 form bytes 9728000  tokens 7809534  max count input 7808000  secs 23.87

Code: content = contents.get_data() ...; if len(content) > PDF_PAGE_MAX_EXACT_CONTENT_BYTES: return _pdf_string_operand_bytes(content); return count_function(page.extract_text() or ""). The check never looks at /Resources /XObject.

The new tests (test_dense_pdf_page_is_priced_without_extracting_its_full_text and the fake-page tests) place text only in the page's direct content stream, so none of them cover this path.

Latest summary by code-review · View this review · Reviewed 89793b5adfd6

@codspeed

codspeed Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will degrade performance by 84.26%

1 warning

⚠️ 1 benchmark is dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

⚡ 1 improved benchmark
❌ 2 regressed benchmarks
✅ 40 untouched benchmarks
🆕 14 new benchmarks

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ test_pdf_page_of_parent_forms_sharing_one_child_form 305.6 ms 30,541.1 ms -99%
❌ test_pdf_page_of_drawing_operators_and_no_image 23.4 ms 66.8 ms -65.03%
⚡ test_pdf_page_of_forms_sharing_one_resources_dictionary 19.7 ms 17.7 ms +11.43%
🆕 test_pdf_invocation_scan_ignores_unterminated_comments N/A 869.1 ms N/A
🆕 test_pdf_string_operand_scan_after_escaped_parentheses N/A 26.6 ms N/A
🆕 test_unterminated_pdf_literal_string_scan N/A 9.6 s N/A
🆕 test_pdf_invocation_scan_with_crlf_comments[23-crlf-comments] N/A 407.5 µs N/A
🆕 test_pdf_invocation_scan_with_crlf_comments[40-crlf-comments-with-trailing-spaces] N/A 505.1 µs N/A
🆕 test_pdf_inline_image_scan_no_ei[100k] N/A 180.9 ms N/A
🆕 test_pdf_inline_image_scan_no_ei[1m] N/A 1.7 s N/A
🆕 test_pdf_inline_image_scan_repeated_bi_without_id N/A 1.1 s N/A
🆕 test_pdf_text_leaf_doubling_form_tree_stays_within_sample_cap N/A 146.5 ms N/A
🆕 test_pdf_text_object_scan[repeated-bt] N/A 1.3 s N/A
🆕 test_pdf_text_object_scan[repeated-et-literal] N/A 2 s N/A
🆕 test_pdf_text_object_scan[repeated-open-literal] N/A 1.8 s N/A
🆕 test_pdf_textless_doubling_form_tree_skips_subtrees N/A 802.4 µs N/A
🆕 test_pdf_16m_text_object_stream_is_capped N/A 4.2 s N/A

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing litellm_bound_pdf_token_count (45f04df) with main (cfddaaf)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (4311254) during the generation of this report, so cfddaaf was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@codecov

codecov Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.13573% with 32 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/litellm_core_utils/token_counter.py 91.13% 32 Missing ⚠️

📢 Thoughts on this report? Let us know!

if not sampled_pages:
return rendering_tokens
sampled_text_tokens: Final = sum(_pdf_page_text_tokens(page, count_function) for page in sampled_pages)
return rendering_tokens + round(sampled_text_tokens * len(pages) / len(sampled_pages))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

High: PDF text omission bypasses budget reservations

reserve_budget_for_request() uses this result for admission, so an authenticated caller can leave all 16 deterministic sample pages blank, put dense text only on omitted pages, and submit concurrent requests whose billable input exceeds the reserved budget. The oversized-page shortcut also assigns zero text tokens to a valid ~70 KB literal operand containing a backslash-newline continuation, despite pypdf extracting its text; preserve conservative bounds for omitted pages and unparsed streams instead of extrapolating attacker-controlled samples or treating unmatched operands as empty.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Continuation half fixed in add181e. Sampling stays by design, since reading every page is the unbounded cost this fixes, and post-call usage still bills real tokens

@veria-ai

veria-ai Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

This PR updates PDF token counting to bound processing of base64 PDFs and price drawing-heavy pages according to their text content.

Five issues have been addressed, but open counting gaps still allow authenticated callers to understate PDF input tokens and bypass budget reservations, including through concurrent requests. PDF literal matching can also exhaust worker memory on a small compressed input. The remaining issues affect both budget enforcement and service availability.

Open issues (3)

Fixed/addressed: 5 · PR risk: 7/10

…traction limit

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

def _pdf_page_form_xobject_content_streams(page: _PdfPage) -> tuple[bytes, ...]:
resources: Final = _pdf_resolve_object(page.get("/Resources"))
if not isinstance(resources, _PdfResourceDictionary):
return ()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium · Shared page resources multiply PDF token counts by the page count

  1. Take a 20-page PDF where every page points to one shared /Resources dictionary. That dictionary lists all 20 per-page Form XObjects (/Fm0 … /Fm19). Each page draws only its own form with /FmN Do, and each form holds about 2.8 KB of text.
  2. A caller sends the PDF to /utils/token_counter, or through any request that runs pre-call token counting.
  3. For each page, _pdf_page_form_xobject_content_streams gathers every Form XObject listed in the page's resources. It does not check which forms the page actually draws. Every page therefore sees all 20 forms, about 115 KB of content, which exceeds PDF_PAGE_MAX_EXACT_CONTENT_BYTES. Each page is then priced from the string operands of all 20 forms.
  4. Main extracts 55,200 characters of text for this PDF. This branch counts 1,158,680 tokens with a len counter, which is 21x too high. At 40 pages the count is 4,573,360 against 110,400 characters, or 41x. Pre-call limit checks can then reject PDFs that main counted correctly.

Smallest fix: include only the XObjects that the content stream names in Do operators, or deduplicate forms across the whole document rather than per page. Add a regression test where pages share one resource dictionary.

Evidence

Reproducer /tmp/shared.py: N pages, each with /Resources 4 0 R (one shared dict listing N Form XObjects) and contents /FmI Do. Each form has 60 lines of (Revenue grew eleven percent while churn fell.) Tj.

Output on this checkout:

pages 2  exact chars 5520   counted(len) 8588    secs 0.01
pages 20 exact chars 55200  counted(len) 1158680 secs 0.03
pages 40 exact chars 110400 counted(len) 4573360 secs 0.21

exact chars is the sum of page.extract_text() lengths, which matches how main prices the text.

Code: _pdf_page_form_xobject_content_streams returns xobjects.values() from the resource dictionary, and _pdf_page_text_tokens sums _pdf_string_operand_bytes across all of those streams. The visited set is scoped to a single page.

Latest summary by code-review · View this review · Reviewed 0aeb504c8d42

…ngs in linear time

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@greptile-apps

greptile-apps Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The follow-up appears safe to merge and fixes the repeated-scan issue.

Summary

PDF counting now samples pages and uses bounded text extraction for oversized content. The latest update reuses each form's content scan while keeping each drawing context's resources separate.

  • PDF estimates sample pages and scale their text costs.
  • Repeated PDF drawings reuse scans while keeping their own text resources.
  • Dense PDF pages are counted from bounded text samples.
  • Token-counter tests no longer enforce a wall-clock limit.

Reviews (16) · Last reviewed commit: "fix(token_counter): align shared stream ..." · Reviewed by Greptile

mateo-berri and others added 3 commits October 20, 2026 20:51
…F string text

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…en finding form draws

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

def _pdf_bounded_operand_sample(samples: Iterable[bytes]) -> bytes:
return bytes(islice(chain.from_iterable(samples), PDF_PAGE_MAX_EXACT_CONTENT_BYTES))


Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium · Pages with a large inline image are priced at about 120x their real token cost

  1. Take a one-page base64 PDF whose content stream holds a 300×300 RGB inline image (BI … ID &lt;270 KB of binary> EI) and one line of text, (Hello world) Tj. Some scanner and report generators write images this way instead of as image XObjects.
  2. A caller sends the PDF to /utils/token_counter, or through any request that runs pre-call token counting.
  3. _pdf_page_text_tokens sees 270,106 content bytes, which is over PDF_PAGE_MAX_EXACT_CONTENT_BYTES (64 KiB). It skips extract_text() and prices the page from PDF_STRING_OPERAND matches. That regex runs over the raw image bytes too, so every stray ( or &lt; inside the binary data counts as a "string operand".
  4. litellm.token_counter(model="gpt-4o") returns 187,794 tokens for this page. main extracts 'Hello world' and adds 1,534 rendering tokens, about 1,540 in total. Pre-call limit checks can now reject PDFs that main counted correctly. This is the same overcount the PR set out to fix for vector drawings, reached through inline image data.

The smallest fix is to remove BI … ID … EI spans from the content (or skip them in the regex scan) before measuring size and string-operand bytes. Add a regression test with an inline image larger than 64 KiB.

Evidence

Reproducer /tmp/inl.py builds one 612×792 page. Its content is q 300 0 0 300 0 0 cm BI /W 300 /H 300 /BPC 8 /CS /RGB ID &lt;random bytes, 'EI' removed> EI Q BT /F1 12 Tf 72 720 Td (Hello world) Tj ET.

Output on this checkout:

exact text: 'Hello world'
branch len-count: 177447 0.008s
token_counter branch: 187794
content bytes 270106

_anthropic_rendered_page_image_tokens(612, 792) = 1534, so main (count_function(page.extract_text()) + rendering) prices the page at about 1,537 tokens.

No new test puts an inline image in a content stream. test_pdf_image_xobject_does_not_trigger_the_content_limit covers only image XObjects.

Latest summary by code-review · View this review · Reviewed 9356f17d22d9

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 48cc412, inline image data between BI and EI is stripped before measuring and scanning page and form streams

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Finding withdrawn

The reply is correct, and the finding is fixed. _pdf_page_text_tokens now runs PDF_INLINE_IMAGE.sub(b" ", ...) on the page content before it measures size or scans string operands. form_metrics_for_xobject does the same for Form XObject streams. With the image bytes gone, the example page stays under the 64 KiB limit and goes through extract_text(). The reproducer now returns 1543 tokens instead of 187,794. Thanks for adding the regression test for both page streams and form streams.

Evidence

litellm/litellm_core_utils/token_counter.py:356 defines PDF_INLINE_IMAGE = re.compile(rb"\bBI\b[\s\S]*?(?:\bID\s[\s\S]*?(?:\sEI\b|\Z)|\Z)").

token_counter.py:1050: content = PDF_INLINE_IMAGE.sub(b" ", contents.get_data() ...) runs before _pdf_page_content_metrics and before the PDF_PAGE_MAX_EXACT_CONTENT_BYTES check.

token_counter.py:971: form streams are stripped the same way before stream_metrics and _pdf_string_operand_sample.

Reproducer output on head: tokens 1543 0.417s render 1534. The original finding reported 187,794.

tests/unit/litellm_core_utils/test_token_counter.py:2330-2360 test_pdf_inline_image_bytes_do_not_push_content_over_the_limit[page-stream|form-stream] asserts that pricing goes through extract_text() and adds only the page text. It passed locally (29 PDF tests passed).

GitHub does not allow this App to resolve this thread. A repository maintainer must do it manually.

Reviewed 48cc412a4795 · View follow-up

…mpled strings

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

…closed text

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@CLAassistant

CLAassistant commented Nov 5, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

mateo-berri and others added 2 commits November 8, 2026 08:48
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@devin-ai-integration

Copy link
Copy Markdown
Contributor

❌ Cannot revive Devin session - the session is too old. Please start a new session instead.

View session

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

PDF_PAGE_MAX_EXACT_CONTENT_BYTES: Final = 64 * 1024
PDF_WHITESPACE_CLASS: Final = b"[\x00\t\n\x0c\r ]"
PDF_HEX_STRING_OPERAND: Final = rb"<[0-9A-Fa-f" + PDF_WHITESPACE_CLASS[1:-1] + rb"]*>"
PDF_LITERAL_STRING_OPERAND: Final = rb"\((?:\\[\x00-\xff]|[^\\()]|\((?:\\[\x00-\xff]|[^\\()])*\)?)*\)?"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium: Full-stream literal matching can exhaust worker memory

_pdf_string_operand_bytes() applies this repeated-alternation pattern to complete decompressed streams before the 64 KiB sample cap; CPython retains matching contexts across these repetitions. (raw.githubusercontent.com) In an isolated helper run, a valid 4.7 KB compressed PDF containing a single 4 MiB literal ending in % hit MemoryError under a 512 MiB address-space limit, while the previous extraction path stayed below 100 MiB RSS.

Replace full-stream uses of this literal matcher—including invocation and inline-image scans—with a bounded-memory syntax scanner so authenticated inline-PDF requests cannot trigger these allocations.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

1 similar comment
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

return _PdfStreamMetrics(b"", 0, 0, inherited_resources, ())
form_resources: Final = _pdf_resolve_object(resolved.get("/Resources"))
resources: Final = form_resources if isinstance(form_resources, _PdfResourceDictionary) else inherited_resources
cache_key: Final = (identity, id(resources))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium: Depth-truncated form metrics are reused for shallow draws

cache_key omits remaining traversal depth, so a form first reached near the 32-level limit is memoized with its text-bearing child omitted and then reused for a later shallow draw. I reproduced a one-page PDF where prepending a deep draw made 44,000 extractable characters in the unchanged shallow draw count as zero text tokens; since this estimate feeds budget reservations, include remaining depth in the cache key and handle truncated branches conservatively.

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit 45f04df. Configure here.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Counting tokens for a base64 PDF has no cost bound, so a few uploads stall every token count on the worker

3 participants