Skip to content

[fix] LLM 재시도 시 토큰이 누적되지 않던 문제 해결 - #67

Merged
theminjunchoi merged 2 commits into
devfrom
fix/66-retry-token-accumulation
Jul 30, 2026
Merged

[fix] LLM 재시도 시 토큰이 누적되지 않던 문제 해결#67
theminjunchoi merged 2 commits into
devfrom
fix/66-retry-token-accumulation

Conversation

@theminjunchoi

@theminjunchoi theminjunchoi commented Jul 29, 2026

Copy link
Copy Markdown
Collaborator

🔗 연관 이슈

📌 문제

LLM 생성은 파싱/검증 실패 시 최대 2회 재시도하는데, generation_log한 시도의 토큰만 기록되어 재시도로 소모된 토큰이 누락됨 → 비용 집계·유저 일일 토큰 상한이 모두 과소 집계.

  • 성공(1차 실패→2차 성공): output.usedTokens(2차만) 기록 → 1차 과금 토큰 소실
  • 전 시도 실패: lastError?.usedTokens(마지막만) 기록 → 이전 시도 토큰 소실

🔧 변경

  • TokenUsageAccumulator 도입 — 시도별 토큰(성공은 output, 실패는 예외에 실린 토큰; 호출 자체 실패면 null→0)을 합산.
  • generateWithRetry / generateReplyWithRetry: 모든 시도의 토큰을 누적해 성공·최종실패·재시도불가 로그 모두 누적값으로 기록.
  • 카드 경로(CardService)는 재시도 없음(단일 호출) → 변경 없음.

🧪 테스트

  • TokenUsageAccumulatorTest: 성공+실패 누적, null→0.
  • 서비스: 1차 실패→2차 성공 = 합산(300) 기록, 양쪽 실패 = 합산(300) 실패 로그 검증.
  • 전체 백엔드 테스트 통과.

스코프

  • generation_log(비용·일일한도 집계) 정확성만 수정. 앱 응답의 GenerationResult.usedTokens(성공 시도 표시값)는 그대로.

🌐 API · DB 영향

  • API 변경: 없음. DB: 없음(기록 값 정확도만 개선).

Summary by CodeRabbit

  • 개선 사항

    • AI 댓글 및 답변 생성 재시도 과정에서 모든 시도의 토큰 사용량을 합산해 기록합니다.
    • 성공한 시도뿐 아니라 실패한 시도의 토큰 사용량도 통계에 반영됩니다.
    • 재시도 횟수와 성공 여부가 누적 토큰 사용량과 함께 정확히 기록됩니다.
  • 버그 수정

    • 일부 재시도 또는 검증 실패 시 토큰 사용량이 누락되던 문제를 개선했습니다.
    • 토큰 정보가 없는 실패 상황에서도 사용량이 안정적으로 처리됩니다.

재시도(다중 LLM 호출) 시 성공/최종실패 로그에 한 시도의 토큰만 남겨 재시도로
소모된 토큰이 누락됐다(비용·일일 상한 과소 집계). 시도별 토큰을 합산하는
TokenUsageAccumulator 를 도입해, 모든 시도(성공+실패)의 토큰을 최종 로그에 누적한다.
누산기 단위 테스트와, 1차 실패→2차 성공 및 양쪽 실패 시 두 시도 토큰이
합산 기록되는지 검증하는 서비스 테스트를 추가한다.
@coderabbitai

coderabbitai Bot commented Jul 29, 2026

Copy link
Copy Markdown

Review Change Stack

Walkthrough

LLM 댓글·답글 생성의 재시도별 성공 및 실패 토큰을 TokenUsageAccumulator로 합산하고, 최종 생성 로그에 누적값을 기록하도록 변경했습니다. 누적기와 성공·실패 재시도 시나리오 테스트도 추가했습니다.

Changes

재시도 토큰 집계

Layer / File(s) Summary
토큰 누적기 계약과 검증
src/main/kotlin/.../TokenUsageAccumulator.kt, src/test/kotlin/.../TokenUsageAccumulatorTest.kt
성공 출력과 실패 예외의 used/cached/input/output 토큰을 합산하며, null 토큰은 0으로 처리합니다.
댓글·답글 재시도 로깅 통합
src/main/kotlin/.../CommentGenerationService.kt, src/test/kotlin/.../CommentGenerationServiceTest.kt
generateWithRetrygenerateReplyWithRetry가 모든 시도의 토큰을 누적해 성공·실패 로그에 기록하며, 2회 재시도 결과를 검증합니다.

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

Sequence Diagram(s)

sequenceDiagram
  participant CommentGenerationService
  participant LLM
  participant GenerationLogRecorder
  loop 재시도
    CommentGenerationService->>LLM: 생성 요청
    LLM-->>CommentGenerationService: 출력 또는 실패 예외
    CommentGenerationService->>CommentGenerationService: 토큰 누적
  end
  CommentGenerationService->>GenerationLogRecorder: 누적 토큰 및 결과 기록
Loading

Possibly related PRs

Suggested reviewers: kite707

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed 재시도 시 모든 시도의 토큰을 누적해 최종 로그에 반영하므로 #66의 핵심 요구를 충족합니다.
Out of Scope Changes check ✅ Passed 재시도 누적 로직과 누산기·테스트 추가만 보이며 목적과 무관한 변경은 보이지 않습니다.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed 태그와 내용이 실제 변경사항(LLM 재시도 토큰 누적 문제 수정)을 명확히 담아 제목 규칙과 목적에 부합합니다.
Description check ✅ Passed 연관 이슈, 문제·변경·테스트·API/DB 영향이 포함돼 있어 충분히 구체적이며, 템플릿과 대체로 맞습니다.
✨ 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/66-retry-token-accumulation

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.

@github-actions

Copy link
Copy Markdown

Test Results

303 tests  +4   303 ✅ +4   1m 20s ⏱️ +4s
 50 suites +1     0 💤 ±0 
 50 files   +1     0 ❌ ±0 

Results for commit 83688c2. ± Comparison against base commit 9a19962.

@github-actions

Copy link
Copy Markdown

Test Coverage

Overall Project 73.22% -0.19% 🍏
Files changed 87.3% 🍏

File Coverage
TokenUsageAccumulator.kt 100% 🍏
CommentGenerationService.kt 84.06% -2.22% 🍏

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

🤖 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/test/kotlin/com/nexters/gamss/conversation/service/CommentGenerationServiceTest.kt`:
- Around line 180-249: CommentGenerationServiceTest의 기존 토큰 누적 검증에 답글 재시도 경로를
추가하세요. generateReplyWithRetry에서 첫 시도 검증 실패 후 두 번째 시도 성공하는 경우, 두 시도의 토큰 합계와 성공
로그를 검증하고, 첫 시도 후 재시도할 수 없는 일반 예외로 즉시 종료되는 경우에도 누적 토큰과 실패 로그가 기록되는지 검증하세요.
🪄 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: ASSERTIVE

Plan: Pro Plus

Run ID: 5a51d731-da59-4b78-a1e1-d652821a44c3

📥 Commits

Reviewing files that changed from the base of the PR and between 9a19962 and 83688c2.

📒 Files selected for processing (4)
  • src/main/kotlin/com/nexters/gamss/conversation/service/CommentGenerationService.kt
  • src/main/kotlin/com/nexters/gamss/conversation/service/TokenUsageAccumulator.kt
  • src/test/kotlin/com/nexters/gamss/conversation/service/CommentGenerationServiceTest.kt
  • src/test/kotlin/com/nexters/gamss/conversation/service/TokenUsageAccumulatorTest.kt

@theminjunchoi theminjunchoi changed the title [fix] LLM 재시도 시 토큰이 누적되지 않아 비용·일일 상한이 과소 집계됨 [fix] LLM 재시도 시 토큰이 누적되지 않던 문제 해결 Jul 29, 2026
@theminjunchoi
theminjunchoi requested a review from kite707 July 29, 2026 18:04

@kite707 kite707 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

작업하느라 고생하셨습니다!

처음에는 CommentGenerationFailedException에 대해서만 addFailed를 호출할 수 있는 점이 우려되었는데, 코드를 확인해보니 어떤 경우든 응답 만들기에 실패하면 위 에러가 발생하기 때문에 문제 없을 듯 합니다!

@theminjunchoi
theminjunchoi merged commit 54d75ab into dev Jul 30, 2026
6 checks passed
@theminjunchoi
theminjunchoi deleted the fix/66-retry-token-accumulation branch July 30, 2026 05:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[fix] LLM 재시도 시 토큰이 누적되지 않아 비용·일일 상한이 과소 집계됨

2 participants