fix(tokenizers): price Anthropic document blocks by page count, not as base64 text (#4441)

fix(tokenizers): price Anthropic document blocks by page count, not as
base64 text
---
## Description

The shared content walker (`BaseTokenizer._count_content_parts`, also
used by the Anthropic and OpenAI estimate counters through
`count_content_blocks`) has branches for images, Strands documents and
thinking, but none for Anthropic's native `{"type": "document",
"source": {"type": "base64", "media_type": "application/pdf", "data":
...}}` block. It falls to the JSON catch-all, which prices the base64
string as prose. Measured: a 1 MB PDF inside a `tool_result` counts
**907,006 tokens**, while an image block carrying the same bytes counts
**1,607**. Claude Code's Read tool on a PDF produces exactly this block.

Effect: every request that carries a PDF has a hugely inflated
`tokens_before`, and any transform that removes or dedups the block (a
re-read PDF folded by cross-turn dedup, an offloaded tool result) books
that inflated count as savings. Before #4052, streamed Anthropic turns
also recorded this local estimate as the billed input, so input volume
and cost were inflated the same way.

No existing issue; found while reconciling a user's local input volume
(~13x the provider-reported total) against Anthropic usage.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made
- `headroom/tokenizers/base.py`: new `part_type == "document"` branch
next to the image branch, priced by `_count_document_block` per source
type:
- `base64`: decoded, then 1,500 tokens per page (the low end of
Anthropic's documented 1,500-3,000 text tokens per page, the same
per-page figure the Strands branch already used).
  - `text`, or an untyped source carrying text: counts `data` as text.
  - `content`: walks its blocks.
- `url` / `file`: one nominal page, since the bytes live with the
provider.
  - `title` / `context` strings are counted when present.
- New `_estimate_document_tokens` / `_pdf_page_count`: for bytes with a
`%PDF-` header in the first 1024 bytes, the page count comes from the
PDF's active page tree, read the way a PDF reader reads it
(`_PdfReader`):
- The cross-reference data the last `startxref` points at (a classic
table, an xref stream, a hybrid `/XRefStm`, then each `/Prev` section)
gives `/Root` (the newest trailer's) and each object's location, the
newest entry per number winning.
- The catalog and its `/Pages` node are read only at their xref
location: a type 1 entry must hold `N G obj` with the matching number
and generation; a type 2 entry is index i of object stream M, where M is
read through its own entry, verified the same way, and its header pair i
must name object N. Nothing is ever taken from wherever an object's text
happens to appear in the file, so an unreferenced later definition
(after `%%EOF`, or packed in an object stream the xref does not point
at) never counts.
- Xref streams with a PNG predictor (10-15, each row's own filter byte:
None, Sub, Up, Average, Paeth) are decoded; `/Columns` must match the
`/W` width.
- A stream's data ends at its `/Length`, direct or indirect (`N G R`,
read through the xref and verified as `N G obj <int> endobj`), and only
if `endstream` follows it. The `stream` keyword starts data after any
spaces and an optional CR, CRLF or LF (pypdf's data start).
- Comments and string literals (nested parentheses and escapes included)
are cut from an object's syntax, and every key is read from its own
dictionary's top level only (`_pdf_own_keys` replaces each nested dict,
array and hex string first; an array of plain integers, which cannot
hold a key, stays, for an xref stream's `/W` and `/Index`): `/Root` and
`/Prev` in the trailer or xref stream dict, `/Pages` in the catalog,
`/Count` in the page tree, and `/Length`, `/Filter`, `/DecodeParms`,
`/Type /XRef`, `/Type /ObjStm` and `/First` in stream dicts.
- Shared per-document budgets cover the whole traversal, repeated and
overlapping sections included: 4 MB of bytes scanned or inflated per
file (section dicts, object syntax, xref and object streams), 100,000
xref rows read (table and stream rows, plus one per section and
subsection), and at most 1,000 sections in the `/Prev` chain.
- A missing, damaged or unverifiable xref, a filter other than Flate, an
encrypted or undecodable stream, a `/Count` outside 1-10,000 (read with
at most 5 digits, so no unbounded `int()` runs), or a spent budget gives
the old ~3KB-of-file-per-page size estimate, never a partial read.
Content streams are never read, and the old linear object walk and its
`/Type /Page` fallback are gone.
- The Strands `{"document": {"source": {"bytes": ...}}}` branch now
shares that page estimate; non-PDF bytes keep the old size heuristic
exactly.
- `tests/test_provider_counter_content_blocks.py`: fixtures are real
structured PDFs (catalog, page tree, pages, xref table and trailer, or
an xref stream with an optional Predictor 12 indexing object streams,
with a `prior=` incremental-update mode). 15 document tests (36 cases):
- A 1 MB base64 PDF at top level and inside a `tool_result` counts its
pages through the shared walker and both provider counters.
- Fallbacks: a truncated file (no xref) gets the size estimate; a page
tree inside an object stream counts; no `%PDF-` gives the size estimate;
undecodable base64 is one page; a Strands txt document quoting PDF
syntax keeps the size estimate.
- Only the page tree's object stream is inflated (fonts in other object
streams are never read), within the budget; a file past the row budget
gets the size estimate.
- A one-page PDF whose page text is `hello`, `/Type /Pages /Count
999999`, `/Type /Pages /Count ` plus 5,000 digits, or a fake `2 0 obj <<
/Type /Pages /Count 999 >> endobj`; a page tree dict with a comment and
a nested string quoting `/Count 999`; a private `/Count 9999` nested
ahead of the real `/Count 1` in a dict or in an array next to a hex
string. Each is 1 page; a real `/Count 1000000` and a 5,000-digit
`/Count` give the size estimate (1 page at this size).
- Decoys behind nested keys: a private `/Pages` in the catalog and a
private `/Root` in the trailer, each pointing at a decoy tree with
`/Count 9999`; a stream marked `/Type /ObjStm` only in private data; a
private `/Length 0` ahead of a stream's own. Every case is 1 page.
- Stream data, each with page text quoting `endstream 2 0 obj << /Type
/Pages /Count 9999 >> endobj`: JerrettDavis's `/Length 6 0 R` case; the
same with a fake `6 0 obj 24 endobj` in the page text; the length read
through an xref stream and through `/Prev`; a lone CR after `stream`; a
length packed in an object stream, a wrong length, a reference to no
object and no `/Length`. Each is 1 page, since the page tree is read at
its xref offset and content is never walked.
- Shared budgets: JerrettDavis's two compressed xref sections of 100,000
entries each give the size estimate, while a normal update through one
compressed section still counts; 100 sections each inflating to 4 MB of
rows inflate once, then give the size estimate; 300 table sections whose
trailer dicts stay open (each holding every later one) give the size
estimate.
- File order: a later `2 0 obj` with `/Count 9999` that the xref does
not list, the same packed in an unlisted object stream, and in a listed
one: each is 1 page.
- A Predictor 12 xref stream whose rows cycle all five PNG filter types
prices 12 pages, with the tree at top level and packed.
- An incremental update that moves 2 of 5 pages under a new tree prices
2 pages.
- Text, content (block list or plain string) and titled sources count
their text; URL and file sources are one page.

## Testing
- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
$ uv run --frozen --extra dev pytest tests/test_provider_counter_content_blocks.py tests/test_tokenizers.py tests/test_strands_tokenizer.py tests/test_image_decoder_guard.py -q
117 passed, 15 skipped in 2.56s

# every test file that imports a tokenizer, counts messages or builds a token counter (95 files)
$ uv run --frozen --extra dev pytest $(grep -rlE "headroom\.tokenizers|count_messages|count_content_blocks|get_token_counter" tests --include='*.py') -q
1827 passed, 74 skipped, 4 warnings in 69.32s

# the new tests against adcc4f1d's estimator (base.py swapped back, tests kept)
$ uv run --frozen --extra dev pytest tests/test_provider_counter_content_blocks.py -q
12 failed, 36 passed
# failing: the 3 shared-budget tests, the 3 file-order cases (14,998,500 tokens each),
# and 6 cases whose expectation changed with the reader: 4 stream-length cases that gave
# the size estimate now count 1 page (content is never walked), the truncated file now
# takes the size estimate (no xref), and only the page tree's object stream is inflated

# the same against 78c22acc (shared budgets only)
9 failed, 39 passed
# the 3 shared-budget tests pass; the 3 file-order cases and the 6 changed expectations fail

$ uvx ruff@0.17.0 check headroom/tokenizers/base.py tests/test_provider_counter_content_blocks.py
All checks passed!
$ uvx ruff@0.17.0 format --check headroom/tokenizers/base.py tests/test_provider_counter_content_blocks.py
2 files already formatted
$ uv run --frozen --extra dev mypy headroom/tokenizers/base.py
Success: no issues found in 1 source file
```

Every well-formed fixture opens in pypdf 6.21.2 with `strict=True` at
the expected page count: the three file-order fixtures at 1 page with
the real tree's `/Count 1` (pypdf ignores the unreferenced decoy too),
the Predictor 12 fixtures at 12 pages (tree at top level and packed),
and all 9 stream-data fixtures at 1 page with `/Count 1` (pypdf, like
this reader, does not read the broken content streams to list pages);
the absurd-count and truncated fixtures are malformed on purpose. pypdf
was used only for that check and is not a dependency.

## Real Behavior Proof
- Environment: macOS, Python 3.11.13, head f07addcd (upstream/main
a616232d merged), real `headroom proxy` process on port 6811 with a
clean temporary HOME, telemetry and beacon off.
- Exact command / steps: Started a controlled upstream (a local stub
that answers every `POST /v1/messages` with a fixed Anthropic-shaped
reply and never calls out) on 6812, then `uv run --frozen --extra proxy
python -m headroom.cli proxy --port 6811 --no-http2 --no-rate-limit
--no-subscription-tracking --anthropic-api-url http://127.0.0.1:6812
--log-file <tmp>/requests.jsonl`. Sent `POST /v1/messages` with a base64
`document` block plus a text block for each PDF below, timed each
request, and read `input_tokens_original` from the proxy's request log.
Repeated with adcc4f1d's `base.py` (and, for the earlier tables,
6d8e9d26's, 0ecaceb9's and c4d50305's).
- Observed result: adcc4f1d priced all three file-order decoys at
14,998,512 tokens; this head prices them at 1,512, the same as the
control. JerrettDavis's two 100,000-entry sections took 0.15 s on
adcc4f1d and 0.01 s here, priced by the size estimate (1 page at 2,373
bytes). 1,000 chained xref streams of 4 MB of rows each took 83.22 s on
adcc4f1d (about 14 s per count, counted several times per request) and
6.81 s here, priced by the size estimate of the 4 MB file. Of those 6.81
s, `_estimate_document_tokens` takes 0.001 s; 6.8 s is the content
router's own `tokens_before` (`Transform content_router ... [6792.3ms]`
in the proxy log), which BPE-tokenizes `str(content)` and is unchanged
by this PR (see Additional Notes); a 4 MB control of random bytes takes
0.74 s. All requests HTTP 200, no traceback in the proxy log. Corpus:
`_pdf_page_count` on 2,207 local PDFs that Spotlight gives a page count
for (`kMDItemNumberOfPages`, 15,663 pages): 2,201 exact on adcc4f1d,
2,200 on this head. 5 gained (iText, Ghostscript, Canva, ReportLab and a
94-page file adcc4f1d counted as 93); 6 moved to the size estimate: 4
encrypted files whose page tree sits in an encrypted object stream
(pypdf decrypts them with the empty user password; this reader does not
decrypt) and 2 with a damaged xref stream (iTextSharp 4.0.2,
CrawfordTech PDF Driver), both rejected by pypdf strict. 7 of 2,207
(0.32%) take the size estimate in all, the 7th an encrypted file that
was already 0 on adcc4f1d. Earlier rounds' proofs are kept in the tables
below.
- Not tested: counts against Anthropic's `count_tokens` API (1,500 per
page is the documented lower bound, page images are not added); xref or
object streams with a filter other than Flate, `/DecodeParms` given as
an array, and encrypted object streams (all take the size estimate);
Bedrock and Vertex document shapes.

| PDF sent to the proxy (this round) | adcc4f1d | this head |
| --- | --- | --- |
| one page, page tree `/Count 1` (control) | 1,512 (HTTP 200, 0.19 s) |
1,512 (HTTP 200, 0.18 s) |
| later `2 0 obj << /Type /Pages /Count 9999 >>` the xref does not list
| 14,998,512 (HTTP 200) | 1,512 (HTTP 200) |
| the same object 2 packed in an unlisted object stream | 14,998,512
(HTTP 200) | 1,512 (HTTP 200) |
| the same object 2 packed in a listed object stream (the xref puts 2 at
its own offset) | 14,998,512 (HTTP 200) | 1,512 (HTTP 200) |
| Predictor 12 xref stream, 12-page tree | 18,012 (HTTP 200) | 18,012
(HTTP 200) |
| 2 compressed xref sections x 100,000 entries (JerrettDavis) | 1,512
(HTTP 200, 0.15 s) | 1,512, size estimate (HTTP 200, 0.01 s) |
| one page plus a 4 MB stream of random bytes (size control) | 1,512
(HTTP 200, 0.72 s) | 1,512 (HTTP 200, 0.74 s) |
| 1,000 chained xref streams, 4 MB of rows each (4.0 MB file) | 1,512
(HTTP 200, 83.22 s) | 2,011,512, size estimate (HTTP 200, 6.81 s) |

| PDF sent to the proxy (previous round) | 6d8e9d26 | adcc4f1d |
| --- | --- | --- |
| one page, direct `/Length`, page tree `/Count 1` (control) | 1,512
(HTTP 200) | 1,512 (HTTP 200) |
| `/Length 6 0 R`, page text `endstream 2 0 obj << /Type /Pages /Count
9999 >> endobj` | 14,998,512 (HTTP 200) | 1,512 (HTTP 200) |
| same, plus `6 0 obj 24 endobj` in the page text | 14,998,512 (HTTP
200) | 1,512 (HTTP 200) |
| `stream` + lone CR, bare `endobj 2 0 obj << /Type /Pages /Count 9999
>> endobj` after `ET` | 14,998,512 (HTTP 200) | 1,512 (HTTP 200) |

| PDF sent to the proxy (second round) | 0ecaceb9 | 6d8e9d26 |
| --- | --- | --- |
| one page, page tree `/Count 1` (control) | 1,512 (HTTP 200) | 1,512
(HTTP 200) |
| page tree `/PieceInfo << /Example << /Private << /Count 9999 >> >> >>
/Count 1` | 14,998,512 (HTTP 200) | 1,512 (HTTP 200) |
| catalog `/PieceInfo << /Private << /Pages 7 0 R >> >>` ahead of
`/Pages 2 0 R` | 14,998,512 (HTTP 200) | 1,512 (HTTP 200) |
| trailer `/Private << /Root 6 0 R >>` ahead of `/Root 1 0 R` |
14,998,512 (HTTP 200) | 1,512 (HTTP 200) |

| PDF sent to the proxy (first round) | c4d50305 | 0ecaceb9 |
| --- | --- | --- |
| one page, page text `hello` | 1,511 (HTTP 200) | 1,511 (HTTP 200) |
| one page, page text `/Type /Pages /Count 999999` | 1,499,998,511 (HTTP
200) | 1,511 (HTTP 200) |
| one page, page text `/Type /Pages /Count ` + 5,000 digits | HTTP 500,
ValueError | 1,511 (HTTP 200) |
| incremental update, old tree 5 pages, active tree 2 | 7,511 (HTTP 200)
| 3,011 (HTTP 200) |

`_pdf_page_count` alone, this round (corpus: one warm-up call, then one
timed call per file; synthetic files built in-process):

| | adcc4f1d | this head |
| --- | --- | --- |
| 2,231 local PDFs, p50 / p90 / p99 / max ms | 0.39 / 2.53 / 12.0 / 57.2
| 0.05 / 0.30 / 1.6 / 14.5 |
| synthetic 30 MB, 800K page objects | 108 ms | 11 ms |
| synthetic 800K small dict objects | 0.13 s | 0.02 s |
| synthetic 99K page objects, no trailer | 0.64 s (99,000 pages) | 0.00
s (size estimate) |
| synthetic 99K streams with a direct `/Length` | 0.79 s | 0.02 s |
| synthetic 49K streams with an indirect `/Length`, one 98K-row xref
table | 0.36 s | 0.04 s |
| 100 chained xref streams, 4 MB of rows each (0.4 MB file) | 1.45 s |
0.00 s (size estimate) |
| 1,000 chained xref streams, 4 MB of rows each (4.0 MB file) | 14.39 s
| 0.00 s (size estimate) |
| 1,000 table sections whose trailer dicts stay open (0.6 MB file) |
6.69 s | 0.08 s (size estimate) |
| catalog padded with 20 MB of `()` pairs | 6.87 s | 1.34 s |
| catalog padded with 20 MB of `[]` pairs | 4.33 s | 0.04 s |

## Runtime Rollout Safety
- Rollout-managed feature(s): None.
- Minimum rollout channel: Stable.
- Stable/default behavior changed: Yes, token estimates for messages
that carry a `document` block drop to the page estimate, read from the
PDF's active page tree at the location its cross-reference data gives,
each object verified and each key from its own dictionary, within shared
per-document budgets, or the size estimate instead; text, image, tool
and Strands non-PDF blocks are unchanged (pinned by the existing tests).
- Kill switch / disable path: Not applicable, this corrects an estimate
and has no flag.
- Unsafe override required: No.
- Qualification impact: tokens_before and savings fall for requests that
carry PDFs; that drop is the correction.
- Rollback path: Revert this PR's commits.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` - it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Screenshots (if applicable)

Not applicable.

## Additional Notes
- Documentation: no user-facing docs describe token estimation for
documents, so none changed.
- Review follow-ups: shared per-document budgets for xref rows,
accumulated entries and scanned or inflated bytes answer JerrettDavis's
fourth review (per-section limits while entries accumulated across the
`/Prev` chain); reading the catalog and page tree at their xref location
closes the file-order limit this body listed before (an unreferenced
later definition won), which we found ourselves and was not part of his
review; xref-resolved indirect lengths and the lone-CR stream start
answer his third review; own-dictionary key reads answer his second
review (nested `/Count`); the active-tree resolution answers his first
review and the incremental-update thread; the `%PDF-` header gate for
Strands bytes is unchanged.
- Known limits: a missing, damaged or unverifiable xref, an encrypted
object stream holding the page tree, a filter other than Flate on an
xref or object stream, and a download cut off before its xref all give
the size estimate rather than a page count (7 of 2,207 local PDFs,
above). Readers that rebuild a damaged xref by scanning the file (pypdf
non-strict) count the 2 damaged-xref files; doing that here would bring
back the file-order problem, so they keep the size estimate.
- Cost: the budgets bound every case, and the slowest synthetic inputs
left are a catalog of 20 MB of `()` pairs at 1.34 s (6.87 s on adcc4f1d,
cut at the 4 MB scan budget), a catalog of 3.9 MB of `[]` pairs just
under that budget at 0.83 s, and a Paeth-predicted xref stream of 99K
rows of 27 bytes at 0.45 s.
- Follow-up, not in this PR: OpenAI Responses `input_file` parts with
base64 `file_data` have no branch in the walker either and reach the
same catch-all. The content router's own `tokens_before`
(`headroom/transforms/content_router.py` lines 6109 and 7071 on
upstream/main) counts `str(m["content"])` as text, so a base64 document
still costs one BPE pass there and its logged transform counts still
price the base64 (645 tokens for the 600-byte control above); the
router's net-cost path already uses `count_content_blocks`
(`_netcost_message_tokens`), and these two sums could do the same.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
This commit is contained in:
gglucass
2026-10-30 09:12:20 -05:00
committed by GitHub
co-authored by Claude Opus 5.5 JerrettDavis
parent 1fe8549f9c
commit fc1ba891bf
2 changed files with 822 additions and 2 deletions
+367 -2
View File
@@ -6,7 +6,11 @@ tokenizer backends must implement.
from __future__ import annotations
import base64
import binascii
import json
import re
import zlib
from abc import ABC, abstractmethod
from collections.abc import Callable
from typing import Any, Protocol, runtime_checkable
@@ -25,6 +29,323 @@ _COUNT_CACHE_MIN_CHARS = 256
_COUNT_CACHE_MAX_ENTRIES = 4096
_COUNT_CACHE_MAX_CHARS = 8_000_000
#: Document pricing (see ``BaseTokenizer._estimate_document_tokens``). Anthropic
#: documents ~1,500-3,000 text tokens per PDF page; the low end is used. Pages
#: come from the PDF's active page tree, read the way a PDF reader reads it: the
#: cross-reference data the last ``startxref`` chains to (tables and xref streams,
#: through ``/Prev``) gives ``/Root`` and where each object lives, and the catalog
#: and its ``/Pages`` node are read there (an ``N G obj`` at that offset, or entry
#: i of an object stream), each verified, never wherever their text happens to
#: appear in the file. Comments and string literals are cut from an object's
#: syntax, and each key comes from its own dictionary's top level, never from a
#: dict, array or hex string nested in it. A missing, damaged or unverifiable xref,
#: an absurd ``/Count``, or a spent budget gives ~3KB of file per page instead.
_DOCUMENT_TOKENS_PER_PAGE = 1500
_DOCUMENT_BYTES_PER_PAGE = 3000
_PDF_MAX_PAGES = 10_000 # a larger /Count is treated as malformed, not priced
# One budget per file of bytes scanned or inflated, and one of xref rows read
# (repeats included), so no chain of sections or streams can multiply the work.
_PDF_OBJECT_STREAM_MAX_BYTES = 4_000_000
_PDF_MAX_OBJECTS = 100_000
_PDF_MAX_XREF_SECTIONS = 1_000 # a longer /Prev chain is treated as malformed
# Each pattern opens with a lookahead on its first byte so the scan skips binary fast.
# A stream's data starts after its keyword, any spaces and an EOL if present (a
# lone CR too): the spec requires CRLF or LF, but readers accept the others.
_PDF_SYNTAX_STOP = re.compile(
rb"(?=[%(se])(?:%[^\r\n]*|\(|(?<![A-Za-z/])(?:stream *(?:\r\n?|\n)?|endobj|startxref))"
)
_PDF_STRING_TOKEN = re.compile(rb"\\.|[()]", re.S)
_PDF_STREAM_LENGTH = re.compile(rb"/Length\s+(\d{1,10})(?!\d|\s+\d+\s+R)")
_PDF_STREAM_END = re.compile(rb"\s*endstream")
_PDF_ROOT = re.compile(rb"/Root\s+(\d{1,10})\s+(\d{1,5})\s+R")
_PDF_PAGES = re.compile(rb"/Pages\s+(\d{1,10})\s+(\d{1,5})\s+R")
# A longer digit run never reaches int(): it is malformed, and the size estimate stands in.
_PDF_COUNT = re.compile(rb"/Count\s+(\d{1,5})(?!\d)")
_PDF_FIRST = re.compile(rb"/First\s+(\d{1,10})")
_PDF_NESTING = re.compile(rb"<<|>>|<[^<>]*>|(\[[\d\s]*\])|\[|\]")
_PDF_LENGTH_REF = re.compile(rb"/Length\s+(\d{1,10})\s+(\d{1,5})\s+R")
_PDF_LENGTH_OBJECT = re.compile(rb"\s*(\d{1,10})\s+(\d{1,5})\s+obj\s*(\d{1,10})\s*endobj")
_PDF_OBJECT_HEADER = re.compile(rb"\s*(\d{1,10})\s+(\d{1,5})\s+obj\b")
_PDF_STARTXREF = re.compile(rb"startxref\s+(\d{1,10})")
_PDF_XREF_TABLE = re.compile(rb"\s*xref\b")
_PDF_XREF_SUBSECTION = re.compile(rb"\s*(\d{1,10})\s+(\d{1,5})\s+")
_PDF_XREF_ROW = re.compile(rb"(\d{10}) (\d{5}) ([nf])")
_PDF_XREF_TRAILER = re.compile(rb"\s*trailer\b")
_PDF_XREF_WIDTHS = re.compile(rb"/W\s*\[\s*(\d)\s+(\d)\s+(\d)\s*\]")
def _pdf_syntax(data: bytes, pos: int = 0, end: int | None = None) -> tuple[bytes, int, bool]:
"""PDF syntax from ``pos`` to the next ``stream``/``endobj``/``startxref`` (or ``end``),
minus comments and string literals; also where it stopped and whether a stream
starts there."""
end = len(data) if end is None else min(end, len(data))
parts = []
while match := _PDF_SYNTAX_STOP.search(data, pos, end):
parts.append(data[pos : match.start()])
pos = match.end()
if match.group() == b"(":
depth = 0 # a string literal may nest balanced parentheses
pos = end
for token in _PDF_STRING_TOKEN.finditer(data, match.start(), end):
depth += {b"(": 1, b")": -1}.get(token.group(), 0)
if not depth:
pos = token.end()
break
elif not match.group().startswith(b"%"):
return b"".join(parts), pos, match.group().startswith(b"stream")
return b"".join(parts) + data[pos:end], end, False
def _pdf_own_keys(syntax: bytes, nested: list[bytes] | None = None) -> bytes:
"""The top level of the dictionary ``syntax`` opens with, each nested dict, array
and hex string cut to ``_<i>``: a key read from it is that dictionary's own. An
array of plain integers holds no key, so it stays (an xref stream's ``/W`` and
``/Index``). ``nested`` collects what was cut, ``_<i>`` being entry i."""
body = syntax.lstrip(b"\0\t\n\x0c\r ")
if not body.startswith(b"<<"):
return b""
cut: list[bytes] = [] if nested is None else nested
parts: list[bytes] = []
depth = pos = opened = 0
for token in _PDF_NESTING.finditer(body):
step = {b"<<": 1, b"[": 1, b">>": -1, b"]": -1}.get(token.group(), 0)
if depth == 1:
parts.append(body[pos : token.start()])
if step < 0:
break # the dictionary's own end
if token.group(1):
parts.append(token.group(1))
else:
parts.append(b" _%d " % len(cut))
opened = token.start()
if not step:
cut.append(token.group()) # a hex string
depth += step
if step < 0 and depth == 1:
cut.append(body[opened : token.end()])
if not depth:
break
pos = token.end()
return b"".join(parts)
def _pdf_png_rows(data: bytes, columns: int) -> bytes:
"""``data`` decoded from PNG predictor rows: each a filter byte, then ``columns``
bytes, one per sample (an xref stream's /Colors 1 /BitsPerComponent 8)."""
out, prior = bytearray(), bytes(columns)
for at in range(0, len(data), columns + 1):
kind, row = data[at], bytearray(data[at + 1 : at + 1 + columns])
if kind == 2:
row = bytearray((a + b) & 255 for a, b in zip(row, prior))
elif kind:
for i in range(len(row)):
left, up, corner = row[i - 1] if i else 0, prior[i], prior[i - 1] if i else 0
if kind == 1:
row[i] = (row[i] + left) & 255
elif kind == 3:
row[i] = (row[i] + (left + up) // 2) & 255
elif kind == 4:
guess = left + up - corner # Paeth: the neighbour nearest the guess
pa, pb, pc = abs(guess - left), abs(guess - up), abs(guess - corner)
row[i] = (
row[i] + (left if pa <= pb and pa <= pc else up if pb <= pc else corner)
) & 255
else:
raise _PdfUnreadable
out += row
prior = bytes(row)
return bytes(out)
class _PdfUnreadable(Exception):
"""The PDF fails verification or a budget runs out: its size estimate stands in."""
class _PdfReader:
"""Reads objects at the locations the PDF's cross-reference data gives for them."""
def __init__(self, doc: bytes) -> None:
self.doc = doc
self.budget = _PDF_OBJECT_STREAM_MAX_BYTES
self.rows = _PDF_MAX_OBJECTS
self.entries: dict[int, tuple[int, int, int]] = {} # number: (type, field 2, field 3)
self.packed: dict[int, tuple[list[bytes], int, bytes]] = {} # header, /First, data
self.root: re.Match[bytes] | None = None
eof = doc.rfind(b"%%EOF") # bytes after the last revision hold no objects
last = doc.rfind(b"startxref", 0, len(doc) if eof < 0 else eof)
start = _PDF_STARTXREF.match(doc, last) if last >= 0 else None
todo = [int(start.group(1))] if start else []
seen: set[int] = set()
while todo:
at = todo.pop(0)
if at in seen:
continue
seen.add(at)
if len(seen) > _PDF_MAX_XREF_SECTIONS:
raise _PdfUnreadable
self.spend(rows=1)
table = _PDF_XREF_TABLE.match(doc, at)
keys = self.read_table(table.end()) if table else self.read_xref_stream(at)
self.root = self.root or _PDF_ROOT.search(keys) # the newest trailer's
for key in (rb"/XRefStm", rb"/Prev"): # a table's stream entries, then older sections
if found := re.search(key + rb"\s+(\d{1,10})(?!\d)", keys):
todo.append(int(found.group(1)))
if not self.root:
raise _PdfUnreadable
def spend(self, scanned: int = 0, rows: int = 0) -> None:
self.budget -= scanned
self.rows -= rows
if self.budget < 0 or self.rows < 0:
raise _PdfUnreadable
def keys_at(self, pos: int, nested: list[bytes] | None = None) -> tuple[bytes, int, bool]:
"""Own keys of the dictionary at ``pos``, where its syntax stops, and whether a
stream starts there; the scan is charged to the budget."""
syntax, stop, is_stream = _pdf_syntax(self.doc, pos, pos + self.budget + 1)
self.spend(stop - pos) # a scan past the budget stops one byte beyond it
return _pdf_own_keys(syntax, nested), stop, is_stream
def read_table(self, pos: int) -> bytes:
while sub := _PDF_XREF_SUBSECTION.match(self.doc, pos):
self.spend(rows=int(sub.group(2)) + 1) # also caps the distinct counts compiled
rows = re.compile(rb"(?:\d{10} \d{5} [nf]\s{1,2}){%s}" % sub.group(2))
if not (block := rows.match(self.doc, sub.end())):
raise _PdfUnreadable
for number, (offset, gen, kind) in enumerate(
_PDF_XREF_ROW.findall(block.group()), int(sub.group(1))
):
if kind == b"n": # the newest section is read first, so its entry wins
self.entries.setdefault(number, (1, int(offset), int(gen)))
pos = block.end()
if not (trailer := _PDF_XREF_TRAILER.match(self.doc, pos)):
raise _PdfUnreadable
return self.keys_at(trailer.end())[0]
def read_xref_stream(self, at: int) -> bytes:
header = _PDF_OBJECT_HEADER.match(self.doc, at)
nested: list[bytes] = []
keys, data = self.stream(header.end(), nested) if header else (b"", b"")
widths = _PDF_XREF_WIDTHS.search(keys)
size = re.search(rb"/Size\s+(\d{1,10})", keys)
if not (widths and size and re.search(rb"/Type\s*/XRef\b", keys)):
raise _PdfUnreadable
kind, field, gen = map(int, widths.groups())
width = kind + field + gen
predicted = 0
if parms := re.search(rb"/DecodeParms\s+_(\d{1,4})(?!\d)", keys):
raw = nested[int(parms.group(1))] if int(parms.group(1)) < len(nested) else b""
if not raw.startswith(b"<<"):
raise _PdfUnreadable # an array, or "_<i>" typed into the dict itself
values = _pdf_own_keys(raw)
predictor = re.search(rb"/Predictor\s+(\d{1,2})(?!\d)", values)
columns = re.search(rb"/Columns\s+(\d{1,2})(?!\d)", values)
if re.search(rb"/Colors\s+(?!1(?!\d))|/BitsPerComponent\s+(?!8(?!\d))", values):
raise _PdfUnreadable
if predictor and int(predictor.group(1)) >= 10:
predicted = 1
if int(columns.group(1) if columns else 1) != width:
raise _PdfUnreadable
elif predictor and int(predictor.group(1)) != 1:
raise _PdfUnreadable # TIFF prediction: not written for xref streams
if not width:
raise _PdfUnreadable
index = re.search(rb"/Index\s*\[([\d\s]*)\]", keys)
bounds = (index.group(1) if index else b"0 " + size.group(1)).split()
if any(len(n) > 10 for n in bounds):
raise _PdfUnreadable
starts, lengths = [int(n) for n in bounds[::2]], [int(n) for n in bounds[1::2]]
count = min(sum(lengths), len(data) // (width + predicted))
self.spend(rows=count)
data = data[: count * (width + predicted)]
if predicted:
data = _pdf_png_rows(data, width)
numbers = (n for a, length in zip(starts, lengths) for n in range(a, a + length))
for number, at_row in zip(numbers, range(0, count * width, width)):
entry = data[at_row : at_row + width]
entry_type = int.from_bytes(entry[:kind] or b"\x01", "big")
if entry_type in (1, 2):
second = int.from_bytes(entry[kind : kind + field], "big")
self.entries.setdefault(
number, (entry_type, second, int.from_bytes(entry[kind + field :], "big"))
)
return keys
def stream(self, pos: int, nested: list[bytes]) -> tuple[bytes, bytes]:
"""Own keys and inflated data of the stream object whose dict starts at ``pos``.
Its end must be verified: ``endstream`` right after ``/Length`` bytes."""
keys, start, is_stream = self.keys_at(pos, nested)
length = _PDF_STREAM_LENGTH.search(keys)
size = int(length.group(1)) if length else self.integer(_PDF_LENGTH_REF.search(keys))
if not (is_stream and _PDF_STREAM_END.match(self.doc, start + size)):
raise _PdfUnreadable
data = self.doc[start : start + size]
if b"/Filter" not in keys:
if b"/DecodeParms" in keys:
raise _PdfUnreadable
return keys, data
if not re.search(rb"/Filter\s*/FlateDecode\b", keys) or self.budget <= 0:
raise _PdfUnreadable # (max_length 0 would mean no limit)
inflate = zlib.decompressobj()
try:
data = inflate.decompress(data, self.budget)
except zlib.error:
raise _PdfUnreadable from None
if inflate.unconsumed_tail:
raise _PdfUnreadable
self.spend(len(data))
return keys, data
def integer(self, ref: re.Match[bytes] | None) -> int:
"""The integer an indirect ``/Length`` names, at its xref offset."""
entry = self.entries.get(int(ref.group(1))) if ref else None
value = _PDF_LENGTH_OBJECT.match(self.doc, entry[1]) if entry and entry[0] == 1 else None
if not (ref and entry and value and value.group(1, 2) == ref.group(1, 2)):
raise _PdfUnreadable
if int(ref.group(2)) != entry[2]: # the generation the xref holds
raise _PdfUnreadable
return int(value.group(3))
def get(self, ref: re.Match[bytes] | None) -> bytes:
"""Own keys of the object ``ref`` names, read where the xref says it lives."""
number, gen = (int(ref.group(1)), int(ref.group(2))) if ref else (-1, -1)
kind, where, extra = self.entries.get(number, (0, 0, 0))
if kind == 1 and extra == gen:
header = _PDF_OBJECT_HEADER.match(self.doc, where)
if header and (int(header.group(1)), int(header.group(2))) == (number, gen):
return self.keys_at(header.end())[0]
elif kind == 2 and gen == 0:
head, first, data = self.packed.get(where) or self.unpack(where)
i = 2 * extra # entry i of the stream's header of (number, offset) pairs
if i + 1 < len(head) and int(head[i]) == number:
stop = first + int(head[i + 3]) if i + 3 < len(head) else len(data)
return _pdf_own_keys(_pdf_syntax(data[first + int(head[i + 1]) : stop])[0])
raise _PdfUnreadable
def unpack(self, number: int) -> tuple[list[bytes], int, bytes]:
"""An object stream's header numbers, its /First and its inflated data."""
kind, where, gen = self.entries.get(number, (0, 0, 0))
header = _PDF_OBJECT_HEADER.match(self.doc, where) if kind == 1 else None
if not (header and (int(header.group(1)), int(header.group(2))) == (number, gen)):
raise _PdfUnreadable
keys, data = self.stream(header.end(), [])
first = _PDF_FIRST.search(keys)
if not (first and re.search(rb"/Type\s*/ObjStm\b", keys)) or b"/DecodeParms" in keys:
raise _PdfUnreadable
head = re.findall(rb"\d{1,10}", data[: int(first.group(1))])
self.packed[number] = head, int(first.group(1)), data
return self.packed[number]
def _pdf_page_count(doc: bytes) -> int:
"""Pages in the PDF's active page tree, else 0."""
try:
reader = _PdfReader(doc)
count = _PDF_COUNT.search(reader.get(_PDF_PAGES.search(reader.get(reader.root))))
except _PdfUnreadable:
return 0
return int(count.group(1)) if count and 0 < int(count.group(1)) <= _PDF_MAX_PAGES else 0
class TokenCountCache:
"""Exact memo for ``count_text``.
@@ -273,6 +594,12 @@ class BaseTokenizer(ABC):
# This prevents the base64 blob from being json.dumps'd and counted
# as text tokens (1MB image = ~330K fake tokens without this).
total += 1600
elif part_type == "document":
# Anthropic document block. Its base64 PDF used to reach the
# JSON catch-all below and be priced as prose: a 1 MB PDF
# counted ~907K tokens, against the ~1,600 an image of the
# same bytes gets.
total += self._count_document_block(part)
elif part_type in ("input_audio", "audio"):
# Audio has fixed token cost, not tokenized as text
total += 200
@@ -332,8 +659,7 @@ class BaseTokenizer(ABC):
source = doc.get("source", {})
doc_bytes = source.get("bytes", b"")
if isinstance(doc_bytes, bytes | bytearray):
estimated_pages = max(1, len(doc_bytes) // 3000)
total += estimated_pages * 1500
total += self._estimate_document_tokens(bytes(doc_bytes))
else:
total += self.count_text(str(doc_bytes))
elif not part_type and "image" in part:
@@ -404,6 +730,45 @@ class BaseTokenizer(ABC):
)
return int(self.count_text(sample) * len(s) / len(sample))
def _count_document_block(self, part: dict[str, Any]) -> int:
"""Price an Anthropic ``document`` block by its source type."""
source = part.get("source")
source = source if isinstance(source, dict) else {}
source_type = source.get("type")
if source_type == "base64":
try:
doc_bytes = base64.b64decode(source.get("data") or b"")
except (binascii.Error, TypeError, ValueError):
doc_bytes = b""
total = self._estimate_document_tokens(doc_bytes)
elif source_type == "content":
content = source.get("content")
if isinstance(content, list):
total = self._count_content_parts(content)
else:
total = self.count_text(str(content or ""))
elif source_type in ("url", "file"):
# The bytes live with the provider; one page as a nominal estimate.
total = _DOCUMENT_TOKENS_PER_PAGE
else:
# A plain-text source, or an untyped one carrying text.
total = self.count_text(str(source.get("data") or ""))
for key in ("title", "context"):
value = part.get(key)
if isinstance(value, str):
total += self.count_text(value)
return total
@staticmethod
def _estimate_document_tokens(doc_bytes: bytes) -> int:
"""Estimate a document file's tokens from its page count (see the constants)."""
if b"%PDF-" not in doc_bytes[:1024]:
# Only a PDF has a page tree: other bytes (a Strands txt/csv/docx
# document) keep the size estimate even when their text quotes PDF syntax.
return max(1, len(doc_bytes) // _DOCUMENT_BYTES_PER_PAGE) * _DOCUMENT_TOKENS_PER_PAGE
pages = _pdf_page_count(doc_bytes) or len(doc_bytes) // _DOCUMENT_BYTES_PER_PAGE
return max(1, pages) * _DOCUMENT_TOKENS_PER_PAGE
@staticmethod
def _estimate_image_tokens(image_data: dict[str, Any]) -> int:
"""Estimate tokens for an image using Anthropic's formula: (w*h)/750.
@@ -29,10 +29,14 @@ media a pixel/byte-based estimate instead.
from __future__ import annotations
import base64
import zlib
import pytest
from headroom.providers.anthropic import AnthropicProvider
from headroom.providers.openai import OpenAIProvider
from headroom.tokenizers import base
from headroom.tokenizers.base import count_content_blocks
_BIG = "x " * 3400 # ~6,800 chars
@@ -104,3 +108,454 @@ def test_shared_walker_counts_nested_tool_result_blocks() -> None:
}
flat = {"type": "tool_result", "tool_use_id": "t", "content": _BIG}
assert abs(count_content_blocks([nested], len) - count_content_blocks([flat], len)) < 100
def _stream(data: bytes, entries: bytes = b"") -> bytes:
return b"<< /Length %d%s >>\nstream\n%s\nendstream" % (len(data), entries, data)
def _png_encoded(data: bytes, width: int) -> bytes:
"""``data`` as PNG predictor rows of ``width`` bytes, cycling the five filter types."""
out, prior = b"", bytes(width)
for number, at in enumerate(range(0, len(data), width)):
row, coded = data[at : at + width], bytearray()
for i, value in enumerate(row):
left, up, corner = row[i - 1] if i else 0, prior[i], prior[i - 1] if i else 0
guess = left + up - corner
pa, pb, pc = abs(guess - left), abs(guess - up), abs(guess - corner)
paeth = left if pa <= pb and pa <= pc else up if pb <= pc else corner
coded.append((value - (0, left, up, (left + up) // 2, paeth)[number % 5]) & 255)
out += bytes([number % 5]) + coded
prior = row
return out
def _pdf_file(
objects: dict[int, bytes | dict[int, bytes]],
prior: bytes = b"",
trailer: bytes = b"",
predictor: bool = False,
) -> bytes:
"""A PDF with catalog 1, indexed by an xref table and trailer, or by an xref stream
when a dict value packs those objects into an object stream or ``predictor`` asks
for a Flate xref stream with PNG predictor rows. With ``prior``, an incremental
update of that file; ``trailer`` opens the trailer's dict."""
out = prior or b"%PDF-1.7\n"
rows = {} if prior else {0: (0, 0, 65535)}
for number, body in objects.items():
if isinstance(body, dict):
head, data = b"", b""
for index, (packed, obj) in enumerate(body.items()):
head, data = head + b"%d %d " % (packed, len(data)), data + obj + b"\n"
rows[packed] = (2, number, index)
entries = b" /Type /ObjStm /N %d /First %d /Filter /FlateDecode" % (
len(body),
len(head),
)
body = _stream(zlib.compress(head + data), entries)
rows[number] = (1, len(out), 0)
out += b"%d 0 obj\n%s\nendobj\n" % (number, body)
prev = b" /Prev %s" % prior.split(b"startxref")[-1].split()[0] if prior else b""
xref_at = len(out)
if predictor or any(kind == 2 for kind, _, _ in rows.values()):
rows[max(rows) + 1] = (1, xref_at, 0)
index = b" ".join(b"%d 1" % number for number in sorted(rows))
table = b"".join(
bytes([kind]) + a.to_bytes(4, "big") + b.to_bytes(2, "big")
for _, (kind, a, b) in sorted(rows.items())
)
entries = b" %s/Type /XRef /Size %d /W [1 4 2] /Index [%s] /Root 1 0 R%s" % (
trailer,
max(rows) + 1,
index,
prev,
)
if predictor:
table = zlib.compress(_png_encoded(table, 7))
entries += b" /Filter /FlateDecode /DecodeParms << /Columns 7 /Predictor 12 >>"
out += b"%d 0 obj\n%s\nendobj\n" % (max(rows), _stream(table, entries))
else:
out += b"xref\n" + b"".join(
b"%d 1\n%010d %05d %s \n" % (number, a, b, b"n" if kind else b"f")
for number, (kind, a, b) in sorted(rows.items())
)
out += b"trailer\n<< %s/Size %d /Root 1 0 R%s >>\n" % (trailer, max(rows) + 1, prev)
return out + b"startxref\n%d\n%%%%EOF\n" % xref_at
def _page_tree(page_count: int) -> dict[int, bytes]:
"""Catalog 1, page tree 2 and ``page_count`` blank pages from object 3 on."""
kids = range(3, 3 + page_count)
return {
1: b"<< /Type /Catalog /Pages 2 0 R >>",
2: b"<< /Type /Pages /Kids [%s] /Count %d /MediaBox [0 0 612 792] >>"
% (b" ".join(b"%d 0 R" % kid for kid in kids), page_count),
**dict.fromkeys(kids, b"<< /Type /Page /Parent 2 0 R >>"),
}
def _pdf(page_count: int, *, trailer: bool = True, pad: int = 1_000_000) -> bytes:
"""Blank pages plus ``pad`` bytes of image data; ``trailer=False`` cuts the file
before its xref and trailer, as a truncated download would."""
image = _stream(bytes(range(256)) * (pad // 256))
pdf = _pdf_file({**_page_tree(page_count), 3 + page_count: image})
return pdf if trailer else pdf[: pdf.rindex(b"xref")]
def _base64_document(raw: bytes) -> dict:
data = base64.b64encode(raw).decode()
return {
"type": "document",
"source": {"type": "base64", "media_type": "application/pdf", "data": data},
}
def test_base64_pdf_document_is_priced_by_pages_not_as_text() -> None:
"""A 1 MB base64 PDF read as prose was ~907K tokens; 12 pages are ~18K."""
document = _base64_document(_pdf(12))
for placement in (
[document],
[{"type": "tool_result", "tool_use_id": "t", "content": [document]}],
):
assert count_content_blocks(placement, len) == 12 * 1500
for name, counter in _counters().items():
got = counter.count_messages([{"role": "user", "content": placement}])
assert 12 * 1500 <= got < 12 * 1500 + 100, f"{name} priced a 12-page PDF at {got}"
def test_pdf_page_count_falls_back_from_the_tree_to_the_size_estimate() -> None:
# A truncated file has no xref to find its page tree through: ~3KB of file per page.
truncated = _pdf(5, trailer=False)
assert count_content_blocks([_base64_document(truncated)], len) == len(truncated) // 3000 * 1500
# PDF 1.5+ keeps the page tree inside a compressed object stream.
hidden = _pdf_file({10: _page_tree(7), 11: _stream(bytes(range(256)) * 4096)})
assert count_content_blocks([_base64_document(hidden)], len) == 7 * 1500
# Page tree hidden (compressed object streams): ~3KB of file per page.
opaque = bytes(range(256)) * 4096
assert count_content_blocks([_base64_document(opaque)], len) == len(opaque) // 3000 * 1500
# Text that quotes PDF syntax is not a PDF (a Strands txt document): size estimate.
quoted = b"Notes on /Type /Pages /Count 1 and /Type /Page objects.\n" + b"x" * 300_000
strands = {"document": {"format": "txt", "name": "notes", "source": {"bytes": quoted}}}
assert count_content_blocks([strands], len) == len(quoted) // 3000 * 1500
# Undecodable base64 is still a document: one page, no exception.
broken = {"type": "document", "source": {"type": "base64", "data": "not base64!"}}
assert count_content_blocks([broken], len) == 1500
def test_only_the_page_trees_object_stream_is_inflated_within_the_budget(monkeypatch) -> None:
fonts = dict.fromkeys(range(10, 30), b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>")
pdf = _pdf_file({30: fonts, 31: _page_tree(7), 32: _stream(bytes(range(256)) * 4096)})
inflates = []
real = zlib.decompressobj
monkeypatch.setattr(base.zlib, "decompressobj", lambda *a: inflates.append(1) or real(*a))
assert count_content_blocks([_base64_document(pdf)], len) == 7 * 1500
assert len(inflates) == 1 # the fonts' stream is never read
# A budget the page tree's stream does not fit in gives the size estimate.
monkeypatch.setattr(base, "_PDF_OBJECT_STREAM_MAX_BYTES", 600)
assert count_content_blocks([_base64_document(pdf)], len) == len(pdf) // 3000 * 1500
def test_a_pdf_with_more_xref_rows_than_the_budget_gets_the_size_estimate(monkeypatch) -> None:
pdf = _pdf(5)
monkeypatch.setattr(base, "_PDF_MAX_OBJECTS", 4)
assert count_content_blocks([_base64_document(pdf)], len) == len(pdf) // 3000 * 1500
def _one_page_objects(
text: bytes, count: bytes = b"/Count 1", length: bytes | None = None
) -> dict[int, bytes]:
"""A minimal valid one-page PDF showing ``text``; ``count`` ends its page tree's dict.
With ``length``, that is the content stream's whole dict and object 6 holds the
stream's real length, for ``/Length 6 0 R``."""
data = b"BT /F1 12 Tf 72 720 Td (%s) Tj ET" % text
return {
1: b"<< /Type /Catalog /Pages 2 0 R >>",
2: b"<< /Type /Pages /Kids [3 0 R] /MediaBox [0 0 612 792] %s >>" % count,
3: b"<< /Type /Page /Parent 2 0 R /Contents 4 0 R"
b" /Resources << /Font << /F1 5 0 R >> >> >>",
4: _stream(data) if length is None else b"<< %s >>\nstream\n%s\nendstream" % (length, data),
5: b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
**({} if length is None else {6: b"%d" % len(data)}),
}
def _one_page_pdf(text: bytes, count: bytes) -> bytes:
return _pdf_file(_one_page_objects(text, count))
@pytest.mark.parametrize(
("text", "count"),
[
(b"hello", b"/Count 1"),
# Page text quoting page-tree syntax is content, not structure.
(b"/Type /Pages /Count 999999", b"/Count 1"),
(b"/Type /Pages /Count " + b"9" * 5000, b"/Count 1"),
(b"2 0 obj << /Type /Pages /Count 999 >> endobj", b"/Count 1"),
# Neither is a comment or a string inside the page tree's own dict.
(b"hello", b"% /Count 999\n/Title (a (nested) /Count 999) /Count 1"),
# A malformed or absurd count gives the size estimate (1 page at this size).
(b"hello", b"/Count 1000000"),
(b"hello", b"/Count " + b"9" * 5000),
# A count in a dict, array or hex string nested in the tree's dict is not its own.
(b"hello", b"/PieceInfo << /Example << /Private << /Count 9999 >> >> >> /Count 1"),
(b"hello", b"/Private [<00ff> << /Count 9999 >>] /Count 1"),
],
ids=[
"plain",
"quoted-tree",
"long-number",
"fake-object",
"comment-string",
"absurd",
"long",
"nested-dict",
"nested-array",
],
)
def test_page_count_comes_only_from_the_page_tree_dict(text: bytes, count: bytes) -> None:
assert base.BaseTokenizer._estimate_document_tokens(_one_page_pdf(text, count)) == 1500
_FAKE_TREE = b"endstream 2 0 obj << /Type /Pages /Count 9999 >> endobj"
@pytest.mark.parametrize(
("objects", "trailer"),
[
# The catalog nests a private /Pages ahead of its own.
(
{1: b"<< /PieceInfo << /Private << /Pages 7 0 R >> >> /Type /Catalog /Pages 2 0 R >>"},
b"",
),
# The trailer nests a private /Root ahead of its own.
({}, b"/Private << /Root 6 0 R >> "),
# Laid out like an object stream redefining page tree 2, but /Type /ObjStm is
# private data, not a key of the stream's own dict.
(
{
8: _stream(
zlib.compress(b"2 0 << /Type /Pages /Count 9999 >>"),
b" /Filter /FlateDecode /Private << /Type /ObjStm /N 1 /First 4 >>",
)
},
b"",
),
# A private /Length 0 ahead of the stream's own would end the skip at the
# stream's first byte, and its data would be walked as objects.
(
{
8: b"<< /DecodeParms << /Length 0 >> /Length %d >>\nstream\n%s\nendstream"
% (len(_FAKE_TREE), _FAKE_TREE)
},
b"",
),
],
ids=["catalog-pages", "trailer-root", "object-stream", "stream-length"],
)
def test_root_pages_and_stream_keys_come_only_from_their_own_dicts(
objects: dict[int, bytes], trailer: bytes
) -> None:
decoys = {
6: b"<< /Type /Catalog /Pages 7 0 R >>",
7: b"<< /Type /Pages /Kids [] /Count 9999 >>",
}
pdf = _pdf_file({**_page_tree(1), **decoys, **objects}, trailer=trailer)
assert base.BaseTokenizer._estimate_document_tokens(pdf) == 1500
def _packed(objects: dict[int, bytes], number: int) -> dict[int, bytes | dict[int, bytes]]:
"""``objects`` with ``number`` moved into object stream 7, indexed by an xref stream."""
return {**{n: o for n, o in objects.items() if n != number}, 7: {number: objects[number]}}
_INDIRECT = _one_page_objects(_FAKE_TREE, length=b"/Length 6 0 R")
_LONE_CR = b"BT /F1 12 Tf 72 720 Td (hi) Tj ET endobj 2 0 obj << /Type /Pages /Count 9999 >> endobj"
@pytest.mark.parametrize(
("pdf", "pages"),
[
# JerrettDavis's case: object 6, read at its xref offset, ends the stream.
(_pdf_file(_INDIRECT), 1),
# Page text that also fakes object 6 with the length (24) of the quoted endstream.
(
_pdf_file(
_one_page_objects(_FAKE_TREE + b" 6 0 obj 24 endobj", length=b"/Length 6 0 R")
),
1,
),
# Through an xref stream, and through /Prev to the section that lists object 6.
(_pdf_file(_packed(_INDIRECT, 5)), 1),
(_pdf_file({5: _INDIRECT[5]}, prior=_pdf_file(_INDIRECT)), 1),
# A lone CR after the stream keyword still starts a stream, so bare tokens after
# the text operators stay data.
(
_pdf_file(
{
**_INDIRECT,
4: b"<< /Length 6 0 R >>\nstream\r%s\nendstream" % _LONE_CR,
6: b"%d" % len(_LONE_CR),
}
),
1,
),
# The page count never reads a content stream, so neither does its length: one
# packed in an object stream, a wrong one, a reference to no object, or none.
(_pdf_file(_packed(_INDIRECT, 6)), 1),
(_pdf_file({**_INDIRECT, 6: b"40"}), 1),
(_pdf_file(_one_page_objects(_FAKE_TREE, length=b"/Length 9 0 R")), 1),
(_pdf_file(_one_page_objects(_FAKE_TREE, length=b"")), 1),
],
ids=[
"indirect",
"fake-length-object",
"xref-stream",
"prev-section",
"lone-cr",
"packed-length",
"wrong-length",
"dangling-length",
"no-length",
],
)
def test_stream_data_is_never_walked_as_objects(pdf: bytes, pages: int) -> None:
assert base._pdf_page_count(pdf) == pages
def _xref_chain(*sections: bytes) -> bytes:
"""A file of xref streams chained by /Prev, each of ``sections`` the end of one's dict
and its stream, ready as an update's ``prior``."""
out, prev = b"%PDF-1.7\n", b""
for number, body in enumerate(sections, 100):
at = len(out)
out += b"%d 0 obj\n<< /Type /XRef /Size 999999 /W [1 4 2]%s%s\nendobj\n" % (
number,
prev,
body,
)
prev = b" /Prev %d" % at
return out + b"startxref\n%d\n%%%%EOF\n" % at
def _flate_rows(index: bytes, data: bytes) -> bytes:
packed = zlib.compress(data, 9)
return b" /Index [%s] /Filter /FlateDecode /Length %d >>\nstream\n%s\nendstream" % (
index,
len(packed),
packed,
)
def _priced_after(prior: bytes) -> int:
return base._pdf_page_count(_pdf_file(_INDIRECT, prior=prior))
def test_xref_rows_share_one_budget_across_sections() -> None:
# Two compressed sections of 100,000 entries each: 200,000 rows read is past the
# 100,000 the whole traversal may read, so the size estimate stands in.
rows = bytes(7 * 100_000)
chain = _xref_chain(_flate_rows(b"0 100000", rows), _flate_rows(b"100000 100000", rows))
assert _priced_after(chain) == 0
# A normal update chain through a compressed section is well inside the budgets.
assert _priced_after(_xref_chain(_flate_rows(b"0 1", bytes(7)))) == 1
def test_xref_streams_share_the_files_one_inflate_budget(monkeypatch) -> None:
# 100 sections each inflating to 4 MB of rows: the first runs out the file's one
# 4 MB budget, so the size estimate stands in and no other section is inflated.
inflates = []
real = zlib.decompressobj
monkeypatch.setattr(base.zlib, "decompressobj", lambda *a: inflates.append(1) or real(*a))
assert _priced_after(_xref_chain(*[_flate_rows(b"0 571428", bytes(4_000_000))] * 100)) == 0
assert len(inflates) == 1
def test_xref_dicts_share_one_scan_budget_across_sections() -> None:
# 300 table sections whose trailer dicts stay open, so each holds every later one:
# reading the chain would rescan most of the file 300 times.
section = b"xref\n0 0\ntrailer\n<< /Prev %010d " + b"/A " * 200
width = len(section % 0)
chain = b"%PDF-1.7\n" + b"".join(section % (9 + (i + 1) * width) for i in range(300))
assert _priced_after(chain + b">> " * 300 + b"\nstartxref\n9\n%%EOF\n") == 0
def _unreferenced(pdf: bytes, obj: bytes) -> bytes:
"""``pdf`` (an xref table file) with ``obj`` added before its table, which does not list it."""
at = pdf.rindex(b"\nxref\n") + 1
xref_at = int(pdf.rsplit(b"startxref\n", 1)[1].split()[0])
tail = pdf[at:].replace(b"startxref\n%d" % xref_at, b"startxref\n%d" % (xref_at + len(obj)))
return pdf[:at] + obj + tail
_DECOY_TREE = b"<< /Type /Pages /Kids [3 0 R] /Count 9999 >>"
_DECOY_STREAM = _stream(
zlib.compress(b"2 0 " + _DECOY_TREE), b" /Type /ObjStm /N 1 /First 4 /Filter /FlateDecode"
)
@pytest.mark.parametrize(
"pdf",
[
# A later "2 0 obj" outside any stream that the xref does not list.
_unreferenced(_one_page_pdf(b"hello", b"/Count 1"), b"2 0 obj\n%s\nendobj\n" % _DECOY_TREE),
# A later object stream holding an object 2, unlisted or listed: either way the
# xref puts object 2 at its own offset.
_unreferenced(
_one_page_pdf(b"hello", b"/Count 1"), b"9 0 obj\n%s\nendobj\n" % _DECOY_STREAM
),
_pdf_file({**_one_page_objects(b"hello"), 9: _DECOY_STREAM}),
],
ids=["object", "unlisted-object-stream", "listed-object-stream"],
)
def test_only_the_definition_the_xref_points_at_counts(pdf: bytes) -> None:
assert base.BaseTokenizer._estimate_document_tokens(pdf) == 1500
def test_a_predictor_12_xref_stream_is_decoded_row_by_row() -> None:
# Its rows cycle the five PNG filter types; the tree is top level, or packed.
for pdf in (
_pdf_file(_page_tree(12), predictor=True),
_pdf_file({20: _page_tree(12)}, predictor=True),
):
assert base.BaseTokenizer._estimate_document_tokens(pdf) == 12 * 1500
def test_incremental_update_prices_the_active_page_tree_not_an_obsolete_one() -> None:
original = _pdf_file(_page_tree(5))
# An edit keeps two pages under a new tree; the old tree (/Count 5) stays in the file.
edited = _pdf_file(
{
1: b"<< /Type /Catalog /Pages 8 0 R >>",
3: b"<< /Type /Page /Parent 8 0 R >>",
4: b"<< /Type /Page /Parent 8 0 R >>",
8: b"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] >>",
},
prior=original,
)
assert base.BaseTokenizer._estimate_document_tokens(original) == 5 * 1500
assert base.BaseTokenizer._estimate_document_tokens(edited) == 2 * 1500
def test_text_and_content_document_sources_count_their_text() -> None:
text = {
"type": "document",
"source": {"type": "text", "media_type": "text/plain", "data": _BIG},
}
assert count_content_blocks([text], len) == len(_BIG)
content = {
"type": "document",
"source": {"type": "content", "content": [{"type": "text", "text": _BIG}]},
}
assert count_content_blocks([content], len) == len(_BIG)
plain = {"type": "document", "source": {"type": "content", "content": _BIG}}
assert count_content_blocks([plain], len) == len(_BIG)
titled = {**text, "title": "Q3 report", "context": "board deck"}
assert count_content_blocks([titled], len) == len(_BIG) + len("Q3 report") + len("board deck")
def test_url_and_file_document_sources_are_one_nominal_page() -> None:
for source in (
{"type": "url", "url": "https://example.com/a.pdf"},
{"type": "file", "file_id": "file_1"},
):
assert count_content_blocks([{"type": "document", "source": source}], len) == 1500