Building a Document Knowledge Workbench: From Search to RAG to Agent

When I first started building Anchr, the problem was very concrete: documents kept piling up, and I needed a way to pull information back out and actually put it to use.

Folder trees only answer “where did I save that file?”, and built-in full-text search assumes you still remember the exact wording used in the original text. When you only have a few files, that’s fine. Once the collection grows, the daily routine turns into: I remember some document talked about this, I have no idea what the file was named, and I can’t recall how it was phrased.

So Anchr started with document search. Once search worked, I layered answer generation on top of retrieval. Later still, when single-pass retrieval proved helpless against cross-document investigations, an Agent grew out of it naturally.

Even though the feature labels evolved from Search to RAG to Agent, the core work underneath has always been the same: reliably breaking raw documents down into evidence that a model can use and a human can trace straight back to the source.

1
2
3
4
5
6
7
8
9
10
11
12
13
Raw files
↓
Parsing & structure extraction
↓
Chunking & embedding
↓
Versioned index writes
↓
Query rewrite → Multi-way recall → Fusion → Rerank
↓
Traceable evidence
↓
Model answer → Citation validation → Save & render

This pipeline has one nasty property: whatever gets lost upstream can never be recovered downstream.

Lose table structure and page numbers during parsing, and no amount of search precision will reconstruct the scene. Slice a chunk right between a precondition and its conclusion, and the model only sees half a statement. Let old and new index versions mix in the same recall pool, and the smartest reranker on earth can’t tell which one is current. Build one of these systems and you quickly see that most off-target RAG answers have nothing to do with the prompt.

Technical documentation magnifies every one of these flaws. An engineering statement is usually pinned to a version number, a set of preconditions, and a runtime environment: “enabled by default” might only apply after a major release; “automatic retry” might only hold for idempotent endpoints. Drop a single qualifier upstream, and the model will take real source passages and assemble an answer that sounds airtight while steering you straight into a ditch.

First, turn documents into chunks with coordinates

Users drop in PDFs, Markdown, plain text, or images, but a retrieval system can’t just store a filename next to a giant blob of text. At minimum it has to know which sentences belong to the same paragraph, which page they sit on, what order they appear in, and how figures map to the surrounding text.

In Anchr, every ingested document goes first to a separately deployed Python sidecar service (anchr-docling) for parsing. The main service submits an async job, polls for status, and collects structured output at the end.

Funneling everything through one parsing entry point means the rest of the pipeline stops caring about the format differences between “page 3 of a PDF” and “the second H2 heading of a Markdown file.” Downstream only sees a uniform abstraction: text blocks, images, page numbers, heading hierarchy, and coordinates. Format-specific mess gets absorbed at the parsing layer, while the positional structure needed to jump back to the original text survives all the way to the end.

This matters a lot for PDFs. Markdown and plain text carry reading order natively; a PDF is a layout canvas where text, tables, and diagrams get their meaning from page coordinates. Picture a distributed-transaction spec with a table listing “execution phase, participant state, persistent log, recovery action.” If you scrape text in raw PDF byte-stream order, the recovery action for prepared can easily get concatenated onto committed. Using Docling to restore tables and layout structure while recording page numbers and bounding boxes is step one toward keeping the whole pipeline straight.

Parsed documents don’t go into the index whole; they get split into a sequence of Segment records. A Segment is Anchr’s atomic unit of search and citation: ordinary paragraphs, OCR text extracted from images, and even original embedded images are each their own Segment, carrying their parent document, page number, sequence index, and coordinates. Content meant for semantic retrieval then runs through an embedding model into vectors.

Rather than flattening every modality into plain text, I kept them distinct:

  • Regular paragraphs get text vectors computed directly from their body text.
  • OCR text participates in full-text search.
  • If the configured embedding model supports multimodality, original images also retain standalone visual vectors.

Take a sequence diagram of “coordinator crash recovery” inside a spec doc: it might get pulled in by full-text search via the prepare and commit labels in the diagram, or matched by a multimodal vector based on its interaction topology. Either way, both paths land back on the same coordinates in the same source document.

Chunking Segments isn’t something you solve by tuning a single chunk_size either. Slice too fine, and “once a participant enters prepared, it must hold locks and transaction logs” gets severed from “…until it receives the final decision or completes crash recovery,” turning the first half into an unconditional rule with no exit. Slice too coarse, and normal commit, coordinator recovery, and heuristic handling all get mashed into one block, blurring both BM25 and vector similarity.

My solution was to separate “search localization” from “context reading.” Retrieval uses smaller Segments to pinpoint hits accurately; when a user opens the source preview or a later stage needs surrounding context, the system pulls the adjacent Segments by sequence index. That’s far more flexible than making retrieval chunks bigger up front, and it lets search, citations, and source previews share one coordinate system.

Don’t touch the old content until the new index is done

Document parsing, embedding API calls, and Elasticsearch index writes are all slow operations with external dependencies and erratic latency. If the upload endpoint sat synchronously waiting for the whole pipeline to finish, one large PDF or an embedding rate limit would hang the request outright. So in Anchr, ingestion is an async background job. A successful upload means the file hit disk, not that it’s searchable yet.

Within a single upload batch, each document has its own independent state machine stepping through “parse -> embed -> index.” One broken file never stalls the rest of the batch, and progress bars in the UI map straight onto real pipeline stages.

Splitting the stages also eliminates opaque “ingestion failed” errors: you know immediately whether Docling couldn’t fetch the source file, parsed empty output, hit an embedding rate limit, or timed out writing to Elasticsearch. Transient blips from Docling or the embedding API get a bounded number of in-process retries; anything that still fails records the exact stage and reason so the user can rerun it from the UI.

Initial ingestion of a brand-new file is just waiting for the pipeline to finish. The moment you support “re-parse and re-index,” though, you hit a harder concurrency problem: at what exact second does the old version go offline, and at what exact second does the new version become searchable?

Suppose a deployment guide changes its runtime requirement from JDK 17 to JDK 21. During re-indexing, if you delete old data before writing the new data, the guide vanishes completely during the rebuild window. If you overwrite in place as you go, a single search can return both “requires JDK 17” and “requires JDK 21” side by side. For a retrieval system, temporarily holding two copies on disk is no big deal; exposing two versions in the same query is a disaster.

To handle cutover cleanly, Anchr assigns an incrementing index version (generation) to every build job:

  1. While a rebuild runs, the old version continues serving live search traffic while the new version runs parsing, embedding, and Elasticsearch writes in the background.
  2. Once Elasticsearch writes finish, the main service doesn’t just trust that “the last request didn’t throw an error”; it verifies that the written document ID, target generation, and expected Segment count all match.
  3. Right before flipping the switch, it re-checks the document’s current state. If the user deleted the document mid-build, or kicked off an even newer build, this slower job gets discarded, so it never brings deleted or stale data back to life.

There are no distributed transactions between MySQL and Elasticsearch here. MySQL is the single source of truth (storing the active generation), and Elasticsearch is just a rebuildable search replica. At query time, Elasticsearch may return candidate chunks from multiple historical generations, and the main service hard-filters them against MySQL’s active generation, dropping anything that doesn’t match.

Old versions and debris from aborted builds get swept up later by an async cleanup job. Even if cleanup temporarily falls behind or a few inactive ghost generations linger in Elasticsearch, users never see them. MySQL’s version number is the sole authority on what’s live.

One search has to catch both exact wording and overall meaning

Before touching the index, step one is locking down the search boundary. Is the user searching across the whole knowledge base, or asking inside one specific technical manual? That scope has to be pinned down first. Downstream query rewriting can only refine what terms to search with. It is never allowed to widen the document scope, or stray material from outside the current context will bleed into the answer.

Once the scope is locked, we deal with the question itself. People are terse in multi-turn conversations. Say they first ask “Why can PostgreSQL’s Serializable isolation level still abort transactions?”, and immediately follow up with “Does that happen to read-only transactions too?” Search with that second sentence raw and you lose the database, the isolation level, and serialization conflicts altogether. So Anchr rewrites the query using the last few turns of conversation to restore missing context. If the rewriter times out or returns garbage, the system falls back straight to the user’s raw question. Rewriting assists recall; it never overwrites what the user actually asked.

Next comes multi-way recall. Full-text search and vector retrieval each have clear blind spots:

  • A user asks “why does a database proactively roll back a transaction just to preserve serializability?” while the manual says “when read/write dependencies could produce non-serializable outcomes, one transaction must be aborted.” Almost zero lexical overlap, same concurrency mechanism. That’s where vector retrieval helps.
  • Flip it around: SQLSTATE 40001, class names, config keys, or an exact error string like could not serialize access due to read/write dependencies lose precision fast once blurred into a semantic vector. There you need full-text search to lock onto exact tokens.
  • If multimodal embeddings are enabled, the same query vector also reaches into architecture and sequence diagrams embedded in the docs.
1
2
3
Full-text recall    ──┐
Text vector recall ──┼→ RRF fusion → Active-version filter → Diversification → Rerank
Doc image recall ──┘

The raw scores from those three recall paths live on incompatible scales; take a weighted sum and whichever path has the widest numeric spread dominates the leaderboard. So Anchr uses RRF (Reciprocal Rank Fusion), ignoring raw scores and combining only each candidate’s rank in its respective list. A Segment that matches an exact error code and ranks high semantically shoots to the top; a result that only shows up in one path doesn’t get crushed just because its scoring scale is smaller.

After RRF fusion, the order is strict: active-version filter first, diversification second, Rerank last.

That ordering matters a lot. Stale chunks from an old version have no business taking up slots, let alone burning reranker compute. Push version filtering to the end, and stale results will fill the candidate window while current content never even makes it to reranking.

Where diversification happens matters too. Adjacent paragraphs in one long document tend to match together; left unchecked, eight of your Top 10 results can come from the same file. When searching the whole knowledge base, Anchr caps per-document and per-type counts before Rerank to keep slots open for more sources. When the user explicitly scopes a question to a single document, however, the goal flips to “find every relevant passage inside this file,” so diversification gets deferred until after Rerank to avoid pruning contiguous key context too early.

Rerank only refines an already narrowed candidate pool; it is not a second round of recall. Anything cut upstream by scope, version number, or slot caps cannot be conjured back by the reranker. Final ranking blends the normalized retrieval score with the rerank score; if the rerank service hiccups or times out, the system falls back straight to the RRF ranking so the main pipeline stays up.

Don’t dump every search hit straight into the model

A search results page and an answer-generation model want conflicting things from retrieval.

Humans scanning search results like to glance over a few document cards and click into the promising ones. A generation model’s context window is limited. Every irrelevant chunk you cram in not only burns tokens, it raises the odds that the model mixes things up, grafting preconditions from document A onto conclusions from document B.

So at the display layer, Anchr groups ranked Segments by parent document into cards, surfacing the top matching passages per card. The user sees “which documents are worth opening,” not a wall of fragments from the same file.

Evidence handed to the fixed RAG generation model gets tightened a second time on top of that: at most 5 chunks that have real Segment IDs, correspond to displayed cards, and contain substantive text. Better to hand over less than to dump raw Top-K straight into the prompt. Otherwise duplicate paragraphs, marginal fluff, and conflicting statements from different sections force the model to denoise retrieval output before it can even start writing.

There’s a hard line for image recall here too: if a visual vector surfaces a relevant architecture diagram, but the diagram has no accompanying text that can actually be cited, it stays on the search card for humans to inspect; it is never handed to the model as grounds for generating a claim. Helping with ranking does not automatically make something admissible evidence.

When assembling the generation prompt, we feed four clearly labeled pieces: the user’s original question, the rewritten search query, the current answer mode, and the numbered evidence list. Showing both the original question and the rewritten query is deliberate: it keeps retrieval-expansion keywords from hijacking the user’s actual intent.

Before calling the LLM, the backend runs a preflight check: if there isn’t a single citable Segment, or the usable text is too short, or retrieval scores are weak across the board, the system short-circuits directly to “insufficient evidence” without ever calling the generation model. That saves money, prevents the model from hallucinating on thin context, and cleanly separates “the knowledge base genuinely lacks evidence on this” from “the LLM API failed.”

After the model writes, backend code checks the output

The generation model is required to return structured output with a status code and citation IDs: ANSWERED when evidence is sufficient, NO_EVIDENCE when it isn’t.

Even when the model returns ANSWERED, the backend treats that response as an unverified draft. Anyone who has worked with LLMs knows they can spit out broken JSON, invent a citation ID out of thin air, or write three paragraphs of claims without a single footnote. Writing “do not fabricate” a hundred times in the prompt won’t cure that; you need hard code validation.

Anchr’s backend strictly parses the payload. It verifies the status code, checks that every inline citation number in the body falls within the input evidence range (if you feed it evidence 1 through 5 and it cites [7], it gets rejected immediately), and confirms that factual claims actually carry citations.

Once validation passes, the backend cleans the output: only Segments genuinely cited in the body are kept. Unused runner-up candidates are never padded into a “References” list to make the output look thorough. Surviving chunks get grouped by document, renumbered, and hydrated with filenames, page numbers, source coordinates, and match reasons. If the model didn’t write a decent citation blurb, the system substitutes the match snippet produced during retrieval instead of making another LLM call just to polish a caption. At this point, the coordinates preserved back in the parsing stage finally turn into clickable source highlights in the frontend.

There’s a subtle detail with frontend streaming too. The JSON streaming back from the model contains protocol fields like status codes and citation arrays that shouldn’t leak raw onto the user’s screen. As tokens arrive, the server strips out only the body text to stream to the UI. Once generation finishes and post-validation runs, if the finalized, verified text differs from what was streamed, the frontend swaps in the validated final text. Streaming kills the anxiety of staring at a blank screen; post-validation decides whether the answer actually counts.

Finally, the generated answer, inline citations, result cards, and the complete retrieval trace underneath (what the query was rewritten to, which recall paths fired, what got filtered out) are all persisted alongside the conversation. Refreshing the page never wipes the state; and whenever an answer looks off later, I can walk straight back down the saved trace and see whether query rewriting drifted, recall missed, or version filtering, Rerank, or post-validation killed the right chunk. Store only the final chat message, and a broken RAG pipeline turns into an opaque black box with no audit trail.

Of course, footnotes only prove which page the model looked at while writing a sentence, not that it understood what it read. PostgreSQL’s docs clearly state that “VACUUM cannot remove dead tuples still visible to any active transaction snapshot,” yet a model summarizing it can still slip into saying “long-running transactions completely block VACUUM from running,” inflating “some old row versions can’t be reclaimed” into “the whole cleanup process stalls.”

Citations can’t eliminate reading-comprehension drift, but they give the user a door to jump straight back to the source text and check for themselves. At that point, the single-pass fixed RAG loop is finally closed.

Fixed RAG’s open debts, and where the Agent begins

This fixed pipeline already washes raw documents into coordinate-backed evidence and runs the full path from multi-way recall through fusion, rerank, evidence gating, generation, and citation validation. There are still a few clear engineering debts left to pay down:

  • Ingestion jobs don’t yet support resuming from an intermediate stage if the main service restarts mid-flight.
  • Multi-way recall, RRF, and Rerank are all wired up, but I still lack a sizable human-labeled evaluation set for offline scoring.
  • The boundary between generation failure and insufficient evidence could be drawn more cleanly.

Those, however, are all refinements inside the single-pass pipeline. What actually pushed me to start building an Agent was a different class of question that no amount of tuning a single search pass can solve.

The fixed RAG pipeline described here gets exactly one shot at retrieval before it has to answer. Ask “Why doesn’t ordinary PostgreSQL VACUUM usually shrink the table file on disk?” and as long as that one shot pulls up the difference between internal space reuse and OS-level file truncation, the fixed pipeline handles it well.

Now ask: “Why does replication lag on our PostgreSQL read replica keep climbing?” The bottleneck could be primary WAL shipping, network transfer, standby write/flush, replay conflicting on locks with long-running queries, or specific config parameters. You have to take a first shot, see which stage the lag is stuck in, and only then decide whether the next search looks at network throughput or replay lock conflicts. The moment what you search next depends completely on what you just read, single-pass fixed RAG hits a wall.

Anchr’s Agent starts right at that wall. It didn’t invent a separate retrieval stack. It reuses the exact recall, version-filtering, and citation-validation foundation above, simply placing that single lookup inside a loop where the model can inspect intermediate results and decide where to dig next.

How to control call budgets, state transitions, and evidence boundaries once that loop is open is the topic of the next post, When One RAG Pass Isn’t Enough: Iterating on Agent RAG in Anchr.

Source code: https://github.com/ryanmeowy/anchr-app
Web frontend: https://github.com/ryanmeowy/anchr-web
Document parser service: https://github.com/ryanmeowy/anchr-docling