Skip to content

Commit a493011

Browse files
committed
수정: reference가 대조 불가를 0% 매칭으로 보고하지 않게 한다
1 parent e6fb0fc commit a493011

4 files changed

Lines changed: 151 additions & 2 deletions

File tree

‎mainPlan/v1-readiness-review/01-verdict-ledger.md‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2099,3 +2099,50 @@ production 호출자가 0 이라 이번 순서에서 다루지 않고 별도 항
20992099
`riskPremiums.loadDamodaranERP` 의 `source` 가 항상 상수이고 문서가 약속한 parquet
21002100
경로가 미구현인 것, 지원 국가 수 표기(90+ vs 실제 14)도 같은 항목이다.
21012101
다음 체크포인트는 L1.5 reference 다.
2102+
2103+
### L1.5 reference 대조 불가 표면화·매핑 SSOT 체크포인트: 완료 (2026-07-31)
2104+
2105+
범위는 `reference/docs/bridge.py` 와 `reference/mappers/accountMapper.py`, 그리고
2106+
실제 소비자인 server analysis API(`/api/company/{code}/topics/verify` 경로)와 매핑
2107+
호출자다. `reference/mapping/*` 운영 CLI, `reference/render/*` 재수출, capability
2108+
builder 는 전수 대조에서 이번 계약 밖이거나 이미 정직해 결함이 아니었다.
2109+
2110+
제품 결함은 실패가 사실 주장으로 바뀌는 것이었다. `getFinanceAmounts` 는 IS·BS·CF 세 장을
2111+
모두 못 읽어도 빈 dict 를 돌려줬고, 소비자 API 는 그 결과로
2112+
`matchRate = matched / max(extracted, 1)` 을 계산해 `matchRate: 0.0` 을 응답했다.
2113+
클라이언트에게 이 값은 "공시 본문 금액이 재무제표와 하나도 맞지 않는다" 는 경보성 결론이며,
2114+
대조 자체가 불가능했던 상황과 구분되지 않는다. 하필 회계 신뢰성을 점검하려고 부르는
2115+
자리다. 같은 파일 주석에 이 함수가 예전에 통째로 무력했던 사고가 이미 기록돼 있었다.
2116+
2117+
두 번째는 매핑 SSOT 분기다. `accountMapper` 는 모듈 docstring 에서 "매칭 로직은
2118+
`core.accounts.AccountNormalizer` 한 곳이 소유하며 같은 사전 위 두 매칭 분산은 SSOT
2119+
위반" 이라고 선언해 놓고, `korToSnakeId` 가 그 normalizer 를 우회한 raw dict 조회였다.
2120+
`lookup` 이 흡수하는 공백·괄호·하이픈 변형과 synonym 을 `korToSnakeId` 는 `None` 으로
2121+
돌려줘 같은 한글명이 경로에 따라 다르게 해소됐다.
2122+
2123+
근본 원인은 각각 "실패와 0 을 같은 모양으로 반환한 것" 과 "선언한 단일 소유자를 우회한
2124+
두 번째 매칭 경로" 다.
2125+
2126+
수정은 두 곳이다. `getFinanceAmounts` 는 재무를 한 장도 읽지 못했거나 대조할 기간이
2127+
없으면 원인을 담은 `RuntimeError` 를 올린다. `RuntimeError` 는 server 의
2128+
`HANDLED_API_ERRORS` 에 이미 포함돼 404 안내로 나가므로, 클라이언트는 "안 맞음" 대신
2129+
"대조 불가" 를 받는다. `korToSnakeId` 는 `AccountNormalizer` 로 위임해 `lookup` 과 같은
2130+
SSOT 를 쓴다.
2131+
2132+
공개 행동 실측으로 확정했다. 재무 부재(FileNotFoundError) 주입에서 이제 빈 dict 대신
2133+
"재무제표를 읽지 못해 본문 금액을 대조할 수 없습니다" 가 올라오고, 기간 불일치도 별도
2134+
사유로 구분된다. 흡수 목록 밖 I/O 실패는 그대로 전파돼 소비자가 실패로 본다. 정상 경로는
2135+
그대로 계정 금액(10억)을 돌려주고 연간 표기의 Q4 해소도 유지된다. 매핑은
2136+
`"매출액"`·`"매출"`·`"영업이익"`·`"매출 액"` 네 표기에서 `korToSnakeId` 와
2137+
`lookup.snakeId` 가 모두 일치했고, 공백이 낀 `"매출 액"` 은 수정 전 `None` 이었다.
2138+
2139+
Guard와 회귀는 통과했다. 신규 bridge 회귀 `5 passed`, 매핑 호출자 회귀 `45 passed`,
2140+
변경 2개 소스 Ruff·formatter·Pyright `0 errors, 0 warnings`,
2141+
`bridge.py` `silentSubstitute --strict` 위반 0(기존 baseline 항목이 실제로 해소됐다).
2142+
2143+
남은 부채는 다음 순서로 넘긴다. `bridge.py` 모듈 docstring 의 snake_case 예제 심볼
2144+
(`extract_amounts_from_text` 등)은 실재 심볼과 달라 복사하면 ImportError 이고,
2145+
`_parseNumber` 가 float 반환 계약에서 파싱 실패에 `0` 을 돌려주는 것(현재 소비자가
2146+
`tv == 0` 을 건너뛰어 무해)도 문서·계약 정리 항목이다. capability builder 가 import 실패한
2147+
axis registry 를 진단 없이 빠뜨리는 것은 baseline 에 있는 기존 부채다.
2148+
이로써 L1.5 네 형제(scan·frame·synth·reference) 체크포인트를 모두 닫았다.

‎src/dartlab/reference/docs/bridge.py‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,11 @@ def getFinanceAmounts(company, period: str) -> dict[str, float]:
106106
107107
sections 기간이 '2024'(연간)이면 finance에서 '2024Q4'를 찾고,
108108
'2024Q3'(분기)이면 그대로 찾는다.
109+
110+
Raises:
111+
RuntimeError: 재무제표를 한 장도 읽지 못했거나 대조할 기간이 없을 때.
112+
빈 dict 를 돌려주면 소비자가 만드는 matchRate 가 0.0 이 되어 "대조 불가"가
113+
"하나도 안 맞음"이라는 다른 사실 주장으로 바뀌므로 구분해서 올린다.
109114
"""
110115
result: dict[str, float] = {}
111116

@@ -116,13 +121,19 @@ def getFinanceAmounts(company, period: str) -> dict[str, float]:
116121
# 예전에는 `company.finance` 에서 세 장을 꺼냈다. `finance` 는 표면에서 빠진 이름이라
117122
# 매 회전이 except 로 continue 했고, 이 함수가 어느 회사에서도 빈 dict 만 냈다. 그래서
118123
# 공시 본문 금액과 재무제표를 대조하는 검증이 통째로 무력했다. 공개 계약으로 부른다.
124+
loaded = 0
125+
periodMatched = 0
126+
failures: list[str] = []
119127
for stmt_name in ("IS", "BS", "CF"):
120128
try:
121129
stmt = company.panel(stmt_name)
122-
except (AttributeError, FileNotFoundError, KeyError, RuntimeError, TypeError, ValueError):
130+
except (AttributeError, FileNotFoundError, KeyError, RuntimeError, TypeError, ValueError) as exc:
131+
failures.append(f"{stmt_name}: {type(exc).__name__}")
123132
continue
124133
if stmt is None or getattr(stmt, "height", 0) == 0:
134+
failures.append(f"{stmt_name}: 빈 재무제표")
125135
continue
136+
loaded += 1
126137

127138
target_period = None
128139
for cand in candidates:
@@ -131,6 +142,7 @@ def getFinanceAmounts(company, period: str) -> dict[str, float]:
131142
break
132143
if target_period is None:
133144
continue
145+
periodMatched += 1
134146

135147
for row in stmt.iter_rows(named=True):
136148
account = row.get("항목") or row.get("account")
@@ -141,6 +153,15 @@ def getFinanceAmounts(company, period: str) -> dict[str, float]:
141153
except (ValueError, TypeError):
142154
pass
143155

156+
# 재무를 한 장도 못 읽었거나 대조할 기간이 없으면 빈 dict 를 돌려주지 않는다.
157+
# 소비자(server analysis API)는 이 결과로 matchRate 를 만들기 때문에, 빈 dict 는
158+
# "공시 금액이 재무제표와 하나도 안 맞는다" 는 경보성 사실 주장(matchRate 0.0)이 된다.
159+
# 대조 자체가 불가능한 것과 대조해서 안 맞는 것은 다른 답이다.
160+
if loaded == 0:
161+
raise RuntimeError(f"재무제표를 읽지 못해 본문 금액을 대조할 수 없습니다 ({'; '.join(failures)})")
162+
if periodMatched == 0:
163+
raise RuntimeError(f"재무제표에 기간 {period} 이(가) 없어 본문 금액을 대조할 수 없습니다")
164+
144165
return result
145166

146167

‎src/dartlab/reference/mappers/accountMapper.py‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,10 @@ def snakeIds(self) -> list[str]:
184184
def korToSnakeId(self, korName: str) -> str | None:
185185
"""한국어 계정명 → snakeId.
186186
187+
본 모듈의 SSOT 선언대로 매칭은 ``AccountNormalizer`` 한 곳만 소유한다. 예전에는
188+
같은 사전을 raw dict 조회로 한 번 더 훑어, ``lookup`` 이 해소하는 한글명(공백·
189+
괄호·하이픈 변형, synonym, "액" 접미 흡수)을 여기서는 ``None`` 으로 돌려줬다.
190+
187191
Args:
188192
korName: Korean account name.
189193
@@ -200,7 +204,9 @@ def korToSnakeId(self, korName: str) -> str | None:
200204
>>> AccountMapper().korToSnakeId("__missing__") is None
201205
True
202206
"""
203-
return self._mappings().get(korName)
207+
from dartlab.core.accounts import AccountNormalizer
208+
209+
return AccountNormalizer.get().normalize("", korName)
204210

205211
def snakeIdToKor(self, snakeId: str) -> str | None:
206212
"""snakeId → 한국어 계정명.
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
"""reference docs bridge 의 대조 불가 표면화 계약 회귀.
2+
3+
재무제표를 못 읽은 것과 본문 금액이 재무제표와 안 맞는 것은 다른 답이다. 빈 dict 로
4+
뭉개면 소비자(server analysis API)가 matchRate 0.0 이라는 경보성 사실 주장을 낸다.
5+
"""
6+
7+
from __future__ import annotations
8+
9+
import polars as pl
10+
import pytest
11+
12+
from dartlab.reference.docs.bridge import getFinanceAmounts
13+
14+
pytestmark = pytest.mark.unit
15+
16+
17+
class _Company:
18+
"""panel 호출을 흉내내는 최소 대역."""
19+
20+
def __init__(self, frames: dict[str, object] | None = None, error: Exception | None = None):
21+
self._frames = frames or {}
22+
self._error = error
23+
24+
def panel(self, name: str):
25+
"""요청한 재무제표를 돌려주거나 주입된 실패를 낸다."""
26+
if self._error is not None:
27+
raise self._error
28+
frame = self._frames.get(name)
29+
if frame is None:
30+
raise FileNotFoundError(f"{name} 없음")
31+
return frame
32+
33+
34+
def _statement(period: str) -> pl.DataFrame:
35+
"""항목·기간 열을 가진 최소 재무제표."""
36+
return pl.DataFrame({"항목": ["매출액"], period: [1_000_000_000.0]})
37+
38+
39+
def testAllStatementsUnreadableRaises() -> None:
40+
"""세 장을 모두 못 읽으면 빈 dict 가 아니라 RuntimeError 다 (결함 회귀).
41+
42+
panel artifact 부재(FileNotFoundError)는 이 함수가 흡수하던 대표 경로다.
43+
"""
44+
with pytest.raises(RuntimeError, match="읽지 못해"):
45+
getFinanceAmounts(_Company(error=FileNotFoundError("panel 없음")), "2024")
46+
47+
48+
def testUnhandledIoErrorPropagates() -> None:
49+
"""흡수 목록 밖 I/O 실패는 그대로 전파된다 (소비자가 실패로 본다)."""
50+
with pytest.raises(OSError, match="disk"):
51+
getFinanceAmounts(_Company(error=OSError("disk")), "2024")
52+
53+
54+
def testMissingPeriodRaises() -> None:
55+
"""재무는 읽었지만 대조할 기간이 없으면 0% 매칭이 아니라 실패다."""
56+
company = _Company({"IS": _statement("2019Q4"), "BS": _statement("2019Q4"), "CF": _statement("2019Q4")})
57+
58+
with pytest.raises(RuntimeError, match="기간"):
59+
getFinanceAmounts(company, "2024")
60+
61+
62+
def testReadableStatementsReturnAmounts() -> None:
63+
"""정상 경로는 그대로 계정 금액을 돌려준다 (회귀 가드)."""
64+
company = _Company({"IS": _statement("2024Q4"), "BS": _statement("2024Q4"), "CF": _statement("2024Q4")})
65+
66+
amounts = getFinanceAmounts(company, "2024")
67+
68+
assert amounts["매출액"] == pytest.approx(10.0) # 10억
69+
70+
71+
def testAnnualPeriodFallsBackToQ4() -> None:
72+
"""연간 표기는 Q4 열로 해소된다 (기존 계약 유지)."""
73+
company = _Company({"IS": _statement("2024Q4")})
74+
75+
assert getFinanceAmounts(company, "2024")["매출액"] == pytest.approx(10.0)

0 commit comments

Comments
 (0)