Skip to content

feat(api): search document text across formatting with a trigram index - #768

Merged
pikann merged 8 commits into
Paca-AI:masterfrom
msammu07:feat/doc-text-search
Nov 15, 2026
Merged

pikann merged 8 commits into
Paca-AI:masterfrom
msammu07:feat/doc-text-search

Conversation

@msammu07

@msammu07 msammu07 commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Part of #747 (docs pull / push / content check for coding agents). Document search now matches a phrase across formatting and uses an index. It is independent of the other open parts of #747.

Before

Search matched the query inside one text run of the stored JSON. A phrase that crossed bold, italic or a link (foo **bar**) was not found by foo bar, and every search read all documents of the project.

After

  • Plain text column. documents.content_text holds the document's text, one line per block, with the inline runs of a block joined. The API writes it with every insert and content update.
  • Indexed. Trigram (pg_trgm) GIN indexes on content_text and title serve the ILIKE match for queries of three or more characters.
  • Block number. A content hit carries block (1-based position of the matching block) and its excerpt comes from that block. Title hits carry no block.
  • Old rows keep working. Rows written before the migration have content_text IS NULL until the background backfill fills them (it runs after the content-hash backfill, in the same worker). Until then search finds them through the old JSON match. The backfill does not move updated_at, the document sequence or the change feed.
  • MCP. search_docs prints the block number when the server sends one, and its description no longer says a match is limited to one run of text.

Migration 000091

  • CREATE EXTENSION IF NOT EXISTS pg_trgm is the first statement. pg_trgm is a trusted extension (PostgreSQL 13+), so the migration role needs CREATE on the database. If it does not have it, the migration fails at that statement with nothing applied; the file's header says what to run by hand. The bundled postgres:16-alpine images ship pg_trgm.
  • Adds the column, the two trigram indexes and a partial index on rows still waiting for the backfill (so every branch of the search OR has an index; it is empty once the backfill is done).
  • Adds a trigger that sets content_text back to NULL when content changes and the writer did not fill content_text itself (an API pod from before this migration during a rolling upgrade, or a manual SQL update). Search then finds the row through the old JSON match instead of returning it for text it no longer has, and the backfill refills it at the next start. The API declares its own writes with a transaction-local setting (paca.content_text_written, the same mechanism as paca.skip_doc_seq), so they keep the column filled.
  • Up-only and safe to apply twice.

Decisions, listed so they can be challenged

  1. A query is matched within one block. Line breaks in a query become spaces.
  2. A table is one line (cells tab-separated) and a hard break inside a block becomes a space, so block is always a block position.
  3. Content whose top level is not an array (legacy rows; the API rejects it today) is indexed from its text values, and its hits carry no block.
  4. The excerpt is computed in Go from the content, with the same function that fills the column, so it is the same for rows not backfilled yet.

Known gaps

  • Queries of one or two characters cannot use the trigram index and scan, as before.
  • A row cleared by the trigger above after the backfill of the running API has finished stays unindexed (still found, through the old match) until the next API start or the next edit of the document.
  • The backfill stops for this process run when every remaining row is locked by another transaction; those rows are picked up at the next start (same as the hash backfill).
  • On a very large table each backfill batch may sort the remaining rows.
  • Text stored outside inline content (for example inside block props) was matched by the old search and is not in content_text. BlockNote's own blocks keep their text in inline content.

Type of Change

  • New feature (API, MCP), with a migration

Testing

  • services/api, CI's commands in a Linux container on this branch rebased on master: go vet, unit tests with -race and ./test/e2e/... pass.
    • New e2e tests in test/e2e/doc_text_search_test.go: a content change by a writer that does not fill the text column (raw SQL) clears it and search follows the new text, the same content written again keeps it, a formatting-only change through the API keeps it, the migration applied twice leaves one trigger, phrase across formatting, block number, scope, row not backfilled yet, % _ \ taken literally, a query with a line break, legacy non-array content, backfill leaves the change feed quiet, write by path stores the text, and TestSearch_UsesTrigramIndexes (5000 rows, EXPLAIN of the real statement: both trigram indexes used and no sequential scan under default settings; 20 of 20 runs pass).
    • Unit tests for ContentText, the hit builder, the query normalisation and the backfill worker.
  • Migration checked by hand: applied twice without error; with a role that lacks CREATE on the database it fails at the first statement and adds nothing.
  • apps/mcp: tsc clean, vitest 748 of 748.
  • Browser specs (apps/e2e, chromium, tests/docs and tests/realtime) on a stack built from this branch: 215 passed, 6 skipped, 1 failed. The failure is docs.spec.ts:640 (edit own comment, uses Control+a on macOS), which fails the same way on master.

Checklist

  • The change is focused and scoped.
  • Related documentation is updated: none needed (migration header and code comments).

Store each document's plain text in documents.content_text (one line per
block, inline runs joined) on every insert and update, and fill older rows
from the hash backfill worker without moving seq, so search matches a
phrase across bold, italic and links. Search uses trigram indexes on title
and content_text, keeps the JSON-path match for rows not backfilled yet,
and reports the block of the first match.
Move the EXPLAIN check from the DSN-gated repository test to test/e2e,
on a seeded and analysed table, with sequential scans off and with the
default planner settings. SearchDocumentsQuery exposes the exact
statement SearchDocuments runs.
…ne queries

Content whose top level is not a block array now gives every "text"
string as content_text, so a row the old JSON-path search found is still
found after the backfill (its hits carry no block). A query's line
breaks become spaces, so the SQL and the per-line hit builder agree.
Update the repository comment to describe content_text.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No critical issues — two rough edges worth a look.

Reviewed changes

  • Plain-text search column. Migration 000091 adds documents.content_text, one line per block with a block's inline runs joined; insertDocument and updateDocumentLocked write it from docdom.ContentText, and empty content stores '' so NULL always means "not backfilled".
  • Flattener. internal/domain/doc/contenttext.go walks blocks, children, links, tables and string content, and falls back to every text string (streamed, at any depth) for legacy non-array content, reporting those lines as not blocks.
  • Indexed search. SearchDocuments now matches title and content_text with ILIKE, keeping the JSON-path branch only for rows where content_text IS NULL; two GIN trigram indexes plus a partial index on unbackfilled rows serve the statement.
  • Block position on hits. SearchHit.Block, the DTO block field and a per-block excerpt in NewSearchHit; the MCP search_docs tool prints the block number and its description no longer promises single-run matching.
  • Query normalisation. docdom.SearchQuery turns line breaks into spaces so a query is matched within one block by both the SQL and the hit builder, applied in the service.
  • Backfill. DocHashBackfill now drains content_text after hashes (BackfillContentText), with the same "no seq, no updated_at, no change feed" rules, and reports the sum of both drains.
  • Tests. Unit tests for the flattener, hit builder, query normalisation and worker; PG tests for writes and the backfill; e2e tests for phrases across formatting, block numbers, scope, wildcards, unbackfilled rows, legacy content, the change feed staying quiet, by-path writes and an EXPLAIN of the real statement.

ℹ️ A rolling upgrade leaves content_text stale, and nothing repairs it

The API Deployment in the Helm chart has no explicit strategy, so it is RollingUpdate; with replicaCount: 1 the new pod applies 000091 and becomes ready while the old pod still serves writes. An old pod's UPDATE documents ... does not know content_text, so the previous value survives — non-NULL, and therefore invisible to a backfill that only selects content_text IS NULL. Documents saved in that window keep returning hits for text they no longer contain (with an empty excerpt, since NewSearchHit rebuilds from the current content) and their new text stays unsearchable until a new pod saves them again. The mirror case is cheaper but also worth knowing: a document inserted by an old pod after the backfill finished stays NULL until the next process start, so it is searched through the JSON path.

Technical details
# Stale `content_text` after a mixed-version upgrade

## Affected sites
- `services/api/migrations/000091_add_documents_content_text.sql:25` — column added with no default, so pre-000091 writers simply do not touch it.
- `services/api/internal/repository/postgres/document_repository.go:706` — the only update path that refreshes `content_text`; code without it (old pod, or any future direct SQL writer) leaves the previous value.
- `services/api/internal/repository/postgres/document_repository.go:801` — backfill selects `content_text IS NULL` only, so a stale non-NULL value is never revisited.
- `deploy/helm/paca/templates/api/deployment.yaml:9` — no `strategy`, defaults to RollingUpdate; `deploy/helm/paca/values.yaml:232` sets `api.replicaCount: 1`.

## Required outcome
Either the staleness is accepted and recorded as a known gap, or there is a path that re-derives `content_text` for rows whose stored text no longer matches `docdom.ContentText(content)` (a one-off reindex command, or a startup option that ignores the NULL filter). The consequence to state either way: after an upgrade, search may return a document for text it no longer contains, with no excerpt, until that document is edited again.

## Open questions for the human
- Is a mixed-version window during Helm upgrades a scenario this feature needs to survive, or is a doc note on the upgrade path enough?

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

Delta since the prior pullfrog review (97c5e11): one commit, 7a55ffc8.

  • Query normalisation moved next to the SQL. searchDocumentsQuery now builds its pattern from docdom.SearchQuery(query) instead of a bare strings.TrimSpace, so a direct SearchDocuments/SearchDocumentsQuery caller gets the same single-line pattern as the service path. The call is idempotent on the service path, which still normalises and still short-circuits an empty query before hitting the repo.
  • Regression assertion in the EXPLAIN e2e test. TestSearch_UsesTrigramIndexes now runs " the\r\nworker\n" through SearchDocumentsQuery and requires a %the worker% argument, so the invariant that a query is matched within one block is pinned at the repository seam rather than only through the service.
  • Stale comment fixed. The backfill test comment now names migration 000091.

ℹ️ The rolling-upgrade staleness question from the prior review is still open

This was raised as an informational observation before this commit and the new commit does not change it: a document saved by an old pod during a rolling upgrade keeps its previous content_text (non-NULL, so the content_text IS NULL backfill never revisits it), and search can keep returning it for text it no longer contains, with no excerpt, until it is edited again. Nothing here needs to change for the search fix itself; the open item is whether that upgrade window must survive or is acceptable as a documented known gap.

Technical details
# Mixed-version `content_text` staleness (carried over, unresolved by design decision)

## Affected sites
- `services/api/internal/repository/postgres/document_repository.go:706` — the only update path that refreshes `content_text`; a pre-000091 writer leaves the old value.
- `services/api/internal/repository/postgres/document_repository.go:801` — the backfill selects `content_text IS NULL` only.
- `deploy/helm/paca/templates/api/deployment.yaml:9` — no `strategy`, so RollingUpdate; `deploy/helm/paca/values.yaml:232` sets `api.replicaCount: 1`.

## Required outcome
Either record the window in the PR's known gaps / upgrade notes, or add a path that re-derives `content_text` for rows whose stored text no longer matches `docdom.ContentText(content)`.

## Open questions for the human
- Is a mixed-version window during Helm upgrades a scenario this feature needs to survive, or is a doc note on the upgrade path enough?

Pullfrog  | View workflow run | Using deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

@pikann pikann left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! Thank you for the contribution! 🚀

@pikann
pikann merged commit 436e31b into Paca-AI:master Nov 15, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants