Skip to content

Reduce cold RAG round trips and reconcile retention controls#632

Merged
BigSimmo merged 5 commits into
mainfrom
codex/rag-performance-followups
Jul 13, 2026
Merged

Reduce cold RAG round trips and reconcile retention controls#632
BigSimmo merged 5 commits into
mainfrom
codex/rag-performance-followups

Conversation

@BigSimmo

@BigSimmo BigSimmo commented Jul 13, 2026

Copy link
Copy Markdown
Owner

Summary

  • remove the second cross-region shared-cache miss diagnostic read
  • parallelize independent metadata, index-quality, page, and direct-image hydration reads
  • persist a provider-generation degradation signal without counting intentional extractive answers
  • consolidate response-cache retention onto one bounded hourly purge
  • correct Singapore processing/privacy disclosures and reconcile stale launch/RAG documentation

Why

Cold RAG answers were paying avoidable serial database round trips, the degraded-answer SLO lacked a provider-specific signal, and governance/runbook state no longer matched the deployed Railway Singapore and Supabase Sydney topology.

Areas changed

  • src/lib/rag-cache.ts, src/lib/rag.ts, answer SLO/health telemetry
  • response-cache retention migration and schema regression coverage
  • privacy page, PIA, deployment architecture, launch runbook, observability SLOs, RAG backlog
  • focused cache, concurrency, SLO, fallback, privacy, and migration tests

Verification

  • npm run check:runtime — passed (Node 24.18.0 / npm 11.17.0)
  • npm run format:check — passed
  • npm run lint — passed
  • npm run typecheck — passed, including after review fix
  • npm run test — 2,213 passed / 1 skipped on the initial PR head
  • review fix — focused ESLint and 45/45 targeted tests passed
  • npm run build — passed; 636 pages generated and client-bundle secret scan passed
  • npm run eval:rag:offline — 36 fixtures and 277/277 contract tests passed before and after review fix
  • production check:supabase-project — correct Clinical KB Database ref
  • production check:production-readiness — READY, 6 passes / 2 expected local-file warnings
  • git diff --check — passed

The combined verify:pr-local wrapper exceeded the local shell's 15-minute ceiling; every selected component above was rerun individually and passed.

Review follow-up

Codex identified that the broad source-only degraded state also includes healthy extractive answers. Commit 07cac8f4 adds provider_generation_degraded, derived only from generation_fallback, and points the provider-health SLO at that narrower flag. The thread is fixed and resolved.

Production and governance notes

The bounded retention migration was already applied and verified live: query-miss job 13 and response-cache job 16 are active, and the obsolete unbounded job is absent. This PR records that state and supplies the matching migration artifact.

No deployment, read replica, model change, dependency change, or legal agreement acceptance is included. Model-routing experiments remain blocked by exhausted OpenAI quota. Railway/OpenAI contractual execution remains with the authorised account/legal owner.

Checks not run

  • Live model generation: blocked by provider quota and not required for these fail-closed/local changes.

Summary by CodeRabbit

  • New Features
    • Added hourly, cron-based cleanup for expired RAG response-cache entries.
    • Improved RAG enrichment speed by fetching ranking and page evidence in parallel.
    • Enhanced observability with dedicated provider-generation degradation metadata.
  • Bug Fixes
    • Fixed “degraded/source-only” health measurement to use an explicit provider-generation degradation flag.
    • Refined shared search cache miss handling for more consistent cold/invalid results.
  • Documentation
    • Updated privacy, deployment/performance, launch runbook, observability SLOs, RAG hybrid findings, and cross-border governance notes.
  • Tests
    • Expanded coverage for SLO counting, cache behavior, concurrency, privacy UI copy, and schema/retention validation.

Correct degraded-answer telemetry, consolidate bounded cache retention, parallelize independent hydration reads, and reconcile privacy and launch documentation with the verified live topology.
@supabase

supabase Bot commented Jul 13, 2026

Copy link
Copy Markdown

Updates to Preview Branch (codex/rag-performance-followups) ↗︎

Deployments Status Updated
Database Mon, 13 Jul 2026 22:02:19 UTC
Services Mon, 13 Jul 2026 22:02:19 UTC
APIs Mon, 13 Jul 2026 22:02:19 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 Mon, 13 Jul 2026 22:02:21 UTC
Migrations Mon, 13 Jul 2026 22:02:23 UTC
Seeding Mon, 13 Jul 2026 22:02:25 UTC
Edge Functions Mon, 13 Jul 2026 22:02:26 UTC

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

@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@BigSimmo, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 6 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

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.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 24ee031d-cc90-40a7-bb82-c6e7ae37d05a

📥 Commits

Reviewing files that changed from the base of the PR and between a2eb6db and fa0a617.

📒 Files selected for processing (4)
  • docs/branch-review-ledger.md
  • docs/observability-slos.md
  • src/lib/observability/answer-slo.ts
  • tests/answer-slo.test.ts
📝 Walkthrough

Walkthrough

The change updates provider-generation degradation measurement, concurrent RAG enrichment, shared-cache handling, response-cache retention, privacy disclosures, cross-border governance records, launch sequencing, and performance findings. Tests cover the revised SLO filters, concurrency, cache behavior, privacy copy, and migration SQL.

Changes

RAG platform and operations

Layer / File(s) Summary
Explicit provider-generation degradation telemetry
src/lib/observability/answer-slo.ts, src/lib/health-response.ts, src/lib/rag-answer-support.ts, src/lib/rag.ts, tests/*, docs/observability-slos.md
Degraded-answer metrics now count explicit provider_generation_degraded metadata, with corresponding logging, classification, typing, documentation, and tests.
Concurrent enrichment and cache outcomes
src/lib/rag.ts, src/lib/rag-cache.ts, tests/rag-query-concurrency.test.ts, tests/rag-shared-cache.test.ts
Document and image enrichment fetches run concurrently; shared-cache miss reasons and lookup behavior are simplified and tested.
Retention and privacy control alignment
supabase/migrations/*, tests/supabase-schema.test.ts, src/app/privacy/page.tsx, docs/privacy-impact-assessment.md, tests/privacy-ui.test.ts
Response-cache cleanup is consolidated into one bounded hourly cron job, while privacy materials describe Sydney, Singapore, and US processing locations and current purge coverage.
Cross-border governance record
docs/openai-cross-border-basis.md
OpenAI and Railway processing status, APP 8 scope, operator approval limits, contract tracking, and source references are updated.
Launch sequencing and performance evidence
docs/launch-operator-runbook.md, docs/deployment-architecture.md, docs/rag-hybrid-findings-and-todo.md, docs/branch-review-ledger.md
Runbook migration gates, deployment guardrails, latency evidence, RAG backlog status, and review records are refreshed.

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

Sequence Diagram(s)

sequenceDiagram
  participant RAGAnswerRoutes
  participant logRagQuery
  participant answerSloSnapshot
  participant Supabase
  RAGAnswerRoutes->>logRagQuery: persist provider_generation_degraded metadata
  answerSloSnapshot->>Supabase: count provider_generation_degraded = "true"
  Supabase-->>answerSloSnapshot: return degraded count
  answerSloSnapshot-->>RAGAnswerRoutes: expose degradedQueries and degradedRate
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed, but it doesn't follow the required template and omits the Clinical Governance Preflight checklist needed here. Rewrite it to the repo template, including the checkbox verification list, Clinical Governance Preflight items, and a filled Notes section.
Docstring Coverage ⚠️ Warning Docstring coverage is 46.15% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately captures the main changes: reducing RAG round trips and reconciling retention controls.
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 unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/rag-performance-followups

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: aa264e92c4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/lib/observability/answer-slo.ts Outdated
@BigSimmo

Copy link
Copy Markdown
Owner Author

@codex resolve actionable Codex review findings for this pull request and current head using the repository instructions. This is the pull request's single automatic repair pass: do not perform a fresh review, create new standalone findings, or request another review. Work only the existing unresolved Codex threads on the current head. Always fix P0 and P1 findings. For P2 and lower findings, fix only clear, scoped, low-risk issues; otherwise disposition them with a concise reason. After fixing or dispositioning a thread, reply in that thread with as the first line, followed by a concise summary; that marker authorizes the workflow to close that exact thread. If human input or new authorization is required, do not use the marker and leave the thread open with the blocker. Finish only after every actionable thread is fixed or dispositioned and closed, or explicitly left open for a human decision. Do not update the branch from main, address unrelated reviews, broaden scope, or create more than one scoped fix commit. Do not use external APIs, paid services, credentials, dependency changes, or broad refactors unless explicitly authorized. Add targeted tests where behavior changes and run the narrowest relevant validation.

@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: 1

🧹 Nitpick comments (2)
docs/openai-cross-border-basis.md (1)

152-154: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

Track Railway’s pending DPA in the checklist/status table.

The paragraph correctly says the Railway contract is pending, but the numbered checklist and status table track only OpenAI. Because PIA-1 covers both Singapore and US processing, add a Railway checkbox and evidence/status field so completing the visible checklist cannot imply that the whole cross-border record is closed.

🤖 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 `@docs/openai-cross-border-basis.md` around lines 152 - 154, Update the
numbered checklist and status table in the cross-border processing documentation
to include Railway alongside OpenAI, adding a checkbox and corresponding
evidence/status field for Railway’s pending DPA and Singapore
processor/sub-processor basis. Ensure the visible checklist cannot indicate
PIA-1 is complete while Railway’s requirements remain unfinished.
src/lib/rag-cache.ts (1)

270-271: 🗄️ Data Integrity & Integration | 🔵 Trivial

LGTM on the correctness of the fold — the selector's existing filters (indexing_version, dependency_version, expires_at) do cover what the removed probe distinguished, and the new single-read path is verified by tests/rag-shared-cache.test.ts.

One thing worth a quick check: collapsing TTL-expired/indexing-mismatch/dependency-mismatch into one unknown_filter_miss reason loses the granularity any existing cache-miss dashboards or triage runbooks may have relied on for those specific causes.

Also applies to: 360-379

🤖 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 `@src/lib/rag-cache.ts` around lines 270 - 271, Update SharedCacheMissReason
and the shared-cache miss classification flow to preserve distinct reasons for
TTL expiration, indexing-version mismatch, and dependency-version mismatch
instead of mapping them to unknown_filter_miss. Trace the selector/result
handling around the single-read path and retain compatible reason names for
existing dashboards and triage runbooks, while keeping cache_lookup_error,
cache_lookup_exception, and cache_payload_invalid unchanged.
🤖 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 `@docs/openai-cross-border-basis.md`:
- Around line 104-106: Update the merge-status statement in the APP 5/1 section
to describe the privacy page and composer notice as a shipped draft with
governance approval pending, rather than marking APP 5/1 complete. Preserve the
existing PR and commit references, and ensure PIA-5 remains explicitly listed as
open alongside APP 8.

---

Nitpick comments:
In `@docs/openai-cross-border-basis.md`:
- Around line 152-154: Update the numbered checklist and status table in the
cross-border processing documentation to include Railway alongside OpenAI,
adding a checkbox and corresponding evidence/status field for Railway’s pending
DPA and Singapore processor/sub-processor basis. Ensure the visible checklist
cannot indicate PIA-1 is complete while Railway’s requirements remain
unfinished.

In `@src/lib/rag-cache.ts`:
- Around line 270-271: Update SharedCacheMissReason and the shared-cache miss
classification flow to preserve distinct reasons for TTL expiration,
indexing-version mismatch, and dependency-version mismatch instead of mapping
them to unknown_filter_miss. Trace the selector/result handling around the
single-read path and retain compatible reason names for existing dashboards and
triage runbooks, while keeping cache_lookup_error, cache_lookup_exception, and
cache_payload_invalid unchanged.
🪄 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: db64555d-9063-42a7-a6c9-ef1033405241

📥 Commits

Reviewing files that changed from the base of the PR and between 3737598 and aa264e9.

📒 Files selected for processing (19)
  • docs/branch-review-ledger.md
  • docs/deployment-architecture.md
  • docs/launch-operator-runbook.md
  • docs/observability-slos.md
  • docs/openai-cross-border-basis.md
  • docs/privacy-impact-assessment.md
  • docs/rag-hybrid-findings-and-todo.md
  • src/app/privacy/page.tsx
  • src/lib/health-response.ts
  • src/lib/observability/answer-slo.ts
  • src/lib/rag-cache.ts
  • src/lib/rag.ts
  • supabase/migrations/20260713201542_consolidate_rag_response_cache_retention.sql
  • tests/answer-slo.test.ts
  • tests/privacy-ui.test.ts
  • tests/rag-answer-fallback.test.ts
  • tests/rag-query-concurrency.test.ts
  • tests/rag-shared-cache.test.ts
  • tests/supabase-schema.test.ts

Comment thread docs/openai-cross-border-basis.md Outdated
Track generation fallbacks separately from intentional extractive answers so healthy source-only traffic does not page the provider-health SLO.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 07cac8f4e0

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread docs/privacy-impact-assessment.md Outdated

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a2eb6db0ef

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/lib/observability/answer-slo.ts Outdated
@BigSimmo
BigSimmo merged commit d36b75b into main Jul 13, 2026
20 checks passed
@BigSimmo
BigSimmo deleted the codex/rag-performance-followups branch July 14, 2026 11: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