Skip to content

[Feat] response_citations 저장 - ResponseCitationCommandService 구현 - #74

Merged
kangcheolung merged 5 commits into
developfrom
feature/73
Jul 28, 2026
Merged

[Feat] response_citations 저장 - ResponseCitationCommandService 구현#74
kangcheolung merged 5 commits into
developfrom
feature/73

Conversation

@kangcheolung

@kangcheolung kangcheolung commented Jul 28, 2026

Copy link
Copy Markdown
Member

🔍️ 작업 내용

✨ 상세 설명

RAG 블록 Issue 4 구현입니다. Issue 3(#71)에서 저장한 rag_responses가 실제로 어떤 chunk를 근거로 썼는지 response_citations에 구조화해서 저장합니다.

  • ResponseCitationRepository, ResponseCitationCommandService 신규 구현
  • Issue 1의 PromptBuilder가 사용한 것과 동일한 List<VectorSearchCandidate> 순서를 그대로 재사용해 citation_order/citation_label 부여 (별도 라벨 재계산 없음)
  • SearchResultCommandService.saveAll()과 동일하게 entityManager.getReference()로 불필요한 SELECT 없이 chunk FK 연결
  • search_result_id는 이번 이슈에서 채우지 않음(null) — SearchResultCommandService.saveAll()이 저장된 SearchResult를 반환하지 않아 이 시점에는 알 수 없음, Issue 5에서 채울 예정
  • ResponseCitation 엔티티 필드별 주석 보강

상세 설계 배경은 docs/design/kangcheolung-#73-response-citation-save.md 참고해주세요.

🛠️ 추후 리팩토링 및 고도화 계획

  • Issue 5: SearchResultCommandService.saveAll()List<SearchResult> 반환으로 바꿔서 search_result_id 채우기
  • Issue 5: RagFacadeSearchFacade/SearchController와 실제 연결

📸 스크린샷 (선택)

N/A

💬 리뷰 요구사항

  • search_result_id를 Issue 5로 미룬 판단이 적절한지
  • 클래스명을 이슈 설명의 "CitationService"에서 기존 컨벤션에 맞춰 ResponseCitationCommandService로 바꾼 것에 이견 없는지

Summary by CodeRabbit

  • 새 기능

    • AI 답변에 사용된 근거 자료를 인용 정보로 저장합니다.
    • 인용 순서와 [1], [2] 형식의 라벨을 자동으로 생성합니다.
    • 인용문, 페이지 번호, 관련도 점수를 함께 보존합니다.
    • 여러 근거 자료를 한 번에 처리할 수 있습니다.
  • 문서

    • 근거 자료 저장 흐름과 동작 사양, 예외 처리 기준을 문서화했습니다.
  • 테스트

    • 인용 순서, 라벨, 세부 정보 매핑 및 빈 근거 목록 처리를 검증했습니다.

citationOrder/citationLabel을 분리한 이유, quotedText/pageNo/relevanceScore가
각각 어떤 의미인지 필드별로 명시한다.
… (F-RAG-04)

PromptBuilder가 라벨을 매긴 것과 동일한 candidates 순서를 citation_order/
citation_label 근거로 재사용해 response_citations에 저장한다.
SearchResultCommandService.saveAll()과 동일하게 entityManager.getReference()로
불필요한 SELECT 없이 chunk FK를 연결한다.
search_result_id는 이번 이슈에서 채우지 않는다(null) — SearchResultCommandService.saveAll()이
저장된 SearchResult를 반환하지 않아 이 시점에는 알 수 없고, Issue 5에서 채운다.
정상 케이스(순서/라벨/텍스트/페이지/점수 저장, searchResult null 확인)와
빈 후보 리스트 케이스를 검증한다.
@coderabbitai

coderabbitai Bot commented Jul 28, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

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

Next review available in: 51 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: 3c93a59c-7e98-4cbe-a4dd-d2fa494182af

📥 Commits

Reviewing files that changed from the base of the PR and between 3a12167 and 9ca9857.

📒 Files selected for processing (1)
  • src/test/java/com/opensource/docgrid/domain/rag/service/command/ResponseCitationCommandServiceTest.java
📝 Walkthrough

Walkthrough

RAG 응답에 사용된 후보들을 ResponseCitation으로 변환해 저장하는 리포지토리와 커맨드 서비스가 추가되었습니다. 후보 순서, 라벨, 인용 필드 매핑 및 빈 목록 처리를 단위 테스트로 검증하고 설계 문서에 구현 범위와 후속 작업을 기록했습니다.

Changes

응답 인용 저장

Layer / File(s) Summary
인용 저장 계약 및 설계
docs/design/..., src/main/java/com/opensource/docgrid/domain/rag/entity/ResponseCitation.java
인용 순서·라벨과 후보 필드 매핑, search_result_id 미설정 범위, 빈 후보 처리 및 후속 연계 계획을 문서화하고 엔티티 필드 주석을 보강했습니다.
인용 저장 서비스 및 검증
src/main/java/com/opensource/docgrid/domain/rag/repository/ResponseCitationRepository.java, src/main/java/com/opensource/docgrid/domain/rag/service/command/ResponseCitationCommandService.java, src/test/java/com/opensource/docgrid/domain/rag/service/command/ResponseCitationCommandServiceTest.java
ResponseCitationRepositorysaveAll 서비스를 추가했습니다. 후보별 DocumentChunk 참조, 순서·라벨 및 필드 매핑 후 일괄 저장하며, 다중 후보와 빈 후보 동작을 테스트합니다.

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

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning #73의 핵심 요구인 chunk_id 외에 search_result_id FK 연결이 아직 구현되지 않아 요구사항을 모두 충족하지 못합니다. SearchResultCommandService.saveAll()가 저장 결과를 반환하도록 바꾸고, ResponseCitation 저장 시 search_result_id를 함께 매핑하세요.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed 제목이 response_citations 저장과 ResponseCitationCommandService 구현이라는 핵심 변경을 정확히 요약합니다.
Description check ✅ Passed 템플릿의 작업 내용, 상세 설명, 추후 계획, 리뷰 요구사항을 대부분 포함해 설명이 충분합니다.
Out of Scope Changes check ✅ Passed 추가된 설계 문서, 테스트, 주석은 citation 저장 기능과 직접 연관되어 있어 범위를 벗어난 변경으로 보이지 않습니다.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/73

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.

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
docs/design/kangcheolung-#73-response-citation-save.md (1)

143-150: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

저장 실패 시 예외 전파 계약을 정확히 문서화해 주세요.

ResponseCitationCommandService는 예외를 별도로 처리하지 않으므로 리포지토리/JPA 저장 실패가 호출자에게 전파될 수 있습니다. “예외를 던지지 않는다” 대신 “예외를 변환하지 않으며 저장 실패는 전파된다”는 식으로 실제 동작을 명시해야 합니다.

As per coding guidelines, 설계 문서는 에러 케이스를 문서화해야 합니다.

🤖 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/design/kangcheolung-`#73-response-citation-save.md around lines 143 -
150, Update the “에러 케이스 정리” section for ResponseCitationCommandService to state
that it does not transform or handle exceptions, and repository/JPA save
failures are propagated to the caller. Keep the existing empty-candidates and
multi-chunk behavior unchanged.

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/main/java/com/opensource/docgrid/domain/rag/repository/ResponseCitationRepository.java`:
- Around line 7-8: Document the ResponseCitationRepository interface with a
class-level Javadoc describing its role, responsibilities, and scope boundary as
the persistence repository for ResponseCitation entities, while keeping the
existing JpaRepository inheritance unchanged.

In
`@src/test/java/com/opensource/docgrid/domain/rag/service/command/ResponseCitationCommandServiceTest.java`:
- Around line 53-68: Strengthen the saveAll test by configuring
entityManager.getReference for each candidate to return distinct DocumentChunk
mocks, then assert each captured ResponseCitation from
responseCitationCommandService.saveAll has the corresponding chunk association.
Keep the existing citation field assertions and verify the expected chunk IDs
are passed to getReference.

---

Nitpick comments:
In `@docs/design/kangcheolung-`#73-response-citation-save.md:
- Around line 143-150: Update the “에러 케이스 정리” section for
ResponseCitationCommandService to state that it does not transform or handle
exceptions, and repository/JPA save failures are propagated to the caller. Keep
the existing empty-candidates and multi-chunk behavior 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: 31f9c033-c2c3-40d0-af4e-1b6389f420e5

📥 Commits

Reviewing files that changed from the base of the PR and between 1602454 and 3a12167.

📒 Files selected for processing (5)
  • docs/design/kangcheolung-#73-response-citation-save.md
  • src/main/java/com/opensource/docgrid/domain/rag/entity/ResponseCitation.java
  • src/main/java/com/opensource/docgrid/domain/rag/repository/ResponseCitationRepository.java
  • src/main/java/com/opensource/docgrid/domain/rag/service/command/ResponseCitationCommandService.java
  • src/test/java/com/opensource/docgrid/domain/rag/service/command/ResponseCitationCommandServiceTest.java

Comment on lines +7 to +8
public interface ResponseCitationRepository extends JpaRepository<ResponseCitation, Long> {
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

신규 저장소 인터페이스의 역할과 경계를 Javadoc으로 명시해 주세요.

As per coding guidelines, 새로 만든 인터페이스에는 역할·책임·경계를 설명하는 클래스 수준 주석이 필요합니다.

제안 변경
+/**
+ * ResponseCitation 엔티티의 영속화를 담당하는 저장소.
+ *
+ * 조회·저장 규칙은 Spring Data JPA에 위임하며 도메인 로직은 포함하지 않는다.
+ */
 public interface ResponseCitationRepository extends JpaRepository<ResponseCitation, Long> {
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public interface ResponseCitationRepository extends JpaRepository<ResponseCitation, Long> {
}
/**
* ResponseCitation 엔티티의 영속화를 담당하는 저장소.
*
* 조회·저장 규칙은 Spring Data JPA에 위임하며 도메인 로직은 포함하지 않는다.
*/
public interface ResponseCitationRepository extends JpaRepository<ResponseCitation, Long> {
}
🤖 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/main/java/com/opensource/docgrid/domain/rag/repository/ResponseCitationRepository.java`
around lines 7 - 8, Document the ResponseCitationRepository interface with a
class-level Javadoc describing its role, responsibilities, and scope boundary as
the persistence repository for ResponseCitation entities, while keeping the
existing JpaRepository inheritance unchanged.

Source: Coding guidelines

entityManager.getReference()가 항상 null을 반환하도록 mocking되어 있어
잘못된 chunkId가 전달돼도 테스트가 통과하던 문제를 수정한다. 후보별로
서로 다른 DocumentChunk mock을 반환하도록 하고, 저장된 citation의 chunk가
올바르게 매핑됐는지 검증을 추가한다.
@kangcheolung
kangcheolung merged commit 50da23e into develop Jul 28, 2026
1 check was pending
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.

[Feat] response_citations 저장

1 participant