CloudStock/KR파이프라인
# 한국장 매시간 파이프라인 설계
> Phase 4 상세 설계 | 장중 매시간 섹터 등락률 수집 → 대표주 선정 → 요약 → 푸시/대시보드
---
## 개요
미장(매일 1회 배치)과 달리 한국장은 장 운영 시간 동안 매시간 실행된다.
```
미장: 매일 1회 배치 → 정적 요약
한국장: 평일 9:00~15:30, 매시간 → 실시간 섹터 등락률 + 이슈 리포트
```
파이프라인은 3단계로 구성된다.
```
Step 1. 수집 KIS → 섹터 인덱스 등락률 + 개별 종목 등락률
Step 2. 선정 deterministic 로직 → 상승/하락 대표 섹터 + 대표주
Step 3. 요약 Perplexity Search → Gemma 4 → D1 저장 + 푸시/대시보드
```
---
## Step 1 — 수집
KIS API 두 가지를 병렬 호출한다.
### 섹터 인덱스 등락률
```
GET /uapi/domestic-stock/v1/quotations/inquire-index-price
TR ID: FHPUP02100000
```
업종코드(D1 `sectors` 테이블의 `index_code`)별로 순회하여 섹터 인덱스 등락률을 수집한다.
| 필드 | 설명 |
|------|------|
| `bstp_nmix_prpr` | 업종 현재지수 |
| `bstp_nmix_prdy_vrss` | 전일 대비 |
| `bstp_nmix_prdy_ctrt` | 등락률 (%) |
| `acml_vol` | 누적 거래량 |
### 개별 종목 등락률
```
GET /uapi/domestic-stock/v1/quotations/inquire-price
TR ID: FHKST01010100
```
D1 `sectors` 테이블의 한국 종목 전체 순회. Self-throttle 15 req/sec.
주요 수집 필드:
| 필드 | 설명 |
|------|------|
| `stck_prpr` | 현재가 |
| `prdy_ctrt` | 등락률 (%) |
| `acml_vol` | 거래량 |
| `acml_tr_pbmn` | 거래대금 (원) — 대표주 선정 기준 |
---
## Step 2 — 선정 (deterministic, LLM 없음)
### 섹터 선정
수집한 섹터 인덱스 등락률을 정렬하여 2개를 고정 선정한다.
```
top_sector = 등락률 최고 섹터 (1위)
bottom_sector = 등락률 최저 섹터 (꼴찌)
```
### 대표주 선정 기준
각 섹터 내 종목을 아래 기준으로 정렬하여 상위 N개를 대표주로 선정한다.
**기준: 거래대금 상위 필터 → 등락률 정렬**
```
1. 섹터 내 전체 종목을 거래대금 기준 상위 50%로 필터
2. 필터된 종목 중 등락률 절댓값 내림차순 정렬
3. 상위 3개 선정
```
> 단순 등락률 1위(A안)를 쓰지 않는 이유: 소형주·저유동성 종목이 거래 없이 튀는 케이스를 제거하기 위함.
> 거래대금 필터(B안)를 적용하면 실질적으로 움직이는 종목만 남아 "대표주"다운 결과가 나온다.
### 선정 결과 구조
```typescript
interface SectorResult {
sector: string; // 섹터 슬러그
sector_name: string; // 표시명 (예: "반도체")
index_change_pct: number; // 섹터 인덱스 등락률
rep_stocks: {
ticker: string;
name: string;
change_pct: number; // 개별 등락률
volume_amount: number; // 거래대금
}[]; // 최대 3개
}
// 최종 선정
top_sector: SectorResult // 최다 상승 섹터
bottom_sector: SectorResult // 최다 하락 섹터
```
---
## Step 3 — 요약
### Perplexity Search 쿼리
선정된 섹터/종목 기준으로 **동적 쿼리**를 구성한다. 고정 쿼리가 아니라 매 시간 선정 결과에 따라 달라진다.
공식문서 예시 쿼리
```javascript
import Perplexity from '@perplexity-ai/perplexity_ai';
const client = new Perplexity({
apiKey: process.env.PERPLEXITY_API_KEY,
});
try {
const search = await client.search.create({
query: "쿼리",
max_results: 10,
max_tokens: 25000,
max_tokens_per_page: 2048,
country: "KR",
search_recency_filter: "day" //hour, week, month, year
});
for (const result of search.results) {
console.log(`${result.title}: ${result.url}`)
}
} catch (error) {
console.error(error)
}
```
공식문서 예시 응답
```json
{
"results": [
{
"date": "2026-05-26",
"last_updated": "2026-05-26",
"snippet": "SK hynix has unveiled iHBM, a next-generation HBM (high-bandwidth memory) cooling technology that can lower thermal resistance by more than 30% compared with existing models.\nSK hynix plans to apply the technology to next-generation HBM, including HBM5.\nOn the 26th, SK hynix unveiled the ‘iHBM’ technology, which reduces heat generation by embedding an integrated cooling element (ICE) into the HBM package.\n...\niHBM features placing a thermal control device (ICE) inside the D2D PHY area, where heat concentrates the most, creating a dedicated path for heat to escape.\nIt lowers thermal resistance by more than 30% compared with existing implementations, helping maintain stable operation even in high-temperature·high-load environments.\n...\nSK hynix plans to apply the iHBM technology starting with next-generation products such as HBM5.",
"title": "SK hynix unveils ‘iHBM’ technology that tames heat···Thermal resistance 30%↓",
"url": "https://www.khan.co.kr/en/article/202605261450037"
},
{
"date": "2026-05-26",
"last_updated": "2026-05-26",
"snippet": "- SK Hynix said it unveiled **iHBM** technology designed to reduce heat in high-bandwidth memory, or **HBM**, and improve its structural limitations.\n...\nSK Hynix on May 26 unveiled iHBM, a new technology aimed at improving the performance of high-bandwidth memory, or HBM.\nThe company said an integrated cooling element, or ICE, reduces heat and helps overcome structural limits in HBM.\nSK Hynix said it developed iHBM by placing an ICE inside HBM to create an additional heat dissipation path.\nThe company uses a silicon-based material that does not conduct electricity but offers high thermal conductivity.\n...\nHBM has so far relied on releasing heat outward through its core dies.\nHBM stacks DRAM chips vertically, like building a high-rise out of single-story homes.\nPerformance improves as more chips are stacked, but heat buildup has long been a persistent problem.\nApplying iHBM can cut thermal resistance by more than 30% from existing levels, SK Hynix said.\n...\nSK Hynix plans to apply iHBM to next-generation products including HBM5, the eighth generation of HBM.",
"title": "SK Hynix Unveils ‘iHBM’ Technology to Cut Heat in HBM Chips",
"url": "https://en.bloomingbit.io/feed/news/112876"
},
{
"date": "2026-05-26",
"last_updated": "2026-05-26",
"snippet": "SK하이닉스가 발열을 획기적으로 낮춘 메모리 설루션 ‘iHBM’ 기술을 26일 공개했다.\nHBM(고대역폭 메모리, High Bandwidth Memory) 패키지에 일체형 냉각 요소 ‘ICE(Integrated Cooling Elements)’를 적용한 기술이라고 소개했다.\nICE는 전기가 통하지 않지만 열 전도가 높은 실리콘 소재를 활용해 HBM 패키지 내부에 추가적인 열 배출 경로를 형성하는 냉각 요소다.\n...\nSK하이닉스 iHBM 기술은 이러한 발열 문제를 구조적으로 해결한 것이 특징이라고 한다.\n기존 HBM은 열을 코어 다이(Core Die)를 거쳐 외부로 내보내는 간접적인 방식에 의존해 왔는데 iHBM은 발열이 가장 집중되는 D2D PHY 영역 안에 열 제어 소자(ICE)를 넣어 열이 빠져 나갈 수 있는 전용 경로(Heat Path)를 별도로 만들었다는 설명이다.\n...\n가령 기존 HBM이 일반 면 티셔츠라면 iHBM은 땀과 열이 많이 나는 부위에 전용 통풍 소재가 적용된 기능성 메시 티셔츠로 볼 수 있다.\n이를 통해 기존 대비 열저항(Thermal Resistance)을 30% 이상 낮추고 고온·고부하 환경에서도 안정적인 동작 특성을 유지할 수 있다고 SK하이닉스 측은 전했다.\n...\n특히 고객사의 기존 SiP(System in Package, 시스템 통합 패키지) 환경과 높은 설계 호환성을 확보한 만큼 고객들은 큰 설계 변경 없이 즉시 적용이 가능해 실질적인 기술 도입 부담을 낮췄다고 SK하이닉스 측은 소개했다.\nSK하이닉스는 iHBM 기술을 HMB5 등 차세대 제품부터 적용해 고성능 컴퓨팅(HPC), AI 데이터센터 등 초고집적·초고대역폭 환경에서 요구되는 열 관리 수준을 충족하고 시스템 전반의 안정성과 운영 효율을 높인다는 계획이다.",
"title": "다시 앞서가는 SK하이닉스, 발열 잡는 'iHBM' 기술 공개… “HBM5 등 ...",
"url": "https://www.donga.com/news/amp/all/20260526/133991927/1"
},
{
"date": "2026-05-26",
"last_updated": "2026-05-26",
"snippet": "SK hynix unveiled next-generation technology that reduces heat by inserting a cooling element inside a high bandwidth memory (HBM) package.\nOn the 26th, SK hynix said it introduced \"iHBM,\" a technology that embeds an integrated cooling element, ICE, in an HBM package.\nICE is a cooling element that creates an additional heat dissipation path inside HBM by using a silicon material with high thermal conductivity that does not conduct electricity.\n...\nSK hynix's iHBM is characterized by inserting ICE into this section to create a dedicated path for heat to escape.\n...\nSK hynix plans to apply iHBM technology starting with next-generation products such as HBM5.",
"title": "SK hynix debuts iHBM to cut HBM heat and ready rollout from HBM5",
"url": "https://biz.chosun.com/en/en-it/2026/05/26/A5GTBBYN4JDXRG6MKSADZFKV2A/?outputType=amp"
},
{
"date": "2026-05-26",
"last_updated": "2026-05-26",
"snippet": "[이코노미스트 원태영 기자]SK하이닉스가 HBM 패키지에 일체형 냉각 요소 'ICE'를 내재해 발열을 획기적으로 낮춘 'iHBM' 기술을 26일 공개했다.ICE(Integrated Cooling Elements)는 전기는 통하지 않지만 열 전도가 높은 실리콘 소재를 활용해 HBM 패키지 내부에 추가적인 열 배출 경로를 형성하는 냉각 요소를 의미한다.\n폭증하는 AI 연산 수요 대응을 위해 HBM은 적층 단수 확대와 고속화를 거듭하며 성능이 발전하고 있지만, 동시에 발열이 높아지는 문제가 발생할 수 있다.\n이런 이유로 HBM과 GPU를 연결하는 D2D PHY 구간의 발열 밀도를 효과적으로 제어하는 기술이 차세대 HBM 기술 경쟁력의 핵심으로 부상하고 있다.iHBM 기술은 이 문제를 구조적으로 해결한 것이 특징이다.\n기존 HBM은 열을 코어 다이(Core Die)를 거쳐 외부로 내보내는 간접적인 방식에 의존해 왔다.\niHBM은 발열이 가장 집중되는 D2D PHY 영역 안에 열 제어 소자(ICE)를 넣어, 열이 빠져 나갈 수 있는 전용 경로(Heat Path)를 별도로 만든 것이 핵심이다.\n이를 통해 기존 대비 열저항(Thermal Resistance)을 30% 이상 낮추고, 고온·고부하 환경에서도 안정적인 동작 특성을 유지할 수 있다.양산성 측면에서도 강점을 갖췄다.\n이미 시장에서 검증된 Advanced MR-MUF 기반 WLP 공정을 적용해 안정적인 대량 생산이 가능하다.\n고객사의 기존 SiP 환경과 높은 설계 호환성을 확보한 만큼, 고객들은 큰 설계 변경 없이 즉시 적용이 가능해 실질적인 도입 부담도 낮췄다.SK하이닉스는 iHBM 기술을 HBM5 등 차세대 제품부터 적용해 고성능 컴퓨팅(HPC), AI 데이터센터 등 초고집적·초고대역폭 환경에서 요구되는 열 관리 수준을 충족하며 시스템 전반의 안정성과 운영 효율을 높인다는 계획이다.\nSK하이닉스 이강욱 부사장(PKG개발 담당)은 'iHBM은 메모리 설계 역량과 첨단 패키징 기술을 결합해 개발한 발열 최소화를 위한 최적의 설루션'이라면서 'AI 환경에서 고객이 필요로 하는 가치를 선제적으로 제공하며 AI 메모리 리더십을 더욱 공고히 하겠다'고 말했다.",
"title": "SK하이닉스, 발열 잡는 메모리 솔루션 ‘iHBM' 기술 공개",
"url": "https://economist.co.kr/article/view/ecn202605260016"
},
{
"date": "2026-05-26",
"last_updated": "2026-05-26",
"snippet": "HBM 패키지에 냉각 요소 넣어 열 방출 경로 개선SK하이닉스가 고대역폭메모리(HBM) 패키지에 일체형 냉각 요소를 내재해 발열을 획기적으로 낮춘 'iHBM' 기술을 26일 공개했다.(",
"title": "SK하이닉스, 발열 잡는 메모리 설루션 'iHBM' 기술 공개",
"url": "https://www.news1.kr/industry/general-industry/6177179"
},
{
"date": "2026-05-26",
"last_updated": "2026-05-26",
"snippet": "As thermal management emerges as a key challenge for HBM, SK hynix has unveiled its iHBM solution, which integrates cooling elements (ICEs) directly into the HBM package.\nThe company plans to adopt the technology in next-generation products, including HBM5, according to its press release.\nAccording to SK hynix, unlike conventional HBM designs that dissipate heat through the core die, iHBM integrates cooling elements (ICEs), made of thermally conductive, electrically non-conductive silicon-based materials, directly into the D2D PHY between HBM and GPUs, where heat is most concentrated.\nThe company said the technology reduces thermal resistance by 30% and improves operating stability.\nAs highlighted by SK hynix, the iHBM solution adopts a structural approach to thermal management by creating an additional heat dissipation path within the package.",
"title": "[News] SK hynix Introduces iHBM Solution, Targets HBM5 Adoption ...",
"url": "https://www.trendforce.com/news/2026/05/26/news-sk-hynix-introduces-ihbm-solution-targets-hbm5-adoption-with-30-thermal-resistance-reduction/"
},
{
"date": "2026-05-26",
"last_updated": "2026-05-26",
"snippet": "SEOUL, May 26 (AJP) - South Korean chipmaker SK hynix Inc.\non Tuesday unveiled its \"iHBM\" (Integrated High Bandwidth Memory) technology, a memory solution incorporating Integrated Cooling Elements (ICE) directly into the High Bandwidth Memory (HBM) package to dramatically reduce heat and enhance the efficiency of overall AI systems.1\nThe company plans to apply the iHBM technology starting with its next-generation products, such as HBM5, to meet the stringent thermal management requirements of ultra-high integration and ultra-high bandwidth environments like High-Performance Computing (HPC) and AI data centers.\nSK hynix developed iHBM to address rising heat issues as HBM performance advances through increased stacking and faster speeds to handle soaring AI processing demands.\nThe technology structurally resolves this issue by placing a thermal control element (ICE) in the Die-to-Die Physical Layer (D2D PHY) area—where heat is most concentrated—creating a separate, dedicated \"Heat Path\".\nThis method, which contrasts with the traditional indirect approach of relying on the Core Die to expel heat, reduces thermal resistance by over 30 percent, ensuring stable operating characteristics even in high-temperature and high-load environments.\nICE uses a silicon material with high thermal conductivity but no electrical conductivity to form the additional heat dissipation route inside the HBM package.\n\"iHBM is the optimal solution for minimizing heat generation, developed by combining memory design capability and advanced packaging technology,\" said Lee Kang-wook, Vice President of Package Development at SK hynix.",
"title": "SK hynix unveils iHBM cooling tech to tackle AI chip heat - aju press",
"url": "https://m.ajupress.com/amp/20260526133355516"
},
{
"date": "2026-05-26",
"last_updated": "2026-05-26",
"snippet": "SK Hynix unveiled on the 26th the ‘iHBM’ technology that significantly reduces heat generation issues in high-bandwidth memory (HBM) used in AI accelerators.\n...\nSK Hynix stated that it has resolved this issue with iHBM technology, thereby enhancing AI efficiency.\nThe iHBM technology lowers heat generation by integrating an all-in-one thermal control element called ICE within the HBM package.\nHeat is most intensively generated between the base die containing the HBM chip, where data moves at ultra-high speeds, and the AI accelerator die.\nThe core innovation of iHBM is the creation of a dedicated path for heat dissipation by placing ICE between the dies.\nSK Hynix noted, “Through this, we have reduced thermal resistance by over 30% compared to conventional methods and can maintain stable operation even in high-temperature and high-load environments.”",
"title": "SK Hynix Unveils iHBM for AI Heat Reduction",
"url": "https://www.chosun.com/english/industry-en/2026/05/26/7OMFFQE3IBAL3ERSXM22PIEUZ4/"
},
{
"date": "2026-05-26",
"last_updated": "2026-05-26",
"snippet": "",
"title": "Новости по тегу hbm, страница 1 из 10 - 3DNews",
"url": "https://3dnews.ru/tags/hbm"
}
],
"id": "1a28311e-1833-47c6-b880-c4bb971d6dbc",
"server_time": "1.594s"
}
```
```typescript
const queries = {
top: `${top_sector.sector_name} ${top_sector.rep_stocks[0].name} 상승 이유 오늘`,
bottom: `${bottom_sector.sector_name} ${bottom_sector.rep_stocks[0].name} 하락 이유 오늘`,
};
// 공통 파라미터
{
max_results: 5,
search_recency_filter: "day",
country: "KR",
search_language_filter: ["ko"],
}
```
### Gemma 4 요약 프롬프트 방향
```
입력:
- 섹터명, 인덱스 등락률
- 대표주 3개 + 각 등락률
- Perplexity raw 검색결과 (snippets)
출력 (JSON):
{
"sector": "반도체",
"index_change": "+2.3%",
"summary": "HBM 수출 규제 완화 기대감에 반도체 업종이 강세...", // 2~3문장
"rep_stocks": [
{ "ticker": "005930", "name": "삼성전자", "change": "+3.1%", "reason": "HBM3E 공급 계약 소식" },
...
],
"source": "https://..."
}
```
프롬프트 원칙:
- 사실 관찰만, 예측/추천 금지
- 경어, 신문 칼럼 말투
- 검색결과에 단서 없으면 시세 동향만 기술
### D1 저장
```sql
-- ai_summary 테이블 upsert
INSERT INTO ai_summary (market, kind, target_date, ticker, payload, model, created_at)
VALUES ('kr', 'sector_hourly', DATE('now'), NULL, ?, ?, unixepoch())
ON CONFLICT (market, kind, target_date, COALESCE(ticker, ''))
DO UPDATE SET payload = excluded.payload, created_at = excluded.created_at;
```
`payload` JSON 구조:
```json
{
"hour": "11:00",
"top_sector": { ...SectorResult + summary },
"bottom_sector": { ...SectorResult + summary },
"all_sectors": [ ...전 섹터 인덱스 등락률 ],
"updated_at": 1234567890
}
```
---
## 출력 — 푸시 알림
기존 웹 푸시 채널 그대로 활용. 간결하게 2줄.
```
[11:00 한국장]
📈 반도체 +2.3% | 삼성전자 +3.1% — HBM 수출 규제 완화 기대
📉 조선 -1.8% | HD현대중공업 -2.4% — 원자재 가격 상승 압박
```
---
## 출력 — 대시보드 카드
대시보드 한국장 탭에 표시되는 카드 구조.
```
┌─────────────────────────────────────────────────┐
│ 11:00 기준 │
│ │
│ 📈 반도체 +2.3% 📉 조선 -1.8% │
│ ┌──────────────────┐ ┌──────────────────┐ │
│ │삼성전자 +3.1% │ │HD현대중공업 -2.4%│ │
│ │SK하이닉스 +2.8% │ │삼성중공업 -1.9%│ │
│ │DB하이텍 +1.9% │ │한화오션 -1.5%│ │
│ └──────────────────┘ └──────────────────┘ │
│ HBM 수출 규제 완화 기대감 원자재 가격 상승 압박 │
│ 출처: [조선일보 링크] 출처: [한국경제 링크] │
└─────────────────────────────────────────────────┘
━ 전 섹터 등락률 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
반도체 +2.3% ████████
방산 +1.1% ████
바이오 +0.3% █
금융 -0.2%
2차전지 -1.2% ▓▓▓▓
조선 -1.8% ▓▓▓▓▓▓
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
```
---
## 스케줄링
```toml
# wrangler.toml
crons = [
"0 22 * * *", # 07:00 KST 매일 (미장)
"0 0-7 * * 1-5", # 09:00~16:00 KST 평일 매시간 (한국장)
]
```
Worker 내부 시간 필터:
```typescript
function isKrMarketOpen(): boolean {
const now = new Date();
// KST = UTC+9
const kstHour = (now.getUTCHours() + 9) % 24;
const kstMin = now.getUTCMinutes();
const kstTime = kstHour * 100 + kstMin;
// 09:00 ~ 15:30
if (kstTime < 900 || kstTime >= 1530) return false;
// 공휴일 체크 (D1 kr_holidays 테이블)
const today = toKSTDateString(now);
const holiday = await env.DB.prepare(
'SELECT 1 FROM kr_holidays WHERE date = ?'
).bind(today).first();
return !holiday;
}
```
---
## D1 추가 테이블
기존 스키마 대비 한국장 파이프라인에서 추가되는 테이블.
```sql
-- 한국 공휴일 (연간 사전 입력)
CREATE TABLE IF NOT EXISTS kr_holidays (
date TEXT PRIMARY KEY -- 'YYYY-MM-DD'
);
```
기존 `sectors` 테이블에 업종 인덱스 코드 컬럼 추가:
```sql
ALTER TABLE sectors ADD COLUMN index_code TEXT; -- KRX 업종코드
```
---
## 배치 step 구성
> **Agents SDK · Durable Object 는 사용하지 않는다.** 초기 설계에서는 `StockRadarAgent` Durable Object(Agents SDK)의 `this.step()` 체크포인트를 가정했으나, 미장 배치를 모듈 함수 + D1 `step_cache`(migration `0006_step_cache.sql`)로 전환하면서 DO 를 제거했다. 한국장도 동일한 패턴을 따른다 — `worker/batch/stockRadar.ts` 의 `fetchUSMarket(env, runId)` 와 같은 구조의 평범한 모듈 함수.
step 헬퍼는 `(env, runId, stepName, fn)` 시그니처다. `step_cache` 에 `(run_id, step_name)` 히트가 있으면 `fn` 을 실행하지 않고 저장된 결과를 반환하고, 미스면 `fn` 실행 후 결과를 저장한다. 같은 `runId` 로 재실행하면 이미 끝난 step 은 건너뛰어 부분 재개가 된다. Cloudflare Cron 은 자동 재시도가 없으므로 재실행은 수동 트리거 또는 외부 알림(Phase 5)으로 한다.
한국장은 매시간 실행되므로 `runId` 에 거래일과 시각을 함께 넣어 슬롯마다 분리한다 (다른 시각끼리 `step_cache` 충돌 없음).
```typescript
export async function fetchKRMarket(env: Env, runId?: string) {
if (!(await isKrMarketOpen(env))) return;
// runId = 거래일+시각 식별자. 같은 슬롯 재시도 시 step_cache 히트로 부분 재개.
const id = runId ?? `kr-${krDateHour()}`; // 예: "kr-2026-05-26-11"
// Step 1: 수집
const token = await step(env, id, "kr_token", () => getKISToken(env));
const indexes = await step(env, id, "kr_indexes", () => fetchSectorIndexes(env, token));
const quotes = await step(env, id, "kr_quotes", () => fetchKRQuotes(env, token));
// Step 2: 선정 (순수 함수, step 불필요)
const { topSector, bottomSector } = selectSectors(indexes, quotes);
// Step 3: 요약
const search = await step(env, id, "kr_search", () => searchSectorNews(env, topSector, bottomSector));
const summary = await step(env, id, "kr_summarize", () => summarizeKR(env, topSector, bottomSector, search));
// 저장 + 전송
await step(env, id, "kr_persist", () => persistKRSnapshot(env, summary));
await step(env, id, "kr_push", () => sendKRPush(env, summary));
}
```
step 헬퍼 본체는 미장과 공유한다.
```typescript
async function step<T>(env: Env, runId: string, name: string, fn: () => Promise<T>): Promise<T> {
const cached = await env.DB.prepare(
`SELECT result FROM step_cache WHERE run_id = ? AND step_name = ? LIMIT 1`,
).bind(runId, name).first<{ result: string }>();
if (cached) return JSON.parse(cached.result) as T;
const out = await fn();
// OR IGNORE: 동시 재시도 충돌 방어(first-write-wins).
await env.DB.prepare(
`INSERT OR IGNORE INTO step_cache (run_id, step_name, result, created_at) VALUES (?, ?, ?, ?)`,
).bind(runId, name, JSON.stringify(out), Math.floor(Date.now() / 1000)).run();
return out;
}
```
Step 2 선정은 순수 함수라 step 체크포인트가 불필요하다 — 외부 호출이 없어 실패 시나리오가 없다. 반대로 LLM 요약처럼 일시적 실패가 `step_cache` 에 sticky 하게 굳으면 곤란한 단계는, 미장 헤드라인 번역처럼 `step()` 으로 감싸지 않고 매 run fresh 시도하는 선택지도 있다.
---
## 비용 추정
| 항목 | 계산 | 월 비용 |
|------|------|--------|
| Perplexity Search | 2쿼리/시간 × 6.5h × 22일 = 286건 | ~$1.5 |
| Workers AI Gemma 4 | 2섹터 요약/시간 × 6.5h × 22일 | ~$0.5 |
| KIS API | 무료 | $0 |
| **소계** | | **~$2/월** |
미장 변동비 대비 소폭 증가. 전체 월 예상 비용은 $16~18로 유지.