Repository navigation
fix(token_counter): bound base64 PDF counting and price drawing-heavy pages by their text - #47613
mateo-berri wants to merge 27 commits into
Conversation
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>
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
|
@litereview code-review |
✅ code-review5/5 · Ready for human reviewScope: 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
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
I stress-tested adversarial content streams with a len/4 counter, via
One case returned Repository standards: I read the root
View review · Reviewed |
| 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: |
There was a problem hiding this comment.
Medium · Dense PDF page drawn through a Form XObject still blocks token counting
- 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. - A caller sends that PDF to
/utils/token_counter, or through any request that runs pre-call token counting. _pdf_page_text_tokenscompares onlypage.get_contents().get_data()againstPDF_PAGE_MAX_EXACT_CONTENT_BYTES. Here that stream is 7 bytes, so the code callspage.extract_text(). pypdf then walks the whole XObject, andcount_functiontokenizes the full text.- 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
Merging this PR will degrade performance by 84.26%1 warning
Warning Please fix the performance issues or acknowledge them on CodSpeed. Performance ChangesTip Investigate this regression by commenting Comparing Footnotes |
Codecov Report❌ Patch coverage is
📢 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)) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
PR overviewThis 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>
|
@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 () |
There was a problem hiding this comment.
Medium · Shared page resources multiply PDF token counts by the page count
- Take a 20-page PDF where every page points to one shared
/Resourcesdictionary. 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. - A caller sends the PDF to
/utils/token_counter, or through any request that runs pre-call token counting. - For each page,
_pdf_page_form_xobject_content_streamsgathers 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 exceedsPDF_PAGE_MAX_EXACT_CONTENT_BYTES. Each page is then priced from the string operands of all 20 forms. - Main extracts 55,200 characters of text for this PDF. This branch counts 1,158,680 tokens with a
lencounter, 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>
|
@litereview code-review |
[Medium impact] The follow-up appears safe to merge and fixes the repeated-scan issue. SummaryPDF 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.
Reviews (16) · Last reviewed commit: "fix(token_counter): align shared stream ..." · Reviewed by Greptile |
…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>
|
@litereview code-review |
| def _pdf_bounded_operand_sample(samples: Iterable[bytes]) -> bytes: | ||
| return bytes(islice(chain.from_iterable(samples), PDF_PAGE_MAX_EXACT_CONTENT_BYTES)) | ||
|
|
||
|
|
There was a problem hiding this comment.
Medium · Pages with a large inline image are priced at about 120x their real token cost
- Take a one-page base64 PDF whose content stream holds a 300×300 RGB inline image (
BI … ID <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. - A caller sends the PDF to
/utils/token_counter, or through any request that runs pre-call token counting. _pdf_page_text_tokenssees 270,106 content bytes, which is overPDF_PAGE_MAX_EXACT_CONTENT_BYTES(64 KiB). It skipsextract_text()and prices the page fromPDF_STRING_OPERANDmatches. That regex runs over the raw image bytes too, so every stray(or<inside the binary data counts as a "string operand".litellm.token_counter(model="gpt-4o")returns 187,794 tokens for this page.mainextracts'Hello world'and adds 1,534 rendering tokens, about 1,540 in total. Pre-call limit checks can now reject PDFs thatmaincounted 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 <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
There was a problem hiding this comment.
Fixed in 48cc412, inline image data between BI and EI is stripped before measuring and scanning page and form streams
There was a problem hiding this comment.
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>
|
@litereview code-review |
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
bugbot run |
…closed text Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
@litereview code-review |
|
bugbot run |
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>
|
❌ Cannot revive Devin session - the session is too old. Please start a new session instead. |
|
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]|[^\\()])*\)?)*\)?" |
There was a problem hiding this comment.
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.
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>
1 similar comment
| 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)) |
There was a problem hiding this comment.
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.
|
bugbot run |
There was a problem hiding this comment.
✅ 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.
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:
How it solves it:
User Flow
Before: a developer sends a PDF and their token count hangs, and an engineering drawing PDF gets rejected for size
After: dense PDFs return quickly without holding other token counts
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
uv run pytest tests/unit/<your_test_file>.py -vScreenshots / Proof of Fix
Setup
The raw API proof uses
POST /utils/token_counterfor token counts andPOST /v1/chat/completionsfor one real provider call. PDF token-count requests use a text block and a file block withfile.file_dataset to adata:application/pdf;base64,...URL. The chat payload usesmodel=gemini-flash-liteandmax_tokens=50gemini/gemini-3.5-flash-liteis the latest chat-capable Gemini Flash-Lite entry inmodel_prices_and_context_window.json. The newergemini-3.8-flash-lite-ttsentry is for audio speechThe sanitized proxy config was:
No database URL was configured. Both proxies used
--num_workers 1, withDATABASE_URLandDIRECT_URLunsetPayloads were generated with:
The generator copies the PDF builders from
bench.pyandbench_vector.pywithout importing those scripts. Payloads are inpayloads/Before used
wt-mainat7e8be61fa04c253fb950b2d146a6b169472d232. Its import check resolved towt-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 200After used
wt-fixat658ca5c9a90d3f3dcf4556853a72e1815911660e, confirmed bygit rev-parse HEAD. Its import check resolved towt-fix/litellm/__init__.py. After ran on port 4002, and health returned 200$MASTER_KEYwas read from the corresponding proxy process environment for each curl. The Gemini credential and master key were not printed or written to this reportThe Before proxy log is
live-main-proxy-clean.log. The After proxy log islive-after-proxy-658ca5c9.logAfter response JSON and curl metadata are in
/home/ubuntu/lit9408/live-after-658ca5c9-*.jsonand/home/ubuntu/lit9408/live-after-658ca5c9-*.metaBefore (7e8be61)
tiny_text
Command:
Output:
status=200 time_total=0.169368s,curl_exit=0,total_tokens=12,model_used=gemini-3.5-flash-lite,tokenizer_type=openai_tokenizervector_20
Command:
Output:
status=200 time_total=3.317411s,curl_exit=0,total_tokens=30895,model_used=gemini-3.5-flash-lite,tokenizer_type=openai_tokenizertext_500
Command:
Output:
status=200 time_total=6.313796s,curl_exit=0,total_tokens=1670015,model_used=gemini-3.5-flash-lite,tokenizer_type=openai_tokenizerform_xobject
Command:
Output:
status=200 time_total=37.570648s,curl_exit=0,total_tokens=491549,model_used=gemini-3.5-flash-lite,tokenizer_type=openai_tokenizerstall test
Four dense requests ran in the background. After a two-second delay, the tiny request ran, then all four dense requests were awaited
The tiny curl and all four dense curls exited 124 at their
timeout 400limits. No HTTP status,time_total, or token count was returned. The dense.metafiles are emptyreal chat completion with vector_20
Command:
Output:
status=200 time_total=20.676302s,curl_exit=0,usage.prompt_tokens=10406After (658ca5c)
tiny_text
Command:
Output:
status=200 time_total=0.176362s,curl_exit=0,total_tokens=12,model_used=gemini-3.5-flash-lite,tokenizer_type=openai_tokenizervector_20
Command:
Output:
status=200 time_total=0.195980s,curl_exit=0,total_tokens=30895,model_used=gemini-3.5-flash-lite,tokenizer_type=openai_tokenizertext_500
Command:
Output:
status=200 time_total=0.235155s,curl_exit=0,total_tokens=1670015,model_used=gemini-3.5-flash-lite,tokenizer_type=openai_tokenizerform_xobject
Command:
Output:
status=200 time_total=0.328970s,curl_exit=0,total_tokens=491549,model_used=gemini-3.5-flash-lite,tokenizer_type=openai_tokenizerstall test
Four dense requests ran in the background. After a two-second delay, the tiny request ran, then all four dense requests were awaited
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=4014043real chat completion with vector_20
Command:
Output:
status=200 time_total=6.390040s,curl_exit=0,usage.prompt_tokens=10406,usage.completion_tokens=46Summary
tiny_textvector_20text_500form_xobjectstall testtime_totalreal chat completionusage.prompt_tokens=10406/ 20.676302susage.prompt_tokens=10406/ 6.390040sBoth 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 / secondsType
🐛 Bug Fix
Caveats (if any)
Medium
Final Attestation
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
Current follow-up
The update at
45f04dfb05c8c16da02b9999f3b5b891048ab3e2keeps provider-specific PDF pricing while sharing bounded text sampling across the supported page typesThe focused counter and PDF workload run passed 555 tests with one skip. The main update retained the existing deep-form behavior and passed
make checkwithout lint or type-count growthA 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
658ca5c9a90d3f3dcf4556853a72e1815911660eand is not a new-tip live verification claimCurrent 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