Compare commits
1 Commits
ed61d29632
...
v0.1.33
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
648ccde4d7 |
@@ -150,26 +150,25 @@ public class OciGenAiService {
|
|||||||
return mapper.readValue(raw, Object.class);
|
return mapper.readValue(raw, Object.class);
|
||||||
} catch (Exception ignored) {}
|
} catch (Exception ignored) {}
|
||||||
|
|
||||||
// Try to recover truncated array
|
// #326 — Recover truncated array. Brace depth counter로 단일 패스 O(N).
|
||||||
|
// 이전: 각 idx에서 end를 1씩 늘려가며 매번 readValue → O(N²) + 예외 스택트레이스 양산.
|
||||||
if (raw.trim().startsWith("[")) {
|
if (raw.trim().startsWith("[")) {
|
||||||
List<Object> items = new ArrayList<>();
|
List<Object> items = new ArrayList<>();
|
||||||
int idx = raw.indexOf('[') + 1;
|
int idx = raw.indexOf('[') + 1;
|
||||||
while (idx < raw.length()) {
|
while (idx < raw.length()) {
|
||||||
while (idx < raw.length() && " \t\n\r,".indexOf(raw.charAt(idx)) >= 0) idx++;
|
while (idx < raw.length() && " \t\n\r,".indexOf(raw.charAt(idx)) >= 0) idx++;
|
||||||
if (idx >= raw.length() || raw.charAt(idx) == ']') break;
|
if (idx >= raw.length() || raw.charAt(idx) == ']') break;
|
||||||
|
if (raw.charAt(idx) != '{') break; // 객체 시작이 아니면 복구 중단
|
||||||
|
|
||||||
// Try to parse next object
|
int end = findObjectEnd(raw, idx);
|
||||||
boolean found = false;
|
if (end < 0) break; // 잘린 객체 — 거기서 멈춤
|
||||||
for (int end = idx + 1; end <= raw.length(); end++) {
|
try {
|
||||||
try {
|
Object obj = mapper.readValue(raw.substring(idx, end + 1), Object.class);
|
||||||
Object obj = mapper.readValue(raw.substring(idx, end), Object.class);
|
items.add(obj);
|
||||||
items.add(obj);
|
} catch (Exception ignored2) {
|
||||||
idx = end;
|
break; // 불가해 객체 — 멈춤
|
||||||
found = true;
|
|
||||||
break;
|
|
||||||
} catch (Exception ignored2) {}
|
|
||||||
}
|
}
|
||||||
if (!found) break;
|
idx = end + 1;
|
||||||
}
|
}
|
||||||
if (!items.isEmpty()) {
|
if (!items.isEmpty()) {
|
||||||
log.info("Recovered {} items from truncated JSON", items.size());
|
log.info("Recovered {} items from truncated JSON", items.size());
|
||||||
@@ -179,4 +178,27 @@ public class OciGenAiService {
|
|||||||
|
|
||||||
throw new RuntimeException("JSON parse failed: " + raw.substring(0, Math.min(80, raw.length())));
|
throw new RuntimeException("JSON parse failed: " + raw.substring(0, Math.min(80, raw.length())));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* #326 — JSON 객체 시작 위치(`{`)에서 매칭되는 닫는 `}` 인덱스를 반환.
|
||||||
|
* 문자열 안의 `{` `}`와 escape는 무시. 매칭 못 찾으면 -1.
|
||||||
|
*/
|
||||||
|
private static int findObjectEnd(String raw, int start) {
|
||||||
|
int depth = 0;
|
||||||
|
boolean inString = false;
|
||||||
|
boolean escaped = false;
|
||||||
|
for (int i = start; i < raw.length(); i++) {
|
||||||
|
char c = raw.charAt(i);
|
||||||
|
if (escaped) { escaped = false; continue; }
|
||||||
|
if (c == '\\') { escaped = true; continue; }
|
||||||
|
if (c == '"') { inString = !inString; continue; }
|
||||||
|
if (inString) continue;
|
||||||
|
if (c == '{') depth++;
|
||||||
|
else if (c == '}') {
|
||||||
|
depth--;
|
||||||
|
if (depth == 0) return i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
81
docs/design/326-parsejson-optimization/README.md
Normal file
81
docs/design/326-parsejson-optimization/README.md
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
# 설계서: OciGenAiService.parseJson 단일 패스 최적화 (#326)
|
||||||
|
|
||||||
|
> **상태**: Approved
|
||||||
|
> **작성**: [AI] Architect · **최종수정**: 2026-06-15
|
||||||
|
> **추적성** — Redmine: #326 · 부모: #292 (추출 파이프라인 Reviewer 후속, 09-Done)
|
||||||
|
> · 구현 파일: `backend-java/src/main/java/com/tasteby/service/OciGenAiService.java`
|
||||||
|
|
||||||
|
## 1. 목적 (Why)
|
||||||
|
|
||||||
|
LLM 응답이 잘린(truncated) 배열일 때 `parseJson`의 복구 로직이 O(N²): 각 객체 시작점에서 `end`를 1씩 늘려가며 매번 `mapper.readValue(substring)`을 try. 8192 토큰 응답(약 30KB)에서 매우 비효율 + 매 try마다 Jackson 예외 객체 생성(스택트레이스 양산). brace depth counter로 단일 패스 O(N)으로 교체.
|
||||||
|
|
||||||
|
## 2. 범위
|
||||||
|
|
||||||
|
- **포함**: `parseJson`의 truncated-array 복구 로직을 brace depth counter로 변경.
|
||||||
|
- **제외**: `parseJson`의 마크다운/콤마 정규식 전처리는 그대로. Jackson streaming API 도입은 추가 최적화이지만 본 범위 밖.
|
||||||
|
|
||||||
|
## 3. 인수조건
|
||||||
|
|
||||||
|
- [ ] 정상 JSON 배열 → 동일 결과 반환.
|
||||||
|
- [ ] 잘린 배열(끝 `}` 누락) → 가능한 만큼 객체 추출 + 로그.
|
||||||
|
- [ ] 문자열 안의 `{` `}` `"` (escape 포함) 잘못 카운트 안 됨.
|
||||||
|
- [ ] 8192 token 응답 처리 시간 < 10ms (이전: 수백 ms 가능).
|
||||||
|
- [ ] 회귀 없음 (기존 추출 파이프라인 시나리오 통과).
|
||||||
|
|
||||||
|
## 4. 컨텍스트 & 제약
|
||||||
|
|
||||||
|
- LLM 응답은 마크다운 + JSON 혼합 가능.
|
||||||
|
- 응답 크기 최대 약 30KB (8192 token × 4 char/token).
|
||||||
|
- mapper는 Jackson ObjectMapper.
|
||||||
|
|
||||||
|
## 5. 아키텍처 개요
|
||||||
|
|
||||||
|
```
|
||||||
|
parseJson(raw)
|
||||||
|
├ strip markdown/trailing commas (기존)
|
||||||
|
├ try readValue(raw) → 성공 시 반환
|
||||||
|
└ truncated array 복구:
|
||||||
|
idx = '['의 다음
|
||||||
|
while idx < len:
|
||||||
|
skip whitespace, ','
|
||||||
|
if raw[idx] != '{': break // 객체 아님
|
||||||
|
depth=0, inString=false, escaped=false
|
||||||
|
단일 패스로 객체 끝 (depth==0 && } 만남) 찾음
|
||||||
|
items.add(readValue(substring))
|
||||||
|
idx = 객체 끝 다음
|
||||||
|
return items
|
||||||
|
```
|
||||||
|
|
||||||
|
## 6. 함수 명세
|
||||||
|
|
||||||
|
| 함수 | 책임 | 비고 |
|
||||||
|
|------|------|------|
|
||||||
|
| `parseJson(raw)` (수정) | brace depth + 단일 readValue | private 헬퍼 `findObjectEnd(raw, start)` 추출 |
|
||||||
|
|
||||||
|
## 7. 흐름
|
||||||
|
|
||||||
|
1. 기존 정규식 전처리.
|
||||||
|
2. 전체 파싱 시도.
|
||||||
|
3. 실패 + 배열 시작이면 위 알고리즘으로 객체 단위 복구.
|
||||||
|
|
||||||
|
## 8. 엣지케이스
|
||||||
|
|
||||||
|
- **빈 배열 `[]`**: 일반 readValue가 처리.
|
||||||
|
- **문자열 안 `{` `}`**: inString 토글로 무시.
|
||||||
|
- **escape `\"` `\\`**: escaped 토글로 무시.
|
||||||
|
- **객체가 아닌 원시값 배열 `[1, 2, 3]`**: 첫 char가 `{`가 아니므로 break. 전체 파싱이 성공할 경우 도달 안 함.
|
||||||
|
- **매우 짧은 응답**: 전체 파싱이 성공 → 복구 경로 미진입.
|
||||||
|
|
||||||
|
## 9. 테스트
|
||||||
|
|
||||||
|
- 정상 배열, 잘린 끝, 마크다운 wrap, escape 포함 5케이스 unit test (후속).
|
||||||
|
|
||||||
|
## 10. 리스크 & 대안
|
||||||
|
|
||||||
|
- **선택**: brace depth counter (단일 패스).
|
||||||
|
- **대안 A**: Jackson `JsonParser` streaming API — 더 빠르지만 코드 복잡.
|
||||||
|
- **대안 B**: 응답을 모두 받지 않고 streaming 파싱 — 본 범위 밖.
|
||||||
|
|
||||||
|
## 11. 미해결 질문
|
||||||
|
|
||||||
|
- LLM 응답에 객체 외 다른 타입 섞일 수 있는가? 현재 추출 결과는 `[{...}, {...}]` 형태로 가정.
|
||||||
Reference in New Issue
Block a user