Skip to content

Commit d13a10a

Browse files
committed
수정: 선택적 공급자 실패를 엔진 경계에서 격리한다
Linux AnyIO가 묶어 반환하는 네트워크 실패와 fallback 집계 원인을 재귀적으로 판정한다. 모든 원인이 선택적 실패일 때만 강등하고 로컬 데이터 오류가 섞이면 다시 전파한다. 분석 엔진은 실패한 계산 블록을 calculationErrors와 coverage에 남기고 계속 실행한다. story 빌더는 같은 실패를 build failure로 기록해 전체 보고서가 무너지지 않게 한다. 제품 스모크 아티팩트에 전체 traceback을 남기고 분석, gather, story 회귀 테스트를 추가한다.
1 parent 776c5ff commit d13a10a

7 files changed

Lines changed: 172 additions & 15 deletions

File tree

‎src/dartlab/analysis/financial/__init__.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -462,6 +462,13 @@ def _run(
462462
) as exc:
463463
results[calc.blockKey] = None
464464
calculationErrors[calc.blockKey] = type(exc).__name__
465+
except Exception as exc:
466+
from dartlab.gather.types import isOptionalSourceError
467+
468+
if not isOptionalSourceError(exc):
469+
raise
470+
results[calc.blockKey] = None
471+
calculationErrors[calc.blockKey] = type(exc).__name__
465472

466473
usableBlocks = [
467474
calc.blockKey

‎src/dartlab/gather/types.py‎

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -909,19 +909,6 @@ class SourceUnavailableError(GatherError):
909909
"""소스 접근 불가."""
910910

911911

912-
def isOptionalSourceError(exc: BaseException) -> bool:
913-
"""OS별 네트워크 예외 포장 차이를 선택적 source 실패로 정규화한다."""
914-
if isinstance(exc, BaseExceptionGroup):
915-
return bool(exc.exceptions) and all(isOptionalSourceError(child) for child in exc.exceptions)
916-
if isinstance(exc, (ImportError, OSError, RuntimeError, AttributeError, GatherError)):
917-
return True
918-
try:
919-
import httpx
920-
except ImportError:
921-
return False
922-
return isinstance(exc, httpx.HTTPError)
923-
924-
925912
class SourceAttemptsExhaustedError(SourceUnavailableError):
926913
"""Fallback source가 모두 실패했음을 원인별로 보존하는 예외.
927914
@@ -954,6 +941,25 @@ def __init__(self, operation: str, attempts: Iterable[tuple[str, Exception]]) ->
954941
super().__init__(f"{operation} fallback source가 모두 실패했습니다 ({detail})")
955942

956943

944+
def isOptionalSourceError(exc: BaseException) -> bool:
945+
"""OS별 네트워크 예외 포장 차이를 선택적 source 실패로 정규화한다.
946+
947+
fallback 집계 예외는 이름만 보고 삼키지 않는다. 보존된 모든 source 원인이
948+
선택적 실패일 때만 강등해 로컬 데이터 오류나 프로그래밍 오류를 숨기지 않는다.
949+
"""
950+
if isinstance(exc, SourceAttemptsExhaustedError):
951+
return bool(exc.attempts) and all(isOptionalSourceError(child) for _, child in exc.attempts)
952+
if isinstance(exc, BaseExceptionGroup):
953+
return bool(exc.exceptions) and all(isOptionalSourceError(child) for child in exc.exceptions)
954+
if isinstance(exc, (ImportError, OSError, RuntimeError, AttributeError, GatherError)):
955+
return True
956+
try:
957+
import httpx
958+
except ImportError:
959+
return False
960+
return isinstance(exc, httpx.HTTPError)
961+
962+
957963
class RateLimitExceededError(GatherError):
958964
"""Rate limit 초과."""
959965

‎src/dartlab/story/registry.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,11 @@ def _makeSafeCall(failures: list[dict]):
8585
def _safeCall(fn: Callable):
8686
try:
8787
return fn()
88-
except _SAFE_BUILD_ERRORS as exc:
88+
except Exception as exc:
89+
from dartlab.gather.types import isOptionalSourceError
90+
91+
if not isinstance(exc, _SAFE_BUILD_ERRORS) and not isOptionalSourceError(exc):
92+
raise
8993
name = getattr(fn, "__name__", "?")
9094
_LOG.debug("story block build 실패: %s - %s: %s", name, type(exc).__name__, exc)
9195
failures.append(

‎tests/analysis/test_engine.py‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -358,3 +358,73 @@ def broken(company):
358358
assert result["dataAsOf"]["earliestPeriod"] == "2024"
359359
assert result["dataAsOf"]["blockLatestPeriods"] == {"older": "2024", "newer": "2025"}
360360
assert result["dataAsOf"]["mixedPeriods"] is True
361+
362+
363+
def test_run_degrades_only_optional_aggregated_source_failures(monkeypatch):
364+
"""OS가 묶은 외부 source 실패는 한 calc 결손으로 남기되 로컬 오류는 숨기지 않는다."""
365+
from types import SimpleNamespace
366+
367+
import dartlab.analysis.financial as financial
368+
from dartlab.analysis.financial import Analysis
369+
from dartlab.analysis.financial._registry import _AxisEntry, _CalcEntry
370+
from dartlab.core.offlineGuard import OfflineViolation
371+
from dartlab.gather.types import SourceAttemptsExhaustedError, SourceUnavailableError
372+
373+
optionalError = SourceAttemptsExhaustedError(
374+
"history",
375+
[
376+
("naver", ExceptionGroup("connect", [OfflineViolation("blocked")])),
377+
("fmp", SourceUnavailableError("key missing")),
378+
],
379+
)
380+
381+
def stable(company):
382+
return {"period": "2025"}
383+
384+
def optional(company):
385+
raise optionalError
386+
387+
module = SimpleNamespace(stable=stable, optional=optional)
388+
monkeypatch.setattr(financial.importlib, "import_module", lambda name: module)
389+
entry = _AxisEntry(
390+
section="테스트",
391+
partId="test",
392+
description="",
393+
example="",
394+
calcs=(
395+
_CalcEntry("stable", "synthetic", "stable", "stable"),
396+
_CalcEntry("optional", "synthetic", "optional", "optional"),
397+
),
398+
)
399+
400+
result = Analysis()._run(SimpleNamespace(), entry)
401+
402+
assert result["assessmentStatus"] == "partial"
403+
assert result["calculationErrors"] == {"optional": "SourceAttemptsExhaustedError"}
404+
assert result["coverage"]["usableBlockKeys"] == ["stable"]
405+
406+
407+
def test_run_does_not_hide_mixed_aggregated_source_failures(monkeypatch):
408+
"""fallback 집계 안의 로컬 데이터 오류는 정상 실패로 다시 올린다."""
409+
from types import SimpleNamespace
410+
411+
import dartlab.analysis.financial as financial
412+
from dartlab.analysis.financial import Analysis
413+
from dartlab.analysis.financial._registry import _AxisEntry, _CalcEntry
414+
from dartlab.gather.types import SourceAttemptsExhaustedError
415+
416+
def broken(company):
417+
raise SourceAttemptsExhaustedError("history", [("local", ValueError("invalid cached row"))])
418+
419+
module = SimpleNamespace(broken=broken)
420+
monkeypatch.setattr(financial.importlib, "import_module", lambda name: module)
421+
entry = _AxisEntry(
422+
section="테스트",
423+
partId="test",
424+
description="",
425+
example="",
426+
calcs=(_CalcEntry("broken", "synthetic", "broken", "broken"),),
427+
)
428+
429+
with pytest.raises(SourceAttemptsExhaustedError):
430+
Analysis()._run(SimpleNamespace(), entry)

‎tests/audit/productSmoke.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -336,7 +336,7 @@ def sampleLoop() -> None:
336336
"ok": False,
337337
"errorType": type(exc).__name__,
338338
"error": str(exc),
339-
"traceback": traceback.format_exc(limit=8),
339+
"traceback": traceback.format_exc(),
340340
}
341341
)
342342
finally:

‎tests/gather/test_types.py‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,24 @@ def testOptionalSourceErrorRecursesThroughExceptionGroups() -> None:
3030

3131
assert isOptionalSourceError(optional) is True
3232
assert isOptionalSourceError(mixed) is False
33+
34+
35+
def testOptionalSourceErrorInspectsEveryAggregatedAttempt() -> None:
36+
"""fallback 집계는 모든 원인이 선택적일 때만 강등한다."""
37+
from dartlab.core.offlineGuard import OfflineViolation
38+
from dartlab.gather.types import SourceAttemptsExhaustedError, SourceUnavailableError, isOptionalSourceError
39+
40+
optional = SourceAttemptsExhaustedError(
41+
"history",
42+
[
43+
("naver", ExceptionGroup("connect", [OfflineViolation("blocked")])),
44+
("fmp", SourceUnavailableError("key missing")),
45+
],
46+
)
47+
mixed = SourceAttemptsExhaustedError(
48+
"history",
49+
[("naver", SourceUnavailableError("down")), ("local", ValueError("invalid cached row"))],
50+
)
51+
52+
assert isOptionalSourceError(optional) is True
53+
assert isOptionalSourceError(mixed) is False

‎tests/story/test_missingValueHonesty.py‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,55 @@ def _brokenBuilder():
132132
assert failures[0]["builder"] == "_brokenBuilder"
133133

134134

135+
def testOptionalSourceFailureIsRecordedWithoutBreakingStory() -> None:
136+
"""스토리의 보조 source 고장은 lens gap으로 남고 다른 블록은 계속 만든다."""
137+
from dartlab.core.offlineGuard import OfflineViolation
138+
from dartlab.gather.types import SourceAttemptsExhaustedError, SourceUnavailableError
139+
140+
failures: list[dict] = []
141+
safe = _makeSafeCall(failures)
142+
143+
def _offlineBuilder():
144+
raise SourceAttemptsExhaustedError(
145+
"history",
146+
[
147+
("naver", ExceptionGroup("connect", [OfflineViolation("blocked")])),
148+
("fmp", SourceUnavailableError("key missing")),
149+
],
150+
)
151+
152+
assert safe(_offlineBuilder) == []
153+
assert failures == [
154+
{
155+
"code": "BLOCK_BUILD_FAILED",
156+
"builder": "_offlineBuilder",
157+
"error": "SourceAttemptsExhaustedError",
158+
"message": str(
159+
SourceAttemptsExhaustedError(
160+
"history",
161+
[
162+
("naver", ExceptionGroup("connect", [OfflineViolation("blocked")])),
163+
("fmp", SourceUnavailableError("key missing")),
164+
],
165+
)
166+
),
167+
}
168+
]
169+
170+
171+
def testStoryDoesNotHideMixedAggregatedSourceFailure() -> None:
172+
"""외부 source 집계에 섞인 로컬 오류는 story 경계에서도 전파한다."""
173+
from dartlab.gather.types import SourceAttemptsExhaustedError
174+
175+
safe = _makeSafeCall([])
176+
177+
def _brokenBuilder():
178+
raise SourceAttemptsExhaustedError("history", [("local", ValueError("invalid cached row"))])
179+
180+
with pytest.raises(SourceAttemptsExhaustedError):
181+
safe(_brokenBuilder)
182+
183+
135184
def testBlockMapCarriesTheFailures() -> None:
136185
"""기록이 결과까지 따라와야 보고서가 결손을 감추지 않는다."""
137186

0 commit comments

Comments
 (0)