Skip to content

Commit f8ab36f

Browse files
committed
수정: EDGAR 본문 수집에 시간 예산을 둬 매 run 이 timeout cancelled 로 끝나던 것을 없앤다
하루치가 10~54 분인데 20 일을 시도해 120 분 상한에 항상 잘렸다. 진행분은 남지만 결론이 거짓이라 감시에 실패로 보인다. 60 분이 지나면 새 날짜를 시작하지 않고 success 로 끝낸다.
1 parent 8de741c commit f8ab36f

3 files changed

Lines changed: 117 additions & 12 deletions

File tree

‎.github/scripts/sync/fillEdgarAllFilingsContent.py‎

Lines changed: 71 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,27 @@
11
"""US allFilings 본문 점진 수집 runner. recent.parquet 메타로 일자별 content_raw 를 채워 HF per-day 발행.
22
33
전 수시공시 본문을 모은다(정기 10-K/10-Q 등은 panel 소유라 recent.parquet 에서 이미 제외). 전 종목 2015 이후
4-
전 공시는 4M+ 이라 한 번에 못 받는다. run 당 예산(maxDays)만큼 forward(최신 미충전일) + backfill(과거
5-
미충전일)로 점진 수집한다. 일자별 fillContentDay 가 idempotent(ok/no_body skip, error retry)라 재실행 안전.
6-
DART allFilingsBackfill 대칭.
4+
전 공시는 4M+ 이라 한 번에 못 받는다. run 당 예산(maxDays 와 budgetMinutes)만큼 forward(최신 미충전일) +
5+
backfill(과거 미충전일)로 점진 수집한다. 일자별 fillContentDay 가 idempotent(ok/no_body skip, error retry)라
6+
재실행 안전. DART allFilingsBackfill 대칭.
7+
8+
시간 예산: 하루치가 10~55 분(2026-08-31 실측 최장 53.5 분)이라 20 일은 job 상한(120 분) 안에 못 끝난다. 예산 없이 돌리면 매 run 이
9+
timeout 으로 cancelled 로 끝나 감시에서 실패로 보이고(2026-08-31·09-01 실측), 진행분은 남지만 결론이
10+
거짓이다. budgetMinutes 가 지나면 새 날짜를 시작하지 않고 success 로 끝낸다. 남은 시간에 하루치가 들어가야
11+
하므로 workflow timeout 보다 최장 하루치만큼 작게 둔다.
712
813
실행::
914
10-
uv run python -X utf8 .github/scripts/sync/fillEdgarAllFilingsContent.py [--max-days 20] [--forward-days 3]
15+
uv run python -X utf8 .github/scripts/sync/fillEdgarAllFilingsContent.py [--max-days 20] [--forward-days 3] [--budget-minutes 60]
1116
"""
1217

1318
from __future__ import annotations
1419

1520
import argparse
1621
import os
1722
import sys
23+
import time
24+
from collections.abc import Callable
1825
from pathlib import Path
1926

2027
import polars as pl
@@ -50,11 +57,54 @@ def selectDays(allDays: list[str], done: set[str], *, maxDays: int, forwardDays:
5057
return (fwd + back)[:maxDays]
5158

5259

60+
def fillDays(
61+
todo: list[str],
62+
fillDay: Callable[[str], None],
63+
*,
64+
budgetSeconds: float,
65+
clock: Callable[[], float] = time.monotonic,
66+
) -> list[str]:
67+
"""예산(초) 안에서 날짜를 순서대로 처리한다(순수 흐름, 테스트 대상).
68+
69+
새 날짜는 예산이 남았을 때만 시작한다. 시작한 날짜는 끝까지 처리하므로 실제 소요는 예산 + 하루치다.
70+
71+
Args:
72+
todo: 처리 순서대로의 날짜(YYYYMMDD).
73+
fillDay: 하루치를 수집·발행하는 함수.
74+
budgetSeconds: 새 날짜 시작을 허용하는 누적 시간(초).
75+
clock: 단조 시계(테스트 주입용).
76+
77+
Returns:
78+
처리를 마친 날짜 목록.
79+
80+
Raises:
81+
없음. fillDay 의 예외는 그대로 전파한다.
82+
83+
Example:
84+
>>> fillDays(["20260101", "20260102"], lambda day: None, budgetSeconds=60)
85+
['20260101', '20260102']
86+
"""
87+
startedAt = clock()
88+
done: list[str] = []
89+
for day in todo:
90+
if clock() - startedAt >= budgetSeconds:
91+
break
92+
fillDay(day)
93+
done.append(day)
94+
return done
95+
96+
5397
def main() -> int:
5498
"""recent.parquet 메타 → 미충전 일자 선정 → fillContentDay + HF 발행 (예산만큼)."""
5599
ap = argparse.ArgumentParser()
56-
ap.add_argument("--max-days", type=int, default=20, help="이번 run 처리할 일 수(CI 시간 예산)")
100+
ap.add_argument("--max-days", type=int, default=20, help="이번 run 처리할 일 수 상한")
57101
ap.add_argument("--forward-days", type=int, default=3, help="최신 미충전일 우선 충전 수(피드 신선도)")
102+
ap.add_argument(
103+
"--budget-minutes",
104+
type=float,
105+
default=60.0,
106+
help="이 시간이 지나면 새 날짜를 시작하지 않는다(분). workflow timeout 보다 최장 하루치만큼 작게",
107+
)
58108
args = ap.parse_args()
59109

60110
tok = os.environ.get("HF_TOKEN", "").strip()
@@ -73,10 +123,15 @@ def main() -> int:
73123
if not todo:
74124
print(f"[content] 전 {len(allDays)}일 충전 완료", flush=True)
75125
return 0
76-
print(f"[content] 전 {len(allDays)}일 · 미충전 {unfilled}일 · 이번 run {len(todo)}일", flush=True)
126+
print(
127+
f"[content] 전 {len(allDays)}일 · 미충전 {unfilled}일 · 이번 run 최대 {len(todo)}일 · 예산 {args.budget_minutes:g}분",
128+
flush=True,
129+
)
77130

78131
outDir = Path(_cfg.dataDir) / "edgar" / "allFilingsContent"
79-
for day in todo:
132+
133+
def fillDay(day: str) -> None:
134+
startedAt = time.monotonic()
80135
dayMeta = meta.filter(pl.col("filingDate") == day)
81136
outPath = outDir / f"{day}.parquet"
82137
fillContentDay(dayMeta, outPath)
@@ -88,8 +143,15 @@ def main() -> int:
88143
repo_type="dataset",
89144
commit_message=f"본문: {_CONTENT_DIR}/{day}",
90145
)
91-
print(f" 발행 {day}", flush=True)
92-
print(f"[content] {len(todo)}일 완료 · 남은 {unfilled - len(todo)}일", flush=True)
146+
print(f" 발행 {day} ({(time.monotonic() - startedAt) / 60:.1f}분)", flush=True)
147+
148+
finished = fillDays(todo, fillDay, budgetSeconds=args.budget_minutes * 60.0)
149+
skipped = len(todo) - len(finished)
150+
print(
151+
f"[content] {len(finished)}일 완료 · 남은 {unfilled - len(finished)}일"
152+
+ (f" · 예산 소진으로 이번 run 미착수 {skipped}일" if skipped else ""),
153+
flush=True,
154+
)
93155
return 0
94156

95157

‎.github/workflows/edgarFilingsContentSync.yml‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,9 +40,12 @@ jobs:
4040
run: uv sync
4141
- name: Fill allFilings content (forward + backfill → HF)
4242
run: |
43+
# 예산 60 분 + 최장 하루치(2026-08-31 실측 53.5 분, 여유 55 분) < job 상한 120 분. 예산이 끝나면
44+
# 새 날짜를 시작하지 않고 success 로 끝난다(timeout cancelled 가 감시에 실패로 잡히던 것을 없앤다).
4345
uv run python -X utf8 .github/scripts/sync/fillEdgarAllFilingsContent.py \
4446
--max-days "${{ github.event.inputs.maxDays || '20' }}" \
45-
--forward-days "${{ github.event.inputs.forwardDays || '3' }}"
47+
--forward-days "${{ github.event.inputs.forwardDays || '3' }}" \
48+
--budget-minutes 60
4649
env:
4750
HF_TOKEN: ${{ secrets.HF_TOKEN }}
4851
DARTLAB_DATA_DIR: ${{ github.workspace }}/data

‎tests/gather/edgar/test_fillEdgarAllFilingsContent.py‎

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,15 @@
1515
_SCRIPT = Path(__file__).resolve().parents[3] / ".github" / "scripts" / "sync" / "fillEdgarAllFilingsContent.py"
1616

1717

18-
def _selectDays():
18+
def _module():
1919
spec = importlib.util.spec_from_file_location("fillEdgarAllFilingsContentForTest", _SCRIPT)
2020
module = importlib.util.module_from_spec(spec)
2121
spec.loader.exec_module(module)
22-
return module.selectDays
22+
return module
23+
24+
25+
def _selectDays():
26+
return _module().selectDays
2327

2428

2529
def test_forward_newest_plus_backfill_oldest():
@@ -44,3 +48,39 @@ def test_backfill_only_when_forward_zero():
4448
selectDays = _selectDays()
4549
allDays = ["20260101", "20260102", "20260103"]
4650
assert selectDays(allDays, set(), maxDays=2, forwardDays=0) == ["20260101", "20260102"]
51+
52+
53+
# ─── 시간 예산 (2026-09-01: 매 run 이 timeout cancelled 로 끝나 감시에 실패로 보이던 것) ───
54+
55+
56+
def test_fill_days_stops_starting_new_days_after_budget():
57+
"""예산이 지나면 새 날짜를 시작하지 않는다. 시작한 날짜는 끝까지 간다."""
58+
fillDays = _module().fillDays
59+
now = [0.0]
60+
filled: list[str] = []
61+
62+
def fillDay(day: str) -> None:
63+
filled.append(day)
64+
now[0] += 30.0 # 하루치 30 초
65+
66+
done = fillDays(["d1", "d2", "d3", "d4"], fillDay, budgetSeconds=50.0, clock=lambda: now[0])
67+
# 0s: d1 시작(예산 안) -> 30s: d2 시작(예산 안) -> 60s: 예산 초과, d3 미착수
68+
assert done == ["d1", "d2"]
69+
assert filled == ["d1", "d2"]
70+
71+
72+
def test_fill_days_finishes_all_when_budget_remains():
73+
"""예산이 남으면 todo 를 전부 처리한다."""
74+
fillDays = _module().fillDays
75+
assert fillDays(["a", "b"], lambda day: None, budgetSeconds=60.0) == ["a", "b"]
76+
77+
78+
def test_workflow_passes_budget_below_job_timeout():
79+
"""workflow 의 예산(분) + 실측 최장 하루치가 job timeout 안에 들어야 timeout cancelled 가 사라진다."""
80+
import re
81+
82+
workflow = (_SCRIPT.parents[2] / "workflows" / "edgarFilingsContentSync.yml").read_text(encoding="utf-8")
83+
timeout = int(re.search(r"timeout-minutes:\s*(\d+)", workflow).group(1))
84+
budget = float(re.search(r"--budget-minutes\s+(\d+)", workflow).group(1))
85+
longestDayMinutes = 55 # 2026-08-31 run 실측 최장 53.5 분(20251202) + 여유
86+
assert budget + longestDayMinutes < timeout, f"예산 {budget} + 하루치 {longestDayMinutes} >= timeout {timeout}"

0 commit comments

Comments
 (0)