Skip to content

Commit 596e2aa

Browse files
committed
수정: L3 서사·시뮬레이션의 증거와 실행 무결성을 봉인한다
1 parent 1628641 commit 596e2aa

55 files changed

Lines changed: 3508 additions & 422 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎mainPlan/v1-readiness-review/01-verdict-ledger.md‎

Lines changed: 69 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -49,21 +49,20 @@ Guard는 현재 레이어의 source를 동결한 뒤 한 번 실행한다. Guard
4949

5050
### 세션 인계
5151

52-
- 현재 계층: **L2.5 dataHub** (진입 대기)
53-
- 최근 완료한 레이어: **L2 analysis/macro/quant/industry/credit 전체 완료** (2026-08-01).
54-
다섯 엔진의 전체 source와 실제 호출자를 데이터 계약, 결측, 시점, 오류 투명성,
55-
발행 경계 기준으로 대조했다. 공식 strict Guard는 1,792파일, 7개 규칙과 6개 외부
56-
게이트 모두 통과했다. 그 앞은 L0 core, L1 gather/providers,
57-
L1.5 scan/frame/synth/reference 완료다.
58-
- 현재 작업 단위: **L2.5 dataHub 전체 안정화**. 파일이나 함수 하나를 별도 완료 단위로
52+
- 현재 계층: **L4 소비자·AI·MCP** (진입 대기)
53+
- 최근 완료한 레이어: **L3 story·simulate 전체 완료** (2026-08-01). Story 381개,
54+
simulate 509개, L3 bridge 뒤 DataHub 606개와 architecture 계약이 통과했다. 공식 strict
55+
Guard는 1,796파일, 7개 규칙과 6개 외부 게이트 모두 통과했다. 그 앞은 L0 core,
56+
L1 gather/providers, L1.5 scan/frame/synth/reference, L2 다섯 엔진, L2.5 dataHub 완료다.
57+
- 현재 작업 단위: **L4 공개 소비자 전체 안정화**. 파일이나 함수 하나를 별도 완료 단위로
5958
쪼개지 않는다.
60-
- L2.5 완료 조건: dataHub의 catalog와 query 공개 축, factor와 narrative projection,
61-
로컬·원격 materialization, PIT envelope, receipt와 cache, 실제 L2·L3 소비자를
62-
전수 대조한다. 결함 수정과 집중 회귀를 끝내고 source 동결 뒤 공식 Guard, 원장,
63-
커밋, push까지 닫는다.
64-
- 다음 첫 행동: `src/dartlab/dataHub` 전체 source와 catalog/query 호출자, operation
65-
계약을 읽고 상태·시점·오류·재현성 경계를 정적 census로 만든다.
66-
- 금지: 함수나 파일 하나만 끝내고 완료 보고, L3 이상 수정 선행,
59+
- L4 완료 조건: AI tool dispatch와 serialization, public capability catalog, Web/API/MCP와
60+
브라우저 소비자가 L0-L3의 status·gap·provenance·asOf를 보존하는지 전수 대조한다.
61+
실행 allowlist, payload budget, async 경계, 공개 API drift와 release gate를 닫고 source
62+
동결 뒤 공식 Guard, 원장, 커밋, push까지 완료한다.
63+
- 다음 첫 행동: `src/dartlab/ai`, Web/API/MCP 진입점과 capability catalog의 실제 호출
64+
그래프를 만들고 실행 권한·직렬화·상태 손실을 제품 경로에서 재현한다.
65+
- 금지: 함수나 파일 하나만 끝내고 완료 보고, 하위 상태를 성공으로 승격,
6766
중간 source에서 공식 Guard 반복
6867

6968
## L1.5 scan, frame, synth, reference 순차 안정화 원장 (2026-07-30)
@@ -3110,3 +3109,59 @@ source와 실제 호출자의 최종 순회, source freeze, 공식 Guard다.
31103109
**판정: L2.5 dataHub는 현재 지원하는 catalog, query, PIT, paging, materialization과 remote
31113110
worker 범위에서 요청·결과·원천 identity를 검증하고, 증명하지 못한 exact와 completion을
31123111
발행하지 않는다.** L2.5를 완료하고 다음 계층인 L3 story·simulate로 이동한다.
3112+
3113+
### L3 최종 판정: Story 증거 계약과 simulate 실행 무결성 동결 (2026-08-01)
3114+
3115+
**상태: L3 전체 완료.** Story와 simulate를 각각
3116+
표현 조합과 상태 전이 실행이라는 책임으로 분리해 보되, 두 경로가 공유하는 시점, 근거,
3117+
결측, 해시, 외부 데이터 admission 경계를 함께 대조했다. 검증되지 않은 값과 실행물을
3118+
부분 성공으로 승격하는 대신 구조화 gap과 blocked 상태로 닫았다.
3119+
3120+
1. **범위와 실제 호출자.** Story의 Company 진입점, report type, block builder, narrative,
3121+
lens product, HTML·Markdown·JSON emitter, IPO와 전문 report 소비자를 확인했다. simulate는
3122+
Company 진입점, DataHub simulation input bridge, scenario와 expectation cycle, world model,
3123+
law·action·path admission, executable hash, run result와 evidence projection을 대조했다.
3124+
DART와 EDGAR Company facade, architecture layer test, L2.5 DataHub 소비자까지 포함했다.
3125+
2. **제품 결함 재현.** Story는 HTML에 원문 문자열을 그대로 넣고 opaque 객체를 문자열로
3126+
JSON 변환했으며, 결측 forecast·asset·valuation·risk를 0처럼 표현했다. lens status와
3127+
gap을 잃고 `basePeriod` 요청에도 최신 macro·quant·industry·thesis를 섞을 수 있었다.
3128+
simulate는 query identity 안에 runtime Company를 넣고 구조화 DataEvidence를 축약했으며,
3129+
WACC·순차입금·FCF 결측을 현재값 또는 압축 배열로 바꿨다. admission은 raw law row와
3130+
식별 action을 서명 없이 신뢰했고 executable hash가 callable closure·global·전략과
3131+
변수·행동 계약 전체를 봉인하지 않았다.
3132+
3. **단일 SSOT와 발행 경계.** Story는 `basePeriod`, canonical lens `status=usable`,
3133+
`lensGaps`, Block metadata와 strict JSON tree가 발행 경계다. 검증된 narrative 입력이
3134+
없으면 자체 수치 claim을 만들지 않는다. simulate는 canonical DataQuery와 private runtime
3135+
binding을 분리하고 DataEvidence, partition content seal, catalog·data snapshot, lineage를
3136+
결과까지 보존한다. identified law·action과 admitted path는 신뢰 issuer가 서명한 receipt,
3137+
cutoff·frequency·horizon·semantics 일치가 필요하며 실행 identity는 256-bit canonical hash다.
3138+
4. **수정과 fail-closed 범위.** 모든 Story 출력에서 외부 문자열을 escape하고 JSON은
3139+
dataclass·날짜·Decimal·Enum·Path를 포함한 명시 타입만 직렬화한다. 결측은 0 대신 `-`,
3140+
None, gap으로 남기고 lens 미완전 결론을 차단했다. report 선택에 필요한 block만 계산한다.
3141+
Company `story(reportType=)` 별칭과 충돌 검사를 DART·EDGAR에 맞췄다. simulate는 strict query
3142+
params, 단일 subject runtime binding, share·net debt 근거, WACC와 FCF 유효성, snapshot 포함
3143+
input hash를 강제한다. world receipt 검증과 executable hash v2는 mutable closure·global,
3144+
callable code/default, law·action·strategy·variable 전체를 봉인하고 opaque·cycle을 거절한다.
3145+
5. **실제 공개 행동, 정확성, 속도, 메모리.** Story의 HTML과 JSON은 원문 삽입과 opaque
3146+
fallback 없이 렌더링되고 lens gap을 세 형식에서 유지한다. 과거 industry와 historical
3147+
thesis처럼 현재 원천으로 증명하지 못하는 경로는 최신 결론 대신 unsupported를 낸다.
3148+
selective report build로 불필요한 100개 이상 block 전수 계산을 피한다. simulate 결과는
3149+
revenue와 FCF의 내부 결측 위치를 보존하고, 실패 assertion·gap·truncation이 하나라도 있으면
3150+
quality를 partial로 내린다. DataHub stress audit 21개는 188.82초에 통과해 장기 경로도
3151+
timeout 우회 없이 확인했다.
3152+
6. **회귀와 Guard.** Story 20개 파일을 독립 pytest process로 실행해 `381 passed`,
3153+
simulate 41개 파일은 `509 passed`, L3 bridge 변경 뒤 DataHub는 `606 passed, 4 skipped`,
3154+
architecture import-direction은 `1 passed`다. 변경 Python 전체 Ruff format/check,
3155+
Pyright `0 errors, 0 warnings`, compileall, diff whitespace와 U+2013/U+2014 검사가 통과했다.
3156+
source 동결 뒤 공식 strict Guard는 1,796파일, 7/7 규칙과 cycleScan,
3157+
architecturePytest, folderMirror, gatherGate, providerGate, publicApiSmoke를 모두 통과했다.
3158+
7. **남은 부채와 판정.** Story Block은 현재 block 단위 근거와 gap은 보존하지만 모든 표시값에
3159+
개별 ref·source·date·status를 붙이는 value-level provenance 모델은 아직 없다. `basePeriod`는
3160+
재무기간이지 모든 외부 원천의 완전한 knownAt cutoff가 아니므로 역사 industry·thesis는
3161+
지원하지 않는다. 기존 signed receipt가 없는 simulate 자산은 admitted로 승격되지 않는다.
3162+
이 제한은 현재 결과에 숨지 않고 partial·unsupported·blocked로 격리했으며 L4 소비자는
3163+
이 상태를 삭제하거나 완전 성공으로 바꾸지 않아야 한다.
3164+
3165+
**판정: L3 Story와 simulate는 증명되지 않은 값, 과거시점 결론, 실행 admission을 성공으로
3166+
승격하지 않고 구조화 결손과 차단 상태를 보존한다.** L3를 완료하고 L4 소비자·AI·MCP로
3167+
이동한다.

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,8 +119,13 @@ def simulationInputs(
119119
if not periods or any(type(period) is not str for period in periods):
120120
raise ValueError("분기 재무 periods가 비었거나 유효하지 않습니다")
121121
series, effectiveAsOf, latestAsOf, requestedAsOf = sliceFinanceSeries(rawSeries, periods, asOf)
122+
from dartlab.analysis.financial._companyLookup import _getSharesOutstandingInput
123+
124+
sharesEvidence = _getSharesOutstandingInput(resolvedCompany, basePeriod=asOf)
122125
return {
123126
"series": series,
127+
"shares": sharesEvidence["value"] if sharesEvidence is not None else None,
128+
"sharesEvidence": sharesEvidence,
124129
"asOf": effectiveAsOf,
125130
"latestAsOf": latestAsOf,
126131
"requestedAsOf": requestedAsOf,

‎src/dartlab/dataHub/contracts.py‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from __future__ import annotations
44

5+
import math
56
from collections.abc import Iterator
67
from dataclasses import dataclass, field
78
from typing import TYPE_CHECKING, Any, Literal, Mapping
@@ -22,6 +23,27 @@ def _requireStringTuple(value: Any, name: str) -> None:
2223
raise ValueError(f"{name}에는 비어 있지 않은 string만 사용할 수 있습니다")
2324

2425

26+
def _requireJsonTree(value: Any, name: str) -> None:
27+
"""Query identity에 들어가는 값은 주소 repr이 필요 없는 JSON tree로 제한한다."""
28+
if value is None or type(value) in {str, int, bool}:
29+
return
30+
if type(value) is float:
31+
if not math.isfinite(value):
32+
raise ValueError(f"{name}에는 finite float만 사용할 수 있습니다")
33+
return
34+
if isinstance(value, Mapping):
35+
for key, item in value.items():
36+
if type(key) is not str:
37+
raise TypeError(f"{name}의 key는 string이어야 합니다")
38+
_requireJsonTree(item, f"{name}.{key}")
39+
return
40+
if isinstance(value, (list, tuple)):
41+
for index, item in enumerate(value):
42+
_requireJsonTree(item, f"{name}[{index}]")
43+
return
44+
raise TypeError(f"{name}에는 JSON-safe 값만 사용할 수 있습니다")
45+
46+
2547
@dataclass(frozen=True, slots=True)
2648
class TimeContext:
2749
"""Data query의 valid time과 knowledge cutoff."""
@@ -223,6 +245,7 @@ def __post_init__(self) -> None:
223245
_requireStringTuple(self.measures, "DataRequest.measures")
224246
if not isinstance(self.params, Mapping):
225247
raise TypeError("DataRequest.params는 mapping이어야 합니다")
248+
_requireJsonTree(self.params, "DataRequest.params")
226249
if self.subjects and self.universe is not None:
227250
raise ValueError("DataRequest는 subjects와 universe를 동시에 사용할 수 없습니다")
228251

@@ -283,6 +306,7 @@ def __post_init__(self) -> None:
283306
raise TypeError("DataQuery.projection이 유효하지 않습니다")
284307
if not isinstance(self.params, Mapping):
285308
raise TypeError("DataQuery.params는 mapping이어야 합니다")
309+
_requireJsonTree(self.params, "DataQuery.params")
286310
if not isinstance(self.budget, QueryBudget):
287311
raise TypeError("budget은 QueryBudget이어야 합니다")
288312
if not isinstance(self.materialization, MaterializationDirective):

‎src/dartlab/dataHub/entry.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,7 @@ def __call__(
180180
*,
181181
assets: str | Sequence[str] | None = None,
182182
query: CatalogQuery | DataQuery | None = None,
183+
_runtimeBindings: Mapping[str, Mapping[str, Any]] | None = None,
183184
**kwargs: Any,
184185
):
185186
"""Data Workbench의 catalog 또는 query axis를 실행한다.
@@ -232,7 +233,7 @@ def __call__(
232233
assetIds = (assetValue,) if isinstance(assetValue, str) else tuple(assetValue or ())
233234
if activeQuery.continuation is not None and assetIds:
234235
raise ValueError("continuation query는 target 또는 assets override를 허용하지 않습니다")
235-
return executeDataQuery(assetIds, activeQuery)
236+
return executeDataQuery(assetIds, activeQuery, runtimeBindings=_runtimeBindings)
236237
raise KeyError("dataHub axis는 'catalog' 또는 'query'여야 합니다")
237238

238239

‎src/dartlab/dataHub/execution.py‎

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import dataclasses
66
import hashlib
77
import time
8-
from collections.abc import Sequence
8+
from collections.abc import Mapping, Sequence
99
from concurrent.futures import ThreadPoolExecutor
1010
from concurrent.futures import TimeoutError as FutureTimeoutError
1111

@@ -306,7 +306,12 @@ def _uncoveredMarkets(
306306
return rows
307307

308308

309-
def executeDataQuery(assetIds: Sequence[str], query: DataQuery) -> DataResult:
309+
def executeDataQuery(
310+
assetIds: Sequence[str],
311+
query: DataQuery,
312+
*,
313+
runtimeBindings: Mapping[str, Mapping[str, object]] | None = None,
314+
) -> DataResult:
310315
"""Asset IDs를 resolve, validate, execute, project해 하나의 DataResult로 반환한다.
311316
312317
Capabilities:
@@ -326,6 +331,18 @@ def executeDataQuery(assetIds: Sequence[str], query: DataQuery) -> DataResult:
326331
startedAt = time.perf_counter()
327332
deadline = startedAt + query.budget.timeoutMs / 1000
328333
materialization = query.materialization
334+
runtimeBindings = runtimeBindings or {}
335+
if runtimeBindings and (query.continuation is not None or materialization.mode != "runtime"):
336+
raise ValueError("runtime binding은 새 runtime query에서만 사용할 수 있습니다")
337+
if runtimeBindings:
338+
if set(runtimeBindings) != {"analysis.simulationInputs"}:
339+
raise ValueError("runtime binding은 simulation input asset에만 허용됩니다")
340+
binding = runtimeBindings["analysis.simulationInputs"]
341+
if set(binding) != {"company"} or len(query.subjects) != 1:
342+
raise ValueError("simulation runtime binding은 단일 subject Company만 허용합니다")
343+
companySubject = str(getattr(binding["company"], "stockCode", ""))
344+
if not companySubject or companySubject != query.subjects[0]:
345+
raise ValueError("runtime binding Company와 query subject가 일치하지 않습니다")
329346
query = dataclasses.replace(
330347
query,
331348
materialization=MaterializationDirective(),
@@ -384,6 +401,8 @@ def executeDataQuery(assetIds: Sequence[str], query: DataQuery) -> DataResult:
384401
ownerPaging = tuple(isPageableOwner(descriptor, activeQuery) for _, descriptor, activeQuery in resolved)
385402
pagingEntry = _pageableEntryPoint(resourcePaging, ownerPaging)
386403
if pagingEntry is not None:
404+
if runtimeBindings:
405+
raise ValueError("pageable query는 process-local runtime binding을 지원하지 않습니다")
387406
_, contractHash = _resolvedIdentity(resolved, query)
388407
return pagingEntry(
389408
assetIds,
@@ -410,7 +429,16 @@ def executeDataQuery(assetIds: Sequence[str], query: DataQuery) -> DataResult:
410429
if stopExecution:
411430
break
412431
executor = ThreadPoolExecutor(max_workers=len(window), thread_name_prefix="dartlab-data")
413-
futures = tuple(executor.submit(_execute, task.descriptor, task.query, task.selector) for task in window)
432+
futures = tuple(
433+
executor.submit(
434+
_execute,
435+
task.descriptor,
436+
task.query,
437+
task.selector,
438+
runtimeBindings.get(task.descriptor.assetId),
439+
)
440+
for task in window
441+
)
414442
abandonWindow = False
415443
try:
416444
for task, future in zip(window, futures, strict=True):

‎src/dartlab/dataHub/executionSupport.py‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -261,13 +261,19 @@ def _requestedMeasures(query: DataQuery) -> tuple[str, ...]:
261261
return tuple(query.measures or projectionMeasures)
262262

263263

264-
def _callableCall(descriptor: DataAssetDescriptor, query: DataQuery, selector: Mapping[str, str]) -> Any:
264+
def _callableCall(
265+
descriptor: DataAssetDescriptor,
266+
query: DataQuery,
267+
selector: Mapping[str, str],
268+
runtimeParams: Mapping[str, Any] | None = None,
269+
) -> Any:
265270
"""Owner-declared callable을 descriptor에 적힌 인자 계약으로 실행한다."""
266271
if descriptor.executorModule is None or descriptor.executorAttribute is None:
267272
raise ValueError("callable executor 경로가 없습니다")
268273
module = importlib.import_module(descriptor.executorModule)
269274
executor = getattr(module, descriptor.executorAttribute)
270275
kwargs = dict(query.params)
276+
kwargs.update(runtimeParams or {})
271277
if descriptor.measureParam:
272278
if descriptor.measureParam in kwargs:
273279
raise ValueError(f"{descriptor.measureParam}은 factor projection이 소유합니다")
@@ -286,13 +292,18 @@ def _callableCall(descriptor: DataAssetDescriptor, query: DataQuery, selector: M
286292
return executor(**kwargs)
287293

288294

289-
def _execute(descriptor: DataAssetDescriptor, query: DataQuery, selector: Mapping[str, str]) -> Any:
295+
def _execute(
296+
descriptor: DataAssetDescriptor,
297+
query: DataQuery,
298+
selector: Mapping[str, str],
299+
runtimeParams: Mapping[str, Any] | None = None,
300+
) -> Any:
290301
if descriptor.executorKind == "engineAxis":
291302
return _engineCall(descriptor, query, selector)
292303
if descriptor.executorKind == "resource":
293304
return _resourceCall(descriptor, query, selector)
294305
if descriptor.executorKind == "callable":
295-
return _callableCall(descriptor, query, selector)
306+
return _callableCall(descriptor, query, selector, runtimeParams)
296307
raise ValueError("catalog-only asset은 materialize할 수 없습니다")
297308

298309

‎src/dartlab/providers/dart/company.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2101,9 +2101,11 @@ def simulate(
21012101
TargetMarkets:
21022102
- KR (getPresetScenarios("KR") + KR elasticity).
21032103
"""
2104+
from dartlab.simulate.registry import validateScenarioSpec
21042105
from dartlab.simulate.run import runScenario
21052106
from dartlab.story.lensProducts import collectLensProducts
21062107

2108+
validateScenarioSpec(scenario, horizon)
21072109
lensBundle = collectLensProducts(
21082110
self,
21092111
engines=("analysis", "credit", "quant", "macro"),
@@ -2981,6 +2983,7 @@ def _storyImpl(
29812983
helper: bool | None = None,
29822984
*,
29832985
type: str | None = None,
2986+
reportType: str | None = None,
29842987
template: str | None = None,
29852988
detail: bool | None = None,
29862989
basePeriod: str | None = None,
@@ -3008,6 +3011,8 @@ def _storyImpl(
30083011
section: 섹션명 ("수익구조" 등). None이면 전체.
30093012
layout: StoryLayout 커스텀. None이면 기본.
30103013
helper: True면 해석 힌트 텍스트 포함. None이면 자동.
3014+
type: 보고서 타입. ``reportType``과 같은 값의 하위 호환 이름.
3015+
reportType: 공식 보고서 타입 이름. ``type``과 함께 주면 같은 값이어야 함.
30113016
preset: 프리셋명 ("executive"/"audit"/"credit"/"growth"/"valuation"). None이면 전체.
30123017
template: 스토리 템플릿 ("성장"/"자본집약"/"지주" 등). "auto"면 자동 판별.
30133018
detail: True면 전체 블록, False면 섹션 요약만. None이면 preset 기본값 또는 True.
@@ -3065,6 +3070,11 @@ def _storyImpl(
30653070

30663071
buildStory = importlib.import_module("dartlab.story.registry").buildStory
30673072

3073+
if reportType is not None:
3074+
if type is not None and type != reportType:
3075+
raise ValueError("story(type=...)와 story(reportType=...)는 같은 값이어야 합니다.")
3076+
type = reportType
3077+
30683078
return buildStory(
30693079
self,
30703080
section=section,

0 commit comments

Comments
 (0)