Skip to content

Studio: store float32 RAG vectors from their buffer and pack the query once - #15859

Merged
danielhanchen merged 3 commits into
mainfrom
perf/rag-f32
Oct 29, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
perf/rag-f32

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

What changes

core/rag/store.py::_f32 packed every vector with struct.pack(f"{n}f", *(float(x) for x in vector)). The sentence-transformers embedder returns float32 numpy rows, so each stored chunk and each query converted every element to a Python float and back.

  • A 1-D, native byte order, float32 numpy.ndarray with no NaN is now written from its own buffer (tobytes()). A float32 value survives the float round trip exactly, including -0.0, infinities and subnormals, so the bytes are the same. NaN rows, other dtypes, big-endian arrays, lists and anything else keep the struct path, so NaN payload handling is unchanged.
  • numpy is only looked up in sys.modules; nothing new is imported.
  • _search_dense packs the query once per search instead of once per scope and widening pass. With no live scope it packs nothing, as before.

Results

Deterministic counts, 3 scopes x 3000 chunks of 768-d float32 rows, then 50 dense searches over the 3 scopes:

base head
struct.pack calls during ingest 9000 0
struct.pack calls during 50 searches 150 0
sha256 of every stored embedding blob 046ec7d5b6633a6d 046ec7d5b6633a6d
sha256 of the search results 6b24e2f20fac7aca 6b24e2f20fac7aca

Wall time, alternating base and head, 3 runs each: ingest base 1084.5 / 1070.3 / 1079.8 ms, head 726.5 / 719.3 / 716.4 ms (about 33% less store write time for 9000 vectors). Search time is dominated by the vec0 KNN and is unchanged (base 525-535 ms, head 526-539 ms per 50 searches).

Single 1024-d float32 row, 5 repeats of 500 calls: base 53.0 us (51.2-60.8), base again 51.6 us (51.5-51.8), head 1.13 us (1.12-1.20).

Parity of base vs head _f32 over 28 inputs (random and subnormal rows of 0 to 4096 dims, -0.0, infinities, float32 max and smallest subnormal, quiet NaN, signalling NaN, NaN with a payload, non-contiguous views, big-endian, float64, float16, lists, tuples, a 2-D array): 0 mismatches in bytes or raised exception type on Python 3.9 (numpy 1.26.4 and 2.0.2), 3.10, 3.11, 3.12, 3.13 and 3.14.

Tests

  • New test_dense_packs_float32_rows_without_struct_and_the_query_once: stores float32 rows in three scopes, checks the stored bytes equal the struct packing, checks a float32 query and the same query as a list return identical results, and counts one struct.pack for the three-scope list query. Fails on main, passes here.
  • tests/test_rag_store.py: 27 passed plus the new test failing on main, 28 passed here.
  • The other tests/test_rag*.py files on both arms: 1049 passed, 47 skipped and the same 16 failing test IDs on main and here (optional packages missing on this host); tests/test_rag_ocr_fallback.py cannot be collected here (no pymupdf) on either arm.
  • py_compile on Python 3.9, 3.10, 3.11, 3.12 and 3.14.

Not covered

  • Only x86-64 Linux was run. Big-endian hosts take the same path since both struct native f and the numpy buffer use native order; ARM64, Windows and macOS were not run.
  • Torch tensors (any device or dtype), numpy subclasses (memmap, masked arrays) and 0-d / 2-D arrays keep the struct path, so their bytes and exceptions are unchanged.
  • The llama-server embedder returns Python lists, which keep the struct path.

danielhanchen added a commit that referenced this pull request Oct 28, 2026
…xtensions (#15862)

The `macos-15` cross-platform leg on #15859 ran
`studio/backend/tests/test_rag_store.py`, because that PR changes it,
and got `4 passed, 24 errors`:

```
E   AttributeError: 'GatedConnection' object has no attribute 'enable_load_extension'
E   storage.rag_db.RagExtensionUnavailable: RAG unavailable: sqlite-vec extension could not be loaded
```

#15859 is not at fault here. Every one of the 24 errors is in the
`rag_conn` fixture.

## Cause

The Python on the macOS runner has a `sqlite3` built without
loadable-extension support: `sqlite3.Connection` has no
`enable_load_extension` at all. On such an interpreter RAG can never
load sqlite-vec. The product handles that: `get_connection` raises
`RagExtensionUnavailable` and Studio reports RAG as unavailable.

The RAG tests that open a connection themselves already skip on exactly
this condition (`test_rag_wal_keeper.py`,
`test_rag_delete_document_scan.py`, `test_account_storage.py`,
`test_rag_unavailable_quiet.py`):

```python
not rag_db.RAG_AVAILABLE or not hasattr(sqlite3.Connection, "enable_load_extension")
```

The shared `rag_conn` fixture in `studio/backend/tests/conftest.py` did
not. So any of the 17 files built on it errors on that leg as soon as a
PR touches it.

## Fix

`rag_conn` skips on the same condition before opening the connection.
Nothing else changes. On an interpreter that can load extensions, a
sqlite-vec that fails to load still raises out of the fixture, so a real
breakage is not turned into a skip.

## Verification

To reproduce on Linux, a pytest plugin stands in for that interpreter:
`sqlite3.Connection` without `enable_load_extension`, and connections
that raise `AttributeError` for it.

| run | main `06314b97dd` | this branch |
|---|---|---|
| `test_rag_store.py`, normal | 27 passed | 27 passed |
| `test_rag_store.py`, no-extension interpreter | 4 passed, 23 errors
(the CI failure) | 4 passed, 23 skipped |
| `test_rag_store.py`, extension loading works but `sqlite_vec.load`
raises | 4 passed, 23 errors | 4 passed, 23 errors (still fails, as it
should) |
| the 17 files that use `rag_conn`, normal, `-n 8` | | 634 passed, 18
skipped |

## Not covered here

`rag_conn` is the shared fixture, but many RAG tests reach
`rag_db.get_connection()` through the ingest and upload paths instead.
Under the same simulated interpreter, about 25 other files still fail,
among them `test_rag_ingestion.py`, `test_rag_upload_formats.py`,
`test_rag_linked_folders.py` and `test_rag_embedding_identity.py`. The
simulation overstates this a little: module-level `skipif`s are
evaluated before the plugin patches `sqlite3`.

Those files would fail on the macOS leg only when a PR changes them. The
cleaner end state is a macOS leg whose Python can load sqlite
extensions, rather than skipping RAG coverage there. That is a separate
change to the harness.
@danielhanchen danielhanchen self-assigned this Oct 29, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-29T10:57:41.758433Z
We couldn’t complete this review. Comment @codex review to try again.
dc7ba79 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: 223959cc66

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen marked this pull request as ready for review October 29, 2026 10:57
@danielhanchen
danielhanchen merged commit bdfffd7 into main Oct 29, 2026
7 of 45 checks passed
@danielhanchen
danielhanchen deleted the perf/rag-f32 branch October 29, 2026 10:57
danielhanchen added a commit that referenced this pull request Oct 29, 2026
…Grouper CUDA test on a real card (#15948)

## Summary

Two more checks are red on main itself, so every PR based on it today
inherits them (seen on staging for #15859 and #15936, neither of which
touches these files):

1.
`tests/security/test_lint_risky_loaders.py::test_the_tree_matches_the_baseline`
(workflow-trigger lint):
   ```
   1 risky loader call site(s) not in the baseline:
     unsloth/import_fixes.py:1040  [dynamic-import] import_module
   ```
#15850 added a fourth `importlib.import_module(module_name)` in
`unsloth/import_fixes.py` (the torchao import-time probe). The baseline
keys a call on its source text, so the existing entry for that text
(count 3) now sees 4 and reports the overflow at the first site. The new
call iterates the fixed `_TORCHAO_IMPORT_TIME_MODULES` tuple, so it is
the same trusted shape as the other three. The product is fine; the
baseline needed the count and the reason updated.

2.
`tests/python/test_accelerator_skip_guards.py::test_no_skip_guard_reads_a_spoofable_accelerator_probe`
(Repo tests, CPU):
   ```
   test_prefix_grouper_layout.py:199: torch.cuda.is_available()
   ```
#15835 added `test_cuda_layout_reads_the_device_once_and_copies_once`
gated on `torch.cuda.is_available()`, which
`tests/_zoo_aggressive_cuda_spoof.py` patches to `True` process-wide, so
on a CPU runner sharing a session with the compat suites the test
un-skips and calls `.cuda()`. Here the guard is right and the new test
was wrong: it now gates on `has_real_cuda()` like the other CUDA-only
tests.

## What changed

- `scripts/risky_loaders_baseline.json`: the `59e72c01edb14c86` entry
goes from count 3 to 4 (regenerated with `scripts/lint_risky_loaders.py
--update`, only that line moved), and its reason names
`_TORCHAO_IMPORT_TIME_MODULES` beside the other fixed tables.
- `tests/test_prefix_grouper_layout.py`: `skipif(not has_real_cuda(),
...)` instead of `skipif(not torch.cuda.is_available(), ...)`.

## Verification

- Base (main at `a4aee21490`): both tests fail as above.
- Head: `test_lint_risky_loaders.py`, `test_accelerator_skip_guards.py`
and `test_prefix_grouper_layout.py` give 75 passed, 1 skipped on a
CPU-only run.
- On a real GPU (torch 2.13 + CUDA 13.0) all 6 PrefixGrouper tests run,
including the CUDA one, so the new gate does not skip it on real
hardware.
- Each guard still fails without its fix: putting
`torch.cuda.is_available()` back makes the skip-guard test fail, and
putting the baseline count back to 3 makes the loader lint fail.
danielhanchen added a commit that referenced this pull request Oct 29, 2026
…s in flight (#15953)

## Summary

`Chat UI Tests (extra)` fails now and then in
`tests/studio/playwright_ui_font_scale.py`, on PRs that do not touch the
UI (#15917, #15859):

```
[font-scale] FAIL in step 'default restores exactly' after 0.3s:
default drifted for navFont: 13.5938 -> 18.125
```

18.125 is the nav font at UI size 20 (13.5938 x 20 / 15), so a size the
test had left two steps earlier came back after it set the default. The
test is right; this is a real product race in `usePersonalizationSync`:

1. On load, the hook GETs `/api/settings/personalization` and, when the
answer arrives, `replaceAll`s the appearance store with the server copy.
2. Saves are debounced by 800 ms, so a size changed shortly before a
navigation is in localStorage but not on the server. In the run above,
20 was saved, then 12 was set and the page reloaded inside the debounce.
3. After the reload the user (here, the test) sets the size again. If
the GET resolves after that, the server's stale 20 replaces the value
they just picked.

A user who changes a setting in the first moments after opening Studio
can see it snap back the same way.

## What changed

- `use-personalization-sync.ts` notes the appearance customization when
the load starts. If the store holds a different object when the server
answers, the user edited during the request, so local wins: the store is
not overwritten, and because the baseline records the server's values,
the normal debounced push uploads the edit.
- Without an edit in flight, nothing changes: a saved server
customization still replaces the local one.

## Verification

- Two tests in
`studio/frontend/tests/personalization-locale-hydration.test.ts`, using
its existing hook harness with the GET held open:
- an edit made while the request is in flight survives and is the value
that gets saved (fails on main: the size becomes the server's 20)
  - with no edit in flight, the server customization still wins
- The whole file: 14 pass. Against the unfixed hook, only the in-flight
test fails.
- `npm run typecheck` passes and eslint is clean on both files. Biome
reports the same 2 errors as on main, all in lines this change does not
touch.

The fix changes when a setting is kept, not anything drawn, so there is
nothing to screenshot. The Playwright font-scale check in `Chat UI Tests
(extra)` is the end-to-end cover.
danielhanchen added a commit that referenced this pull request Oct 29, 2026
…che builds in the background (#16013)

## Summary


`studio/backend/tests/test_rag_store.py::test_dense_packs_float32_rows_without_struct_and_the_query_once`
(from #15859) fails now and then since #15961, on PRs that do not touch
RAG (seen on the `(Python 3.13, g-r)` shard for #15900):

```
tests/test_rag_store.py:619: in test_dense_packs_float32_rows_without_struct_and_the_query_once
    assert ranked == as_list and ranked[0][1] > 0.99
E   At index 4 diff: ('d1:2', 0.7071067988872528) != ('d1:2', 0.7071067690849304)
```

The test runs `search_dense` twice (numpy query, then the same query as
a list) and expects identical results. Since #15961 the first search
finds no in-memory matrix for the scope and queues a build on the
`rag-vec-cache` background thread. If that build lands before the second
search, the second answer comes from the numpy matrix instead of vec0,
and the two backends' cosine scores differ in the last few ulps.
Reproduced on main by pausing 1 s between the two calls: it fails every
time. What the test is about (the query is packed once, numpy and list
inputs answer alike) does not depend on the cache.

## What changed

The test sets `RAG_VEC_CACHE=0` through `monkeypatch`, so both searches
go through vec0 regardless of timing.

## Verification

- Main with a 1 s pause between the two searches: fails with the diff
above. Same pause with this change: passes.
- `tests/test_rag_store.py` and `tests/test_rag_vec_cache.py`: 45
passed.
- With `_search_dense` packing the query per scope instead of once, the
test fails with `assert 4 == 1`, so the guard it was written for still
bites.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant