Skip to content

[Feat] 텍스트 파싱 및 Chunk 저장 - #76

Merged
Gimini-3 merged 18 commits into
developfrom
feature/68
Jul 29, 2026
Merged

[Feat] 텍스트 파싱 및 Chunk 저장#76
Gimini-3 merged 18 commits into
developfrom
feature/68

Conversation

@Gimini-3

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

Copy link
Copy Markdown
Contributor

🔍️ 작업 내용

현재 Worker가 소유한 PROCESSING Embedding Job과 STARTED Attempt를 실행 Context로 검증한 뒤,
MinIO의 TXT·Markdown 원본을 결정적인 Unicode Code Point 기반 Chunk로 분할해
document_chunks에 저장합니다.

  • 최초 Chunk Set 저장: 201 Created
  • 완료 결과 재호출·동시 후발 호출: 200 OK
  • Endpoint: POST /admin/indexing-jobs/{jobId}/attempts/{attemptId}/chunks
  • DB Migration 및 신규 Production Dependency: 없음

✨ 상세 설명

1. 전체 요청 흐름

  1. ADMIN 요청이 Job ID, Attempt ID, Worker ID와 canonical UUID Claim Token을 전달합니다.
  2. 준비 Transaction이 Embedding Job을 쓰기 잠금으로 조회합니다.
  3. 잠금 획득 뒤 현재 시각을 계산하고 공통 Validator가 PROCESSING 상태, 소유권 필드,
    Worker, Claim Token과 Lease를 검증합니다.
  4. 현재 Claim Token의 Attempt가 Path Attempt ID, 요청 Worker와 일치하고 STARTED 상태인지 확인합니다.
  5. Job이 직접 참조하는 Document Version을 쓰기 잠금으로 조회합니다.
    Document.currentVersion은 처리 대상 판단에 사용하지 않습니다.
  6. TXT·Markdown Content Type, FileObject 연관, Bucket·Object Key, 기존 Chunk와 Version 상태를 확인합니다.
  7. 최초 요청이면 Version을 UPLOADED → PARSING으로 전환하고 PARSE_STARTED 이벤트를
    같은 Transaction에 저장합니다.
  8. 준비 Transaction Commit 뒤 모든 DB Lock을 해제합니다.
  9. Transaction 밖에서 FileObject Snapshot의 Bucket과 Object Key로 MinIO Object 전체 Byte를 읽고
    Stream을 닫습니다.
  10. Parser가 잘못된 Byte를 허용하지 않는 엄격한 UTF-8 Decode, 선두 BOM 제거와
    CRLF·CR → LF 정규화를 수행합니다. Markdown 문법과 일반 공백은 보존합니다.
  11. Chunker가 Unicode Code Point 기준으로 Index, 반열린 범위, 본문, 공백 기반 Token 추정치와
    소문자 SHA-256 Hash를 계산합니다.
  12. 완료 Transaction이 Job과 Version을 다시 잠그고 소유권·Lease·Attempt 및
    준비 단계 Version ID를 재검증합니다.
  13. 모든 Draft를 같은 Version의 DocumentChunk로 변환해 saveAllAndFlush하고,
    Version을 CHUNKED로 전환하며 CHUNKED 이벤트를 저장합니다.
  14. 최초 저장은 201, 이미 완료된 결과의 멱등 재생은 200으로 반환합니다.

2. 설계·동작 원리

짧은 두 Transaction과 외부 작업 분리

DocumentParsingService에는 @Transactional을 적용하지 않았습니다. 준비와 완료는 별도 Spring Bean인
DocumentChunkTransactionService의 서로 다른 Public 메서드가 담당합니다. 따라서 MinIO I/O와
UTF-8 Decode·Hash 계산 동안 DB Connection과 Job·Version 행 잠금을 유지하지 않습니다.

준비 단계는 JPA Entity 대신 Version ID, Document Type과 StoredFile만 가진 불변 Snapshot을
반환합니다. 외부 작업 결과도 Entity가 아닌 DocumentChunkDraft 목록이므로 Persistence Context가
Transaction 밖으로 새지 않습니다.

외부 작업 전후의 소유권 재검증

MinIO 읽기와 계산 중 Lease가 만료되거나 Claim Token이 교체될 수 있습니다. 완료 Transaction은 Lock을
다시 획득한 뒤 새 현재 시각으로 Worker·Token·Lease와 Attempt를 다시 검증합니다.
과거 Worker가 늦게 계산한 결과는 Chunk Insert 전에 거부됩니다.

Lock 순서와 원자성

모든 경로는 Embedding Job을 먼저, Document Version을 다음 순서로 잠급니다. Claim 교체와 같은 Job
중복 요청은 Job Lock으로, 동일 Version의 Chunk Set 경합은 Version Lock으로 직렬화합니다.

완료 Transaction의 Chunk 전체 Insert·Flush, CHUNKED 상태 전환과 완료 이벤트 중 하나라도 실패하면
모두 Rollback됩니다. 기존 (document_version_id, chunk_index) Unique Constraint는 Service 경로를
우회한 중복 Insert의 최종 방어선입니다.

멱등성과 동시성

  • UPLOADED → PARSINGPARSE_STARTED는 한 번만 기록합니다.
  • PARSING 상태 재개는 외부 계산을 다시 수행할 수 있지만 시작 이벤트를 추가하지 않습니다.
  • CHUNKED 재호출은 MinIO·Parser·Chunker를 호출하지 않고 저장된 Chunk 수를 반환합니다.
  • 두 요청이 외부 작업을 동시에 수행해도 먼저 완료한 요청만 Chunk와 이벤트를 저장합니다.
  • 후발 요청은 Version Lock 뒤 CHUNKED를 확인하고 같은 결과를 재생합니다.

결정적인 Text와 Chunk 규칙

  • 기본 Chunk 크기: 1,000 Code Point
  • 기본 Overlap: 200 Code Point
  • 다음 시작 증가량: 800 Code Point
  • 범위: 0 기반 반열린 구간 [charStart, charEnd)
  • Token 추정: Unicode 공백으로 구분된 비어 있지 않은 Run 수
  • Hash: Chunk Text UTF-8 Byte의 SHA-256 소문자 Hex
  • TXT·Markdown의 Page, Section, Metadata: null

Java UTF-16 char가 아니라 Code Point 배열로 범위를 계산하므로 Emoji의 Surrogate Pair를 중간에서
자르지 않습니다. 같은 Canonical Text와 설정은 같은 Draft와 DB Row를 만듭니다.

Storage와 오류 분리

FileStorageService.read(StoredFile) 계약을 추가했습니다. MinioStorageService는 전달된 Bucket과
Object Key로 GetObject를 호출하고 try-with-resources 안에서 모든 Byte를 읽어 Stream을 닫습니다.

  • NoSuchKey, NoSuchObject: DOCUMENT-STORAGE-002, 404
  • 그 밖의 연결·인증·Timeout·SDK 오류: 기존 DOCUMENT-STORAGE-001, 503

보안과 외부 노출

기존 /admin/** ADMIN 정책을 재사용하므로 SecurityConfig는 변경하지 않았습니다.
Claim Token, 원문, Chunk 본문, Bucket과 Object Key는 성공 응답에 포함하지 않습니다.
Token과 본문은 이벤트와 일반 로그에도 남기지 않습니다.

3. 설정과 외부 연결

document:
  chunking:
    chunk-size: ${DOCUMENT_CHUNK_SIZE:1000}
    overlap: ${DOCUMENT_CHUNK_OVERLAP:200}

Chunk 크기는 양수, Overlap은 0 이상이면서 Chunk 크기보다 작아야 합니다.
같은 배포군의 Worker는 결정성을 위해 같은 설정을 사용해야 합니다.

기존 Spring Boot, Spring Data JPA, OpenSQL/PostgreSQL, Flyway와 MinIO Java SDK만 사용합니다.
새 Schema, Migration, Message Broker, Cache, Markdown Library와 Production Dependency는
추가하지 않았습니다.

4. 기능별 커밋과 코드 변경

7c71cd2 — Embedding Job 소유권 검증기 추가

  • EmbeddingJobOwnershipValidator를 추가했습니다.
  • 잠긴 Job의 PROCESSING 상태, 소유권 필드 완전성, Worker·Token 일치와 Lease를 순서대로 검증합니다.
  • Repository 조회와 Transaction 시작은 호출 Service에 남겨 Attempt와 Chunk 흐름이 같은 정책을
    재사용할 수 있게 했습니다.

0a3cae8 — 소유권 검증 계약 Test

  • 정상·상태·필드 누락·다른 Worker·과거 Token·Lease 경계 13개 Validator 시나리오를 고정했습니다.
  • 기존 Attempt Service Test Fixture를 공통 Validator 의존성에 맞췄습니다.

53ca125 — Attempt 시작의 공통 Validator 위임

  • EmbeddingJobAttemptService의 중복 Private 검증 메서드를 제거했습니다.
  • Job Lock 뒤 계산한 시각과 Worker·Token을 공통 Validator에 전달합니다.
  • Claim Token 멱등 조회, Attempt 번호 계산과 생성·재생 책임은 기존 Service에 유지했습니다.

d0b15ef — 프로젝트 경로 독립 Hook

  • 폴더명 변경 전 backend 절대 경로를 참조하던 .codex/hooks.json을 저장소 상대 경로로 바꿨습니다.
  • 일반 명령 허용과 force push 차단 동작을 확인했습니다.

b7f8e6a — 결정적 Parser·Chunker 구현

  • DocumentChunkingProperties, TextDocumentParser, FixedSizeChunker, DocumentChunkDraft를 추가했습니다.
  • 엄격한 UTF-8, BOM·줄바꿈 정규화, 공백 전용 문서 오류를 구현했습니다.
  • Code Point 범위, Token 추정치와 SHA-256 Hash를 계산합니다.
  • application.yml, .env.example과 Parser 관련 ErrorCode를 추가했습니다.

d64f80c — Parser·Chunker 단위 Test

  • 설정 3개, Parser 5개, Chunker 6개 Test를 추가했습니다.
  • Markdown 보존, 잘못된 UTF-8, Emoji 경계, Overlap, 마지막 Chunk와 Hash 결정성을 검증합니다.

74312d7 — MinIO 원본 읽기

  • FileStorageServiceread(StoredFile)을 추가했습니다.
  • MinioStorageServiceGetObject, 전체 Byte 읽기, Stream 종료와
    Object 없음·일반 장애 분리를 구현했습니다.

109fa88 — MinIO 읽기 단위 Test

  • 전달 Bucket·Object Key, 반환 Byte, 원본 Stream 종료를 검증했습니다.
  • NoSuchKey와 일반 I/O 오류의 ErrorCode 변환을 검증했습니다.
  • 기존 MinIO 업로드 동시성 Test Wrapper가 확장된 Interface를 위임하도록 수정했습니다.

b09adbe — Version 상태와 Chunk Repository

  • DocumentVersion.markParsing, markChunked에 허용 상태 Guard를 추가했습니다.
  • DocumentVersionRepository.findByIdForUpdate를 추가했습니다.
  • DocumentChunkRepository에 Version별 존재·개수 조회를 추가했습니다.

43b028c — Version 상태 전이 Test

  • 정상 UPLOADED → PARSING → CHUNKED, 잘못된 상태의 두 전이 거부와 기존 후속 전이를 포함한
    12개 Test를 추가했습니다.

45f9c9e — Chunk Transaction·Orchestration·관리자 API

  • DocumentChunkTransactionService에 준비·완료 Transaction을 구현했습니다.
  • DocumentParsingService가 두 Transaction 사이의 MinIO·Parser·Chunker를 조정합니다.
  • Request·Response DTO와 관리자 Endpoint, Swagger 및 Attempt·Version·Parser·Chunk 오류 코드를
    추가했습니다.
  • Draft 불변식 검증과 Entity 변환을 완료 Transaction 안에 두었습니다.

aa727f9 — API·원자성·동시성·실제 MinIO Test

  • Orchestration 4개, Transaction 7개와 Controller 계약 Test를 추가했습니다.
  • 실제 OpenSQL에서 결정적 Row·상태·이벤트와 두 Thread의 생성·재생 수렴을 검증했습니다.
  • 실제 MinIO에서 기본 Bucket, 전달된 다른 Bucket과 없는 Object를 검증했습니다.

9b9f176 — 설계 문서 확정

  • docs/design/text-parsing-chunk-storage.md에 범위, 전체 흐름, 상태, Transaction, Lock,
    오류, 보안, 설정, Test와 후속 경계를 기록했습니다.
  • 최신 develop 기준과 실제 기능 커밋 구성을 반영했습니다.

5. 검증 결과

  • ./gradlew clean test: 319개 성공
  • DocumentChunkingIntegrationTest: 2개 성공
  • MinioDocumentReadIntegrationTest: 3개 성공
  • Parser·Chunker 집중 Test: 14개 성공
  • Version 상태 전이 Test: 12개 성공
  • Transaction·Orchestration·Controller 집중 Test: 48개 성공
  • git diff --check: 성공

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

  • Embedding 생성과 저장 및 Job·Attempt 완료 상태 연결
  • 실패 시 PARSE_FAILED, Attempt 종료와 오류 이력 기록
  • Lease 연장, 만료 Job 회수와 Worker 자동 Polling
  • PDF·DOCX·HTML Parser 및 페이지·섹션 Metadata
  • 모델별 실제 Tokenizer와 의미 기반 Chunking
  • 대용량 문서를 위한 Streaming Parser

📸 스크린샷 (선택)

  • API·Transaction·Storage 중심 Backend 변경으로 별도 화면 스크린샷은 없습니다.

💬 리뷰 요구사항

  • MinIO I/O와 Chunk 계산이 DB Transaction 밖에 유지되는지 확인 부탁드립니다.
  • Job → Version Lock 순서와 완료 단계의 소유권 재검증을 중점적으로 봐주세요.
  • PARSING 재개와 CHUNKED 재생의 이벤트·Row 비증가 계약을 확인 부탁드립니다.
  • Code Point Offset과 기본 1,000/200 Chunk 정책이 후속 Embedding·Citation 흐름에 적합한지
    의견 부탁드립니다.

Summary by CodeRabbit

  • 새 기능
    • TXT·Markdown 문서를 UTF-8로 검증하고 표준화한 뒤 고정 크기 청크로 분할해 저장합니다.
    • 청크 크기와 중복 범위를 환경 변수로 설정할 수 있습니다.
    • 관리자용 API에서 문서 청크 생성 결과와 처리 상태를 확인할 수 있습니다.
    • 동일 요청을 반복해도 중복 청크가 생성되지 않습니다.
  • 버그 수정
    • 잘못된 인코딩, 빈 문서, 지원하지 않는 형식 및 존재하지 않는 파일을 명확한 오류로 안내합니다.
    • 문서 처리 상태 전이를 검증해 잘못된 진행을 방지합니다.
  • 문서화
    • 문서 파싱·청크 저장 정책과 처리 규칙을 상세히 정리했습니다.

@coderabbitai

coderabbitai Bot commented Jul 29, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

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

Next review available in: 18 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: d6b229e0-edd6-4c2a-92c3-0bfed5714428

📥 Commits

Reviewing files that changed from the base of the PR and between 9b9f176 and 6e81a72.

📒 Files selected for processing (5)
  • docs/design/Gimini-3-#68-text-parsing-chunk-storage.md
  • src/main/java/com/opensource/docgrid/domain/document/service/FixedSizeChunker.java
  • src/main/java/com/opensource/docgrid/domain/document/storage/MinioStorageService.java
  • src/test/java/com/opensource/docgrid/domain/document/service/FixedSizeChunkerTest.java
  • src/test/java/com/opensource/docgrid/domain/embedding/controller/IndexingJobAdminControllerTest.java
📝 Walkthrough

Walkthrough

MinIO의 TXT·Markdown 원문을 엄격한 UTF-8로 정규화하고 Unicode Code Point 기준 Chunk로 분할해 document_chunks에 원자적으로 저장하는 파이프라인을 추가했습니다. 관리자 API, 멱등성·동시성 제어, 상태·이벤트 전이, 소유권 검증과 관련 테스트도 포함됩니다.

Changes

문서 Chunk 파이프라인

Layer / File(s) Summary
계약·상태·설정 및 소유권 검증
docs/design/..., src/main/java/com/opensource/docgrid/domain/document/config/*, src/main/java/com/opensource/docgrid/domain/document/entity/DocumentVersion.java, src/main/java/com/opensource/docgrid/domain/document/repository/*, src/main/java/com/opensource/docgrid/domain/embedding/dto/*, src/main/java/com/opensource/docgrid/domain/embedding/service/command/*, src/main/java/com/opensource/docgrid/global/exception/ErrorCode.java
Chunk 설정, 상태 전이 가드, 잠금 조회, API DTO, 오류 코드 및 공통 Job 소유권 검증을 정의했습니다.
텍스트 파싱·Chunk 계산 및 MinIO 읽기
src/main/java/com/opensource/docgrid/domain/document/service/TextDocumentParser.java, FixedSizeChunker.java, DocumentChunkDraft.java, src/main/java/com/opensource/docgrid/domain/document/storage/*, src/test/java/com/opensource/docgrid/domain/document/service/*Test.java, src/test/java/com/opensource/docgrid/domain/document/storage/*Test.java, src/test/java/com/opensource/docgrid/domain/document/integration/minio/*
원문을 정규화하고 고정 크기·중첩 Chunk와 해시를 생성하며 MinIO 객체를 byte 배열로 읽고 오류를 변환합니다.
준비·완료 트랜잭션과 멱등 저장
src/main/java/com/opensource/docgrid/domain/document/service/DocumentParsingService.java, src/main/java/com/opensource/docgrid/domain/document/service/command/DocumentChunkTransactionService.java, src/test/java/com/opensource/docgrid/domain/document/integration/DocumentChunkingIntegrationTest.java, src/test/java/com/opensource/docgrid/domain/document/service/*Test.java
준비 단계와 외부 파일 처리, 완료 단계의 재검증을 분리하고 Chunk·상태·이벤트를 원자적으로 저장하며 재호출과 동시 요청을 기존 결과로 수렴시킵니다.
관리자 Chunk API 연결 및 계약 검증
src/main/java/com/opensource/docgrid/domain/embedding/controller/IndexingJobAdminController.java, src/test/java/com/opensource/docgrid/domain/embedding/controller/IndexingJobAdminControllerTest.java
Chunk 생성 Endpoint를 추가하고 최초 생성은 201, 완료 결과 재생은 200으로 응답하며 입력·권한·비즈니스 오류 매핑을 검증합니다.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant 관리자
  participant IndexingJobAdminController
  participant DocumentParsingService
  participant MinioStorageService
  participant DocumentChunkTransactionService
  participant Database

  관리자->>IndexingJobAdminController: POST /admin/indexing-jobs/{jobId}/attempts/{attemptId}/chunks
  IndexingJobAdminController->>DocumentParsingService: createChunks(...)
  DocumentParsingService->>DocumentChunkTransactionService: prepare(...)
  DocumentChunkTransactionService-->>DocumentParsingService: FileSnapshot 또는 replay
  DocumentParsingService->>MinioStorageService: read(StoredFile)
  MinioStorageService-->>DocumentParsingService: 원문 bytes
  DocumentParsingService->>DocumentChunkTransactionService: complete(..., drafts)
  DocumentChunkTransactionService->>Database: Chunk·상태·이벤트 원자적 저장
  Database-->>DocumentChunkTransactionService: 저장 결과
  DocumentChunkTransactionService-->>IndexingJobAdminController: ChunkResult
  IndexingJobAdminController-->>관리자: 201 생성 또는 200 재생 응답
Loading

Possibly related PRs

  • DocGrid/backend#22: 문서 저장소 계약을 도입한 PR로, 이번 변경의 FileStorageService.read 확장과 직접 연결됩니다.
  • DocGrid/backend#49: Claim Token과 Lease 기반 Job 소유권 흐름을 도입해 이번 소유권 검증과 연결됩니다.
  • DocGrid/backend#64: Attempt 시작 서비스의 소유권 검증 흐름을 다뤄 이번 Validator 위임 변경과 직접 연결됩니다.

Suggested labels: ✨ Feature

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning .codex/hooks.json의 훅 경로 변경은 #68의 텍스트 파싱 및 Chunk 저장 범위와 직접 관련이 없습니다. 해당 훅 경로 변경은 별도 PR로 분리하거나, 이 변경이 필요한 근거를 본문에 명시하세요.
Docstring Coverage ⚠️ Warning Docstring coverage is 6.94% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed 제목이 텍스트 파싱과 Chunk 저장이라는 핵심 변경을 간결하게 잘 요약합니다.
Description check ✅ Passed 필수 섹션과 작업 내용, 상세 설명, 후속 계획, 리뷰 요구사항이 모두 포함되어 있습니다.
Linked Issues check ✅ Passed #68의 소유권 검증, 결정적 파싱/청크, 원자적 저장, MinIO 외부 처리, 테스트와 문서화 요구를 충족합니다.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/68

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 marked this pull request as ready for review July 29, 2026 06:05

@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)
src/main/java/com/opensource/docgrid/domain/document/service/command/DocumentChunkTransactionService.java (1)

282-294: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Content Hash 정규식 매번 컴파일

draft.contentHash().matches(...)는 호출마다 Pattern을 새로 컴파일합니다. Chunk 수가 많은 대용량 문서(최대 10MB, 최대 약 1.2만개)에서는 Job/Version Lock을 쥔 채로 이 검증이 반복되므로, static final Pattern으로 미리 컴파일해두면 Lock 보유 시간을 소폭이나마 줄일 수 있습니다. 다만 실질적 영향은 크지 않아 급하지 않은 개선입니다.

🤖 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/document/service/command/DocumentChunkTransactionService.java`
around lines 282 - 294, Update DocumentChunkTransactionService by introducing a
static final precompiled Pattern for the 64-character lowercase hexadecimal
content hash, and replace the matches call in validateDraft with that Pattern.
Preserve the existing validation and exception behavior.
src/test/java/com/opensource/docgrid/domain/document/service/FixedSizeChunkerTest.java (1)

1-123: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

overlap >= chunkSize 경계에 대한 테스트가 없습니다.

FixedSizeChunker.chunk()overlap >= chunkSize일 때 무한 루프 또는 예외를 유발할 수 있는데(별도 코멘트 참고), 이를 검증하는 테스트가 없습니다. 이 값에 대한 방어 로직을 추가한 뒤 회귀 테스트도 함께 추가하는 것을 권장합니다.

🤖 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/document/service/FixedSizeChunkerTest.java`
around lines 1 - 123, Extend FixedSizeChunkerTest to cover configurations where
overlap is equal to or greater than chunkSize, and assert the intended guarded
behavior after updating FixedSizeChunker.chunk() to reject or safely handle
these invalid settings without looping or throwing unexpectedly. Add regression
coverage for both boundary values while preserving existing valid-overlap
behavior.

Source: Path instructions

🤖 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 `@docs/design/text-parsing-chunk-storage.md`:
- Line 1: Rename the design document currently named
text-parsing-chunk-storage.md to follow the required
{github아이디}-#68-text-parsing-chunk-storage.md convention, replacing {github아이디}
with the actual author’s GitHub ID while preserving the existing document
contents.

In
`@src/main/java/com/opensource/docgrid/domain/document/service/FixedSizeChunker.java`:
- Around line 42-68: Validate at the start of FixedSizeChunker.chunk() that
overlap is non-negative and strictly less than chunkSize, failing fast with an
appropriate exception otherwise. Add regression coverage in FixedSizeChunkerTest
for overlap equal to chunkSize and greater than chunkSize, verifying both cases
throw.

In
`@src/main/java/com/opensource/docgrid/domain/document/storage/MinioStorageService.java`:
- Around line 63-67: Update logStorageReadFailure() to stop logging
storedFile.bucketName() and storedFile.objectKey() directly; remove those MinIO
location values from the error message or replace them with an approved
correlation identifier, while preserving the existing failure logging and
DocGridException behavior in the surrounding read flow.

In
`@src/test/java/com/opensource/docgrid/domain/embedding/controller/IndexingJobAdminControllerTest.java`:
- Around line 359-373: Extend invalidChunkRequests() with a case for a
whitespace-only claimToken, using {"workerId": 1, "claimToken": " "}, and retain
the expected invalid-request behavior so the /chunks contract test verifies a
400 response for `@NotBlank` validation.

---

Nitpick comments:
In
`@src/main/java/com/opensource/docgrid/domain/document/service/command/DocumentChunkTransactionService.java`:
- Around line 282-294: Update DocumentChunkTransactionService by introducing a
static final precompiled Pattern for the 64-character lowercase hexadecimal
content hash, and replace the matches call in validateDraft with that Pattern.
Preserve the existing validation and exception behavior.

In
`@src/test/java/com/opensource/docgrid/domain/document/service/FixedSizeChunkerTest.java`:
- Around line 1-123: Extend FixedSizeChunkerTest to cover configurations where
overlap is equal to or greater than chunkSize, and assert the intended guarded
behavior after updating FixedSizeChunker.chunk() to reject or safely handle
these invalid settings without looping or throwing unexpectedly. Add regression
coverage for both boundary values while preserving existing valid-overlap
behavior.
🪄 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: 985e52c3-5084-4b5a-a4d9-ad952aff852a

📥 Commits

Reviewing files that changed from the base of the PR and between 50da23e and 9b9f176.

📒 Files selected for processing (34)
  • .codex/hooks.json
  • .env.example
  • docs/design/text-parsing-chunk-storage.md
  • src/main/java/com/opensource/docgrid/domain/document/config/DocumentChunkingProperties.java
  • src/main/java/com/opensource/docgrid/domain/document/entity/DocumentVersion.java
  • src/main/java/com/opensource/docgrid/domain/document/repository/DocumentChunkRepository.java
  • src/main/java/com/opensource/docgrid/domain/document/repository/DocumentVersionRepository.java
  • src/main/java/com/opensource/docgrid/domain/document/service/DocumentChunkDraft.java
  • src/main/java/com/opensource/docgrid/domain/document/service/DocumentParsingService.java
  • src/main/java/com/opensource/docgrid/domain/document/service/FixedSizeChunker.java
  • src/main/java/com/opensource/docgrid/domain/document/service/TextDocumentParser.java
  • src/main/java/com/opensource/docgrid/domain/document/service/command/DocumentChunkTransactionService.java
  • src/main/java/com/opensource/docgrid/domain/document/storage/FileStorageService.java
  • src/main/java/com/opensource/docgrid/domain/document/storage/MinioStorageService.java
  • src/main/java/com/opensource/docgrid/domain/embedding/controller/IndexingJobAdminController.java
  • src/main/java/com/opensource/docgrid/domain/embedding/dto/request/CreateDocumentChunksRequest.java
  • src/main/java/com/opensource/docgrid/domain/embedding/dto/response/DocumentChunksResponse.java
  • src/main/java/com/opensource/docgrid/domain/embedding/service/command/EmbeddingJobAttemptService.java
  • src/main/java/com/opensource/docgrid/domain/embedding/service/command/EmbeddingJobOwnershipValidator.java
  • src/main/java/com/opensource/docgrid/global/exception/ErrorCode.java
  • src/main/resources/application.yml
  • src/test/java/com/opensource/docgrid/domain/document/config/DocumentChunkingPropertiesTest.java
  • src/test/java/com/opensource/docgrid/domain/document/entity/DocumentVersionTest.java
  • src/test/java/com/opensource/docgrid/domain/document/integration/DocumentChunkingIntegrationTest.java
  • src/test/java/com/opensource/docgrid/domain/document/integration/minio/MinioDocumentReadIntegrationTest.java
  • src/test/java/com/opensource/docgrid/domain/document/integration/minio/MinioUploadConcurrencyIntegrationTest.java
  • src/test/java/com/opensource/docgrid/domain/document/service/DocumentParsingServiceTest.java
  • src/test/java/com/opensource/docgrid/domain/document/service/FixedSizeChunkerTest.java
  • src/test/java/com/opensource/docgrid/domain/document/service/TextDocumentParserTest.java
  • src/test/java/com/opensource/docgrid/domain/document/service/command/DocumentChunkTransactionServiceTest.java
  • src/test/java/com/opensource/docgrid/domain/document/storage/MinioStorageServiceTest.java
  • src/test/java/com/opensource/docgrid/domain/embedding/controller/IndexingJobAdminControllerTest.java
  • src/test/java/com/opensource/docgrid/domain/embedding/service/command/EmbeddingJobAttemptServiceTest.java
  • src/test/java/com/opensource/docgrid/domain/embedding/service/command/EmbeddingJobOwnershipValidatorTest.java

Comment thread docs/design/Gimini-3-#68-text-parsing-chunk-storage.md
@Gimini-3
Gimini-3 merged commit cd61fa5 into develop Jul 29, 2026
1 check passed
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] 텍스트 파싱 및 Chunk 저장

1 participant