Repository navigation
feat(api): search document text across formatting with a trigram index - #768
Conversation
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.
There was a problem hiding this comment.
ℹ️ No critical issues — two rough edges worth a look.
Reviewed changes
- Plain-text search column. Migration
000091addsdocuments.content_text, one line per block with a block's inline runs joined;insertDocumentandupdateDocumentLockedwrite it fromdocdom.ContentText, and empty content stores''so NULL always means "not backfilled". - Flattener.
internal/domain/doc/contenttext.gowalks blocks, children, links, tables and string content, and falls back to everytextstring (streamed, at any depth) for legacy non-array content, reporting those lines as not blocks. - Indexed search.
SearchDocumentsnow matchestitleandcontent_textwithILIKE, keeping the JSON-path branch only for rows wherecontent_text IS NULL; two GIN trigram indexes plus a partial index on unbackfilled rows serve the statement. - Block position on hits.
SearchHit.Block, the DTOblockfield and a per-block excerpt inNewSearchHit; the MCPsearch_docstool prints the block number and its description no longer promises single-run matching. - Query normalisation.
docdom.SearchQueryturns 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.
DocHashBackfillnow drainscontent_textafter hashes (BackfillContentText), with the same "no seq, noupdated_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
EXPLAINof 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?deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏
…ation number in a comment
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Delta since the prior pullfrog review (97c5e11): one commit, 7a55ffc8.
- Query normalisation moved next to the SQL.
searchDocumentsQuerynow builds its pattern fromdocdom.SearchQuery(query)instead of a barestrings.TrimSpace, so a directSearchDocuments/SearchDocumentsQuerycaller 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_UsesTrigramIndexesnow runs" the\r\nworker\n"throughSearchDocumentsQueryand 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?deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏
pikann
left a comment
There was a problem hiding this comment.
LGTM! Thank you for the contribution! 🚀

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 byfoo bar, and every search read all documents of the project.After
documents.content_textholds 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.pg_trgm) GIN indexes oncontent_textandtitleserve theILIKEmatch for queries of three or more characters.block(1-based position of the matching block) and its excerpt comes from that block. Title hits carry no block.content_text IS NULLuntil 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 moveupdated_at, the document sequence or the change feed.search_docsprints the block number when the server sends one, and its description no longer says a match is limited to one run of text.Migration
000091CREATE EXTENSION IF NOT EXISTS pg_trgmis the first statement.pg_trgmis a trusted extension (PostgreSQL 13+), so the migration role needsCREATEon 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 bundledpostgres:16-alpineimages shippg_trgm.ORhas an index; it is empty once the backfill is done).content_textback to NULL whencontentchanges and the writer did not fillcontent_textitself (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 aspaca.skip_doc_seq), so they keep the column filled.Decisions, listed so they can be challenged
blockis always a block position.textvalues, and its hits carry noblock.Known gaps
props) was matched by the old search and is not incontent_text. BlockNote's own blocks keep their text in inline content.Type of Change
Testing
services/api, CI's commands in a Linux container on this branch rebased onmaster:go vet, unit tests with-raceand./test/e2e/...pass.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, andTestSearch_UsesTrigramIndexes(5000 rows,EXPLAINof the real statement: both trigram indexes used and no sequential scan under default settings; 20 of 20 runs pass).ContentText, the hit builder, the query normalisation and the backfill worker.CREATEon the database it fails at the first statement and adds nothing.apps/mcp:tscclean,vitest748 of 748.apps/e2e, chromium,tests/docsandtests/realtime) on a stack built from this branch: 215 passed, 6 skipped, 1 failed. The failure isdocs.spec.ts:640(edit own comment, usesControl+aon macOS), which fails the same way onmaster.Checklist