#!/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,450 files, 1024-wide vectors, ~1 kB of text per chunk) with a stubbed embedder, then runs a refresh in which a single file changed, and reports every full-index operation the run performs: how many rows it rewrites and how many bytes it writes. Counts rather than wall-clock: this is meant to be runnable while a real build has 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 traffic and the matrix file alike; the matrix share is separated out by looking at the generation file each operation leaves behind. uv run python eval/refresh-cost.py """ from __future__ import annotations import argparse import hashlib import os import shutil import sys import tempfile import time from 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: E402 from code_index.files import SourceFile # noqa: E402 from 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()