Skip to content

Commit 1628641

Browse files
committed
수정: dataHub의 시점·페이징·원격 결과 계약을 봉인한다
1 parent 6d65295 commit 1628641

43 files changed

Lines changed: 1686 additions & 277 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: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3046,3 +3046,67 @@ source와 실제 호출자의 최종 순회, source freeze, 공식 Guard다.
30463046
**판정: L2 다섯 엔진은 현재 보유한 원천과 방법론으로 증명 가능한 범위에서 원장과
30473047
일치한다.** 미지원 기능을 수치로 가장하지 않는 발행 경계까지 포함해 L2를 완료하고,
30483048
다음 계층인 L2.5 dataHub로 이동한다.
3049+
3050+
### L2.5 최종 판정: Data Workbench 계약, PIT, 페이징, 원격 실행 동결 (2026-08-01)
3051+
3052+
**상태: L2.5 전체 완료.** 시점·빈티지, 페이징·materialization, 공개 소비자·원격
3053+
제어면을 나눈 세 전문 검토와 master의 전체 호출자 대조를 결합했다. 기존 구현은 owner가
3054+
스스로 적은 exact 선언을 그대로 신뢰했고, native projection으로 PIT 검사를 우회할 수
3055+
있었으며, durable job의 요청과 worker 결과가 같은 논리 쿼리인지 완료 시 다시 증명하지
3056+
않았다. 값과 artifact의 크기, 타입, 수명주기 경계도 여러 계층에 흩어져 있었다.
3057+
3058+
1. **범위와 실제 호출자.** `dataHub`의 catalog·query 공개 진입점, descriptor와 query
3059+
dataclass, universe resolver, feature observation/PIT projection, eager·owner·resource·
3060+
composite paging, continuation CAS와 materialization, sync·async remote client, FastAPI
3061+
control plane, worker lease·heartbeat·completion, analysis simulation input bridge를 함께
3062+
대조했다. PRIVATE callable과 L3·L4 소비자가 catalog 능력을 해석하는 경로도 포함했다.
3063+
2. **제품 결함 재현.** 문자열을 tuple 필드로 넣으면 문자 단위 selector가 됐고 bool이
3064+
숫자 budget으로 통과했다. native projection이 `knownAt` 요청의 관측시점 증명을 건너뛰고,
3065+
owner가 반환한 단일 feature entity를 요청 subject로 다시 붙일 수 있었다. vintage provider
3066+
불일치와 self-declared `asKnown/asOfExact`도 exact로 승격됐다. universe ID 정규화 전
3067+
중복 검사와 public/source 역충돌 누락, locator의 payload read와 source pin 부재,
3068+
nested DataFrame의 `repr` byte 계산, 누적 page gap 유실을 재현했다. 원격면은 oversized
3069+
body 후검사, 외부 평문 HTTP, 논리 쿼리 기본값 차이, job 간 결과 바꿔치기, CAS GC와 새
3070+
참조의 race, 결정적 terminal 오류의 재시도 덮어쓰기가 가능했다.
3071+
3. **단일 SSOT와 발행 경계.** query dataclass가 sequence·bool·projection·visibility의
3072+
strict 계약을 소유한다. remote policy는 request 1MiB, 결과 payload 12,517,376 bytes,
3073+
wire 16MiB와 외부 HTTPS를 한 곳에서 정의한다. durable query는 canonical default를
3074+
채운 `refresh` materialization만 허용하고 continuation·reuse·offline은 계획 부재로
3075+
차단한다. 제출 시 catalog snapshot, ordered AssetRef, contract hash, 요청·해결 수와
3076+
logical query digest를 예상 결과 계약으로 봉인한다. exact PIT는 검증된 admission
3077+
receipt가 없는 한 발행하지 않고 conditional coverage로 남긴다.
3078+
4. **수정과 fail-closed 범위.** sequence scalar와 잘못된 중첩 query를 입구에서 거절하고
3079+
PRIVATE callable은 catalog-only로 고정했다. observation PIT는 FactorProjection과
3080+
관측 envelope를 강제하고 native 우회, subject relabel, provider가 다른 vintage를
3081+
차단했다. canonical universe ID를 먼저 만들고 market별 source alias 정책을 명시했다.
3082+
resource locator는 manifest cache 경계에서 description만 읽어 full source pin과 schema를
3083+
반환하며 payload는 읽지 않는다. 새 native value codec은 mapping·sequence·bytes·scalar와
3084+
중첩 Polars DataFrame을 Arrow로 왕복하고 cycle, 지원하지 않는 객체, logical byte 초과를
3085+
typed gap으로 닫는다. composite는 이전 page gap count를 마지막 page까지 보존한다.
3086+
simulation input bridge는 owner 오류와 결손을 삼키지 않는다.
3087+
5. **원격 내구성과 무결성.** job envelope v2가 canonical query와 예상 결과 계약을 CAS에
3088+
함께 저장한다. completion은 lease, request digest, catalog/asset/contract identity,
3089+
partition content hash·schema·row count, result snapshot과 materialization receipt query
3090+
digest를 다시 확인하고 continuation이 남은 결과를 거절한다. HTTP body와 client stream은
3091+
decode 전에 상한을 적용하며 worker는 413/422를 non-retryable terminal 오류로 기록한다.
3092+
SQLite writer lock 안의 artifact tombstone으로 GC와 새 submit/read의 re-reference race를
3093+
닫고, terminal error code를 보존한다.
3094+
6. **회귀와 Guard.** `tests/dataHub` 42개 파일을 각각 독립 pytest process로 전수 실행해
3095+
`581 passed, 4 skipped`, analysis bridge `5 passed`가 통과했다. 변경 Python은 Ruff
3096+
format/check, Pyright `0 errors, 0 warnings`, compileall, diff whitespace와 U+2013/U+2014
3097+
검사가 통과했다. public API coverage는 `dartlab=34`, `api=6`, `scanAxes=27`,
3098+
`company=9`, `scenarios=43`이다. source 동결 뒤 공식 strict Guard는 1,796파일,
3099+
7/7 규칙과 cycleScan, architecturePytest, folderMirror, gatherGate, providerGate,
3100+
publicApiSmoke를 모두 통과했다.
3101+
7. **남은 부채와 판정.** self-declared vintage를 exact로 승격하지 않으므로 서명된 admission
3102+
receipt 검증 rail이 생기기 전 feature PIT는 conditional이다. 로컬 runtime의 일반 eager
3103+
owner는 기존 thread 동시성을 유지해 비협조 callable을 강제 종료하지 못한다. pageable,
3104+
mixed, materialization과 durable worker의 일반 eager 경로는 fresh child process와
3105+
zero-live supervisor를 사용한다. hard cancellation이 필요한 외부 실행은 durable 경로를
3106+
사용하며, 로컬 in-process timeout의 process 전환은 결과 bundle 상한과 monkeypatch 없는
3107+
import 재구성 계약을 함께 바꾸는 후속 기능 부채로 남긴다. 이 제한은 exact나 완료를
3108+
가장하지 않고 typed gap과 운영 경로 구분으로 격리했다.
3109+
3110+
**판정: L2.5 dataHub는 현재 지원하는 catalog, query, PIT, paging, materialization과 remote
3111+
worker 범위에서 요청·결과·원천 identity를 검증하고, 증명하지 못한 exact와 completion을
3112+
발행하지 않는다.** L2.5를 완료하고 다음 계층인 L3 story·simulate로 이동한다.

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

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -104,20 +104,21 @@ def simulationInputs(
104104

105105
companyFactory = getattr(dartlab, "Company")
106106
company = companyFactory(subject)
107+
if asOf is not None:
108+
_periodKey(asOf)
107109
resolvedCompany: Any = company
108-
try:
109-
quarterly = resolvedCompany._buildFinanceSeries(freq="Q")
110-
except (ValueError, KeyError, AttributeError):
111-
quarterly = None
112-
rawSeries = quarterly[0] if isinstance(quarterly, tuple) and len(quarterly) >= 2 else None
113-
periods = list(quarterly[1]) if isinstance(quarterly, tuple) and len(quarterly) >= 2 else []
114-
if rawSeries:
115-
series, effectiveAsOf, latestAsOf, requestedAsOf = sliceFinanceSeries(rawSeries, periods, asOf)
116-
else:
117-
requestedAsOf = str(asOf) if asOf is not None else "latest"
118-
effectiveAsOf = requestedAsOf
119-
latestAsOf = "latest"
120-
series = None
110+
quarterly = resolvedCompany._buildFinanceSeries(freq="Q")
111+
if not isinstance(quarterly, tuple) or len(quarterly) < 2:
112+
raise ValueError("분기 재무 owner 결과가 (series, periods) 계약을 지키지 않았습니다")
113+
rawSeries, rawPeriods = quarterly[:2]
114+
if not isinstance(rawSeries, dict) or not rawSeries:
115+
raise ValueError("분기 재무 series가 비었습니다")
116+
if not isinstance(rawPeriods, Sequence) or isinstance(rawPeriods, (str, bytes)):
117+
raise ValueError("분기 재무 periods가 sequence가 아닙니다")
118+
periods = list(rawPeriods)
119+
if not periods or any(type(period) is not str for period in periods):
120+
raise ValueError("분기 재무 periods가 비었거나 유효하지 않습니다")
121+
series, effectiveAsOf, latestAsOf, requestedAsOf = sliceFinanceSeries(rawSeries, periods, asOf)
121122
return {
122123
"series": series,
123124
"asOf": effectiveAsOf,

‎src/dartlab/dataHub/catalog/discovery.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -348,6 +348,7 @@ def _declaredAssets(provider: Mapping[str, Any]) -> Iterable[DataAssetDescriptor
348348
validTimeParam=executorParams["validTimeParam"],
349349
knowledgeTimeParam=executorParams["knowledgeTimeParam"],
350350
)
351+
visibility = str(spec.get("visibility", "LOCAL"))
351352
yield DataAssetDescriptor(
352353
assetId=assetId,
353354
assetVersionId=f"asset:{_digest(payload)}",
@@ -357,9 +358,9 @@ def _declaredAssets(provider: Mapping[str, Any]) -> Iterable[DataAssetDescriptor
357358
label=str(spec.get("label", assetId)),
358359
description=str(spec.get("description", spec.get("label", assetId))),
359360
sourceRef=f"python:{executor['module']}:{executor['attribute']}",
360-
queryable=True,
361+
queryable=visibility != "PRIVATE",
361362
hidden=bool(spec.get("hidden", False)),
362-
visibility=str(spec.get("visibility", "LOCAL")),
363+
visibility=visibility,
363364
licenseRef=str(spec["licenseRef"]) if spec.get("licenseRef") else None,
364365
temporalSupport=tuple(str(item) for item in spec.get("temporalSupport", ("latest",))),
365366
executorKind="callable",

‎src/dartlab/dataHub/catalog/universe.py‎

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,11 @@ class ResolvedMarket:
3636
sourceEntityIds: tuple[tuple[str, str], ...] = ()
3737
entityParams: tuple[tuple[str, tuple[tuple[str, str], ...]], ...] = ()
3838

39+
def __post_init__(self) -> None:
40+
entities = tuple(entity for entity, _ in self.sourceEntityIds)
41+
if len(entities) != len(set(entities)):
42+
raise ValueError("universe public identity에는 source identity가 하나만 있어야 합니다")
43+
3944
def sourceIdByEntity(self) -> dict[str, str]:
4045
"""공개 entity ID를 owner 원천 식별자로 연결한다.
4146
@@ -150,7 +155,7 @@ def _callResolver(spec: Mapping[str, Any], selection: UniverseSelection, market:
150155

151156
def _entityParamsFromFrame(
152157
normalized, paramColumns: tuple[str, ...], market: str
153-
) -> tuple[tuple[tuple[str, tuple[tuple[str, str], ...]], ...] | None, DataGap | None]:
158+
) -> tuple[tuple[tuple[str, tuple[tuple[str, str], ...]], ...], DataGap | None]:
154159
"""entity 별 파라미터를 모은다. 같은 entity 가 서로 다른 값을 들고 오면 gap.
155160
156161
한 종목이 두 벌의 파라미터를 갖는 것은 universe 정의 자체가 어긋난 것이라 부분 성공으로
@@ -166,7 +171,7 @@ def _entityParamsFromFrame(
166171
)
167172
previous = paramsByEntity.get(entityId)
168173
if previous is not None and previous != params:
169-
return None, DataGap(
174+
return (), DataGap(
170175
"UNIVERSE_RESOLUTION_FAILED",
171176
f"{market} entity parameter가 충돌합니다: {entityId}",
172177
systemic=True,
@@ -175,7 +180,7 @@ def _entityParamsFromFrame(
175180
return tuple(sorted(paramsByEntity.items())), None
176181

177182

178-
def _readMembershipFrame(frame, market: str):
183+
def _readMembershipFrame(frame, market: str, *, allowSourceAliases: bool = False):
179184
"""resolver 프레임에서 식별자, 원천 식별자, entity 파라미터를 꺼낸다.
180185
181186
프레임을 읽는 일과 그 결과로 무엇을 고를지 정하는 일을 나눈다. 앞은 자료 모양을 알고
@@ -185,7 +190,12 @@ def _readMembershipFrame(frame, market: str):
185190
Returns:
186191
``(ids, sourceIds, entityParams, gap)``. gap 이 있으면 앞 셋은 쓰지 않는다.
187192
"""
188-
normalized = frame.with_columns(pl.col("entityId").cast(pl.Utf8))
193+
entityExpression = pl.col("entityId").cast(pl.Utf8).str.strip_chars()
194+
if market == "US":
195+
entityExpression = entityExpression.str.to_uppercase()
196+
elif market == "KR":
197+
entityExpression = entityExpression.str.pad_start(6, "0")
198+
normalized = frame.with_columns(entityExpression.alias("entityId"))
189199
ids = tuple(sorted({str(value) for value in normalized["entityId"].drop_nulls().to_list() if str(value)}))
190200
sourceIds: tuple[tuple[str, str], ...] = ()
191201
if "sourceEntityId" in normalized.columns:
@@ -198,6 +208,19 @@ def _readMembershipFrame(frame, market: str):
198208
}
199209
)
200210
)
211+
entities = tuple(entity for entity, _ in sourceIds)
212+
sources = tuple(source for _, source in sourceIds)
213+
if len(entities) != len(set(entities)) or not allowSourceAliases and len(sources) != len(set(sources)):
214+
return (
215+
(),
216+
(),
217+
(),
218+
DataGap(
219+
"UNIVERSE_SOURCE_ID_AMBIGUOUS",
220+
f"{market} universe의 public/source identity가 일대일이 아닙니다",
221+
systemic=True,
222+
),
223+
)
201224
paramColumns = tuple(sorted(column for column in normalized.columns if column.startswith("param_")))
202225
entityParams: tuple[tuple[str, tuple[tuple[str, str], ...]], ...] = ()
203226
if paramColumns:
@@ -225,7 +248,12 @@ def _loadMembership(selection: UniverseSelection, market: str) -> tuple[Resolved
225248
if frame.height and "provider" in frame.columns
226249
else str(spec.get("provider") or "unknown")
227250
)
228-
ids, sourceIds, entityParams, paramGap = _readMembershipFrame(frame, market)
251+
aliasMarkets = {str(value).upper() for value in spec.get("sourceAliasMarkets", ())}
252+
ids, sourceIds, entityParams, paramGap = _readMembershipFrame(
253+
frame,
254+
market,
255+
allowSourceAliases=market in aliasMarkets,
256+
)
229257
if paramGap is not None:
230258
return None, paramGap
231259
explicit = tuple(value.split(":", 1)[1] for value in selection.explicitIds if value.startswith(f"{market}:"))

0 commit comments

Comments
 (0)