Skip to content

refactor: handle 트랜잭션 제거 및 SessionPersistenceService 분리#70

Merged
Boyeon-Shin merged 1 commit into
mainfrom
refactor/transactional-boundary
May 5, 2026
Merged

refactor: handle 트랜잭션 제거 및 SessionPersistenceService 분리#70
Boyeon-Shin merged 1 commit into
mainfrom
refactor/transactional-boundary

Conversation

@Boyeon-Shin
Copy link
Copy Markdown
Collaborator

📝 작업 내용 (Description)

handle 트랜잭션 제거 및 SessionPersistenceService 분리

🔄 변경 유형 (Type of Change)

  • ✨ 새로운 기능 (feat)
  • 🐛 버그 수정 (fix)
  • 📝 문서 수정 (docs)
  • 💄 스타일 (style)
  • ♻️ 리팩토링 (refactor)
  • ✅ 테스트 (test)
  • 🔧 기타 (chore)

✅ 체크리스트 (Checklist)

  • 코드가 정상적으로 동작하는지 확인했습니다
  • 기존 테스트가 통과합니다
  • 필요한 경우 새로운 테스트를 추가했습니다

@Boyeon-Shin Boyeon-Shin self-assigned this May 5, 2026
@Boyeon-Shin Boyeon-Shin merged commit e5b9f2f into main May 5, 2026
3 checks passed
Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request refactors the session completion and failure logic by introducing a new SessionPersistenceService and removing the @Transactional annotation from the asynchronous AllAnalysisCompletedHandler.handle method. The review identifies a critical concurrency risk where multiple threads could simultaneously pass state checks and trigger redundant, expensive feedback generation. Furthermore, the feedback suggests improving data integrity by passing session IDs to the persistence service and reloading entities within the transaction to prevent overwriting changes and to utilize JPA's dirty checking mechanism.

@Async("videoTaskExecutor")
@EventListener
@Transactional
public void handle(AllAnalysisCompletedEvent event) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

handle 메서드에서 @transactional이 제거되고 @async로 동작함에 따라, 여러 답변이 동시에 완료될 경우 isFinalFeedbackReady 체크를 여러 스레드가 동시에 통과할 가능성이 있습니다. 이로 인해 비용이 많이 드는 feedbackGenerator.generateFinal() 호출이 중복으로 발생하고, 최종 결과가 여러 번 저장되거나 SSE 이벤트가 중복 전송될 수 있습니다. 세션의 상태를 '분석 중' 등의 중간 상태로 변경하여 원자적으로 확인하거나, 분산 락 등을 고려하여 중복 실행을 방지하는 것이 좋습니다.

Comment on lines +1 to +26
package io.wisoft.prepair.prepair_api.interview.session.service;

import io.wisoft.prepair.prepair_api.interview.session.entity.InterviewSession;
import io.wisoft.prepair.prepair_api.interview.session.repository.SessionRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class SessionPersistenceService {

private final SessionRepository sessionRepository;

@Transactional
public void saveCompletedSession(InterviewSession session, int finalScore, String finalFeedback) {
session.complete(finalScore, finalFeedback);
sessionRepository.save(session);
}

@Transactional
public void saveFailedSession(InterviewSession session) {
session.fail();
sessionRepository.save(session);
}
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

준영속 상태의 엔티티를 save()(merge)하는 방식은 AI 분석과 같은 긴 작업 도중 다른 트랜잭션에 의해 변경된 데이터를 덮어쓸 위험이 있습니다. UUID를 전달받아 트랜잭션 내에서 엔티티를 다시 조회하고 상태를 변경하는 것이 더 안전합니다. 또한, 영속성 컨텍스트의 변경 감지(Dirty Checking) 기능을 활용하면 명시적인 save() 호출 없이도 변경 사항을 반영할 수 있습니다.

package io.wisoft.prepair.prepair_api.interview.session.service;

import io.wisoft.prepair.prepair_api.interview.session.entity.InterviewSession;
import io.wisoft.prepair.prepair_api.interview.session.entity.SessionStatus;
import io.wisoft.prepair.prepair_api.interview.session.repository.SessionRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

@Service
@RequiredArgsConstructor
public class SessionPersistenceService {

    private final SessionRepository sessionRepository;

    @Transactional
    public void saveCompletedSession(UUID sessionId, int finalScore, String finalFeedback) {
        InterviewSession session = sessionRepository.findById(sessionId)
                .orElseThrow(() -> new IllegalArgumentException("존재하지 않는 세션입니다."));

        if (session.getStatus() == SessionStatus.COMPLETED) {
            return;
        }

        session.complete(finalScore, finalFeedback);
    }

    @Transactional
    public void saveFailedSession(UUID sessionId) {
        InterviewSession session = sessionRepository.findById(sessionId)
                .orElseThrow(() -> new IllegalArgumentException("존재하지 않는 세션입니다."));

        if (session.getStatus() != SessionStatus.IN_PROGRESS) {
            return;
        }

        session.fail();
    }
}


session.complete(data.finalScore(), finalResult.finalFeedback());
sessionRepository.save(session);
sessionPersistenceService.saveCompletedSession(session, data.finalScore(), finalResult.finalFeedback());
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

SessionPersistenceService의 메서드 시그니처 변경에 맞춰 sessionId를 전달하도록 수정합니다.

Suggested change
sessionPersistenceService.saveCompletedSession(session, data.finalScore(), finalResult.finalFeedback());
sessionPersistenceService.saveCompletedSession(sessionId, data.finalScore(), finalResult.finalFeedback());

InterviewSession session = answer.getInterviewQuestion().getInterviewSession();
session.fail();
sessionRepository.save(session);
sessionPersistenceService.saveFailedSession(session);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

SessionPersistenceService의 메서드 시그니처 변경에 맞춰 sessionId를 전달하도록 수정합니다.

Suggested change
sessionPersistenceService.saveFailedSession(session);
sessionPersistenceService.saveFailedSession(session.getId());

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.

1 participant