Skip to content

fix(ai): 법령 RAG 로컬 검색 보완 - #35

Merged
HOKAGO-MEMORIES merged 3 commits into
developfrom
fix/f3-local-rag-fallback
Jun 23, 2026
Merged

fix(ai): 법령 RAG 로컬 검색 보완#35
HOKAGO-MEMORIES merged 3 commits into
developfrom
fix/f3-local-rag-fallback

Conversation

@HOKAGO-MEMORIES

@HOKAGO-MEMORIES HOKAGO-MEMORIES commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

변경 내용

  • Supabase PostgreSQL 포트가 막힌 로컬 환경에서 backend-ai 법령 RAG 검색이 실패하지 않도록 REST fallback을 추가했습니다.
  • REST fallback은 기존 pgvector SQL 검색 실패 시 legal_document_chunks를 HTTPS로 조회하고 로컬 cosine similarity로 Top-K를 계산합니다.
  • 실제 한국어 질문이 LEGAL_CONSULT로 분류되도록 법률 상담 키워드를 보강했습니다.
  • 로컬 법령 원문/변환 파일과 실행 로그가 PR에 섞이지 않도록 .gitignore를 정리했습니다.

연결 이슈

closes #34

테스트

  • cd backend-ai && .\.venv\Scripts\python.exe -m pytest tests → 34 passed
  • �ackend-ai 직접 호출에서 LEGAL_CONSULT, legalCards=3, LLM 답변 생성 확인
  • Spring /api/v1/chat 브라우저 검증은 현재 네트워크의 Supabase PostgreSQL 포트 차단으로 미완료

참고

  • 로컬에서 Supabase pooler 6543 및 Gmail SMTP 587 포트가 차단되어 정상 인증/브라우저 전체 플로우는 확인하지 못했습니다.
  • F-3 아키텍처 경계는 유지했습니다: Frontend는 Spring만 호출하고, 법령 검색/LLM 처리는 backend-ai에 남아 있습니다.

Summary by CodeRabbit

  • New Features
    • Added Korean-language intent recognition for legal consultation and property search.
  • Improvements
    • Enhanced legal document retrieval by attempting direct database similarity search first, then automatically falling back to a REST-based similarity search when database connectivity fails (non-production).
  • Chores
    • Updated local ignore rules to exclude additional run log folders and data/legal/.
  • Tests
    • Expanded coverage for Korean intent examples and pgvector/REST fallback parsing and behavior, including production-mode propagation.

@coderabbitai

coderabbitai Bot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: dea56177-7e08-4228-a1b4-06093664f978

📥 Commits

Reviewing files that changed from the base of the PR and between ab4e546 and 0a9b0b2.

📒 Files selected for processing (2)
  • backend-ai/app/clients/supabase_client.py
  • backend-ai/tests/test_legal_retriever.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • backend-ai/tests/test_legal_retriever.py
  • backend-ai/app/clients/supabase_client.py

📝 Walkthrough

Walkthrough

Adds a two-tier similarity search strategy to SupabaseVectorClient that falls back from pgvector/Postgres to a REST-based implementation using httpx and Python-side cosine similarity when Postgres is unreachable. Separately, extends classify_message() with Korean-language keyword lists for LEGAL_CONSULT and PROPERTY_SEARCH intents. Both changes include tests. .gitignore gains data/legal/ and run-log exclusions.

Changes

Legal RAG REST Fallback & Korean Intent Classification

Layer / File(s) Summary
Korean keyword intent classification
backend-ai/app/graph/nodes/classify_intent.py, backend-ai/tests/test_agent_chat.py
Defines KOREAN_LEGAL_KEYWORDS and KOREAN_PROPERTY_KEYWORDS constant lists; adds two new branches in classify_message() returning Intent.LEGAL_CONSULT and Intent.PROPERTY_SEARCH on Korean keyword matches; adds test_classify_intent_korean_examples covering both intents.
Supabase pgvector→REST fallback search with helpers and tests
backend-ai/app/clients/supabase_client.py, backend-ai/tests/test_legal_retriever.py
Adds math, re, httpx imports and REST_PAGE_SIZE constant; wraps similarity_search_legal_documents in try/except psycopg.OperationalError dispatching to _similarity_search_legal_documents_rest; implements REST fetch via httpx with project-ref extraction, embedding parsing, cosine similarity computation, and top-k return; adds supabase_project_ref, parse_pgvector_value, parse_float_value, and cosine_similarity module-level helpers with dimension and norm checking; extends tests with parse_pgvector_value unit coverage, a full REST fallback integration test mocking Postgres failure, and a production-mode safety test ensuring the fallback does not suppress exceptions in production.
.gitignore artifact exclusions
.gitignore
Adds data/legal/ to the data-output ignore block and a new "Local run logs" section ignoring run-logs/ and .codex/run-logs/.

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant SupabaseVectorClient
  participant Postgres
  participant SupabaseREST as Supabase REST API

  Caller->>SupabaseVectorClient: similarity_search_legal_documents(query_embedding, top_k)
  SupabaseVectorClient->>Postgres: _similarity_search_legal_documents_pgvector()
  alt Postgres reachable
    Postgres-->>SupabaseVectorClient: ranked rows
    SupabaseVectorClient-->>Caller: top-k results
  else psycopg.OperationalError
    SupabaseVectorClient->>SupabaseVectorClient: supabase_project_ref(database_url)
    SupabaseVectorClient->>SupabaseREST: httpx.get /rest/v1/legal_document_chunks
    SupabaseREST-->>SupabaseVectorClient: rows with embedding strings
    SupabaseVectorClient->>SupabaseVectorClient: parse_pgvector_value + cosine_similarity per row
    SupabaseVectorClient-->>Caller: sorted top-k results
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • ssafy-salman/salmanhae#21: Introduced the original SupabaseVectorClient legal similarity-search logic that this PR extends with the pgvector→REST fallback path and helper utilities for embedding parsing and cosine similarity.

Poem

🐇 Hop, hop through the network fog,
When pgvector sleeps like a log,
REST swoops in with cosine grace,
Korean keywords find their place.
No secret files shall crowd the tree—
The rabbit keeps the repo clean and free! 🌿

🚥 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 The PR title 'fix(ai): 법령 RAG 로컬 검색 보완' directly addresses the main objective—adding local search fallback and improving Korean intent classification for legal RAG functionality.
Description check ✅ Passed The description provides clear details on changes, linked issue, test results, and architecture considerations. All required template sections are addressed with substantive content.
Linked Issues check ✅ Passed All three requirements from #34 are met: REST fallback for pgvector failures is implemented [supabase_client.py], Korean intent classification is enhanced [classify_intent.py], and .gitignore is updated to exclude local outputs.
Out of Scope Changes check ✅ Passed All changes are directly aligned with the linked issue objectives. No extraneous modifications unrelated to REST fallback, Korean intent classification, or .gitignore cleanup are present.

✏️ 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 fix/f3-local-rag-fallback

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

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

🤖 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 `@backend-ai/app/clients/supabase_client.py`:
- Around line 98-103: The hardcoded limit of 1000 rows in the params dictionary
of the Supabase REST query causes similarity scoring to be computed only on a
truncated subset, potentially missing true nearest neighbors if the
legal_document_chunks table has more rows. Remove the fixed "limit": "1000"
constraint and implement pagination logic to retrieve candidates in batches
before ranking them by similarity score, ensuring all relevant candidates are
considered for scoring. Apply this pagination approach consistently across all
similar REST fallback queries in the file, including the instances around lines
123-124.
- Around line 218-230: The parse_pgvector_value function can raise a ValueError
when converting malformed string items to float in the final return statement,
causing the entire search request to fail instead of gracefully skipping bad
values. Wrap the float conversion in a try-except block within the list
comprehension to catch ValueError exceptions and filter out malformed items that
cannot be converted to float, ensuring the function returns whatever valid float
values it can parse without aborting the request.

In `@backend-ai/tests/test_legal_retriever.py`:
- Around line 180-183: The test settings contain hardcoded credential-shaped
values for supabase_db_url and supabase_service_role_key which violates the
coding guideline requiring credentials to be managed through environment
variables. Replace the hardcoded string literals for supabase_db_url and
supabase_service_role_key with values sourced from environment-backed test
fixtures, such as using environment variable lookups or test configuration
providers, to ensure credentials are not embedded directly in the code.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: b95e047c-8a38-4885-8696-3c3df9907009

📥 Commits

Reviewing files that changed from the base of the PR and between 1c0142e and ddea200.

📒 Files selected for processing (5)
  • .gitignore
  • backend-ai/app/clients/supabase_client.py
  • backend-ai/app/graph/nodes/classify_intent.py
  • backend-ai/tests/test_agent_chat.py
  • backend-ai/tests/test_legal_retriever.py

Comment thread backend-ai/app/clients/supabase_client.py Outdated
Comment thread backend-ai/app/clients/supabase_client.py
Comment thread backend-ai/tests/test_legal_retriever.py Outdated

@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)
backend-ai/app/clients/supabase_client.py (1)

42-51: 🚀 Performance & Scalability | 🟠 Major

Fallback fires on every OperationalError, including transient production failures.

psycopg.OperationalError is broad—it covers transient connection drops, statement timeouts surfaced as connection resets, and pooler hiccups, not just the locally-blocked port 6543 this PR targets. When triggered in production, the REST path downloads the entire legal_document_chunks table page-by-page and computes cosine similarity in Python, causing large memory/latency spikes and silently masking a real database outage instead of failing fast.

The app_env setting already exists in config and could gate this behavior. Consider using it to restrict the REST fallback to local/dev environments only.

🤖 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 `@backend-ai/app/clients/supabase_client.py` around lines 42 - 51, The
try-except block in the similarity search fallback logic is too broad and
triggers the REST fallback for all `psycopg.OperationalError` exceptions in
production, causing unnecessary performance degradation and masking real
database outages. Restrict the REST fallback to only local and development
environments by checking the existing `app_env` configuration setting. Only
attempt to fallback to `_similarity_search_legal_documents_rest` when `app_env`
is not set to production, otherwise let the `psycopg.OperationalError` propagate
to fail fast in production environments.
🤖 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 `@backend-ai/app/clients/supabase_client.py`:
- Around line 42-51: The try-except block in the similarity search fallback
logic is too broad and triggers the REST fallback for all
`psycopg.OperationalError` exceptions in production, causing unnecessary
performance degradation and masking real database outages. Restrict the REST
fallback to only local and development environments by checking the existing
`app_env` configuration setting. Only attempt to fallback to
`_similarity_search_legal_documents_rest` when `app_env` is not set to
production, otherwise let the `psycopg.OperationalError` propagate to fail fast
in production environments.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: f76371c1-6ac9-49d4-b301-d877094b5467

📥 Commits

Reviewing files that changed from the base of the PR and between ddea200 and ab4e546.

📒 Files selected for processing (2)
  • backend-ai/app/clients/supabase_client.py
  • backend-ai/tests/test_legal_retriever.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend-ai/tests/test_legal_retriever.py

@HOKAGO-MEMORIES
HOKAGO-MEMORIES merged commit ac157bc into develop Jun 23, 2026
1 check passed
@HOKAGO-MEMORIES
HOKAGO-MEMORIES deleted the fix/f3-local-rag-fallback branch June 25, 2026 07:57
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.

[BUG][F-3] 법령 RAG 로컬 네트워크 fallback 및 의도 분류 보완

1 participant