Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273#!/usr/bin/env python3"""What an incremental refresh costs when almost nothing changed.
Builds a synthetic index of the real one's shape (~37,700 chunks over ~2,450files, 1024-wide vectors, ~1 kB of text per chunk) with a stubbed embedder, thenruns a refresh in which a single file changed, and reports every full-indexoperation the run performs: how many rows it rewrites and how many bytes itwrites.
Counts rather than wall-clock: this is meant to be runnable while a real buildhas all 16 cores, where timings say more about the other process than this one.Bytes come from /proc/self/io write_bytes, so they include SQLite's WAL trafficand the matrix file alike; the matrix share is separated out by looking at thegeneration file each operation leaves behind.
uv run python eval/refresh-cost.py"""
from __future__ import annotations
import argparseimport hashlibimport osimport shutilimport sysimport tempfileimport timefrom dataclasses import dataclass
import numpy as np
# paths.py reads its environment at import, so the data directory is chosen here.ARGS = argparse.ArgumentParser(description=__doc__)ARGS.add_argument("--files", type=int, default=2448)ARGS.add_argument("--chunks", type=int, default=37704)ARGS.add_argument("--repos", type=int, default=24)ARGS.add_argument("--dim", type=int, default=1024)ARGS.add_argument("--text-len", type=int, default=974)ARGS.add_argument("--changed", type=int, default=1, help="files edited since the last run")ARGS.add_argument("--data", default=None, help="index directory (default: a temp dir)")opts = ARGS.parse_args()
_tmp = opts.data or tempfile.mkdtemp(prefix="refresh-cost-")os.environ["CODE_INDEX_DATA"] = _tmp
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "src"))
from code_index import embed, indexer # noqa: E402from code_index.files import SourceFile # noqa: E402from code_index.store import Store, discard_shadow # noqa: E402
# -- the corpus -------------------------------------------------------------
LOREM = ( "def handler(request, context):\n" " # Resolve the account before touching the store, so a bad id fails\n" " # before anything is written.\n" " account = context.accounts.get(request.account_id)\n" " if account is None:\n" " raise NotFound(request.account_id)\n" " return context.store.apply(account, request.changes)\n")
def chunk_text(n: int, length: int) -> str: body = f"# chunk {n}\n" + LOREM * (length // len(LOREM) + 1) return body[:length]
@dataclass(frozen=True)class StubFile(SourceFile): """A discovered file whose contents come from the generator, not the disk."""
text: str = ""
def read(self) -> tuple[str, str]: return self.text, self.sha
def corpus(opts) -> tuple[list[str], dict[str, list[StubFile]]]: """Repository paths and their files, at the shape of the real index.""" repos = [f"/synthetic/repo{i:02d}" for i in range(opts.repos)] by_repo: dict[str, list[StubFile]] = {r: [] for r in repos} for i in range(opts.files): repo = repos[i % opts.repos] rel = f"src/pkg{i % 40}/module_{i}.py" by_repo[repo].append( StubFile( repo=repo, rel=rel, size=4096, sha=hashlib.sha256(f"{repo}/{rel}:v1".encode()).hexdigest(), text="", ) ) return repos, by_repo
def seed(opts, repos, by_repo) -> int: """Write a whole index directly, without paying for a build to make one.""" per_file = opts.chunks // opts.files now = time.time() records = [] for repo in repos: for sf in by_repo[repo]: for c in range(per_file): records.append( (sf.repo, sf.rel, sf.sha, c * 20 + 1, c * 20 + 20, chunk_text(len(records), opts.text_len), now) ) rng = np.random.default_rng(0) vecs = rng.standard_normal((len(records), opts.dim), dtype=np.float32) vecs /= np.linalg.norm(vecs, axis=1, keepdims=True)
store = Store(dim=opts.dim) store.rebuild(records, vecs) store.set_meta("model", os.path.basename(indexer.MODEL_PATH)) store.set_meta("dim", str(opts.dim)) store.set_meta("built_at", time.strftime("%Y-%m-%d %H:%M:%S")) store.close() return len(records)
# -- instrumentation --------------------------------------------------------
EVENTS: list[dict] = []
def write_bytes() -> int: with open("/proc/self/io") as fh: for line in fh: if line.startswith("write_bytes:"): return int(line.split()[1]) return 0
def _tag(store: Store) -> str: return "shadow" if "shadow" in store.db_path else "live"
def instrument() -> None: """Record rows rewritten and bytes written by each full-index operation.""" original_rows = Store._replace_rows
def counting_rows(self, records, generation): n = original_rows(self, records, generation) if EVENTS: EVENTS[-1]["rows"] += n return n
Store._replace_rows = counting_rows original_insert = Store._insert_rows
def counting_insert(self, records, first_row): n = original_insert(self, records, first_row) if EVENTS: EVENTS[-1]["rows"] += n return n
Store._insert_rows = counting_insert
def matrix_state(store): raw = store.get_meta("vector_generation") if raw is None: return None, 0, False path = store._generation_path(int(raw)) if not os.path.exists(path): return int(raw), 0, False st = os.stat(path) return int(raw), st.st_size, st.st_nlink > 1
for name in ("rebuild", "replace_from", "append"): original = getattr(Store, name)
def wrapper(self, *a, _name=name, _original=original, **kw): event = {"op": _name, "store": _tag(self), "rows": 0, "matrix_bytes": 0, "matrix_linked": False, "bytes": 0} EVENTS.append(event) was, was_size, _ = matrix_state(self) before = write_bytes() try: return _original(self, *a, **kw) finally: event["bytes"] = write_bytes() - before now, size, linked = matrix_state(self) # An append that extended the file in place wrote only the growth; # anything that produced a new generation wrote the whole file. grew_in_place = _name == "append" and now == was event["matrix_bytes"] = max(size - was_size, 0) if grew_in_place else size event["matrix_linked"] = linked and not grew_in_place
setattr(Store, name, wrapper)
def stub_embedder(dim: int) -> None: def stub_embed(texts, is_query=False, timeout=None): vecs = np.random.default_rng(1).standard_normal((len(texts), dim), dtype=np.float32) return vecs / np.linalg.norm(vecs, axis=1, keepdims=True)
embed.embed = stub_embed embed.start = lambda *a, **kw: None embed.EMBED_DIM = dim
# -- the run ----------------------------------------------------------------
def main() -> None: stub_embedder(opts.dim) repos, by_repo = corpus(opts)
print(f"data dir: {_tmp}", file=sys.stderr) print("seeding...", file=sys.stderr) t0 = time.time() n = seed(opts, repos, by_repo) print(f" {n} chunks, {opts.files} files, {len(repos)} repos " f"({time.time() - t0:.1f}s)", file=sys.stderr)
# The edited files get a new sha and new contents, so they alone are # re-chunked and re-embedded. Everything else reuses the previous vectors. for n in range(opts.changed): repo = repos[n % len(repos)] slot = n // len(repos) old = by_repo[repo][slot] by_repo[repo][slot] = StubFile( repo=old.repo, rel=old.rel, size=4096, sha=hashlib.sha256(f"{old.repo}/{old.rel}:v2".encode()).hexdigest(), text="\n".join(f"def fn_{i}():\n return {i}\n" for i in range(400)), )
indexer.find_repos = lambda root: list(repos) indexer.discover = lambda repo: (by_repo[repo], {})
instrument() before = write_bytes() t0 = time.time() stats = indexer.build(["/synthetic"]) elapsed = time.time() - t0 total_bytes = write_bytes() - before
print() print(f"refresh: {stats['embedded_chunks']} chunks re-embedded, " f"{stats['total_chunks']} in the index, {elapsed:.1f}s wall " "(noisy; the machine is shared)") print() header = f"{'operation':<26}{'rows':>9}{'matrix':>16}{'write_bytes':>14}" print(header) print("-" * len(header)) rows = matrix = written = 0 for e in EVENTS: label = f"{e['op']}({e['store']})" mat = f"{e['matrix_bytes'] / 1e6:.1f} MB" + (" link" if e["matrix_linked"] else "") print(f"{label:<26}{e['rows']:>9}{mat:>16}{e['bytes'] / 1e6:>11.1f} MB") rows += e["rows"] matrix += 0 if e["matrix_linked"] else e["matrix_bytes"] written += e["bytes"] print("-" * len(header)) print(f"{'total':<26}{rows:>9}{matrix / 1e6:>13.1f} MB{written / 1e6:>11.1f} MB") print() print(f"matrix writes: {matrix / 1e6:.0f} MB of {written / 1e6:.0f} MB " f"({100 * matrix / max(written, 1):.0f}%)") print(f"row rewriting: {(written - matrix) / 1e6:.0f} MB, {rows} rows inserted " f"for {stats['embedded_chunks']} changed chunks")
discard_shadow() if opts.data is None: shutil.rmtree(_tmp, ignore_errors=True)
if __name__ == "__main__": main()