From 4fa919970731086c598114571512db8861e4b059 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 01:28:43 -0600 Subject: [PATCH] perf(atlas-search): run hybrid branches concurrently (#12900 thread 1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The FTS and vector branches of a hybrid query are independent and join only at RRF fusion, but run_search executed them strictly serially on every backend shape: the local FTS query finished before the vector scan started, the turso index path ran its FTS pipeline to completion before the index branch, and the turso scan path sent both statements in one pipeline, which executes sequentially server-side. They now run concurrently through run_branches (a thread pool, results collected by name; a single branch still runs inline, so fts-only and vector-only keep their exact old shape). LocalBackend gives each thread its own sqlite connection — the TEMP views of _setup_views and the ATTACHes of load_matrix are per-connection state — so branch workers never share one. die() inside a branch is ferried back and re-raised as SystemExit on the calling thread with its exit code intact. Output is unchanged: fixtures/gen_core_fixtures.py regenerated against this code produces a core-expectations.json value-identical to the committed recording, and the new tests in tests/test_branch_concurrency.py pin serial == concurrent == recorded envelopes, real overlap under slowed branch entry points, and die() propagation on both backend shapes. Refs #12900 --- pkgs/atlas-search/atlas_search.py | 146 ++++++++++-- .../tests/test_branch_concurrency.py | 215 ++++++++++++++++++ 2 files changed, 345 insertions(+), 16 deletions(-) create mode 100644 pkgs/atlas-search/tests/test_branch_concurrency.py diff --git a/pkgs/atlas-search/atlas_search.py b/pkgs/atlas-search/atlas_search.py index a12eb64710..bd88590bea 100755 --- a/pkgs/atlas-search/atlas_search.py +++ b/pkgs/atlas-search/atlas_search.py @@ -87,12 +87,14 @@ import argparse import base64 +import concurrent.futures import json import os import re import sqlite3 import subprocess import sys +import threading import time import urllib.error import urllib.request @@ -367,13 +369,40 @@ def __init__(self, db_path, vecdb_arg=None, vec_table=VEC_TABLE, trunc=0): self.db_path = db_path self.vec_table = vec_table self.trunc = trunc - self.con = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True) - self.con.row_factory = sqlite3.Row self.notes = [] + # One sqlite connection per thread (the con property below): + # the TEMP views of _setup_views and the ATTACHes of + # load_matrix are per-connection state, and hybrid search runs + # its branches on worker threads (#12900 thread 1), which must + # never share a connection. + self._tls = threading.local() + self._home_thread = threading.current_thread() + _ = self.con # the home thread's connection, built eagerly self._setup_views() self._vec_sources = self._find_vec_sources(vecdb_arg) self._matrix = None # (ids list, numpy matrix, id->row index) + @property + def con(self): + """The calling thread's sqlite connection. First touch on a + new thread opens a fresh connection and replays _setup_views + on it (TEMP views/tables and the aux ATTACH do not cross + connections). Setup notes can therefore append once per + connection; run_search folds backend notes with dedup, so the + repeats never surface.""" + con = getattr(self._tls, "con", None) + if con is None: + con = sqlite3.connect(f"file:{self.db_path}?mode=ro", uri=True) + con.row_factory = sqlite3.Row + self._tls.con = con + if threading.current_thread() is not self._home_thread: + self._setup_views() + return con + + @con.setter + def con(self, value): + self._tls.con = value + # -- schema normalization: temp views give the queries one shape # whether the file is a publish copy (labels+sensitivity+vecs) or # canonical atlas.db (none of those; attached from siblings). @@ -921,6 +950,51 @@ def turso_index_branch(be, filters, qvec_json, pool, vbackend): return [(cid, dist.get(cid)) for cid in survivors] +class _BranchExit(Exception): + """A branch's die() (SystemExit), ferried to the calling thread.""" + + def __init__(self, code): + super().__init__(code) + self.code = code + + +def run_branches(named): + """Run a search's branch callables; return {name: ranked list}. + + A hybrid query's branches are independent and join only at RRF + fusion (#12900 thread 1), so with two or more branches they run + concurrently on a thread pool and are collected by name — fusion + order, and therefore the output envelope, is unchanged. A single + branch runs inline, keeping the fts-only / vector-only shapes + exactly as before. die() in a branch raises SystemExit in the + worker thread; it is ferried back and re-raised here, on the + calling thread, so a branch failure exits the same way the serial + shape's did.""" + + def guarded(fn): + def call(): + try: + return fn() + except SystemExit as e: + raise _BranchExit(e.code) from None + + return call + + if len(named) < 2: + return {name: guarded(fn)() for name, fn in named.items()} + ex = concurrent.futures.ThreadPoolExecutor(max_workers=len(named)) + try: + futures = {ex.submit(guarded(fn)): name for name, fn in named.items()} + out = {} + for fut in concurrent.futures.as_completed(futures): + out[futures[fut]] = fut.result() + return out + except _BranchExit as e: + raise SystemExit(e.code) from None + finally: + ex.shutdown(wait=False) + + def run_search(be, args): vbackend = getattr(args, "vector_backend", "scan") if ( @@ -958,23 +1032,53 @@ def run_search(be, args): ) if isinstance(be, TursoBackend): if vbackend == "scan" or qvec_json is None: - stmts = branch_queries(be, filters, match_expr, qvec_json, args.pool) - results = be.pipeline(stmts) - i = 0 + # One pipeline per branch, run concurrently: a single + # pipeline executes its statements sequentially + # server-side, so the batched shape serialized the two + # branches against each other (#12900 thread 1). + + def turso_scan_fts(): + stmts = branch_queries(be, filters, match_expr, None, args.pool) + if not stmts: + return [] + return [(r["cid"], None) for r in be.pipeline(stmts)[0]] + + def turso_scan_vec(): + stmts = branch_queries(be, filters, None, qvec_json, args.pool) + if not stmts: + return [] + return [(r["cid"], r["dist"]) for r in be.pipeline(stmts)[0]] + + branches = {} if match_expr is not None: - fts_ranked = [(r["cid"], None) for r in results[i]] - i += 1 + branches["fts"] = turso_scan_fts if qvec_json is not None: - vec_ranked = [(r["cid"], r["dist"]) for r in results[i]] + branches["vec"] = turso_scan_vec + got = run_branches(branches) + fts_ranked = got.get("fts", []) + vec_ranked = got.get("vec", []) else: - fts_stmts = branch_queries(be, filters, match_expr, None, args.pool) - if fts_stmts: - fts_ranked = [(r["cid"], None) for r in be.pipeline(fts_stmts)[0]] - vec_ranked = turso_index_branch(be, filters, qvec_json, args.pool, vbackend) + + def turso_index_fts(): + fts_stmts = branch_queries(be, filters, match_expr, None, args.pool) + if not fts_stmts: + return [] + return [(r["cid"], None) for r in be.pipeline(fts_stmts)[0]] + + branches = {} + if match_expr is not None: + branches["fts"] = turso_index_fts + branches["vec"] = lambda: turso_index_branch( + be, filters, qvec_json, args.pool, vbackend + ) + got = run_branches(branches) + fts_ranked = got.get("fts", []) + vec_ranked = got.get("vec", []) else: where, params = filters.where(be) joins = filters.joins(be) - if match_expr is not None: + + def local_fts(): rows = be.execute( "SELECT c.id AS cid FROM chunks c " "JOIN chunks_fts f ON f.rowid = c.id " @@ -983,19 +1087,29 @@ def run_search(be, args): "ORDER BY bm25(chunks_fts) LIMIT ?", [match_expr, *params, args.pool], ) - fts_ranked = [(r["cid"], None) for r in rows] - if qvec is not None: + return [(r["cid"], None) for r in rows] + + def local_vec(): allowed = { r["cid"] for r in be.execute( f"SELECT c.id AS cid FROM chunks c {joins} WHERE {where}", params ) } - vec_ranked = [ + return [ (cid, 1.0 - sim) for cid, sim in be.vector_search(qvec, allowed, args.pool) ] + branches = {} + if match_expr is not None: + branches["fts"] = local_fts + if qvec is not None: + branches["vec"] = local_vec + got = run_branches(branches) + fts_ranked = got.get("fts", []) + vec_ranked = got.get("vec", []) + # Reciprocal rank fusion, k=10 (production shape, decided 2026-10-31). fused = {} for rank, (cid, _raw) in enumerate(fts_ranked, start=1): diff --git a/pkgs/atlas-search/tests/test_branch_concurrency.py b/pkgs/atlas-search/tests/test_branch_concurrency.py new file mode 100644 index 0000000000..0216572967 --- /dev/null +++ b/pkgs/atlas-search/tests/test_branch_concurrency.py @@ -0,0 +1,215 @@ +#!/usr/bin/env python3 +"""Branch-concurrency tests for atlas_search.run_search (#12900 thread 1). + +Oracle: the serial shape. A hybrid query's branches are independent +and join only at RRF fusion, so running them concurrently must not +change any output — and with slowed branch entry points the +concurrent run must finish well under the serial sum (proof the +branches actually overlap, not merely that both ran). + +Cases: +- hybrid envelope under concurrency == envelope under a forced-serial + run_branches == the committed recording in + fixtures/core-expectations.json (the same recording atlas-core's + parity tests hold the Rust port to). +- fts-only and vector-only envelopes (the inline single-branch shape) + == their committed recordings. +- overlap timing with 0.6 s sleeps injected at both branch entries. +- die() inside a branch (SystemExit) reaches the caller with its + exit code, on both the local and the turso branch paths. + +Fixture rig mirrors fixtures/gen_core_fixtures.py: the fixture +corpus DB built in a temp dir, embed_query monkeypatched to the +fixture query vector. Run on the laptop with a numpy-carrying +python (the v3 venv; LD_LIBRARY_PATH per gen_core_fixtures.py): + + LD_LIBRARY_PATH=: \ + ~/atlas/v3-venv/bin/python tests/test_branch_concurrency.py +""" + +import argparse +import importlib.util +import json +import os +import sqlite3 +import struct +import sys +import tempfile +import time +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +PKG = os.path.dirname(HERE) +FIXTURES = os.path.join(PKG, "fixtures") + +spec = importlib.util.spec_from_file_location( + "atlas_search", os.path.join(PKG, "atlas_search.py") +) +A = importlib.util.module_from_spec(spec) +spec.loader.exec_module(A) + +import numpy as np # noqa: E402 + +with open(os.path.join(FIXTURES, "fixture_spec.json")) as f: + FSPEC = json.load(f) +QVEC_RAW = FSPEC["qvec_raw"] + +with open(os.path.join(FIXTURES, "core-expectations.json")) as f: + EXPECTED = {c["name"]: c["envelope"] for c in json.load(f)["search_cases"]} + + +def fixture_embed_query(text, model=None, embedder=None, trunc=0): + """embed_query stand-in: the fixture qvec, normalized exactly as + the real embed_query normalizes (float32, divide by float norm).""" + v = np.array(QVEC_RAW, dtype=np.float32) + if trunc: + v = v[:trunc] + n = float(np.linalg.norm(v)) + return v / n + + +A.embed_query = fixture_embed_query + + +def mkargs(**over): + base = dict( + query="how do we back up the database", + mode="hybrid", + k=10, + pool=100, + kind=None, + topic=None, + project=None, + client=None, + since=None, + until=None, + max_sensitivity="personal", + group_by_session=False, + expand=0, + with_message=False, + model=A.MODEL, + embedder="auto", + trunc=0, + vector_backend="scan", + ) + base.update(over) + return argparse.Namespace(**base) + + +def build_db(path): + with open(os.path.join(FIXTURES, "fixture_corpus.sql")) as f: + sql = f.read() + con = sqlite3.connect(path) + con.executescript(sql) + for cid, vec in FSPEC["vectors"].items(): + con.execute( + "INSERT INTO vec_snowflake_m_v2_768_f32 (chunk_id, vec) VALUES (?, ?)", + (int(cid), struct.pack(f"<{len(vec)}f", *vec)), + ) + con.commit() + con.close() + + +def serial_run_branches(named): + return {name: fn() for name, fn in named.items()} + + +class BranchConcurrencyTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.tmp = tempfile.mkdtemp(prefix="atlas-branch-test-") + cls.db = os.path.join(cls.tmp, "fixture.db") + build_db(cls.db) + + def backend(self): + return A.LocalBackend(self.db) + + def test_hybrid_envelope_identical_serial_concurrent_recorded(self): + be = self.backend() + concurrent = A.run_search(be, mkargs()) + real = A.run_branches + A.run_branches = serial_run_branches + try: + serial = A.run_search(be, mkargs()) + finally: + A.run_branches = real + self.assertEqual(serial, EXPECTED["hybrid_default"]) + self.assertEqual(concurrent, EXPECTED["hybrid_default"]) + + def test_single_branch_envelopes_match_recorded(self): + be = self.backend() + self.assertEqual( + A.run_search(be, mkargs(mode="fts")), EXPECTED["fts_default"] + ) + self.assertEqual( + A.run_search(be, mkargs(mode="vector")), EXPECTED["vector_default"] + ) + + def test_branches_actually_overlap(self): + be = self.backend() + A.run_search(be, mkargs()) # warm the matrix cache + orig_execute, orig_vs = be.execute, be.vector_search + + def slow_execute(sql, args=()): + if "chunks_fts MATCH" in sql: + time.sleep(0.6) + return orig_execute(sql, args) + + def slow_vs(qvec, allowed, pool): + time.sleep(0.6) + return orig_vs(qvec, allowed, pool) + + be.execute, be.vector_search = slow_execute, slow_vs + try: + real = A.run_branches + A.run_branches = serial_run_branches + try: + t0 = time.monotonic() + A.run_search(be, mkargs()) + serial_s = time.monotonic() - t0 + finally: + A.run_branches = real + t0 = time.monotonic() + A.run_search(be, mkargs()) + concurrent_s = time.monotonic() - t0 + finally: + be.execute, be.vector_search = orig_execute, orig_vs + # The injected sleeps really engaged on the serial shape... + self.assertGreaterEqual(serial_s, 1.15) + # ...and the concurrent shape overlaps them instead of summing. + self.assertLess(concurrent_s, 1.0) + + def test_local_branch_die_exits_with_code(self): + be = self.backend() + orig_execute = be.execute + + def dying_execute(sql, args=()): + if "chunks_fts MATCH" in sql: + raise SystemExit(2) + return orig_execute(sql, args) + + be.execute = dying_execute + try: + with self.assertRaises(SystemExit) as cm: + A.run_search(be, mkargs()) + self.assertEqual(cm.exception.code, 2) + finally: + be.execute = orig_execute + + def test_turso_branch_die_exits_with_code(self): + be = object.__new__(A.TursoBackend) + be.vec_table = A.VEC_TABLE + be.token = "unused" + be.token_source = "test" + + def dying_pipeline(stmts): + raise SystemExit(3) + + be.pipeline = dying_pipeline + with self.assertRaises(SystemExit) as cm: + A.run_search(be, mkargs()) + self.assertEqual(cm.exception.code, 3) + + +if __name__ == "__main__": + unittest.main(verbosity=2)