Skip to content

fix(rag): restore live-validated retrieval order#915

Merged
BigSimmo merged 5 commits into
mainfrom
codex/restore-live-retrieval-order
Jul 19, 2026
Merged

fix(rag): restore live-validated retrieval order#915
BigSimmo merged 5 commits into
mainfrom
codex/restore-live-retrieval-order

Conversation

@BigSimmo

@BigSimmo BigSimmo commented Jul 19, 2026

Copy link
Copy Markdown
Owner

Summary

  • Restore the live-eval-proven hybrid retrieval order before final deduplication.
  • Keep deterministic/app-layer rank scores available for evidence ranking and telemetry.
  • Add a regression test proving unvalidated second-stage ordering cannot replace the released order.

Verification

  • npm run eval:rag:offline — 36 golden cases, 21 suites, 294 tests passed.
  • Focused ranking suite — 3 files, 32 tests passed.
  • npm run lint — passed.
  • Prettier and git diff --check — passed.
  • npm run verify:cheap — all guards plus 319 files / 2,894 tests passed before this two-file patch; the focused patch checks above passed afterward.
  • npm run verify:ui — production build plus 239/239 Playwright tests passed before this retrieval-only patch; UI verification not repeated because no UI, route, styling, or browser behavior changed.
  • npm run typecheck — pending the repository-wide heavyweight lock owned by an unrelated verify:pr-local run; hosted Build/CI also covers type safety.
  • npm run eval:retrieval:quality -- --fail-on-threshold — branch-scoped live canary 29678081433 is in progress on 8dedbfa06.
  • npm run eval:rag -- --limit 15 + npm run eval:quality -- --rag-only — the workflow runs its answer-quality subset after retrieval passes.
  • npm run check:production-readiness equivalent provider checks — Supabase project identity, migration history, live ACL/title-scope postconditions, security advisors, and performance advisors checked through the authorized Supabase MCP deployment workflow.

Risk and rollout

  • Risk: Final result ordering changes back to the last provider-eval-green hybrid order; risk is stale or lower-quality evidence if live corpus behavior differs.
  • Rollback: Revert commit 8dedbfa06; no schema or production-data rollback is required.
  • Provider or production effects: Authorized live Supabase verification and GitHub/OpenAI canary evaluation only. No production data was changed by this PR.
  • Rollout gate: Do not merge unless the branch-scoped 36-case retrieval canary and answer-quality subset pass.

Clinical Governance Preflight

  • Source-backed claims still require linked source verification before clinical use
  • No patient-identifiable document workflow was introduced or expanded without explicit governance approval
  • Supabase target remains Clinical KB Database (sjrfecxgysukkwxsowpy)
  • Service-role keys and private document access remain server-only
  • Demo/synthetic content remains clearly separated from real clinical sources
  • Source metadata, review status, and outdated/unknown-source behavior remain conservative
  • Deployment classification/TGA SaMD impact was checked when clinical decision-support behavior changed
    • Result: this restores the last live-eval-green evidence order and adds no new clinical recommendation behavior.

Notes

  • Fresh main canary 29677244606 reproduced four deterministic failures: clozapine ANC threshold, patient safety plan, lithium monitoring, and alcohol CIWA threshold.
  • The same metrics and cases failed in the preceding scheduled run, while the last pre-ranking-change scheduled canary was green.

Summary by CodeRabbit

  • Bug Fixes
    • Standardized search result ordering to consistently follow the released live-evaluation ranking across reranking and telemetry, including deterministic deduping behavior.
    • Improved deterministic tie-breaking in answer evidence ranking by using rankScore from score explanations as a final fallback.
  • Tests
    • Added coverage to ensure released ordering remains correct after second-stage reranking when duplicates are present.
    • Added coverage to verify answer evidence tie-break behavior matches expectations when evidence signals are equal.

@supabase

supabase Bot commented Jul 19, 2026

Copy link
Copy Markdown

This pull request has been ignored for the connected project sjrfecxgysukkwxsowpy because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

@coderabbitai

coderabbitai Bot commented Jul 19, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds deterministic released search-result stabilization before telemetry processing and uses rankScore as a final answer-evidence tie-breaker. Tests cover duplicate selection, result ordering, telemetry preparation, and equal-signal answer ranking.

Changes

Ranking consistency

Layer / File(s) Summary
Released ordering helper
src/lib/rag.ts
Exports stabilizeReleasedSearchOrder, which deduplicates results in place while selecting the strongest duplicate using ordered score and id tie-breakers.
Telemetry integration and regression validation
src/lib/rag.ts, tests/rag-second-stage-ranking.test.ts
Stabilizes results before telemetry deduplication and verifies that second-stage reranking retains the strongest duplicate.
Answer ranking tie-breaking
src/lib/answer-ranking.ts, tests/answer-ranking.test.ts
Uses descending score_explanation.rankScore after other ranking signals and verifies equal final chunk scores for tied results.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

  • BigSimmo/Database#901: Both changes modify search-result ordering and telemetry behavior in src/lib/rag.ts.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: restoring the validated retrieval order in RAG.
Description check ✅ Passed The description follows the required template with Summary, Verification, Risk and rollout, Clinical Governance Preflight, and Notes sections.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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/restore-live-retrieval-order

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

@github-actions

Copy link
Copy Markdown

CI triage

CI failed on this PR. Automated classification of the 2 failed job(s):

  • Unit coverageneeds investigation: inspect the failing step and uploaded diagnostics; rerun only after classifying the cause.
  • PR requiredneeds investigation: inspect the failing step and uploaded diagnostics; rerun only after classifying the cause.

Compared with main CI run #3531 (success).

Classification is evidence routing, not permission to ignore a failure. Exact quarantined Playwright identities remain governed by the flake ledger.

@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: 8dedbfa060

ℹ️ 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/rag.ts
@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 (1)
tests/rag-second-stage-ranking.test.ts (1)

140-180: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Cover the changed telemetry path, not only the helper.

This test calls stabilizeReleasedSearchOrder directly, so it will still pass if the production call in src/lib/rag.ts, Line 590 is removed or moved after deduplication. Add duplicate-ID fixtures and drive the public telemetry path, asserting the retained result and top_score/second_top_score.

As per coding guidelines, retrieval changes require realistic failure-path verification and focused tests proving the changed behavior.

🤖 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 `@tests/rag-second-stage-ranking.test.ts` around lines 140 - 180, The test
currently validates stabilizeReleasedSearchOrder directly instead of the
production telemetry flow. Extend the test around applySecondStageRerankIfNeeded
with duplicate-ID fixtures, exercise the public path that invokes stabilization
and deduplication, and assert the retained result plus telemetry top_score and
second_top_score values. Ensure the test would fail if the production
stabilization call is removed or moved after deduplication.

Source: Coding guidelines

🤖 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 `@src/lib/rag.ts`:
- Line 569: Replace the locale-dependent ID comparison in the result comparator
with deterministic plain string ordering using < and >, while preserving the
existing equal-score tie-breaker behavior and return ordering.

---

Nitpick comments:
In `@tests/rag-second-stage-ranking.test.ts`:
- Around line 140-180: The test currently validates stabilizeReleasedSearchOrder
directly instead of the production telemetry flow. Extend the test around
applySecondStageRerankIfNeeded with duplicate-ID fixtures, exercise the public
path that invokes stabilization and deduplication, and assert the retained
result plus telemetry top_score and second_top_score values. Ensure the test
would fail if the production stabilization call is removed or moved after
deduplication.
🪄 Autofix (Beta)

❌ Autofix failed (check again to retry)

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: 82f24383-9a14-4ded-be2c-616119c7155c

📥 Commits

Reviewing files that changed from the base of the PR and between 01040d2 and 8dedbfa.

📒 Files selected for processing (2)
  • src/lib/rag.ts
  • tests/rag-second-stage-ranking.test.ts

Comment thread src/lib/rag.ts

@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: 2f8e6416f1

ℹ️ 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/rag.ts
@coderabbitai

coderabbitai Bot commented Jul 19, 2026

Copy link
Copy Markdown
Contributor

Note

Autofix is a beta feature. Expect some limitations and changes as we gather feedback and continue to improve it.

⚠️ Branch updated during autofix.

The branch was updated while autofix was in progress. Please try again.

auto-merge was automatically disabled July 19, 2026 07:41

Head branch was pushed to by a user without write access

@BigSimmo
BigSimmo enabled auto-merge (squash) July 19, 2026 07:42

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
tests/rag-second-stage-ranking.test.ts (1)

140-187: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Cover the production telemetry path, not only the helper sequence.

This test calls stabilizeReleasedSearchOrder directly at Line 183, so it can pass even if the real telemetry pipeline omits stabilization or runs it after deduplication—the behavior this PR is meant to protect. Add an assertion around the production telemetry-processing entry point, preserving the stronger duplicate through that path.

As per coding guidelines, retrieval changes must verify realistic failure paths and add focused tests for changed behavior.

🤖 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 `@tests/rag-second-stage-ranking.test.ts` around lines 140 - 187, Extend the
test to exercise the production telemetry-processing entry point that normally
handles the results, rather than relying only on direct calls to
applySecondStageRerankIfNeeded and stabilizeReleasedSearchOrder. Assert that
this pipeline preserves the stronger released-hybrid duplicate and produces the
expected distinct order, while keeping the existing helper-level assertions for
focused coverage.

Source: Coding guidelines

🤖 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.

Outside diff comments:
In `@tests/rag-second-stage-ranking.test.ts`:
- Around line 140-187: Extend the test to exercise the production
telemetry-processing entry point that normally handles the results, rather than
relying only on direct calls to applySecondStageRerankIfNeeded and
stabilizeReleasedSearchOrder. Assert that this pipeline preserves the stronger
released-hybrid duplicate and produces the expected distinct order, while
keeping the existing helper-level assertions for focused coverage.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: d445d8f5-86c6-4575-8aaf-bfc93a4ec6eb

📥 Commits

Reviewing files that changed from the base of the PR and between a18b08e and c4eb3ef.

📒 Files selected for processing (2)
  • src/lib/rag.ts
  • tests/rag-second-stage-ranking.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/lib/rag.ts

@BigSimmo
BigSimmo merged commit cac3fc2 into main Jul 19, 2026
26 checks passed
@BigSimmo
BigSimmo deleted the codex/restore-live-retrieval-order branch July 19, 2026 07:43
Copilot stopped work on behalf of BigSimmo due to an error July 19, 2026 07:44
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