Skip to content

fix(back): wire DATABASE_URL through to the RAG retrieval path (WO-06) - #124

Merged
sergi-torres merged 1 commit into
mainfrom
fix/wo-06-rag-database-url
Jul 28, 2026
Merged

fix(back): wire DATABASE_URL through to the RAG retrieval path (WO-06)#124
sergi-torres merged 1 commit into
mainfrom
fix/wo-06-rag-database-url

Conversation

@sergi-torres

Copy link
Copy Markdown
Owner

Closes #87. Rama rescatada: existía sin PR y con ~10 PRs de Sprint 3 por delante. Rebasada sobre main, no mergeada (un merge habría revertido medio Sprint 3).

El defecto

La ruta llamaba a orchestrate(...) sin database_url. La cadena completa:

  1. generator.py llamaba a retrieve_top_k(..., database_url=None).
  2. autoria_ai/db.py caía a os.environ["DATABASE_URL"].
  3. El backend no cargaba .env en ningún punto.
  4. El KeyError resultante lo tragaba el except Exception del generador.

Resultado: cada generación corría con cero pasajes RAG y emitía un Passport con rag_sources: [], en silencio, con solo un warning en el log. La "R" de RAG no existía en el producto.

El arreglo

  • app/config.py carga el .env de la raíz con override=False — la variable inyectada por la plataforma siempre gana, así que en Railway/Vercel es un no-op. La ausencia de python-dotenv se degrada con warning en vez de tumbar /health.
  • to_asyncpg_dsn() traduce en la frontera: .env documenta postgresql:// (lo que da Supabase y lo que esperan los scripts de siembra con psycopg2), pero create_async_engine lo rechaza sin driver. Se traduce en el backend en vez de romper cualquiera de los dos contratos.
  • La ruta pasa database_url=settings.database_url explícitamente.

Verificación

pytest backend/tests -q   -> 1 failed, 113 passed

El único fallo es test_generate_live_watsonx, que apunta al ibm/granite-3-8b-instruct retirado upstream — ajeno a esta rama, en curso en el PR #120.

Hallazgo destapado al verificar esto de punta a punta

Con el RAG por fin activo, orchestrate contra Supabase + Watsonx reales falló de forma intermitente: la rama condicionada agota el timeout duro de 8 s unas veces sí y otras no. La causa está medida y corregida en el PR #123 (el tope de salida se ignoraba y luego 512 tokens no cabían en el presupuesto de latencia). Los dos PRs se necesitan mutuamente para que /api/generate sea fiable: este pone los pasajes, aquel evita el 503.

🤖 Generated with Claude Code

Every generation ran without RAG passages: the system prompt went out with
"(no example passages provided)" and the passport carried rag_sources: [],
while the request still returned 200 (issue #87 / WO-06).

Two independent breaks were masking each other:

* The backend never read `.env`, despite README/CONTRIBUTING/DEPLOYMENT all
  instructing developers to create one. app.config now loads the repo-root
  `.env` on import, which is enough for the whole process because every
  entry point reaches configuration through that module.
* `routes/generate.py` never forwarded `database_url` to `orchestrate()`, so
  `autoria_ai.db` fell back to `os.environ["DATABASE_URL"]` and the resulting
  KeyError was swallowed by generator.py's `except Exception` — turning a
  configuration error into a per-request warning.

`.env` is loaded with `override=False`: Railway and Vercel inject the real
secrets into the process environment, and a stale `.env` shipped in an image
must never outrank them.

DATABASE_URL is normalised to the `postgresql+asyncpg://` form in
app.config.to_asyncpg_dsn. `.env.example` documents the plain `postgresql://`
scheme (what Supabase hands out, what the psycopg2 seeding scripts consume)
but SQLAlchemy's create_async_engine rejects a driver-less URL, so the backend
translates at the boundary — the same rule, in the same direction, as
scripts/seed_corpus.py:to_asyncpg_url. `ai_pipeline/autoria_ai/db.py` is
untouched; its contract was already correct.

A missing DATABASE_URL is now reported once, explicitly, at import, instead of
surfacing as a generic "RAG retrieval failed" warning on every generation.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@vercel

vercel Bot commented Jul 28, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
author-ai Ready Ready Preview, Comment Jul 28, 2026 9:31pm

@sergi-torres
sergi-torres merged commit c34d815 into main Jul 28, 2026
8 checks passed
@sergi-torres
sergi-torres deleted the fix/wo-06-rag-database-url branch July 28, 2026 21:49
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.

[backend] WO-06 — Cablear DATABASE_URL hasta el RAG y cargar .env en el backend

1 participant