[Performance] Warm-query latency on small collections with query() and query_internal_ids() in v0.8.0

Abierto
#841 0 comentarios 0 reacciones 2 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

@egolearner ya está trabajando en esto.

Desde el 22/10/2026.

Evaluación

Este issue todavía no se ha evaluado.

Descripción

Description

Small collections are common in embedded retrieval applications. zvec provides persistent storage and indexing beyond an in-memory baseline, but the query latency gap is worth investigating even when only IDs are requested.

The following benchmark compares both zvec query APIs against straightforward in-memory implementations on 100, 1,000 and 10,000 records. It measures warmed-up queries only, excluding collection creation, opening and first-query initialization.

Environment and methodology

  • Apple M4 Pro, macOS 26.6.2 arm64.
  • Python 3.12.13, zvec 0.8.0, NumPy 2.5.4 with Apple Accelerate.
  • zvec query threads and BLAS thread settings configured to 1.
  • Read-only collections; Top-K = 10; 20 deterministic queries.
  • Each API call contains exactly one query and runs synchronously. Queries and reader processes run sequentially: no batching and no concurrent requests.
  • Each reader process executes all 20 queries once before timing, then measures 400 individual queries. Six processes per backend and dataset size cover all backend execution-order permutations, yielding 2,400 warm samples per backend/size.
  • Imports, index preparation and correctness checks are excluded. Timings include Python query construction, SDK/binding overhead and native query execution. These are single-request latencies, not batch-throughput or pure C++ kernel measurements.

API configurations:

  • query(): output_fields=[], include_vector=False; returns external IDs and scores.
  • query_internal_ids(): return_scores=False; returns internal IDs only. No resolve_internal_ids() or ID-mapping cache is used.

These APIs return different amounts of information, so the comparison also shows how much the lighter output path helps.

Results

All values below are P50 latency in microseconds; lower is better.

Dense retrieval

Exact cosine search over 2,560-dimensional FP32 vectors using a Flat index.

The NumPy baseline caches corpus normalization, then performs query normalization, matrix-vector multiplication and Top-K selection during each timed query.

Records NumPy zvec query() zvec query_internal_ids()
100 8.1 54.4 30.4
1,000 39.9 273.9 251.8
10,000 1,071.2 2,651.9 2,572.6

query_internal_ids() reduces latency relative to query() by approximately 44%, 8% and 3%, respectively. It remains approximately 3.7×, 6.3× and 2.4× slower than NumPy.

Dense Top-10 IDs and ordering match the NumPy baseline for every validation query.

Full-text retrieval

BM25 with k1=1.2, b=0.75, standard tokenization and lowercasing. The baseline is a handwritten Python inverted index with query-time BM25 scoring and heapq.nlargest() Top-K selection—not NumPy.

Records Python BM25 zvec query() zvec query_internal_ids()
100 16.3 102.2 101.8
1,000 133.6 430.4 430.7
10,000 2,471.0 4,381.4 4,378.9

The ID-only API provides no consistent P50 improvement in this FTS workload. Its latency remains approximately 6.3×, 3.2× and 1.8× that of the Python baseline.

This synthetic corpus contains 32 distinct words, 12–24 tokens per document and two-word OR queries, matching approximately 67% of documents. It is a high-match-rate workload, not representative of every FTS use case. BM25 scores match within FP32 tolerance; tied scores can produce different Top-10 document selections.

Discussion

The lighter API substantially helps dense retrieval at 100 records, but does not eliminate the gap. Its benefit becomes smaller as the dense collection grows, while FTS shows little benefit at these settings. These measurements therefore do not establish result materialization as the sole bottleneck.

The absolute differences are small and may be insignificant in remote-model workflows, but matter more for fully local retrieval or repeated queries.

Are there recommended configurations or execution paths to reduce this overhead? In particular:

  • Can exact dense retrieval on small collections get closer to the NumPy baseline?
  • Can ID-only FTS avoid more of the work performed by the regular query path?

Reproduction

Save the three scripts below as repro.py, dense_scale.py and fts_scale.py in the same directory:

python -m pip install 'numpy==2.5.4' 'zvec==0.8.0'
python dense_scale.py dense-results.json
python fts_scale.py fts-results.json

Both original JSON reports are also included below, with per-run measurements, P50/P95 latency and validation results.

repro.py
"""Reproduce small-corpus hybrid-search overhead without Qwen or remote models.

Install: python -m pip install 'numpy==2.5.4' 'zvec==0.8.0'
Run:     python repro.py [result.json]

Protocol 2: synthetic 81 x 2560 FP32 vectors, unfiltered exact cosine + BM25 +
RRF + identical Top-10 fields/scores. Both routes use the same deterministic
tie rule (scores rounded to 5 decimals, then numeric ID). This is a controlled
application-workflow comparison, NOT a native-kernel or relevance benchmark.

Both dependencies and runtime configuration are initialized before timing.
Workers request one query/BLAS/indexing thread. Write timing includes payload
preparation, API save/flush/close, and a COMMON barrier: fsync every artifact
file and directory; on macOS also F_FULLFSYNC after directory sync. No silent
fallback is allowed. This requests equal OS durability, not a power-loss test.
NPZ stores data only and rebuilds BM25 on load; zvec persists a vector/text
index. These different implementation costs belong to the application paths;
their write or open phases alone are not equal-work engine comparisons.

Every repetition uses new stores and separate writer/reader processes. Artifact
bytes are pre-read before opening BOTH backends: process-fresh, warm OS cache,
NOT disk-cold startup. First query position rotates; backend order is balanced.
Full returned fields, route scores/ranks and final result order must match
within stated FP32 tolerances, or the run FAILS without publishing timings.
Protocol-1 reports must not be mixed with these results.
"""

import fcntl
import importlib.metadata
import json
import math
import os
import platform
import subprocess
import sys
import tempfile
import time
from collections import Counter, defaultdict
from pathlib import Path

import numpy as np
import zvec

N, DIM, TOPK, QUERIES, RUNS, REPEATS = 81, 2560, 10, 20, 6, 20
FIELDS = ["node_id", "node_type", "macro_id", "text"]
SCORE_DECIMALS = 5
THREAD_ENV = {
    key: "1"
    for key in (
        "OPENBLAS_NUM_THREADS",
        "OMP_NUM_THREADS",
        "MKL_NUM_THREADS",
        "BLIS_NUM_THREADS",
        "VECLIB_MAXIMUM_THREADS",
    )
}


def timed(fn, *args):
    start = time.perf_counter_ns()
    value = fn(*args)
    return value, (time.perf_counter_ns() - start) / 1e6


def artifact_files(path):
    if path.is_symlink():
        raise RuntimeError("Refusing to follow a symlink artifact root")
    paths = [path] if path.is_file() else sorted(path.rglob("*"))
    if any(p.is_symlink() for p in paths):
        raise RuntimeError("Refusing to follow symlinks in benchmark artifacts")
    return [p for p in paths if p.is_file()]


def sync_artifact(path):
    """Same explicit OS-sync boundary for each backend; failures are fatal."""
    files = artifact_files(path)
    if not files:
        raise RuntimeError("No artifact files to synchronize")
    for file in files:
        fd = os.open(file, os.O_RDWR)
        try:
            os.fsync(fd)
        finally:
            os.close(fd)
    directories = {path.parent}
    if path.is_dir():
        directories |= {path} | {p for p in path.rglob("*") if p.is_dir()}
    for directory in sorted(directories, key=lambda p: (-len(p.parts), str(p))):
        fd = os.open(directory, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))
        try:
            os.fsync(fd)
        finally:
            os.close(fd)
    if sys.platform == "darwin":
        # All artifacts are on one filesystem; request device-cache flush LAST.
        fd = os.open(files[0], os.O_RDWR)
        try:
            fcntl.fcntl(fd, fcntl.F_FULLFSYNC)
        finally:
            os.close(fd)
    return {"files": len(files), "directories": len(directories)}


def warm_artifact(path):
    for file in artifact_files(path):
        with file.open("rb") as handle:
            while handle.read(1024 * 1024):
                pass


def rank(items):
    return sorted(items, key=lambda item: (-round(item[1], SCORE_DECIMALS), int(item[0])))


def build_bm25(nodes):
    tokens = [node["text"].split() for node in nodes]  # Lowercase ASCII fixture.
    avg_dl = sum(map(len, tokens)) / len(tokens)
    df = Counter(token for doc in tokens for token in set(doc))
    postings = defaultdict(list)
    for i, doc in enumerate(tokens):
        for token, tf in Counter(doc).items():
            idf = math.log(1 + (N - df[token] + 0.5) / (df[token] + 0.5))
            postings[token].append((str(i), tf, idf, len(doc)))
    return postings, avg_dl


def sparse_search(index, query):
    postings, avg_dl = index
    scores = defaultdict(float)
    for token in query.split():
        for doc_id, tf, idf, dl in postings.get(token, ()):
            scores[doc_id] += idf * tf * 2.2 / (tf + 1.2 * (0.25 + 0.75 * dl / avg_dl))
    return list(scores.items())


def fuse(dense, sparse):
    # Same zero-based RRF (k=60) implementation for both backends.
    dense, sparse = rank(dense), rank(sparse)
    scores = {i: 1 / (60 + position) for position, (i, _) in enumerate(dense)}
    for position, (i, _) in enumerate(sparse):
        scores[i] = scores.get(i, 0) + 1 / (60 + position)
    cosine = dict(dense)
    return [(i, scores[i], cosine[i]) for i in sorted(scores, key=lambda i: (-scores[i], int(i)))[:TOPK]]


def build_fixture(root):
    rng = np.random.default_rng(20261022)
    vectors = rng.standard_normal((N, DIM), dtype=np.float32)
    words = [f"word{i}" for i in range(32)]
    nodes = [
        {
            "node_id": str(i),
            "node_type": "event",
            "macro_id": str(i // 10),
            "text": " ".join(rng.choice(words, size=int(rng.integers(12, 25)))),
        }
        for i in range(N)
    ]
    np.savez(root / "input.npz", embeddings=vectors, nodes=json.dumps(nodes))
    positions = rng.choice(N, size=QUERIES, replace=False)
    queries = [" ".join(nodes[i]["text"].split()[:2]) for i in positions]
    np.savez(root / "queries.npz", vectors=vectors[positions], texts=json.dumps(queries))


def zvec_payload(nodes, vectors):
    schema = zvec.CollectionSchema(
        name="small_memory",
        fields=[
            zvec.FieldSchema("node_id", zvec.DataType.STRING),
            zvec.FieldSchema("node_type", zvec.DataType.STRING),
            zvec.FieldSchema("macro_id", zvec.DataType.STRING),
            zvec.FieldSchema(
                "text",
                zvec.DataType.STRING,
                index_param=zvec.FtsIndexParam(tokenizer_name="standard", filters=["lowercase"]),
            ),
        ],
        vectors=zvec.VectorSchema(
            "embedding",
            zvec.DataType.VECTOR_FP32,
            DIM,
            index_param=zvec.FlatIndexParam(metric_type=zvec.MetricType.COSINE),
        ),
    )
    docs = [zvec.Doc(id=str(i), fields=nodes[i], vectors={"embedding": vectors[i].tolist()}) for i in range(N)]
    return schema, docs


def write_worker(backend, root):
    with np.load(root / "input.npz", allow_pickle=False) as data:
        nodes, vectors = json.loads(str(data["nodes"])), data["embeddings"]
    started = time.perf_counter_ns()  # Both backends start with the same Python records and FP32 matrix.
    if backend == "npz":
        metadata, prepare_ms = timed(json.dumps, nodes)
        _, save_ms = timed(lambda: np.savez(root / "corpus.npz", embeddings=vectors, nodes=metadata))
        sync_counts, sync_ms = timed(sync_artifact, root / "corpus.npz")
        total_ms = (time.perf_counter_ns() - started) / 1e6
        return {
            "write_total_ms": total_ms,
            "write_prepare_ms": prepare_ms,
            "write_save_close_ms": save_ms,
            "write_common_sync_ms": sync_ms,
            "sync_counts": sync_counts,
        }
    (schema, docs), prepare_ms = timed(zvec_payload, nodes, vectors)
    collection, create_ms = timed(zvec.create_and_open, str(root / "collection"), schema)
    try:
        statuses, insert_ms = timed(collection.insert, docs)
        _, flush_ms = timed(collection.flush)
    finally:
        _, close_ms = timed(collection.close)
    sync_counts, sync_ms = timed(sync_artifact, root / "collection")
    total_ms = (time.perf_counter_ns() - started) / 1e6
    assert len(statuses) == N and all(s.ok() for s in statuses), statuses
    return {
        "write_total_ms": total_ms,
        "write_prepare_ms": prepare_ms,
        "write_create_ms": create_ms,
        "write_insert_ms": insert_ms,
        "write_flush_ms": flush_ms,
        "write_close_ms": close_ms,
        "write_common_sync_ms": sync_ms,
        "sync_counts": sync_counts,
    }


def worker(backend, root, first_position=0):
    with np.load(root / "queries.npz", allow_pickle=False) as data:
        queries, vectors = json.loads(str(data["texts"])), data["vectors"]
    collection = None
    warm_artifact(root / ("corpus.npz" if backend == "npz" else "collection"))
    if backend == "npz":

        def load():
            with np.load(root / "corpus.npz", allow_pickle=False) as data:
                nodes, embeddings = json.loads(str(data["nodes"])), data["embeddings"]
            return nodes, embeddings, build_bm25(nodes)

        (nodes, embeddings, sparse_index), open_ms = timed(load)
        normalized = None

        def routes(vector, query):
            nonlocal normalized
            if normalized is None:  # Application's lazy cosine-normalization cache.
                normalized = embeddings / np.linalg.norm(embeddings, axis=1, keepdims=True)
            scores = normalized @ (vector / np.linalg.norm(vector))
            return [(str(i), float(s)) for i, s in enumerate(scores)], sparse_search(sparse_index, query)

        def fetch(ids):
            return {i: nodes[int(i)] for i in ids}
    else:
        collection, open_ms = timed(zvec.open, str(root / "collection"), zvec.CollectionOption(read_only=True))

        def routes(vector, query):
            # Full rankings are an exact-RRF application choice, NOT a zvec requirement.
            dense = collection.query(
                zvec.Query(field_name="embedding", vector=vector), topk=N, output_fields=[], include_vector=False
            )
            sparse = collection.query(
                zvec.Query(field_name="text", fts=zvec.Fts(match_string=query)),
                topk=N,
                output_fields=[],
                include_vector=False,
            )
            return [(d.id, 1 - float(d.score)) for d in dense], [(d.id, float(d.score)) for d in sparse]

        def fetch(ids):
            docs = collection.fetch(ids, output_fields=FIELDS, include_vector=False)
            return {i: docs[i].fields for i in ids}

    def search(vector, query):
        selected = fuse(*routes(vector, query))
        docs = fetch([i for i, _, _ in selected])
        return [dict(docs[i], score=round(s, 6), cosine=round(c, 4)) for i, s, c in selected]

    try:
        _, first_ms = timed(search, vectors[first_position], queries[first_position])
        results = [search(v, q) for v, q in zip(vectors, queries, strict=True)]  # Warm all inputs.
        order = np.random.default_rng(20261022 + first_position).permutation(len(queries))
        warm_ms = [timed(search, vectors[i], queries[i])[1] for _ in range(REPEATS) for i in order]
        assert all(len(rows) == TOPK for rows in results)
        # Reopen checks run in a separate process from the writer and OUTSIDE timed sections.
        with np.load(root / "input.npz", allow_pickle=False) as data:
            raw, expected_nodes = data["embeddings"], json.loads(str(data["nodes"]))
        if collection is not None:
            # Untimed sanity check with explicit FP32 tolerance, not byte identity.
            docs = collection.fetch([str(i) for i in range(N)], output_fields=FIELDS, include_vector=True)
            stored = np.array([docs[str(i)].vectors["embedding"] for i in range(N)])
            np.testing.assert_allclose(stored, raw, rtol=1e-6, atol=1e-7)
            assert [docs[str(i)].fields for i in range(N)] == expected_nodes
        else:
            np.testing.assert_array_equal(embeddings, raw)
            assert nodes == expected_nodes
        # Independently check both complete routes for EVERY query, not just Top-K.
        reference_index = build_bm25(expected_nodes)
        reference_vectors = raw / np.linalg.norm(raw, axis=1, keepdims=True)
        for vector, query, rows in zip(vectors, queries, results, strict=True):
            expected_cosine = reference_vectors @ (vector / np.linalg.norm(vector))
            expected_dense = [(str(i), float(s)) for i, s in enumerate(expected_cosine)]
            expected_sparse = sparse_search(reference_index, query)
            actual_routes = routes(vector, query)
            for actual, expected in zip(actual_routes, (expected_dense, expected_sparse), strict=True):
                a, e = dict(actual), dict(expected)
                assert len(actual) == len(a) and a.keys() == e.keys(), "Candidate IDs differ"
                np.testing.assert_allclose([a[i] for i in e], list(e.values()), rtol=1e-6, atol=1e-6)
                assert [i for i, _ in rank(actual)] == [i for i, _ in rank(expected)], "Route order differs"
            selected = fuse(expected_dense, expected_sparse)
            assert [r["node_id"] for r in rows] == [i for i, _, _ in selected], "Final order differs"
            for row, (i, score, cosine) in zip(rows, selected, strict=True):
                assert {field: row[field] for field in FIELDS} == expected_nodes[int(i)]
                assert row["score"] == round(score, 6)
                assert abs(row["cosine"] - cosine) <= 0.000051
        return {
            "open_ms": open_ms,
            "first_ms": first_ms,
            "open_first_ms": open_ms + first_ms,
            "warm_ms": warm_ms,
            "first_query_position": first_position,
            "ids": [[r["node_id"] for r in rows] for rows in results],
        }
    finally:
        if collection is not None:
            collection.close()


def main():
    assert RUNS % 2 == 0, "Use an even count to balance backend order"
    samples = {"npz": [], "zvec": []}
    with tempfile.TemporaryDirectory(prefix="zvec-small-memory-") as directory:
        for run in range(RUNS):
            root = Path(directory) / f"run-{run}"
            root.mkdir()
            build_fixture(root)
            for backend in ["npz", "zvec"] if run % 2 == 0 else ["zvec", "npz"]:
                sample = {}
                for mode in ("--write", "--worker"):
                    first_position = (run * QUERIES // RUNS) % QUERIES
                    command = [
                        sys.executable,
                        str(Path(__file__).resolve()),
                        mode,
                        backend,
                        str(root),
                        str(first_position),
                    ]
                    process = subprocess.run(
                        command, check=False, text=True, capture_output=True, env=os.environ | THREAD_ENV
                    )
                    if process.returncode:
                        raise RuntimeError(process.stderr or process.stdout)
                    sample.update(json.loads(process.stdout))
                samples[backend].append(sample)
                sample["write_plus_open_first_ms"] = sample["write_total_ms"] + sample["open_first_ms"]
    metrics = {}
    for backend, runs in samples.items():
        values = {key: [r[key] for r in runs] for key in runs[0] if key.endswith("_ms") and key != "warm_ms"}
        values["warm_ms"] = [v for r in runs for v in r["warm_ms"]]
        metrics[backend] = {
            key: {"p50": float(np.median(v)), "p95": float(np.percentile(v, 95))} for key, v in values.items()
        }
    pairs = [
        (a, b)
        for nr, zr in zip(samples["npz"], samples["zvec"], strict=True)
        for a, b in zip(nr["ids"], zr["ids"], strict=True)
    ]
    report = {
        "environment": {
            "python": platform.python_version(),
            "platform": platform.platform(),
            "numpy": np.__version__,
            "zvec": importlib.metadata.version("zvec"),
            "worker_thread_env": THREAD_ENV,
            "zvec_query_threads": 1,
            "zvec_optimize_threads": 1,
        },
        "workload": {
            "nodes": N,
            "dimension": DIM,
            "topk": TOPK,
            "queries": QUERIES,
            "runs": RUNS,
            "warm_repeats": REPEATS,
            "seed": 20261022,
            "synthetic": True,
            "protocol_version": 2,
            "os_cache": "explicit artifact pre-read for both backends; not disk-cold",
            "imports_included": False,
            "runtime_configuration_included": False,
            "phase_sum_excludes_process_startup_and_cache_prewarm": True,
            "write_includes_payload_preparation": True,
            "separate_writer_reader_processes": True,
            "common_sync": "file and directory fsync" + (" + F_FULLFSYNC" if sys.platform == "darwin" else ""),
            "unused_scalar_indexes": False,
            "canonical_score_decimals": SCORE_DECIMALS,
            "phases_are_application_costs_not_equal_work_engine_operations": True,
        },
        "timing_ms": metrics,
        "parity": {
            "mean_top10_set_overlap": float(np.mean([len(set(a) & set(b)) / len(a) for a, b in pairs])),
            "exact_order_agreement": float(np.mean([a == b for a, b in pairs])),
            "all_route_scores_and_fields_validated": True,
        },
        "per_run": {
            backend: [
                {k: v for k, v in sample.items() if k not in ("ids", "warm_ms")}
                | {"warm_p50_ms": float(np.median(sample["warm_ms"]))}
                for sample in runs
            ]
            for backend, runs in samples.items()
        },
    }
    assert report["parity"]["exact_order_agreement"] == 1.0, "Do not publish incomparable result-order timings"
    print(json.dumps(report, indent=2))
    if len(sys.argv) == 2:
        Path(sys.argv[1]).write_text(json.dumps(report, indent=2) + "\n")


if __name__ == "__main__":
    if len(sys.argv) == 2 and sys.argv[1] in ("-h", "--help"):
        print(__doc__)
    elif len(sys.argv) == 5 and sys.argv[1] in ("--write", "--worker"):
        zvec.init(query_threads=1, optimize_threads=1)
        result = (
            write_worker(sys.argv[2], Path(sys.argv[3]))
            if sys.argv[1] == "--write"
            else worker(sys.argv[2], Path(sys.argv[3]), int(sys.argv[4]))
        )
        print(json.dumps(result))
    elif len(sys.argv) <= 2:
        main()
    else:
        raise SystemExit("Usage: python repro.py [result.json]")
dense_scale.py
"""Dense Top-10 hot-query scaling: NumPy vs both zvec 0.8 query APIs.

Run with the isolated zvec 0.8 environment:
    python dense_scale.py [result.json]

Same raw FP32 queries, exact cosine, sorted Top-10 numeric IDs. NumPy caches
corpus normalization outside timing, as index preparation; query normalization,
matrix multiplication, argpartition and final sorting are timed. Zvec uses
Flat/COSINE, a read-only collection, return_scores=False, and no ID resolution.
The internal-ID path and NumPy output ID arrays. Ordinary query() returns Doc
objects with external IDs/scores and no fields/vectors. Its output is therefore
richer; no application-side conversion is added to its timed interval.
Zvec query construction/SDK/binding work is timed;
this is an API comparison, not isolated C++ kernel timing.

Each size has six fresh reader processes per backend in all six backend orders,
20 warmed queries and 20 timed repetitions. BLAS and zvec request one thread.
Imports, creation, open, corpus normalization and validation are outside timing.
Collections keep the earlier repro's vector + metadata + FTS schema, but this
test runs only dense, unfiltered queries. Queries are independent random vectors,
not corpus self-matches. Counts are 100/1000/10000, dimension 2560, K=10.

Before timing, public zvec query validates that returned internal IDs match
the controlled sequential fixture's numeric row IDs, and both backends must
match NumPy Top-10 exactly. No resolve_internal_ids or ID mapping cache is used.
Different corpus sizes and independent queries make these results distinct from
the earlier 81-node, full-candidate hybrid benchmark. No disk durability or
startup claim is made here. Temp stores are deleted after successful/failed runs.
"""

from __future__ import annotations

import importlib.metadata
import itertools
import json
import os
import platform
import subprocess
import sys
import tempfile
import time
from pathlib import Path

import numpy as np
import zvec
from repro import DIM, FIELDS, THREAD_ENV, warm_artifact

SIZES = (100, 1000, 10000)
TOPK, QUERIES, RUNS, REPEATS, SEED = 10, 20, 6, 20, 20261022


def numpy_query(normalized: np.ndarray, vector: np.ndarray) -> np.ndarray:
    scores = normalized @ (vector / np.linalg.norm(vector))
    candidates = np.argpartition(scores, len(scores) - TOPK)[-TOPK:]
    return candidates[np.argsort(scores[candidates])[::-1]].astype(np.int64, copy=False)


def prepare(root: Path, count: int) -> None:
    # Identical corpus prefixes and queries at every scale.
    vectors = np.random.default_rng(SEED).standard_normal((count, DIM), dtype=np.float32)
    queries = np.random.default_rng(SEED + 1).standard_normal((QUERIES, DIM), dtype=np.float32)
    np.save(root / "vectors.npy", vectors)
    np.save(root / "queries.npy", queries)
    schema = zvec.CollectionSchema(
        name="small_memory",
        fields=[zvec.FieldSchema(name, zvec.DataType.STRING) for name in FIELDS if name != "text"]
        + [
            zvec.FieldSchema(
                "text",
                zvec.DataType.STRING,
                index_param=zvec.FtsIndexParam(tokenizer_name="standard", filters=["lowercase"]),
            )
        ],
        vectors=zvec.VectorSchema(
            "embedding",
            zvec.DataType.VECTOR_FP32,
            DIM,
            index_param=zvec.FlatIndexParam(metric_type=zvec.MetricType.COSINE),
        ),
    )
    collection = zvec.create_and_open(str(root / "collection"), schema)
    try:
        for offset in range(0, count, 256):
            docs = [
                zvec.Doc(
                    id=str(i),
                    fields=dict(zip(FIELDS, (str(i), "event", str(i // 10), f"event word{i % 32}"))),
                    vectors={"embedding": vectors[i].tolist()},
                )
                for i in range(offset, min(offset + 256, count))
            ]
            statuses = collection.insert(docs)
            if len(statuses) != len(docs) or not all(status.ok() for status in statuses):
                raise RuntimeError(f"Insert failed at batch {offset}")
        collection.flush()
    finally:
        collection.close()


def validate(root: Path) -> dict:
    raw = np.load(root / "vectors.npy", allow_pickle=False)
    queries = np.load(root / "queries.npy", allow_pickle=False)
    normalized = raw / np.linalg.norm(raw, axis=1, keepdims=True)
    expected = []
    margins = []
    collection = zvec.open(str(root / "collection"), zvec.CollectionOption(read_only=True))
    try:
        for vector in queries:
            scores = normalized @ (vector / np.linalg.norm(vector))
            ids = numpy_query(normalized, vector)
            np.testing.assert_array_equal(ids, np.argsort(scores)[::-1][:TOPK])
            ordered = np.sort(scores)[::-1]
            margins.append(float(ordered[TOPK - 1] - ordered[TOPK]))
            query = zvec.Query(field_name="embedding", vector=vector)
            internal = collection.query_internal_ids(query, topk=TOPK, return_scores=False)
            public = collection.query(query, topk=TOPK, output_fields=[], include_vector=False)
            # Fixture-specific identity checked, never assumed for arbitrary databases.
            np.testing.assert_array_equal(internal, [int(doc.id) for doc in public])
            np.testing.assert_array_equal(internal, ids)
            np.testing.assert_allclose([1 - doc.score for doc in public], scores[ids], rtol=1e-6, atol=1e-6)
            expected.append(ids)
    finally:
        collection.close()
    np.save(root / "expected.npy", np.asarray(expected, dtype=np.int64))
    return {"exact_order_agreement": 1.0, "min_topk_boundary_margin": min(margins)}


def worker(root: Path, backend: str, run: int) -> dict:
    queries = np.load(root / "queries.npy", allow_pickle=False)
    expected = np.load(root / "expected.npy", allow_pickle=False)
    collection = None
    if backend == "numpy":
        raw = np.load(root / "vectors.npy", allow_pickle=False)
        normalized = raw / np.linalg.norm(raw, axis=1, keepdims=True)
        del raw

        def search(vector):
            return numpy_query(normalized, vector)
    else:
        warm_artifact(root / "collection")
        collection = zvec.open(str(root / "collection"), zvec.CollectionOption(read_only=True))

        def search(vector):
            if backend == "zvec_query":
                return collection.query(
                    zvec.Query(field_name="embedding", vector=vector),
                    topk=TOPK,
                    output_fields=[],
                    include_vector=False,
                )
            return collection.query_internal_ids(
                zvec.Query(field_name="embedding", vector=vector), topk=TOPK, return_scores=False
            )

    def check(result, ids):
        if backend == "zvec_query":
            assert all(not doc.fields and not doc.vectors for doc in result)
            result = np.asarray([int(doc.id) for doc in result], dtype=np.int64)
        np.testing.assert_array_equal(result, ids)

    try:
        for vector, ids in zip(queries, expected, strict=True):
            check(search(vector), ids)
        order = np.random.default_rng(SEED + run).permutation(QUERIES)
        times = []
        for _ in range(REPEATS):
            for position in order:
                vector = queries[position]
                start = time.perf_counter_ns()
                result = search(vector)
                elapsed = (time.perf_counter_ns() - start) / 1000
                times.append(elapsed)
                del result
        for vector, ids in zip(queries, expected, strict=True):
            check(search(vector), ids)
        return {"times_us": times}
    finally:
        if collection is not None:
            collection.close()


def child(*args: str) -> dict:
    process = subprocess.run(
        [sys.executable, str(Path(__file__).resolve()), *args],
        env=os.environ | THREAD_ENV,
        check=False,
        capture_output=True,
        text=True,
    )
    if process.returncode:
        raise RuntimeError(process.stderr or process.stdout)
    return json.loads(process.stdout)


def main() -> None:
    report = {
        "environment": {
            "python": platform.python_version(),
            "platform": platform.platform(),
            "cpu": (
                subprocess.check_output(["sysctl", "-n", "machdep.cpu.brand_string"], text=True).strip()
                if sys.platform == "darwin"
                else platform.processor()
            ),
            "numpy": np.__version__,
            "numpy_blas": getattr(np.__config__, "CONFIG", {}).get("Build Dependencies", {}).get("blas", {}),
            "zvec": importlib.metadata.version("zvec"),
            "worker_thread_env": THREAD_ENV,
            "zvec_query_threads": 1,
            "zvec_optimize_threads": 1,
        },
        "workload": {
            "dimension": DIM,
            "topk": TOPK,
            "queries": QUERIES,
            "runs": RUNS,
            "warm_repeats": REPEATS,
            "seed": SEED,
            "query_source": "independent random FP32 vectors",
            "return_scores": False,
            "backend_apis": {
                "numpy": "exact cosine and sorted Top-10 int64 row IDs",
                "zvec": "query_internal_ids(return_scores=False); internal int64 IDs",
                "zvec_query": "query(output_fields=[], include_vector=False); Doc external IDs and scores",
            },
            "resolve_calls": 0,
            "imports_open_and_corpus_normalization_included": False,
            "query_normalization_selection_sort_and_api_overhead_included": True,
            "new_stores_no_deletions_sequential_fixture_ids": True,
            "insert_batch_size": 256,
            "notes": "Same exact dense cosine Top-10; API outputs differ as documented; no FTS/filter/fusion/field fetch; API not C++ kernel timing",
        },
        "results": [],
    }
    with tempfile.TemporaryDirectory(prefix="zvec-dense-scale-") as directory:
        for count in SIZES:
            root = Path(directory) / str(count)
            root.mkdir()
            print(f"Preparing and validating {count} vectors", file=sys.stderr, flush=True)
            parity = child("--prepare", str(root), str(count))
            samples = {backend: [] for backend in ("numpy", "zvec", "zvec_query")}
            orders = list(itertools.permutations(samples))
            assert len(orders) == RUNS
            for run, order in enumerate(orders):
                for backend in order:
                    samples[backend].append(child("--worker", str(root), backend, str(run))["times_us"])
                print(f"{count} vectors: round {run + 1}/{RUNS} complete", file=sys.stderr, flush=True)
            result = {"nodes": count, "raw_vectors_mib": count * DIM * 4 / (1024 * 1024), "parity": parity}
            for backend, runs in samples.items():
                flat = [value for run in runs for value in run]
                result[backend] = {
                    "p50_us": float(np.median(flat)),
                    "p95_us": float(np.percentile(flat, 95)),
                    "samples": len(flat),
                    "per_run_p50_us": [float(np.median(run)) for run in runs],
                }
            result["zvec_over_numpy_p50"] = result["zvec"]["p50_us"] / result["numpy"]["p50_us"]
            result["query_over_internal_ids_p50"] = result["zvec_query"]["p50_us"] / result["zvec"]["p50_us"]
            report["results"].append(result)
    encoded = json.dumps(report, indent=2) + "\n"
    if len(sys.argv) == 2:
        Path(sys.argv[1]).write_text(encoded)
    print(encoded)


if __name__ == "__main__":
    if len(sys.argv) >= 2 and sys.argv[1].startswith("--"):
        zvec.init(query_threads=1, optimize_threads=1)
        if sys.argv[1] == "--prepare":
            prepare(Path(sys.argv[2]), int(sys.argv[3]))
            print(json.dumps(validate(Path(sys.argv[2]))))
        elif sys.argv[1] == "--worker":
            print(json.dumps(worker(Path(sys.argv[2]), sys.argv[3], int(sys.argv[4]))))
        else:
            raise SystemExit("Usage: python dense_scale.py [result.json]")
    elif len(sys.argv) <= 2:
        main()
    else:
        raise SystemExit("Usage: python dense_scale.py [result.json]")
fts_scale.py
"""FTS Top-10 hot queries: Python BM25 vs both zvec APIs, 100/1k/10k docs.

Run: python fts_scale.py [result.json]

The controlled fixture uses 32 lowercase ASCII words, 12-24 tokens per document,
and 20 fixed two-distinct-word OR queries. Corpus prefixes/queries are identical
across scales. This is a high-match-rate synthetic workload, not natural-language
relevance evaluation. Full-vector/metadata/FTS schema matches the earlier repro.

Python builds the earlier repro's BM25 inverted index (k1=1.2, b=.75) before
timing. A query includes tokenization, posting traversal, scoring, heap Top-K
selection and ordered int64 ID-array creation. Zvec uses query_internal_ids with
return_scores=False and a read-only collection; query construction is timed.
Ordinary query() is also timed, returning Doc objects with external IDs/scores
and no fields/vectors. This richer output is not converted in the timed region.
There is no resolve_internal_ids, mapping cache, reranking or field fetch.

Before measurement, validate all matching scores via the ordinary zvec query API
and validate native IDs against the controlled fixture's external numeric IDs.
BM25 ties need not choose the same IDs: report exact-ID agreement separately and
require the returned Top-K score sequence to match within FP32 tolerance.
All paths rank Top-10, with arbitrary order among ties and API-specific output.
Six fresh readers/backend/scale, all six backend orders, 20 warmed queries,
20 repetitions, single-thread requests. Imports/open/index build are excluded.
"""

from __future__ import annotations

import heapq
import importlib.metadata
import itertools
import json
import os
import platform
import subprocess
import sys
import tempfile
import time
from pathlib import Path

import numpy as np
import repro
import zvec
from dense_scale import DIM, QUERIES, REPEATS, RUNS, SEED, SIZES, TOPK

VOCABULARY = 32


def python_query(index, query):
    pairs = repro.sparse_search(index, query)
    selected = heapq.nlargest(TOPK, pairs, key=lambda item: item[1])
    return np.asarray([int(doc_id) for doc_id, _ in selected], dtype=np.int64)


def prepare(root, count):
    rng = np.random.default_rng(SEED + 2)
    words = [f"word{i}" for i in range(VOCABULARY)]
    nodes = [
        {
            "node_id": str(i),
            "node_type": "event",
            "macro_id": str(i // 10),
            "text": " ".join(rng.choice(words, size=int(rng.integers(12, 25)))),
        }
        for i in range(count)
    ]
    query_rng = np.random.default_rng(SEED + 3)
    queries = [" ".join(query_rng.choice(words, size=2, replace=False)) for _ in range(QUERIES)]
    (root / "fixture.json").write_text(json.dumps({"nodes": nodes, "queries": queries}))
    vectors = np.random.default_rng(SEED).standard_normal((count, DIM), dtype=np.float32)
    schema = zvec.CollectionSchema(
        name="small_memory",
        fields=[zvec.FieldSchema(name, zvec.DataType.STRING) for name in repro.FIELDS if name != "text"]
        + [
            zvec.FieldSchema(
                "text",
                zvec.DataType.STRING,
                index_param=zvec.FtsIndexParam(tokenizer_name="standard", filters=["lowercase"]),
            )
        ],
        vectors=zvec.VectorSchema(
            "embedding",
            zvec.DataType.VECTOR_FP32,
            DIM,
            index_param=zvec.FlatIndexParam(metric_type=zvec.MetricType.COSINE),
        ),
    )
    collection = zvec.create_and_open(str(root / "collection"), schema)
    try:
        for offset in range(0, count, 256):
            docs = [
                zvec.Doc(id=str(i), fields=nodes[i], vectors={"embedding": vectors[i].tolist()})
                for i in range(offset, min(offset + 256, count))
            ]
            statuses = collection.insert(docs)
            assert len(statuses) == len(docs) and all(status.ok() for status in statuses)
        collection.flush()
    finally:
        collection.close()


def check_topk(ids, scores):
    ids = ids.tolist()
    assert len(ids) == min(TOPK, len(scores)) and len(set(ids)) == len(ids)
    assert all(str(i) in scores for i in ids)
    expected = sorted(scores.values(), reverse=True)[:TOPK]
    actual = [scores[str(i)] for i in ids]
    np.testing.assert_allclose(actual, expected, rtol=1e-6, atol=1e-6)


def validate(root):
    fixture = json.loads((root / "fixture.json").read_text())
    repro.N = len(fixture["nodes"])
    index = repro.build_bm25(fixture["nodes"])
    checks, overlaps, orders, match_counts = [], [], [], []
    collection = zvec.open(str(root / "collection"), zvec.CollectionOption(read_only=True))
    try:
        for text in fixture["queries"]:
            scores = dict(repro.sparse_search(index, text))
            query = zvec.Query(field_name="text", fts=zvec.Fts(match_string=text))
            all_docs = collection.query(query, topk=repro.N, output_fields=[], include_vector=False)
            native_scores = {doc.id: doc.score for doc in all_docs}
            assert native_scores.keys() == scores.keys()
            np.testing.assert_allclose([native_scores[k] for k in scores], list(scores.values()), rtol=1e-6, atol=1e-6)
            ids = collection.query_internal_ids(query, topk=TOPK, return_scores=False)
            public_topk = collection.query(query, topk=TOPK, output_fields=[], include_vector=False)
            np.testing.assert_array_equal(ids, [int(doc.id) for doc in public_topk])
            py_ids = python_query(index, text)
            check_topk(ids, scores)
            check_topk(py_ids, scores)
            orders.append(bool(np.array_equal(ids, py_ids)))
            overlaps.append(len(set(ids.tolist()) & set(py_ids.tolist())) / TOPK)
            match_counts.append(len(scores))
            checks.append(scores)
    finally:
        collection.close()
    (root / "checks.json").write_text(json.dumps(checks))
    lengths = [len(node["text"].split()) for node in fixture["nodes"]]
    return {
        "all_matching_scores_and_topk_score_sequences_validated": True,
        "exact_id_order_agreement": float(np.mean(orders)),
        "mean_topk_id_set_overlap": float(np.mean(overlaps)),
        "mean_matching_documents": float(np.mean(match_counts)),
        "mean_document_tokens": float(np.mean(lengths)),
        "text_utf8_bytes": sum(len(node["text"].encode()) for node in fixture["nodes"]),
        "note": "Exact-ID differences allowed only when Top-K scores agree within stated FP32 tolerance",
    }


def worker(root, backend, run):
    fixture = json.loads((root / "fixture.json").read_text())
    checks = json.loads((root / "checks.json").read_text())
    queries = fixture["queries"]
    collection = None
    if backend == "python_bm25":
        repro.N = len(fixture["nodes"])
        index = repro.build_bm25(fixture["nodes"])

        def search(text):
            return python_query(index, text)
    else:
        repro.warm_artifact(root / "collection")
        collection = zvec.open(str(root / "collection"), zvec.CollectionOption(read_only=True))

        def search(text):
            if backend == "zvec_query":
                return collection.query(
                    zvec.Query(field_name="text", fts=zvec.Fts(match_string=text)),
                    topk=TOPK,
                    output_fields=[],
                    include_vector=False,
                )
            return collection.query_internal_ids(
                zvec.Query(field_name="text", fts=zvec.Fts(match_string=text)), topk=TOPK, return_scores=False
            )

    def check(result, scores):
        if backend == "zvec_query":
            assert all(not doc.fields and not doc.vectors for doc in result)
            result = np.asarray([int(doc.id) for doc in result], dtype=np.int64)
        check_topk(result, scores)

    del fixture
    try:
        for text, scores in zip(queries, checks, strict=True):
            check(search(text), scores)
        order = np.random.default_rng(SEED + run).permutation(QUERIES)
        samples = []
        for _ in range(REPEATS):
            for i in order:
                text = queries[i]
                start = time.perf_counter_ns()
                result = search(text)
                samples.append((time.perf_counter_ns() - start) / 1000)
                del result
        for text, scores in zip(queries, checks, strict=True):
            check(search(text), scores)
        return {"times_us": samples}
    finally:
        if collection is not None:
            collection.close()


def child(*args):
    p = subprocess.run(
        [sys.executable, str(Path(__file__).resolve()), *args],
        env=os.environ | repro.THREAD_ENV,
        capture_output=True,
        text=True,
        check=False,
    )
    if p.returncode:
        raise RuntimeError(p.stderr or p.stdout)
    return json.loads(p.stdout)


def main():
    report = {
        "environment": {
            "platform": platform.platform(),
            "python": platform.python_version(),
            "cpu": subprocess.check_output(["sysctl", "-n", "machdep.cpu.brand_string"], text=True).strip()
            if sys.platform == "darwin"
            else platform.processor(),
            "numpy": np.__version__,
            "zvec": importlib.metadata.version("zvec"),
            "worker_thread_env": repro.THREAD_ENV,
            "zvec_query_threads": 1,
            "zvec_optimize_threads": 1,
        },
        "workload": {
            "topk": TOPK,
            "queries": QUERIES,
            "runs": RUNS,
            "warm_repeats": REPEATS,
            "vocabulary": VOCABULARY,
            "document_tokens": "12-24",
            "query_tokens": 2,
            "operator": "OR",
            "tokenizer": "lowercase ASCII: Python split vs zvec standard+lowercase",
            "bm25_k1": 1.2,
            "bm25_b": 0.75,
            "return_scores": False,
            "backend_apis": {
                "python_bm25": "BM25 and sorted Top-10 int64 row IDs",
                "zvec": "query_internal_ids(return_scores=False); internal int64 IDs",
                "zvec_query": "query(output_fields=[], include_vector=False); Doc external IDs and scores",
            },
            "resolve_calls": 0,
            "full_schema_vector_dimension": DIM,
            "insert_batch_size": 256,
            "timed": "query tokenization, BM25 matching/scoring, Top-K selection/sort and native API output; SDK construction included",
            "excluded": "imports, open, index construction, ID resolution, fusion, field fetch",
            "scope": "synthetic high-match-rate workload; not relevance evaluation or general FTS throughput",
        },
        "results": [],
    }
    with tempfile.TemporaryDirectory(prefix="zvec-fts-scale-") as directory:
        for count in SIZES:
            root = Path(directory) / str(count)
            root.mkdir()
            print(f"Preparing and validating {count} documents", file=sys.stderr, flush=True)
            parity = child("--prepare", str(root), str(count))
            samples = {name: [] for name in ("python_bm25", "zvec", "zvec_query")}
            orders = list(itertools.permutations(samples))
            assert len(orders) == RUNS
            for run, order in enumerate(orders):
                for backend in order:
                    samples[backend].append(child("--worker", str(root), backend, str(run))["times_us"])
                print(f"{count} documents: round {run + 1}/{RUNS} complete", file=sys.stderr, flush=True)
            result = {"nodes": count, "validation": parity}
            for backend, runs in samples.items():
                flat = [v for run in runs for v in run]
                result[backend] = {
                    "p50_us": float(np.median(flat)),
                    "p95_us": float(np.percentile(flat, 95)),
                    "samples": len(flat),
                    "per_run_p50_us": [float(np.median(run)) for run in runs],
                }
            result["zvec_over_python_p50"] = result["zvec"]["p50_us"] / result["python_bm25"]["p50_us"]
            result["query_over_internal_ids_p50"] = result["zvec_query"]["p50_us"] / result["zvec"]["p50_us"]
            report["results"].append(result)
    encoded = json.dumps(report, indent=2) + "\n"
    if len(sys.argv) == 2:
        Path(sys.argv[1]).write_text(encoded)
    print(encoded)


if __name__ == "__main__":
    if len(sys.argv) >= 2 and sys.argv[1].startswith("--"):
        zvec.init(query_threads=1, optimize_threads=1)
        if sys.argv[1] == "--prepare":
            prepare(Path(sys.argv[2]), int(sys.argv[3]))
            print(json.dumps(validate(Path(sys.argv[2]))))
        elif sys.argv[1] == "--worker":
            print(json.dumps(worker(Path(sys.argv[2]), sys.argv[3], int(sys.argv[4]))))
        else:
            raise SystemExit("Usage: python fts_scale.py [result.json]")
    elif len(sys.argv) <= 2:
        main()
    else:
        raise SystemExit("Usage: python fts_scale.py [result.json]")
result-dense-scale-apis-zvec-0.8.0.json
{
  "environment": {
    "python": "3.12.13",
    "platform": "macOS-26.6.2-arm64-arm-64bit",
    "cpu": "Apple M4 Pro",
    "numpy": "2.5.4",
    "numpy_blas": {
      "name": "accelerate",
      "found": true,
      "version": "unknown",
      "detection method": "system",
      "include directory": "unknown",
      "lib directory": "unknown",
      "openblas configuration": "unknown",
      "pc file directory": "unknown"
    },
    "zvec": "0.8.0",
    "worker_thread_env": {
      "OPENBLAS_NUM_THREADS": "1",
      "OMP_NUM_THREADS": "1",
      "MKL_NUM_THREADS": "1",
      "BLIS_NUM_THREADS": "1",
      "VECLIB_MAXIMUM_THREADS": "1"
    },
    "zvec_query_threads": 1,
    "zvec_optimize_threads": 1
  },
  "workload": {
    "dimension": 2560,
    "topk": 10,
    "queries": 20,
    "runs": 6,
    "warm_repeats": 20,
    "seed": 20261022,
    "query_source": "independent random FP32 vectors",
    "return_scores": false,
    "backend_apis": {
      "numpy": "exact cosine and sorted Top-10 int64 row IDs",
      "zvec": "query_internal_ids(return_scores=False); internal int64 IDs",
      "zvec_query": "query(output_fields=[], include_vector=False); Doc external IDs and scores"
    },
    "resolve_calls": 0,
    "imports_open_and_corpus_normalization_included": false,
    "query_normalization_selection_sort_and_api_overhead_included": true,
    "new_stores_no_deletions_sequential_fixture_ids": true,
    "insert_batch_size": 256,
    "notes": "Same exact dense cosine Top-10; API outputs differ as documented; no FTS/filter/fusion/field fetch; API not C++ kernel timing"
  },
  "results": [
    {
      "nodes": 100,
      "raw_vectors_mib": 0.9765625,
      "parity": {
        "exact_order_agreement": 1.0,
        "min_topk_boundary_margin": 1.790747046470642e-05
      },
      "numpy": {
        "p50_us": 8.125,
        "p95_us": 9.333,
        "samples": 2400,
        "per_run_p50_us": [
          8.375,
          8.0,
          8.042,
          8.042,
          8.167,
          8.375
        ]
      },
      "zvec": {
        "p50_us": 30.375,
        "p95_us": 36.583,
        "samples": 2400,
        "per_run_p50_us": [
          29.0835,
          30.2705,
          30.209,
          30.334,
          30.75,
          30.917
        ]
      },
      "zvec_query": {
        "p50_us": 54.4375,
        "p95_us": 74.042,
        "samples": 2400,
        "per_run_p50_us": [
          53.042,
          52.0,
          53.521,
          58.396,
          54.5835,
          55.208
        ]
      },
      "zvec_over_numpy_p50": 3.7384615384615385,
      "query_over_internal_ids_p50": 1.7921810699588476
    },
    {
      "nodes": 1000,
      "raw_vectors_mib": 9.765625,
      "parity": {
        "exact_order_agreement": 1.0,
        "min_topk_boundary_margin": 1.2915581464767456e-05
      },
      "numpy": {
        "p50_us": 39.8955,
        "p95_us": 51.41809999999999,
        "samples": 2400,
        "per_run_p50_us": [
          40.646,
          39.958,
          41.7705,
          39.667,
          39.0415,
          38.2085
        ]
      },
      "zvec": {
        "p50_us": 251.8125,
        "p95_us": 283.50205,
        "samples": 2400,
        "per_run_p50_us": [
          255.1455,
          246.66649999999998,
          249.167,
          254.16649999999998,
          250.79149999999998,
          254.1255
        ]
      },
      "zvec_query": {
        "p50_us": 273.9165,
        "p95_us": 313.79729999999995,
        "samples": 2400,
        "per_run_p50_us": [
          280.3755,
          274.04200000000003,
          275.52049999999997,
          267.6455,
          267.4375,
          278.896
        ]
      },
      "zvec_over_numpy_p50": 6.311802082941686,
      "query_over_internal_ids_p50": 1.0877795979151152
    },
    {
      "nodes": 10000,
      "raw_vectors_mib": 97.65625,
      "parity": {
        "exact_order_agreement": 1.0,
        "min_topk_boundary_margin": 2.1204352378845215e-05
      },
      "numpy": {
        "p50_us": 1071.167,
        "p95_us": 1266.2122,
        "samples": 2400,
        "per_run_p50_us": [
          1039.5835000000002,
          1112.4375,
          1048.625,
          1076.292,
          1066.8125,
          1077.7085
        ]
      },
      "zvec": {
        "p50_us": 2572.6255,
        "p95_us": 2764.9877999999994,
        "samples": 2400,
        "per_run_p50_us": [
          2527.625,
          2547.8955,
          2594.4584999999997,
          2571.458,
          2613.9165000000003,
          2561.4995
        ]
      },
      "zvec_query": {
        "p50_us": 2651.875,
        "p95_us": 2884.5125,
        "samples": 2400,
        "per_run_p50_us": [
          2547.5,
          2766.187,
          2648.708,
          2659.417,
          2670.1665000000003,
          2604.1045
        ]
      },
      "zvec_over_numpy_p50": 2.401703469206949,
      "query_over_internal_ids_p50": 1.0308049111695425
    }
  ]
}
result-fts-scale-apis-zvec-0.8.0.json
{
  "environment": {
    "platform": "macOS-26.6.2-arm64-arm-64bit",
    "python": "3.12.13",
    "cpu": "Apple M4 Pro",
    "numpy": "2.5.4",
    "zvec": "0.8.0",
    "worker_thread_env": {
      "OPENBLAS_NUM_THREADS": "1",
      "OMP_NUM_THREADS": "1",
      "MKL_NUM_THREADS": "1",
      "BLIS_NUM_THREADS": "1",
      "VECLIB_MAXIMUM_THREADS": "1"
    },
    "zvec_query_threads": 1,
    "zvec_optimize_threads": 1
  },
  "workload": {
    "topk": 10,
    "queries": 20,
    "runs": 6,
    "warm_repeats": 20,
    "vocabulary": 32,
    "document_tokens": "12-24",
    "query_tokens": 2,
    "operator": "OR",
    "tokenizer": "lowercase ASCII: Python split vs zvec standard+lowercase",
    "bm25_k1": 1.2,
    "bm25_b": 0.75,
    "return_scores": false,
    "backend_apis": {
      "python_bm25": "BM25 and sorted Top-10 int64 row IDs",
      "zvec": "query_internal_ids(return_scores=False); internal int64 IDs",
      "zvec_query": "query(output_fields=[], include_vector=False); Doc external IDs and scores"
    },
    "resolve_calls": 0,
    "full_schema_vector_dimension": 2560,
    "insert_batch_size": 256,
    "timed": "query tokenization, BM25 matching/scoring, Top-K selection/sort and native API output; SDK construction included",
    "excluded": "imports, open, index construction, ID resolution, fusion, field fetch",
    "scope": "synthetic high-match-rate workload; not relevance evaluation or general FTS throughput"
  },
  "results": [
    {
      "nodes": 100,
      "validation": {
        "all_matching_scores_and_topk_score_sequences_validated": true,
        "exact_id_order_agreement": 0.55,
        "mean_topk_id_set_overlap": 0.985,
        "mean_matching_documents": 67.8,
        "mean_document_tokens": 18.09,
        "text_utf8_bytes": 12024,
        "note": "Exact-ID differences allowed only when Top-K scores agree within stated FP32 tolerance"
      },
      "python_bm25": {
        "p50_us": 16.25,
        "p95_us": 19.542,
        "samples": 2400,
        "per_run_p50_us": [
          16.8335,
          16.6045,
          15.875,
          16.4165,
          16.083,
          16.0
        ]
      },
      "zvec": {
        "p50_us": 101.813,
        "p95_us": 127.37704999999998,
        "samples": 2400,
        "per_run_p50_us": [
          106.584,
          100.167,
          100.896,
          100.208,
          100.8745,
          103.3335
        ]
      },
      "zvec_query": {
        "p50_us": 102.166,
        "p95_us": 119.83305,
        "samples": 2400,
        "per_run_p50_us": [
          102.25,
          103.167,
          101.604,
          100.375,
          102.7915,
          102.1665
        ]
      },
      "zvec_over_python_p50": 6.265415384615385,
      "query_over_internal_ids_p50": 1.0034671407384126
    },
    {
      "nodes": 1000,
      "validation": {
        "all_matching_scores_and_topk_score_sequences_validated": true,
        "exact_id_order_agreement": 0.5,
        "mean_topk_id_set_overlap": 0.9899999999999999,
        "mean_matching_documents": 672.2,
        "mean_document_tokens": 18.013,
        "text_utf8_bytes": 119455,
        "note": "Exact-ID differences allowed only when Top-K scores agree within stated FP32 tolerance"
      },
      "python_bm25": {
        "p50_us": 133.563,
        "p95_us": 457.0333499999998,
        "samples": 2400,
        "per_run_p50_us": [
          130.125,
          137.2495,
          132.416,
          134.14600000000002,
          130.33350000000002,
          201.47899999999998
        ]
      },
      "zvec": {
        "p50_us": 430.667,
        "p95_us": 1021.1395999999993,
        "samples": 2400,
        "per_run_p50_us": [
          418.583,
          440.5625,
          431.91650000000004,
          420.5415,
          651.5830000000001,
          427.0005
        ]
      },
      "zvec_query": {
        "p50_us": 430.4375,
        "p95_us": 487.31699999999984,
        "samples": 2400,
        "per_run_p50_us": [
          423.58299999999997,
          438.0,
          424.125,
          440.25,
          436.375,
          422.35400000000004
        ]
      },
      "zvec_over_python_p50": 3.224448387652269,
      "query_over_internal_ids_p50": 0.9994671056756149
    },
    {
      "nodes": 10000,
      "validation": {
        "all_matching_scores_and_topk_score_sequences_validated": true,
        "exact_id_order_agreement": 0.2,
        "mean_topk_id_set_overlap": 0.975,
        "mean_matching_documents": 6776.1,
        "mean_document_tokens": 18.0113,
        "text_utf8_bytes": 1194559,
        "note": "Exact-ID differences allowed only when Top-K scores agree within stated FP32 tolerance"
      },
      "python_bm25": {
        "p50_us": 2470.9790000000003,
        "p95_us": 3041.876799999999,
        "samples": 2400,
        "per_run_p50_us": [
          2470.2295,
          2612.5625,
          2712.3125,
          2215.5,
          2685.9375,
          2239.958
        ]
      },
      "zvec": {
        "p50_us": 4378.9375,
        "p95_us": 4663.3556,
        "samples": 2400,
        "per_run_p50_us": [
          4381.833,
          4351.9375,
          4373.4995,
          4416.125,
          4413.5625,
          4340.542
        ]
      },
      "zvec_query": {
        "p50_us": 4381.417,
        "p95_us": 4679.5503,
        "samples": 2400,
        "per_run_p50_us": [
          4367.6669999999995,
          4428.0205000000005,
          4358.812,
          4329.916499999999,
          4384.9585,
          4397.875
        ]
      },
      "zvec_over_python_p50": 1.7721467887829072,
      "query_over_internal_ids_p50": 1.0005662332472205
    }
  ]
}
Lenguaje dominante
C++
Estrellas
16.3k
Forks
1k
Merge medio
2 d 10 h
PR fusionados (30 d)
32

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de alibaba/zvec

Todos los issues de alibaba/zvec

Issues similares

Más issues de C++

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.