Seventeen working examples covering every package in the stack.
Four are sector-specific tracer scenarios — medicine, government, law and
finance — with the data structures those systems actually use. Every example
was executed locally before publication, and every one starts with the
pip install line it needs.
Every script installs its own dependencies on the first run. Paste it into
a Colab cell and execute; the pip install happens inside the
cell, before the imports.
This matters because a !pip install line written inside a
comment never executes — which is the most common reason a Colab example
fails with ModuleNotFoundError. All seventeen scripts here were
verified in a clean virtual environment with none of the packages installed.
| # | Example | Package | Domain |
|---|---|---|---|
| 00 | Hello world | madhava | — |
| 01 | E-discovery with provable completeness | madhava | legal |
| 02 | Clinical record for a denied claim | madhava | health |
| 03 | Credit decision reconstruction | madhava | finance |
| 04 | Reproduce the benchmark | madhava | — |
| 05 | Quality gate on a broken corpus | madhava + normalize | — |
| 06 | Auditable agent memory | madhava | agents |
| 07 | SQL to search (minimal) | madhava | — |
| 08 | RAG agent (minimal) | madhava | — |
| 09 | Tracer-MED — hospital audit trail | madhava + tracer | health |
| 10 | Tracer-GOV — procurement audit | madhava + tracer | government |
| 11 | Tracer-JUS — contract due diligence | madhava + tracer | legal |
| 12 | Tracer-GAP — financial reconciliation | madhava + tracer | finance |
| 13 | X-Factor — manifold projection | xfactor | — |
| 14 | Nano — tokenizer and weight blending | nano | — |
| 15 | Normalize — providers, L2, drift | normalize | — |
| 16 | Build speed across corpus sizes | madhava | — |
The smallest working example. A corpus of five vectors, one query, and the proof that the four non-returned vectors could not belong.
import numpy as np
import winnex_madhava as mad
corpus = np.array([...], dtype=np.float32) # 5 vectors, dim 16
engine = mad.build_engine(corpus, dim=16, k=2,
k1_fraction=1.0, postfilter=True,
audit_exhaustive=True)
result = mad.retrieve(engine, corpus[0], k=2)
Output from the actual run:
indices: [0, 4]
bound violations: 0
latency: 0.016 ms
proof: every excluded document carries a Cauchy-Schwarz proof...
Download .py
A litigation support database holds custodial documents. Counsel must produce the responsive set and certify nothing was missed — under penalty of sanctions for spoliation. Every platform returns documents; none can show that the withheld set was correctly excluded.
The example loads seven custodial documents into SQLite (the shape Relativity, Everlaw and Concordance all use), withholds the privileged one before indexing, and produces a certificate listing both the production set and the withheld set with proof.
CREATE TABLE documents (
doc_id TEXT PRIMARY KEY,
custodian TEXT,
doc_date TEXT,
file_type TEXT,
subject TEXT,
body TEXT,
privilege INTEGER DEFAULT 0
)
Output from the actual run:
documents in database : 7
privileged withheld : 1
indexed for search : 6
responsive documents:
1. [0.742] DOC-0001 Re: Contrato de Fornecimento - Cláusula 7
2. [0.577] DOC-0004 Conciliação de multas Q1 2024
3. [0.477] DOC-0002 Re: Contrato de Fornecimento - prazo
─── production certificate ───
production set : ['DOC-0001', 'DOC-0004', 'DOC-0002']
withheld as irrelevant : ['DOC-0003', 'DOC-0005', 'DOC-0007']
bound violations : 0 (must be 0)
What the certificate asserts. For each withheld document, the engine computed a Cauchy–Schwarz upper bound below the score of the third responsive document — so it could not belong in the responsive set, and an opposing expert can re-run the arithmetic. An approximate index gives the same three documents and no way to make that statement.
Download .pyAn insurer denies a claim. The revenue cycle team has 30 days to produce the clinical documentation proving the procedure was justified, or the revenue is written off. The documentation exists in the EHR — the question is whether the search finds it, and whether anyone can tell the difference between "no record found" and "no record exists".
The example loads clinical notes in the table layout Cerner, Epic, MV and Tasy all use, indexes the notes for one patient under dispute, and produces the statement the hospital sends to the payer.
CREATE TABLE notas_clinicas (
id INTEGER PRIMARY KEY,
paciente_id TEXT,
data_atendimento TEXT,
tipo TEXT, -- evolução, descrição cirúrgica, sumário
profissional TEXT,
texto TEXT
)
Output from the actual run:
patient under dispute : PAC-4471
clinical notes on file: 4
insurer's question: justificativa clínica para videolaparoscopia
documentation produced:
1. [0.558] descrição cirúrgica de 2026-03-02
2. [0.467] evolução de 2026-03-02
3. [0.466] sumário de alta de 2026-03-05
notes supporting the procedure : 3
notes excluded with proof : 1
bound violations : 0
Why the revenue cycle team cares. A denied claim that is not appealed is revenue the hospital already earned and will never collect. The work of appealing is searching the record for justification — and every search returning "nothing found" is a claim written off. What matters is knowing whether nothing was found or nothing was proven absent.
Download .pyA credit application is denied. The applicant invokes their right to review under LGPD art. 20 / GDPR art. 22, and the regulator asks the bank to reconstruct the grounds. The bank must show which policies applied — and that no policy was missed.
This is the case where approximate search becomes a liability: if the retrieval misses the exception clause that would have approved the application, the bank denied credit on incomplete grounds and cannot demonstrate otherwise.
CREATE TABLE politicas_credito (
codigo TEXT PRIMARY KEY,
vigencia TEXT,
categoria TEXT, -- limite, garantia, exceção, restrição
titulo TEXT,
texto TEXT,
aprovado_por TEXT
)
Output from the actual run — a denial at 33% income commitment, 7-year relationship, no active restriction:
application : PROP-2026-03-4471
commitment : 33.0%
relationship : 7 years
decision : NEGADO
policy that governs this decision:
1. [0.818] POL-0187 (garantia)
2. [0.813] PRE-0088 (precedente)
3. [0.801] POL-0203 (exceção)
4. [0.713] POL-0142 (limite)
policies excluded with proof : ['POL-0115', 'POL-0264']
bound violations : 0
What the reconstruction reveals. POL-0203 allows up to 35% commitment for clients with more than five years of relationship and no active restriction. The applicant has seven years, no restriction, and 33% commitment. The retrieval surfaces it — and proves no other policy in the repository is responsive. Whether the denial was correct is a credit judgement; whether it was made on a complete reading of policy is now on the record.
Download .pyThe sector examples use a deterministic hash embedding so they run with no
API key. Swap embed() for a domain encoder before measuring
anything — the retrieval logic does not change, but the quality of the result
will.
Do not trust our numbers. This generates its own corpus, computes brute-force ground truth, and compares. If it cannot reproduce exact scan on synthetic data, it will not on BIGANN either.
Output from the actual run (20,000 vectors × 384 dims, 50 queries):
top-1 agreement 1.0000
setR@10 overlap 1.0000
bound violations 0
------------------------------------------------
build time 177.0 ms
search time 107.5 ms (2.15 ms per query)
brute force time 36.4 ms
Download .py
A bound proof is only as strong as the vectors it was computed on. The
engine will index a corpus full of NaN and return
bound_violations = 0, because the arithmetic is correct — the
inputs were garbage. This example feeds it a broken corpus and shows the
thirteen-flag audit catching it.
Output from the actual run — NaN, zeros and inf mixed in:
has_fail : True
fail flags : 1
warn flags : 3
FAIL [dataset.nan]
150 of 32000 values are NaN/inf (0.4687%) — the engine would
silently produce garbage scores with 0 bound violations.
WARN [dataset.recall_not_guaranteed]
seed recall@K = 0.375 vs the motor's own search_exact...
the returned top-K is the best WITHIN the pool, NOT proven
the global top-K.
The second warning is the important one: a query can report zero bound violations and still not be globally guaranteed, because the count only covers the candidate pool. The gate tells you which case you are in. See the flag system in the main documentation for all thirteen codes.
Download .pyAn agent that remembers past interactions is only as trustworthy as its ability to recall them. If memory silently drops a past instruction, the agent behaves unpredictably and nobody can explain why.
class AuditableMemory:
def remember(self, texto, **meta): ... # append + rebuild
def recall(self, consulta, k=3): ... # memories + proof
def explain(self, consulta, alvo): ... # why not recalled?
Output from the actual run:
consulta: quando posso contatar o cliente
[0.909] (contexto) O cliente atua no setor hospitalar, em Portugal.
[0.899] (preferencia) O cliente pediu para não ser contatado às sextas.
total de memórias : 5
recuperadas : 2
excluídas COM PROVA : 3
violações de bound : 0
Every remember() rebuilds the index — viable because a
1M-vector index builds in 1.69 s against 33.6 s for HNSW on the same corpus.
Agent memory can grow in real time without the guarantee degrading.
The shortest path from a database to a provably complete answer, with no domain framing. Use this when you want the mechanics without the scenario.
Download .pyHow to wire the engine into an existing RAG pipeline, including the system prompt that lets the model state the retrieval was proven complete.
Download .pyStated plainly, because documentation is only useful when the limits are visible:
Four examples, one per vertical. Each loads a realistic corpus for its domain, instruments the engine so every search produces a signed record, and reads back the exclusion evidence.
A medical audit service holds 400 reports. The query "apendicite" returns two, and the engine reports how many were excluded with proof.
laudos no corpus : 400
laudos encontrados : 2
excluídos com prova : 17
garantia : exact_global
bound violations : 0
registro de exclusão (amostra):
doc 13: bound=0.3854 excluído=True
Download .py
A court of accounts scans 600 procurement processes for emergency dispensations lacking justification.
processos analisados : 600
processos retornados : 5
garantia : exact_global
bound violations : 0
Download .py
500 contract clauses searched for early-termination risk. The point is proving no risky clause was omitted.
cláusulas no repositório : 500
cláusulas de risco : 4
garantia : exact_global
bound violations : 0
Download .py
800 accounting entries in a period with a discrepancy. Internal audit asks which entries lack supporting documentation.
lançamentos no período : 800
lançamentos suspeitos : 5
garantia : exact_global
bound violations : 0
Download .py
Derives the subspace where a model's token embeddings live, without training and without running the model. The example is honest about a subtlety: synthetic noise has no low-dimensional structure, so the projection does not reduce anything. Real weights do.
embedding table : 4,000 tokens x 256 dims
manifold basis : (256, 256) (rank efetivo 236)
residual : 0.9521
Download .py
Two components that run with no model download: the deterministic spectral tokenizer (perfect round-trip across five languages, including accents and Japanese) and the weight balancer that fuses two models without gradients.
[OK] 'Winnex AI' -> 'Winnex AI'
[OK] 'Ñoño café — acentuação preservada' -> idêntico
[OK] '日本語のテスト' -> idêntico
modelo A (70%) + modelo B (30%)
fundido: [3.70, 7.40, 11.10, 14.80]
Download .py
Applies the L2 unit-norm contract by hand, shows validation rejecting NaN and wrong dimensions, and demonstrates drift detection with an embedding fingerprint.
norma antes : min=87.74 max=105.67
norma depois : min=1.0000 max=1.0000
[aceito] vetores válidos
[recusado] com NaN — ValueError
[recusado] dimensão errada — ValueError
[embedding.provider_drift] espaço deslocado:
batch-centroid cosine 0.061 (< 0.8)
Download .py
Measures build time from 1,000 to 200,000 vectors and compares query latency against brute force. Ends with the honest crossover: Madhava is competitive in query time up to roughly 50,000 vectors, and always far ahead on build.
corpus build per 1k docs
1,000 9.1 ms 9.07 ms
50,000 93.2 ms 1.86 ms
200,000 269.3 ms 1.35 ms
vs HNSW on 99,800 vectors: 1.45 s vs 33.60 s (23.1x)
Download .py