Skip to content

perf(db): optimize scoped retrieval queries#714

Merged
BigSimmo merged 2 commits into
mainfrom
codex/chat-supabase-migration-preflight-b463
Jul 17, 2026
Merged

perf(db): optimize scoped retrieval queries#714
BigSimmo merged 2 commits into
mainfrom
codex/chat-supabase-migration-preflight-b463

Conversation

@BigSimmo

@BigSimmo BigSimmo commented Jul 17, 2026

Copy link
Copy Markdown
Owner

Summary

  • optimize owner-plus-public text retrieval as one scoped query
  • split index-unit text and term candidate branches so PostgreSQL can use the existing GIN indexes
  • preserve committed-generation, document-status, and owner/public access filtering before ranking
  • update the canonical schema, drift manifest, regression coverage, and review ledger
  • allow isolated drift replay containers for concurrent worktrees

Why

The production review found a P2 latency hotspot: text retrieval took about 1.269 seconds and the daily index-unit snapshot averaged 3.673 seconds. The old wrappers executed owner and public paths separately, while the index-unit query combined two indexed predicates with a cross-index OR.

After deployment, warm text retrieval measured 34 ms and warm index-unit retrieval measured 36–39 ms. Access-scope parity remained unchanged.

Production and governance

Migration 20260717160000_optimize_owner_public_retrieval.sql has already been applied to Clinical KB Database (sjrfecxgysukkwxsowpy) through the linked migration workflow.

  • post-deploy drift: No unexpected schema drift
  • local and remote migration history aligned through 20260717160000
  • Supabase security advisor: zero findings
  • scoped helpers remain revoked from PUBLIC, anon, and authenticated; service-role access only
  • live parity checks found no private-document exposure
  • no OpenAI calls were made

Verification

Passed:

  • isolated Docker schema replay
  • ESLint
  • TypeScript
  • focused Vitest: 74/74
  • offline RAG fixtures: 36/36
  • offline RAG contract tests: 291/291
  • npm run check:function-grants
  • npm run check:production-readiness
  • npm run check:supabase-project
  • npm run check:drift
  • npx supabase migration list --linked
  • git diff --check

The exact integrated-head verify:pr-local plan was attempted twice but did not start because another Database worktree held the repository-wide heavyweight test lock. Hosted CI is therefore the required exact-head merge gate. The earlier broad verify:cheap run reached the 10-minute host timeout during aggregate Vitest; all affected focused and domain suites passed.

Residual risk

Cold-cache index-unit retrieval remains sensitive to physical reads (2.376 seconds in the measured cold run). Backup/PITR restoration and write-load testing were not performed.

Summary by CodeRabbit

  • Performance

    • Improved document retrieval performance for text and index-unit searches.
  • Security & Access

    • Retrieval now applies owner/public access controls and committed-content checks within a single scoped query.
  • Reliability

    • Added validation coverage for optimized retrieval paths and schema drift tracking.
  • Maintenance

    • Added support for custom scratch database container names when generating drift manifests.

@supabase

supabase Bot commented Jul 17, 2026

Copy link
Copy Markdown

Updates to Preview Branch (codex/chat-supabase-migration-preflight-b463) ↗︎

Deployments Status Updated
Database Fri, 17 Jul 2026 11:42:59 UTC
Services Fri, 17 Jul 2026 11:42:59 UTC
APIs Fri, 17 Jul 2026 11:42:59 UTC

Tasks are run on every commit but only new migration files are pushed.
Close and reopen this PR if you want to apply changes from existing seed or migration files.

Tasks Status Updated
Configurations Fri, 17 Jul 2026 11:43:07 UTC
Migrations Fri, 17 Jul 2026 11:44:16 UTC
Seeding Fri, 17 Jul 2026 11:44:19 UTC
Edge Functions Fri, 17 Jul 2026 11:44:20 UTC

View logs for this Workflow Run ↗︎.
Learn more about Supabase for Git ↗︎.

@coderabbitai

coderabbitai Bot commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

Retrieval optimization and validation

Layer / File(s) Summary
Scoped retrieval implementations
supabase/migrations/..., supabase/schema.sql
Adds scoped text and index-unit retrieval RPCs with owner/public filtering, committed-generation checks, indexed candidate paths, and ranking logic.
Wrapper contracts and validation
supabase/schema.sql, supabase/migrations/..., supabase/drift-manifest.json, tests/retrieval-access-scope.test.ts
Routes versioned RPCs through scoped helpers, updates execute permissions and drift metadata, and verifies the scoped SQL structure in both schema sources.
Drift-manifest operations
scripts/generate-drift-manifest.ts, docs/branch-review-ledger.md, supabase/drift-manifest.json
Adds configurable scratch-container naming and records the production preflight and schema-validation results.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant service_role
  participant v2_RPC
  participant scoped_RPC
  participant retrieval_tables
  service_role->>v2_RPC: invoke retrieval
  v2_RPC->>scoped_RPC: forward scope parameters
  scoped_RPC->>retrieval_tables: filter and rank candidates
  retrieval_tables-->>scoped_RPC: return matching rows
  scoped_RPC-->>service_role: return scoped results
Loading

Possibly related PRs

  • BigSimmo/Database#568: Both changes modify the owner/public retrieval RPC wrappers and their use of retrieval_owner_matches_v2.
  • BigSimmo/Database#446: Both changes modify the branch review ledger documentation.

Suggested reviewers: copilot, claude

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed Clear, concise summary of the main DB retrieval optimization.
Description check ✅ Passed Covers summary, rationale, production notes, verification, and residual risk, though it doesn't mirror the template's checkbox sections exactly.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/chat-supabase-migration-preflight-b463

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

@BigSimmo
BigSimmo merged commit 220de89 into main Jul 17, 2026
14 checks passed

@coderabbitai coderabbitai 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.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@scripts/generate-drift-manifest.ts`:
- Around line 62-70: Remove the preemptive docker(["rm", "-f", container])
cleanup around the scratch-container startup, including the corresponding
try/catch near the cleanup path. Let docker(["run", ...]) fail naturally when
the requested container name is already in use, and ensure later cleanup
executes only after this invocation successfully starts its own container.

In `@supabase/migrations/20260717160000_optimize_owner_public_retrieval.sql`:
- Around line 280-296: Apply the min_similarity threshold to the index-unit
retrieval query before candidate limiting, filtering on vector similarity so
low-similarity rows are excluded. Mirror this change in both
supabase/migrations/20260717160000_optimize_owner_public_retrieval.sql (lines
280-296) and supabase/schema.sql (lines 7245-7261), then add regression coverage
verifying candidates below the requested threshold are not returned.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 60a36258-e3a0-48e3-8e29-827e564e7b79

📥 Commits

Reviewing files that changed from the base of the PR and between 9a3cc9f and 1ef0fae.

📒 Files selected for processing (6)
  • docs/branch-review-ledger.md
  • scripts/generate-drift-manifest.ts
  • supabase/drift-manifest.json
  • supabase/migrations/20260717160000_optimize_owner_public_retrieval.sql
  • supabase/schema.sql
  • tests/retrieval-access-scope.test.ts

Comment on lines +62 to +70
console.log(`Starting scratch container ${container} (${image}) on port ${port}…`);
try {
docker(["rm", "-f", CONTAINER]);
docker(["rm", "-f", container]);
} catch {
// not running — fine
}
const startedAt = Date.now();
const scratchPassword = randomBytes(16).toString("hex");
docker(["run", "-d", "--name", CONTAINER, "-e", `POSTGRES_PASSWORD=${scratchPassword}`, "-p", `${port}:5432`, image]);
docker(["run", "-d", "--name", container, "-e", `POSTGRES_PASSWORD=${scratchPassword}`, "-p", `${port}:5432`, image]);

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Do not forcibly remove an arbitrary --container target.

A typo or reused name currently executes docker rm -f against an unrelated container. Let docker run fail on collision; cleanup will then only run after this invocation successfully starts its own container.

Proposed fix
   console.log(`Starting scratch container ${container} (${image}) on port ${port}…`);
-  try {
-    docker(["rm", "-f", container]);
-  } catch {
-    // not running — fine
-  }
   const startedAt = Date.now();

As per coding guidelines, “do not kill or modify another project's server.”

Also applies to: 124-129

🧰 Tools
🪛 ast-grep (0.44.1)

[warning] Importing child_process exposes a command-execution surface; ensure any command/argument built from input is validated, and prefer execFile/spawn with an argument array over exec.
Context: import { execFileSync } from "node:child_process";
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

(detect-child-process-typescript)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@scripts/generate-drift-manifest.ts` around lines 62 - 70, Remove the
preemptive docker(["rm", "-f", container]) cleanup around the scratch-container
startup, including the corresponding try/catch near the cleanup path. Let
docker(["run", ...]) fail naturally when the requested container name is already
in use, and ensure later cleanup executes only after this invocation
successfully starts its own container.

Source: Coding guidelines

Comment on lines +280 to +296
similarity,
text_rank,
(
(similarity * 0.52)
+ (least(text_rank, 1) * 0.28)
+ (quality_score * 0.12)
+ (case when extraction_mode in ('model_heavy', 'hybrid') then 0.04 else 0 end)
+ (case
when unit_type in ('askable_question', 'threshold', 'table_fact', 'table_threshold', 'visual_askable_question') then 0.04
when unit_type in ('workflow_step', 'medication_monitoring', 'flowchart_step', 'diagram_decision', 'medication_chart_row', 'risk_matrix_cell') then 0.03
else 0
end)
)::double precision as hybrid_score,
metadata
from ranked
order by hybrid_score desc, id
limit match_count;

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Honor min_similarity in both index-unit implementations.

Both functions accept the threshold but return candidates without applying it, allowing results below the caller’s requested similarity.

  • supabase/migrations/20260717160000_optimize_owner_public_retrieval.sql#L280-L296: filter by vector similarity before candidate limiting.
  • supabase/schema.sql#L7245-L7261: mirror the same filter in the canonical schema.

Add regression coverage proving low-similarity candidates are excluded.

📍 Affects 2 files
  • supabase/migrations/20260717160000_optimize_owner_public_retrieval.sql#L280-L296 (this comment)
  • supabase/schema.sql#L7245-L7261
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@supabase/migrations/20260717160000_optimize_owner_public_retrieval.sql`
around lines 280 - 296, Apply the min_similarity threshold to the index-unit
retrieval query before candidate limiting, filtering on vector similarity so
low-similarity rows are excluded. Mirror this change in both
supabase/migrations/20260717160000_optimize_owner_public_retrieval.sql (lines
280-296) and supabase/schema.sql (lines 7245-7261), then add regression coverage
verifying candidates below the requested threshold are not returned.

@BigSimmo
BigSimmo deleted the codex/chat-supabase-migration-preflight-b463 branch July 17, 2026 14:36
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.

1 participant