Skip to content

[Feat] 기본 임베딩 모델 등록 및 조회 - #11

Merged
Gimini-3 merged 4 commits into
developfrom
feature/10
Jul 14, 2026
Merged

[Feat] 기본 임베딩 모델 등록 및 조회#11
Gimini-3 merged 4 commits into
developfrom
feature/10

Conversation

@Gimini-3

@Gimini-3 Gimini-3 commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

작업 내용

  • embedding_modelsdimension > 0 제약과 active+searchable 단일 모델 partial unique index를 추가했습니다.
  • local/test Profile에서 사용할 1024차원 Mock 모델을 멱등 Seed로 등록했습니다.
  • 내부 도메인 서비스용 getActiveModel()과 외부 API용 DTO 조회를 분리했습니다.
  • GET /api/embedding-models/active와 Swagger/OpenAPI 문서를 추가했습니다.
  • 모델 미설정과 중복 설정을 별도 ErrorCode 및 HTTP 500 응답으로 처리했습니다.
  • Entity, Repository, Service, Controller 테스트를 추가했습니다.

설계 배경

후속 문서 업로드 작업은 embedding job 생성 시점의 기본 모델 Entity를 조회해 embedding_model_id를 고정해야 합니다. Worker가 처리 중인 Job은 이후 기본 모델 설정 변경의 영향을 받지 않도록 내부 조회 메서드는 DTO가 아닌 Entity를 반환합니다.

외부 API는 내부 설정인 configJson, vectorStorageStrategy, 활성 상태와 감사 필드를 노출하지 않고 공개 메타데이터 6개만 반환합니다.

DB 및 Profile

  • 기존에 공유·적용된 V14는 수정하지 않고 V27 Migration을 추가했습니다.
  • OpenSQL-PG 14.6에서 CHECK, partial unique index, ON CONFLICT 동작을 확인했습니다.
  • local/test에서만 db/seed Flyway location을 사용하며 prod에는 Mock Seed가 적용되지 않습니다.
  • test Profile은 H2 대신 OpenSQL의 docgrid_test 전용 스키마를 사용합니다.

검증

  • ./gradlew build
  • 전체 테스트 17개 통과
  • OpenSQL V27 및 repeatable Seed 적용 확인
  • 애플리케이션 재기동 후 Mock 모델 1개 유지 확인
  • /v3/api-docs에서 ApiResponse Wrapper, Enum, 두 HTTP 500 예시 확인
  • 현재 기존 Security 설정에서 미인증 API 호출은 본문 없는 HTTP 403임을 확인

Summary by CodeRabbit

  • 새로운 기능

    • 현재 활성화된 임베딩 모델 정보를 조회하는 API를 추가했습니다.
    • 모델 제공자, 이름, 버전, 벡터 차원 및 거리 계산 방식을 확인할 수 있습니다.
    • 기본 임베딩 모델이 없거나 여러 개로 설정된 경우 명확한 오류를 제공합니다.
    • 로컬 및 테스트 환경에서 모크 임베딩 모델을 자동으로 사용할 수 있습니다.
  • 버그 수정 및 안정성

    • 임베딩 모델의 이름, 버전, 차원 및 필수 설정값을 검증합니다.
    • 활성 및 검색 가능 상태의 모델이 하나만 유지되도록 제한했습니다.
  • 문서

    • 프로젝트 개발 규칙과 주요 실행 지침을 추가했습니다.

@coderabbitai

coderabbitai Bot commented Jul 14, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

임베딩 모델의 생성 검증과 데이터베이스 제약, 활성 모델 조회 서비스 및 REST API가 추가되었습니다. 테스트 프로파일과 시드 데이터가 구성되었고, 위험한 Git push를 차단하는 Bash 훅과 프로젝트 작업 지침 문서가 추가되었습니다.

Changes

임베딩 모델 조회 API

Layer / File(s) Summary
임베딩 모델 계약과 저장소 제약
src/main/java/.../embedding/entity/EmbeddingModel.java, src/main/java/.../embedding/repository/EmbeddingModelRepository.java, src/main/resources/db/..., src/main/resources/application-*.yml, src/test/java/.../embedding/{entity,repository,fixture}/*
모델 입력값 검증, 활성·검색 가능 모델 저장소 조회, 차원 및 단일 활성 모델 데이터베이스 제약, 테스트 시드와 관련 검증이 추가되었습니다.
활성 모델 조회와 응답 변환
src/main/java/.../embedding/{service,converter,dto}/..., src/main/java/.../global/exception/ErrorCode.java, src/test/java/.../embedding/service/query/*
활성 모델이 없거나 여러 개인 경우의 오류 처리를 포함한 조회 서비스와 응답 DTO 변환이 구현되고 테스트되었습니다.
임베딩 모델 REST 엔드포인트
src/main/java/.../embedding/controller/EmbeddingModelController.java, src/test/java/.../embedding/controller/*
GET /api/embedding-models/active 엔드포인트와 OpenAPI 응답 문서, 성공·오류 시나리오 테스트가 추가되었습니다.

개발 가이드와 명령 보호

Layer / File(s) Summary
위험한 Git 명령 차단
.codex/hooks.json, .codex/hooks/pre-bash.sh
Bash 실행 전 git push --force/-f와 main 브랜치 직접 push를 검사해 차단하는 훅이 구성되었습니다.
프로젝트 작업 지침
AGENTS.md
개발 원칙, 프로젝트 구조, Gradle 명령어와 금지 규칙이 문서화되었습니다.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant EmbeddingModelController
  participant EmbeddingModelQueryService
  participant EmbeddingModelRepository
  Client->>EmbeddingModelController: GET /api/embedding-models/active
  EmbeddingModelController->>EmbeddingModelQueryService: getActiveModelResponse()
  EmbeddingModelQueryService->>EmbeddingModelRepository: findAllByIsActiveTrueAndIsSearchableTrue()
  EmbeddingModelRepository-->>EmbeddingModelQueryService: 활성·검색 가능 모델 목록
  EmbeddingModelQueryService-->>EmbeddingModelController: EmbeddingModelResponse
  EmbeddingModelController-->>Client: ApiResponse
Loading

Possibly related PRs

  • DocGrid/backend#6: EmbeddingModel과 초기 embedding_models 스키마를 추가한 선행 변경입니다.

Suggested labels: ✨ Feature

🚥 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 주요 변경인 기본 임베딩 모델의 등록/조회 기능을 간결하게 잘 요약합니다.
Description check ✅ Passed 핵심 작업, 설계 배경, DB/Profile, 검증 내용이 포함돼 있어 요구사항을 대부분 충족합니다.
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 feature/10

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.

@Gimini-3 Gimini-3 self-assigned this Jul 14, 2026
@Gimini-3
Gimini-3 marked this pull request as ready for review July 14, 2026 08:43
@Gimini-3
Gimini-3 merged commit eecf255 into develop Jul 14, 2026
1 check was pending
@Gimini-3 Gimini-3 changed the title 기본 임베딩 모델 등록 및 조회 [FEAT] 기본 임베딩 모델 등록 및 조회 Jul 14, 2026
@Gimini-3 Gimini-3 changed the title [FEAT] 기본 임베딩 모델 등록 및 조회 [Feat] 기본 임베딩 모델 등록 및 조회 Jul 14, 2026
@Gimini-3 Gimini-3 added the ✨ Feature 기능 개발 label Jul 14, 2026

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

🧹 Nitpick comments (2)
AGENTS.md (1)

55-55: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

코드 블록 언어 명시

렌더링 품질 향상 및 정적 분석 도구의 경고 해결을 위해, 펜스 코드 블록에 적절한 언어(예: text)를 명시하는 것이 좋습니다.

🛠 제안하는 수정안
-```
+```text
🤖 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 `@AGENTS.md` at line 55, 문서의 언어 지정 없는 펜스 코드 블록을 찾아 내용에 맞는 언어 식별자를 추가하세요. 일반 텍스트
예시는 text를 사용하고, 기존 코드 블록 내용은 변경하지 마세요.

Source: Linters/SAST tools

src/test/java/com/opensource/docgrid/domain/embedding/service/query/EmbeddingModelQueryServiceTest.java (1)

58-61: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

메서드 참조를 사용하여 코드를 더 간결하게 작성하세요.

람다 표현식 () -> embeddingModelQueryService.getActiveModel() 대신 메서드 참조를 사용하면 클린코드 관점에서 코드의 가독성을 높일 수 있습니다.

  • src/test/java/com/opensource/docgrid/domain/embedding/service/query/EmbeddingModelQueryServiceTest.java#L58-L61: assertThatThrownBy(embeddingModelQueryService::getActiveModel)로 변경하세요.
  • src/test/java/com/opensource/docgrid/domain/embedding/service/query/EmbeddingModelQueryServiceTest.java#L71-L74: 동일하게 assertThatThrownBy(embeddingModelQueryService::getActiveModel)로 변경하세요.
🤖 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/test/java/com/opensource/docgrid/domain/embedding/service/query/EmbeddingModelQueryServiceTest.java`
around lines 58 - 61, Replace the lambda passed to assertThatThrownBy with the
embeddingModelQueryService::getActiveModel method reference in both affected
sites:
src/test/java/com/opensource/docgrid/domain/embedding/service/query/EmbeddingModelQueryServiceTest.java
lines 58-61 and 71-74. Preserve the existing exception type and errorCode
assertions.
🤖 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 @.codex/hooks.json:
- Line 9: Update the hook command in the hooks configuration to remove the
hardcoded user-specific absolute path and invoke pre-bash.sh using a
project-root-relative path, preserving the existing hook script and bash
execution behavior.

In `@AGENTS.md`:
- Line 33: AGENTS.md의 상황별 룰 안내에서 경로 표기를 실제 구조인 .codex/hooks/로 통일하고, 문서 내 언어 미지정
코드 블록에는 bash 등 적절한 언어 식별자를 추가하세요.

In `@src/main/resources/db/migration/V27__add_embedding_model_constraints.sql`:
- Around line 2-3: Update the ck_embedding_models_dimension_positive CHECK
constraint definition to use the database’s NOT VALID option, deferring
validation and avoiding the initial full-table scan; leave constraint validation
to a separate future migration using VALIDATE CONSTRAINT.
- Around line 6-9: Update the uk_embedding_models_one_active_searchable index
creation to use PostgreSQL’s CONCURRENTLY option, and configure or split the
Flyway migration so this statement executes outside a transaction while
preserving the existing uniqueness and predicate.

---

Nitpick comments:
In `@AGENTS.md`:
- Line 55: 문서의 언어 지정 없는 펜스 코드 블록을 찾아 내용에 맞는 언어 식별자를 추가하세요. 일반 텍스트 예시는 text를
사용하고, 기존 코드 블록 내용은 변경하지 마세요.

In
`@src/test/java/com/opensource/docgrid/domain/embedding/service/query/EmbeddingModelQueryServiceTest.java`:
- Around line 58-61: Replace the lambda passed to assertThatThrownBy with the
embeddingModelQueryService::getActiveModel method reference in both affected
sites:
src/test/java/com/opensource/docgrid/domain/embedding/service/query/EmbeddingModelQueryServiceTest.java
lines 58-61 and 71-74. Preserve the existing exception type and errorCode
assertions.
🪄 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: 8ead191e-0d9e-4754-a98a-bbcb7270d443

📥 Commits

Reviewing files that changed from the base of the PR and between 458aba6 and a73a92c.

📒 Files selected for processing (20)
  • .codex/hooks.json
  • .codex/hooks/pre-bash.sh
  • AGENTS.md
  • src/main/java/com/opensource/docgrid/domain/embedding/controller/EmbeddingModelController.java
  • src/main/java/com/opensource/docgrid/domain/embedding/converter/EmbeddingModelConverter.java
  • src/main/java/com/opensource/docgrid/domain/embedding/dto/response/EmbeddingModelResponse.java
  • src/main/java/com/opensource/docgrid/domain/embedding/entity/EmbeddingModel.java
  • src/main/java/com/opensource/docgrid/domain/embedding/repository/EmbeddingModelRepository.java
  • src/main/java/com/opensource/docgrid/domain/embedding/service/query/EmbeddingModelQueryService.java
  • src/main/java/com/opensource/docgrid/global/exception/ErrorCode.java
  • src/main/resources/application-local.yml
  • src/main/resources/application-test.yml
  • src/main/resources/db/migration/V27__add_embedding_model_constraints.sql
  • src/main/resources/db/seed/R__seed_mock_embedding_model.sql
  • src/test/java/com/opensource/docgrid/DocgridApplicationTests.java
  • src/test/java/com/opensource/docgrid/domain/embedding/controller/EmbeddingModelControllerTest.java
  • src/test/java/com/opensource/docgrid/domain/embedding/entity/EmbeddingModelTest.java
  • src/test/java/com/opensource/docgrid/domain/embedding/fixture/EmbeddingModelFixture.java
  • src/test/java/com/opensource/docgrid/domain/embedding/repository/EmbeddingModelRepositoryTest.java
  • src/test/java/com/opensource/docgrid/domain/embedding/service/query/EmbeddingModelQueryServiceTest.java

Comment thread .codex/hooks.json
"hooks": [
{
"type": "command",
"command": "bash '/Users/giminkim/IdeaProjects/backend/.codex/hooks/pre-bash.sh'"

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 | 🔴 Critical | ⚡ Quick win

절대 경로 사용 금지 및 상대 경로로 변경

환경에 종속적인 절대 경로가 하드코딩되어 있어, 다른 개발자의 로컬 환경이나 CI 파이프라인에서 훅이 정상적으로 실행되지 않고 실패합니다. 프로젝트 루트 기준의 상대 경로로 수정해야 합니다.

🛠 제안하는 수정안
-            "command": "bash '/Users/giminkim/IdeaProjects/backend/.codex/hooks/pre-bash.sh'"
+            "command": "bash .codex/hooks/pre-bash.sh"
📝 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
"command": "bash '/Users/giminkim/IdeaProjects/backend/.codex/hooks/pre-bash.sh'"
"command": "bash .codex/hooks/pre-bash.sh"
🤖 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 @.codex/hooks.json at line 9, Update the hook command in the hooks
configuration to remove the hardcoded user-specific absolute path and invoke
pre-bash.sh using a project-root-relative path, preserving the existing hook
script and bash execution behavior.

Comment thread AGENTS.md
- 프로젝트 구조 → 이 파일 (AGENTS.md)
- 도메인 목록 → `src/main/java/com/opensource/docgrid/domain/`

### 🟢 상황별 룰 (`.Codex/rules/`) — 자동 로드됨

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 | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Check the actual casing of the codex directory in the root.
ls -ld .[cC]odex 2>/dev/null

Repository: DocGrid/backend

Length of output: 209


🏁 Script executed:

sed -n '1,120p' AGENTS.md | cat -n

Repository: DocGrid/backend

Length of output: 3196


🏁 Script executed:

find .codex -maxdepth 3 -type d -o -type f | sort

Repository: DocGrid/backend

Length of output: 216


경로 표기와 코드 블록 형식을 정리하세요

  • AGENTS.md:33.Codex/rules/는 실제 경로인 .codex/hooks/와 이름/대소문자가 다릅니다. 경로를 실제 구조에 맞게 통일해야 혼동을 줄일 수 있습니다.
  • AGENTS.md:55의 코드 블록에는 언어 지정이 없어 lint 경고가 납니다. bash 같은 식으로 붙여 주세요.
🤖 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 `@AGENTS.md` at line 33, AGENTS.md의 상황별 룰 안내에서 경로 표기를 실제 구조인 .codex/hooks/로
통일하고, 문서 내 언어 미지정 코드 블록에는 bash 등 적절한 언어 식별자를 추가하세요.

Comment on lines +2 to +3
ADD CONSTRAINT ck_embedding_models_dimension_positive
CHECK (dimension > 0);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

운영 환경에서의 테이블 락(Lock) 방지를 위해 제약 조건 검증을 지연시키세요.

기본적으로 기존 테이블에 새로운 CHECK 제약 조건을 추가하면 전체 테이블 스캔이 발생하며 쓰기 작업이 차단됩니다. 테이블 락에 의한 성능 및 가용성 저하를 막기 위해 NOT VALID 옵션을 사용하여 제약 조건을 추가한 후, 향후 별도의 마이그레이션에서 VALIDATE CONSTRAINT를 수행하는 것을 권장합니다.

🛠 제안하는 수정안
     ADD CONSTRAINT ck_embedding_models_dimension_positive
-        CHECK (dimension > 0);
+        CHECK (dimension > 0) NOT VALID;
📝 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
ADD CONSTRAINT ck_embedding_models_dimension_positive
CHECK (dimension > 0);
ADD CONSTRAINT ck_embedding_models_dimension_positive
CHECK (dimension > 0) NOT VALID;
🧰 Tools
🪛 Squawk (2.59.0)

[warning] 2-3: By default new constraints require a table scan and block writes to the table while that scan occurs. Use NOT VALID with a later VALIDATE CONSTRAINT call.

(constraint-missing-not-valid)

🤖 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/resources/db/migration/V27__add_embedding_model_constraints.sql`
around lines 2 - 3, Update the ck_embedding_models_dimension_positive CHECK
constraint definition to use the database’s NOT VALID option, deferring
validation and avoiding the initial full-table scan; leave constraint validation
to a separate future migration using VALIDATE CONSTRAINT.

Source: Linters/SAST tools

Comment on lines +6 to +9
CREATE UNIQUE INDEX uk_embedding_models_one_active_searchable
ON embedding_models ((1))
WHERE is_active = TRUE
AND is_searchable = 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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

운영 환경에서의 쓰기 작업 차단을 방지하기 위해 인덱스를 동시 생성(Concurrently)하세요.

일반적인 인덱스 생성은 완료될 때까지 테이블의 쓰기(Update/Insert/Delete) 작업을 차단합니다. 시스템 가용성을 유지하기 위해 CONCURRENTLY 키워드를 사용하는 것이 좋습니다.

단, PostgreSQL에서 CONCURRENTLY는 트랜잭션 블록 내에서 실행할 수 없으므로, Flyway 환경에서는 스크립트가 트랜잭션 외부에서 실행되도록 설정(예: Flyway 설정 조정 또는 마이그레이션 파일 분리)해야 할 수 있습니다.

🛠 제안하는 수정안
-CREATE UNIQUE INDEX uk_embedding_models_one_active_searchable
+CREATE UNIQUE INDEX CONCURRENTLY uk_embedding_models_one_active_searchable
     ON embedding_models ((1))
📝 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
CREATE UNIQUE INDEX uk_embedding_models_one_active_searchable
ON embedding_models ((1))
WHERE is_active = TRUE
AND is_searchable = TRUE;
CREATE UNIQUE INDEX CONCURRENTLY uk_embedding_models_one_active_searchable
ON embedding_models ((1))
WHERE is_active = TRUE
AND is_searchable = TRUE;
🧰 Tools
🪛 Squawk (2.59.0)

[warning] 6-9: During normal index creation, table updates are blocked, but reads are still allowed. Use concurrently to avoid blocking writes.

(require-concurrent-index-creation)

🤖 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/resources/db/migration/V27__add_embedding_model_constraints.sql`
around lines 6 - 9, Update the uk_embedding_models_one_active_searchable index
creation to use PostgreSQL’s CONCURRENTLY option, and configure or split the
Flyway migration so this statement executes outside a transaction while
preserving the existing uniqueness and predicate.

Source: Linters/SAST tools

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

✨ Feature 기능 개발

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant