cd /news/ai-agents/chunk-freshness-for-retrieval-archit… · home › topics › ai-agents › article
[ARTICLE · art-175074] src=dev.to ↗ pub= topic=ai-agents verified=true sentiment=↑ positive

Chunk Freshness for Retrieval Architecture — Tuning Legal Contract Review in Postgres

A developer describes building a hybrid retrieval pipeline for a legal contract review workspace on Postgres, combining a full-text index for exact terms with a vector index for semantic matches while keeping retrieval separate from generation. The design uses immutable, versioned chunks with stable clause IDs, metadata filters for tenant, matter and document version, and a small relevance test set, with a simple linear blend of normalized lexical and vector scores logged component by component. The engineer reports that a stale termination date traced to an out-of-order asynchronous indexing job, not the embedding model, and was fixed with an idempotency key of document ID plus version and a monotonic activation check.

recommendation

Filter by tenant, matter and active document version in the query before ranking, and key chunk writes on document ID plus version with a monotonic activation check to stop stale clauses resurfacing.

more in playbook: Retrieval and RAG
by read6 min views1 publishedNov 23, 2026

Short answer: use a hybrid retrieval pipeline with versioned chunks, metadata filters, and a small relevance test set. In a legal contract review workspace, freshness beats a clever embedding model: an answer built from yesterday's clause is worse than a visibly incomplete answer.

The least complex design that holds up is a Postgres table for canonical text and metadata, a full-text index for exact terms, and a vector index for semantic matches. Keep retrieval separate from generation. That boundary makes relevance measurable and lets the review UI show the source clause, page, and document version.

Design choice Good default Trade-off
Chunk unit Heading plus 1–3 paragraphs, with clause ID Larger context, fewer independent hits
Freshness signal document_version andupdated_at filters More indexing work during edits
Candidate set Hybrid lexical + vector, then rerank Extra latency and tuning surface
Evidence Span offsets and page coordinates Slightly more storage

This is a boring table. Boring is useful here. A reviewer needs the latest indemnity clause, not a fluent paragraph assembled from two revisions.

Start with an explicit query contract. A search request carries the tenant, matter, allowed document IDs, query text, and an optional “as of” timestamp. The retrieval layer must enforce those fields before ranking. Prompt instructions are not an access-control system.

For each chunk, store a stable clause_id, a monotonically increasing document_version, the embedding model name, and the character range in the source file. On update, mark the old version inactive and insert new chunks. Do not mutate a chunk in place: immutable records make audit replay possible and prevent a cached result from pointing at changed text.

The ranking score can stay understandable. Normalize lexical and vector scores inside the candidate set, then apply a freshness penalty only after permission filtering. A simple linear blend is easier to debug than a dozen opaque features. Log every component score, the selected version, and the final evidence IDs.

The interface below keeps storage replaceable. It also makes a useful test seam: feed the same candidates to different rankers and compare which clause wins.

type SearchRequest = {
  tenantId: string;
  matterId: string;
  query: string;
  allowedDocumentIds: string[];
  asOf?: string;
};

type Candidate = {
  clauseId: string;
  documentId: string;
  documentVersion: number;
  text: string;
  lexical: number;
  semantic: number;
  updatedAt: string;
};

export function rankCandidates(rows: Candidate[]): Candidate[] {
  const maxLexical = Math.max(...rows.map((row) => row.lexical), 1);
  const maxSemantic = Math.max(...rows.map((row) => row.semantic), 1);

  return rows
    .map((row) => ({
      row,
      score: 0.45 * (row.lexical / maxLexical) +
        0.55 * (row.semantic / maxSemantic),
    }))
    .sort((a, b) => b.score - a.score)
    .map(({ row }) => row);
}

The production query should fetch only active versions visible to the matter. The ranker must not receive unauthorized rows and then be asked to “down-rank” them. That mistake can leak a clause through explanations, logs, or token counts.

I once treated a bad result as an embedding problem because the search returned an old termination date. The actual defect was an asynchronous indexing job that accepted edits out of order. Version 12 arrived, then version 11 overwrote its active flag. The fix was an idempotency key made from document ID and version, plus a monotonic activation check. The vector model never changed.

Another trap is splitting on a fixed character count. It severs “except as provided in Section 8.2” from Section 8.2, so a semantically close hit loses its legal qualifier. Parse headings, numbered clauses, tables, and page boundaries first. Keep a small overlap only when the parser cannot preserve those relationships.

The evaluation set should mirror the workspace, too. Include one tenant with thousands of nearly identical procurement templates, another with scanned PDFs that carry weak text extraction, and a matter where access changes halfway through review. Those cases exercise deduplication, parser confidence, and authorization together. Record the expected evidence span, not just a yes/no answer, so a fluent response cannot hide a citation that points to the wrong sentence. When a miss is found, label its cause before changing a weight: stale version, bad boundary, lexical gap, semantic gap, or policy filter. Otherwise the team ends up tuning the score to compensate for an ingestion defect.

Freshness needs a visible policy. For live drafting, search the newest active version. For a signed-review snapshot, pin the version at matter creation. Your mileage may vary when documents arrive from multiple systems; record the source timestamp and choose one clock for the policy.

Compare them against the same labeled questions, not against intuition. A useful set includes defined-term lookups, negation (“may not”), cross-reference questions, and questions whose answer changed between versions. Measure recall at 5, citation precision, stale-hit rate, p95 latency, and the percentage of answers with an evidence span.

Hybrid search is the baseline when clause numbers and names matter. A reranker can improve ordering when the candidate set is already fresh and authorized, but it adds latency and another model to monitor. A snapshot index gives reproducible review results; it is the wrong fit for a workspace where editors expect an upload to be searchable immediately.

The catch is operational cost. Re-embedding every chunk on every keystroke wastes compute and creates transient versions. Debounce edits, batch indexing, and expose an “index pending” state in the UI. Conversely, do not hide staleness behind a spinner for signed matters: show the pinned version and let the reviewer choose a newer draft explicitly.

Ship ten representative queries before tuning weights. Save the expected clause IDs and the acceptable alternatives. On each change, run the set in CI, inspect misses by failure type, and keep a few adversarial examples permanently. A three-word query can expose a tokenizer issue; a long question can expose a chunk boundary. Use traces that connect query, filter, candidate IDs, scores, selected version, and cited offsets. Redact contract text in routine logs and retain hashes for correlation. If the workspace cannot explain why a clause appeared, the retrieval architecture is not ready for review work. This test loop also catches regressions that a single offline benchmark hides: a weight change may raise average recall while dropping every negation query, and a parser update may preserve text while shifting page offsets used by citations. Keep those checks beside deployment, because relevance and freshness are release properties, not just model settings.

Keep it measurable.

This approach is not suitable when you need multilingual legal corpora with specialized morphology and no team to operate model evaluation; a managed search service may be a better fit. Stick with a simpler lexical index when contracts are short, terminology is fixed, and auditability matters more than paraphrase recall.

── more in #ai-agents 4 stories · sorted by recency
── more on @postgres 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/chunk-freshness-for-…] indexed:0 read:6min 2026-11-23 · —