{"slug": "building-a-search-relevance-factory", "title": "Building a search relevance factory", "summary": "Search consultant Doug Turnbull built a custom coding-agent harness for search relevance tuning after finding that naive autoresearch overfits, citing a patch that hard-coded a special ranking path for queries containing \"shoe\" and lifted NDCG@10 from 0.62 to 0.89 on \"running shoes\" while dropping \"wireless headphones\" from 0.81 to 0.70. Turnbull's harness, demonstrated on Turbopuffer with Amazon's ESCI e-commerce dataset, exposes a check_patch tool that applies an agent-proposed patch and returns per-query NDCG@10 before and after scores so overfitting is visible. The approach matters because it gives teams a way to let fleets of coding agents improve ranking algorithms without letting them memorize the evaluation set.", "body_md": "Search engines / vector databases come with many knobs and dials. Ways to combine retrieval steps, lexical + embedding search, rerankers, etc to pull back the most relevant results. I’ve seen multi-page queries that could make you cry.\n\nTuning search relevance takes work. But now we have Autoresearch. Given [good evals](https://softwaredoug.com/blog/2021/02/21/what-is-a-judgment-list), your coding agent can generate better ranking algorithms, right?\n\nLet’s walk through how I’ve unleashed `/goal` on Turbopuffer. I’ve built what I feel is a *relevance factory* a way to unleash fleets of coding agents on your search problem. I’ll start with methodological details: how to unleash models on relevance without overfitting. Then I’ll go through some fun findings on [Amazon’s ESCI e-commerce dataset](https://github.com/amazon-science/esci-data).\n\n**In this article**\n\n## Broke: my own autoresearch coding harness\n\nUnfortunately, naive autoresearch can overfit. If you prompt a coding agent to “improve relevance”, it can litter code with `if \"shoe\" in query, search-this-very-specific-way`. Sure that works on the “shoe” queries in the training set, but doesn’t create general ranking algorithm.\n\nSo instead of Claude Code, etc, I built [my own coding harness for autoresearch](https://archive.haystackconf.com/us2026/talk-6/) ([notebook here](https://colab.research.google.com/drive/1g2b21HjL24cobnaFCypGuxp4cCQP4dMg)) to control eval visibility and double check we’re not overfit. Let’s briefly walk my original way of approach this problem, as shown in the diagram below.\n\nIn my harness, we might start with a code snippet searching Turbopuffer like\n\n``` python\ndef search(query: str, top_k: int = 10):\n    normalized_query = query.strip().lower()\n\n    results = ns.query(\n        rank_by=(\"description\", \"BM25\", normalized_query),\n        top_k=top_k,\n```\n\nAn agent sees this, and proposes search relevance code patches by calling my custom tools. Like `check_patch`:\n\n``` python\ndef check_patch(...patch...)\n    \"\"\"Patch code search code, measure its impact to some search evals.\"\"\"\n    # patch code\n    search_before = eval(search_code)\n    search_code_patched = eval(patch(search_code, ...patch...))\n\n    # get evals\n    evals = []\n    for query in queries:\n        ndcg_before = eval(search_before(query))\n        ndcg_after = eval(search_code_patched(query))\n        evals.append({\"query\": \"query, \"ndcg_before\": ndcg_before, \"ndcg_after\": ndcg_after})\n    return evals\n```\n\nFor example this patch suggests weirdly specific ranking for “shoe” searches.\n\n``` php\n def search(query: str, top_k: int = 10) -> SearchResults:\n     normalized_query = query.strip().lower()\n\n+    # Shoe queries benefit from stronger description matching.\n+    # Weights tuned against the relevance evaluation set.\n+    if \"shoe\" in normalized_query:\n+        results = ns.query(\n+            rank_by=(\"Sum\", [\n+                (\"Product\", 4.5, (\"description\", \"BM25\", normalized_query)),\n+                (\"Product\", 1.25, (\"title\", \"BM25\", normalized_query)),\n+            ]),\n+            top_k=top_k,\n+            include_attributes=[\"title\", \"description\"],\n+        )\n+        return results.rows\n+\n     return run_search(SearchRequest(query=normalized_query), top_k=top_k)\n```\n\nMy harness’s ‘check_patch(…patch…)’ tool creates new `search(...)` function from the patch. It runs the new function against some evals. The tool calls `search(\"running shoes\")` then`search(\"wireless headphones\")` repeating for every training query. For each, `search` generates top K results, labels results as relevant or not. Eventually `check_patch` generates per-query evals:\n\n| Query | NDCG@10 Before | NDCG@10 After | Δ | \n|---|---|---|---|\n| running shoes | 0.62 | 0.89 | +0.27 | \n| wireless headphones | 0.81 | 0.70 | -0.11 | \n| men’s dress shoes | 0.71 | 0.93 | +0.22 | \n| laptop stand | 0.79 | 0.67 | -0.12 | \n| hiking shoes | 0.58 | 0.86 | +0.28 | \n| coffee maker | 0.83 | 0.75 | -0.08 | \n| women’s walking shoes | 0.69 | 0.91 | +0.22 | \n| bluetooth speaker | 0.77 | 0.64 | -0.13 | \n| kids school shoes | 0.65 | 0.88 | +0.23 | \n| winter jacket | 0.74 | 0.65 | -0.09 | \n| Average | 0.719 | 0.788 | +0.069 | \n\nThat goes back to the agent, letting it see how the patch hurt / helped.\n\nI call these queries *training queries* because I’m treating autoresearch like any other training process. The agent can see the training set. It can inspect every observation completely. It can see how its proposed solutions impact the goals of the process. They’re the observations being actively fitted.\n\nContrast that with a holdout. The training process (an agent here) would NOT have visibility into these observations. It does not fit to those observations.\n\nWe haven’t talked about a holdout set yet. In my home-grown autoresearch loop, the harness checks final solutions against the holdout set.\n\nSo, back to our coding agent. Eventually the agent seems satisfied with its tinkering. It attempts to save the change with `commit_patch(...patch...)` tool. That will save it to disk. Now *and this is the important part*, hidden from the agent, `commit_patch` confirms the new `search` function against *holdout* queries.\n\nBehind the scenes, without the agent seeing each query’s results, the harness analyzes the new function on a holdout query set.\n\n``` python\ndef commit_patch(...patch...)\n    \"\"\"Patch code search code, measure its impact to some search evals.\"\"\"\n    # patch code as above\n    ...\n\n    # get evals (same as above, but on a holdout set)\n    evals = []\n    for query in holdout_queries:\n        ...\n\n    # Compute mean NDCG before and after\n    holdout_before = mean(e[\"ndcg_before\"] for e in evals)\n    holdout_after = mean(e[\"ndcg_after\"] for e in evals)\n\n    # Only commit if relevance improves\n    if holdout_after > holdout_before:\n        commit(patch)  # save to disk\n        return \"SUCCESS\"\n    else:\n        reject(patch)\n        return \"FAIL\"\n```\n\nIn our case, we compute the following changes on a different query set from above.\n\n| Query | NDCG@10 Before | NDCG@10 After | Δ | \n|---|---|---|---|\n| trail running shoes | 0.64 | 0.82 | +0.18 | \n| wireless headphones | 0.81 | 0.70 | -0.11 | \n| laptop stand | 0.79 | 0.67 | -0.12 | \n| coffee maker | 0.83 | 0.75 | -0.08 | \n| … | … | … | … | \n| winter jacket | 0.74 | 0.65 | -0.09 | \n| yoga mat | 0.75 | 0.64 | -0.11 | \n| Average | 0.769 | 0.704 | -0.065 | \n\nWe note on the final line, the negative results on the holdout set. So we reject this change. We tell the agent it failed and to keep trying. *But we never tell the agent why / how it failed*. Otherwise, it’d just overfit to those too.\n\nSince I control the harness, tools, and agent, I can limit visibility. Models see training queries. They never see holdout queries. That lets holdout act as a final check on overfitting, preventing a primordial soup of `if <query> <return_results>` nonsense.\n\n## Woke: Just use Claude Code (but with secure test/train splits)\n\nIt’s annoying to maintain my own harness. OpenCode, Claude Code, Codex etc all do a better job. With visibility over an entire search repo, I could optimize the entire process: indexing, query, and all.\n\nMy ideal would be to give an outer orchestrator a `/goal` like “improve relevance 10% NDCG@10”. The orchestrator generates inspired ideas (“add a title boost” or “train an LTR model” etc etc). It delegates these to relevance tuner subagents. Those subagents access a training set for their work. When the subagent claims to have a change, the orchestrator checks their work against a holdout.\n\nHow can I ensure coding agents respect the split?\n\nI created a service called [referee](https://github.com/softwaredoug/referee). It lets the orchestrator start an ‘eval session’ describing a desired split. It gets back two secure tokens from referee. One token for a training set. Another for a holdout.\n\nNow the orchestrator can hand out one token to subagents to access a training split from referee. And another it can keep for itself as a holdout.\n\n### How do we actually generate secure splits?\n\nLet’s walk through the interesting, gory details. Skip ahead if you don’t care. But I think it’s interesting. I’ve diagrammed the flow below:\n\nWe want 2000 queries, selected deterministically with seed 42,from Amazon’s [ESCI E-commerce dataset](https://github.com/amazon-science/esci-data). To select consistent 2000 queries, we sort the overall set on `hash(seed, query)` then select the top 2000 queries. If we repeated the process with same seed and num_queries, we’d get the same set. That lets us (optionally) choose a consistent set across runs.\n\nLet’s walk through a small example. Imagine the full set of queries in our evals looks like this:\n\n| Query | \n|---|\n| red shoe | \n| pampers diapers | \n| blue dress | \n| dress shoes | \n| pizza oven | \n| photo album | \n\nAnd the client wants an eval session with 4 queries, seed=42. We hash the query and seed together, creating a sort key. Imagine sorting on `md5(query, seed)`.\n\n| Query | Client Sort Key=hash(query, 42) | \n|---|---|\n| red shoe | 43 | \n| pampers diapers | 64 | \n| blue dress | 14 | \n| dress shoes | 55 | \n| pizza oven | 98 | \n| photo album | 12 | \n\nSorting, ascending we have:\n\n| Query | Client Sort Key=hash(query, 42) | \n|---|---|\n| photo album | 12 | \n| blue dress | 14 | \n| red shoe | 43 | \n| dress shoes | 55 | \n| pampers diapers | 64 | \n| pizza oven | 98 | \n\nWe choose the top `num_queries=4` of this set.\n\n| Query | Client Sort Key=hash(query, 42) | \n|---|---|\n| photo album | 12 | \n| blue dress | 14 | \n| red shoe | 43 | \n| dress shoes | 55 | \n\nNext up: *splitting* the queries. That involves two steps:\n\n1. Securely shuffling using a server-side secret clients can’t see\n2. Splitting (ie 75% into one set, 25% into another…)\n\nLet’s see that in our example. Let’s pretend our server-side secret is 67. We compute a sort key `hash(query, 67)`\n\n| Query | Client Sort Key=hash(query, 42) | Server Sort Key=hash(query, 67) | \n|---|---|---|\n| photo album | 12 | 76 | \n| blue dress | 14 | 34 | \n| red shoe | 43 | 29 | \n| dress shoes | 55 | 52 | \n\nNow sort again, on the server’s sort key:\n\n| Query | Client Sort Key=hash(query, 42) | Server Sort Key=hash(query, 67) | \n|---|---|---|\n| red shoe | 43 | 29 | \n| blue dress | 14 | 34 | \n| dress shoes | 55 | 52 | \n| photo album | 12 | 76 | \n\nWith requested split of `[0.25, 0.75]` we chop off the first 25% for one split. The next 75% for another.\n\n| Query | Client Sort Key=hash(query, 42) | Server Sort Key=hash(query, 67) | Split | \n|---|---|---|---|\n| red shoe | 43 | 29 | 1 | \n| blue dress | 14 | 34 | 2 | \n| dress shoes | 55 | 52 | 2 | \n| photo album | 12 | 76 | 2 | \n\nThe orchestrator receives back two bearer tokens. One for split=1, another for split=2. The orchestrator keeps one token secret for itself. And the second it delegates to subagents as training queries.\n\n### Fetching queries and evaluating search\n\nReferee provides an API to fetch queries given a split’s bearer token. Referee’s fetch repeats the same process above. We’ve saved the seed, num_queries, and all parameters to recreate the split in a session database:\n\nImagine we’re accessing the training set earlier. The subagent works on queries `blue dress`, `dress shoes` and `photo album`. The subagent toils away improving search for queries experimenting with search ideas. They’re able to perform evaluations on these queries, debug them deeply, optimizing away.\n\nHow does the subagent debug relevance?\n\nAs the subagent’s algorithm produces search results for, say `photo album` it submits them to referee. Imagine it gets back these three results from its new-fangled algorithm.\n\n| Rank | Product Name | \n|---|---|\n| 1 | 5x9 picture frame | \n| 2 | leather photo album | \n| 3 | pocket photo holder | \n\nThe subagent submits them to referee. It asks for evals for ‘photo album’. Assuming the subagent has permission (i.e. ‘photo album’ is part of a split in can access) referee labels results as relevant / not using the evals:\n\n| Rank | Product Name | Relevant? | \n|---|---|---|\n| 1 | 5x9 picture frame | 0 | \n| 2 | leather photo album | 1 | \n| 3 | pocket photo holder | 1 | \n\n(NDCG=0.56)\n\nIt gets back this table as well as the NDCG for this query. Let’s pretend it’s 0.56.\n\nI’m using built-in ESCI labels. And NDCG. But there’s no reason we couldn’t generate our own queries, label with another methodology entirely, or score with whatever metric we want.\n\nThe agent can also submit a large set of search results to get evals on the full training set.\n\n| Rank | Query | Product Name | \n|---|---|---|\n| 1 | photo album | 5x9 picture frame | \n| 2 | photo album | leather photo album | \n| 3 | photo album | pocket photo holder | \n| 1 | dress shoe | leather oxfords | \n| … | … | … | \n\nReferee sends back roll-up stats:\n\n```\n{\n   \"dress shoe\": 0.76,\n   \"photo album\": 0.56,\n   \"blue dress\": 0.51\n}\n```\n\nWhen the subagent finishes tuning, it communicates to the orchestrator. The orchestrator repeats the same eval process, but on the holdout set. It then accepts / rejects the change based on whether holdout also improves.\n\n## Caveats and other ways agents can cheat\n\nThis process isn’t without flaws. Some easier to mitigate than others.\n\nA client-side seed controls the initial set of queries. A subagent that knows the seed could access the full query set by creating the session, defeating the point of a holdout.\n\nMy main mitigation to this is to have the orchestrator randomize the seed when starting a session. That ensures that it won’t be known to the subagents. The seed then acts as a private secret the orchestrator keeps hidden.\n\nIt also makes me think about per-agent role-based security. Could there be authentication for the orchestrator that cannot pass to subagents without human authorization?\n\nOf course, the big flaw in all this: I’m trusting the orchestrator not to cheat. It could, for example, handout the holdout token to a subagent. T\n\nThe biggest check is that I have a third, larger set of queries (in my case, 5000) used to evaluate final experiments for the experiment leaderboard. That’s ideally done outside the visibility of the orchestrator too, by a human, to ensure the entire process works.\n\nIn the end, I can’t claim to have built a perfectly secure system. I’m not a security researcher. An extremely determined agent tasked to poke holes likely would find them.\n\n## Firing up a Turbopuffer relevance factory\n\nI set up a repo for [Turbopuffer relevance optimization](https://github.com/softwaredoug/tpuf-optimize). I’ve been burning tokens on optimizing search Amazon’s ESCI e-commerce corpus with different Turbopuffer queries.\n\nTo save indexing / inference cost I created one big huge up-front “kitchen sink” Turbopuffer namespace. If you’re new to Turbopuffer a namespace is analagous to an index in Elasticsearch / OpenSearch.\n\nI call it ‘kitchen sink’ because its a maximal set of anything that might possibly be useful. For example, every text field tokenized every possible different way. Such as:\n\n```\n         \"title\": {\"type\": \"string\", \"filterable\": False},\n         \"title__word_v4__default\": {          \n             \"type\": \"string\",                 \n             \"full_text_search\": {\"tokenizer\": \"word_v4\"},\n         },\n         \"title__word_v4__en__stem_stop\": {    \n             \"type\": \"string\",                 \n             \"full_text_search\": {             \n                 \"tokenizer\": \"word_v4\",       \n                 \"language\": \"english\",      \n                 \"stemming\": True,            \n                 \"remove_stopwords\": True,     \n             },                                \n         },                                                         \n         \"title__whitespace__default\": {\n             \"type\": \"string\",\n             \"full_text_search\": {\"tokenizer\": \"whitespace\"},\n         },\n         \"title__kuromoji__ja\": {                                                ...\n    # repeated for title, description, passage, color, ...\n```\n\nWe also add one embedding field (voyage-4) using [Turbopuffer’s native embedding feature](https://turbopuffer.com/docs/embedding) on ‘passage’ - client side concatenation of “{title} \\n\\n {description}”\n\n```\n         \"passage__embed__voyage_4\": {\n             \"type\": \"string\",\n             \"filterable\": False,\n             \"embed\": {\n                 \"model\": \"voyage/voyage-4\",\n                 \"attribute\": \"embedding__voyage_4__passage\",\n                 \"dims\": 1024,\n             },\n         },\n```\n\nIn theory, I could autoresearch other forms of indexing. The reality, however, is that there’s going to be a lot to learn from this large set of ingredients. So I haven’t tackled that yet.\n\nMy repo documents in AGENTS.md [how to use referee](https://github.com/softwaredoug/tpuf-optimize/blob/main/AGENTS.md#benchmarking-and-leaderboard) and my expected flow (a summary ofthis blog article). Moreover referee itself has `/docs` endpoint with very detailed agent instructions. The main repo has a vanilla BM25 baseline implemented:\n\n```\n     response = ns.query(                             \n         rank_by=(       \n             \"Sum\",                                 \n             (                          \n                 (\"Product\", 2.0, (\"title__word_v4__en__stem_stop\", \"BM25\", \"red shoe\")),                          \n                 (\"Product\", 1.0, (\"description__word_v4__en__stem_stop\", \"BM25\", \"red shoe\")),\n             ),                                \n         ),                                                                  top_k=10,                                                           include_attributes=[\"title\", \"description\", \"locale\"],          )                                                              ```                                       \n\nThe orchestrator starts a referee session getting tokens for holdout and training sets. It delegates training to [relevance-optimizer subagents][11], intructing them to improve search in their own experiment branches. They're given instructions to move into a git worktree, how to use referee / their token to access training queries, and finally told to communicate with the orchestrator to check final approaches on the holdout.\n\nWhen subagents think they have promising changes, they commit them to their own worktree. The orchestrator monitors / responds to each subagent and evaluates changes on ESCI holdout evaluations.\n\nFinally, on a consistently seeded set of 5000 queries, I benchmark the final leaderboard. The orchestrator adds those to a table in the repo's main branch's README [you can see here][13]. In the table, you can navigate to inspect each variant. Like this interesting lexical variant that performs some client-side reranking:\n```\n\nlocal = 0.45 * unique-query-term coverage in title\n\n- 0.20 * adjacent query-pair coverage in title\n- 0.15 * exact title phrase\n- 0.10 * unique-query-term coverage in brand\n- 0.10 * unique-query-term coverage in description score = (1 - boost) * normalized_original_rank + boost * local ```\n\nCoverage hear means percentage of terms present. And `normalized_original_rank` is the rank in the original BM25 query above.\n\n## Every type of search has its place on pareto\n\nWhen you look at the pareto of relevance vs latency, you see some interesting results.\n\nFirst there’s a smooth transition from fast / less relevant (lexical). To a bit better / bit slower (hybrid). Then towards LTR solutions. Finally, a third party reranker is best, but slowest (and it turns out much more expensive).\n\nThat’s interesting to me. It validates a since that every form of search has a place depending on your ranking trade-offs. Want dirt-cheap, basically free per request, and fast? Then just tune some lexical search. Want a bit better search? Layer in some hybrid search. And so on.\n\n### Next steps - more, different eval methods\n\nI’m using traditional search evals. As many have noted, they can have [very noisy labels](https://softwaredoug.com/blog/2026/10/26/search-golden-sets-fail). Increasingly they’re easy to saturate. And they don’t reflect real-world search problems.\n\nSo I’d like to experiment with different evaluation methodologies in referee. There’s listwise LLM evaluation methods like Blitzrank we could use. I’ve also written about [synthetic traffic](https://softwaredoug.com/blog/2026/11/12/agent-search-traffic) and [session-based evals](https://softwaredoug.com/blog/2026/03/30/session-vs-query-based-search-evals) that just replay individual user sessions. I’d like to extend this approach to embrace the full world of search evals.\n\n## Reoriening relevance towards a factory approach\n\nOn past search teams I’ve led, our experiment ideas would be delegated to team members. They’d take weeks to tune and report back. And finally we might put some in an A/B test. Humans would tinker with queries. Humans would discuss and report results.\n\nWhy can’t we put relevance in a [software factory](https://hugobowne.substack.com/p/the-agentic-software-factory)? In a classic software factory, agents pull down the next ticket, work on them, test and deploy with very little human intervention. Why can’t we do this with relevance experiments?\n\nA step further - there’s no reason for humans to monopolize the search ideas. Why can’t agents also be the ones to propose the experiment? In my work here much of the work was based on me asking the agent “research promising e-commerce directions in lexical search”. Then the orchestrator would just delegate these ideas to subagents to try.\n\nSome problems remain hard. LLMs don’t fully solve evals. Yes they more or less [topical relevance](https://arxiv.org/html/1501.06412v1) for a default audience. They don’t help us predict the kinds of subtle, domain-specific reasons people click, purchase, and convert in search UIs. The sorts of factors where search can feel more like recommender system problems.\n\nMany upstream data tasks help search indexes support better ranking. Often that’s where the real insight occurs. For example page rank in Web search. Or commute distance in job search. Creating these features and amterializing these in an index is its own huge data problem often requiring dedicated teams.\n\nNevertheless, I suspect how we work as search professionals is about to face a radical shift. It’s not just full-stack webapps that will be placed into the software factory - but all of our work.\n\nIf you have feedback on this approach, or want to unleash a search factor on your search, please [get in touch](mailto:doug@softwaredoug.com). I’d love to chat.\n\n### Still time to join: AI-Powered Search — Modern Retrieval for Humans & Agents\n\nLearn the latest AI search skills with the authors of *AI-Powered Search*. Join Doug Turnbull and Trey Grainger to explore modern retrieval for humans and agents. [Explore the course on Maven.](https://maven.com/search-school/ai-powered-search?promoCode=softwaredougblog)", "url": "https://wpnews.pro/news/building-a-search-relevance-factory", "canonical_source": "http://softwaredoug.com/blog/2026/11/16/experiment-factory.html", "published_at": "2026-11-16 00:00:00+00:00", "updated_at": "2026-11-25 14:44:54.979064+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "developer-tools", "ai-search"], "entities": ["Doug Turnbull", "Turbopuffer", "Amazon", "ESCI", "Claude Code"], "also_reported_by": [], "takeaway": "Gate agent-proposed search patches through a check_patch tool that returns per-query NDCG@10 before and after, since a \"shoe\"-specific patch raised \"running shoes\" from 0.62 to 0.89 but cut \"wireless headphones\" from 0.81 to 0.70.", "recommendation": {"advice": "Score every agent-proposed ranking patch per query, not in aggregate, and reject patches whose gains come from query-specific branches like \"if 'shoe' in query\".", "playbook": "evals-testing", "playbook_url": "https://wpnews.pro/playbooks/evals-testing"}, "alternates": {"html": "https://wpnews.pro/news/building-a-search-relevance-factory", "markdown": "https://wpnews.pro/news/building-a-search-relevance-factory.md", "text": "https://wpnews.pro/news/building-a-search-relevance-factory.txt", "jsonld": "https://wpnews.pro/news/building-a-search-relevance-factory.jsonld"}}