Skip to content

Commit cc019b9

Browse files
committed
검증: Company 에 없는 이름을 부르는 자리를 상시 차단한다
하루에 같은 결함을 열두 번 만났다. 공개 계약을 좁히면서 옛 이름을 부르던 소비처를 같이 안 고쳤고, `getattr(company, "X", None)` 과 넓은 except 가 그 실패를 지웠다. 예외가 안 나니 어느 게이트도 못 봤고, 사용자 표면 넷이 통째로 죽은 채 초록불이었다. 보고서가 빈 제목만 냈고, 재무 차트 다섯이 매번 죽었고, spec 생성기 여덟 중 일곱이 늘 빈 손이었고, DCF 도구가 모든 회사에서 실패했다. 감사 하나를 둔다. `company.X` 또는 `getattr(company, "X", ...)` 로 부르는 X 가 Company 정의 어디에도 없으면 위반이다. 표면은 provider company 파일에서 정적으로 모으므로 실행도 데이터도 필요 없다. 원장을 두고 신규만 차단한다. lint 게이트에 등록해 상시 돈다. 지금 원장 34 건에 신규 0 건이다. 감사를 만들면서 한 자리가 더 걸렸다. 공시 본문 금액을 재무제표와 대조하는 `getFinanceAmounts` 가 `company.finance` 에서 세 장을 꺼내는데, 그 이름이 없어서 매 회전이 except 로 continue 했다. 검증이 통째로 무력했다. 공개 계약으로 바꾸니 삼성전자 기준 0 개에서 116 개 계정이 나온다.
1 parent 133428a commit cc019b9

4 files changed

Lines changed: 240 additions & 3 deletions

File tree

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

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -113,12 +113,15 @@ def getFinanceAmounts(company, period: str) -> dict[str, float]:
113113
if re.match(r"^\d{4}$", period):
114114
candidates.append(f"{period}Q4")
115115

116+
# 예전에는 `company.finance` 에서 세 장을 꺼냈다. `finance` 는 표면에서 빠진 이름이라
117+
# 매 회전이 except 로 continue 했고, 이 함수가 어느 회사에서도 빈 dict 만 냈다. 그래서
118+
# 공시 본문 금액과 재무제표를 대조하는 검증이 통째로 무력했다. 공개 계약으로 부른다.
116119
for stmt_name in ("IS", "BS", "CF"):
117120
try:
118-
stmt = getattr(company.finance, stmt_name)
119-
except (AttributeError, FileNotFoundError, RuntimeError):
121+
stmt = company.panel(stmt_name)
122+
except (AttributeError, FileNotFoundError, KeyError, RuntimeError, TypeError, ValueError):
120123
continue
121-
if stmt is None:
124+
if stmt is None or getattr(stmt, "height", 0) == 0:
122125
continue
123126

124127
target_period = None
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
{
2+
"policy": "no_new_violations",
3+
"note": "Company 에 없는 이름을 부르는 자리. 신규 추가만 차단한다.",
4+
"known": [
5+
"_blockMap@viz/display/adapters.py",
6+
"_ensureNetwork@server/api/company.py",
7+
"_series@analysis/valuation/_dFVDrivers.py",
8+
"_series@analysis/valuation/_dFVTsd.py",
9+
"_storyLensProducts@story/lensProducts.py",
10+
"_strategy_start@quant/strategy/styles/_common.py",
11+
"benchmark@quant/screen/_extendedCache.py",
12+
"benchmark@quant/screen/extended.py",
13+
"benchmarkMode@quant/screen/_extendedCache.py",
14+
"benchmarkMode@quant/screen/extended.py",
15+
"code@story/lensProducts.py",
16+
"companyName@ai/workbench/heuristic.py",
17+
"currentPrice@analysis/valuation/_valuationInputAccess.py",
18+
"docs@analysis/financial/insight/_gradingGovernance.py",
19+
"industryName@analysis/financial/sectorKpi/dispatcher.py",
20+
"name@ai/tools/engineCall.py",
21+
"name@analysis/forecast/scenarioSim.py",
22+
"name@analysis/valuation/analyst.py",
23+
"name@analysis/valuation/bankDFV.py",
24+
"profile@analysis/financial/_signalsPeer.py",
25+
"profile@analysis/financial/_valuationInputs.py",
26+
"profile@analysis/forecast/prediction.py",
27+
"profile@analysis/valuation/analyst.py",
28+
"rankInfo@analysis/forecast/prediction.py",
29+
"salesOrder@analysis/financial/_forecastCalcsInputs.py",
30+
"sectorInfo@analysis/forecast/prediction.py",
31+
"segments@analysis/financial/_forecastCalcsInputs.py",
32+
"stock_code@analysis/financial/governance.py",
33+
"stock_code@analysis/financial/macroExposure.py",
34+
"stock_code@analysis/valuation/analyst.py",
35+
"stock_code@quant/screen/_extendedNarrative.py",
36+
"stock_code@quant/strategy/styles/_common.py",
37+
"stock_code@scan/builders/kr/extended.py",
38+
"timeseries@providers/edgar/report/employee.py"
39+
]
40+
}

‎tests/audit/deadCompanyAccessor.py‎

Lines changed: 190 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,190 @@
1+
"""Company 에 없는 이름을 부르는 자리를 찾는다.
2+
3+
2026-07-28 하루에 같은 결함을 열두 번 만났다. 공개 계약을 좁히면서 옛 이름을 부르던
4+
소비처를 같이 안 고쳤고, `getattr(company, "X", None)` 과 넓은 except 가 그 실패를 지웠다.
5+
예외가 안 나니 어느 게이트도 못 봤고, 사용자 표면 넷이 통째로 죽은 채 초록불이었다.
6+
7+
- `dartlab report` 가 빈 제목 네 개만 출력 (BS · IS · CF · ratios · insights)
8+
- 재무 차트 다섯이 매번 데이터 없음 예외 (IS · BS · CF · dividend)
9+
- 차트 spec 생성기 여덟 중 일곱이 늘 None (annual · ratioSeries · insights · dividend)
10+
- DCF 밸류에이션 도구가 모든 회사에서 실패 (finance · sharesOutstanding · currentPrice)
11+
12+
그래서 이 감사를 둔다. 회귀가 아니라 *이 계열의 재유입*을 막는 것이 목적이다.
13+
14+
판정 기준은 이름 하나다. `company.X` 또는 `getattr(company, "X", ...)` 로 부르는 X 가
15+
Company 정의 어디에도 없으면 위반이다. 표면은 provider company 파일에서 정적으로 모은다
16+
(클래스 메서드 · 클래스 변수 · `self.X =` 대입). 실행이 필요 없어 데이터 없이도 돈다.
17+
18+
사용법::
19+
20+
python tests/audit/deadCompanyAccessor.py # 신규 위반만 차단
21+
python tests/audit/deadCompanyAccessor.py --json # 기계 판독
22+
python tests/audit/deadCompanyAccessor.py --update # 현재 상태를 원장으로 저장
23+
24+
종료 코드: 0 신규 위반 없음 / 1 신규 위반 발견.
25+
"""
26+
27+
from __future__ import annotations
28+
29+
import argparse
30+
import ast
31+
import json
32+
import sys
33+
from pathlib import Path
34+
35+
_ROOT = Path(__file__).resolve().parents[2]
36+
_SRC = _ROOT / "src" / "dartlab"
37+
_BASELINE = _ROOT / "tests" / "audit" / "_baselines" / "deadCompanyAccessor.json"
38+
39+
# Company 표면을 정의하는 파일. 여기서 이름을 모은다.
40+
_SURFACE_FILES = (
41+
"company.py",
42+
"providers/dart/company.py",
43+
"providers/edgar/company.py",
44+
)
45+
46+
# 표면 파일 밖에서 붙는 이름. 정적 수집이 못 보는 것만 최소로 둔다.
47+
_EXTRA_SURFACE = frozenset({"_cache", "_hintedKeys"})
48+
49+
# `company` / `comp` 라는 이름이 Company 가 아닌 자리. 여기서 나온 속성은 세지 않는다.
50+
_NON_COMPANY_ATTRS = frozenset(
51+
{
52+
"get",
53+
"setdefault",
54+
"values",
55+
"keys",
56+
"items",
57+
"exists",
58+
"glob",
59+
"company",
60+
}
61+
)
62+
63+
_TARGET_VARS = frozenset({"company", "comp"})
64+
65+
66+
def collectSurface() -> set[str]:
67+
"""Company 가 실제로 갖는 이름 전수 (정적)."""
68+
names: set[str] = set(_EXTRA_SURFACE)
69+
for rel in _SURFACE_FILES:
70+
path = _SRC / rel
71+
if not path.exists():
72+
continue
73+
tree = ast.parse(path.read_text(encoding="utf-8"))
74+
for node in ast.walk(tree):
75+
if isinstance(node, ast.ClassDef):
76+
for item in node.body:
77+
if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
78+
names.add(item.name)
79+
elif isinstance(item, ast.Assign):
80+
names.update(t.id for t in item.targets if isinstance(t, ast.Name))
81+
elif isinstance(node, ast.Assign):
82+
for target in node.targets:
83+
if isinstance(target, ast.Attribute) and _isSelf(target.value):
84+
names.add(target.attr)
85+
return names
86+
87+
88+
def _isSelf(node: ast.expr) -> bool:
89+
return isinstance(node, ast.Name) and node.id == "self"
90+
91+
92+
class _Visitor(ast.NodeVisitor):
93+
"""`company.X` 와 `getattr(company, "X", ...)` 를 모은다."""
94+
95+
def __init__(self, rel: str, surface: set[str]) -> None:
96+
self.rel = rel
97+
self.surface = surface
98+
self.hits: list[tuple[str, str, int]] = []
99+
100+
def _record(self, attr: str, lineno: int) -> None:
101+
if attr.startswith("__") or attr in self.surface or attr in _NON_COMPANY_ATTRS:
102+
return
103+
self.hits.append((attr, self.rel, lineno))
104+
105+
def visit_Attribute(self, node: ast.Attribute) -> None:
106+
if isinstance(node.value, ast.Name) and node.value.id in _TARGET_VARS:
107+
self._record(node.attr, node.lineno)
108+
self.generic_visit(node)
109+
110+
def visit_Call(self, node: ast.Call) -> None:
111+
func = node.func
112+
if isinstance(func, ast.Name) and func.id == "getattr" and len(node.args) >= 2:
113+
target, name = node.args[0], node.args[1]
114+
if (
115+
isinstance(target, ast.Name)
116+
and target.id in _TARGET_VARS
117+
and isinstance(name, ast.Constant)
118+
and isinstance(name.value, str)
119+
):
120+
self._record(name.value, node.lineno)
121+
self.generic_visit(node)
122+
123+
124+
def scan() -> list[dict[str, object]]:
125+
"""전 소스에서 위반 후보를 모은다."""
126+
surface = collectSurface()
127+
found: list[dict[str, object]] = []
128+
for path in sorted(_SRC.rglob("*.py")):
129+
rel = path.relative_to(_SRC).as_posix()
130+
try:
131+
tree = ast.parse(path.read_text(encoding="utf-8"))
132+
except (SyntaxError, UnicodeDecodeError):
133+
continue
134+
visitor = _Visitor(rel, surface)
135+
visitor.visit(tree)
136+
for attr, where, lineno in visitor.hits:
137+
found.append({"attr": attr, "file": where, "line": lineno})
138+
return found
139+
140+
141+
def _key(item: dict[str, object]) -> str:
142+
return f"{item['attr']}@{item['file']}"
143+
144+
145+
def loadBaseline() -> set[str]:
146+
if not _BASELINE.exists():
147+
return set()
148+
data = json.loads(_BASELINE.read_text(encoding="utf-8"))
149+
return set(data.get("known", []))
150+
151+
152+
def main(argv: list[str] | None = None) -> int:
153+
parser = argparse.ArgumentParser(description=__doc__)
154+
parser.add_argument("--json", action="store_true", help="기계 판독 출력")
155+
parser.add_argument("--update", action="store_true", help="현재 상태를 원장으로 저장")
156+
args = parser.parse_args(argv)
157+
158+
found = scan()
159+
if args.update:
160+
_BASELINE.parent.mkdir(parents=True, exist_ok=True)
161+
payload = {
162+
"policy": "no_new_violations",
163+
"note": "Company 에 없는 이름을 부르는 자리. 신규 추가만 차단한다.",
164+
"known": sorted({_key(item) for item in found}),
165+
}
166+
_BASELINE.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
167+
print(f"[dead-company-accessor] 원장 저장 {len(payload['known'])} 건 -> {_BASELINE}")
168+
return 0
169+
170+
baseline = loadBaseline()
171+
fresh = [item for item in found if _key(item) not in baseline]
172+
173+
if args.json:
174+
print(json.dumps({"total": len(found), "new": fresh}, indent=2, ensure_ascii=False))
175+
return 1 if fresh else 0
176+
177+
if fresh:
178+
print(f"[dead-company-accessor] 신규 위반 {len(fresh)} 건 (원장 {len(baseline)} 건)")
179+
for item in fresh:
180+
print(f" {item['file']}:{item['line']} company.{item['attr']}")
181+
print("\nCompany 에 없는 이름이다. 공개 계약(panel · analysis · capital 등)으로 부르거나,")
182+
print("정말 Company 가 아니면 변수 이름을 바꿔라. 오탐이면 --update 로 원장에 올린다.")
183+
return 1
184+
185+
print(f"[dead-company-accessor] OK. 신규 위반 0 (원장 {len(baseline)} 건 / 현재 {len(found)} 건).")
186+
return 0
187+
188+
189+
if __name__ == "__main__":
190+
sys.exit(main())

‎tests/run.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,10 @@ class Gate:
142142
# 실제로 지배적인 침묵은 광범위 catch 가 원인을 버리고 대체값을 돌려주는
143143
# 모양이라 별도로 센다. 통과 조건은 흐름 변경이 아니라 원인 한 줄 기록이다.
144144
"python -X utf8 tests/audit/silentSubstitute.py && "
145+
# 계약을 좁히면서 옛 이름을 부르던 소비처를 같이 안 고치면, 넓은 catch 가 그
146+
# AttributeError 를 지워 사용자 표면이 통째로 죽은 채 초록불이 된다. 2026-07-28
147+
# 하루에 열두 번 나왔다(보고서 백지 · 차트 다섯 · spec 생성기 일곱 · DCF 도구).
148+
"python -X utf8 tests/audit/deadCompanyAccessor.py && "
145149
"python tests/audit/stale_references.py && "
146150
"python -X utf8 tests/audit/lint_camelcase_ast.py --changed --strict && "
147151
# baseline 은 2-cycle 목록이다. 예전에는 개수만 적고 늘어나도 WARN 만 찍은

0 commit comments

Comments
 (0)