Skip to content

Require strict OpenRAG retrieval by default; add verifier, health endpoint, and recommender support#911

Merged
Smartappli merged 2 commits into
masterfrom
verifier-l-utilisation-complete-de-openrag
May 11, 2026
Merged

Require strict OpenRAG retrieval by default; add verifier, health endpoint, and recommender support#911
Smartappli merged 2 commits into
masterfrom
verifier-l-utilisation-complete-de-openrag

Conversation

@Smartappli
Copy link
Copy Markdown
Owner

@Smartappli Smartappli commented May 11, 2026

Motivation

  • Prefer strict OpenRAG retrieval by default and fail fast when the runtime is unavailable to avoid returning ungrounded recommendations.
  • Provide a lightweight runtime verifier and CLI entrypoint hook to allow preflight checks at container start.
  • Surface OpenRAG readiness to ops via an authenticated staff-only HTTP health endpoint.
  • Simplify FARM package reporting and update dependency references for Flower integration.

Description

  • Add RAG.verify_openrag CLI and module to perform machine-readable and human-readable OpenRAG readiness checks and return POSIX exit codes (new verify-openrag script in pyproject.toml).
  • Add strict-mode handling in the recommender: introduce OpenRAGRuntimeUnavailableError, _safe_retrieve_strict, _resolve_strict_openrag, and a strict_openrag argument to recommend_models_for_query that defaults from RAG_STRICT_OPENRAG env var.
  • Update web views and routing to call recommend_models_for_query(..., strict_openrag=True), return 503 on strict retrieval failures, and expose a new GET /api/rag/health/ staff-only endpoint that returns ready and status flags.
  • Add entrypoint preflight when RAG_VERIFY_ON_START=1 to run the OpenRAG readiness check before migrations in entrypoint.sh.
  • Add documentation RAG/OPENRAG_INTEGRATION.md describing environment variables, strictness policy, verification commands, and health endpoint behavior.
  • Add and update tests: new RAG/tests/test_recommender_strict.py, extended RAG/tests/test_healthcheck.py, updated website tests to assert strict behavior and 503 handling, and new FARM/tests/test_info.py for _safe_version behavior.
  • Replace Syft-related references in FARM with Flower (flwr) and update FARM/info.py to report flwr version safely and update FARM/pyproject.toml dependency.

Testing

  • Ran pytest on the changed modules, including RAG.tests.test_healthcheck, RAG.tests.test_recommender_strict, website recommendation/health tests, and FARM.tests.test_info, and the test cases completed successfully.
  • Executed the new verifier CLI manually via verify-openrag and python -m RAG.verify_openrag to confirm output format and exit codes during local validation.
  • Exercised the API endpoints in unit tests to confirm recommend returns 200 on success and 503 when strict OpenRAG retrieval errors are raised, and the rag/health endpoint enforces authentication and staff access.

Codex Task

Summary by CodeRabbit

Release Notes

  • New Features

    • Added strict OpenRAG retrieval mode with configurable fallback behavior.
    • Introduced /api/rag/health/ endpoint to monitor OpenRAG runtime status (staff-only access).
    • Added verify-openrag command-line tool for OpenRAG integration verification.
    • API now returns HTTP 503 when OpenRAG runtime is unavailable in strict mode.
  • Documentation

    • Added OpenRAG integration guide with environment variables and verification commands.
  • Chores

    • Updated FARM module to use Flower 1.29.0 package for federated learning orchestration.

Review Change Stack

Comment thread AIMER-ROOT/website/views.py Fixed
@codacy-production
Copy link
Copy Markdown

codacy-production Bot commented May 11, 2026

Not up to standards ⛔

🔴 Issues 4 high · 1 minor

Alerts:
⚠ 5 issues (≤ 0 issues of at least minor severity)

Results:
5 new issues

Category Results
Documentation 1 minor
Security 4 high

View in Codacy

🟢 Metrics 0 complexity

Metric Results
Complexity 0

View in Codacy

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

Copy link
Copy Markdown

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

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: d67401389d

ℹ️ 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".

payload = recommend_models_for_query(
query=query,
top_k=top_k,
strict_openrag=True,
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Honor RAG_STRICT_OPENRAG in recommendation view

Passing strict_openrag=True unconditionally makes the RAG_STRICT_OPENRAG environment toggle ineffective for the main HTTP recommendation path, so deployments that set RAG_STRICT_OPENRAG=0 for fallback behavior will still return 503 whenever OpenRAG is unavailable. This turns the new strictness setting into dead configuration for API consumers and can break non-strict runtime scenarios.

Useful? React with 👍 / 👎.

@patch("website.views.recommend_models_for_query")
def test_recommendation_api_returns_503_when_openrag_unavailable(self, mock_recommend) -> None:
"""Ensure runtime retrieval errors are surfaced as HTTP 503."""
mock_recommend.side_effect = OpenRAGRuntimeUnavailableError("OpenRAG retrieval is required")
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Import OpenRAGRuntimeUnavailableError in API tests

This test references OpenRAGRuntimeUnavailableError without importing it, so executing the test raises NameError before the view behavior is asserted. As written, the new 503 regression coverage is broken and will fail when this test case runs.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a strict OpenRAG retrieval mode that prevents silent fallbacks when the retrieval runtime is unavailable, returning a 503 error instead. It adds a verification script, a staff-only health API, and updates the FARM module to use the flwr package directly. Feedback suggests removing the hardcoded strict mode in the recommendation view to honor environment configurations and consolidating dependency validation logic to reduce maintenance overhead.

payload = recommend_models_for_query(
query=query,
top_k=top_k,
strict_openrag=True,
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The strict_openrag=True argument is hardcoded here, which overrides the RAG_STRICT_OPENRAG environment variable. This prevents the "Optional dev fallback" (RAG_STRICT_OPENRAG=0) mentioned in the documentation (OPENRAG_INTEGRATION.md) from working for the web API. It is better to pass None (or omit the argument) to allow the recommender to resolve the strictness policy from the environment, while still defaulting to strict mode as intended.

Suggested change
strict_openrag=True,
strict_openrag=None,

Comment on lines +18 to +24
REQUIRED_KEYS = (
"openrag_installed",
"langchain_ollama_installed",
"langchain_core_installed",
"dotenv_installed",
"openrag_endpoint_set",
)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The REQUIRED_KEYS tuple and the manual check in runtime_status (line 30) duplicate the validation logic already defined in RAG.healthcheck.is_rag_runtime_ready. This duplication increases maintenance overhead if the set of required dependencies or configuration keys changes. Consider reusing is_rag_runtime_ready() to determine the ready flag.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 11, 2026

Walkthrough

This PR introduces strict-mode OpenRAG integration with configurable runtime verification and separate Flower dependency migration in FARM. The main cohort adds error handling when OpenRAG retrieval runtime is unavailable, supplies a health endpoint and CLI verification tool, and updates the recommendation API to fail-fast in strict mode. The secondary cohort completes FARM's migration from Syft to Flower 1.29.0.

Changes

OpenRAG Strict Mode Integration

Layer / File(s) Summary
Exception and Error Handling Contract
AIMER-ROOT/RAG/recommender.py
Introduces OpenRAGRuntimeUnavailableError to represent strict-mode retrieval failures.
Core Retrieval Logic and Mode Resolution
AIMER-ROOT/RAG/recommender.py
Adds _safe_retrieve_strict() wrapper that raises error on fallback; adds _resolve_strict_openrag() to centralize strict-mode decision from argument or RAG_STRICT_OPENRAG environment variable.
Recommender Public API Update
AIMER-ROOT/RAG/recommender.py
Extends recommend_models_for_query() with strict_openrag parameter and routes to strict or non-strict retrieval based on resolved setting.
Verification Module and Status Reporting
AIMER-ROOT/RAG/verify_openrag.py
New module with RuntimeStatusPayload type, runtime_status() computation, format_report() human-readable output, and main() CLI entry point.
Website API Endpoints
AIMER-ROOT/website/views.py
RagRecommendationView.get() now calls recommend_models_for_query(..., strict_openrag=True) and catches OpenRAGRuntimeUnavailableError to return HTTP 503; new RagRuntimeHealthView endpoint with staff-only authentication returns runtime health status.
URL Routing Configuration
AIMER-ROOT/website/urls.py
Adds /api/rag/health route mapping to RagRuntimeHealthView; reformats imports to multiline.
Script Entry Point and Package Config
AIMER-ROOT/pyproject.toml
Declares verify-openrag CLI script in [project.scripts] pointing to RAG.verify_openrag:main.
Startup Verification Integration
AIMER-ROOT/entrypoint.sh
Adds optional RAG_VERIFY_ON_START=1 environment variable check to run verify-openrag during container startup.
OpenRAG Integration Documentation
AIMER-ROOT/RAG/OPENRAG_INTEGRATION.md
Comprehensive guide covering environment variables, strict-mode policy, verification commands with exit codes, smoke test examples, startup preflight, and health endpoint access control and payload schema.
Verification and Strict Mode Tests
AIMER-ROOT/RAG/tests/test_recommender_strict.py, AIMER-ROOT/RAG/tests/test_healthcheck.py, AIMER-ROOT/website/tests.py
Tests for strict-mode resolution, retrieval error handling, verification module output, health endpoint access control, and API 503 responses.

FARM Flower Dependency Migration

Layer / File(s) Summary
Flower Dependency Declaration
FARM/pyproject.toml
Adds flwr==1.29.0 as active dependency, replacing commented-out syft-flwr==0.5.1.
Version Reporting Implementation
FARM/info.py
New _safe_version() helper uses importlib.metadata to fetch package version with "NOT_INSTALLED" fallback; main() reports Flower version instead of Syft.
FARM Documentation Update
FARM/README.md
Replaces "Flower + Syft" with Flower-only orchestration; removes Syft section; adds "Dépendances clés" listing flwr==1.29.0, django, granian with uv.lock regeneration guidance.
Version Helper Tests
FARM/tests/test_info.py
Tests _safe_version() fallback when importlib.metadata.version raises PackageNotFoundError, asserting deterministic "NOT_INSTALLED" return.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • Smartappli/AIMER#907: Contains identical strict OpenRAG logic (exception, retrieval wrappers, verify_openrag module) and matching API/test updates.
  • Smartappli/AIMER#908: Introduces the same strict OpenRAG feature set including exception, mode resolution, verification module, health endpoint, and test coverage.

Suggested labels

📒 Documentation

Poem

🐰 OpenRAG now stands strict and tall,
Health checks blooming in the hall,
Flower picks up Syft's old crown,
Verification marches through the town!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 68.18% 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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title accurately summarizes the primary changes: requiring strict OpenRAG retrieval by default and adding supporting infrastructure (verifier, health endpoint, recommender support).
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 verifier-l-utilisation-complete-de-openrag
⚔️ Resolve merge conflicts
  • Resolve merge conflict in branch verifier-l-utilisation-complete-de-openrag

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.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

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

⚠️ Outside diff range comments (1)
AIMER-ROOT/RAG/recommender.py (1)

626-628: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Strict mode still emits ungrounded fallback recommendations.

Line 626–628 always returns _fallback_recommendations(...) when scored is empty, even with resolved_strict=True. That reintroduces non-grounded recommendations in strict mode.

🐛 Proposed fix
     if not scored:
-        recommendations = _fallback_recommendations(catalog, profile, top_k)
+        if resolved_strict:
+            raise OpenRAGRuntimeUnavailableError(
+                "Strict OpenRAG mode enabled, but no grounded evidence matched the query.",
+            )
+        recommendations = _fallback_recommendations(catalog, profile, top_k)
🤖 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 `@AIMER-ROOT/RAG/recommender.py` around lines 626 - 628, The code currently
calls _fallback_recommendations(catalog, profile, top_k) whenever scored is
empty, which reintroduces ungrounded recommendations even when resolved_strict
is True; update the branch around scored to first check resolved_strict and, if
resolved_strict is True and scored is empty, set recommendations to an empty
list (or otherwise return no recommendations) instead of calling
_fallback_recommendations; modify the logic in the function containing the
scored check (referencing variables scored, resolved_strict, recommendations,
and the _fallback_recommendations call) so fallback is only used when not in
strict mode.
♻️ Duplicate comments (1)
AIMER-ROOT/website/views.py (1)

233-234: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Sanitize exception message to prevent information disclosure.

Directly exposing str(exc) in the API response can leak implementation details, stack traces, or internal paths that aid reconnaissance. Return a generic message instead.

🔒 Proposed fix to use a generic error message
         except OpenRAGRuntimeUnavailableError as exc:
-            return JsonResponse({"error": str(exc)}, status=503)
+            return JsonResponse(
+                {"error": "RAG retrieval service is currently unavailable"},
+                status=503,
+            )

As per coding guidelines, the CodeQL static analysis tool flagged this as "Information exposure through an exception" at line 234.

🤖 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 `@AIMER-ROOT/website/views.py` around lines 233 - 234, The except block that
returns JsonResponse({"error": str(exc)}, status=503) exposes internal exception
details (OpenRAGRuntimeUnavailableError); change this to return a generic
message like JsonResponse({"error":"Service temporarily unavailable"},
status=503) and log the real exception server-side (e.g., logger.exception or
logger.error with the exc) inside the same except branch so internal details are
not sent to clients; update the handler in website/views.py where
OpenRAGRuntimeUnavailableError is caught and ensure JsonResponse is used only
with the generic message.
🧹 Nitpick comments (4)
FARM/tests/test_info.py (1)

20-21: ⚡ Quick win

Consider patching at the importlib.metadata level for robustness.

The current monkeypatch.setattr("info.version", fake_version) patches the imported version reference in the info module after it has been imported. While this works, patching at the source (importlib.metadata.version) is more explicit and robust.

♻️ Alternative patch location
     def fake_version(_package_name: str) -> str:
         raise PackageNotFoundError
 
-    monkeypatch.setattr("info.version", fake_version)
+    monkeypatch.setattr("importlib.metadata.version", fake_version)
     assert _safe_version("flwr") == "NOT_INSTALLED"

This patches the function at its source rather than at the import site, making the test more resilient to refactoring.

Note: The Codacy warning about assert is a false positive—pytest uses assert statements natively for test assertions, and they are not removed in test contexts.

🤖 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 `@FARM/tests/test_info.py` around lines 20 - 21, Replace the patch location to
target the origin of the version lookup: instead of
monkeypatch.setattr("info.version", fake_version) patch
importlib.metadata.version (e.g., monkeypatch.setattr("importlib.metadata",
"version", fake_version)) so the test fakes the source used by info.version;
update the test around the _safe_version("flwr") assertion to use this new
monkeypatch target, ensuring the mocked function name is exactly
importlib.metadata.version and restores correctly after the test.
AIMER-ROOT/RAG/verify_openrag.py (1)

53-57: ⚡ Quick win

Unify report and exit-code readiness source.

On Line 55 and Line 57, readiness is evaluated twice through different paths. This can make the printed runtime_ready disagree with the process exit code in transient conditions. Use one computed payload for both report rendering and return code.

♻️ Proposed refactor
-def format_report() -> str:
+def format_report(payload: RuntimeStatusPayload | None = None) -> str:
     """Build a human-readable OpenRAG readiness report."""
-    payload = runtime_status()
+    payload = runtime_status() if payload is None else payload
     status = payload["status"]
@@
 def main() -> int:
     """Print readiness report and return shell status code."""
-    report = format_report()
+    payload = runtime_status()
+    report = format_report(payload)
     print(report)
-    return 0 if is_rag_runtime_ready() else 1
+    return 0 if payload["ready"] else 1
🤖 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 `@AIMER-ROOT/RAG/verify_openrag.py` around lines 53 - 57, The main() function
currently calls format_report() which computes readiness and separately calls
is_rag_runtime_ready() for the exit code, risking a mismatch; modify main() to
compute the readiness once (e.g., call is_rag_runtime_ready() and store the
result in a local variable like runtime_ready), pass that same value into
format_report() or into whatever payload format_report() needs, print the
resulting report, and use the stored runtime_ready to determine the return value
so both printed report and exit code come from the same computed readiness.
AIMER-ROOT/RAG/tests/test_recommender_strict.py (1)

12-18: ⚡ Quick win

Isolate strict-mode test from catalog/index side effects.

This test targets strict retrieval fallback, but recommend_models_for_query(...) still executes catalog/profile prep first. Mock those dependencies too, so failures stay scoped to strict-mode behavior.

♻️ Proposed test hardening
 from RAG.recommender import OpenRAGRuntimeUnavailableError, recommend_models_for_query
@@
     monkeypatch.setattr("RAG.recommender._safe_retrieve", fake_retrieve)
+    monkeypatch.setattr("RAG.recommender._build_model_catalog", lambda **_: {})
 
     try:
         recommend_models_for_query(
🤖 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 `@AIMER-ROOT/RAG/tests/test_recommender_strict.py` around lines 12 - 18, The
test currently only stubs RAG.recommender._safe_retrieve but still runs
catalog/profile preparation inside recommend_models_for_query, so side-effects
from catalog/index setup can mask strict-mode behavior; extend the monkeypatch
to stub the catalog and profile prep functions used by
recommend_models_for_query (e.g., the catalog loader/index builder/profile
preparer functions called within recommend_models_for_query) to return minimal
no-op values or mocks before calling recommend_models_for_query, so the test
isolates strict_openrag behavior and any failure is scoped to _safe_retrieve
fallback.
AIMER-ROOT/website/views.py (1)

242-247: 💤 Low value

Add method docstring.

The get method lacks a docstring describing its purpose, parameters, and return value.

📝 Proposed docstring
     `@override`
     def get(
         self,
         request: HttpRequest,
         *args: object,
         **kwargs: object,
     ) -> JsonResponse:
+        """
+        Return OpenRAG runtime health status for staff users.
+
+        Returns:
+            JsonResponse: Health payload with ready flag and status details,
+                or error response for unauthorized access.
+
+        """
         del args, kwargs
🤖 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 `@AIMER-ROOT/website/views.py` around lines 242 - 247, Add a concise docstring
to the get method explaining its purpose, the parameters (request: HttpRequest,
*args, **kwargs) and the return type (JsonResponse); update the docstring inside
the get function definition in AIMER-ROOT/website/views.py (the get method) to
state what the endpoint does, what inputs it expects, and what the JsonResponse
contains so future readers and tools can understand its behavior.
🤖 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 `@AIMER-ROOT/website/tests.py`:
- Around line 594-606: The test
test_recommendation_api_returns_503_when_openrag_unavailable references
OpenRAGRuntimeUnavailableError but doesn't import it; add an import for
OpenRAGRuntimeUnavailableError at the top of the tests file (or alongside
existing related imports) so the symbol is defined when
test_recommendation_api_returns_503_when_openrag_unavailable is executed; ensure
the import comes from the module that defines OpenRAGRuntimeUnavailableError to
avoid import errors.

In `@FARM/tests/test_info.py`:
- Around line 9-11: Remove the sys.path manipulation and replace the top-of-file
import with a proper package import (e.g., import _safe_version from the package
module) so tests rely on normal package discovery; specifically, delete the
sys.path.append(...) line in FARM/tests/test_info.py and change the import "from
info import _safe_version" to a package-aware import such as "from FARM.info
import _safe_version" or a relative import "from ..info import _safe_version"
depending on how tests are executed and the test runner configuration.

---

Outside diff comments:
In `@AIMER-ROOT/RAG/recommender.py`:
- Around line 626-628: The code currently calls
_fallback_recommendations(catalog, profile, top_k) whenever scored is empty,
which reintroduces ungrounded recommendations even when resolved_strict is True;
update the branch around scored to first check resolved_strict and, if
resolved_strict is True and scored is empty, set recommendations to an empty
list (or otherwise return no recommendations) instead of calling
_fallback_recommendations; modify the logic in the function containing the
scored check (referencing variables scored, resolved_strict, recommendations,
and the _fallback_recommendations call) so fallback is only used when not in
strict mode.

---

Duplicate comments:
In `@AIMER-ROOT/website/views.py`:
- Around line 233-234: The except block that returns JsonResponse({"error":
str(exc)}, status=503) exposes internal exception details
(OpenRAGRuntimeUnavailableError); change this to return a generic message like
JsonResponse({"error":"Service temporarily unavailable"}, status=503) and log
the real exception server-side (e.g., logger.exception or logger.error with the
exc) inside the same except branch so internal details are not sent to clients;
update the handler in website/views.py where OpenRAGRuntimeUnavailableError is
caught and ensure JsonResponse is used only with the generic message.

---

Nitpick comments:
In `@AIMER-ROOT/RAG/tests/test_recommender_strict.py`:
- Around line 12-18: The test currently only stubs
RAG.recommender._safe_retrieve but still runs catalog/profile preparation inside
recommend_models_for_query, so side-effects from catalog/index setup can mask
strict-mode behavior; extend the monkeypatch to stub the catalog and profile
prep functions used by recommend_models_for_query (e.g., the catalog
loader/index builder/profile preparer functions called within
recommend_models_for_query) to return minimal no-op values or mocks before
calling recommend_models_for_query, so the test isolates strict_openrag behavior
and any failure is scoped to _safe_retrieve fallback.

In `@AIMER-ROOT/RAG/verify_openrag.py`:
- Around line 53-57: The main() function currently calls format_report() which
computes readiness and separately calls is_rag_runtime_ready() for the exit
code, risking a mismatch; modify main() to compute the readiness once (e.g.,
call is_rag_runtime_ready() and store the result in a local variable like
runtime_ready), pass that same value into format_report() or into whatever
payload format_report() needs, print the resulting report, and use the stored
runtime_ready to determine the return value so both printed report and exit code
come from the same computed readiness.

In `@AIMER-ROOT/website/views.py`:
- Around line 242-247: Add a concise docstring to the get method explaining its
purpose, the parameters (request: HttpRequest, *args, **kwargs) and the return
type (JsonResponse); update the docstring inside the get function definition in
AIMER-ROOT/website/views.py (the get method) to state what the endpoint does,
what inputs it expects, and what the JsonResponse contains so future readers and
tools can understand its behavior.

In `@FARM/tests/test_info.py`:
- Around line 20-21: Replace the patch location to target the origin of the
version lookup: instead of monkeypatch.setattr("info.version", fake_version)
patch importlib.metadata.version (e.g.,
monkeypatch.setattr("importlib.metadata", "version", fake_version)) so the test
fakes the source used by info.version; update the test around the
_safe_version("flwr") assertion to use this new monkeypatch target, ensuring the
mocked function name is exactly importlib.metadata.version and restores
correctly after the test.
🪄 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

Run ID: 8263e29a-902a-48ab-a96f-850a98f7ec8d

📥 Commits

Reviewing files that changed from the base of the PR and between a23b7e6 and d674013.

📒 Files selected for processing (14)
  • AIMER-ROOT/RAG/OPENRAG_INTEGRATION.md
  • AIMER-ROOT/RAG/recommender.py
  • AIMER-ROOT/RAG/tests/test_healthcheck.py
  • AIMER-ROOT/RAG/tests/test_recommender_strict.py
  • AIMER-ROOT/RAG/verify_openrag.py
  • AIMER-ROOT/entrypoint.sh
  • AIMER-ROOT/pyproject.toml
  • AIMER-ROOT/website/tests.py
  • AIMER-ROOT/website/urls.py
  • AIMER-ROOT/website/views.py
  • FARM/README.md
  • FARM/info.py
  • FARM/pyproject.toml
  • FARM/tests/test_info.py

Comment on lines +594 to +606
@patch("website.views.recommend_models_for_query")
def test_recommendation_api_returns_503_when_openrag_unavailable(self, mock_recommend) -> None:
"""Ensure runtime retrieval errors are surfaced as HTTP 503."""
mock_recommend.side_effect = OpenRAGRuntimeUnavailableError("OpenRAG retrieval is required")

response = self.client.get(
"/api/rag/recommend/",
{"q": "classification mri"},
)

self._check_equal(response.status_code, 503)
self._check("error" in response.json())

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.

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Missing import for OpenRAGRuntimeUnavailableError.

The test references OpenRAGRuntimeUnavailableError at line 597 but it is not imported. This will cause a NameError at runtime.

🔧 Proposed fix to add the missing import
 from RAG.omop import build_omop_metadata
-from RAG.recommender import recommend_models_for_query
+from RAG.recommender import OpenRAGRuntimeUnavailableError, recommend_models_for_query
 from RAG.timm_articles import (
🧰 Tools
🪛 GitHub Check: Codacy Static Code Analysis

[warning] 597-597: AIMER-ROOT/website/tests.py#L597
undefined name 'OpenRAGRuntimeUnavailableError' (F821)

🤖 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 `@AIMER-ROOT/website/tests.py` around lines 594 - 606, The test
test_recommendation_api_returns_503_when_openrag_unavailable references
OpenRAGRuntimeUnavailableError but doesn't import it; add an import for
OpenRAGRuntimeUnavailableError at the top of the tests file (or alongside
existing related imports) so the symbol is defined when
test_recommendation_api_returns_503_when_openrag_unavailable is executed; ensure
the import comes from the module that defines OpenRAGRuntimeUnavailableError to
avoid import errors.

Comment thread FARM/tests/test_info.py
Comment on lines +9 to +11
sys.path.append(str(Path(__file__).resolve().parents[1]))

from info import _safe_version
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.

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Refactor to use proper package imports.

Manipulating sys.path in tests is an anti-pattern that makes tests brittle and environment-dependent. Since this is part of the FARM package, use proper relative imports or configure your test environment to make the package discoverable.

♻️ Proposed refactor using proper imports
-from pathlib import Path
 import sys
 
-sys.path.append(str(Path(__file__).resolve().parents[1]))
-
-from info import _safe_version
+from FARM.info import _safe_version

Alternatively, if running tests from the FARM directory, ensure your test runner (pytest) is configured to discover the package properly rather than modifying sys.path at runtime.

🤖 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 `@FARM/tests/test_info.py` around lines 9 - 11, Remove the sys.path
manipulation and replace the top-of-file import with a proper package import
(e.g., import _safe_version from the package module) so tests rely on normal
package discovery; specifically, delete the sys.path.append(...) line in
FARM/tests/test_info.py and change the import "from info import _safe_version"
to a package-aware import such as "from FARM.info import _safe_version" or a
relative import "from ..info import _safe_version" depending on how tests are
executed and the test runner configuration.

@Smartappli Smartappli merged commit 2c3beff into master May 11, 2026
9 of 21 checks passed
@Smartappli Smartappli deleted the verifier-l-utilisation-complete-de-openrag branch May 11, 2026 21:02
from RAG.verify_openrag import runtime_status

payload = runtime_status()
assert set(payload.keys()) == {"ready", "status"}

payload = runtime_status()
assert set(payload.keys()) == {"ready", "status"}
assert isinstance(payload["ready"], bool)
payload = runtime_status()
assert set(payload.keys()) == {"ready", "status"}
assert isinstance(payload["ready"], bool)
assert isinstance(payload["status"], dict)
Comment thread FARM/tests/test_info.py
raise PackageNotFoundError

monkeypatch.setattr("info.version", fake_version)
assert _safe_version("flwr") == "NOT_INSTALLED"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants