diff --git a/README.md b/README.md index fd69298..dea4bee 100644 --- a/README.md +++ b/README.md @@ -14,10 +14,9 @@ python -m pip check ## Usage -本开发分支将QDK固定到`ba136c2fa2eea121bfb2ad7887b536c3952586f7`, -并保留日线 PIT 风险分支的因子证据改进。跨仓开发请使用配套本地工作区; -最终依赖提交与锁文件须在验收后同步更新。 -旧发布标签保持不变。 +本版本将QDK固定到`fd080755eebdd5851d98e2b00830235f39ea5ce7`, +包含共享不可变快照与CAS接口。依赖声明、Python3.10–3.12锁及版本一致性测试 +同步使用该提交;旧发布标签保持原版本。 ```bash quant-factors list diff --git a/docs/persistent-cache.md b/docs/persistent-cache.md new file mode 100644 index 0000000..9f8005b --- /dev/null +++ b/docs/persistent-cache.md @@ -0,0 +1,58 @@ +# 持久滚动因子缓存v1 + +`quant_factors.cache.FactorCache`复用`engine_v2.compute_factor_table`及既有`FactorSpec`、`FrequencySpec`、`AsOfSpec`。原有因子、PIT及FactorFrame接口保持原样。 + +```python +from pathlib import Path +from quant_factors.cache import FactorCache +from quant_factors.contracts_v2 import AsOfSpec, FactorDependency, FactorSpec, FrequencySpec + +frequency = FrequencySpec( + "daily", "session_bar", "365", "synthetic-daily-v1", "v1", + None, "trading_day", None, None, None, +) +factor = FactorSpec( + "momentum", "1.0.0", "momentum", "bar", + [FactorDependency("market", "close", "available_at")], + 5, "float64", False, "null", +) +result = FactorCache(Path("state/factors.sqlite3")).compute( + verified_arrow_table, frequency, [factor], + as_of=AsOfSpec("source_available_at", None), + input_identities=[snapshot_artifact_ref_json, member_artifact_ref_json], + universe=["SYNTH-A", "SYNTH-B"], run_id="window-5", +) +print(result.computation_id, result.metadata) +``` + +输入由可信resolver验证;缓存不打开`ArtifactRef.uri`,也不把传入身份当作已验证字节。实际投影后的Arrow内容摘要同时绑定到计算身份。因此同一ref意外返回不同内容不会命中旧结果;外部真实性仍由resolver保证。Lab的`QdkResearchAdapter`使用真实QDK验证清单、成员、角色、schema和摘要。 + +## 算法和增量语义 + +支持`momentum`、`volatility`、`downside_volatility`、`mean_reversion_z`、`rolling_mean`、`rolling_sum`,每个因子只允许一个`market`依赖。窗口单位是按证券排序的**观测数**,不补齐缺失交易日,不推断日历。波动率年化沿用显式`FrequencySpec.periods_per_year`。其他算法、多依赖及辅助源请求明确拒绝。 + +行情按`instrument_id/event_time/sequence/event_id`规范排序;重复完整事件身份、空身份、空选择被拒绝。键不同的同时间事件是不同观测。缺失数值、可得性、固定点及时间顺序沿用现有引擎;`missing_policy=null`保留null,`error`报错。 + +首个版本全量执行。相同语义族的新输入逐证券比较最长相同前缀和后缀。重算从第一个变化处开始,延伸到最后变化处之后一个完整依赖窗口;输入切片再向前补充回看窗口。未变前缀及影响范围之外的后缀直接使用旧结果。插入、删除会改变观测位置,因此后缀必须先经过完整窗口才恢复复用。追加只执行新增行及回看区间。数值运算仍完全由同一个既有引擎完成,验收使用Arrow整表`equals`,比较字段、键、null及数值,**不使用数值容差**。 + +`execution_mode`区分`full`、`incremental`、`cache_hit`。`engine_rows`是实际送入引擎的行数,包含回看;`recomputed_rows`是实际替换输出行数;`reused_rows`是保留输出行数;`input_rows`是选中行情行数。参数或源码变化走全量;新输入内容相同而不可变版本变化时可零计算复用,生成新的计算身份。 + +## 身份和持久化 + +完整计算键绑定操作/版本、因子参数、源码文件字节、Python/pandas/PyArrow版本、输入内容身份、投影Arrow摘要、频率/日历、PIT、证券池及训练声明。源码来自`cache.py`、`engine_v2.py`、`pit_v2.py`、`contracts_v2.py`,摘要不包含机器绝对路径。输入ref的URI和媒体标签不构成内容身份。 + +增量候选族不包含输入版本,但包含上述其他语义。即使上一条候选来自不同快照,也必须逐行实际比较,不能凭版本前缀猜测追加。所有旧结果按完整身份保留,历史修订不覆盖旧结果。 + +SQLite表`factor_cache_inputs_v1`按投影输入字节摘要只存一份Arrow IPC;`factor_cache_v1`的各参数结果引用`input_hash`。输入、输出和元数据在一个事务中提交。读取校验BLOB摘要;并发同身份发布以唯一键归并,并核对输出摘要一致。没有自动删除、迁移旧业务库或把缓存作为任务状态权威。 + +**资源边界:**QDK保留原始共享字节,缓存另外保留一份去重投影和每组因子输出。读取、比较和序列化仍为O(N),本版本显式全表物化;只承诺因子计算增量,不能视为端到端流式。多个稀疏修订之间的区间可能一并重算。本机SQLite/可信进程适用;不承诺多机共享文件数据库或恶意缓存防护。 + +## PIT与训练边界 + +引擎沿用每个依赖的`available_at`检查;迟到依赖在相应as-of之前输出null,窗口位置保留。固定as-of不会让未来行情产生可用值;后续追加不修改旧观测结果。每个输入快照必须已是期望市场版本的一行一个事件,**不在本缓存内选择多vintage市场修订**。如果以晚可得修订替换旧行,旧值不再包含在该快照里,既有引擎会产生null,而不会从其他缓存版本猜回旧值;要重现旧时点必须使用包含正确历史vintage的不可变快照。已有辅助源双时态选择器及其回归保留,新缓存不支持辅助源。 + +可选`training={"start_ns":"...","end_ns":"...","fold_id":"fold-1","state_sha256":null}`要求固定as-of不晚于end;event_time晚于end的行情不参与引擎。start之前的行只供回看,Lab摘要仅统计start之后的区间。折、起止边界均进入身份;本版没有拟合,非null拟合状态明确拒绝,不能将声明隔离测试称为已验证拟合无泄漏。 + +## 验证 + +`python -m pytest tests/test_cache.py -q --no-cov`覆盖六算法的追加、修改、插入、删除、迟到、窗口1、多窗口、多证券、重启命中、并发、损坏拒绝、时间与源码身份、训练截止。运行完整`python -m pytest -q`同时验证原有PIT及统计回归。 diff --git a/pyproject.toml b/pyproject.toml index fce0f44..1bfe56f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -10,7 +10,7 @@ readme = "README.md" license = { text = "MIT" } requires-python = ">=3.10" dependencies = [ - "quant-data-kit @ git+https://github.com/PureSaber/quant-data-kit.git@ba136c2fa2eea121bfb2ad7887b536c3952586f7", + "quant-data-kit @ git+https://github.com/PureSaber/quant-data-kit.git@fd080755eebdd5851d98e2b00830235f39ea5ce7", "pandas>=2.0", "numpy>=1.24", "pyarrow>=14.0", diff --git a/requirements.lock b/requirements.lock index f9079e8..722b73d 100644 --- a/requirements.lock +++ b/requirements.lock @@ -78,7 +78,7 @@ pyyaml==6.0.3 # quant-factors (pyproject.toml) # quant-data-kit # quant-lab -quant-data-kit @ git+https://github.com/PureSaber/quant-data-kit.git@ba136c2fa2eea121bfb2ad7887b536c3952586f7 +quant-data-kit @ git+https://github.com/PureSaber/quant-data-kit.git@fd080755eebdd5851d98e2b00830235f39ea5ce7 # via quant-factors (pyproject.toml) quant-lab @ git+https://github.com/PureSaber/quant-lab.git@a923a791315312a4d9caecf3b9776f08d53bb736 # via quant-factors (pyproject.toml) diff --git a/src/quant_factors/cache.py b/src/quant_factors/cache.py new file mode 100644 index 0000000..7cb5e7b --- /dev/null +++ b/src/quant_factors/cache.py @@ -0,0 +1,388 @@ +"""Transactional local cache over the existing finite-window PIT engine. + +Input comparison and storage are O(N). Only factor evaluation is incremental. +No fitted transform or auxiliary dependency is supported by this first version. +""" + +from __future__ import annotations + +import hashlib +import json +import logging +import platform +import re +import sqlite3 +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path + +import pandas as pd +import pyarrow as pa +from pyarrow import compute as pc +from pyarrow import ipc + +from quant_factors import contracts_v2, engine_v2, pit_v2 +from quant_factors.contracts_v2 import AsOfSpec, FactorSpec, FrequencySpec + +SUPPORTED_ALGORITHMS = frozenset( + { + "momentum", + "volatility", + "downside_volatility", + "mean_reversion_z", + "rolling_mean", + "rolling_sum", + } +) +_KEYS = ("instrument_id", "event_time", "sequence", "event_id") +_LOG = logging.getLogger(__name__) + + +def canonical(value) -> str: + return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False) + + +def digest(value) -> str: + return hashlib.sha256(canonical(value).encode()).hexdigest() + + +def artifact_identity(ref: dict) -> dict: + """Validate the public ArtifactRef and exclude its machine-specific locator.""" + required = {"schema_version", "sha256", "size_bytes", "uri"} + if ( + not isinstance(ref, dict) + or not required <= ref.keys() + or ref.keys() - required - {"media_type"} + or ref["schema_version"] != "quant.artifact-ref/v1" + or not isinstance(ref["sha256"], str) + or re.fullmatch(r"[0-9a-f]{64}", ref["sha256"]) is None + or type(ref["size_bytes"]) is not int + or ref["size_bytes"] < 0 + or not isinstance(ref["uri"], str) + or not ref["uri"].strip() + or ("media_type" in ref and not isinstance(ref["media_type"], str)) + ): + raise ValueError("Invalid quant.artifact-ref/v1") + return {key: ref[key] for key in ("schema_version", "sha256", "size_bytes")} + + +def source_identity() -> dict: + """Bind actual source bytes and numerical runtime, without absolute paths.""" + files = [Path(__file__), *[Path(m.__file__) for m in (contracts_v2, engine_v2, pit_v2)]] + return { + "files": {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in files}, + "python": platform.python_version(), + "pandas": pd.__version__, + "pyarrow": pa.__version__, + } + + +def _encode(table: pa.Table) -> bytes: + sink = pa.BufferOutputStream() + with ipc.new_stream(sink, table.schema) as writer: + writer.write_table(table.combine_chunks()) + return sink.getvalue().to_pybytes() + + +def _decode(blob: bytes, expected: str) -> pa.Table: + if hashlib.sha256(blob).hexdigest() != expected: + raise ValueError("Factor cache checksum mismatch") + return ipc.open_stream(blob).read_all() + + +class _Connection(sqlite3.Connection): + def __exit__(self, *args): + try: + return super().__exit__(*args) + finally: + self.close() + + +@dataclass(frozen=True) +class CachedFactors: + table: pa.Table + computation_id: str + metadata: dict + + +class FactorCache: + """Append-only results; SQLite commits input, output and identity atomically.""" + + def __init__(self, path: str | Path): + self.path = Path(path) + self.path.parent.mkdir(parents=True, exist_ok=True) + with self._connect() as db: + db.executescript(""" + CREATE TABLE IF NOT EXISTS factor_cache_inputs_v1 ( + input_hash TEXT PRIMARY KEY, input_blob BLOB NOT NULL); + CREATE TABLE IF NOT EXISTS factor_cache_v1 ( + sequence INTEGER PRIMARY KEY AUTOINCREMENT, + computation_id TEXT UNIQUE NOT NULL, family_id TEXT NOT NULL, + input_hash TEXT NOT NULL REFERENCES factor_cache_inputs_v1(input_hash), + output_blob BLOB NOT NULL, output_hash TEXT NOT NULL, + metadata TEXT NOT NULL); + CREATE INDEX IF NOT EXISTS factor_cache_family_v1 + ON factor_cache_v1(family_id, sequence); + """) + + def _connect(self): + db = sqlite3.connect(self.path, timeout=30, factory=_Connection) + db.execute("PRAGMA foreign_keys=ON") + return db + + def compute( + self, + table: pa.Table, + frequency: FrequencySpec, + factors: list[FactorSpec], + *, + as_of: AsOfSpec, + input_identities: list[dict], + universe: list[str], + run_id: str, + training: dict | None = None, + ) -> CachedFactors: + if not isinstance(run_id, str) or not run_id.strip(): + raise ValueError("run_id is required") + specs = tuple(sorted(factors, key=lambda f: f.factor_id)) + if not specs or len({s.factor_id for s in specs}) != len(specs): + raise ValueError("Distinct factor specs required") + for spec in specs: + if ( + spec.algorithm_id not in SUPPORTED_ALGORITHMS + or len(spec.dependencies) != 1 + or spec.dependencies[0].role != "market" + ): + raise ValueError("Incremental cache supports listed unary market factors only") + if ( + not isinstance(universe, list) + or not universe + or any(not isinstance(x, str) or not x.strip() for x in universe) + or len(set(universe)) != len(universe) + ): + raise ValueError("Explicit distinct universe required") + if not input_identities: + raise ValueError("Immutable input identities required") + identities = sorted([artifact_identity(r) for r in input_identities], key=canonical) + if not isinstance(table, pa.Table) or not table.num_rows: + raise ValueError("Nonempty Arrow input required") + if len(set(table.column_names)) != len(table.column_names): + raise ValueError("Duplicate input columns") + required = {*_KEYS, "received_at", "available_at"} + required.update( + c + for s in specs + for c in ( + s.dependencies[0].value_column, + s.dependencies[0].availability_column, + ) + ) + if not required <= set(table.column_names): + raise ValueError("Missing input columns") + # Project only genuine dependencies. Column order/unused fields cannot alter arithmetic. + selected = table.select(sorted(required)).replace_schema_metadata(None) + selected = selected.filter(pc.is_in(selected["instrument_id"], pa.array(universe))) + selected = selected.sort_by([(key, "ascending") for key in _KEYS]).combine_chunks() + if training is not None: + self._validate_training(training, as_of) + cutoff = pa.scalar(pd.Timestamp(int(training["end_ns"]), unit="ns", tz="UTC")) + selected = selected.filter(pc.less_equal(selected["event_time"], cutoff)) + if not selected.num_rows: + raise ValueError("Empty selected input") + rows = selected.to_pylist() + seen = set() + for row in rows: + key = tuple(row[c] for c in _KEYS) + if key in seen or any(row[c] is None for c in _KEYS): + raise ValueError("Duplicate or null event identity") + if not all(isinstance(row[c], str) and row[c] for c in ("instrument_id", "event_id")): + raise ValueError("Nonempty event identity required") + seen.add(key) + family = { + "operation": "quant-factors/finite-window-cache", + "version": "1.0.0", + "source": source_identity(), + "parameters": [s.to_contract() for s in specs], + "frequency": frequency.to_contract(), + "as_of": as_of.to_contract(), + "universe": sorted(universe), + "training": training, + } + identity = { + **family, + "inputs": identities, + "selected_input_sha256": pit_v2.arrow_table_logical_sha256(selected), + } + computation_id, family_id = digest(identity), digest(family) + with self._connect() as db: + hit = db.execute( + "SELECT output_blob,output_hash,metadata FROM factor_cache_v1 " + "WHERE computation_id=?", + (computation_id,), + ).fetchone() + prior = ( + None + if hit + else db.execute( + "SELECT c.computation_id,i.input_blob,c.input_hash,c.output_blob,c.output_hash " + "FROM factor_cache_v1 c JOIN factor_cache_inputs_v1 i " + "ON i.input_hash=c.input_hash WHERE c.family_id=? " + "ORDER BY c.sequence DESC LIMIT 1", + (family_id,), + ).fetchone() + ) + if hit: + output = _decode(hit[0], hit[1]) + metadata = { + **json.loads(hit[2]), + "execution_mode": "cache_hit", + "engine_rows": 0, + "recomputed_rows": 0, + "reused_rows": output.num_rows, + "run_id": run_id, + } + return self._result(output, computation_id, metadata) + lookback = max( + s.window_periods + if s.algorithm_id + in { + "momentum", + "volatility", + "downside_volatility", + } + else s.window_periods - 1 + for s in specs + ) + old_input = _decode(prior[1], prior[2]) if prior else None + old_output = _decode(prior[3], prior[4]) if prior else None + if old_input is not None and selected.schema.equals(old_input.schema): + output, engine_rows, recomputed = self._incremental( + selected, + old_input, + old_output, + frequency, + specs, + as_of, + lookback, + ) + mode = "incremental" + else: + output = engine_v2.compute_factor_table(selected, frequency, specs, as_of=as_of) + engine_rows = recomputed = selected.num_rows + mode = "full" + metadata = { + "identity": identity, + "execution_mode": mode, + "engine_rows": engine_rows, + "recomputed_rows": recomputed, + "reused_rows": selected.num_rows - recomputed, + "input_rows": selected.num_rows, + "parent_computation_id": prior[0] if prior else None, + "run_id": run_id, + "output_sha256": pit_v2.arrow_table_logical_sha256(output), + } + input_blob, output_blob = _encode(selected), _encode(output) + with self._connect() as db: + db.execute("BEGIN IMMEDIATE") + db.execute( + "INSERT OR IGNORE INTO factor_cache_inputs_v1 VALUES (?,?)", + (hashlib.sha256(input_blob).hexdigest(), input_blob), + ) + db.execute( + "INSERT OR IGNORE INTO factor_cache_v1 " + "(computation_id,family_id,input_hash,output_blob,output_hash,metadata) " + "VALUES (?,?,?,?,?,?)", + ( + computation_id, + family_id, + hashlib.sha256(input_blob).hexdigest(), + output_blob, + hashlib.sha256(output_blob).hexdigest(), + canonical(metadata), + ), + ) + existing = db.execute( + "SELECT output_hash FROM factor_cache_v1 WHERE computation_id=?", + (computation_id,), + ).fetchone()[0] + if existing != hashlib.sha256(output_blob).hexdigest(): + raise ValueError("Non-deterministic factor result for one computation identity") + return self._result(output, computation_id, metadata) + + @staticmethod + def _validate_training(training, as_of): + if ( + not isinstance(training, dict) + or set(training) != {"start_ns", "end_ns", "fold_id", "state_sha256"} + or not isinstance(training["fold_id"], str) + or not training["fold_id"].strip() + or training["state_sha256"] is not None + ): + raise ValueError( + "Training needs start_ns/end_ns/fold_id and null state; fitting unsupported" + ) + start = AsOfSpec("fixed", training["start_ns"]) + end = AsOfSpec("fixed", training["end_ns"]) + if ( + int(start.fixed_at_ns) > int(end.fixed_at_ns) + or as_of.mode != "fixed" + or int(as_of.fixed_at_ns) > int(end.fixed_at_ns) + ): + raise ValueError("Training requires a fixed as-of no later than its end") + + @staticmethod + def _incremental(table, old, old_output, frequency, specs, as_of, lookback): + pieces, engine_rows, recomputed = [], 0, 0 + for instrument in dict.fromkeys(table["instrument_id"].to_pylist()): + current = table.filter(pc.equal(table["instrument_id"], instrument)) + previous = old.filter(pc.equal(old["instrument_id"], instrument)) + previous_output = old_output.filter(pc.equal(old_output["instrument_id"], instrument)) + new_rows, old_rows = current.to_pylist(), previous.to_pylist() + prefix = 0 + while ( + prefix < min(len(new_rows), len(old_rows)) and new_rows[prefix] == old_rows[prefix] + ): + prefix += 1 + suffix = 0 + while ( + suffix < min(len(new_rows), len(old_rows)) - prefix + and new_rows[-1 - suffix] == old_rows[-1 - suffix] + ): + suffix += 1 + # Row-count changes shift rolling windows. A suffix is reusable only after + # a complete new lookback lies inside the common suffix. + stop = min(len(new_rows), len(new_rows) - suffix + lookback) + if prefix == len(new_rows) == len(old_rows): + stop = prefix + if prefix: + pieces.append(previous_output.slice(0, prefix)) + if stop > prefix: + begin = max(0, prefix - lookback) + computed = engine_v2.compute_factor_table( + current.slice(begin, stop - begin), + frequency, + specs, + as_of=as_of, + ) + pieces.append(computed.slice(prefix - begin)) + engine_rows += stop - begin + recomputed += stop - prefix + if stop < len(new_rows): + pieces.append(previous_output.slice(len(old_rows) - (len(new_rows) - stop))) + return pa.concat_tables(pieces).combine_chunks(), engine_rows, recomputed + + @staticmethod + def _result(output, computation_id, metadata): + _LOG.info( + canonical( + { + "event": "factor_cache_result", + "timestamp": datetime.now(timezone.utc).isoformat(), + "run_id": metadata["run_id"], + "computation_id": computation_id, + "execution_mode": metadata["execution_mode"], + "engine_rows": metadata["engine_rows"], + } + ) + ) + return CachedFactors(output, computation_id, metadata) diff --git a/tests/test_cache.py b/tests/test_cache.py new file mode 100644 index 0000000..071c4af --- /dev/null +++ b/tests/test_cache.py @@ -0,0 +1,295 @@ +import sqlite3 +from concurrent.futures import ThreadPoolExecutor +from dataclasses import replace + +import pandas as pd +import pyarrow as pa +import pytest + +from quant_factors import cache as module +from quant_factors.cache import FactorCache +from quant_factors.contracts_v2 import AsOfSpec, FactorDependency, FactorSpec, FrequencySpec +from quant_factors.engine_v2 import compute_factor_table +from quant_factors.pit_v2 import arrow_table_logical_sha256 + + +def bars(n=100): + rows = [] + for symbol in ("A", "B"): + for i in range(n): + stamp = pd.Timestamp("2024-01-01", tz="UTC") + pd.Timedelta(days=i) + rows.append( + { + "instrument_id": symbol, + "event_time": stamp, + "received_at": stamp, + "available_at": stamp, + "sequence": i, + "event_id": f"{symbol}-{i}", + "close": float(100 + i + i % 7), + } + ) + return pa.Table.from_pylist(rows) + + +def frequency(): + return FrequencySpec( + "daily", "session_bar", "252", "synthetic-v1", "v1", None, "trading_day", None, None, None + ) + + +def spec(algorithm="momentum", window=5): + return FactorSpec( + "factor", + "1.0.0", + algorithm, + "bar", + [FactorDependency("market", "close", "available_at")], + window, + "float64", + False, + "null", + ) + + +def refs(table): + return [ + { + "schema_version": "quant.artifact-ref/v1", + "sha256": arrow_table_logical_sha256(table), + "size_bytes": table.nbytes, + "uri": "memory:verified-test", + } + ] + + +def run(cache, table, factor=None, **kwargs): + options = { + "as_of": AsOfSpec("source_available_at", None), + "input_identities": refs(table), + "universe": ["A", "B"], + "run_id": "test", + } + options.update(kwargs) + return cache.compute(table, frequency(), [factor or spec()], **options) + + +@pytest.mark.parametrize("algorithm", sorted(module.SUPPORTED_ALGORITHMS)) +@pytest.mark.parametrize("change", ["append", "revise", "insert", "delete", "late"]) +def test_incremental_is_exactly_full_and_evaluates_only_dirty_windows(tmp_path, algorithm, change): + cache, factor = FactorCache(tmp_path / "cache.db"), spec(algorithm) + original = bars() + if change == "insert": + before = pa.Table.from_pylist([r for r in original.to_pylist() if r["sequence"] != 60]) + after = original + else: + before = original + rows = (bars(103) if change == "append" else original).to_pylist() + if change == "revise": + rows[60]["close"] += 13 + elif change == "delete": + del rows[60] + elif change == "late": + rows[60]["available_at"] += pd.Timedelta(days=7) + after = pa.Table.from_pylist(rows) + run(cache, before, factor) + actual = run(cache, after, factor) + expected = compute_factor_table( + after, frequency(), [factor], as_of=AsOfSpec("source_available_at", None) + ) + assert actual.table.equals(expected) + assert actual.metadata["execution_mode"] == "incremental" + assert actual.metadata["engine_rows"] < 40 + assert actual.metadata["recomputed_rows"] < 22 + assert actual.metadata["reused_rows"] > 160 + + +def test_repeat_survives_restart_and_does_not_invoke_engine(tmp_path, monkeypatch): + path, table = tmp_path / "cache.db", bars() + first = run(FactorCache(path), table) + + def fail(*args, **kwargs): + raise AssertionError("cache hit must not execute factors") + + monkeypatch.setattr(module.engine_v2, "compute_factor_table", fail) + second = run(FactorCache(path), table, run_id="another-run") + assert second.table.equals(first.table) + assert second.computation_id == first.computation_id + assert second.metadata["execution_mode"] == "cache_hit" + assert second.metadata["run_id"] == "another-run" + relocated = refs(table) + relocated[0]["uri"] = "store:other-machine" + assert ( + run(FactorCache(path), table, input_identities=relocated).computation_id + == first.computation_id + ) + + +def test_parameters_source_input_time_universe_and_calendar_invalidate(tmp_path, monkeypatch): + cache, table = FactorCache(tmp_path / "cache.db"), bars() + baseline = run(cache, table) + changed = [ + run(cache, table, spec(window=7)), + run(cache, table, as_of=AsOfSpec("fixed", str(pd.Timestamp("2025", tz="UTC").value))), + run(cache, table, universe=["A"]), + run(cache, table, input_identities=[{**refs(table)[0], "sha256": "a" * 64}]), + cache.compute( + table, + replace(frequency(), calendar_id="another-calendar"), + [spec()], + as_of=AsOfSpec("source_available_at", None), + input_identities=refs(table), + universe=["A", "B"], + run_id="calendar", + ), + ] + source = module.source_identity() + monkeypatch.setattr(module, "source_identity", lambda: {**source, "revision": "changed"}) + changed.append(run(cache, table)) + assert all(r.computation_id != baseline.computation_id for r in changed) + assert all(r.metadata["execution_mode"] == "full" for r in changed[:3] + changed[4:]) + assert changed[3].metadata["engine_rows"] == 0 + + +def test_training_isolation_and_no_future_price_or_availability(tmp_path): + cache, table = FactorCache(tmp_path / "cache.db"), bars() + start = str(pd.Timestamp("2024-01-01", tz="UTC").value) + end = str(pd.Timestamp("2024-02-19", tz="UTC").value) + training = {"start_ns": start, "end_ns": end, "fold_id": "fold-1", "state_sha256": None} + first = run(cache, table, as_of=AsOfSpec("fixed", end), training=training) + assert first.table.num_rows == 100 + changed = table.to_pylist() + for row in changed: + if pd.Timestamp(row["event_time"]).value > int(end): + row["close"] *= 99 + second = run( + cache, pa.Table.from_pylist(changed), as_of=AsOfSpec("fixed", end), training=training + ) + assert second.table.equals(first.table) + assert second.computation_id != first.computation_id # full input version remains bound + assert second.metadata["engine_rows"] == 0 + other_fold = run( + cache, table, as_of=AsOfSpec("fixed", end), training={**training, "fold_id": "fold-2"} + ) + assert other_fold.metadata["execution_mode"] == "full" + with pytest.raises(ValueError, match="fixed as-of"): + run(cache, table, training=training) + with pytest.raises(ValueError, match="fitting unsupported"): + run( + cache, + table, + as_of=AsOfSpec("fixed", end), + training={**training, "state_sha256": "f" * 64}, + ) + changed = table.to_pylist() + changed[49]["available_at"] += pd.Timedelta(days=1) + result = run( + cache, pa.Table.from_pylist(changed), as_of=AsOfSpec("fixed", end), training=training + ) + assert result.table["factor"][49].as_py() is None + + +def test_prefix_is_causal_new_future_rows_do_not_change_history(tmp_path): + cache = FactorCache(tmp_path / "cache.db") + first = run(cache, bars(30)) + second = run(cache, bars(100)) + for symbol in ("A", "B"): + old = first.table.filter(pa.compute.equal(first.table["instrument_id"], symbol)) + new = second.table.filter(pa.compute.equal(second.table["instrument_id"], symbol)).slice( + 0, 30 + ) + assert new.equals(old) + + +def test_unary_boundary_windows_removal_and_multiple_factors(tmp_path): + cache, table = FactorCache(tmp_path / "cache.db"), bars(12) + for algorithm in module.SUPPORTED_ALGORITHMS: + factor = spec(algorithm, 1) + run(cache, table, factor) + shorter = pa.Table.from_pylist(table.to_pylist()[:8]) + result = run(cache, shorter, factor) + assert result.table.equals( + compute_factor_table( + shorter, frequency(), [factor], as_of=AsOfSpec("source_available_at", None) + ) + ) + factors = [spec(window=2), replace(spec("rolling_mean", 9), factor_id="mean")] + kwargs = { + "as_of": AsOfSpec("source_available_at", None), + "universe": ["A", "B"], + "run_id": "multi", + } + cache.compute(table, frequency(), factors, input_identities=refs(table), **kwargs) + later = bars(15) + actual = cache.compute(later, frequency(), factors, input_identities=refs(later), **kwargs) + assert actual.table.equals( + compute_factor_table(later, frequency(), factors, as_of=kwargs["as_of"]) + ) + + +@pytest.mark.parametrize( + "factor", + [ + spec("last_value"), + replace(spec(), dependencies=[FactorDependency("fundamental", "close", "available_at")]), + replace( + spec(), + dependencies=[ + FactorDependency("market", "close", "available_at"), + FactorDependency("market", "other", "available_at"), + ], + ), + ], +) +def test_unsupported_is_rejected_not_silently_recomputed(tmp_path, factor): + with pytest.raises(ValueError, match="unary market"): + run(FactorCache(tmp_path / "cache.db"), bars(), factor) + + +def test_integrity_and_concurrent_publish(tmp_path): + path, table = tmp_path / "cache.db", bars() + FactorCache(path) + with ThreadPoolExecutor(max_workers=4) as pool: + results = list(pool.map(lambda _: run(FactorCache(path), table), range(8))) + assert len({r.computation_id for r in results}) == 1 + with sqlite3.connect(path) as db: + assert db.execute("SELECT count(*) FROM factor_cache_v1").fetchone()[0] == 1 + db.execute("UPDATE factor_cache_v1 SET output_blob=?", (b"corrupt",)) + with pytest.raises(ValueError, match="checksum"): + run(FactorCache(path), table) + + +@pytest.mark.parametrize( + "kwargs", + [ + {"universe": []}, + {"universe": ["A", "A"]}, + {"run_id": ""}, + {"input_identities": []}, + {"input_identities": [{}]}, + {"universe": ["missing"]}, + ], +) +def test_invalid_context_rejected(tmp_path, kwargs): + with pytest.raises(ValueError): + run(FactorCache(tmp_path / "cache.db"), bars(), **kwargs) + + +def test_invalid_table_and_duplicate_specs_rejected(tmp_path): + cache, table = FactorCache(tmp_path / "cache.db"), bars(3) + with pytest.raises(ValueError, match="Duplicate"): + run(cache, pa.concat_tables([table, table])) + with pytest.raises(ValueError, match="Missing"): + run(cache, table.drop(["close"])) + with pytest.raises(ValueError, match="Nonempty"): + run(cache, table.slice(0, 0)) + with pytest.raises(ValueError, match="Distinct"): + cache.compute( + table, + frequency(), + [spec(), spec()], + as_of=AsOfSpec("fixed", "0"), + input_identities=refs(table), + universe=["A"], + run_id="bad", + ) diff --git a/tests/test_release_metadata.py b/tests/test_release_metadata.py index 199b6eb..4cc7703 100644 --- a/tests/test_release_metadata.py +++ b/tests/test_release_metadata.py @@ -1,7 +1,7 @@ from pathlib import Path ROOT = Path(__file__).resolve().parents[1] -QDK_COMMIT = "ba136c2fa2eea121bfb2ad7887b536c3952586f7" +QDK_COMMIT = "fd080755eebdd5851d98e2b00830235f39ea5ce7" def test_cross_interpreter_constraint_is_applied_to_generated_lock() -> None: