Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

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

gglucassfc1ba891bff2
diff --git a/headroom/tokenizers/base.py b/headroom/tokenizers/base.py
index 5ce1ac640..071214777 100644
--- a/headroom/tokenizers/base.py
+++ b/headroom/tokenizers/base.py
@@ -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.
diff --git a/tests/test_provider_counter_content_blocks.py b/tests/test_provider_counter_content_blocks.py
index c4ad57088..98533b91d 100644
--- a/tests/test_provider_counter_content_blocks.py
+++ b/tests/test_provider_counter_content_blocks.py
@@ -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))
+
+
+ ("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"
+
+
+ ("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"
+
+
+ ("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"
+)
+
+
+ "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