Skip to content

Commit 4aeef54

Browse files
committed
리팩토링: allFilings HF 관심사 분할 (룰 3 LoC) + 변경 파일 공개 함수 테스트 동행
- allFilingsCollector 846 LoC 로 800 임계 초과 -> HF 폴백 타입(enum+오류 5종)과 재동기화 게이트를 allFilingsHf.py 로 분할 (797 LoC). collector 는 재수출 + DI 래퍼로 기존 소비자(allFilingsSync·tests) import 경로 무변경. - DI(ensureFromHf·allFilingsDir 주입)로 상향 import 없이 단방향 유지. - 커버리지 게이트 신규 누락 3건 해소: scanLatestAccountValues· sectionLeafConvergeExpr·clearDeltaSegment 실동작 단위 테스트 추가. - allFilingsHf 미러 테스트 4건 신설 (룰 7).
1 parent 8d22925 commit 4aeef54

6 files changed

Lines changed: 272 additions & 76 deletions

File tree

‎src/dartlab/gather/dart/allFilingsCollector.py‎

Lines changed: 27 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@
2929

3030
import os
3131
from concurrent.futures import ThreadPoolExecutor, as_completed
32-
from enum import Enum
3332
from pathlib import Path
3433
from typing import TYPE_CHECKING
3534

@@ -40,6 +39,30 @@
4039
from dartlab.core.logger import getLogger
4140
from dartlab.core.memory import withMemoryBudget
4241
from dartlab.gather.dart.allFilingsDocument import collectOneRaw as _collectOneRaw
42+
43+
# HF 폴백 상태·오류 타입은 allFilingsHf 로 분할 (룰 3 LoC). 기존 소비자
44+
# (allFilingsSync·tests)의 import 경로 보존을 위해 그대로 재수출한다.
45+
from dartlab.gather.dart.allFilingsHf import (
46+
AllFilingsHfDownloadError as AllFilingsHfDownloadError,
47+
)
48+
from dartlab.gather.dart.allFilingsHf import (
49+
AllFilingsHfError as AllFilingsHfError,
50+
)
51+
from dartlab.gather.dart.allFilingsHf import (
52+
AllFilingsHfListingError as AllFilingsHfListingError,
53+
)
54+
from dartlab.gather.dart.allFilingsHf import (
55+
AllFilingsHfUnavailableError as AllFilingsHfUnavailableError,
56+
)
57+
from dartlab.gather.dart.allFilingsHf import (
58+
AllFilingsHfUploadError as AllFilingsHfUploadError,
59+
)
60+
from dartlab.gather.dart.allFilingsHf import (
61+
HfFallbackStatus as HfFallbackStatus,
62+
)
63+
from dartlab.gather.dart.allFilingsHf import (
64+
_maybeResyncFromHf as _maybeResyncFromHfImpl,
65+
)
4366
from dartlab.gather.dart.disclosure import listFilings
4467

4568
if TYPE_CHECKING:
@@ -541,47 +564,10 @@ def pendingDates() -> list[str]:
541564
# HF 동기화 (push / lazy pull)
542565
# ═══════════════════════════════════════════
543566

544-
# 다운로드 1 회 시도 가드 (period 또는 "_ALL_") — 실패 시 무한 retry 회피.
567+
# 다운로드 1 회 시도 가드 (period 또는 "_ALL_"): 실패 시 무한 retry 회피.
545568
_HF_DOWNLOAD_ATTEMPTED: set[str] = set()
546569

547570

548-
class HfFallbackStatus(str, Enum):
549-
"""allFilings HF fallback의 정상 결과."""
550-
551-
LOCAL = "local"
552-
DOWNLOADED = "downloaded"
553-
NOT_FOUND = "not_found"
554-
555-
556-
class AllFilingsHfError(RuntimeError):
557-
"""allFilings HF fallback 기반 오류."""
558-
559-
def __init__(self, message: str, *, period: str | None) -> None:
560-
self.period = period
561-
super().__init__(message)
562-
563-
564-
class AllFilingsHfUnavailableError(AllFilingsHfError):
565-
"""HF fallback을 현재 실행 환경에서 사용할 수 없음."""
566-
567-
568-
class AllFilingsHfDownloadError(AllFilingsHfError):
569-
"""HF fallback 원격 조회·다운로드가 실패함."""
570-
571-
572-
class AllFilingsHfListingError(AllFilingsHfError):
573-
"""HF 원격 artifact 목록 조회가 실패함."""
574-
575-
576-
class AllFilingsHfUploadError(AllFilingsHfError):
577-
"""HF artifact 업로드가 일부 또는 전부 실패함."""
578-
579-
def __init__(self, message: str, *, uploadedFiles: int, totalFiles: int) -> None:
580-
self.uploadedFiles = uploadedFiles
581-
self.totalFiles = totalFiles
582-
super().__init__(message, period=None)
583-
584-
585571
def _bodyParquetFiles(outDir: Path) -> list[Path]:
586572
"""allFilings 본문 parquet만 정렬해 반환한다."""
587573
return sorted(f for f in outDir.glob("*.parquet") if _META_SUFFIX not in f.stem)
@@ -683,44 +669,9 @@ def _ensureFromHf(period: str | None = None, *, refresh: bool = False) -> HfFall
683669
return HfFallbackStatus.NOT_FOUND
684670

685671

686-
# HF 재동기화 TTL. allFilings 는 HF 에 매일(당일분은 장중 증분) 갱신되므로 존재
687-
# 확인만으로 끝내면 로컬이 영구 stale 로 굳는다. 마커 파일 mtime 이 마지막 성공 시각.
688-
_RESYNC_TTL_HOURS = 12
689-
_RESYNC_RECHECK_SECONDS = 900.0 # 프로세스 내 재시도 간격 (오프라인 반복 지연 방지)
690-
_allFilingsResyncCheckedAt: dict[str, float] = {}
691-
692-
693672
def _maybeResyncFromHf(period: str | None) -> None:
694-
"""로컬 artifact 존재 시 TTL 게이트 후 HF 재동기화 (신규 일자·증분 catch-up).
695-
696-
조달이 아니라 갱신이므로 모든 실패는 로컬 유지로 강등한다. `DARTLAB_NO_HF_DOWNLOAD`
697-
·`DARTLAB_NO_REFRESH` 존중. snapshot_download 는 변경분만 받아 증분으로 동작한다.
698-
"""
699-
import os as _os
700-
import time as _time
701-
702-
if _os.environ.get("DARTLAB_NO_HF_DOWNLOAD", "").strip() in ("1", "true", "True"):
703-
return
704-
if _os.environ.get("DARTLAB_NO_REFRESH") == "1":
705-
return
706-
key = period or "_ALL_"
707-
last = _allFilingsResyncCheckedAt.get(key)
708-
now = _time.monotonic()
709-
if last is not None and now - last < _RESYNC_RECHECK_SECONDS:
710-
return
711-
marker = _allFilingsDir() / f".hfSynced_{key}"
712-
try:
713-
if _time.time() - marker.stat().st_mtime < _RESYNC_TTL_HOURS * 3600:
714-
return
715-
except OSError:
716-
pass # 마커 없음: 구세대 로컬. 재동기화 필요.
717-
_allFilingsResyncCheckedAt[key] = now
718-
try:
719-
_ensureFromHf(period, refresh=True)
720-
except Exception as exc: # noqa: BLE001 - 갱신 실패는 로컬 유지 (조달 계약과 다름)
721-
_log.warning("allFilings HF 재동기화 실패. 로컬 유지 (%s): %s", key, exc)
722-
return
723-
marker.touch()
673+
"""HF 재동기화 게이트. 구현은 `allFilingsHf._maybeResyncFromHf` 에 DI 배선."""
674+
_maybeResyncFromHfImpl(period, ensureFromHf=_ensureFromHf, allFilingsDir=_allFilingsDir)
724675

725676

726677
def loadDay(period: str) -> pl.DataFrame | None:
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
"""allFilings HF 폴백 상태·오류 타입과 재동기화 게이트.
2+
3+
`allFilingsCollector` 의 HF 관심사 분할 모듈 (룰 3 LoC 분할). 조달 로직
4+
(`_ensureFromHf`)과 저장 경로(`_allFilingsDir`)는 collector 소유이므로 DI 로
5+
주입받는다 (collector 상향 import 금지: cycle 없는 단방향 유지).
6+
"""
7+
8+
from __future__ import annotations
9+
10+
from enum import Enum
11+
from pathlib import Path
12+
from typing import Callable
13+
14+
from dartlab.core.logger import getLogger
15+
16+
_log = getLogger(__name__)
17+
18+
19+
class HfFallbackStatus(str, Enum):
20+
"""allFilings HF fallback의 정상 결과."""
21+
22+
LOCAL = "local"
23+
DOWNLOADED = "downloaded"
24+
NOT_FOUND = "not_found"
25+
26+
27+
class AllFilingsHfError(RuntimeError):
28+
"""allFilings HF fallback 기반 오류."""
29+
30+
def __init__(self, message: str, *, period: str | None) -> None:
31+
self.period = period
32+
super().__init__(message)
33+
34+
35+
class AllFilingsHfUnavailableError(AllFilingsHfError):
36+
"""HF fallback을 현재 실행 환경에서 사용할 수 없음."""
37+
38+
39+
class AllFilingsHfDownloadError(AllFilingsHfError):
40+
"""HF fallback 원격 조회·다운로드가 실패함."""
41+
42+
43+
class AllFilingsHfListingError(AllFilingsHfError):
44+
"""HF 원격 artifact 목록 조회가 실패함."""
45+
46+
47+
class AllFilingsHfUploadError(AllFilingsHfError):
48+
"""HF artifact 업로드가 일부 또는 전부 실패함."""
49+
50+
def __init__(self, message: str, *, uploadedFiles: int, totalFiles: int) -> None:
51+
self.uploadedFiles = uploadedFiles
52+
self.totalFiles = totalFiles
53+
super().__init__(message, period=None)
54+
55+
56+
# HF 재동기화 TTL. allFilings 는 HF 에 매일(당일분은 장중 증분) 갱신되므로 존재
57+
# 확인만으로 끝내면 로컬이 영구 stale 로 굳는다. 마커 파일 mtime 이 마지막 성공 시각.
58+
_RESYNC_TTL_HOURS = 12
59+
_RESYNC_RECHECK_SECONDS = 900.0 # 프로세스 내 재시도 간격 (오프라인 반복 지연 방지)
60+
_resyncCheckedAt: dict[str, float] = {}
61+
62+
63+
def _maybeResyncFromHf(
64+
period: str | None,
65+
*,
66+
ensureFromHf: Callable[..., object],
67+
allFilingsDir: Callable[[], Path],
68+
) -> None:
69+
"""로컬 artifact 존재 시 TTL 게이트 후 HF 재동기화 (신규 일자·증분 catch-up).
70+
71+
조달이 아니라 갱신이므로 모든 실패는 로컬 유지로 강등한다. `DARTLAB_NO_HF_DOWNLOAD`
72+
·`DARTLAB_NO_REFRESH` 존중. snapshot_download 는 변경분만 받아 증분으로 동작한다.
73+
74+
Args:
75+
period: 특정 일자(YYYYMMDD) 또는 None(디렉토리 전체).
76+
ensureFromHf: collector `_ensureFromHf` (refresh 키워드 지원) DI 주입.
77+
allFilingsDir: collector `_allFilingsDir` DI 주입.
78+
"""
79+
import os
80+
import time
81+
82+
if os.environ.get("DARTLAB_NO_HF_DOWNLOAD", "").strip() in ("1", "true", "True"):
83+
return
84+
if os.environ.get("DARTLAB_NO_REFRESH") == "1":
85+
return
86+
key = period or "_ALL_"
87+
last = _resyncCheckedAt.get(key)
88+
now = time.monotonic()
89+
if last is not None and now - last < _RESYNC_RECHECK_SECONDS:
90+
return
91+
marker = allFilingsDir() / f".hfSynced_{key}"
92+
try:
93+
if time.time() - marker.stat().st_mtime < _RESYNC_TTL_HOURS * 3600:
94+
return
95+
except OSError:
96+
pass # 마커 없음: 구세대 로컬. 재동기화 필요.
97+
_resyncCheckedAt[key] = now
98+
try:
99+
ensureFromHf(period, refresh=True)
100+
except Exception as exc: # noqa: BLE001 - 갱신 실패는 로컬 유지 (조달 계약과 다름)
101+
_log.warning("allFilings HF 재동기화 실패. 로컬 유지 (%s): %s", key, exc)
102+
return
103+
marker.touch()
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
"""allFilingsHf: HF 폴백 타입·재동기화 게이트 단위 테스트 (DI fake, 네트워크 0)."""
2+
3+
from __future__ import annotations
4+
5+
import pytest
6+
7+
pytestmark = pytest.mark.unit
8+
9+
10+
def test_error_taxonomy_preserves_period_and_hierarchy() -> None:
11+
"""오류 계층과 period 보존 계약."""
12+
from dartlab.gather.dart import allFilingsHf as mod
13+
14+
err = mod.AllFilingsHfDownloadError("boom", period="20260527")
15+
assert isinstance(err, mod.AllFilingsHfError)
16+
assert err.period == "20260527"
17+
18+
up = mod.AllFilingsHfUploadError("partial", uploadedFiles=3, totalFiles=5)
19+
assert up.uploadedFiles == 3 and up.totalFiles == 5 and up.period is None
20+
21+
assert mod.HfFallbackStatus.LOCAL.value == "local"
22+
23+
24+
def test_maybe_resync_marker_ttl_and_memo(monkeypatch, tmp_path) -> None:
25+
"""마커 부재 시 1회 재동기화 + 마커 생성. 신선한 마커는 재호출을 차단한다."""
26+
from dartlab.gather.dart import allFilingsHf as mod
27+
28+
monkeypatch.delenv("DARTLAB_NO_HF_DOWNLOAD", raising=False)
29+
monkeypatch.delenv("DARTLAB_NO_REFRESH", raising=False)
30+
monkeypatch.setattr(mod, "_resyncCheckedAt", {}, raising=False)
31+
32+
calls: list[str | None] = []
33+
34+
def fakeEnsure(period=None, *, refresh=False):
35+
assert refresh is True
36+
calls.append(period)
37+
38+
mod._maybeResyncFromHf("20260527", ensureFromHf=fakeEnsure, allFilingsDir=lambda: tmp_path)
39+
assert calls == ["20260527"]
40+
assert (tmp_path / ".hfSynced_20260527").exists()
41+
42+
# memo 를 비워도 신선한 마커 TTL 이 막는다
43+
monkeypatch.setattr(mod, "_resyncCheckedAt", {}, raising=False)
44+
mod._maybeResyncFromHf("20260527", ensureFromHf=fakeEnsure, allFilingsDir=lambda: tmp_path)
45+
assert calls == ["20260527"]
46+
47+
48+
def test_maybe_resync_failure_keeps_marker_absent(monkeypatch, tmp_path) -> None:
49+
"""재동기화 실패는 예외 없이 로컬 유지 + 마커 미생성 (다음 TTL 재시도)."""
50+
from dartlab.gather.dart import allFilingsHf as mod
51+
52+
monkeypatch.delenv("DARTLAB_NO_HF_DOWNLOAD", raising=False)
53+
monkeypatch.delenv("DARTLAB_NO_REFRESH", raising=False)
54+
monkeypatch.setattr(mod, "_resyncCheckedAt", {}, raising=False)
55+
56+
def failEnsure(period=None, *, refresh=False):
57+
raise OSError("network down")
58+
59+
mod._maybeResyncFromHf(None, ensureFromHf=failEnsure, allFilingsDir=lambda: tmp_path)
60+
assert not (tmp_path / ".hfSynced__ALL_").exists()
61+
62+
63+
def test_maybe_resync_env_switches_disable(monkeypatch, tmp_path) -> None:
64+
"""DARTLAB_NO_HF_DOWNLOAD·DARTLAB_NO_REFRESH 는 재동기화를 차단한다."""
65+
from dartlab.gather.dart import allFilingsHf as mod
66+
67+
def trap(*_a, **_k):
68+
raise AssertionError("resync must be disabled by env")
69+
70+
monkeypatch.setattr(mod, "_resyncCheckedAt", {}, raising=False)
71+
monkeypatch.setenv("DARTLAB_NO_HF_DOWNLOAD", "1")
72+
mod._maybeResyncFromHf(None, ensureFromHf=trap, allFilingsDir=lambda: tmp_path)
73+
74+
monkeypatch.delenv("DARTLAB_NO_HF_DOWNLOAD", raising=False)
75+
monkeypatch.setenv("DARTLAB_NO_REFRESH", "1")
76+
monkeypatch.setattr(mod, "_resyncCheckedAt", {}, raising=False)
77+
mod._maybeResyncFromHf(None, ensureFromHf=trap, allFilingsDir=lambda: tmp_path)

‎tests/providers/dart/panel/test_read.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -574,3 +574,23 @@ def okDownload(**_k):
574574

575575
assert R.ensurePanelFromHf("005930")
576576
assert saved == [("005930", "panel")]
577+
578+
579+
def test_section_leaf_converge_expr_honest_passthrough() -> None:
580+
"""sectionLeafConvergeExpr: SPINE/era 미매칭 라벨은 예외 없이 원본 유지(honest)."""
581+
import polars as pl
582+
583+
from dartlab.providers.dart.panel.read import sectionLeafConvergeExpr
584+
585+
expr = sectionLeafConvergeExpr()
586+
assert isinstance(expr, pl.Expr)
587+
588+
frame = pl.DataFrame(
589+
{
590+
"chapter": ["I. 회사의 개요", None],
591+
"sectionLeaf": ["임의의 미매칭 라벨", None],
592+
}
593+
).with_columns(expr)
594+
assert frame["sectionLeaf"][0] == "임의의 미매칭 라벨"
595+
# null 입력은 core 정규화 과정에서 빈 문자열로 접힌다 (실측 계약)
596+
assert frame["sectionLeaf"][1] in ("", None)

‎tests/providers/dart/search/test_fieldIndexRebuild.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,3 +151,14 @@ def test_edgar_period_to_data_as_of_uses_quarter_end() -> None:
151151
assert periodToDataAsOf("2025Q4") == "20251231"
152152
assert periodToDataAsOf("2026Q1") == "20260331"
153153
assert periodToDataAsOf("bad") == ""
154+
155+
156+
def test_clear_delta_segment_removes_artifacts(monkeypatch, tmp_path) -> None:
157+
"""clearDeltaSegment: delta artifact 를 제거하고 캐시를 비운다."""
158+
from dartlab.providers.dart.search import fieldIndex, fieldIndexRebuild
159+
160+
monkeypatch.setattr(fieldIndex, "_contentIndexDir", lambda tier=None: tmp_path)
161+
(tmp_path / "delta.npz").write_bytes(b"\x00")
162+
163+
fieldIndexRebuild.clearDeltaSegment(tier="full")
164+
assert not (tmp_path / "delta.npz").exists()

‎tests/scan/io/test_parquet.py‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,3 +116,37 @@ def test_scanFinanceParquets_existing_corrupt_prebuild_raises(
116116

117117
with pytest.raises(parquetIo.ScanDataError, match="stage=finance_prebuild_read"):
118118
parquetIo.scanFinanceParquets("IS", {"Revenue"}, {"매출액"})
119+
120+
121+
def test_scan_latest_account_values_wide_latest_period(tmp_path) -> None:
122+
"""scanLatestAccountValues: 최신 연도만 남기고 spec 이름의 wide 컬럼으로 집계한다."""
123+
import polars as pl
124+
125+
from dartlab.scan.io.parquet import ScanDataError, scanLatestAccountValues
126+
127+
path = tmp_path / "finance.parquet"
128+
pl.DataFrame(
129+
{
130+
"stockCode": ["005930", "005930"],
131+
"bsns_year": ["2024", "2025"],
132+
"sj_div": ["IS", "IS"],
133+
"fs_nm": ["연결재무제표", "연결재무제표"],
134+
"account_id": ["ifrs-full_Revenue", "ifrs-full_Revenue"],
135+
"account_nm": ["매출액", "매출액"],
136+
"thstrm_amount": ["1,000", "2,000"],
137+
}
138+
).write_parquet(str(path))
139+
140+
out = scanLatestAccountValues(path, {"revenue": ({"ifrs-full_Revenue"}, {"매출액"}, {"IS"})})
141+
assert out.height == 1
142+
row = out.to_dicts()[0]
143+
assert row["bsns_year"] == "2025"
144+
assert row["revenue"] == 2000.0
145+
146+
with pytest.raises(ValueError, match="accountSpecs"):
147+
scanLatestAccountValues(path, {})
148+
149+
bad = tmp_path / "bad.parquet"
150+
pl.DataFrame({"stockCode": ["005930"]}).write_parquet(str(bad))
151+
with pytest.raises(ScanDataError, match="finance_schema"):
152+
scanLatestAccountValues(bad, {"revenue": ({"x"}, {"y"}, None)})

0 commit comments

Comments
 (0)