단일 HTTP 업로드가 불가능한 크기의 AI 모델 파일을, 재개 가능한 청크 전송과 스트리밍 무결성 검증으로 처리한 기록입니다.
사내 RAG AI 제품에서 추론 서버로 Triton Inference Server를 쓰고 있었습니다. 여기에 올릴 LLM·임베딩 모델 파일을 관리자가 업로드할 수 있는 API가 필요했습니다.
LLM 모델 파일은 크기가 기본 기가바이트 단위입니다. 단일 multipart/form-data 업로드 요청으로 처리하기에는 택도 없었습니다.
여기에 모델 목록·버전·태그를 Triton과 일관되게 관리해야 한다는 요구가 붙었습니다. 초기 설계와 구현을 맡았습니다.
이 글에서 사내 제품명은 "사내 RAG AI 제품"으로 표기했습니다. 이 프로젝트는 업무 분장 변경으로 중단되었고, 파일 업로드 파이프라인까지 완성된 상태입니다.
청크 업로드 자체는 잘 알려진 패턴입니다. start → chunk × N → complete. 실제로 고민이 필요했던 건 업로드 진행 상태를 어디에 두느냐였습니다.
| 방식 | 재개 가능 | 정합성 | 구현 비용 | 채택 |
|---|---|---|---|---|
| DB에 업로드된 청크 인덱스 기록 | 가능 | 청크 파일과 어긋날 수 있음 | 중간 | ✗ |
| 파일 시스템만 확인 | 가능 | 항상 정확 | 낮음 | ✓ (진행 상태) |
| 메모리(세션)에 유지 | 재시작 시 소실 | 나쁨 | 최소 | ✗ |
그래서 진행 상태의 단일 출처를 파일 시스템으로 잡았습니다. "37번 청크가 있는가"는 그 경로에 파일이 있는지 보면 됩니다. DB에는 재구성할 수 없는 메타데이터(파일명, 전체 크기, 총 청크 수, 기대 해시값, 상태)만 둡니다. 이렇게 하니 complete 시점의 누락 검사가 단순해졌습니다.
청크 크기를 고정값으로 두면 양쪽에서 문제가 생깁니다. 작게 잡으면 수십 GB 파일에서 청크가 수만 개가 되어 요청 오버헤드가 전송 시간을 지배합니다. 크게 잡으면 100MB짜리 파일도 거대한 요청 하나로 올라갑니다.
그래서 파일 크기 구간별로 청크 크기를 계산하도록 했습니다. 상한은 설정값으로 두고, 그걸 나눠 쓰는 방식입니다. 인프라(프록시 제한)가 바뀌면 상한 하나만 조정하면 됩니다.
def get_optimal_chunk_size(file_size: int | None) -> int:
if file_size is None:
return MIN_CHUNK_SIZE_BYTE
if file_size < mb_to_bytes(100): # 100MB 미만은 작게 쪼갤 이유가 없다
return MIN_CHUNK_SIZE_BYTE
elif file_size < mb_to_bytes(1024): # 1GB 미만
return int(max(mb_to_bytes(settings.MAX_CHUNK_SIZE_MB) / 8, MIN_CHUNK_SIZE_BYTE * 2))
elif file_size < gb_to_bytes(10): # 10GB 미만
return int(max(mb_to_bytes(settings.MAX_CHUNK_SIZE_MB) / 2, MIN_CHUNK_SIZE_BYTE))
else: # 10GB 이상은 상한까지 키운다
return mb_to_bytes(settings.MAX_CHUNK_SIZE_MB)
start 엔드포인트가 이 값을 계산해 돌려주고, 클라이언트는 그 크기로 파일을 잘라 보냅니다. 총 청크 수와 기대 해시값도 이때 함께 등록합니다.
중단한 업로드를 이어붙이려면 서버가 "어디까지 받았는지"를 알고 있어야 합니다. 같은 파일 식별자로 다시 들어온 요청은 기존 상태를 찾아 이어받습니다.
existing_file_model = next(
(f for f in await get_files_by_model_version_id(session, file_create.model_version_id)
if f.name == file_create.name), None)
if existing_file_model:
if existing_file_model.status in [FileStatus.READY, FileStatus.HASH_FAILED]:
# 이미 끝난 파일에 대한 재요청 → 교체로 본다. 새 레코드를 만든다
file_model = FileModel(id=uuid.uuid4(), name=file_create.name,
model_version_id=file_create.model_version_id,
file_size=file_create.file_size,
chunk_size=file_create.chunk_size,
total_chunks=file_create.total_chunks,
status=FileStatus.CREATED, hash_algo="sha256",
hash_value=file_create.hash_value)
await create_file_model(session, file_model)
else:
# 업로드 중이던 파일에 대한 재요청 → 재개. 기존 청크를 살린다
file_model = existing_file_model
if _metadata_changed(file_model, file_create):
# 클라이언트가 청크 크기를 다시 계산해 온 경우 메타데이터만 갱신
await update_file_model(session, file_model.id, **file_create.model_dump(),
status=FileStatus.CREATED)
await session.commit()
상태 값을 세밀하게 쪼갠 것도 의도적입니다. 업로드는 여러 단계를 거치고, 각 단계의 실패가 서로 다른 복구 동작을 요구합니다. hash_failed는 재전송이 필요하고, extract_failed는 파일은 온전하니 압축 해제만 재시도하면 됩니다. 이걸 failed 하나로 묶으면 재시도 API를 만들 수 없습니다.
class FileStatus:
CREATED = "created" # 업로드 준비 완료
UPLOADING = "uploading" # 청크 수신 중
VERIFYING = "verifying" # 병합 후 해시 검증 중
EXTRACTING = "extracting" # 압축 해제 중
READY = "ready" # 사용 가능
HASH_FAILED = "hash_failed" # 전송 손상 → 재전송 필요
EXTRACT_FAILED = "extract_failed" # 파일은 온전, 해제만 재시도 가능
INTEGRITY_FAILED = "integrity_failed" # 사후 무결성 검사 실패
complete에서 청크를 합칩니다. 여기서 절대 하지 말아야 할 일이 전체 파일을 메모리에 올리는 것입니다. 청크를 하나씩 읽어 최종 파일에 이어 쓰는 방식으로, 상주 메모리를 청크 하나 크기로 제한했습니다.
async def merge_chunks(file_id: UUID, total_chunks: int,
final_file_path: str, filename: str | None = None) -> bool:
os.makedirs(os.path.dirname(final_file_path), exist_ok=True)
async with aiofiles.open(final_file_path, "wb") as final_file:
for chunk_index in range(total_chunks):
chunk_path = get_chunk_upload_path(file_id, chunk_index, filename)
if not os.path.exists(chunk_path):
logger.error(f"Chunk {chunk_index} not found at {chunk_path}")
return False
# 한 번에 청크 하나만 메모리에 둔다
async with aiofiles.open(chunk_path, "rb") as chunk_file:
await final_file.write(await chunk_file.read())
return True
해시 검증도 같은 원칙입니다. 8KB 단위로 읽어 해시 객체에 밀어 넣습니다. 수십 GB 파일도 상수 메모리로 처리됩니다.
async def calculate_file_hash(file_path: str, hash_algorithm: str = "sha256") -> str:
hash_obj = hashlib.sha256() if hash_algorithm.lower() == "sha256" \\
else hashlib.new(hash_algorithm)
chunk_size = 8192 # 파일 크기와 무관하게 상수 메모리
async with aiofiles.open(file_path, "rb") as f:
while chunk := await f.read(chunk_size):
hash_obj.update(chunk)
return hash_obj.hexdigest()
async def verify_file_hash(file_path: str, expected_hash: str,
hash_algorithm: str = "sha256") -> bool:
return (await calculate_file_hash(file_path, hash_algorithm)).lower() \\
== expected_hash.lower()
검증 실패 시에는 병합된 파일을 지우고 상태를 HASH_FAILED로 바꿉니다. 손상된 파일을 남겨 두면 나중에 그게 정상 파일로 오인될 수 있습니다.
missing_chunks = [i for i in range(file_model.total_chunks)
if not os.path.exists(get_chunk_upload_path(file_id, i, file_model.name))]
if missing_chunks:
# 어느 청크가 없는지 알려줘야 클라이언트가 그것만 다시 보낼 수 있다
raise HTTPException(status_code=400, detail=f"Missing chunks: {sorted(missing_chunks)}")
이 응답을 실제로 확인하려면 청크를 일부러 빼고 보내야 합니다. 그래서 실패를 주입할 수 있는 검증용 클라이언트를 따로 만들었습니다.
모델 파일은 대부분 압축된 형태로 옵니다. ZIP, TAR, TAR.GZ, TGZ를 자동 해제하도록 했는데, 여기서 보안 문제를 만났습니다. 압축 파일 내부의 엔트리 경로는 공격자가 통제할 수 있는 입력입니다. ../../etc/passwd 같은 경로가 들어 있으면 해제 대상 디렉터리를 벗어나 파일을 씁니다.
정규화를 여러 단계로 넣었습니다. 구분자 통일, 절대 경로 제거, .. 세그먼트 해소, 그리고 마지막에 결과 경로가 해제 디렉터리 안에 있는지 절대 경로로 재확인합니다. 앞 단계의 정규화에 구멍이 있어도 마지막 확인이 막습니다.
def sanitize_archive_path(file_path: str, extract_path: str) -> str:
normalized_path = file_path.replace("\\\\", "/") # 구분자 통일
if normalized_path.startswith("/"): # Unix 절대 경로
normalized_path = normalized_path.lstrip("/")
elif len(normalized_path) > 1 and normalized_path[1] == ":": # Windows 절대 경로
normalized_path = os.path.basename(normalized_path)
if ".." in normalized_path: # 상위 이동 시도 해소
path_parts = []
for part in normalized_path.split("/"):
if part == "..":
if path_parts:
path_parts.pop()
elif part and part != ".":
path_parts.append(part)
normalized_path = "/".join(path_parts)
if not normalized_path or normalized_path == ".":
normalized_path = os.path.basename(file_path) or "extracted_file"
# 최종 방어선 — 절대 경로로 변환해 해제 디렉터리 밖을 가리키는지 확인
extract_abs = os.path.abspath(extract_path)
target_abs = os.path.abspath(os.path.join(extract_path, normalized_path))
if not target_abs.startswith(extract_abs + os.sep) and target_abs != extract_abs:
raise Exception(f"Path traversal detected: {file_path} -> {normalized_path}")
return normalized_path
상태의 단일 출처를 어디로 할지 먼저 정해야 한다는 걸 배웠습니다. 진행 상태를 DB와 파일 시스템 양쪽에 두려다가, 둘이 어긋날 때의 복구 로직이 본체보다 복잡해지는 걸 보고 방향을 바꿨습니다. 파일 시스템 하나로 정하고 나서는 누락 검사·재개·진행률 조회가 모두 같은 질문으로 환원됐습니다. 상태 값을 세밀하게 나눈 것도 마찬가지입니다. failed 하나로 묶으면 "다시 올려야 하나요"에 답할 수 없는데, 실패 이유를 상태로 표현하면 복구 경로가 API로 드러납니다. 최종 파일을 로컬 디스크에 둔 구조라 수평 확장 경로가 없다는 게 가장 큰 미완입니다.