From 6b4d96a272319753a85cb8da7a87536a0050ec40 Mon Sep 17 00:00:00 2001 From: Junyou Park Date: Mon, 10 Aug 2026 02:25:59 +0900 Subject: [PATCH] feat: publish and cache adjusted market history --- apps/pipeline_worker/config.py | 24 ++ apps/pipeline_worker/main.py | 25 +- apps/pipeline_worker/sync_market_history.py | 377 +++++++++++++++++++ market_pipeline_lib/engine.py | 5 +- tests/test_market_history_sync.py | 391 ++++++++++++++++++++ 5 files changed, 819 insertions(+), 3 deletions(-) create mode 100644 apps/pipeline_worker/sync_market_history.py create mode 100644 tests/test_market_history_sync.py diff --git a/apps/pipeline_worker/config.py b/apps/pipeline_worker/config.py index ff3b7b4..4dcf184 100644 --- a/apps/pipeline_worker/config.py +++ b/apps/pipeline_worker/config.py @@ -88,6 +88,30 @@ "PostgreSQL URL used for durable realtime watermarks. Empty keeps the local " "in-memory repository for development only.", ), + ( + "PIPELINE_WORKER_MARKET_HISTORY_REDIS_URI", + False, + "", + "TLS Redis URI used only by --sync-market-history for the read-model projection.", + ), + ( + "PIPELINE_WORKER_MARKET_HISTORY_REDIS_KEY_PREFIX", + False, + "i2s", + "Plain Redis hash-tag prefix shared with backend market-data reads.", + ), + ( + "PIPELINE_WORKER_MARKET_HISTORY_LIMIT", + False, + "400", + "Recent adjusted bars retained per instrument and strategy timeframe.", + ), + ( + "MARKET_DATA_BUCKET", + False, + "", + "Versioned canonical S3 bucket used by scheduled market-history sync.", + ), ( "PIPELINE_WORKER_CORPORATE_ACTION_APPROVAL", False, diff --git a/apps/pipeline_worker/main.py b/apps/pipeline_worker/main.py index 298d29f..2010058 100644 --- a/apps/pipeline_worker/main.py +++ b/apps/pipeline_worker/main.py @@ -52,6 +52,14 @@ def build_parser() -> argparse.ArgumentParser: "Requires PIPELINE_WORKER_DATABASE_URL." ), ) + parser.add_argument( + "--sync-market-history", + action="store_true", + help=( + "Publish missing adjusted daily history, project recent AVAILABLE " + "bars to Redis, advance watermarks, and exit." + ), + ) return parser @@ -66,16 +74,29 @@ def main( return EXIT_OK if arguments.publish_manifest_watermarks: - from apps.pipeline_worker.publish_manifest_watermarks import execute + from apps.pipeline_worker.publish_manifest_watermarks import ( + execute as publish_manifest_watermarks, + ) try: - result = execute([], environment) + result = publish_manifest_watermarks([], environment) except (OSError, RuntimeError, ValueError) as error: print(f"publish-manifest-watermarks failed: {error}", file=sys.stderr) return EXIT_RUNTIME_FAILURE print(json.dumps(result, indent=2, sort_keys=True)) return EXIT_OK + if arguments.sync_market_history: + from apps.pipeline_worker.sync_market_history import execute as sync_market_history + + try: + result = sync_market_history(environment) + except (OSError, RuntimeError, ValueError) as error: + print(f"sync-market-history failed: {error}", file=sys.stderr) + return EXIT_RUNTIME_FAILURE + print(json.dumps(result, indent=2, sort_keys=True)) + return EXIT_OK + try: config = WorkerConfig.from_environment(environment) except ConfigurationError as error: diff --git a/apps/pipeline_worker/sync_market_history.py b/apps/pipeline_worker/sync_market_history.py new file mode 100644 index 0000000..6588c35 --- /dev/null +++ b/apps/pipeline_worker/sync_market_history.py @@ -0,0 +1,377 @@ +"""Scheduled canonical history publication and Redis read-model projection.""" + +from __future__ import annotations + +import csv +import hashlib +import json +import os +import tempfile +from collections import defaultdict, deque +from collections.abc import Mapping +from dataclasses import dataclass +from datetime import UTC, date, datetime, timedelta +from pathlib import Path +from typing import Any + +import pandas_market_calendars as mcal +import pyarrow.parquet as pq + +from market_pipeline_lib.catalog import PostgresCatalog, StorageObjectsPolicy +from market_pipeline_lib.contracts import ADJUSTED_FEED, ET, deterministic_uuid +from market_pipeline_lib.engine import AlpacaBarSource, MarketPipelineEngine, PipelineConfig +from market_pipeline_lib.storage import S3ObjectStore + +TIMEFRAMES: dict[str, tuple[str, int]] = { + "30m": ("ADJUSTED", 120), + "1h": ("DERIVED", 240), + "4h": ("DERIVED", 600), + "1d": ("DERIVED", 900), +} +PUBLICATION_SESSION_BATCH = 20 + + +@dataclass(frozen=True) +class HistorySyncConfig: + database_url: str + bucket: str + redis_uri: str + redis_key_prefix: str + limit: int + api_key: str + api_secret: str + state_root: Path + + @classmethod + def from_environment( + cls, environment: Mapping[str, str] | None = None + ) -> HistorySyncConfig: + values = os.environ if environment is None else environment + required = { + "PIPELINE_WORKER_DATABASE_URL": values.get("PIPELINE_WORKER_DATABASE_URL", ""), + "MARKET_DATA_BUCKET": values.get("MARKET_DATA_BUCKET", ""), + "PIPELINE_WORKER_MARKET_HISTORY_REDIS_URI": values.get( + "PIPELINE_WORKER_MARKET_HISTORY_REDIS_URI", "" + ), + "ALPACA_API_KEY": values.get("ALPACA_API_KEY", ""), + "ALPACA_SECRET_KEY": values.get("ALPACA_SECRET_KEY", ""), + } + missing = sorted(name for name, value in required.items() if not value.strip()) + if missing: + raise ValueError(f"sync-market-history missing environment variables: {missing}") + prefix = values.get("PIPELINE_WORKER_MARKET_HISTORY_REDIS_KEY_PREFIX", "i2s") + if not prefix or "{" in prefix or "}" in prefix: + raise ValueError("market history Redis key prefix must be plain and non-empty") + try: + limit = int(values.get("PIPELINE_WORKER_MARKET_HISTORY_LIMIT", "400")) + except ValueError as error: + raise ValueError("PIPELINE_WORKER_MARKET_HISTORY_LIMIT must be an integer") from error + if limit < 1 or limit > 1_000: + raise ValueError("PIPELINE_WORKER_MARKET_HISTORY_LIMIT must be between 1 and 1000") + state_root = Path( + values.get("PIPELINE_WORKER_OBJECT_STORE_ROOT", "/var/lib/idea2strategy/pipeline") + ).expanduser() + return cls( + database_url=required["PIPELINE_WORKER_DATABASE_URL"], + bucket=required["MARKET_DATA_BUCKET"], + redis_uri=required["PIPELINE_WORKER_MARKET_HISTORY_REDIS_URI"], + redis_key_prefix=prefix, + limit=limit, + api_key=required["ALPACA_API_KEY"], + api_secret=required["ALPACA_SECRET_KEY"], + state_root=state_root, + ) + + +def _timestamp(value: object) -> datetime: + parsed = datetime.fromisoformat(str(value).replace("Z", "+00:00")) + if parsed.tzinfo is None or parsed.utcoffset() is None: + raise ValueError(f"timestamp must be timezone-aware: {value}") + return parsed.astimezone(UTC) + + +def completed_sessions_after( + latest_period_end: datetime, now: datetime, calendar_name: str = "XNYS" +) -> list[date]: + if now.tzinfo is None or now.utcoffset() is None: + raise ValueError("now must be timezone-aware") + schedule = mcal.get_calendar(calendar_name).schedule( + start_date=latest_period_end.astimezone(ET).date(), + end_date=now.astimezone(ET).date(), + tz="UTC", + ) + return [ + index.date() + for index, row in schedule.iterrows() + if row["market_close"].to_pydatetime() > latest_period_end + and row["market_close"].to_pydatetime() <= now + ] + + +def _adjusted_manifests(catalog: Any, resolution: str, layer: str) -> list[dict[str, Any]]: + feed_id = deterministic_uuid("feed", "ALPACA", ADJUSTED_FEED) + return sorted( + ( + row + for row in catalog.records("market_data.dataset_manifests") + if row["status"] == "AVAILABLE" + and str(row["feed_id"]) == feed_id + and row["data_layer"] == layer + and row["resolution"] == resolution + ), + key=lambda row: (_timestamp(row["period_start"]), int(row["revision_number"])), + ) + + +def _write_instrument_map(catalog: Any, output: Path, now: datetime) -> int: + instruments = { + str(row["id"]): row for row in catalog.records("market_data.instruments") + } + cutoff = now.date() + rows: list[tuple[str, str]] = [] + for symbol in catalog.records("market_data.instrument_symbols"): + instrument = instruments.get(str(symbol["instrument_id"])) + if instrument is None: + continue + if symbol["exchange_mic"] != instrument["primary_exchange_mic"]: + continue + effective_from = _timestamp(symbol["effective_from"]) + effective_to = ( + None if symbol.get("effective_to") is None else _timestamp(symbol["effective_to"]) + ) + if effective_from > now or (effective_to is not None and now >= effective_to): + continue + listed = instrument.get("listed_at") + delisted = instrument.get("delisted_at") + if listed is not None and date.fromisoformat(str(listed)) > cutoff: + continue + if delisted is not None and date.fromisoformat(str(delisted)) <= cutoff: + continue + rows.append((str(symbol["symbol"]), str(instrument["id"]))) + rows.sort() + if not rows: + raise RuntimeError("canonical catalog has no active primary instrument symbols") + output.parent.mkdir(parents=True, exist_ok=True) + with output.open("w", encoding="utf-8", newline="") as handle: + writer = csv.writer(handle) + writer.writerow(("provider_symbol", "instrument_id")) + writer.writerows(rows) + return len(rows) + + +def _publish_missing_history( + catalog: Any, + object_store: S3ObjectStore, + config: HistorySyncConfig, + now: datetime, +) -> dict[str, Any]: + manifests = _adjusted_manifests(catalog, "30m", "ADJUSTED") + if not manifests: + raise RuntimeError("no AVAILABLE adjusted 30m manifest exists to continue") + latest_end = max(_timestamp(row["period_end"]) for row in manifests) + sessions = completed_sessions_after(latest_end, now) + if not sessions: + return {"status": "CURRENT", "sessions": [], "latest_period_end": latest_end.isoformat()} + instrument_map = config.state_root / "market-history" / "active-instruments.csv" + instrument_count = _write_instrument_map(catalog, instrument_map, now) + staging_root = config.state_root / "market-history" / "staging" + staging_root.mkdir(parents=True, exist_ok=True) + engine = MarketPipelineEngine( + PipelineConfig( + local_root=config.state_root / "market-history" / "objects", + staging_root=staging_root, + instrument_map_path=instrument_map, + resume=True, + ), + object_store=object_store, + catalog=catalog, + source=AlpacaBarSource(config.api_key, config.api_secret), + ensure_provider_metadata=False, + ) + run_ids: list[str] = [] + for offset in range(0, len(sessions), PUBLICATION_SESSION_BATCH): + batch = sessions[offset : offset + PUBLICATION_SESSION_BATCH] + result = engine.incremental( + sessions=batch, + price_types=("adjusted",), + resolutions=tuple(TIMEFRAMES), + ) + if result.get("status") != "SUCCEEDED": + raise RuntimeError( + f"adjusted incremental publication failed: {result.get('status')}" + ) + if result.get("pipeline_run_id"): + run_ids.append(str(result["pipeline_run_id"])) + return { + "status": "PUBLISHED", + "instrument_count": instrument_count, + "sessions": [session.isoformat() for session in sessions], + "pipeline_run_ids": run_ids, + } + + +def _verified_parquet( + object_store: S3ObjectStore, relation: Mapping[str, Any], temporary_root: Path +) -> Path: + storage = relation["storage"] + verification = object_store.verify_version( + str(storage["object_key"]), + str(storage["provider_version_id"]), + str(storage["content_hash"]), + int(storage["byte_size"]), + ) + if not verification.ok: + raise RuntimeError( + f"canonical S3 object failed verification: {storage['object_key']} ({verification.message})" + ) + path = temporary_root / f"{storage['id']}.parquet" + digest = hashlib.sha256() + size = 0 + with object_store.open_version( + str(storage["object_key"]), str(storage["provider_version_id"]) + ) as source, path.open("wb") as target: + while chunk := source.read(1024 * 1024): + digest.update(chunk) + size += len(chunk) + target.write(chunk) + if digest.hexdigest() != storage["content_hash"] or size != int(storage["byte_size"]): + raise RuntimeError(f"downloaded canonical bytes differ: {storage['object_key']}") + return path + + +def compact_history_payload( + instrument_id: str, timeframe: str, bars: list[Mapping[str, Any]] +) -> str: + payload = { + "schemaVersion": 1, + "adjustment": "all", + "timeframe": timeframe, + "instrumentId": instrument_id, + "bars": [ + { + "t": bar["bar_start_at"].astimezone(UTC).isoformat().replace("+00:00", "Z"), + "o": bar["open"], + "h": bar["high"], + "l": bar["low"], + "c": bar["close"], + "v": bar["volume"], + } + for bar in bars + ], + } + return json.dumps(payload, sort_keys=True, separators=(",", ":"), allow_nan=False) + + +def _project_history( + catalog: Any, + object_store: S3ObjectStore, + redis_client: Any, + config: HistorySyncConfig, + now: datetime, +) -> dict[str, Any]: + counts: dict[str, int] = {} + manifest_ids: list[str] = [] + projected_keys = 0 + hash_tag = "{" + config.redis_key_prefix + ":market}" + with tempfile.TemporaryDirectory(prefix="i2s-history-") as temporary: + temporary_root = Path(temporary) + for timeframe, (layer, lookback_days) in TIMEFRAMES.items(): + manifests = _adjusted_manifests(catalog, timeframe, layer) + if not manifests: + raise RuntimeError(f"no AVAILABLE adjusted history for {timeframe}") + historical_through = max(_timestamp(row["period_end"]) for row in manifests) + cutoff = historical_through - timedelta(days=lookback_days) + selected = [ + manifest + for manifest in manifests + if _timestamp(manifest["period_end"]) > cutoff + ] + manifest_ids.extend(str(row["id"]) for row in selected) + bars_by_instrument: dict[str, deque[dict[str, Any]]] = defaultdict( + lambda: deque(maxlen=config.limit) + ) + relations = [ + relation + for manifest in selected + for relation in catalog.objects_for_manifest(str(manifest["id"])) + if _timestamp(relation["period_end"]) > cutoff + ] + relations.sort( + key=lambda row: ( + _timestamp(row["period_start"]), + str(row["shard_key"]), + int(row["part_number"]), + ) + ) + for relation in relations: + path = _verified_parquet(object_store, relation, temporary_root) + table = pq.read_table( + path, + columns=[ + "instrument_id", "bar_start_at", "open", "high", + "low", "close", "volume", + ], + filters=[("bar_start_at", ">=", cutoff)], + ).sort_by([("instrument_id", "ascending"), ("bar_start_at", "ascending")]) + for bar in table.to_pylist(): + bars_by_instrument[str(bar["instrument_id"])].append(bar) + path.unlink(missing_ok=True) + counts[timeframe] = sum(len(bars) for bars in bars_by_instrument.values()) + for instrument_id, bars in bars_by_instrument.items(): + key = f"{hash_tag}:history:bars:{instrument_id}:{timeframe}" + redis_client.set( + key, + compact_history_payload(instrument_id, timeframe, list(bars)), + ) + projected_keys += 1 + metadata = { + "schemaVersion": 1, + "adjustment": "all", + "generatedAt": now.isoformat().replace("+00:00", "Z"), + "limit": config.limit, + "manifestIds": sorted(set(manifest_ids)), + "barCounts": counts, + } + redis_client.set( + f"{hash_tag}:history:metadata", + json.dumps(metadata, sort_keys=True, separators=(",", ":")), + ) + return {"projected_key_count": projected_keys, "bar_counts": counts} + + +def execute( + environment: Mapping[str, str] | None = None, + *, + now: datetime | None = None, +) -> dict[str, Any]: + config = HistorySyncConfig.from_environment(environment) + observed_at = (now or datetime.now(UTC)).astimezone(UTC) + import boto3 + import redis + + catalog = PostgresCatalog.connect( + config.database_url, + artifact_root=config.state_root / "market-history" / "catalog-artifacts", + storage_objects=StorageObjectsPolicy.WRITE_D_OWNED, + ) + object_store = S3ObjectStore(config.bucket, client=boto3.client("s3")) + redis_client = redis.Redis.from_url(config.redis_uri, decode_responses=True) + try: + catalog.verify_schema() + publication = _publish_missing_history(catalog, object_store, config, observed_at) + projection = _project_history( + catalog, object_store, redis_client, config, observed_at + ) + finally: + redis_client.close() + catalog.close() + + from apps.pipeline_worker.publish_manifest_watermarks import execute as publish_watermarks + + watermarks = publish_watermarks([], environment) + return { + "status": "SUCCEEDED", + "publication": publication, + "projection": projection, + "watermarks": watermarks, + } diff --git a/market_pipeline_lib/engine.py b/market_pipeline_lib/engine.py index 5e974ce..dc42355 100644 --- a/market_pipeline_lib/engine.py +++ b/market_pipeline_lib/engine.py @@ -280,6 +280,7 @@ def __init__( catalog: MarketDataCatalog | None = None, source: BarSource | None = None, watermark_repository: WatermarkRepository | None = None, + ensure_provider_metadata: bool = True, ) -> None: config.validate() self.config = config @@ -290,12 +291,13 @@ def __init__( ) self.source = source self.watermark_repository = watermark_repository + self.ensure_provider_metadata = ensure_provider_metadata self.mappings = load_instrument_map(config.instrument_map_path) self.feed_ids = { code: deterministic_uuid("feed", PROVIDER_CODE, code) for code in FEED_METADATA } - if not config.dry_run: + if not config.dry_run and ensure_provider_metadata: self._ensure_provider_metadata() def _ensure_provider_metadata(self) -> None: @@ -1937,6 +1939,7 @@ def incremental( catalog=self.catalog, source=self.source, watermark_repository=self.watermark_repository, + ensure_provider_metadata=self.ensure_provider_metadata, ) correction_start = datetime( retained_years[0], diff --git a/tests/test_market_history_sync.py b/tests/test_market_history_sync.py new file mode 100644 index 0000000..ff9c619 --- /dev/null +++ b/tests/test_market_history_sync.py @@ -0,0 +1,391 @@ +from __future__ import annotations + +import hashlib +import json +from datetime import UTC, datetime +from io import BytesIO +from pathlib import Path + +import pyarrow as pa +import pyarrow.parquet as pq +import pytest + +from apps.pipeline_worker import sync_market_history +from apps.pipeline_worker.main import EXIT_OK, main +from apps.pipeline_worker.sync_market_history import ( + HistorySyncConfig, + _project_history, + _publish_missing_history, + _write_instrument_map, + compact_history_payload, + completed_sessions_after, + execute, +) +from market_pipeline_lib.contracts import ADJUSTED_FEED, deterministic_uuid +from market_pipeline_lib.storage import VerificationResult + + +def test_history_sync_config_requires_canonical_sources_and_projection_target() -> None: + with pytest.raises(ValueError, match="ALPACA_API_KEY"): + HistorySyncConfig.from_environment({}) + + +def test_history_sync_config_parses_and_bounds_the_projection() -> None: + environment = { + "PIPELINE_WORKER_DATABASE_URL": "postgresql://catalog", + "MARKET_DATA_BUCKET": "bucket", + "PIPELINE_WORKER_MARKET_HISTORY_REDIS_URI": "rediss://cache:6379", + "PIPELINE_WORKER_MARKET_HISTORY_REDIS_KEY_PREFIX": "market", + "PIPELINE_WORKER_OBJECT_STORE_ROOT": "state", + "ALPACA_API_KEY": "key", + "ALPACA_SECRET_KEY": "secret", + } + + config = HistorySyncConfig.from_environment(environment) + + assert config.limit == 400 + assert config.redis_key_prefix == "market" + assert config.state_root == Path("state") + with pytest.raises(ValueError, match="plain"): + HistorySyncConfig.from_environment({ + **environment, + "PIPELINE_WORKER_MARKET_HISTORY_REDIS_KEY_PREFIX": "{bad}", + }) + with pytest.raises(ValueError, match="between"): + HistorySyncConfig.from_environment({ + **environment, + "PIPELINE_WORKER_MARKET_HISTORY_LIMIT": "0", + }) + + +def test_completed_sessions_selects_only_closes_after_manifest_and_before_now() -> None: + sessions = completed_sessions_after( + datetime(2026, 8, 7, 20, 0, tzinfo=UTC), + datetime(2026, 8, 10, 21, 0, tzinfo=UTC), + ) + + assert sessions == [datetime(2026, 8, 10, tzinfo=UTC).date()] + + +def test_compact_projection_declares_adjusted_semantics_and_timeframe() -> None: + encoded = compact_history_payload( + "70000000-0000-4000-8000-000000000001", + "4h", + [ + { + "bar_start_at": datetime(2026, 8, 10, 13, 30, tzinfo=UTC), + "open": 100.0, + "high": 102.0, + "low": 99.0, + "close": 101.0, + "volume": 1200, + } + ], + ) + + payload = json.loads(encoded) + assert payload == { + "schemaVersion": 1, + "adjustment": "all", + "timeframe": "4h", + "instrumentId": "70000000-0000-4000-8000-000000000001", + "bars": [ + { + "t": "2026-08-10T13:30:00Z", + "o": 100.0, + "h": 102.0, + "l": 99.0, + "c": 101.0, + "v": 1200, + } + ], + } + + +def test_pipeline_worker_exposes_the_scheduled_history_sync(monkeypatch: pytest.MonkeyPatch) -> None: + called: list[object] = [] + monkeypatch.setattr( + sync_market_history, + "execute", + lambda environment: called.append(environment) or {"status": "SUCCEEDED"}, + ) + + assert main(["--sync-market-history"], {"TEST": "value"}) == EXIT_OK + assert called == [{"TEST": "value"}] + + +def test_projection_reads_exact_available_s3_versions_and_writes_separate_history_keys() -> None: + instrument_id = "70000000-0000-4000-8000-000000000001" + observed_at = datetime(2026, 8, 10, 21, 0, tzinfo=UTC) + buffer = BytesIO() + pq.write_table( + pa.table( + { + "instrument_id": [instrument_id], + "bar_start_at": [datetime(2026, 8, 10, 13, 30, tzinfo=UTC)], + "open": [100.0], + "high": [102.0], + "low": [99.0], + "close": [101.0], + "volume": [1200], + } + ), + buffer, + ) + parquet = buffer.getvalue() + digest = hashlib.sha256(parquet).hexdigest() + feed_id = deterministic_uuid("feed", "ALPACA", ADJUSTED_FEED) + manifests = [ + { + "id": timeframe, + "feed_id": feed_id, + "status": "AVAILABLE", + "data_layer": "ADJUSTED" if timeframe == "30m" else "DERIVED", + "resolution": timeframe, + "period_start": "2026-08-10T13:30:00Z", + "period_end": "2026-08-10T20:00:00Z", + "revision_number": 1, + } + for timeframe in ("30m", "1h", "4h", "1d") + ] + + class Catalog: + def records(self, table: str) -> list[dict[str, object]]: + assert table == "market_data.dataset_manifests" + return manifests + + def objects_for_manifest(self, manifest_id: str) -> list[dict[str, object]]: + return [{ + "period_start": "2026-08-10T13:30:00Z", + "period_end": "2026-08-10T20:00:00Z", + "shard_key": "s00-of-16", + "part_number": 1, + "storage": { + "id": f"object-{manifest_id}", + "object_key": f"history/{manifest_id}.parquet", + "provider_version_id": f"version-{manifest_id}", + "content_hash": digest, + "byte_size": len(parquet), + }, + }] + + class ObjectStore: + def __init__(self) -> None: + self.versions: list[tuple[str, str]] = [] + + def verify_version(self, key: str, version: str, sha: str, size: int) -> VerificationResult: + self.versions.append((key, version)) + assert sha == digest + assert size == len(parquet) + return VerificationResult(True, sha, size) + + def open_version(self, key: str, version: str) -> BytesIO: + assert (key, version) in self.versions + return BytesIO(parquet) + + class Redis: + def __init__(self) -> None: + self.values: dict[str, str] = {} + + def set(self, key: str, value: str) -> None: + self.values[key] = value + + store = ObjectStore() + redis = Redis() + config = HistorySyncConfig( + database_url="postgresql://example", + bucket="bucket", + redis_uri="rediss://cache:6379", + redis_key_prefix="i2s", + limit=400, + api_key="key", + api_secret="secret", + state_root=Path("."), + ) + + report = _project_history(Catalog(), store, redis, config, observed_at) # type: ignore[arg-type] + + assert report["projected_key_count"] == 4 + assert len(store.versions) == 4 + history_keys = {key for key in redis.values if ":history:bars:" in key} + assert history_keys == { + f"{{i2s:market}}:history:bars:{instrument_id}:{timeframe}" + for timeframe in ("30m", "1h", "4h", "1d") + } + + +def test_instrument_map_uses_only_the_active_primary_symbol(tmp_path: Path) -> None: + class Catalog: + def records(self, table: str) -> list[dict[str, object]]: + if table == "market_data.instruments": + return [{ + "id": "70000000-0000-4000-8000-000000000001", + "primary_exchange_mic": "XNAS", + "listed_at": "2020-01-01", + "delisted_at": None, + }] + return [ + { + "instrument_id": "70000000-0000-4000-8000-000000000001", + "exchange_mic": "XNAS", + "symbol": "AAPL", + "effective_from": "2020-01-01T00:00:00Z", + "effective_to": None, + }, + { + "instrument_id": "70000000-0000-4000-8000-000000000001", + "exchange_mic": "XNYS", + "symbol": "WRONG", + "effective_from": "2020-01-01T00:00:00Z", + "effective_to": None, + }, + ] + + output = tmp_path / "active.csv" + + assert _write_instrument_map(Catalog(), output, datetime(2026, 8, 10, tzinfo=UTC)) == 1 + assert output.read_text(encoding="utf-8").splitlines() == [ + "provider_symbol,instrument_id", + "AAPL,70000000-0000-4000-8000-000000000001", + ] + + +def test_publication_is_a_no_op_when_the_available_manifest_is_current(tmp_path: Path) -> None: + feed_id = deterministic_uuid("feed", "ALPACA", ADJUSTED_FEED) + + class Catalog: + def records(self, table: str) -> list[dict[str, object]]: + assert table == "market_data.dataset_manifests" + return [{ + "id": "manifest", + "feed_id": feed_id, + "status": "AVAILABLE", + "data_layer": "ADJUSTED", + "resolution": "30m", + "period_start": "2026-08-10T13:30:00Z", + "period_end": "2026-08-10T20:00:00Z", + "revision_number": 1, + }] + + report = _publish_missing_history( + Catalog(), object(), sync_config(tmp_path), datetime(2026, 8, 10, 21, 0, tzinfo=UTC) # type: ignore[arg-type] + ) + + assert report["status"] == "CURRENT" + + +def test_publication_commits_recoverable_session_batches( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + feed_id = deterministic_uuid("feed", "ALPACA", ADJUSTED_FEED) + sessions = [datetime(2026, 7, day, tzinfo=UTC).date() for day in range(1, 22)] + + class Catalog: + def records(self, table: str) -> list[dict[str, object]]: + assert table == "market_data.dataset_manifests" + return [{ + "id": "manifest", + "feed_id": feed_id, + "status": "AVAILABLE", + "data_layer": "ADJUSTED", + "resolution": "30m", + "period_start": "2026-06-01T13:30:00Z", + "period_end": "2026-06-30T20:00:00Z", + "revision_number": 1, + }] + + batches: list[list[object]] = [] + + class Engine: + def __init__(self, *args: object, **kwargs: object) -> None: + pass + + def incremental(self, **kwargs: object) -> dict[str, object]: + batch = list(kwargs["sessions"]) # type: ignore[arg-type] + batches.append(batch) + return {"status": "SUCCEEDED", "pipeline_run_id": f"run-{len(batches)}"} + + monkeypatch.setattr( + "apps.pipeline_worker.sync_market_history.completed_sessions_after", + lambda *_args: sessions, + ) + monkeypatch.setattr( + "apps.pipeline_worker.sync_market_history._write_instrument_map", + lambda *_args: 725, + ) + monkeypatch.setattr("apps.pipeline_worker.sync_market_history.MarketPipelineEngine", Engine) + monkeypatch.setattr( + "apps.pipeline_worker.sync_market_history.AlpacaBarSource", lambda *_args: object() + ) + + report = _publish_missing_history( + Catalog(), object(), sync_config(tmp_path), datetime(2026, 8, 10, 21, 0, tzinfo=UTC) # type: ignore[arg-type] + ) + + assert [len(batch) for batch in batches] == [20, 1] + assert report["pipeline_run_ids"] == ["run-1", "run-2"] + + +def test_execute_closes_adapters_and_advances_watermarks( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + config = sync_config(tmp_path) + + class Catalog: + engine = object() + + def verify_schema(self) -> None: + calls.append("verify") + + def close(self) -> None: + calls.append("catalog-close") + + class Redis: + def close(self) -> None: + calls.append("redis-close") + + calls: list[str] = [] + monkeypatch.setattr( + HistorySyncConfig, "from_environment", classmethod(lambda cls, env: config) + ) + monkeypatch.setattr( + "apps.pipeline_worker.sync_market_history.PostgresCatalog.connect", + lambda *_args, **_kwargs: Catalog(), + ) + monkeypatch.setattr( + "apps.pipeline_worker.sync_market_history.S3ObjectStore", + lambda *_args, **_kwargs: object(), + ) + monkeypatch.setattr("boto3.client", lambda *_args, **_kwargs: object()) + monkeypatch.setattr("redis.Redis.from_url", lambda *_args, **_kwargs: Redis()) + monkeypatch.setattr( + "apps.pipeline_worker.sync_market_history._publish_missing_history", + lambda *_args: {"status": "CURRENT"}, + ) + monkeypatch.setattr( + "apps.pipeline_worker.sync_market_history._project_history", + lambda *_args: {"projected_key_count": 4}, + ) + monkeypatch.setattr( + "apps.pipeline_worker.publish_manifest_watermarks.execute", + lambda *_args: {"advanced": 4}, + ) + + report = execute({}, now=datetime(2026, 8, 10, 21, 0, tzinfo=UTC)) + + assert report["status"] == "SUCCEEDED" + assert calls == ["verify", "redis-close", "catalog-close"] + assert report["watermarks"] == {"advanced": 4} + + +def sync_config(root: Path) -> HistorySyncConfig: + return HistorySyncConfig( + database_url="postgresql://catalog", + bucket="bucket", + redis_uri="rediss://cache:6379", + redis_key_prefix="i2s", + limit=400, + api_key="key", + api_secret="secret", + state_root=root, + )