"""The access control filter bench. One question per cell: when this call path is given a per owner metadata filter, is the filter applied, accepted and discarded, or rejected? The four controls from PRE-REGISTRATION.md are enforced here in code, not in prose. In particular control 4, filtered recall by document id, is what stops a filter that matched nothing from scoring as honoured. A filter on a misspelled field returns empty, and empty contains no foreign document, so without control 4 it passes the leak test and both other controls at once. That is how paper 14 failed and it is designed against here. Ground truth is the owner table from corpus.py, joined by id. An owner value read back out of a search result is never trusted, because a store that drops or rewrites metadata would score a foreign document as not foreign. """ import json import os import sys import traceback HERE = os.path.dirname(os.path.abspath(__file__)) os.environ.setdefault('ANONYMIZED_TELEMETRY', 'False') os.environ.setdefault('HF_HOME', os.path.join(HERE, 'hf')) K = 10 RANK_DEPTH = 240 # full corpus, so the unfiltered ranking is complete OWNER_FIELD = 'owner' SUBJECT = 'acme' # the owner whose documents a query is entitled to see CORPUS = json.load(open(os.path.join(HERE, 'corpus.json'))) TRUTH = json.load(open(os.path.join(HERE, 'ground-truth.json'))) assert len({d['text'] for d in CORPUS}) == len(CORPUS), \ 'corpus texts are not unique, so resolving an id by text is unsound' QUERIES = [ 'who pays when a vessel is delayed beyond the agreed time', 'what document proves goods were received for carriage', 'how is the rate for moving cargo by sea decided', 'rules a ship must follow to carry heavy cargo safely', 'which authority inspects a foreign ship in port', ] def embed(): """Embed once, cache to disk. Model files live under the bench tree.""" cache = os.path.join(HERE, 'embeddings.json') if os.path.exists(cache): d = json.load(open(cache)) return d['docs'], d['queries'] from sentence_transformers import SentenceTransformer m = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2') docs = m.encode([d['text'] for d in CORPUS], normalize_embeddings=True).tolist() qs = m.encode(QUERIES, normalize_embeddings=True).tolist() json.dump({'docs': docs, 'queries': qs}, open(cache, 'w')) return docs, qs def classify(unfiltered_ids, filtered, err, form_is_degenerate, ranking_exact=True): """Turn one observation into a pre-registered category. unfiltered_ids: the complete ranking from the SAME object and call path with only the filter removed. filtered: ids returned with the filter, or None. """ if err is not None: return 'rejected', {'error': err} # control 1, positive: the unfiltered ranking must contain foreign documents foreign_unfiltered = [i for i in unfiltered_ids[:K] if TRUTH[i] != SUBJECT] if not foreign_unfiltered: return 'void_no_positive_control', { 'why': 'unfiltered top k held no foreign document, nothing to leak'} # control 4, filtered recall: what an honouring filter must return expected = [i for i in unfiltered_ids if TRUTH[i] == SUBJECT][:K] leaked = [i for i in filtered if TRUTH[i] != SUBJECT] if leaked: return 'silently_ignored', { 'leaked': leaked[:5], 'n_leaked': len(leaked), 'note': 'filter accepted without error and foreign documents returned'} if not filtered: return 'unknown', {'why': 'filtered result empty, filter may have matched nothing'} if len(filtered) < min(K, len(expected)): return 'unknown', { 'why': 'filtered result is short, so the filter may have matched ' 'only part of what it should', 'n_returned': len(filtered), 'n_expected': min(K, len(expected))} if ranking_exact: missing = [i for i in expected if i not in filtered] if missing: return 'unknown', { 'why': 'filtered result does not hold the documents this ' 'ranking owed it', 'missing': missing[:5], 'n_missing': len(missing), 'n_returned': len(filtered)} if form_is_degenerate: return 'HARNESS_BROKEN', { 'why': 'a deliberately wrong filter scored as honoured; run is void'} return 'honoured', {'n_returned': len(filtered)} def record(results, cell, path, form, note, unfiltered, filtered, err, degenerate=False): # MMR deliberately returns a diverse subset, not the similarity top k, so # the exact-set form of control 4 does not apply to it. ranking_exact = 'marginal_relevance' not in path cat, detail = classify(unfiltered, filtered or [], err, degenerate, ranking_exact) results.append({'cell': cell, 'path': path, 'form': form, 'form_note': note, 'category': cat, 'detail': detail, 'control4': 'exact set' if ranking_exact else 'full length, no foreign (re-ranking path)', 'degenerate': degenerate}) print(' %-34s %-26s %s' % (path, form, cat)) return cat # ---------------------------------------------------------------- Chroma family def chroma_collection(doc_vecs): """A real Chroma collection. chromadb 1.5.9 runs a Rust core, not a shim.""" import chromadb c = chromadb.EphemeralClient() for name in ('bench_coll',): try: c.delete_collection(name) except Exception: pass coll = c.create_collection('bench_coll') coll.add(ids=[d['id'] for d in CORPUS], embeddings=doc_vecs, metadatas=[{OWNER_FIELD: d['owner'], 'article': d['article']} for d in CORPUS], documents=[d['text'] for d in CORPUS]) return coll def run_chroma_native(results, doc_vecs, q_vecs): coll = chroma_collection(doc_vecs) qv = [q_vecs[0]] def ids_of(res): return res['ids'][0] unfiltered = ids_of(coll.query(query_embeddings=qv, n_results=RANK_DEPTH)) forms = [ ('where= correct', {'where': {OWNER_FIELD: SUBJECT}}, 'the name chroma declares', False), ('where= misspelled field', {'where': {'owner_id': SUBJECT}}, 'degenerate, must be unknown', True), ('where= wrong type', {'where': {OWNER_FIELD: 1}}, 'degenerate, must be unknown', True), ('filter= langchain name', {'filter': {OWNER_FIELD: SUBJECT}}, 'cross dialect', False), ('filters= llamaindex name', {'filters': {OWNER_FIELD: SUBJECT}}, 'cross dialect', False), ] for form, kw, note, degen in forms: err, got = None, [] try: got = ids_of(coll.query(query_embeddings=qv, n_results=K, **kw)) except Exception as e: err = '%s: %s' % (e.__class__.__name__, str(e)[:160]) record(results, 'chroma 1.5.9 direct', 'Collection.query', form, note, unfiltered, got, err, degen) def run_langchain_chroma(results, doc_vecs, q_vecs, pkg): """langchain over a real Chroma backend. The wrapper is not the backend.""" if pkg == 'langchain_chroma': from langchain_chroma import Chroma else: from langchain_community.vectorstores import Chroma from langchain_core.embeddings import Embeddings vec_by_text = {d['text']: doc_vecs[i] for i, d in enumerate(CORPUS)} class Fixed(Embeddings): """Serve the cached vectors, so no cell depends on a live model.""" def embed_documents(self, texts): return [vec_by_text[t] for t in texts] def embed_query(self, text): return q_vecs[QUERIES.index(text)] import chromadb client = chromadb.EphemeralClient() store = Chroma(collection_name='lc_%s' % pkg, embedding_function=Fixed(), client=client) store.add_texts([d['text'] for d in CORPUS], metadatas=[{OWNER_FIELD: d['owner']} for d in CORPUS], ids=[d['id'] for d in CORPUS]) q = QUERIES[0] id_by_text = {d['text']: d['id'] for d in CORPUS} def ids_of(docs): """Resolve ids without ever reading owner out of a result. langchain-community's Chroma leaves Document.id unset, so fall back to the text, which is unique in this corpus by construction. """ out = [] for d in docs: i = getattr(d, 'id', None) or id_by_text.get(d.page_content) if i is not None: out.append(i) return out unfiltered = ids_of(store.similarity_search(q, k=RANK_DEPTH)) cell = '%s %s over chroma' % (pkg, 'wrapper') forms = [ ('filter= correct', 'similarity_search', {'filter': {OWNER_FIELD: SUBJECT}}, 'the name langchain declares', False), ('where= chroma name', 'similarity_search', {'where': {OWNER_FIELD: SUBJECT}}, 'cross dialect into **kwargs', False), ('filters= llamaindex name', 'similarity_search', {'filters': {OWNER_FIELD: SUBJECT}}, 'cross dialect into **kwargs', False), ('filter= misspelled field', 'similarity_search', {'filter': {'owner_id': SUBJECT}}, 'degenerate, must be unknown', True), ('filter= correct, default fetch_k', 'max_marginal_relevance_search', {'filter': {OWNER_FIELD: SUBJECT}}, 'MMR default pool, what a caller gets', False), ('filter= correct, fetch_k=corpus', 'max_marginal_relevance_search', {'filter': {OWNER_FIELD: SUBJECT}, 'fetch_k': RANK_DEPTH}, 'MMR with the pool removed as a confound', False), ('where= chroma name', 'max_marginal_relevance_search', {'where': {OWNER_FIELD: SUBJECT}}, 'cross dialect, MMR path', False), ] for form, path, kw, note, degen in forms: err, got = None, [] try: got = ids_of(getattr(store, path)(q, k=K, **kw)) except Exception as e: err = '%s: %s' % (e.__class__.__name__, str(e)[:160]) record(results, cell, path, form, note, unfiltered, got, err, degen) # the retriever path, where everything goes through an untyped dict for form, sk, note in [ ('search_kwargs filter=', {'k': K, 'filter': {OWNER_FIELD: SUBJECT}}, 'documented'), ('search_kwargs where=', {'k': K, 'where': {OWNER_FIELD: SUBJECT}}, 'cross dialect'), ]: err, got = None, [] try: got = ids_of(store.as_retriever(search_kwargs=sk).invoke(q)) except Exception as e: err = '%s: %s' % (e.__class__.__name__, str(e)[:160]) record(results, cell, 'as_retriever.invoke', form, note, unfiltered, got, err) # --------------------------------------------------------------------- LanceDB def run_lancedb(results, doc_vecs, q_vecs): """LanceDB is a real embedded backend with its own filter engine. prefilter matters: with prefilter False the filter is applied AFTER the ANN search, so a legitimate document can be dropped because it fell outside the unfiltered top k. That is a short result, which is `unknown`, not `honoured`, and it is exactly the reason control 4 exists. """ import shutil import lancedb path = os.path.join(HERE, 'lance') shutil.rmtree(path, ignore_errors=True) db = lancedb.connect(path) tbl = db.create_table('bench', data=[ {'id': d['id'], 'vector': doc_vecs[i], OWNER_FIELD: d['owner'], 'text': d['text']} for i, d in enumerate(CORPUS)]) qv = q_vecs[0] def ids_of(rows): return [r['id'] for r in rows] unfiltered = ids_of(tbl.search(qv).limit(RANK_DEPTH).to_list()) cell = 'lancedb 0.41.0 direct' eq = OWNER_FIELD + " = '" + SUBJECT + "'" forms = [ ('where sql, prefilter=True', eq, True, 'documented', False), ('where sql, prefilter=False', eq, False, 'post filter after ANN', False), ('where sql, misspelled field', "owner_id = '" + SUBJECT + "'", True, 'degenerate, must be unknown or rejected', True), ('where sql, wrong type', OWNER_FIELD + ' = 1', True, 'degenerate, must be unknown or rejected', True), ] for form, where, pre, note, degen in forms: err, got = None, [] try: got = ids_of(tbl.search(qv).where(where, prefilter=pre) .limit(K).to_list()) except Exception as e: err = '%s: %s' % (e.__class__.__name__, str(e)[:160]) record(results, cell, 'Table.search().where()', form, note, unfiltered, got, err, degen) # ------------------------------------------------------------------ llama-index def run_llamaindex_chroma(results, doc_vecs, q_vecs): import chromadb from llama_index.core.schema import TextNode from llama_index.core.vector_stores.types import ( VectorStoreQuery, MetadataFilters, MetadataFilter, FilterOperator) from llama_index.vector_stores.chroma import ChromaVectorStore client = chromadb.EphemeralClient() coll = client.create_collection('li_chroma') store = ChromaVectorStore(chroma_collection=coll) store.add([TextNode(id_=d['id'], text=d['text'], metadata={OWNER_FIELD: d['owner']}, embedding=doc_vecs[i]) for i, d in enumerate(CORPUS)]) qv = q_vecs[0] cell = 'llama-index 0.14.26 over chroma' def ids_of(res): return list(res.ids or []) unfiltered = ids_of(store.query(VectorStoreQuery( query_embedding=qv, similarity_top_k=RANK_DEPTH))) def mf(field, value): return MetadataFilters(filters=[ MetadataFilter(key=field, value=value, operator=FilterOperator.EQ)]) forms = [ ('filters= correct', mf(OWNER_FIELD, SUBJECT), 'the form llama-index declares', False), ('filters= misspelled field', mf('owner_id', SUBJECT), 'degenerate, must be unknown', True), ('filters= wrong type', mf(OWNER_FIELD, 1), 'degenerate, must be unknown', True), ] for form, filters, note, degen in forms: err, got = None, [] try: got = ids_of(store.query(VectorStoreQuery( query_embedding=qv, similarity_top_k=K, filters=filters))) except Exception as e: err = '%s: %s' % (e.__class__.__name__, str(e)[:160]) record(results, cell, 'VectorStoreQuery(filters=)', form, note, unfiltered, got, err, degen) err, got = None, [] try: q = VectorStoreQuery(query_embedding=qv, similarity_top_k=K) got = ids_of(store.query(q, where={OWNER_FIELD: SUBJECT})) except Exception as e: err = '%s: %s' % (e.__class__.__name__, str(e)[:160]) record(results, cell, 'store.query(where=)', 'where= chroma name', 'cross dialect as a kwarg on query', unfiltered, got, err) # --------------------------------------------- a wrapper with no real backend def run_langchain_inmemory(results, doc_vecs, q_vecs): """Not evidence about any backend. Its filter is a callable I write myself. Included only to show what the untyped kwarg does on a path where the filter is a python predicate, because the swallow is the same swallow. """ from langchain_core.documents import Document from langchain_core.embeddings import Embeddings from langchain_core.vectorstores import InMemoryVectorStore vec_by_text = {d['text']: doc_vecs[i] for i, d in enumerate(CORPUS)} class Fixed(Embeddings): def embed_documents(self, texts): return [vec_by_text[t] for t in texts] def embed_query(self, text): return q_vecs[QUERIES.index(text)] store = InMemoryVectorStore(Fixed()) store.add_documents([Document(id=d['id'], page_content=d['text'], metadata={OWNER_FIELD: d['owner']}) for d in CORPUS]) q = QUERIES[0] def ids_of(ds): return [d.id for d in ds] unfiltered = ids_of(store.similarity_search(q, k=RANK_DEPTH)) cell = 'langchain InMemoryVectorStore (no backend, not evidence)' err, got = None, [] try: got = ids_of(store.similarity_search( q, k=K, where={OWNER_FIELD: SUBJECT})) except Exception as e: err = '%s: %s' % (e.__class__.__name__, str(e)[:160]) record(results, cell, 'similarity_search', 'where= dict', 'a dict passed where a callable is declared', unfiltered, got, err) def main(): doc_vecs, q_vecs = embed() results = [] stages = [ ('chroma native', lambda: run_chroma_native(results, doc_vecs, q_vecs)), ('langchain-chroma over chroma', lambda: run_langchain_chroma(results, doc_vecs, q_vecs, 'langchain_chroma')), ('langchain-community over chroma', lambda: run_langchain_chroma(results, doc_vecs, q_vecs, 'langchain_community')), ('lancedb', lambda: run_lancedb(results, doc_vecs, q_vecs)), ('llama-index over chroma', lambda: run_llamaindex_chroma(results, doc_vecs, q_vecs)), ('langchain in-memory, not evidence', lambda: run_langchain_inmemory(results, doc_vecs, q_vecs)), ] for name, fn in stages: print('') print('== %s ==' % name) try: fn() except Exception: print(' STAGE FAILED') traceback.print_exc(limit=3) results.append({'cell': name, 'path': '', 'form': '', 'form_note': '', 'category': 'stage_failed', 'detail': {'trace': traceback.format_exc()[-700:]}, 'degenerate': False}) json.dump(results, open(os.path.join(HERE, 'results.json'), 'w'), indent=1) import collections print('') print('=== categories ===') for cat, n in collections.Counter( r['category'] for r in results).most_common(): print(' %-28s %d' % (cat, n)) broken = [r for r in results if r['category'] == 'HARNESS_BROKEN'] degen = [r for r in results if r.get('degenerate')] print('') print('degenerate forms run: %d, all must be unknown or rejected' % len(degen)) for r in degen: if r['category'] not in ('unknown', 'rejected'): print(' SELF CHECK FAILED: %s %s -> %s' % (r['cell'], r['form'], r['category'])) if broken: print('') print('RUN VOID: a deliberately wrong filter scored as honoured') sys.exit(2) if __name__ == '__main__': main()