Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188"""Size bounds on chunks.
The embedding server rejects any single input longer than its physical batch, andone rejection fails the whole request. During a multi-hour index that means the rundies and its unwritten work is lost, so "no chunk is ever too big" is the propertythat most needs a check rather than an argument.
Chunk sizing works in characters because counting tokens would cost a round tripper chunk. That makes the character-to-token ratio the risk: it sits near 3.6:1 onordinary source but collapses towards 1:1 on dense punctuation, base64, and minifiedfragments. The caps are therefore set against the worst case, not the average."""
from __future__ import annotations
import os
import pytest
from code_index import embedfrom code_index.chunk import MAX_CHUNK_CHARS, Chunk, _enforce_cap, chunk_filefrom code_index.files import discover, find_repos
WORKSPACE = os.path.expanduser("~/workspace")
def longest_payload(chunks) -> int: """Longest payload as sent, before the embed-side truncation is applied.
Measuring after truncation would assert that a slice is no longer than the length it was sliced to, which is true however broken the chunker is. The property worth checking is that truncation never has to fire. """ return max( (len(embed.DOC_PREFIX + c.embedding_text()) for c in chunks), default=0 )
def test_caps_are_ordered(): """The embed-side guard must sit above the chunker's cap, not below it.
If it were tighter, every chunk would be silently truncated and the path prefix would be the only thing surviving on large chunks. """ assert MAX_CHUNK_CHARS < embed.MAX_INPUT_CHARS # Compares characters against a token budget, which is only sound because one # token is never fewer than one character. Measured worst case on this corpus # is 1135 tokens for a 1994-byte payload, so the margin is real, not assumed. assert embed.MAX_INPUT_CHARS < embed.CONTEXT
@pytest.mark.parametrize( "name,text", [ ("one enormous line", "x = " + "a," * 20_000), ("base64 blob", "const data = '" + "QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVow" * 400 + "';"), ("no newlines at all", "".join(f"stmt{i}();" for i in range(5000))), ("dense punctuation", "".join("{}[]();,.<>/\\|" for _ in range(3000))), ("one long line among short ones", "short()\n" * 20 + "y = " + "b," * 15_000 + "\nshort()\n"), ("single huge token", "z" * 40_000), ("cjk text", "代码検索" * 5000), ("mixed width", ("éèê" * 30 + "\n") * 200), ],)def test_pathological_input_stays_within_cap(name, text): """No input shape may produce a chunk the server would reject.""" chunks = chunk_file("src/pathological.ts", text) assert chunks, f"{name}: produced no chunks at all" oversized = [c for c in chunks if len(c.text) > MAX_CHUNK_CHARS] assert not oversized, ( f"{name}: {len(oversized)} chunk(s) over MAX_CHUNK_CHARS; " f"largest {max(len(c.text) for c in oversized)}" ) # Truncation is a backstop; if it is doing work, the chunker has already failed. assert longest_payload(chunks) <= embed.MAX_INPUT_CHARS
def test_long_line_is_split_not_dropped(): """Splitting a long line must preserve its content, not discard the tail.""" line = "".join(f"seg{i:05d};" for i in range(2000)) chunks = chunk_file("src/long.ts", line) assert len(chunks) > 1 rejoined = "".join(c.text for c in chunks) assert "seg00000;" in rejoined assert "seg01999;" in rejoined, "tail of a split line was lost"
def test_split_pieces_report_the_lines_they_hold(): """A piece of a split chunk points at its own lines, not the whole chunk's.
The visible cost is a search hit whose line range is wider than the text shown, but the reason to check it is that coverage assertions read these fields: with every piece claiming the full span, content lost in the split still adds up to complete coverage. """ text = "\n".join("x" * 200 for _ in range(20)) pieces = _enforce_cap([Chunk("src/wide.ts", 5, 24, text)])
assert len(pieces) > 1, "the input was meant to exceed the cap" assert pieces[0].start_line == 5 assert pieces[-1].end_line == 24 for piece in pieces: assert 5 <= piece.start_line <= piece.end_line <= 24 for earlier, later in zip(pieces, pieces[1:]): # A cut lands mid-line, so consecutive pieces share a line or sit adjacent; # anything wider is a gap, anything narrower is a span running backwards. assert earlier.end_line <= later.start_line <= earlier.end_line + 1
def test_a_split_line_keeps_its_own_line_number(): """One line over the cap yields several chunks, all on that same line.""" line = "".join(f"seg{i:05d};" for i in range(2000)) chunks = chunk_file("src/long.ts", line) assert len(chunks) > 1 assert all(c.start_line == 1 and c.end_line == 1 for c in chunks)
def test_every_line_is_covered(): """Ordinary source must be fully represented, with no gap between chunks.""" text = "\n".join(f"function f{i}() {{ return {i}; }}" for i in range(400)) chunks = chunk_file("src/many.ts", text) assert chunks assert chunks[0].start_line == 1 assert chunks[-1].end_line == len(text.split("\n")) covered: set[int] = set() for c in chunks: covered.update(range(c.start_line, c.end_line + 1)) missing = set(range(1, len(text.split("\n")) + 1)) - covered assert not missing, f"lines never indexed: {sorted(missing)[:10]}"
def test_small_file_is_one_chunk(): text = "export const answer = 42;\n" chunks = chunk_file("src/tiny.ts", text) assert len(chunks) == 1 assert chunks[0].start_line == 1
def test_blank_file_yields_nothing(): assert chunk_file("src/blank.ts", "\n\n \n\t\n") == []
def test_chunks_carry_their_path(): """The path is embedded alongside the source, so a query can match the name.""" chunks = chunk_file("src/auth/session-store.ts", "const a = 1;\n") assert "session" in chunks[0].embedding_text() assert "store" in chunks[0].embedding_text()
@pytest.mark.skipif( not os.path.isdir(WORKSPACE), reason="no workspace to scan on this machine")def test_real_corpus_stays_within_cap(): """The check that would have caught the failure that motivated these caps.
Synthetic cases only cover the shapes thought of in advance; the corpus is where the unanticipated ones live. """ worst_text = worst_payload = 0 worst_at = "" scanned = 0 for repo in find_repos(WORKSPACE): files, _ = discover(repo) for sf in files: try: with open(sf.abspath, encoding="utf-8") as fh: text = fh.read() except (OSError, UnicodeDecodeError): continue for c in chunk_file(sf.rel, text): scanned += 1 if len(c.text) > worst_text: worst_text = len(c.text) worst_at = f"{os.path.basename(repo)}/{c.rel}:{c.start_line}" worst_payload = max( worst_payload, len(embed.DOC_PREFIX + c.embedding_text()) ) assert scanned > 0, "corpus scan found no chunks; discovery may be broken" assert worst_text <= MAX_CHUNK_CHARS, ( f"{worst_text} char chunk at {worst_at} exceeds " f"MAX_CHUNK_CHARS={MAX_CHUNK_CHARS} (scanned {scanned} chunks)" ) # The path prefix rides along with every chunk, so the cap on chunk text alone # does not bound what is actually sent. assert worst_payload <= embed.MAX_INPUT_CHARS, ( f"payload of {worst_payload} chars would be truncated before embedding" )