Skip to content

feat(rag): folder-scoped search filter - #1865

Merged
yannickmonney merged 2 commits into
mainfrom
feat/rag-folder-scoped-search
Jun 11, 2026
Merged

yannickmonney merged 2 commits into
mainfrom
feat/rag-folder-scoped-search

Conversation

@yannickmonney

Copy link
Copy Markdown
Contributor

Closes #662

What / why

Adds an optional folder filter to RAG search so retrieval can be scoped to one Document Hub folder and all of its subfolders — "search only in Contracts/2024". The issue's original sketch (team_id scoping, (team_id, folder_path) index) is stale: search is scoped by org_slug + a required file_ids list today, and file_ids stays the sole authorization boundary — folder_path is a pure narrowing filter, so staleness can only affect filter precision, never access.

RAG service (services/rag)

  • Migration 20260611000001_add_documents_folder_path.sql: documents.folder_path TEXT + partial (org_slug, folder_path) index.
  • _build_scope_clause now collects document-level filters into a generic condition list applied through the single org-scoped documents subquery (both FTS and vector channels). This is the seam Improvement: Enhance RAG retrieval with metadata pre-filtering and optional cross-encoder re-ranking #1517's metadata filters extend — folder_path is the first generic filter.
  • Boundary-safe hierarchical prefix: (folder_path = $p OR left(folder_path, char_length($p) + 1) = $p || '/') — data-room matches data-room/contracts but never the sibling data-room-x, with no LIKE-escaping surface.
  • POST /api/v1/search gains a flat optional folder_path (normalized + length-capped via pydantic). Semantic cache is bypassed (lookup and store) for folder-filtered queries — the cache key has no scope dimension.
  • Ingestion: folder_path parsed from the existing upload metadata form field, written by _insert_processing_row (insert + conflict-update; the _do_store/_do_clone upserts never touch the column, so dedup/skip paths can't clobber it).
  • New batch PATCH /api/v1/documents/folder-paths (org-scoped, max 200, single UPDATE … FROM unnest(...)) so folder moves stay fresh without re-extraction/re-embedding.

Platform (services/platform)

  • uploadDocument (the chokepoint every RAG upload funnels through) resolves folderPath from the linked Hub document via fileMetadata.documentId and merges folder_path into the upload metadata; uploadDocumentToRag / reindexDocumentInRag pass document.folderPath explicitly (belt-and-suspenders vs. linkage races). Chat uploads carry no folder.
  • New syncRagFolderPaths internal action (warn-and-skip on failure) + freshness hooks: updateDocumentInternal on folder change of an indexed doc (skipped when a re-index is scheduled), WebDAV moveResource document branch, and the folder-subtree fixup (one batch per move).
  • rag_search agent tool gains an optional folderPath arg (hierarchical/recursive, / separators, no leading slash — description contrasts with document_find's fuzzy non-recursive filter).
  • Backfill: migrations/backfill_rag_folder_path.ts (bunx convex run migrations/backfill_rag_folder_path:backfillRagFolderPath) sweeps already-indexed Hub documents through the PATCH endpoint — run once after deploy so pre-existing documents match folder filters.
  • Shared normalization helper lib/helpers/rag_folder_path.ts, kept in sync with app/utils/folder_path.py.

Decision-gate recommendations baked in (veto at review)

Verification

Performed:

  • cd services/rag && uv run pytest — 346 passed (new: scope-clause folder tests incl. param offsets + boundary expression, cache-bypass both ways, BM25-fallback threading, org-isolation folder test, normalization/model validation, _insert_processing_row, PATCH handler incl. dedupe + 500 path).
  • uv run ruff check app + ruff format --check app — clean.
  • Platform vitest: rag_folder_path, upload_document (Hub-doc resolution, explicit override, no-doc/no-path omission), update_document_internal (folder-move sync schedule/skip matrix) — all green.
  • bun run check at repo root — 40/40 tasks green (format, lint, typecheck, all tests incl. docs locale parity).
  • convex/_generated/api.d.ts updated for the new migrations module (codegen needs a live deployment; entry added in the generated-file format).

Manual verification required (needs a running stack):

  • Apply the dbmate migration; upload a Hub doc inside a folder; POST /api/v1/search with/without folder_path, verifying the boundary case (data-room must not match data-room-x).
  • Move the doc to another folder (UI + WebDAV) and re-search.
  • Agent chat: "search only in folder X" → tool call carries folderPath.
  • Run the backfill action once on existing deployments.

Pre-PR checklist

  • Ran bun run check (format, lint, typecheck, all tests).
  • No hand-rolled skeletons — N/A (no UI change).
  • Updated services/platform/messages/{en,de,fr}.json — N/A (no UI strings; agent tool descriptions are not i18n'd).
  • Updated /docs/{en,de,fr}/ — RAG bullet in platform/agents/tools.md mentions folder-scoped retrieval in all three locales.
  • Touched docs pages keep their real opening/closing (bullet-only edit; docs tests pass).
  • Ran bun run --filter @tale/docs lint and bun run --filter @tale/docs test.
  • Updated READMEs — N/A.

Note for #1517: branch feat/rag-folder-scoped-search is the base for the metadata pre-filter work — _build_scope_clause's condition list and the upload-metadata path are the shared seams.

Add an optional folder_path filter to RAG search so retrieval can be
scoped to one Document Hub folder and all of its subfolders (#662).

RAG service:
- documents.folder_path column + partial (org_slug, folder_path) index
- boundary-safe hierarchical prefix filter as the first generic
  per-document condition in _build_scope_clause (the seam #1517's
  metadata filters extend); applied to both FTS and vector channels
- folder_path on POST /api/v1/search (flat wire field, normalized);
  semantic cache bypassed for folder-filtered queries (cache key has
  no scope dimension)
- ingestion: folder_path parsed from the existing upload metadata form
  field, written by _insert_processing_row (insert + conflict-update)
- batch PATCH /api/v1/documents/folder-paths to keep paths fresh on
  folder moves without re-extraction or re-embedding

Platform:
- uploadDocument resolves folderPath from the linked Hub document and
  sends it in the upload metadata (single chokepoint for all upload
  paths); uploadDocumentToRag/reindexDocumentInRag pass it explicitly
- syncRagFolderPaths internal action + hooks on document folder moves
  (updateDocumentInternal) and WebDAV moves (moveResource, folder
  subtree fixup)
- rag_search agent tool gains an optional folderPath arg (hierarchical,
  exact — contrasted with document_find's fuzzy non-recursive filter)
- backfill action migrations/backfill_rag_folder_path for documents
  indexed before the column existed

file_ids remains the sole authorization boundary; folder_path is a pure
narrowing filter, so staleness can only affect filter precision.
@coderabbitai

coderabbitai Bot commented Jun 10, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@yannickmonney, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 23 minutes and 44 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: a35c6744-3968-4e04-b362-2d45c31f024e

📥 Commits

Reviewing files that changed from the base of the PR and between 95ea179 and ae76554.

⛔ Files ignored due to path filters (3)
  • services/platform/convex/_generated/api.d.ts is excluded by !**/_generated/**
  • services/platform/convex/migrations/backfill_rag_folder_path.ts is excluded by !**/migrations/**
  • services/rag/migrations/20260611000001_add_documents_folder_path.sql is excluded by !**/migrations/**
📒 Files selected for processing (24)
  • docs/de/platform/agents/tools.md
  • docs/en/platform/agents/tools.md
  • docs/fr/platform/agents/tools.md
  • services/platform/convex/agent_tools/rag/rag_search_tool.ts
  • services/platform/convex/documents/internal_actions.ts
  • services/platform/convex/documents/update_document_internal.test.ts
  • services/platform/convex/documents/update_document_internal.ts
  • services/platform/convex/lib/helpers/rag_folder_path.test.ts
  • services/platform/convex/lib/helpers/rag_folder_path.ts
  • services/platform/convex/webdav/tree_mutations.ts
  • services/platform/convex/workflow_engine/action_defs/rag/helpers/types.ts
  • services/platform/convex/workflow_engine/action_defs/rag/helpers/upload_document.test.ts
  • services/platform/convex/workflow_engine/action_defs/rag/helpers/upload_document.ts
  • services/platform/convex/workflow_engine/action_defs/rag/rag_action.ts
  • services/rag/app/models.py
  • services/rag/app/routers/documents.py
  • services/rag/app/routers/search.py
  • services/rag/app/services/rag_service.py
  • services/rag/app/services/search_service.py
  • services/rag/app/utils/folder_path.py
  • services/rag/tests/test_folder_path.py
  • services/rag/tests/test_org_isolation.py
  • services/rag/tests/test_rag_service.py
  • services/rag/tests/test_search_service.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/rag-folder-scoped-search

Warning

Billing warning: we have not been able to collect payment for this subscription for more than 72 hours. Please update the payment method or pay any pending invoices in Billing to avoid service interruption.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@yannickmonney
yannickmonney merged commit 2cd6cb2 into main Jun 11, 2026
30 checks passed
@yannickmonney
yannickmonney deleted the feat/rag-folder-scoped-search branch June 11, 2026 00:18
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.

feat(rag): Add folder-scoped search filter

1 participant