diff --git a/Microstructure/.gitignore b/Microstructure/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..612aa69b1f3940b9d87e25c354565d64affbc84a --- /dev/null +++ b/Microstructure/.gitignore @@ -0,0 +1,36 @@ +.DS_Store +.idea/ +.vscode/ +.venv/ +__pycache__/ +*.py[cod] +*.egg-info/ +.pytest_cache/ +.ruff_cache/ +.mypy_cache/ +.coverage +htmlcov/ + +# External and generated research data must stay local. +data/raw/** +data/normalized/** +data/derived/** +data/models/** +data/quality/** +data/_ingestion_manifests/** +data/m8/** +data/m8_l2/** +data/exploratory_aggtrades_2026-08-05_08/** +!data/raw/.gitkeep +!data/normalized/.gitkeep +!data/derived/.gitkeep +!data/models/.gitkeep +!data/quality/.gitkeep +!data/_ingestion_manifests/.gitkeep + +# Generated run artifacts are reproducible and may contain large files. +artifacts/runs/** +!artifacts/runs/.gitkeep + +# Generated dashboard/runtime files. +.streamlit/secrets.toml diff --git a/Microstructure/.python-version b/Microstructure/.python-version new file mode 100644 index 0000000000000000000000000000000000000000..e4fba2183587225f216eeada4c78dfab6b2e65f5 --- /dev/null +++ b/Microstructure/.python-version @@ -0,0 +1 @@ +3.12 diff --git a/Microstructure/AGENTS.md b/Microstructure/AGENTS.md new file mode 100644 index 0000000000000000000000000000000000000000..a848a26bb2c9cec1ef17bcbfdaaeef0490a7b014 --- /dev/null +++ b/Microstructure/AGENTS.md @@ -0,0 +1,66 @@ +# Repository instructions + +These instructions apply to the entire repository. + +## Mission and safety boundary + +Build a reproducible research and simulation system for short-horizon market +microstructure. The repository must never place live orders, authenticate to a +trading account, or imply that a simulated result is executable profit. + +## Research integrity + +- Never invent observations, performance, statistical significance, or a data + source. Label synthetic, fixture, smoke-test, partial, and full-data results. +- Keep predictive quality, execution assumptions, and strategy results separate. +- Every generated result must include the configuration hash, input manifest + hashes, UTC data interval, code version or explicit `UNBORN`, and dirty state. +- Preserve raw observations. Put transformations in normalized or derived data + and log exclusions; do not silently repair suspect events. +- Treat a timestamp at decision time `t` as unavailable unless its event and + receipt ordering prove it was observable at `t`. Features use information at + or before `t`; labels begin strictly after `t`. +- Do not tune against the final test period. Use time-ordered splits, purge + overlapping label horizons, and embargo adjacent folds when configured. + +## Engineering conventions + +- Target Python 3.12 and a local Apple Silicon machine with 16 GB RAM. +- Keep core logic in `src/microstructure`; notebooks may call but not duplicate it. +- Prefer Polars lazy/streaming scans and partitioned Parquet. DuckDB may query + partitions without loading the full data set. +- New data sources implement the adapter interfaces; exchange-specific fields do + not leak into normalized research modules. +- Store timestamps as UTC epoch nanoseconds and prices/quantities as decimal-safe + integer ticks/lots where the adapter supplies metadata; floating research + columns must document their units. +- Randomized procedures require an explicit seed. +- External raw data belongs under ignored `data/raw`; only small, documented test + fixtures belong in Git. + +## Verification + +Run focused tests after each meaningful phase and `make check` before handoff. +Tests must cover sequence gaps and book invariants, temporal leakage, purged +splits, deterministic simulations, partial fills, fees, and latency. A test may +not call the public internet; mock adapters at the HTTP boundary. + +Primary commands: + +```text +make setup +make download-sample +make validate-data +make smoke +make test +make reproduce-sample +make report +make dashboard +``` + +## Documentation discipline + +Record material assumptions and reversals in `docs/DECISION_LOG.md`. Keep +`STATUS.md` honest and current. Update `docs/PROJECT_PLAN.md` acceptance evidence +when a milestone moves state. Do not manually paste model metrics into prose; +reports must read machine-generated run artifacts. diff --git a/Microstructure/LICENSE b/Microstructure/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..742b3e7d361088aebccb84b93401e22b1e11bb84 --- /dev/null +++ b/Microstructure/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Microstructure Research Project + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Microstructure/Makefile b/Microstructure/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..158d0d9eaaaa22f5d7594c4b0af158105d2202d6 --- /dev/null +++ b/Microstructure/Makefile @@ -0,0 +1,202 @@ +PYTHON_BIN ?= python3.12 +PYTHON ?= .venv/bin/python +RUN_DIR ?= artifacts/runs/sample-smoke +PUBLIC_RUN_DIR ?= artifacts/runs/binance-public-sample +SMOKE_CONFIG ?= configs/smoke.toml +PUBLIC_CONFIG ?= configs/public_sample.toml +PUBLIC_INGESTION_MANIFEST ?= +PUBLIC_INGESTION_MANIFEST_SHA256 ?= +M8_CONFIG ?= configs/m8_multidate_trade_study.toml +M8_DATA_ROOT ?= data/m8 +M8_RUN_DIR ?= artifacts/runs/binance-m8-multidate +M8_RAW_MANIFEST ?= +M8_RAW_MANIFEST_SHA256 ?= +M8_L2_CONFIG ?= configs/m8_l2_capture_study.toml +M8_L2_ANALYSIS_CONFIG ?= configs/m8_l2_analysis.toml +M8_L2_DATA_ROOT ?= data/m8_l2 +M8_L2_SESSION_DATE ?= +M8_L2_BUNDLE_DIR ?= +M8_L2_TRAIN_BUNDLE_DIR ?= +M8_L2_TRAIN_MANIFEST_SHA256 ?= +M8_L2_TRAIN_CHECKSUMS_SHA256 ?= +M8_L2_VALIDATION_BUNDLE_DIR ?= +M8_L2_VALIDATION_MANIFEST_SHA256 ?= +M8_L2_VALIDATION_CHECKSUMS_SHA256 ?= +M8_L2_DEVELOPMENT_LOCK_DIR ?= +M8_L2_DEVELOPMENT_LOCK_SHA256 ?= +M8_L2_PRIMARY_BUNDLE_DIR ?= +M8_L2_PRIMARY_MANIFEST_SHA256 ?= +M8_L2_PRIMARY_CHECKSUMS_SHA256 ?= +M8_L2_REPLICATION_BUNDLE_DIR ?= +M8_L2_REPLICATION_MANIFEST_SHA256 ?= +M8_L2_REPLICATION_CHECKSUMS_SHA256 ?= +M8_L2_RUN_DIR ?= artifacts/runs/binance-m8-live-l2 +M8_L2_RUN_MANIFEST_SHA256 ?= +M8_L2_RUN_CHECKSUMS_SHA256 ?= +M8_L2_REPORT_DIR ?= artifacts/runs/binance-m8-live-l2-reports + +.PHONY: setup download-sample download-m8 capture-m8-l2-session verify-m8-l2-session lock-m8-l2-development verify-m8-l2-development-lock reproduce-m8-l2 verify-m8-l2-run report-m8-l2 validate-data validate-public-data smoke check-smoke test reproduce-sample reproduce-public-sample reproduce-m8 verify-run verify-public-run verify-m8-run report report-public report-m8 dashboard dashboard-public lint typecheck check + +setup: + @if command -v uv >/dev/null 2>&1; then \ + uv sync --locked --extra dev; \ + else \ + "$(PYTHON_BIN)" -m venv .venv; \ + .venv/bin/python -m pip install --upgrade pip; \ + .venv/bin/pip install -e ".[dev]"; \ + fi + +download-sample: + $(PYTHON) -m microstructure.cli ingest --config $(PUBLIC_CONFIG) + +download-m8: + $(PYTHON) -m microstructure.cli acquire-m8 --config "$(M8_CONFIG)" --output-root "$(M8_DATA_ROOT)" + +capture-m8-l2-session: + @test -n "$(M8_L2_SESSION_DATE)" || { echo "M8_L2_SESSION_DATE is required"; exit 2; } + @status=0; $(PYTHON) -m microstructure.cli capture-m8-l2-session --config "$(M8_L2_CONFIG)" --date "$(M8_L2_SESSION_DATE)" --output-root "$(M8_L2_DATA_ROOT)" || status=$$?; if [ "$$status" -eq 1 ]; then exit 0; fi; exit "$$status" + +verify-m8-l2-session: + @test -n "$(M8_L2_BUNDLE_DIR)" || { echo "M8_L2_BUNDLE_DIR is required"; exit 2; } + $(PYTHON) -m microstructure.cli verify-m8-l2-session --config "$(M8_L2_CONFIG)" --bundle-dir "$(M8_L2_BUNDLE_DIR)" + +lock-m8-l2-development: + @test -n "$(M8_L2_TRAIN_BUNDLE_DIR)" || { echo "M8_L2_TRAIN_BUNDLE_DIR is required"; exit 2; } + @test -n "$(M8_L2_TRAIN_MANIFEST_SHA256)" || { echo "M8_L2_TRAIN_MANIFEST_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_TRAIN_CHECKSUMS_SHA256)" || { echo "M8_L2_TRAIN_CHECKSUMS_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_VALIDATION_BUNDLE_DIR)" || { echo "M8_L2_VALIDATION_BUNDLE_DIR is required"; exit 2; } + @test -n "$(M8_L2_VALIDATION_MANIFEST_SHA256)" || { echo "M8_L2_VALIDATION_MANIFEST_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_VALIDATION_CHECKSUMS_SHA256)" || { echo "M8_L2_VALIDATION_CHECKSUMS_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_DEVELOPMENT_LOCK_DIR)" || { echo "M8_L2_DEVELOPMENT_LOCK_DIR is required"; exit 2; } + @status=0; $(PYTHON) -m microstructure.cli lock-m8-l2-development --capture-config "$(M8_L2_CONFIG)" --analysis-config "$(M8_L2_ANALYSIS_CONFIG)" --train-bundle-dir "$(M8_L2_TRAIN_BUNDLE_DIR)" --train-manifest-sha256 "$(M8_L2_TRAIN_MANIFEST_SHA256)" --train-checksums-sha256 "$(M8_L2_TRAIN_CHECKSUMS_SHA256)" --validation-bundle-dir "$(M8_L2_VALIDATION_BUNDLE_DIR)" --validation-manifest-sha256 "$(M8_L2_VALIDATION_MANIFEST_SHA256)" --validation-checksums-sha256 "$(M8_L2_VALIDATION_CHECKSUMS_SHA256)" --lock-dir "$(M8_L2_DEVELOPMENT_LOCK_DIR)" || status=$$?; if [ "$$status" -eq 1 ]; then exit 0; fi; exit "$$status" + +verify-m8-l2-development-lock: + @test -n "$(M8_L2_TRAIN_BUNDLE_DIR)" || { echo "M8_L2_TRAIN_BUNDLE_DIR is required"; exit 2; } + @test -n "$(M8_L2_TRAIN_MANIFEST_SHA256)" || { echo "M8_L2_TRAIN_MANIFEST_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_TRAIN_CHECKSUMS_SHA256)" || { echo "M8_L2_TRAIN_CHECKSUMS_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_VALIDATION_BUNDLE_DIR)" || { echo "M8_L2_VALIDATION_BUNDLE_DIR is required"; exit 2; } + @test -n "$(M8_L2_VALIDATION_MANIFEST_SHA256)" || { echo "M8_L2_VALIDATION_MANIFEST_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_VALIDATION_CHECKSUMS_SHA256)" || { echo "M8_L2_VALIDATION_CHECKSUMS_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_DEVELOPMENT_LOCK_DIR)" || { echo "M8_L2_DEVELOPMENT_LOCK_DIR is required"; exit 2; } + @test -n "$(M8_L2_DEVELOPMENT_LOCK_SHA256)" || { echo "M8_L2_DEVELOPMENT_LOCK_SHA256 is required"; exit 2; } + @status=0; $(PYTHON) -m microstructure.cli verify-m8-l2-development-lock --capture-config "$(M8_L2_CONFIG)" --analysis-config "$(M8_L2_ANALYSIS_CONFIG)" --train-bundle-dir "$(M8_L2_TRAIN_BUNDLE_DIR)" --train-manifest-sha256 "$(M8_L2_TRAIN_MANIFEST_SHA256)" --train-checksums-sha256 "$(M8_L2_TRAIN_CHECKSUMS_SHA256)" --validation-bundle-dir "$(M8_L2_VALIDATION_BUNDLE_DIR)" --validation-manifest-sha256 "$(M8_L2_VALIDATION_MANIFEST_SHA256)" --validation-checksums-sha256 "$(M8_L2_VALIDATION_CHECKSUMS_SHA256)" --lock-dir "$(M8_L2_DEVELOPMENT_LOCK_DIR)" --development-lock-sha256 "$(M8_L2_DEVELOPMENT_LOCK_SHA256)" || status=$$?; if [ "$$status" -eq 1 ]; then exit 0; fi; exit "$$status" + +reproduce-m8-l2: + @test -n "$(M8_L2_TRAIN_BUNDLE_DIR)" || { echo "M8_L2_TRAIN_BUNDLE_DIR is required"; exit 2; } + @test -n "$(M8_L2_TRAIN_MANIFEST_SHA256)" || { echo "M8_L2_TRAIN_MANIFEST_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_TRAIN_CHECKSUMS_SHA256)" || { echo "M8_L2_TRAIN_CHECKSUMS_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_VALIDATION_BUNDLE_DIR)" || { echo "M8_L2_VALIDATION_BUNDLE_DIR is required"; exit 2; } + @test -n "$(M8_L2_VALIDATION_MANIFEST_SHA256)" || { echo "M8_L2_VALIDATION_MANIFEST_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_VALIDATION_CHECKSUMS_SHA256)" || { echo "M8_L2_VALIDATION_CHECKSUMS_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_DEVELOPMENT_LOCK_DIR)" || { echo "M8_L2_DEVELOPMENT_LOCK_DIR is required"; exit 2; } + @test -n "$(M8_L2_DEVELOPMENT_LOCK_SHA256)" || { echo "M8_L2_DEVELOPMENT_LOCK_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_PRIMARY_BUNDLE_DIR)" || { echo "M8_L2_PRIMARY_BUNDLE_DIR is required"; exit 2; } + @test -n "$(M8_L2_PRIMARY_MANIFEST_SHA256)" || { echo "M8_L2_PRIMARY_MANIFEST_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_PRIMARY_CHECKSUMS_SHA256)" || { echo "M8_L2_PRIMARY_CHECKSUMS_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_REPLICATION_BUNDLE_DIR)" || { echo "M8_L2_REPLICATION_BUNDLE_DIR is required"; exit 2; } + @test -n "$(M8_L2_REPLICATION_MANIFEST_SHA256)" || { echo "M8_L2_REPLICATION_MANIFEST_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_REPLICATION_CHECKSUMS_SHA256)" || { echo "M8_L2_REPLICATION_CHECKSUMS_SHA256 is required"; exit 2; } + @status=0; $(PYTHON) -m microstructure.cli reproduce-m8-l2 --capture-config "$(M8_L2_CONFIG)" --analysis-config "$(M8_L2_ANALYSIS_CONFIG)" --train-bundle-dir "$(M8_L2_TRAIN_BUNDLE_DIR)" --train-manifest-sha256 "$(M8_L2_TRAIN_MANIFEST_SHA256)" --train-checksums-sha256 "$(M8_L2_TRAIN_CHECKSUMS_SHA256)" --validation-bundle-dir "$(M8_L2_VALIDATION_BUNDLE_DIR)" --validation-manifest-sha256 "$(M8_L2_VALIDATION_MANIFEST_SHA256)" --validation-checksums-sha256 "$(M8_L2_VALIDATION_CHECKSUMS_SHA256)" --development-lock-dir "$(M8_L2_DEVELOPMENT_LOCK_DIR)" --development-lock-sha256 "$(M8_L2_DEVELOPMENT_LOCK_SHA256)" --primary-bundle-dir "$(M8_L2_PRIMARY_BUNDLE_DIR)" --primary-manifest-sha256 "$(M8_L2_PRIMARY_MANIFEST_SHA256)" --primary-checksums-sha256 "$(M8_L2_PRIMARY_CHECKSUMS_SHA256)" --replication-bundle-dir "$(M8_L2_REPLICATION_BUNDLE_DIR)" --replication-manifest-sha256 "$(M8_L2_REPLICATION_MANIFEST_SHA256)" --replication-checksums-sha256 "$(M8_L2_REPLICATION_CHECKSUMS_SHA256)" --run-dir "$(M8_L2_RUN_DIR)" || status=$$?; if [ "$$status" -eq 1 ]; then exit 0; fi; exit "$$status" + +verify-m8-l2-run: + @test -n "$(M8_L2_TRAIN_BUNDLE_DIR)" || { echo "M8_L2_TRAIN_BUNDLE_DIR is required"; exit 2; } + @test -n "$(M8_L2_TRAIN_MANIFEST_SHA256)" || { echo "M8_L2_TRAIN_MANIFEST_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_TRAIN_CHECKSUMS_SHA256)" || { echo "M8_L2_TRAIN_CHECKSUMS_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_VALIDATION_BUNDLE_DIR)" || { echo "M8_L2_VALIDATION_BUNDLE_DIR is required"; exit 2; } + @test -n "$(M8_L2_VALIDATION_MANIFEST_SHA256)" || { echo "M8_L2_VALIDATION_MANIFEST_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_VALIDATION_CHECKSUMS_SHA256)" || { echo "M8_L2_VALIDATION_CHECKSUMS_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_DEVELOPMENT_LOCK_DIR)" || { echo "M8_L2_DEVELOPMENT_LOCK_DIR is required"; exit 2; } + @test -n "$(M8_L2_DEVELOPMENT_LOCK_SHA256)" || { echo "M8_L2_DEVELOPMENT_LOCK_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_PRIMARY_BUNDLE_DIR)" || { echo "M8_L2_PRIMARY_BUNDLE_DIR is required"; exit 2; } + @test -n "$(M8_L2_PRIMARY_MANIFEST_SHA256)" || { echo "M8_L2_PRIMARY_MANIFEST_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_PRIMARY_CHECKSUMS_SHA256)" || { echo "M8_L2_PRIMARY_CHECKSUMS_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_REPLICATION_BUNDLE_DIR)" || { echo "M8_L2_REPLICATION_BUNDLE_DIR is required"; exit 2; } + @test -n "$(M8_L2_REPLICATION_MANIFEST_SHA256)" || { echo "M8_L2_REPLICATION_MANIFEST_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_REPLICATION_CHECKSUMS_SHA256)" || { echo "M8_L2_REPLICATION_CHECKSUMS_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_RUN_MANIFEST_SHA256)" || { echo "M8_L2_RUN_MANIFEST_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_RUN_CHECKSUMS_SHA256)" || { echo "M8_L2_RUN_CHECKSUMS_SHA256 is required"; exit 2; } + @status=0; $(PYTHON) -m microstructure.cli verify-m8-l2-run --capture-config "$(M8_L2_CONFIG)" --analysis-config "$(M8_L2_ANALYSIS_CONFIG)" --train-bundle-dir "$(M8_L2_TRAIN_BUNDLE_DIR)" --train-manifest-sha256 "$(M8_L2_TRAIN_MANIFEST_SHA256)" --train-checksums-sha256 "$(M8_L2_TRAIN_CHECKSUMS_SHA256)" --validation-bundle-dir "$(M8_L2_VALIDATION_BUNDLE_DIR)" --validation-manifest-sha256 "$(M8_L2_VALIDATION_MANIFEST_SHA256)" --validation-checksums-sha256 "$(M8_L2_VALIDATION_CHECKSUMS_SHA256)" --development-lock-dir "$(M8_L2_DEVELOPMENT_LOCK_DIR)" --development-lock-sha256 "$(M8_L2_DEVELOPMENT_LOCK_SHA256)" --primary-bundle-dir "$(M8_L2_PRIMARY_BUNDLE_DIR)" --primary-manifest-sha256 "$(M8_L2_PRIMARY_MANIFEST_SHA256)" --primary-checksums-sha256 "$(M8_L2_PRIMARY_CHECKSUMS_SHA256)" --replication-bundle-dir "$(M8_L2_REPLICATION_BUNDLE_DIR)" --replication-manifest-sha256 "$(M8_L2_REPLICATION_MANIFEST_SHA256)" --replication-checksums-sha256 "$(M8_L2_REPLICATION_CHECKSUMS_SHA256)" --run-dir "$(M8_L2_RUN_DIR)" --run-manifest-sha256 "$(M8_L2_RUN_MANIFEST_SHA256)" --run-checksums-sha256 "$(M8_L2_RUN_CHECKSUMS_SHA256)" || status=$$?; if [ "$$status" -eq 1 ]; then exit 0; fi; exit "$$status" + +report-m8-l2: + @test -n "$(M8_L2_TRAIN_BUNDLE_DIR)" || { echo "M8_L2_TRAIN_BUNDLE_DIR is required"; exit 2; } + @test -n "$(M8_L2_TRAIN_MANIFEST_SHA256)" || { echo "M8_L2_TRAIN_MANIFEST_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_TRAIN_CHECKSUMS_SHA256)" || { echo "M8_L2_TRAIN_CHECKSUMS_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_VALIDATION_BUNDLE_DIR)" || { echo "M8_L2_VALIDATION_BUNDLE_DIR is required"; exit 2; } + @test -n "$(M8_L2_VALIDATION_MANIFEST_SHA256)" || { echo "M8_L2_VALIDATION_MANIFEST_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_VALIDATION_CHECKSUMS_SHA256)" || { echo "M8_L2_VALIDATION_CHECKSUMS_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_DEVELOPMENT_LOCK_DIR)" || { echo "M8_L2_DEVELOPMENT_LOCK_DIR is required"; exit 2; } + @test -n "$(M8_L2_DEVELOPMENT_LOCK_SHA256)" || { echo "M8_L2_DEVELOPMENT_LOCK_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_PRIMARY_BUNDLE_DIR)" || { echo "M8_L2_PRIMARY_BUNDLE_DIR is required"; exit 2; } + @test -n "$(M8_L2_PRIMARY_MANIFEST_SHA256)" || { echo "M8_L2_PRIMARY_MANIFEST_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_PRIMARY_CHECKSUMS_SHA256)" || { echo "M8_L2_PRIMARY_CHECKSUMS_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_REPLICATION_BUNDLE_DIR)" || { echo "M8_L2_REPLICATION_BUNDLE_DIR is required"; exit 2; } + @test -n "$(M8_L2_REPLICATION_MANIFEST_SHA256)" || { echo "M8_L2_REPLICATION_MANIFEST_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_REPLICATION_CHECKSUMS_SHA256)" || { echo "M8_L2_REPLICATION_CHECKSUMS_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_RUN_MANIFEST_SHA256)" || { echo "M8_L2_RUN_MANIFEST_SHA256 is required"; exit 2; } + @test -n "$(M8_L2_RUN_CHECKSUMS_SHA256)" || { echo "M8_L2_RUN_CHECKSUMS_SHA256 is required"; exit 2; } + @status=0; $(PYTHON) -m microstructure.cli report-m8-l2 --capture-config "$(M8_L2_CONFIG)" --analysis-config "$(M8_L2_ANALYSIS_CONFIG)" --train-bundle-dir "$(M8_L2_TRAIN_BUNDLE_DIR)" --train-manifest-sha256 "$(M8_L2_TRAIN_MANIFEST_SHA256)" --train-checksums-sha256 "$(M8_L2_TRAIN_CHECKSUMS_SHA256)" --validation-bundle-dir "$(M8_L2_VALIDATION_BUNDLE_DIR)" --validation-manifest-sha256 "$(M8_L2_VALIDATION_MANIFEST_SHA256)" --validation-checksums-sha256 "$(M8_L2_VALIDATION_CHECKSUMS_SHA256)" --development-lock-dir "$(M8_L2_DEVELOPMENT_LOCK_DIR)" --development-lock-sha256 "$(M8_L2_DEVELOPMENT_LOCK_SHA256)" --primary-bundle-dir "$(M8_L2_PRIMARY_BUNDLE_DIR)" --primary-manifest-sha256 "$(M8_L2_PRIMARY_MANIFEST_SHA256)" --primary-checksums-sha256 "$(M8_L2_PRIMARY_CHECKSUMS_SHA256)" --replication-bundle-dir "$(M8_L2_REPLICATION_BUNDLE_DIR)" --replication-manifest-sha256 "$(M8_L2_REPLICATION_MANIFEST_SHA256)" --replication-checksums-sha256 "$(M8_L2_REPLICATION_CHECKSUMS_SHA256)" --run-dir "$(M8_L2_RUN_DIR)" --run-manifest-sha256 "$(M8_L2_RUN_MANIFEST_SHA256)" --run-checksums-sha256 "$(M8_L2_RUN_CHECKSUMS_SHA256)" --output-dir "$(M8_L2_REPORT_DIR)" || status=$$?; if [ "$$status" -eq 1 ]; then exit 0; fi; exit "$$status" + +validate-data: + $(PYTHON) -m microstructure.cli validate --config $(SMOKE_CONFIG) + +validate-public-data: + $(PYTHON) -m microstructure.cli validate --config $(PUBLIC_CONFIG) + +smoke: + $(PYTHON) -m microstructure.cli reproduce --config $(SMOKE_CONFIG) --run-dir $(RUN_DIR) + +check-smoke: + @check_root="$$(mktemp -d)"; \ + trap 'rm -rf "$$check_root"' EXIT; \ + $(PYTHON) -m microstructure.cli reproduce --config $(SMOKE_CONFIG) --run-dir "$$check_root/run" + +test: + $(PYTHON) -m pytest + +reproduce-sample: smoke + +reproduce-public-sample: + @test -n "$(PUBLIC_INGESTION_MANIFEST)" || { echo "PUBLIC_INGESTION_MANIFEST is required"; exit 2; } + @test -n "$(PUBLIC_INGESTION_MANIFEST_SHA256)" || { echo "PUBLIC_INGESTION_MANIFEST_SHA256 is required"; exit 2; } + $(PYTHON) -m microstructure.cli reproduce --config $(PUBLIC_CONFIG) --run-dir $(PUBLIC_RUN_DIR) --ingestion-manifest $(PUBLIC_INGESTION_MANIFEST) --ingestion-manifest-sha256 $(PUBLIC_INGESTION_MANIFEST_SHA256) + +reproduce-m8: + @test -n "$(M8_RAW_MANIFEST)" || { echo "M8_RAW_MANIFEST is required"; exit 2; } + @test -n "$(M8_RAW_MANIFEST_SHA256)" || { echo "M8_RAW_MANIFEST_SHA256 is required"; exit 2; } + $(PYTHON) -m microstructure.cli reproduce-m8 --config "$(M8_CONFIG)" --run-dir "$(M8_RUN_DIR)" --raw-manifest "$(M8_RAW_MANIFEST)" --raw-manifest-sha256 "$(M8_RAW_MANIFEST_SHA256)" + +verify-run: + $(PYTHON) -m microstructure.cli verify --run-dir $(RUN_DIR) + +verify-public-run: + $(PYTHON) -m microstructure.cli verify --run-dir $(PUBLIC_RUN_DIR) + +verify-m8-run: + @test -n "$(M8_RAW_MANIFEST)" || { echo "M8_RAW_MANIFEST is required"; exit 2; } + @test -n "$(M8_RAW_MANIFEST_SHA256)" || { echo "M8_RAW_MANIFEST_SHA256 is required"; exit 2; } + $(PYTHON) -m microstructure.cli verify-m8 --config "$(M8_CONFIG)" --run-dir "$(M8_RUN_DIR)" --raw-manifest "$(M8_RAW_MANIFEST)" --raw-manifest-sha256 "$(M8_RAW_MANIFEST_SHA256)" + +report: + $(PYTHON) -m microstructure.cli report --run-dir $(RUN_DIR) + +report-public: + $(PYTHON) -m microstructure.cli report --run-dir $(PUBLIC_RUN_DIR) + +report-m8: + @test -n "$(M8_RAW_MANIFEST)" || { echo "M8_RAW_MANIFEST is required"; exit 2; } + @test -n "$(M8_RAW_MANIFEST_SHA256)" || { echo "M8_RAW_MANIFEST_SHA256 is required"; exit 2; } + $(PYTHON) -m microstructure.cli report-m8 --config "$(M8_CONFIG)" --run-dir "$(M8_RUN_DIR)" --raw-manifest "$(M8_RAW_MANIFEST)" --raw-manifest-sha256 "$(M8_RAW_MANIFEST_SHA256)" + +dashboard: + $(PYTHON) -m streamlit run dashboard/app.py -- --run-dir $(RUN_DIR) + +dashboard-public: + $(PYTHON) -m streamlit run dashboard/app.py -- --run-dir $(PUBLIC_RUN_DIR) + +lint: + $(PYTHON) -m ruff check . + +typecheck: + $(PYTHON) -m mypy src/microstructure + +check: lint typecheck test check-smoke diff --git a/Microstructure/README.md b/Microstructure/README.md new file mode 100644 index 0000000000000000000000000000000000000000..238de1042e22b9cc7ca5bc823d9e89c40663fa7e --- /dev/null +++ b/Microstructure/README.md @@ -0,0 +1,509 @@ +# Order Flow to Price Impact + +A research-only, event-driven market-microstructure platform for asking: + +> When do order-flow imbalance, liquidity, and limit-order-book conditions +> predict short-horizon price movement, and how much apparent value survives +> fees, latency, uncertain fills, adverse selection, and inventory risk? + +The project is deliberately reproducibility-first. It keeps market-data evidence, +predictive diagnostics, execution assumptions, and simulated outcomes separate. +It has no authenticated exchange client, account connection, or order-entry path. + +> **Evidence boundary:** `SYNTHETIC_SMOKE` output verifies software behavior only. +> It is not market, alpha, profitability, or investment evidence. + +## Architecture + +```mermaid +flowchart LR + A["Public REST trades or deterministic synthetic events"] --> B["Raw bytes + immutable manifests"] + C["Optional public live diff-depth + REST snapshot"] --> B + B --> D["Versioned UTC-normalized Arrow schemas"] + D --> E["Partitioned, content-addressed Parquet"] + E --> F["Non-mutating quality findings"] + F --> G["Causal features + strictly future labels"] + G --> H["Purged expanding walk-forward models"] + H --> I["OOS-only execution simulation"] + I --> J["Frozen checksummed run bundle"] + J --> K["Generated reports + read-only dashboard"] +``` + +The normalized event contract retains exchange time, local receipt time when +captured, the conservative availability clock used by research, exact integer +ticks/lots, sequence identifiers, and a continuity epoch. Features, labels, +folds, open orders, and markouts cannot cross a known book gap. + +## Quick start + +Python 3.12 is required. The default acceptance path is deterministic and does +not need internet access: + +```bash +make setup +make check +make reproduce-sample +make report +``` + +The frozen sample is written to `artifacts/runs/sample-smoke`; independently +rendered reports go to `artifacts/runs/sample-smoke-reports`. Both directories +are reproducible and intentionally ignored by Git. + +To inspect the completed run: + +```bash +make verify-run +make dashboard +``` + +The dashboard loads only checksum-verified artifacts. It does not download data, +fit models, rerun simulations, or place orders. + +## Credential-free public sample + +The bounded public path downloads BTCUSDT and ETHUSDT aggregate trades from a +fixed UTC interval, fetches `exchangeInfo` for exact tick and lot scales, keeps +the response bytes, and writes raw and normalized manifests: + +```bash +make download-sample +.venv/bin/python -m microstructure.cli validate \ + --config configs/public_sample.toml +``` + +It uses Binance's public market-data-only REST base URL and requires no API key. +The adapter honors retryable status codes, `Retry-After`, and interrupted body +streams; paginates by trade ID to avoid losing tied timestamps; enforces a +response-byte ceiling; and imposes a small per-symbol row cap. Pages flow once +through disk-backed incremental validation into bounded Parquet batches. See +the official [Spot REST documentation](https://developers.binance.com/en/docs/products/spot/rest-api) +and [Spot WebSocket stream guide](https://developers.binance.com/en/docs/catalog/core-trading-spot-trading/api/ws-streams/~). + +Historical public trade ingestion and live order-book collection are separate on +purpose. Public historical Spot depth is not assumed to exist. A book-based +empirical study begins only after a continuous local snapshot/delta epoch has +been captured and passed sequence checks. + +Producing a public research bundle never scans for a "latest" input. Select the +immutable ingestion manifest explicitly by both path and digest: + +```bash +make reproduce-public-sample \ + PUBLIC_INGESTION_MANIFEST=data/_ingestion_manifests/.json \ + PUBLIC_INGESTION_MANIFEST_SHA256=<64-character-sha256> +make verify-public-run +make report-public +``` + +## Frozen multi-date trade study + +The prospective M8 trade-only study uses the complete BTCUSDT and ETHUSDT +Binance Spot daily aggregate-trade archives for 2024-01-03 through 2024-01-06. +Acquisition is deliberately separate from research production: + +```bash +# Networked, raw-only: authenticates ZIP/CHECKSUM/metadata evidence but never +# opens a CSV member or reads an economic field. +make download-m8 + +# Copy the manifest path and lowercase SHA-256 printed by download-m8. +# Production requires the exact clean committed source tree. +make reproduce-m8 \ + M8_RAW_MANIFEST=data/m8/_manifests/.json \ + M8_RAW_MANIFEST_SHA256=<64-character-sha256> +make verify-m8-run \ + M8_RAW_MANIFEST=data/m8/_manifests/.json \ + M8_RAW_MANIFEST_SHA256=<64-character-sha256> +make report-m8 \ + M8_RAW_MANIFEST=data/m8/_manifests/.json \ + M8_RAW_MANIFEST_SHA256=<64-character-sha256> +``` + +The producer opens and validates only the train and validation members first. +It fits and calibrates the selected model and an independent historical prior +exactly once on development data, persists their canonical numeric preprocessing +and estimator states in each per-symbol lock, closes one aggregate lock, and +revalidates the exact protocol, config, Git/source identity, raw authority, +development manifest, fitted-state hashes, and child locks immediately before +every held-out member is opened. Held-out evaluation restores those states with +no fit, refit, recalibration, or update. +A declared-data failure becomes an immutable `INSUFFICIENT_DATA` bundle with no +replacement date or endpoint predictions. A successful bundle remains +trade-only: execution, P&L, capacity, significance, and cross-instrument pooling +are unauthorized by the protocol. + +That failure branch is the observed outcome of the declared study. The canonical +bundle at `artifacts/runs/binance-m8-multidate` stopped on the ETHUSDT training +archive after complete normalization found 53 `temporal.long_silence` warnings. +BTCUSDT training normalization had already completed with 2,071,461 rows and no +findings; ETHUSDT contributed 987,297 rows, zero errors, and 53 warnings. The +producer did not start selection, create a development lock, open either held-out +date, publish a prediction, or run execution. This is a valid, checksummed +`INSUFFICIENT_DATA` result, not an incomplete attempt and not evidence against or +for the economic hypothesis. +`report-m8` revalidates the terminal and its external raw authority, then renders +the failure report into a separate report directory. It does not repair, append +to, or otherwise mutate the canonical failure bundle. + +## Frozen live-L2 sessions — replacement campaign v2 + +Each declared date is captured by one command that waits for the exact common +UTC barrier and starts both public market-data feeds under one authority. It +never authenticates or exposes an order-entry path: + +```bash +make capture-m8-l2-session M8_L2_SESSION_DATE=2026-08-10 +``` + +The superseded v1 campaign is retained as historical control evidence: Aug 8 +was a verified `MISSED_WINDOW`, Aug 9 completed, and its development authority +is permanently `NOT_CREATED`. It is not rewritten or used by v2. Before any v2 +session was observed, the user explicitly reset the empirical campaign to Aug +10 train, Aug 11 validation, Aug 12 primary test, and Aug 13 replication test, +each at 14:00--15:00 UTC. A missed, disconnected, gapped, warning-bearing, or +otherwise insufficient v2 date is frozen as such and is never replaced. Only +checksum-verified `COMPLETE` bundles may expose economic frames. +A verified held-out `INSUFFICIENT_DATA` bundle may be consumed only as control +evidence for an aggregate insufficiency terminal; its economic frames are never +opened. + +The analysis specification is separately frozen in +[`docs/M8_L2_ANALYSIS_CONTRACT.md`](docs/M8_L2_ANALYSIS_CONTRACT.md). Its strict +loader, session input verifier, observed-interval feature/label construction, +Aug 10/11 development-authority producer, no-refit Aug 12/13 evaluation, market-only +execution evaluator, descriptive diagnostics, and artifact-driven report +renderers are integrated behind tested CLI/Make producers and recursive +verifiers. The software path is complete; no v2 session data existed when the +10--13 calendar and authority bytes were fixed, so v2 may reach either a valid +complete result or an honest insufficiency terminal. No L2 metric or execution +result is claimed before those terminals exist. During the campaign, live +status belongs only to the immutable campaign/session authorities; this tracked +README must not be revised between sessions. +Use the ignored run targets +`artifacts/runs/binance-m8-l2-development-lock` for the durable development +authority and `artifacts/runs/binance-m8-live-l2` for the final campaign bundle; +do not place mutable study state in a source-controlled path. + +### Frozen L2 operating sequence + +Every later command requires explicit authorities; none scans for a "latest" +bundle. The Make targets default to the frozen +`M8_L2_CONFIG=configs/m8_l2_capture_study.toml` and +`M8_L2_ANALYSIS_CONFIG=configs/m8_l2_analysis.toml`; do not substitute either +during the campaign. After each capture, retain the emitted JSON. Its +`output_root`, `session_manifest_sha256`, and `checksums` fields identify the +bundle, manifest digest, and checksum file. Independently hash that exact +checksum file: + +```bash +shasum -a 256 /absolute/session/bundle/checksums.sha256 +``` + +Map those values without abbreviation to the role-specific Make variables: + +- `M8_L2__BUNDLE_DIR` +- `M8_L2__MANIFEST_SHA256` +- `M8_L2__CHECKSUMS_SHA256` + +where `` is `TRAIN`, `VALIDATION`, `PRIMARY`, or `REPLICATION`. Make accepts +these as command-line assignments or exported environment variables. First +verify every session. After the Aug 11 validation terminal, create and verify the +development authority before any held-out analysis. If both development +sessions are `COMPLETE`, the authority is `LOCKED` and contains the eight fitted +child states. If either is a valid `INSUFFICIENT_DATA` terminal, the authority is +`NOT_CREATED`; it contains typed control evidence and deliberately opens no +economic frame. In either case it is immutable, and the Aug 12/13 captures must +still proceed on their declared dates: + +```bash +make verify-m8-l2-session M8_L2_BUNDLE_DIR=/absolute/session/bundle + +make lock-m8-l2-development \ + M8_L2_DEVELOPMENT_LOCK_DIR=artifacts/runs/binance-m8-l2-development-lock \ + M8_L2_TRAIN_BUNDLE_DIR=... M8_L2_TRAIN_MANIFEST_SHA256=... \ + M8_L2_TRAIN_CHECKSUMS_SHA256=... \ + M8_L2_VALIDATION_BUNDLE_DIR=... M8_L2_VALIDATION_MANIFEST_SHA256=... \ + M8_L2_VALIDATION_CHECKSUMS_SHA256=... + +make verify-m8-l2-development-lock \ + M8_L2_DEVELOPMENT_LOCK_DIR=artifacts/runs/binance-m8-l2-development-lock \ + M8_L2_DEVELOPMENT_LOCK_SHA256=... \ + M8_L2_TRAIN_BUNDLE_DIR=... M8_L2_TRAIN_MANIFEST_SHA256=... \ + M8_L2_TRAIN_CHECKSUMS_SHA256=... \ + M8_L2_VALIDATION_BUNDLE_DIR=... M8_L2_VALIDATION_MANIFEST_SHA256=... \ + M8_L2_VALIDATION_CHECKSUMS_SHA256=... +``` + +Use the `development_lock_sha256` printed by the command for either `LOCKED` or +`NOT_CREATED`. The direct CLI returns 1 for a valid `NOT_CREATED` command or +verification; the Make wrapper normalizes that research-terminal code to 0. +In both cases inspect the JSON status and preserve its `development_lock.json`, +exact `_NOT_CREATED` marker (`not-created\n`), and printed authority SHA instead +of retrying or changing dates. After Aug 13, pass +the same development coordinates plus both held-out authorities to the final +producer. A `NOT_CREATED` authority forces an aggregate `INSUFFICIENT_DATA` +result, opens no economic frames from any of the four sessions, and reports the +union of development and held-out control reasons. The command below explicitly +lists all four role triplets; none may be omitted or discovered by wildcard: + +```bash +make reproduce-m8-l2 \ + M8_L2_DEVELOPMENT_LOCK_DIR=artifacts/runs/binance-m8-l2-development-lock \ + M8_L2_DEVELOPMENT_LOCK_SHA256=... \ + M8_L2_TRAIN_BUNDLE_DIR=... M8_L2_TRAIN_MANIFEST_SHA256=... \ + M8_L2_TRAIN_CHECKSUMS_SHA256=... \ + M8_L2_VALIDATION_BUNDLE_DIR=... M8_L2_VALIDATION_MANIFEST_SHA256=... \ + M8_L2_VALIDATION_CHECKSUMS_SHA256=... \ + M8_L2_PRIMARY_BUNDLE_DIR=... M8_L2_PRIMARY_MANIFEST_SHA256=... \ + M8_L2_PRIMARY_CHECKSUMS_SHA256=... \ + M8_L2_REPLICATION_BUNDLE_DIR=... M8_L2_REPLICATION_MANIFEST_SHA256=... \ + M8_L2_REPLICATION_CHECKSUMS_SHA256=... +``` + +The producer prints `run_manifest_sha256` and `checksums_sha256`. Reuse the full +four-session/development authority set and add those two values for +`verify-m8-l2-run` and `report-m8-l2`. If that full set has been exported under +the exact Make variable names above, the terminal commands are: + +```bash +make verify-m8-l2-run M8_L2_RUN_MANIFEST_SHA256=... \ + M8_L2_RUN_CHECKSUMS_SHA256=... +make report-m8-l2 M8_L2_RUN_MANIFEST_SHA256=... \ + M8_L2_RUN_CHECKSUMS_SHA256=... +``` + +`report-m8-l2` recursively verifies the final run and all external authorities, +then writes to `artifacts/runs/binance-m8-live-l2-reports`. It never modifies the +immutable run bundle. At the direct CLI boundary, capture, development, final +producer, verifier, and report commands use exit 1 for a valid insufficiency +terminal; Make maps that one code to success because GNU Make otherwise collapses +it into a generic error. Automation must inspect the emitted JSON status and +exact marker rather than infer research status from Make's process code or retry +with changed dates or rules. + +## Commands + +| Command | Purpose | +| --- | --- | +| `make setup` | Create/synchronize the locked Python 3.12 environment | +| `make download-sample` | Download the bounded credential-free public trade sample | +| `make download-m8` | Acquire the frozen M8 raw authority without opening archive members | +| `make capture-m8-l2-session M8_L2_SESSION_DATE=YYYY-MM-DD` | Capture the frozen concurrent BTCUSDT/ETHUSDT L2 session for one declared date | +| `make verify-m8-l2-session M8_L2_BUNDLE_DIR=` | Verify a complete or `INSUFFICIENT_DATA` frozen L2 session bundle | +| `make lock-m8-l2-development` | Atomically publish the Aug 10/11 development authority: fitted `LOCKED` state when both sessions pass, or control-only `NOT_CREATED` evidence when either is insufficient | +| `make verify-m8-l2-development-lock` | Recursively verify either development-authority status against its path, SHA, configs, sessions, campaign, and clean source identity | +| `make reproduce-m8-l2` | Produce a new immutable four-session L2 terminal bundle; use the explicit-digest verifier for an existing target | +| `make verify-m8-l2-run` | Verify a complete or `INSUFFICIENT_DATA` L2 run plus all external authorities | +| `make report-m8-l2` | Re-render verified L2 reports into a separate directory without mutating the run | +| `make validate-data` | Run offline, non-mutating validation on the synthetic fixture | +| `make validate-public-data` | Validate configured public normalized partitions incrementally | +| `make smoke` | Produce or verify the immutable synthetic vertical slice | +| `make test` | Run all unit and integration tests without network access | +| `make reproduce-sample` | Alias for the canonical smoke producer | +| `make reproduce-public-sample` | Produce a trade-only run from an explicit manifest path + SHA | +| `make reproduce-m8` | Produce M8 from an explicit raw manifest + SHA under a clean commit | +| `make verify-run` | Verify run structure and every protected checksum | +| `make verify-public-run` | Verify the explicit public run bundle | +| `make verify-m8-run` | Verify a complete or `INSUFFICIENT_DATA` M8 terminal bundle | +| `make report` | Render a fresh report set from the frozen bundle | +| `make report-m8` | Render a complete M8 bundle or expose its frozen failure report | +| `make dashboard` | Open the local read-only Streamlit research dashboard | +| `make check` | Run Ruff, strict mypy, pytest, and the smoke producer | + +The equivalent CLI is available as `microstructure` after setup. Run +`microstructure --help` for the `ingest`, `acquire-m8`, `validate`, `reproduce`, +`reproduce-m8`, `verify-m8`, `report-m8`, generic `verify`/`report`, the frozen +`capture-m8-l2-session`, `verify-m8-l2-session`, `lock-m8-l2-development`, +`verify-m8-l2-development-lock`, `reproduce-m8-l2`, `verify-m8-l2-run`, and +`report-m8-l2` commands, plus exploratory research-only `collect-l2`. + +## What is implemented + +- Credential-free aggregate-trade ingestion with bounded retries, raw response + preservation, symbol metadata, exact scaling, immutable manifests, and + streaming partitioned Parquet writes. A verified public reader performs + physical-order incremental DQ and a single upstream Parquet pass into a + spill-capable DuckDB canonical sort; eager compatibility reads have a separate + hard row limit. +- Optional public live diff-depth capture plus REST snapshot anchoring and pure + `U/u` reconstruction with stale, overlap, gap, crossed-book, and invariant + checks. Reconnection starts a new continuity epoch. The frozen L2 runner uses + one absolute UTC barrier for both instruments, a byte-bounded receiver queue, + OBSERVED-only continuity intervals, cross-symbol overlap gates, exhaustive + artifact inventory, and atomic `COMPLETE`/`INSUFFICIENT_DATA` evidence. +- Typed quality findings for duplicates, ordering and clocks, invalid values, + scale mismatches, abnormal spread, silence, gaps, and crossed books. Validation + never repairs observations. +- Leakage-safe spread, L1/L5/L10 depth state, queue imbalance, microprice, OFI, + signed flow, intensity, volatility, observable zero-quantity cancellation, + causal lagged impact/recovery, regime, and stability features, with event-time + and clock-time labels and explicit censoring. +- A common-fold model ladder: historical prior, unpenalized logistic regression, + L2-regularized logistic grid, and shallow tree. Selection uses validation data; + the final test is frozen. Calibration and protocol-specific paired bootstrap + diagnostics are serialized with their block count, status, and seed: the + trade-only study uses fixed dependency blocks, while the prospective L2 study + uses interval-local overlapping moving blocks. Neither is presented as a + complete model of cross-instrument or overlapping-label dependence. +- OOS-only market/limit simulation with decision and order latency, maker/taker + fees, adverse price rounding, top-depth caps, partial fills, a declared queue + proxy, adverse selection, inventory limits, liquidation, turnover, and size + sensitivity. +- Atomic run production. `_SUCCESS` is written last; every other file is covered + by `checksums.sha256`. A completed target is read-only and reusable only when + the caller supplies its previously retained manifest and checksum digests to + the recursive verifier. +- Raw-only M8 acquisition with exact official CHECKSUM evidence, bounded ZIP + central-directory inspection, a hard retained-evidence byte ledger, an exact + content-addressed inventory, and an atomic self-contained bundle copy. The M8 + producer enforces development-only normalization and final selected/prior + fitting before a durable analysis lock, restores transparent numeric states + for prediction, and fails closed at every held-out member-open boundary. +- Frozen L2 campaign identity and strict session readers that reject changed + clean-source identities, tampered or symlinked artifacts, invalid Parquet + footers/schemas, row mismatches, and continuity violations before exposing a + frame. One outcome-blind nonce binds all dates to the canonical output-root + path/filesystem identity, loaded source/import origin, and a hashed fingerprint + of Python, platform, and eight production dependency versions. Development-only + regime/model locks, no-refit held-out evaluation, paired dependency-block + diagnostics, market-only scenarios, descriptive analyses, and generated L2 + reports feed one atomic final producer. Fail-closed memory admissions reserve + at most 8 GiB for development materialization and 12 GiB for final production + (raw, causal, evaluation, descriptive, and execution workspaces), leaving at + least 4 GiB of the 16 GiB host envelope for the interpreter and libraries; + every major allocation is checked before and immediately after materialization. + Its verifier streams tabular checks, + recursively revalidates the four external sessions and development authority, + binds a self-contained authority snapshot, rejects tampering, and enforces + `COMPLETE` versus `INSUFFICIENT_DATA` semantics. +- Generated technical report, two-page IC memo, held-out comparison table, and + six-tab Streamlit dashboard, all downstream of frozen serialized artifacts. + +## Run contents + +Each completed run includes: + +```text +run_manifest.json # data interval, symbols, artifact map, assumptions +provenance.json # config/input hashes, seed, runtime, Git commit/state +resolved_config.json +data/normalized/ # partitioned Parquet + immutable manifests +quality/summary.json +research/ # full/evaluation frames and exact fold indices +models/ # all predictions and selected held-out predictions +metrics/ # predictive, execution, and sensitivity diagnostics +execution/ # orders, fills, positions, replay state +reports/ # code-generated report, memo, comparison table +dashboard/market_state.parquet +checksums.sha256 +_SUCCESS +``` + +The final L2 bundle uses the same immutable terminal convention but has its own +study inventory: self-contained `authority/` snapshots, per-date/symbol/endpoint +`causal_frames/`, locked `evaluation/`, seven descriptive analyses, partitioned +market-scenario orders/fills/positions plus assumptions and metrics, a +checksummed `report_inputs.json`, and three generated reports. An +`INSUFFICIENT_DATA` terminal retains the exact authorities, any allowable causal +evidence, report snapshot, and failure reports while omitting promoted +evaluation, descriptive, and execution artifacts. The recursive verifier checks +physical inventory, Parquet semantic claims, rendered-report equality, and all +external authorities. Exactly one final marker closes the bundle: `_SUCCESS` +contains `complete\n` for `COMPLETE`, while `INSUFFICIENT_DATA` contains +`terminal\n` for the typed data-availability terminal. + +The semantic run key is derived from the configuration, immutable input identity, +Git commit, the exact tracked/non-ignored source-tree digest, and seed—not +generation timestamps. Reuse additionally requires the current source identity +and caller-retained output manifest/checksum digests to match; an older or +coordinatedly rewritten bundle cannot masquerade as evidence for changed code. + +## Main findings and current evidence + +Replacement-campaign source-freeze snapshot as of 2026-08-09: + +- The latest settled integration gates passed Ruff, formatting, strict mypy, and + the full pytest suite across the data, reconstruction, timing, modeling, + execution, reporting, dashboard, and pipeline boundaries. Exact test/module + counts belong to the dated verification ledger in `STATUS.md`, not to an + empirical claim. +- A fixed public sample for 2024-01-02 downloaded and normalized 10,000 real + aggregate trades: 5,000 each for BTCUSDT and ETHUSDT. The configured cap was + reached for both instruments, so both ranges are explicitly marked incomplete. + The current validators reported zero errors and zero warnings on those rows. +- The generated trade-only report serializes per-symbol paired held-out + model-minus-prior diagnostics without pooling instruments. Exact metrics live + only in the checksum-verified run bundle; they are not manually copied into + this file. +- The single-date, cap-truncated, validation-selected diagnostics do + not authorize a statistical-significance, persistent-alpha, profitability, + or capacity claim. The public bundle records execution and P&L as `NOT_RUN`; + synthetic model/P&L values are never interpreted economically. +- The prospective M8 acquisition, lock-before-open producer, failure bundle, + verifier, and report interfaces are implemented and tested offline. The eight + official archives and their CHECKSUM/metadata evidence are now present in the + verified raw-only authority + `data/m8/_manifests/m8-acquisition.manifest-04d5c01f3810b6a300ec.json` + (SHA-256 `04d5c01f3810b6a300ec0f9317052f254b2bec5d89bc0dfefd18cd71ad6582e6`). + The raw-acquisition phase opened no CSV member. The corrected clean-source + producer then published and verified the canonical + `artifacts/runs/binance-m8-multidate` terminal at commit + `88060613abe211cd8e80a3499678fca830f8ba2d`. It stopped at the declared ETHUSDT + training DQ gate with 53 warnings, before selection, locks, or held-out access; + execution is `NOT_RUN`. The bundle, rather than this summary, is the authority + for its exact status and evidence inventory. +- The live-L2 capture protocol and analysis contract are frozen, and strict + capture, session-verification, input, development-lock, locked-evaluation, + market-scenario, descriptive-analysis, and report components are covered by + offline tests. The superseded v1 evidence is preserved separately; no v2 + Aug 10--13 L2 session existed at this source freeze, so these tracked bytes + contain no v2 book-based empirical result. + +This distinction is the main research conclusion so far: a functioning simulator +is not evidence that a market effect exists. + +## Limitations and next milestone + +Exchange timestamps are not colocated receipt times. Public trades cannot reveal +true queue priority, hidden liquidity, cancellations, or endogenous impact. The +limit-fill mechanism is therefore a scenario proxy, and reported sensitivity is +not deployable capacity. A short crypto interval cannot generalize across dates, +venues, or asset classes; overlapping horizons also reduce effective sample size +and make multiplicity control necessary. + +The trade-only study is closed at its predeclared `INSUFFICIENT_DATA` gate and +must not be rerun with replacement dates or a relaxed warning policy. The next +empirical milestone is the already-frozen prospective, simultaneous +BTCUSDT/ETHUSDT local-L2 study. It requires four declared session terminals, a +single clean campaign source identity, continuous valid observed intervals, an +Aug 10/11 development authority durably published before either held-out session, +and unchanged Aug 12/13 evaluation when that authority is `LOCKED`. A +`NOT_CREATED` authority records why fitting was forbidden, while the declared +held-out captures still proceed and the final producer opens no economic frame. +A failed session remains evidence of insufficiency; no trade-only result can +substitute for book evidence. + +See [the research protocol](docs/RESEARCH_PROTOCOL.md), [data contract](docs/DATA_CONTRACT.md), +[project plan](docs/PROJECT_PLAN.md), [decision log](docs/DECISION_LOG.md), +[L2 analysis contract](docs/M8_L2_ANALYSIS_CONTRACT.md), and +[methodology limitations](reports/methodology_limitations.md) for the exact +contracts and promotion rules. + +## Portfolio material + +The source-controlled report files contain no manually pasted performance +numbers. Run-specific documents are generated from verified bundles. Supporting +communication artifacts are in `portfolio/`: an interview narrative, three +resume-bullet variants, and a ten-minute presentation outline. + +## Public release + +- Project page: +- GitHub source: +- Versioned code and documentation mirror: +- Interactive evidence explorer: +- Publication and data boundaries: [docs/PUBLICATION.md](docs/PUBLICATION.md) and [docs/DATA_POLICY.md](docs/DATA_POLICY.md) + +Licensed under the MIT License. This repository is for research and simulation, +not investment advice or live trading. diff --git a/Microstructure/STATUS.md b/Microstructure/STATUS.md new file mode 100644 index 0000000000000000000000000000000000000000..f2937e62950f35fc00e0238323f7ba000347a672 --- /dev/null +++ b/Microstructure/STATUS.md @@ -0,0 +1,163 @@ +# Status + +Last updated: 2026-08-09 UTC + +> **Replacement-campaign source-freeze snapshot.** This tracked file records the +> state before the v2 four-date L2 campaign. It must not be edited between the +> first Aug 10 capture and the Aug 13 terminal. During that interval, current +> status is authoritative only in `data/m8_l2/campaign_authority.json` and the +> immutable per-session bundles; after the campaign, generated final-run +> provenance is the authority for results. + +## Current evidence + +The portfolio-quality software vertical slice is complete. Its model and +execution output is labeled `SYNTHETIC_SMOKE` and supports only a software +reproducibility claim. + +A credential-free `PUBLIC_SAMPLE_PARTIAL` ingestion and a frozen trade-only +research protocol were also completed for the +fixed 2024-01-02 UTC configuration: 5,000 aggregate trades each for BTCUSDT and +ETHUSDT. Both symbol ranges reached the configured cap and are explicitly +incomplete. The normalized 10,000 rows produced zero current validation errors +and warnings. This supports a bounded data-pipeline observation only—not a market +signal, statistical-significance, profitability, or capacity claim. The public +producer uses per-symbol purged folds and paired model-minus-prior uncertainty; +execution and P&L are explicitly `NOT_RUN` because no contemporaneous book is +present. + +The frozen trade-only M8 study has reached its canonical terminal state. The +raw-only authority binds two exchange-metadata responses, eight official +ZIP/CHECKSUM pairs, and 36 retained artifacts totaling 117,897,562 bytes; every +acquisition entry records `csv_member_opened=false` and +`economic_fields_inspected=false`. The corrected clean-source producer at commit +`88060613abe211cd8e80a3499678fca830f8ba2d` published the checksummed +`artifacts/runs/binance-m8-multidate` bundle with status +`INSUFFICIENT_DATA`. BTCUSDT training normalization completed with 2,071,461 +rows, zero errors, and zero warnings. ETHUSDT training normalization completed +with 987,297 rows, zero errors, and 53 warnings, triggering the predeclared +quality gate. Selection never started; no development lock or prediction was +published; no validation or held-out archive member was opened; execution and +P&L are `NOT_RUN`. No date or policy was replaced. Its report command revalidates +the terminal/raw authority and writes a fresh external report without modifying +the canonical bundle. + +The live-L2 campaign remains the active evidence milestone. The superseded v1 +campaign is preserved, not repaired: Aug 8 is `MISSED_WINDOW`, Aug 9 is a +verified complete session, and its development authority is `NOT_CREATED`. +Before observing any v2 session, the user reset the active prospective calendar +to Aug 10 train, Aug 11 validation, Aug 12 primary test, and Aug 13 replication +test. V1 evidence is not an input to v2. The v2 capture config, protocol, and +analysis authority are separately hash-bound. The campaign-authority mechanism +requires all four dates to share one outcome-blind nonce, canonical output-root +filesystem identity, clean commit/source/import origin, and hashed +Python/platform/production-dependency fingerprint. Strict capture and session +verification, verified lazy inputs, observed-interval endpoint frames, +Aug 10/11 `LOCKED | NOT_CREATED` development authority, no-refit Aug 12/13 evaluation, dependency-aware +diagnostics, market-only scenarios, descriptive analyses, and artifact-driven +L2 reporting are integrated in a tested end-to-end producer and CLI/Make path. +Development and final production have explicit 8 GiB and 12 GiB fail-closed +live-memory envelopes respectively; crossing any admission or post-allocation +bound is a system failure and cannot publish a research terminal. +The atomic final bundle is either `COMPLETE` or `INSUFFICIENT_DATA`; it embeds +exact config/protocol, campaign, session-control, and development authority +snapshots, while its verifier also revalidates every external authority. Reports +are regenerated only into an external directory, leaving the immutable run +untouched. The software path was complete at this remaining-campaign source +freeze; the real v2 session-control evidence was not. No v2 session bundle or +L2 empirical metric existed when these tracked bytes were frozen. + +## Milestones + +| Milestone | Status | Evidence | +| --- | --- | --- | +| M0 Repository contract | Complete | Required files, Python packaging, locked environment, typed configuration and provenance | +| M1 Event data foundation | Complete | Public/synthetic adapters, exact schemas, partitioned Parquet, immutable raw/normalized manifests | +| M2 Book and quality controls | Complete | Gap-safe snapshot/delta replay and non-mutating quality rules covered by tests | +| M3 Leakage-safe dataset | Complete | Causal features, future labels, censoring, continuity isolation, lineage audit | +| M4 Model evaluation | Complete | Purged walk-forward prior/unpenalized/L2/tree ladder with calibration and block bootstrap | +| M5 Execution research | Complete | OOS-only costs, two-stage latency, market/limit partial fills, queue proxy, inventory, liquidation and sensitivity | +| M6 Reproducible vertical slice | Complete | Atomic CLI producer, immutable checksum bundle, deterministic run key, idempotent verification | +| M7 Research communication | Complete | Code-generated report/memo/table, read-only six-tab dashboard, limitations and portfolio material | +| M8 Broader empirical study | In progress | Trade-only branch closed with a canonical `INSUFFICIENT_DATA` terminal; complete frozen L2 software path verified offline; four prospective local-L2 session terminals and the resulting empirical terminal remain required | + +## Verification ledger + +- 2026-08-08: the final L2 session, input, development-lock, total-producer, + recursive-verifier, CLI/Make, and external-report paths passed their focused + offline suites. A consolidated repository gate is run separately before source + freeze; its volatile test count is not hardcoded in this market-evidence file. +- 2026-08-08: every path listed by the canonical trade M8 + `checksums.sha256` reverified. Its manifest/failure/provenance agree on + `INSUFFICIENT_DATA`, the clean source identity above, zero selection, zero + held-out access, and `NOT_RUN` execution. +- 2026-08-07: `make lint` passed across source, tests, and dashboard. +- 2026-08-08: the pre-L2 baseline `make check` passed Ruff, strict mypy across 40 package + modules, all 574 offline tests on Python 3.12.13, and a fresh current-source + synthetic bundle. `ruff format --check` also passed across all 92 Python files. +- 2026-08-07: `make check` passed Ruff, strict mypy, all tests, and a fresh + current-source synthetic bundle produced in an isolated temporary target. +- 2026-08-07: adversarial M8 tests proved that raw acquisition opens no CSV + member, unsafe ZIP metadata is rejected before the standard ZIP parser, both + symbol locks precede the first held-out open, tampered/missing authorities + expose zero held-out rows, and deterministic data failures publish no endpoint. +- 2026-08-08: raw-only M8 acquisition published and independently reverified + `data/m8/_manifests/m8-acquisition.manifest-04d5c01f3810b6a300ec.json` + (SHA-256 `04d5c01f3810b6a300ec0f9317052f254b2bec5d89bc0dfefd18cd71ad6582e6`). + Verification opened no CSV member and found no extra, missing, symlinked, or + unmanifested raw artifact. +- 2026-08-08: the frozen dual-symbol L2 session core and Binance adapter passed + 82 joint tests. A real adapter-produced mock bundle exposed 19 artifacts that + passed strict raw-journal, snapshot, Parquet footer/schema, quality, manifest, + absolute-time, overlap, and 29-gate reconciliation. +- 2026-08-07: pipeline tests independently reproduced two semantically identical + run bundles, verified their checksums, rejected corruption, and preserved an + incomplete target without repair. +- 2026-08-07: `make download-sample` succeeded after network permission was + granted; raw public responses and metadata were manifested and kept outside + Git. `validate-public-data` passed 10,000 normalized rows with zero findings. +- 2026-08-07: clean-commit canonical synthetic and public bundles were produced, + checksum-verified, and independently re-rendered into technical report, IC + memo, and model table. Generated artifacts remain ignored rather than + committed. + +## Empirical claim register + +- Supported: the fixed, capped public REST sample can be acquired, normalized + with exchange-provided scales, content-hashed, partitioned, and validated. +- Exploratory diagnostic: the public producer persists each symbol's selected + model, paired held-out model-minus-prior loss, fixed-block interval and status + in a checksum-protected artifact. Exact metrics are read by generated reports + and are not manually duplicated in this status file; instruments are not + pooled. +- Not supported: confirmatory order-flow predictability, statistical + significance, effect half-life, cross-date/instrument stability, economic + profitability, live fill probability, or deployable capacity. Execution is + `NOT_RUN` for the public trade-only input. +- Inconclusive by design: the full-archive trade M8 hypothesis was not evaluated + because ETHUSDT training data failed the frozen warning gate. The terminal is + evidence of data insufficiency, not evidence that the hypothesis failed. +- Failed/unsupported hypothesis disclosure is generated per symbol for runs + that reach evaluation. The single capped date cannot test persistence or + book/liquidity hypotheses, and synthetic output cannot evaluate a market + hypothesis. + +## Next evidence sequence + +Retain the canonical trade-only `INSUFFICIENT_DATA` bundle and its source-tagged +predecessor unchanged; do not relax the warning gate, replace a date, or rerun +until a favorable outcome appears. Use the completed L2 producer and explicit +authority interfaces with ignored targets +`artifacts/runs/binance-m8-l2-development-lock` and +`artifacts/runs/binance-m8-live-l2` for the development authority and final run, +respectively. Then capture the exact simultaneous Aug 10--13 BTCUSDT/ETHUSDT +sessions under one new clean v2 campaign authority. After Aug 11, durably publish +either the fitted `LOCKED` authority or the control-only `NOT_CREATED` authority +before Aug 12. A valid `NOT_CREATED` result exits 1 but does not cancel the Aug +12/13 captures; the final producer uses all four control authorities without +opening economic frames. After Aug 13, produce and recursively verify the immutable +final bundle, render reports externally, measure peak RSS, and complete the +clean-room/resource audit. A failed/missed date terminalizes the declared +campaign rather than selecting a substitute. The +frozen facts are in `docs/M8_L2_ANALYSIS_CONTRACT.md`; generated bundles remain +the only authority for any eventual metrics. diff --git a/Microstructure/configs/exploratory_aggtrades_2026-08-05_08.toml b/Microstructure/configs/exploratory_aggtrades_2026-08-05_08.toml new file mode 100644 index 0000000000000000000000000000000000000000..242d9a751b884b53d592fe4d4d57dba67388852a --- /dev/null +++ b/Microstructure/configs/exploratory_aggtrades_2026-08-05_08.toml @@ -0,0 +1,58 @@ +[study] +name = "binance-aggtrades-2026-08-05-08-exploratory" +protocol_version = "1.0.0" +evidence_tier = "PUBLIC_ARCHIVE_EXPLORATORY" +seed = 20260809 +source = "binance_spot_daily_aggtrades_archive" +symbols = ["BTCUSDT", "ETHUSDT"] +selection_metric = "log_loss" +target = "future_trade_up" +label_horizon_events = 20 +calibration_fraction = 0.20 +bootstrap_samples = 2000 +bootstrap_block_events = 40 +feature_stability_bins = 10 +max_archive_compressed_bytes = 268435456 +max_archive_uncompressed_bytes = 2147483648 +max_total_download_bytes = 8589934592 + +[[periods]] +date = "2026-08-05" +role = "train" + +[[periods]] +date = "2026-08-06" +role = "validation" + +[[periods]] +date = "2026-08-07" +role = "primary_test" + +[[periods]] +date = "2026-08-08" +role = "replication_test" + +[features] +trade_windows = [5, 20, 100] +volatility_window = 100 +intensity_window = 50 +large_trade_quantile = 0.95 + +[models] +logistic_c_values = [0.1, 1.0, 10.0] +tree_max_depth_values = [2, 4, 6] +tree_min_samples_leaf = 40 + +[quality] +fail_on_error = true +require_complete_daily_archive = true +require_contiguous_trade_ids_within_symbol_date = true +require_nondecreasing_event_time = true +allow_quality_warnings = true + +[claims] +allow_p_values = false +allow_significance_claim = false +allow_cross_instrument_pooling = false +allow_execution_claim = false +allow_profitability_claim = false diff --git a/Microstructure/configs/m8_l2_analysis.toml b/Microstructure/configs/m8_l2_analysis.toml new file mode 100644 index 0000000000000000000000000000000000000000..3651a6d88312e4f4b9f6977d875645807c821225 --- /dev/null +++ b/Microstructure/configs/m8_l2_analysis.toml @@ -0,0 +1,100 @@ +[study] +name = "binance-m8-live-l2-analysis-v2" +protocol_version = "2.0.0" +seed = 20260807 +source = "verified_m8_l2_session_bundles" +capture_config_source_sha256 = "b1bf3b4e2820e24e4555bfeb9cb0957f9a0bcdef62039f7d92360e0a97d0dd39" +capture_protocol_sha256 = "4c77a2099a4cabd049d10e0f8264d3b4c66704d8e87cbaf0c817fd085f4bbd83" +symbols = ["BTCUSDT", "ETHUSDT"] +training_role = "train" +selection_role = "validation" +primary_endpoint_role = "primary_test" +replication_endpoint_role = "replication_test" + +[features] +decision_scope = "per_symbol_verified_observed_intervals" +flat_direction_policy = "flat_is_non_up" +rolling_windows = [20, 100] +volatility_window = 100 +model_feature_columns = ["spread_bps", "depth_total_l1", "depth_total_l5", "depth_total_l10", "queue_imbalance_l1", "queue_imbalance_l5", "queue_imbalance_l10", "microprice_deviation_bps", "ofi_l1", "ofi_w20", "ofi_w100", "cancellation_intensity_w20", "cancellation_intensity_w100", "realized_volatility_w20", "realized_volatility_w100", "volatility_regime_low", "volatility_regime_high", "liquidity_regime_liquid", "liquidity_regime_stressed"] +clock_max_state_age_ms = 500 +clock_target_policy = "exact_target_locf_same_valid_observed_interval" +clock_label_information_end = "exact_target" +clock_record_target_sequence = true +clock_censor_if_no_eligible_state = true + +[[endpoints]] +name = "event_20" +domain = "event" +horizon_value = 20 +unit = "events" +paired_block_width = 40 +paired_block_unit = "events" +nominal_event_block_width = 40 + +[[endpoints]] +name = "event_100" +domain = "event" +horizon_value = 100 +unit = "events" +paired_block_width = 200 +paired_block_unit = "events" +nominal_event_block_width = 200 + +[[endpoints]] +name = "clock_1000ms" +domain = "clock" +horizon_value = 1000 +unit = "milliseconds" +paired_block_width = 2000 +paired_block_unit = "milliseconds" +nominal_event_block_width = 20 + +[[endpoints]] +name = "clock_5000ms" +domain = "clock" +horizon_value = 5000 +unit = "milliseconds" +paired_block_width = 10000 +paired_block_unit = "milliseconds" +nominal_event_block_width = 100 + +[regimes] +fit_role = "train" +feature = "realized_volatility_w100" +quantile_numerators = [1, 2] +quantile_denominator = 3 + +[calibration] +bins = 10 + +[bootstrap] +method = "paired_moving_block" +samples = 2000 + +[signed_impact] +metric = "ofi_signed_future_mid_markout" +side_rule = "sign_of_horizon_matched_ofi" +price_rule = "ofi_sign_times_future_log_mid_return_bps" + +[execution] +market_orders_only = true +probability_threshold = 0.55 +symmetric_probability_thresholds = true +order_notional_usd = 100.0 +max_l1_participation = 0.10 +inventory_order_multiples = 10 +reference_price_fit_role = "train" +reference_depth_fit_role = "train" +reference_price_statistic = "train_median_mid_price" +reference_depth_statistic = "train_q05_min_bid_ask_l1_depth" +reference_quantity_policy = "min_100usd_and_10pct_train_q05_l1_depth_rounded_down_to_lot" +l1_fill_policy = "fill_up_to_recorded_l1_depth_cancel_remainder" +scenario_reset_policy = "per_symbol_session_endpoint_latency_pair" +extra_slippage_bps = 0.0 +liquidate_at_end = true + +[claims] +allow_capacity_claim = false +allow_realized_execution_claim = false +allow_profitability_claim = false diff --git a/Microstructure/configs/m8_l2_capture_study.toml b/Microstructure/configs/m8_l2_capture_study.toml new file mode 100644 index 0000000000000000000000000000000000000000..e5e2a131d7e204a23765a660ed00f1d6b4b8b32e --- /dev/null +++ b/Microstructure/configs/m8_l2_capture_study.toml @@ -0,0 +1,81 @@ +[study] +name = "binance-m8-live-l2-study-v2" +protocol_version = "2.0.0" +evidence_tier = "FULL_DATA" +seed = 20260807 +source = "binance_spot_live_diff_depth_100ms" +symbols = ["BTCUSDT", "ETHUSDT"] +stream_interval_ms = 100 + +[[sessions]] +date = "2026-08-10" +start_utc = "14:00:00" +end_utc = "15:00:00" +role = "train" + +[[sessions]] +date = "2026-08-11" +start_utc = "14:00:00" +end_utc = "15:00:00" +role = "validation" + +[[sessions]] +date = "2026-08-12" +start_utc = "14:00:00" +end_utc = "15:00:00" +role = "primary_test" + +[[sessions]] +date = "2026-08-13" +start_utc = "14:00:00" +end_utc = "15:00:00" +role = "replication_test" + +[capture] +duration_seconds = 3600 +max_messages_per_symbol = 60000 +max_raw_frame_bytes = 1048576 +max_arrow_batch_bytes = 16777216 +min_overlapping_coverage_seconds = 3300 +min_single_continuity_epoch_seconds = 1800 +require_complete_status = true +require_live_reconstruction = true +max_sequence_gaps = 0 +max_quality_errors = 0 +max_quality_warnings = 0 + +[features] +depth_levels = [1, 5, 10] +event_horizons = [20, 100] +clock_horizons_ms = [1000, 5000] +include_spread = true +include_depth = true +include_ofi = true +include_queue_imbalance = true +include_microprice = true +include_cancellation_intensity = true +include_realized_volatility = true +include_reference_fit_regimes = true + +[models] +selection_metric = "log_loss" +logistic_c_values = [0.1, 1.0, 10.0] +tree_max_depth_values = [2, 4, 6] +tree_min_samples_leaf = 40 +calibration_fraction = 0.20 +bootstrap_samples = 2000 + +[execution] +market_orders_only = true +taker_fee_bps = 4.0 +decision_latency_events = [0, 1, 5] +order_latency_events = [0, 1, 5] +liquidate_at_end = true +allow_limit_fill_claim = false +allow_capacity_claim = false + +[claims] +allow_p_values = false +allow_significance_claim = false +allow_realized_execution_claim = false +allow_profitability_claim = false diff --git a/Microstructure/configs/m8_multidate_trade_study.toml b/Microstructure/configs/m8_multidate_trade_study.toml new file mode 100644 index 0000000000000000000000000000000000000000..57bec1a0136ebae622e867ad3df144a537b49cc2 --- /dev/null +++ b/Microstructure/configs/m8_multidate_trade_study.toml @@ -0,0 +1,58 @@ +[study] +name = "binance-m8-multidate-trades" +protocol_version = "1.0.2" +evidence_tier = "FULL_DATA" +seed = 20260807 +source = "binance_spot_daily_aggtrades_archive" +symbols = ["BTCUSDT", "ETHUSDT"] +selection_metric = "log_loss" +target = "future_trade_up" +label_horizon_events = 20 +calibration_fraction = 0.20 +bootstrap_samples = 2000 +bootstrap_block_events = 40 +feature_stability_bins = 10 +max_archive_compressed_bytes = 268435456 +max_archive_uncompressed_bytes = 2147483648 +max_total_download_bytes = 8589934592 + +[[periods]] +date = "2024-01-03" +role = "train" + +[[periods]] +date = "2024-01-04" +role = "validation" + +[[periods]] +date = "2024-01-05" +role = "primary_test" + +[[periods]] +date = "2024-01-06" +role = "replication_test" + +[features] +trade_windows = [5, 20, 100] +volatility_window = 100 +intensity_window = 50 +large_trade_quantile = 0.95 + +[models] +logistic_c_values = [0.1, 1.0, 10.0] +tree_max_depth_values = [2, 4, 6] +tree_min_samples_leaf = 40 + +[quality] +fail_on_error = true +require_complete_daily_archive = true +require_contiguous_trade_ids_within_symbol_date = true +require_nondecreasing_event_time = true +allow_quality_warnings = false + +[claims] +allow_p_values = false +allow_significance_claim = false +allow_cross_instrument_pooling = false +allow_execution_claim = false +allow_profitability_claim = false diff --git a/Microstructure/configs/public_sample.toml b/Microstructure/configs/public_sample.toml new file mode 100644 index 0000000000000000000000000000000000000000..8c7fc3323196ac098e1fbded0a9130a0059eb8d7 --- /dev/null +++ b/Microstructure/configs/public_sample.toml @@ -0,0 +1,63 @@ +[run] +name = "binance-public-sample" +evidence_tier = "PUBLIC_SAMPLE_PARTIAL" +seed = 20260807 + +[data] +mode = "binance_rest" +source = "binance_spot_rest" +symbols = ["BTCUSDT", "ETHUSDT"] +start = "2024-01-02T00:00:00Z" +end = "2024-01-02T00:10:00Z" +max_events_per_symbol = 5000 +raw_root = "data/raw" +partition_root = "data/normalized" +schema_version = "1.0.0" +base_url = "https://data-api.binance.vision" +request_limit = 1000 +timeout_seconds = 30.0 +max_retries = 5 + +[quality] +max_spread_bps = 100.0 +max_silence_ms = 5000 +fail_on_error = true + +[features] +trade_windows = [5, 20, 100] +volatility_window = 100 +intensity_window = 50 +label_horizon_events = 20 +large_trade_quantile = 0.95 + +[evaluation] +min_train_events = 1200 +validation_events = 400 +test_events = 400 +step_events = 400 +embargo_events = 20 +bootstrap_samples = 500 +calibration_bins = 10 + +[models] +selection_metric = "log_loss" +logistic_c_values = [0.1, 1.0, 10.0] +tree_max_depth_values = [2, 4, 6] +tree_min_samples_leaf = 40 + +[execution] +decision_latency_events = 1 +order_latency_events = 1 +maker_fee_bps = 1.0 +taker_fee_bps = 4.0 +half_spread_bps = 1.0 +slippage_bps_per_unit = 0.20 +signal_threshold = 0.56 +max_position_units = 3.0 +order_size_units = 1.0 +limit_fill_base_probability = 0.55 +queue_ahead_units = 2.0 +limit_max_age_events = 20 +cancel_latency_events = 1 +liquidate_at_end = true +capacity_multipliers = [0.5, 1.0, 2.0, 4.0] diff --git a/Microstructure/configs/smoke.toml b/Microstructure/configs/smoke.toml new file mode 100644 index 0000000000000000000000000000000000000000..b2f1018384ff34e78302ebc053a33c4693888e09 --- /dev/null +++ b/Microstructure/configs/smoke.toml @@ -0,0 +1,57 @@ +[run] +name = "sample-smoke" +evidence_tier = "SYNTHETIC_SMOKE" +seed = 20260807 + +[data] +mode = "synthetic" +source = "synthetic_v1" +symbols = ["BTCUSDT", "ETHUSDT"] +start = "2024-01-02T00:00:00Z" +events_per_symbol = 3600 +partition_root = "data/normalized" +schema_version = "1.0.0" + +[quality] +max_spread_bps = 100.0 +max_silence_ms = 5000 +fail_on_error = true + +[features] +trade_windows = [5, 20, 100] +volatility_window = 100 +intensity_window = 50 +label_horizon_events = 20 +large_trade_quantile = 0.95 + +[evaluation] +min_train_events = 1200 +validation_events = 400 +test_events = 400 +step_events = 400 +embargo_events = 20 +bootstrap_samples = 200 +calibration_bins = 10 + +[models] +selection_metric = "log_loss" +logistic_c_values = [0.1, 1.0, 10.0] +tree_max_depth_values = [2, 4, 6] +tree_min_samples_leaf = 40 + +[execution] +decision_latency_events = 1 +order_latency_events = 1 +maker_fee_bps = 1.0 +taker_fee_bps = 4.0 +half_spread_bps = 1.0 +slippage_bps_per_unit = 0.20 +signal_threshold = 0.56 +max_position_units = 3.0 +order_size_units = 1.0 +limit_fill_base_probability = 0.55 +queue_ahead_units = 2.0 +limit_max_age_events = 20 +cancel_latency_events = 1 +liquidate_at_end = true +capacity_multipliers = [0.5, 1.0, 2.0, 4.0] diff --git a/Microstructure/dashboard/app.py b/Microstructure/dashboard/app.py new file mode 100644 index 0000000000000000000000000000000000000000..87b91ebf15333d423d2f3a6f685d43a56a65cee1 --- /dev/null +++ b/Microstructure/dashboard/app.py @@ -0,0 +1,189 @@ +"""Read-only Streamlit dashboard for a completed microstructure run bundle.""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +from collections.abc import Mapping, Sequence +from pathlib import Path +from typing import Any + +import streamlit as st + +from microstructure.provenance import sha256_file +from microstructure.reporting import RunBundle, RunBundleError, load_run_bundle + +PROJECT_ROOT = Path(__file__).resolve().parents[1] +DEFAULT_RUN_DIR = PROJECT_ROOT / "artifacts" / "runs" / "sample-smoke" + + +def _argument_run_dir(arguments: Sequence[str]) -> Path: + parser = argparse.ArgumentParser(add_help=False) + parser.add_argument("--run-dir") + parsed, _ = parser.parse_known_args(arguments) + configured = parsed.run_dir or os.environ.get("MICROSTRUCTURE_RUN_DIR") + return Path(configured).expanduser() if configured else DEFAULT_RUN_DIR + + +def _integrity_key(run_dir: Path) -> str: + checksum_path = run_dir / "checksums.sha256" + return sha256_file(checksum_path) if checksum_path.is_file() else "missing" + + +@st.cache_resource(show_spinner=False) +def _cached_bundle(run_dir: str, integrity_key: str) -> RunBundle: + del integrity_key # It is part of Streamlit's cache key. + return load_run_bundle(run_dir) + + +def _rows(rows: Sequence[Mapping[str, Any]]) -> list[dict[str, Any]]: + return [dict(row) for row in rows] + + +def _show_rows(rows: Sequence[Mapping[str, Any]], empty_message: str) -> None: + if rows: + st.dataframe(_rows(rows), hide_index=True) + else: + st.info(empty_message) + + +def _show_overview(bundle: RunBundle) -> None: + st.subheader("Evidence and lineage") + columns = st.columns(4) + columns[0].metric("Run", bundle.run_id) + columns[1].metric("Evidence", bundle.evidence_tier) + columns[2].metric("Symbols", len(bundle.symbols)) + columns[3].metric( + "Git state", + "dirty" if bool(cast_mapping(bundle.provenance.get("git")).get("dirty")) else "clean", + ) + st.markdown( + f"**Observed UTC period:** `{bundle.observed_start_utc}` → `{bundle.observed_end_utc}`" + ) + st.markdown(f"**Instruments:** {', '.join(bundle.symbols)}") + st.caption( + "The dashboard reads serialized artifacts only. It does not download data, " + "train models, or simulate orders." + ) + + +def cast_mapping(value: Any) -> Mapping[str, Any]: + return value if isinstance(value, Mapping) else {} + + +def _show_quality(bundle: RunBundle) -> None: + st.subheader("Non-mutating validation findings") + if bundle.quality: + st.json(dict(bundle.quality), expanded=True) + else: + st.info("No quality summary was serialized in this completed run bundle.") + st.caption("Findings are displayed as recorded; this app does not repair observations.") + + +def _show_market_state(bundle: RunBundle) -> None: + st.subheader("Market-state aggregates") + _show_rows( + bundle.market_state, + "No dashboard-safe market-state aggregate was serialized for this run.", + ) + st.caption( + "Only bounded aggregates are loaded here; the dashboard never scans external raw data." + ) + + +def _show_predictions(bundle: RunBundle) -> None: + st.subheader("Serialized predictive diagnostics") + _show_rows( + bundle.predictive_metrics, + "No predictive metric rows were serialized for this run.", + ) + st.caption( + "Predictive metrics do not establish fillability or performance after execution costs." + ) + + +def _show_execution(bundle: RunBundle) -> None: + st.subheader("Serialized simulated performance") + _show_rows( + bundle.execution_metrics, + "No execution or simulated-performance rows were serialized for this run.", + ) + st.markdown("#### Execution sensitivity grid") + _show_rows( + bundle.execution_sensitivity, + "No execution-sensitivity rows were serialized for this run.", + ) + assumptions = bundle.manifest.get("execution_assumptions") + if isinstance(assumptions, Mapping) and assumptions: + st.markdown("#### Recorded execution assumptions") + st.json(dict(assumptions), expanded=False) + st.caption( + "Fees, latency, fills, adverse selection, inventory, and liquidation are model " + "assumptions—not realized trading outcomes." + ) + + +def _show_reproducibility(bundle: RunBundle) -> None: + st.subheader("Frozen provenance") + st.markdown(f"**Run directory:** `{bundle.root}`") + st.markdown(f"**Configuration SHA-256:** `{bundle.provenance.get('config_sha256', 'N/A')}`") + st.markdown("#### Run manifest") + st.code(json.dumps(bundle.manifest, indent=2, sort_keys=True), language="json") + st.markdown("#### Provenance") + st.code(json.dumps(bundle.provenance, indent=2, sort_keys=True), language="json") + st.caption( + "The completion marker and checksum manifest were verified before these values loaded." + ) + + +def render_dashboard(bundle: RunBundle) -> None: + """Render a verified bundle without changing it.""" + st.title("Order Flow to Price Impact") + if bundle.evidence_tier in {"SYNTHETIC_SMOKE", "PUBLIC_SAMPLE_PARTIAL"}: + st.warning(bundle.watermark) + else: + st.info(bundle.watermark) + + labels = ( + "Overview", + "Data Quality", + "Market State", + "Predictions", + "Simulated Performance", + "Reproducibility & Limitations", + ) + tabs = st.tabs(labels) + with tabs[0]: + _show_overview(bundle) + with tabs[1]: + _show_quality(bundle) + with tabs[2]: + _show_market_state(bundle) + with tabs[3]: + _show_predictions(bundle) + with tabs[4]: + _show_execution(bundle) + with tabs[5]: + _show_reproducibility(bundle) + + +def main(arguments: Sequence[str] | None = None) -> None: + st.set_page_config(page_title="Microstructure Research", layout="wide") + run_dir = _argument_run_dir(sys.argv[1:] if arguments is None else arguments).resolve() + try: + bundle = _cached_bundle(str(run_dir), _integrity_key(run_dir)) + except RunBundleError as error: + st.title("Order Flow to Price Impact") + st.error(f"Run bundle is incomplete or invalid: {error}") + st.caption( + "Select a directory containing run_manifest.json, provenance.json, " + "checksums.sha256, and the final _SUCCESS marker." + ) + st.stop() + render_dashboard(bundle) + + +if __name__ == "__main__": + main() diff --git a/Microstructure/data/_ingestion_manifests/.gitkeep b/Microstructure/data/_ingestion_manifests/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Microstructure/data/_ingestion_manifests/.gitkeep @@ -0,0 +1 @@ + diff --git a/Microstructure/data/derived/.gitkeep b/Microstructure/data/derived/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Microstructure/data/derived/.gitkeep @@ -0,0 +1 @@ + diff --git a/Microstructure/data/models/.gitkeep b/Microstructure/data/models/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Microstructure/data/models/.gitkeep @@ -0,0 +1 @@ + diff --git a/Microstructure/data/normalized/.gitkeep b/Microstructure/data/normalized/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Microstructure/data/normalized/.gitkeep @@ -0,0 +1 @@ + diff --git a/Microstructure/data/quality/.gitkeep b/Microstructure/data/quality/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Microstructure/data/quality/.gitkeep @@ -0,0 +1 @@ + diff --git a/Microstructure/docs/DATA_CONTRACT.md b/Microstructure/docs/DATA_CONTRACT.md new file mode 100644 index 0000000000000000000000000000000000000000..b0223e1e27efa272515ccc7c96dc51f0eebd7354 --- /dev/null +++ b/Microstructure/docs/DATA_CONTRACT.md @@ -0,0 +1,269 @@ +# Data contract and lineage + +## Scope + +The normalized layer separates exchange-specific acquisition from research +logic. An adapter may add a new venue, but it must produce the same versioned +event contracts, preserve original bytes, and declare how observation time is +approximated. No normalized table is evidence that an event was available to a +real colocated strategy unless local receipt time was actually captured. + +Current schema version: `1.0.0`. + +## Clocks and ordering + +All timestamps are signed UTC epoch nanoseconds: + +- `event_ts_ns`: timestamp supplied by the market-data source; +- `received_ts_ns`: local wall-clock receipt when captured live, otherwise null; +- `available_ts_ns`: earliest time the pipeline permits the row to enter an + information set; +- `availability_basis`: explicit reason, such as `local_receive_time`, + `exchange_event_time_proxy`, or `synthetic_receipt`; +- `capture_seq`: local arrival ordering when a collector supplies it; +- `continuity_id`: a feed epoch that cannot be crossed by rolling features, + labels, open orders, or markouts. + +Within a continuous book epoch, sequence IDs—not exchange timestamps—are the +authoritative reconstruction order. Research ordering is stable on availability +time, sequence/capture order, and event identity. Separate trade and book streams +with equal timestamps have no assumed common ordering, so cross-stream joins are +strictly prior unless a future source proves a shared sequence. + +## Exact numerical representation + +Adapters retain integer `price_ticks`/`quantity_lots` and the corresponding +`tick_size`/`lot_size`. Floating `price` and `quantity` columns are convenience +units and must agree with the exact representation. Binance symbol scales come +from public `exchangeInfo` filters for each download; fixed `1e-8` scale defaults +exist only as explicit low-level fallbacks and are not the configured sample +path. + +Derived ratios, log returns, volatility, probabilities, and P&L use `Float64` +with their units named or documented. Execution quantities are rounded down to +the observable lot size; slippage-adjusted prices round adversely to the tick. + +## Normalized tables + +### Trades + +Identity is `(venue, symbol, trade_id)`. Required economic fields include exact +and floating price/quantity, quote quantity, first/last constituent trade IDs, +buyer-maker flag, normalized aggressor side, timestamps, and source artifact ID. +A `buy` aggressor lifts the ask; a `sell` aggressor hits the bid. + +### Depth deltas + +Each event contains `first_update_id`, `last_update_id`, optional previous update +ID, and bid/ask lists of exact `(price_ticks, quantity_lots)` changes. Quantity +zero is a delete instruction; a negative quantity is invalid. + +### Book snapshots + +A snapshot carries its request/receipt/availability times, last update ID, +depth limit, exact levels, scale metadata, source artifact ID, and a new +continuity ID. Binance REST snapshots do not provide an exchange event timestamp; +the local receipt time is the anchor availability time. + +### Book observations + +Reconstruction emits best bid/ask, L1 quantities, cumulative depth at 1/5/10 +levels, spread, mid, microprice, queue imbalance, sequence range, validity flag, +and full lineage. A crossed/locked or emptied book terminates the epoch rather +than being silently repaired. + +### Sequence gaps + +A gap row records expected and observed ranges, the missing inclusive range, +detection time, continuity ID, source artifact, and reason. After a forward gap, +the book is not live again until a new snapshot starts a new epoch. + +## Binance acquisition semantics + +The configured historical adapter uses only credential-free public market-data +REST endpoints. It starts aggregate-trade pagination with a fixed UTC interval, +then advances by aggregate trade ID so trades sharing a timestamp are not lost. +HTTP 408/418/429/5xx, connection failures, and recoverable interruptions while +streaming an HTTP 200 body use bounded exponential backoff; `Retry-After` is +honored for rate-limit responses. Response bodies have a byte ceiling. Every +accepted exact body is content-addressed and manifested before normalization; +an interrupted or oversized response preserves a bounded rejected prefix and an +explicit rejection sidecar before retry/failure. + +The optional live collector uses the market-data-only WebSocket endpoint and +diff-depth `U/u` updates. A correct local book buffers updates, fetches a public +snapshot, discards stale events, requires the first usable event to cover +`lastUpdateId + 1`, and then validates continuity for every event. Reconnection +starts a new continuity epoch. These rules follow Binance's official +[Spot WebSocket stream guide](https://developers.binance.com/en/docs/catalog/core-trading-spot-trading/api/ws-streams/~). +Public REST behavior and rate-limit headers are described in the official +[Spot REST documentation](https://developers.binance.com/en/docs/products/spot/rest-api). + +Live capture persists each WebSocket frame before UTF-8/JSON parsing in a typed +base64 journal containing exact bytes, local receipt time, capture sequence and +continuity epoch. Each reconnect snapshot's raw body and sidecar are journaled as +an anchor. A frame above 1 MiB fails only after its evidence is preserved; +normalized Arrow spools flush before an estimated 16 MiB batch ceiling. A +capture-ID-scoped normalized root produces one streaming Parquet descriptor per +nonempty table, and a capture-ID completion summary is atomically published +last. The fixed summary name is only a latest-pointer, never the sole completion +record. Historical REST output retains the date-partition layout described +below. + +Every historical download requires a finite per-symbol event cap, but that cap +is not treated as a RAM budget. The default path lazily yields at most one REST +page per Arrow batch, updates exact disk-backed quality state, and feeds the +Parquet writer once. Eager compatibility materialization has a separate hard +row guard. A `ConfiguredDataAdapter` protocol/registry is the normalized +extension boundary for later venues or institutional sources; its mode must +match the resolved configuration before dispatch. + +### Daily-archive acquisition boundary + +A daily-archive acquisition object authenticates raw transport evidence; it is +not a normalized-data object. Acquisition may hash exact bodies, authenticate +the official `CHECKSUM`, and inspect bounded ZIP +end-of-central-directory/central-directory metadata for member name, count, and +declared compressed/expanded sizes. It must not open or extract the CSV member, +read decompressed member bytes, parse a header or row, expose economic fields, +or compute row/ID/timestamp coverage. The first decompressed member byte is the +economic-data-open boundary, and the archive API must expose a fail-closed guard +immediately before that byte can be read. + +For the prospective M8 study, all declared ZIP, `CHECKSUM`, and exchange-metadata +responses are acquired and placed in an immutable raw acquisition manifest +before any member is opened. Only train and validation members are then +stream-normalized and quality-checked. Their immutable development normalized +manifest is an input to selection. One per-symbol analysis lock and an aggregate +lock committing both child-lock hashes are closed and `fsync`ed, along with +their digest files and containing directories. Each child lock binds the +selected specification, development-frame identity, feature order, imputer and +scaler parameters, selected-estimator state, independent historical-prior state, +calibration state, fit cutoffs, and the canonical numeric fitted-state SHA-256. +Those states are fit on development data and durably closed before held-out +member access. The aggregate lock binds the +protocol/config, raw acquisition manifest, development normalized manifest, and +clean real Git revision. Every primary/replication member-open guard must +re-read and re-hash that exact durable lock before allowing decompression. Test +normalization may construct held-out features, but prediction restores the +locked numeric state; evaluation cannot reselect, fit, refit, recalibrate, or +update it. + +Declared-object 404/410 responses, invalid exchange-metadata semantics, official +`CHECKSUM` or ZIP structural violations, frozen per-response size violations, +and retained-evidence budget exhaustion are typed deterministic insufficiency +and publish an immutable raw-only `INSUFFICIENT_DATA` authority. Retry exhaustion, +connection interruption, permission/local-I/O errors, collisions, and program +faults remain nonterminal system failures so they cannot masquerade as a market +or data result. + +The M8 byte limits have distinct meanings. The compressed ceiling applies to +each archive response while streaming. The expanded ceiling applies to both the +declared and actually streamed bytes of each CSV member. The total-download +ceiling is the hard sum of immutable raw-response evidence retained for the +study: ZIP bodies, official `CHECKSUM` bodies, every response sidecar, +`exchangeInfo` bodies and sidecars, and all retained rejected-response prefixes +and rejection sidecars. Retried attempts still consume the total. A physically +retained content-addressed file is counted once even if referenced more than +once; separate retained copies are counted separately. Normalized Parquet, +quality outputs, and derived aggregate indexes are outside this raw-evidence +sum. Type-specific bounded `CHECKSUM`, metadata, and rejection responses remain +subject to the same total. Accounting is enforced while bytes are retained, not +after all downloads finish, and the raw acquisition manifest records every +accepted/rejected artifact and the final exact total. + +If held-out normalization, continuity/completeness validation, or quality fails +after lock durability, the run publishes an atomic, checksum-protected, +immutable `INSUFFICIENT_DATA` terminal artifact under the same run identity. It +binds the raw and development manifests, per-symbol and aggregate locks, clean +Git identity, typed failure, partial-evidence hashes, and unopened remainder; +it contains no endpoint result. That identity may subsequently verify/reuse the +failure but may not overwrite it, return to selection, substitute inputs, or +publish a partial successful bundle. A source change creates a new clean Git +identity rather than rewriting prior evidence. + +## Storage and manifests + +Normalized Parquet is content-addressed and partitioned beneath: + +```text +//schema-/venue-/symbol-/date-YYYY-MM-DD/ +``` + +Writers reject oversized input batches before row conversion and consume +bounded Arrow record batches; they do not require all event rows in memory. +Each part has an immutable sidecar with source URI, download/creation +time, requested and observed ranges, row/byte counts, schema version, +transformations, input checksum, write ordinal, and Parquet checksum. A dataset +manifest lists all parts, sidecars, hashes, row counts, observed bounds and write +order. Validation checks those bytes before scanning rows. Run bundles snapshot +these manifest hashes and protect every included file with `checksums.sha256`. + +Each config-driven ingestion also writes a content-named immutable ingestion +manifest linking only the exact raw responses used by that invocation to the +normalized dataset manifests. It records the row cap and each symbol's +`complete_range` state, so capped coverage cannot survive merely as terminal +output or be mistaken for the entire requested interval. Quality reports and +full findings JSONL are atomically published under per-run names and their +SHA-256/byte counts are bound into the same ingestion manifest. + +The public research reader verifies metadata, URI/symbol semantics, exact raw +record membership, inverse raw-to-normalized coverage, scales, parts and +sidecars before exposing rows. Its batch API performs physical-order incremental +quality checks while a single upstream Arrow stream is staged through a +memory-limited, spill-capable DuckDB canonical sort. The legacy eager reader has +an independent finite materialization guard checked before any Parquet row read. + +For M8 specifically, the raw acquisition manifest and normalized manifests are +different immutable stages and must not be collapsed into one post hoc record. +A self-contained run preserves the acquisition authority as an exact raw-only +copy below `data/input`; normalization, Parquet, and DQ evidence live separately +below `data/normalized_input`. The final all-date manifest is rooted at `data` +so it may bind both trees without making derived artifacts members of the raw +authority. A failed run inventories every pre-terminal regular file, binds any +completed and failed normalization evidence, and applies the same verifier both +before and after atomic publication. +A successful final bundle binds the raw acquisition manifest, final normalized +manifest for all eight declared symbol/dates, official `CHECKSUM` and metadata +bodies plus their sidecars, per-symbol and aggregate lock hashes, and the clean +real Git revision. Verification rejects a dirty, unborn, synthetic, or changed +source identity and rechecks all bound artifact bytes before reuse. + +External raw and normalized data are ignored by Git. Small deterministic test +fixtures may be committed only under tests and must state whether they are +synthetic or sampled public observations. + +### Frozen dual-symbol live-L2 session authority + +Each prospective L2 date uses one absolute UTC start/end barrier and one +cross-symbol authority for BTCUSDT and ETHUSDT. The two single-symbol producers +run concurrently and preserve raw frames before parsing. Coverage is computed +only from intervals backed by consecutive `OBSERVED` reconstructed book states; +raw socket first/last span, stale updates, excluded messages, gaps, and silent +holes do not create coverage. The session gate uses the exact union/intersection +of those intervals, requires one sufficiently long valid continuity epoch, +reconciles raw/normalized/reconstructed/excluded rows and snapshot anchors, and +enforces the frozen gap, error, warning, frame-byte, and Arrow-batch limits. + +All per-symbol raw journals, snapshots, normalized data, manifests, quality +reports, and capture summaries must form an exhaustive regular-file inventory. +A passing dual-symbol session is published atomically with checksums and exact +`_SUCCESS` bytes; a typed capture/gate failure publishes an immutable +`INSUFFICIENT_DATA` authority. Permission, local-I/O, source/config/protocol +drift, or program faults retain nonterminal raw evidence but may not publish a +research terminal. Neither terminal authorizes live trading. + +## Quality policy + +Validators never sort, deduplicate, clip, interpolate, or rewrite observations. +They emit typed findings for duplicate trades, timestamp/order reversals, +availability/receipt contradictions, sequence gaps or stale updates, crossed +books, invalid price/quantity, scale mismatches, abnormal spread, nonmonotone +depth, long silence, and receipt-clock reversal. A downstream research view may +exclude a row, but it must preserve the normalized source and report the +exclusion count/reason. + +Incremental validators retain only a bounded in-memory finding preview; exact +duplicate/clock/sequence state spills to SQLite and complete findings stream to +JSONL. A failed validation closes and removes only its temporary sink, leaving +any previously published evidence untouched. diff --git a/Microstructure/docs/DATA_POLICY.md b/Microstructure/docs/DATA_POLICY.md new file mode 100644 index 0000000000000000000000000000000000000000..27c9e3a7c0be7a9425fcbe61b3c53e889a9c77da --- /dev/null +++ b/Microstructure/docs/DATA_POLICY.md @@ -0,0 +1,45 @@ +# Data policy + +## Public repository boundary + +The public repository and its Hugging Face mirror contain only Git-tracked +source code, configuration, tests, documentation, and small placeholder files. +They do not contain exchange observations or generated research bundles. + +The following local paths are excluded from every public package: + +- `data/raw/`, `data/normalized/`, `data/derived/`, `data/models/`, and + `data/quality/`; +- `data/m8/`, `data/m8_l2/`, and `data/_ingestion_manifests/`; +- `artifacts/runs/`; +- local environments, caches, bytecode, credentials, and dashboard secrets. + +Empty `.gitkeep` placeholders may exist in the standalone GitHub repository but +are omitted from the Hugging Face publication mirror where practical. + +## Provider terms + +The research adapters use credential-free public Binance market-data endpoints +and official archive metadata. Public availability is not treated as a grant to +redistribute provider data. Users who reproduce a public-data study obtain the +inputs independently and remain responsible for the provider's current terms, +rate limits, and permitted uses. + +## Research outputs + +Source-controlled prose may summarize bounded aggregate validation counts and +protocol terminals. Raw events, normalized rows, derived features, fitted model +states, account-like records, and generated run bundles are not redistributed. +Synthetic fixtures and smoke outputs are labeled `SYNTHETIC_SMOKE` and support +software verification only. + +The public website and Space may encode low-dimensional aggregate values already +stated in tracked README or status prose—for example row counts, warning counts, +and a declared terminal state—when they link back to that source and preserve its +evidence label. They do not publish additional model or execution metrics. + +## Trading boundary + +The repository has no authenticated exchange client, account connection, or +order-entry path. Nothing in the public package is investment advice or evidence +of executable profit. diff --git a/Microstructure/docs/DECISION_LOG.md b/Microstructure/docs/DECISION_LOG.md new file mode 100644 index 0000000000000000000000000000000000000000..e6456df297277234576dcb6ae31b77db1437f678 --- /dev/null +++ b/Microstructure/docs/DECISION_LOG.md @@ -0,0 +1,487 @@ +# Decision log + +## 2026-08-09 — Supersede the incomplete Aug 8–11 campaign with a new prospective v2 calendar + +- **Observed boundary:** The v1 Aug 8 session is an immutable `MISSED_WINDOW`, + the Aug 9 validation session is immutable and complete, and the v1 development + authority is `NOT_CREATED`. Those facts and files remain preserved. +- **User decision:** Abandon v1 as the active empirical study and, before any of + the new dates is observed, freeze Aug 10 train, Aug 11 validation, Aug 12 + primary test, and Aug 13 replication test at 14:00–15:00 UTC. +- **Integrity rule:** This is a new campaign/version and storage/source + authority, not a replacement bundle inside v1. V1 observations are not used + for v2 training, selection, evaluation, or reporting. Once Aug 10 begins, no + v2 date, threshold, feature, model, or interpretation rule may be changed. +- **Consequence:** A complete v2 train and validation may create the eight-state + `LOCKED` development authority before Aug 12; otherwise v2 terminates through + its existing `NOT_CREATED`/`INSUFFICIENT_DATA` branches without substitution. + +## 2026-08-08 — Preserve the missed first L2 window as control evidence only + +- **Observed fact:** The declared Aug 8 14:00--15:00 UTC train window ended + before a clean committed producer authority was available. No capture command + ran, `data/m8_l2` remained absent, and no raw or economic field was opened. +- **Decision:** Never backfill, replace, or infer that session. Once the release + candidate has a clean source authority, invoke the already-tested late-start + path solely to publish `INSUFFICIENT_DATA / MISSED_WINDOW`; it must not call a + symbol capture adapter or network endpoint. Verify and retain that terminal, + then continue Aug 9--11 on their declared windows under the same campaign + authority. +- **Consequence:** The four-date study cannot promote a fitted development lock, + predictive metric, descriptive result, or execution scenario. Its honest final + outcome is necessarily aggregate `INSUFFICIENT_DATA`, backed by one missed + control terminal plus the remaining declared session authorities. + +## 2026-08-08 — Make development insufficiency a positive authority + +- **Problem:** A valid `INSUFFICIENT_DATA` terminal on Aug 8 or Aug 9 forbids + fitting, but a missing development lock cannot authorize the final four-date + terminal and is indistinguishable from an interrupted workflow. +- **Decision:** The Aug 9 command always atomically publishes exactly one + development authority. `LOCKED` contains the eight fitted child states and + uses `_LOCKED` bytes `locked\n`. `NOT_CREATED` contains only typed, + recursively verified session-control reasons, uses `_NOT_CREATED` bytes + `not-created\n`, and must not load any economic frame. Both statuses expose the + same canonical authority path and SHA fields; a valid `NOT_CREATED` command + or verification exits 1 rather than masquerading as a system error. +- **Consequence:** Aug 10/11 are still captured on schedule. After Aug 11 the + one final producer verifies all four session controls and the development + authority. A `NOT_CREATED` branch publishes aggregate `INSUFFICIENT_DATA`, + reports the union of development and held-out reasons, and contains no + Parquet, model, prediction, descriptive, or execution artifact. + +## 2026-08-08 — Complete the explicit-authority L2 terminal producer + +- **Decision:** Expose one operational path through + `lock-m8-l2-development`, `verify-m8-l2-development-lock`, + `reproduce-m8-l2`, `verify-m8-l2-run`, and `report-m8-l2`. Every stage takes + explicit bundle paths and independently supplied manifest/checksum SHA-256 + authorities; development and final verification additionally require the + exact lock and run-control digests. No command discovers a "latest" input. +- **Terminal semantics:** After both held-out bundles' base authorities are + verified, any non-`COMPLETE` held-out session publishes aggregate + `INSUFFICIENT_DATA` without opening either held-out economic frame. If all + sessions are complete but an endpoint has no eligible held-out labels, the + same typed terminal is published without predictive, descriptive, or execution + promotion. Otherwise the producer restores the eight locked states without + refit, writes all declared evaluation/descriptive/market-scenario artifacts, + snapshots its external authorities, checksums the exact inventory, writes + `_SUCCESS` last, and immediately performs recursive verification. The exact + final marker bytes are `complete\n` for `_SUCCESS` and `terminal\n` for + `INSUFFICIENT_DATA`. +- **Reporting:** Both the canonical trade-M8 failure report and live-L2 reports + are rendered only after verification into a directory outside the immutable + run. The generated report-input snapshot is checksummed and re-rendered for + equality; report commands state that the source bundle was not modified. + +## 2026-08-08 — Bind one outcome-blind L2 campaign to its runtime and storage root + +- **Decision:** The first predeclared capture creates one random 256-bit, + outcome-blind campaign nonce and binds all four sessions to one canonical + output-root path plus its filesystem device/inode identity. Moving to a + different root or replacing that directory is rejected before capture rather + than treated as a continuation of the campaign. +- **Runtime authority:** Bind the clean commit/source-tree identity, loaded + package/module origin, Python/platform identity, and the exact versions of the + eight production dependencies. Persist the canonical runtime payload and its + SHA-256 and revalidate it throughout orchestration and later input/final-run + verification. +- **Reason:** A commit hash alone does not prove that all dates used the same + interpreter, dependency environment, imported source tree, physical evidence + root, or prospectively chosen campaign instance. + +## 2026-08-08 — Accept the frozen trade-only M8 data-insufficiency terminal + +- **Observed evidence:** The corrected clean-source run at commit + `88060613abe211cd8e80a3499678fca830f8ba2d` normalized 2,071,461 BTCUSDT + training rows with no findings, then normalized 987,297 ETHUSDT training rows + with zero errors and 53 `temporal.long_silence` warnings. That violated the + predeclared zero-warning gate. +- **Decision:** Treat `artifacts/runs/binance-m8-multidate` as the canonical + `INSUFFICIENT_DATA` terminal. Preserve its complete failed-normalization + evidence and the earlier noncanonical layout-defect terminal unchanged. Do not + replace the date, relax the warning rule, or reinterpret insufficiency as a + failed economic hypothesis. +- **Boundary proved by the terminal:** Selection did not start; no analysis lock, + fitted state, prediction, endpoint, held-out member, execution, P&L, capacity, + or significance result was produced. The trade-only study is closed; live-L2 + evidence remains a separate prospective campaign. + +## 2026-08-08 — Freeze the complete live-L2 analysis contract before capture + +- **Authority:** The exact analysis TOML has source SHA-256 + `71edf7eeb9d5e935a18b0d8e354dc29b5b1132ace8eccd577730572d2caa8617` + and semantic SHA-256 + `eeb9ac23ff275f26de57533a317d8165a89e99a14e86404a667cc69f6477bdac`. + It binds capture-config SHA-256 + `491b14727a3e8bad907d1ad64072f6ebc14e407f98a5c31fca7b0a9e6801e758` + and capture-protocol SHA-256 + `fe6d4aea5af3e9c529486b7e108afefeba623bf5ad3cc0743c0426a5e62e1fa7`. + Every declared TOML field is rendered without amendment in + `docs/M8_L2_ANALYSIS_CONTRACT.md` and enforced by a fail-closed loader. +- **Development boundary:** Fit volatility regimes on Aug 8 only; select each of + the two-symbol by four-endpoint candidates on Aug 9; persist final fitted model, + prior, preprocessing, calibration, regimes, and execution reference in eight + child locks plus one aggregate lock before either held-out session is exposed. +- **Held-out and claims boundary:** Aug 10/11 restore locked state without fit, + refit, recalibration, threshold change, or regime update. Evaluation uses the + four declared horizons and 2,000-draw paired moving blocks. Execution is a + market-order scenario only. Capacity, realized execution, and profitability + claims remain forbidden irrespective of the result. + +## 2026-08-08 — Keep raw authority separate from derived M8 failure evidence + +- **Discovery:** The first clean-source development attempt stopped at its + frozen data-quality gate before selection, locks, or held-out access, but its + terminal bundle could not be reused: normalized and quality artifacts had + been written inside the directory that the raw-acquisition verifier correctly + requires to be an exact raw-only authority. +- **Decision:** Preserve the bundled raw authority unchanged below + `data/input`; write normalized and DQ artifacts below + `data/normalized_input`; root the final cross-stage manifest at `data`. + `INSUFFICIENT_DATA` inventories must exactly match the physical regular-file + tree and bind completed or failed normalization evidence. The producer runs + the external reuse verifier before and after atomic publication. +- **Evidence policy:** The original source-tagged attempt is retained rather + than repaired or overwritten. It is not canonical research evidence, and its + failure opened no declared held-out member. A fresh terminal requires a new + clean committed source identity; the frozen dates and quality policy do not + change. + +## 2026-08-08 — Lock transparent final fitted state before held-out access + +- **Decision:** Fit and calibrate the validation-selected model and an independent + historical prior once on train plus validation. Serialize canonical numeric + preprocessing, estimator, calibration, feature-order, cutoff, and fallback + state into each child lock; bind both state hashes into the aggregate lock. +- **Held-out rule:** Primary and replication prediction restore those numeric + states. No classifier/calibrator fit, refit, recalibration, or online update is + permitted after the aggregate lock becomes durable. +- **Reason:** A lock that committed only a future refit policy did not freeze the + actual model used on untouched data. + +## 2026-08-08 — Separate deterministic acquisition insufficiency from system faults + +- **Decision:** Declared-object absence and authenticated metadata/CHECKSUM/ZIP, + response-size, or total-evidence-budget violations produce a typed immutable + raw-only `INSUFFICIENT_DATA` authority. Transient-network exhaustion, + permission/local-I/O errors, collisions, and program faults do not terminalize. +- **Reason:** Deterministic missing/invalid declared evidence consumes the frozen + study, while an operational failure must remain safely retryable and cannot be + recorded as an empirical outcome. + +## 2026-08-08 — Define prospective L2 coverage by observed book-state intervals + +- **Decision:** A frozen session counts only consecutive receipt-time intervals + backed by `OBSERVED` reconstructed states within one continuity epoch. Stale, + excluded, gapped, invalid, and silent intervals are not bridged. Cross-symbol + coverage is the intersection of each symbol's interval union. +- **Publication:** Both symbols share one absolute UTC barrier and one atomic + terminal authority. Failed data/gates publish `INSUFFICIENT_DATA`; system + faults preserve nonterminal raw evidence. No failed date is replaced. +- **Reason:** Raw first/last websocket timestamps can hide reconnects and silent + holes and therefore cannot prove usable simultaneous book coverage. + +## 2026-08-07 — Enforce raw-only acquisition and lock-before-open execution + +- **Decision:** Split M8 into an immutable raw authority and a one-way research + producer. Acquisition authenticates exchange metadata, eight ZIPs, eight + official CHECKSUM responses, and bounded ZIP directory metadata, but cannot + open a CSV member. The producer normalizes only train/validation, persists two + symbol locks and an aggregate lock, then revalidates every committed identity + immediately before each held-out member is opened. +- **Reason:** Merely delaying a later Parquet scan would not preserve the + prospective boundary if held-out economic rows had already been decompressed. + The first decompressed member byte is therefore the enforced boundary. +- **Failure policy:** Deterministic data insufficiency before or after locking is + an immutable terminal result with no replacement date, endpoint prediction, + execution result, or profitability/significance claim. Unexpected system + failures publish no partial research target. +- **Protocol effect:** This is operational hardening only. It changes no date, + feature, candidate, endpoint, hypothesis, estimand, or interpretation rule. + +## 2026-08-07 — Count every retained raw-evidence byte and physical copy + +- **Decision:** Use one reservation ledger for accepted responses, retry/error + prefixes, CHECKSUM bodies, exchange metadata, and every source sidecar. Raw + manifests enumerate the exact physical inventory. A self-contained run copy + is a distinct retained copy and must fit under the same frozen total ceiling + before its first byte is written. +- **Reason:** Per-response limits alone do not bound accumulated retries, + sidecars, or duplicated evidence on a 16 GB local machine. Post-hoc counting + could leave an oversized partial publication. +- **Consequence:** Raw response publication is fail-closed and rollback-safe; + normalized Parquet and machine-generated manifest indexes remain outside the + raw-response byte ceiling, as declared by the protocol. + +## 2026-08-07 — Freeze future live-L2 sessions before observation + +- **Decision:** Reserve 14:00–15:00 UTC on 2026-08-08 through 2026-08-11 for + concurrent BTCUSDT/ETHUSDT development, validation, primary-test, and + replication-test captures. +- **Acceptance:** Both symbols need at least 3,300 seconds of overlapping + receipt-time coverage, a 1,800-second continuous valid epoch, zero sequence + gaps, zero DQ findings, exact row reconciliation, and complete immutable + capture evidence. +- **Reason:** Fixed future sessions prevent outcome-based window choice and make + disconnects or missing data visible failures rather than hidden replacements. +- **Claim boundary:** The first protocol is book-only. It permits future-mid + prediction and market-order scenarios, but not limit-fill, realized execution, + capacity, significance, or profitability claims. + +## 2026-08-07 — Record the Jan 6 coverage-metadata race + +- **Discovery:** Before a stop message reached the parallel feasibility audit, + it completed the same official archive availability, checksum, byte/row + count, aggregate-trade-ID boundary, and timestamp-boundary checks for Jan 6. + It did not inspect or retain price, quantity, maker direction, class balance, + features, labels, or model results. +- **Correction:** Protocol 1.0.2 records coverage-only inspection for all four + dates. The calendar, roles, hypotheses, model grid, and interpretation rules + were already frozen and remain unchanged. +- **Boundary:** This metadata helps verify feasibility and completeness only. It + is not economic evidence and cannot justify changing or dropping a date. + +## 2026-08-07 — Correct the M8 freeze claim to outcome-blind + +- **Discovery:** A parallel feasibility audit read official Jan 3–5 archive + availability, checksum, byte/row count, aggregate-trade-ID boundary, and + timestamp-boundary metadata before commit `a34ba13`. It did not inspect or + retain economic fields, class balance, features, labels, or model results; + Jan 6 was not inspected. +- **Correction:** Protocol 1.0.1 describes the study as outcome-blind rather + than claiming it was fully acquisition/inspection-blind. The calendar and all + roles remain unchanged because they were selected mechanically before those + metadata were reported. +- **Constraint:** No economic field or model outcome from any declared date may + be inspected until the ingestion, analysis lock, and final-test gates are + implemented. Coverage-only facts cannot be used to replace a date. + +## 2026-08-07 — Freeze the M8 multi-date trade calendar before acquisition + +- **Decision:** Reserve the complete 2024-01-03 and 2024-01-04 UTC Binance Spot + daily aggregate-trade archives for training and validation, and reserve the + adjacent 2024-01-05 and 2024-01-06 archives as primary and replication tests. + Both BTCUSDT and ETHUSDT are mandatory. The inspected 2024-01-02 sample is + excluded from all study estimates. +- **Reason:** Adjacent dates chosen mechanically before acquisition provide an + auditable barrier against outcome-based date selection. Full daily archives + remove the current row-cap truncation while remaining feasible on local disk + with streaming normalization. +- **Evaluation:** Model selection uses validation log loss only. A locked model + is then evaluated without refit on both untouched dates, using paired + 40-trade-block loss differences and explicit direction-replication status. +- **Claim boundary:** This is a complete-data trade-only study. Execution, book, + fill, P&L, capacity, significance, and cross-instrument pooling remain + unauthorized. M8 still requires separately frozen continuous real L2 evidence. +- **Failure policy:** Missing, oversized, corrupt, noncontiguous, or otherwise + invalid declared data produces `INSUFFICIENT_DATA`; dates are never replaced. + +Material choices are appended; prior entries are not rewritten to hide reversals. + +## 2026-08-07 — Initialize the empty `Microstructure` directory + +- **Context:** The requested `microstructure` folder exists as `Microstructure` + and contains no files or Git metadata. +- **Decision:** Treat the capitalized directory as the target and initialize a + clean Python research repository there. +- **Consequence:** There is no existing user work to merge or preserve inside the + target; all new paths are scoped to this directory. + +## 2026-08-07 — Separate offline software evidence from market evidence + +- **Context:** A new user must reproduce a small run without a large download, + while the project must not invent empirical findings. +- **Decision:** Make the default smoke/reproduction data a deterministic, + explicitly synthetic fixture generated from declared rules. Keep public + Binance ingestion as a separate, credential-free command and never describe + fixture metrics as empirical market results. +- **Consequence:** The vertical slice can be tested offline. Economic conclusions + remain deliberately unavailable until a manifested public-data run is made. + +## 2026-08-07 — Use trade events for the initial research slice + +- **Context:** Historical trades are broadly public and compact; historical full + depth is less consistently public. The objective explicitly permits trades or + a small book sample for the first slice. +- **Decision:** Build the first model dataset from signed trades and event-time + liquidity proxies. Implement and test L2 snapshot/delta reconstruction as a + separate adapter path, but do not pretend trade-only data identify queue fills. +- **Consequence:** Initial fill probability and queue position are declared + assumptions. Later L2 runs can replace them through the same interfaces. + +## 2026-08-07 — Prefer integer event ordering plus UTC nanoseconds + +- **Context:** Exchange timestamps may tie and floating timestamps can obscure + exact temporal order. +- **Decision:** Normalize `event_id`, `sequence`, `event_ts_ns`, and + `received_ts_ns`. Stable event ordering is `(event_ts_ns, sequence, event_id)`; + receipt time is retained for latency realism. +- **Consequence:** Features and labels can state observable cutoffs explicitly; + downstream modules must not reorder tied events arbitrarily. + +## 2026-08-07 — Make validation non-mutating + +- **Context:** Silent repair can erase evidence of feed or clock problems. +- **Decision:** Validators emit typed findings and summaries but never mutate raw + or normalized observations. Any later filtering writes a new derived dataset + and records exclusion counts. +- **Consequence:** A run can fail on fatal findings or continue on declared + warnings without altering source evidence. + +## 2026-08-07 — Evaluate event-time models with purged walk-forward folds + +- **Context:** Random splits leak regime information and overlapping future-label + horizons leak outcomes across adjacent partitions. +- **Decision:** Use expanding-window, time-ordered folds. Remove training rows + whose label end reaches the validation/test boundary and support a configurable + embargo. Reserve the last fold for final comparison, not model selection. +- **Consequence:** Small fixtures may yield wide uncertainty; that is preferable + to optimistic metrics. + +## 2026-08-07 — Do not infer historical Spot depth from trade archives + +- **Context:** Binance's credential-free Spot archive exposes trades and + aggregate trades, but not a complete historical Level-2 feed suitable for book + reconstruction. REST snapshots are current anchors rather than historical + depth observations. +- **Decision:** Use fixed, bounded public REST aggregate trades for historical + ingestion. Keep Level-2 research behind an optional public live diff-depth + collector that begins with a locally received snapshot and creates a new epoch + after every reconnect or gap. +- **Consequence:** Historical trade research and book research are different + evidence paths. No queue, cancellation, or depth claim is inferred from the + downloaded trade sample. + +## 2026-08-07 — Derive numerical scales from exchange metadata + +- **Context:** Fixed decimal precision can misrepresent instruments and can + change across venue rules. Binance aggregate-trade timestamps also changed + archive units for newer files, while REST uses its documented request units. +- **Decision:** Fetch `PRICE_FILTER.tickSize` and `LOT_SIZE.stepSize` from public + `exchangeInfo` before normalization, retain integer ticks/lots plus the scale, + and make timestamp-unit conversion explicit at the adapter boundary. +- **Consequence:** Exact source values are reproducible without assuming a + universal `1e-8` quantum. Low-level fallback scales are not used by the sample + workflow. + +## 2026-08-07 — Freeze results as immutable atomic bundles + +- **Context:** A dashboard or report must never read half-written results, and a + repeated command must not silently revise earlier evidence. +- **Decision:** Produce into a sibling staging directory, serialize all inputs, + folds, metrics, ledgers, assumptions and reports, checksum every file, create + `_SUCCESS` last, verify the bundle, then atomically rename it. A completed + target is reusable only if verification passes; incomplete or corrupted + targets are rejected rather than repaired. +- **Consequence:** Changed configuration or assumptions require a new run. The + deterministic semantic run key is based on config, immutable input identity, + Git state and seed, excluding wall-clock generation time. + +## 2026-08-07 — Keep execution conditional and out-of-sample + +- **Context:** Archived public events cannot identify a strategy's true queue + position, endogenous impact, or colocated latency. Replaying in-sample + probabilities would further overstate execution evidence. +- **Decision:** Accept only validation-selected, held-out test predictions in the + execution simulator. Treat market depth, limit-fill Bernoulli behavior, queue + ahead, latency, fees, liquidation and capacity as serialized scenario inputs; + use common keyed randomness for comparable sensitivities. +- **Consequence:** Predictive and execution tables remain separate. Simulated + results are conditional diagnostics, not realized or deployable performance. + +## 2026-08-07 — Cap and label the first public sample + +- **Context:** A local Apple Silicon workflow needs a small, auditable public + acquisition rather than an open-ended download. +- **Decision:** Request the fixed interval beginning 2024-01-02 00:00 UTC for + BTCUSDT and ETHUSDT, capped at 5,000 aggregate trades per symbol, and label the + acquisition `PUBLIC_SAMPLE_PARTIAL`. +- **Consequence:** The cap was reached for both symbols. All 10,000 normalized + rows passed the current validators, but both requested ranges are recorded as + incomplete and no economic hypothesis is promoted from this sample. + +## 2026-08-07 — Freeze the trade-only public study before model comparison + +- **Context:** The already acquired public sample contains aggregate trades but + no contemporaneous order-book state. Reusing book features or the execution + simulator would turn missing observations into assumptions and overstate the + evidence. +- **Decision:** Freeze a retrospective, explicitly exploratory trade-only + protocol with per-symbol causal features, strictly later trade labels, + purged walk-forward folds, validation-only model selection, and a paired + fixed-block comparison against the historical prior. Require the caller to + select the ingestion manifest by both path and SHA-256; never scan for a + "latest" input. Serialize execution artifacts as `NOT_RUN` with a reason. +- **Consequence:** BTCUSDT and ETHUSDT are reported separately, including failed + or contradictory outcomes. The run cannot be interpreted as a book, fill, + P&L, statistical-significance, or persistent-alpha study. + +## 2026-08-07 — Make page/batch streaming the default public ingestion path + +- **Context:** A configurable row cap made the first 10,000-row sample safe, but + the original downloader, validator, and ingestion composition retained the + entire acquisition in memory. A cap on observations is not a RAM contract and + does not satisfy the larger-history requirement. +- **Decision:** Expose a lazy, page-bounded Binance iterator; feed each page once + through an incremental validator with disk-backed exact identity state and + then into a batch-bounded Parquet writer. Keep eager materialization only as an + explicit compatibility operation with its own finite row guard. +- **Consequence:** Public acquisition memory is bounded by response/batch and + validator preview limits rather than total history length. Manifest and part + metadata may still grow with page count; downstream full-history readers must + likewise use verified batch scans instead of eager Arrow/Polars copies. + +## 2026-08-07 — Verify public history before exposing a bounded canonical stream + +- **Context:** Hashing only an ingestion manifest does not prove that normalized + rows still match the declared raw pages, source symbol, exchange metadata, or + physical arrival order. Sorting first can also conceal source-order defects. +- **Decision:** Bind the explicit ingestion path+SHA to configuration, raw URI + semantics and exact aggregate-trade fields; require inverse raw-to-normalized + coverage; run physical-order incremental DQ; and feed that single verified + Arrow stream into a memory-limited DuckDB external sort. Keep eager loading as + a separately guarded compatibility API. +- **Consequence:** The current 10,000-row input can be materialized for the + predeclared small study, while larger consumers can iterate bounded canonical + batches without trusting a global in-memory sort. + +## 2026-08-07 — Make quality evidence atomic and ingestion-manifested + +- **Context:** Reusing a fixed findings filename could truncate a previous + complete JSONL before a rerun succeeded, leaving an older summary pointing at + partial/new evidence. +- **Decision:** Stream findings into a same-directory temporary file, fsync and + atomically publish only on validator completion, use a distinct per-ingestion + quality filename, and bind report/findings paths, byte counts and SHA-256 into + the immutable ingestion manifest. +- **Consequence:** A failed rerun cannot damage previously published findings; + complete quality evidence is independently integrity-checkable. + +## 2026-08-07 — Treat the exact source tree as part of run identity + +- **Context:** A Git commit plus `dirty=true` cannot distinguish different local + patches. It also allowed an old clean bundle to satisfy `make smoke` after the + implementation changed. +- **Decision:** Hash the bytes, paths and modes of every tracked and non-ignored + untracked source file. Include that digest with commit/dirty state in + provenance and both synthetic/public run keys; refuse completed-target reuse + when any component differs. Run the `make check` smoke leg in a fresh temporary + target. +- **Consequence:** Ignored raw/run artifacts do not perturb identity, but changed + code, configuration, tests or documentation requires a new immutable bundle. + +## 2026-08-07 — Journal live depth before parsing and reconstruct incrementally + +- **Context:** Retaining every WebSocket payload, delta and reconstructed book + row in Python made `collect-l2 --max-messages` an in-memory history limit. A + malformed frame could also fail before its original bytes were preserved. +- **Decision:** Emit exact raw frames to a typed capture journal before decoding, + record each reconnect snapshot anchor, enforce per-frame/batch byte ceilings, + run a bounded-state incremental book reconstructor and incremental DQ, and + stream capture-scoped Parquet output. Publish one immutable capture-ID summary + last; keep the fixed summary filename only as a latest-pointer. +- **Consequence:** Capture memory is bounded by book depth and batch limits rather + than message count; every epoch is resnapshotted, every message is reconciled + to an observation/exclusion, and parse/sequence failure leaves explicit raw + evidence without fabricating a completed capture. diff --git a/Microstructure/docs/EXPLORATORY_AGGTRADES_2026_08_05_08.md b/Microstructure/docs/EXPLORATORY_AGGTRADES_2026_08_05_08.md new file mode 100644 index 0000000000000000000000000000000000000000..05baf6ed540223b2357e9b8b9838f168340e87be --- /dev/null +++ b/Microstructure/docs/EXPLORATORY_AGGTRADES_2026_08_05_08.md @@ -0,0 +1,59 @@ +# August 5–8 public aggregate-trade exploratory protocol + +## Scope + +This retrospective, trade-only study uses the complete official Binance Spot +daily `aggTrades` archives for BTCUSDT and ETHUSDT on 2026-08-05 through +2026-08-08. It is independent of the frozen live-L2 campaign. It contains no +book depth, spread, queue, cancellation, local receipt time, or executable +order evidence. + +The date roles are fixed before any archive CSV member is opened: + +| UTC date | Role | +| --- | --- | +| 2026-08-05 | Train | +| 2026-08-06 | Validation and model selection | +| 2026-08-07 | Primary test | +| 2026-08-08 | Replication test | + +The evidence tier is `PUBLIC_ARCHIVE_EXPLORATORY`. Results cannot be described +as confirmatory, statistically significant, persistent alpha, executable P&L, +or an L2 finding. + +## Data and quality + +Each ZIP must match the exchange-published `.CHECKSUM`, contain exactly its +declared CSV member, remain inside bounded compressed and expanded byte limits, +and preserve its raw response and source sidecar. Normalization is streamed to +partitioned Parquet. Aggregate-trade IDs must be contiguous and event time must +not reverse within each symbol/date. + +Quality warnings are retained and reported but do not stop this exploratory +run; any error, checksum failure, archive-contract failure, ID gap, or temporal +violation stops the run. No observation is repaired or replaced. + +## Features, target, and evaluation + +Features use only the current and prior trades within one UTC-day continuity +segment: one-trade return; signed volume, total volume, and imbalance over 5, +20, and 100 trades; 50-trade count and intensity; and 100-trade realized +volatility. The target is whether trade price 20 aggregate trades later is +higher. Segment tails are censored. + +The candidate ladder is the historical prior, unpenalized logistic regression, +the declared L2-regularized logistic grid, and the declared shallow-tree grid. +Only August 5–6 may select and fit the final selected/prior states. Both symbol +locks and one aggregate lock must be persisted before either August 7 or August +8 CSV member opens. No refit is allowed afterward. + +Selected-minus-prior log-loss differences are reported separately for both test +dates and with equal-date weighting. Seeded 40-trade paired block intervals are +descriptive dependence diagnostics only; no p-values or significance claim are +authorized. BTCUSDT and ETHUSDT are never pooled. + +## Explicit exclusions + +Execution, fills, fees, capacity, queue position, market impact, profitability, +and live-L2 conclusions are `NOT_RUN` or unauthorized. A favorable point +estimate is evidence only about these four retrospective trade archives. diff --git a/Microstructure/docs/M8_L2_ANALYSIS_CONTRACT.md b/Microstructure/docs/M8_L2_ANALYSIS_CONTRACT.md new file mode 100644 index 0000000000000000000000000000000000000000..28799f08d13e327eb04094af40ccd62ad75da4e2 --- /dev/null +++ b/Microstructure/docs/M8_L2_ANALYSIS_CONTRACT.md @@ -0,0 +1,183 @@ +# M8 live-L2 analysis contract + +## Authority and status + +This document is a human-readable, field-complete rendering of +`configs/m8_l2_analysis.toml`. It does not amend or supersede those bytes. The +strict loader rejects a changed, missing, or additional field. + +| Authority | SHA-256 | +| --- | --- | +| Analysis TOML source bytes | `0d786d5f4109bb5bf773a6197df3fa861c9b7eb61c16c957bd49fb56147fd7d8` | +| Analysis TOML canonical semantics | `17c91f64765f35195ab03a4caac93d8ff9c5f009c16e785fd84ebd9569d6f84b` | +| Bound capture-config source bytes | `b1bf3b4e2820e24e4555bfeb9cb0957f9a0bcdef62039f7d92360e0a97d0dd39` | +| Bound capture-protocol source bytes | `4c77a2099a4cabd049d10e0f8264d3b4c66704d8e87cbaf0c817fd085f4bbd83` | + +The calendar, capture gates, model candidate grid, fee, and decision/order +latency event-count grid remain authoritative in the bound capture config and +`docs/M8_L2_PROTOCOL.md`; they are not silently restated as analysis-config +fields here. At freeze time, this contract contained no observed session data or +model outcome. It therefore authorizes no empirical conclusion by itself. + +## Operational enforcement + +The implemented producer consumes four explicit session bundle paths, manifest +SHA-256 values, and checksum-file SHA-256 values. Development locking additionally +binds its aggregate SHA, and final verification/reporting additionally binds the +run manifest and checksum-file SHA. The campaign authority ties every date to one +outcome-blind nonce, canonical filesystem root identity, clean source/import +origin, and hashed Python/platform/production-dependency fingerprint. A final +bundle snapshots these authorities for self-contained audit while recursively +revalidating the external originals. Report re-rendering occurs outside the +immutable run and leaves it unchanged. These enforcement facts implement the +frozen contract; they are not additional TOML fields or empirical outcomes. + +## Study fields + +| TOML path | Frozen value | +| --- | --- | +| `study.name` | `binance-m8-live-l2-analysis` | +| `study.protocol_version` | `1.0.0` | +| `study.seed` | `20260807` | +| `study.source` | `verified_m8_l2_session_bundles` | +| `study.capture_config_source_sha256` | `491b14727a3e8bad907d1ad64072f6ebc14e407f98a5c31fca7b0a9e6801e758` | +| `study.capture_protocol_sha256` | `fe6d4aea5af3e9c529486b7e108afefeba623bf5ad3cc0743c0426a5e62e1fa7` | +| `study.symbols` | `BTCUSDT`, `ETHUSDT` | +| `study.training_role` | `train` | +| `study.selection_role` | `validation` | +| `study.primary_endpoint_role` | `primary_test` | +| `study.replication_endpoint_role` | `replication_test` | + +Only checksum-verified session bundles with the exact bound capture authorities +are eligible. All per-symbol decisions operate inside verified observed +continuity intervals; reconnects, gaps, excluded state, and invalid intervals +are never bridged. + +## Feature and label fields + +| TOML path | Frozen value | +| --- | --- | +| `features.decision_scope` | `per_symbol_verified_observed_intervals` | +| `features.flat_direction_policy` | `flat_is_non_up` | +| `features.rolling_windows` | `20`, `100` | +| `features.volatility_window` | `100` | +| `features.clock_max_state_age_ms` | `500` | +| `features.clock_target_policy` | `exact_target_locf_same_valid_observed_interval` | +| `features.clock_label_information_end` | `exact_target` | +| `features.clock_record_target_sequence` | `true` | +| `features.clock_censor_if_no_eligible_state` | `true` | + +The exact ordered `features.model_feature_columns` value is: + +1. `spread_bps` +2. `depth_total_l1` +3. `depth_total_l5` +4. `depth_total_l10` +5. `queue_imbalance_l1` +6. `queue_imbalance_l5` +7. `queue_imbalance_l10` +8. `microprice_deviation_bps` +9. `ofi_l1` +10. `ofi_w20` +11. `ofi_w100` +12. `cancellation_intensity_w20` +13. `cancellation_intensity_w100` +14. `realized_volatility_w20` +15. `realized_volatility_w100` +16. `volatility_regime_low` +17. `volatility_regime_high` +18. `liquidity_regime_liquid` +19. `liquidity_regime_stressed` + +For a clock endpoint, the target is the exact horizon time. The eligible future +book is the most recent state at or before that target, must be no more than 500 +ms old, and must belong to the same valid observed interval. Otherwise the label +is censored. Its information end remains the exact target, and the chosen target +sequence is recorded. A zero future return is assigned to the non-up class. + +## Endpoint fields + +| `endpoints` row | `domain` | `horizon_value` | `unit` | `paired_block_width` | `paired_block_unit` | `nominal_event_block_width` | +| --- | --- | ---: | --- | ---: | --- | ---: | +| `event_20` | `event` | 20 | `events` | 40 | `events` | 40 | +| `event_100` | `event` | 100 | `events` | 200 | `events` | 200 | +| `clock_1000ms` | `clock` | 1000 | `milliseconds` | 2000 | `milliseconds` | 20 | +| `clock_5000ms` | `clock` | 5000 | `milliseconds` | 10000 | `milliseconds` | 100 | + +These four rows are the complete `[[endpoints]]` array; each table column maps +one-for-one to a TOML field. Dependency blocks cannot cross a verified observed +interval. + +## Regime, calibration, bootstrap, and signed-impact fields + +| TOML path | Frozen value | +| --- | --- | +| `regimes.fit_role` | `train` | +| `regimes.feature` | `realized_volatility_w100` | +| `regimes.quantile_numerators` | `1`, `2` | +| `regimes.quantile_denominator` | `3` | +| `calibration.bins` | `10` | +| `bootstrap.method` | `paired_moving_block` | +| `bootstrap.samples` | `2000` | +| `signed_impact.metric` | `ofi_signed_future_mid_markout` | +| `signed_impact.side_rule` | `sign_of_horizon_matched_ofi` | +| `signed_impact.price_rule` | `ofi_sign_times_future_log_mid_return_bps` | + +Regime cutoffs are the training-role one-third and two-thirds quantiles of +`realized_volatility_w100`. They are fit once and then applied without update. +Here “horizon-matched OFI” means decision-time observable rolling OFI matched to +the endpoint window, never OFI measured during or after the label interval: +`event_20` and `clock_1000ms` use `ofi_w20`; `event_100` and `clock_5000ms` use +`ofi_w100`. +Those columns come from the causal decision feature frame, and their maximum +source timestamp is validated not to exceed the decision timestamp. The signed- +impact estimand multiplies that decision-time OFI sign by the strictly future +log-mid return in basis points. The 2,000-draw paired moving-block design uses +each endpoint's frozen block width; it does not authorize a p-value or a cross- +symbol pooled significance claim. + +## Execution fields + +| TOML path | Frozen value | +| --- | --- | +| `execution.market_orders_only` | `true` | +| `execution.probability_threshold` | `0.55` | +| `execution.symmetric_probability_thresholds` | `true` | +| `execution.order_notional_usd` | `100.0` | +| `execution.max_l1_participation` | `0.10` | +| `execution.inventory_order_multiples` | `10` | +| `execution.reference_price_fit_role` | `train` | +| `execution.reference_depth_fit_role` | `train` | +| `execution.reference_price_statistic` | `train_median_mid_price` | +| `execution.reference_depth_statistic` | `train_q05_min_bid_ask_l1_depth` | +| `execution.reference_quantity_policy` | `min_100usd_and_10pct_train_q05_l1_depth_rounded_down_to_lot` | +| `execution.l1_fill_policy` | `fill_up_to_recorded_l1_depth_cancel_remainder` | +| `execution.scenario_reset_policy` | `per_symbol_session_endpoint_latency_pair` | +| `execution.extra_slippage_bps` | `0.0` | +| `execution.liquidate_at_end` | `true` | + +The symmetric threshold means long above `0.55`, short below `0.45`, and no +order otherwise. Reference price and depth are fitted on training data only. The +reference quantity is the smaller of USD 100 at the training median mid and 10% +of the training fifth percentile of minimum bid/ask L1 depth, rounded down to the +exchange lot. Recorded L1 depth caps each fill; any residual is cancelled. +Inventory is capped at ten reference-order multiples. State resets for every +symbol, session, endpoint, and latency pair, and end inventory is liquidated. +Latency values and taker fee are consumed from the separately bound capture +config; latency is measured in events, not milliseconds. Zero extra slippage is +a frozen scenario assumption, not a claim that endogenous impact is zero. + +## Claim fields + +| TOML path | Frozen value | +| --- | --- | +| `claims.allow_capacity_claim` | `false` | +| `claims.allow_realized_execution_claim` | `false` | +| `claims.allow_profitability_claim` | `false` | + +Accordingly, eventual reports may describe predictive diagnostics and +serialized market-order scenarios only. They cannot call those scenarios +realized fills, deployable capacity, or evidence of profitability. Any missing +or invalid declared session may instead produce `INSUFFICIENT_DATA`; that +terminal is not replaced and does not count as a test of the economic +hypothesis unless the required evaluation actually occurred. diff --git a/Microstructure/docs/M8_L2_PROTOCOL.md b/Microstructure/docs/M8_L2_PROTOCOL.md new file mode 100644 index 0000000000000000000000000000000000000000..272b62b8aff2641546833a9355ce4efbbd94ef07 --- /dev/null +++ b/Microstructure/docs/M8_L2_PROTOCOL.md @@ -0,0 +1,103 @@ +# M8 prospective live-L2 protocol — replacement campaign v2 + +## Scope and frozen calendar + +This replacement protocol was fixed before any v2 live session occurred. Both symbols +must be captured concurrently from Binance Spot diff-depth at the requested +100 ms stream interval: + +| UTC session | Role | +| --- | --- | +| 2026-08-10 14:00–15:00 | Train | +| 2026-08-11 14:00–15:00 | Validation | +| 2026-08-12 14:00–15:00 | Primary test | +| 2026-08-13 14:00–15:00 | Replication test | + +The dates are the four consecutive UTC dates beginning after the v2 reset on +2026-08-09, and the common hour was chosen before observing those sessions. Missing, +quiet, volatile, disconnected, corrupt, or unfavorable sessions are never +replaced. They produce an explicit `INSUFFICIENT_DATA` status. The superseded +Aug 8–11 campaign and its evidence remain immutable and are not inputs to this +study. The exact config +bytes in `configs/m8_l2_capture_study.toml`, this protocol, their hashes, and the +freeze Git commit must enter every resulting bundle. + +This is a research-only public market-data capture. It authenticates to no +account and has no order-entry path. + +## Capture and continuity acceptance + +Each symbol receives its own snapshot and diff-depth stream, started as close to +the common boundary as the public network allows. Raw websocket bytes must be +journaled before UTF-8/JSON parsing. Every continuity epoch begins from a fresh +REST snapshot and may use only buffered deltas satisfying Binance `U/u` +bridging. Gaps, malformed ranges, crossed books, or scale mismatches terminate +that epoch; they are recorded rather than repaired. + +A session is usable only when both symbols satisfy all of the following: + +- capture-specific completion status is `COMPLETE` and reconstruction ends + `LIVE`; +- requested duration is 3,600 seconds and overlapping receipt-time coverage is + at least 3,300 seconds; +- at least one valid continuity epoch spans 1,800 seconds; +- sequence gaps and quality errors/warnings are all zero; +- no raw frame exceeds 1 MiB and no Arrow batch estimate exceeds 16 MiB; +- message, normalized-row, reconstructed-row, and excluded-row reconciliation + is exact; +- every epoch has a raw snapshot anchor and every raw/normalized/quality file is + checksum-manifested. + +The 60,000-message ceiling is a safety bound, not a stopping target. A +duration-aware graceful stop must publish completion evidence; SIGINT/cancellation +or hitting the message ceiling early is not a complete one-hour session. + +## Causal dataset + +Continuity is never bridged across reconnects or gaps. At each decision book +event, features may use only locally received snapshot/delta state available at +or before that event. Frozen features are absolute/relative spread, L1/L5/L10 +depth, OFI, L1/L5/L10 queue imbalance, microprice displacement, observable +zero-quantity cancellation intensity, short realized volatility, and regimes +whose thresholds are fit on the training session only. + +Labels begin strictly after the decision event and are censored at continuity +boundaries. Report future mid-price direction/return and signed price impact at +20/100-event and 1/5-second horizons. Limit-fill and adverse-selection labels are +not authorized without contemporaneous trade prints that prove depletion; this +book-only protocol does not infer them from cancellation alone. + +## Evaluation and hypotheses + +Per symbol, train on Aug 10, select the fixed prior/logistic/L2/tree ladder by Aug +11 log loss, lock the specification, then evaluate it without refit on Aug 12 and +Aug 13. Probability calibration and regime thresholds use development data only. +All declared horizons and model comparison rows are published; no final period +is used for selection. + +The primary book hypothesis is that observable OFI, imbalance, microprice, and +liquidity state reduce future-mid-direction log loss relative to a historical +prior on both untouched sessions. Report paired dependency-block differences by +symbol, session, horizon, and train-defined regime, plus equal-session-weighted +stability. A result is directionally replicated only if both untouched sessions +favor the selected model. No p-value, H0 rejection, cross-symbol pooled alpha, +or significance claim is authorized. + +## Execution boundary + +Only scenario-based market-order evaluation is permitted: recorded best quotes, +frozen taker fee, decision/order latency grids, inventory bounds, and end-of-run +liquidation. It may show whether a predictive markout survives those serialized +assumptions, but it is not realized execution. Limit fills, true queue priority, +hidden liquidity, endogenous impact, and deployable capacity remain unsupported. +Every report must keep predictive scores, simulated execution assumptions, and +scenario P&L separate and must state that profitability is not established. + +## Immutable outputs + +The study requires capture-specific raw journals and snapshots, capture and +normalized manifests, DQ/exclusion summaries, causal frames, analysis lock, +frozen predictions/comparisons, regime/stability diagnostics, scenario execution +ledgers, generated reports, config/protocol/input/Git provenance, checksums, and +`_SUCCESS` written last. A missing session or failed gate may produce a failure +bundle, but never a promoted result bundle. diff --git a/Microstructure/docs/M8_MULTIDATE_TRADE_PROTOCOL.md b/Microstructure/docs/M8_MULTIDATE_TRADE_PROTOCOL.md new file mode 100644 index 0000000000000000000000000000000000000000..53c878549c71d4976863f21937e3e8bd2f183d10 --- /dev/null +++ b/Microstructure/docs/M8_MULTIDATE_TRADE_PROTOCOL.md @@ -0,0 +1,269 @@ +# M8 prospective multi-date aggregate-trade protocol + +## Freeze and scope + +This protocol is outcome-blind: it is frozen before inspecting any declared +date's price, quantity, aggressor side, class balance, feature, label, model, or +economic result. During a parallel feasibility audit before the first protocol +commit, the official Jan 3–5 archive availability, checksums, byte/row counts, +aggregate-trade-ID boundaries, and timestamp boundaries were inspected. A +stop-message race then allowed the same coverage-only checks for Jan 6 after the +outcome-blind freeze; no economic field or result was read. These coverage-only +facts were not supplied when the dates were chosen, and the mechanically +selected calendar below was not changed after they became known. The previously +inspected 2024-01-02 sample is +protocol-development evidence only and is excluded from every fit, threshold, +validation score, and test result below. + +The study is a prospective stability test of the trade-only hypothesis. It is +not an order-book, execution, profitability, or capacity study. Even a favorable +result cannot answer the repository's book-dependent or trading-cost questions; +those require separately frozen, contemporaneous, continuous L2 evidence. + +The machine-readable specification is +`configs/m8_multidate_trade_study.toml`. Its exact bytes, Git commit, and SHA-256 +must be copied into the final study bundle. Changing a date, role, feature, +model, endpoint, or interpretation rule creates a new protocol version and may +not overwrite this study. + +### Protocol-boundary clarification + +The acquisition/locking rules below are an operational hardening of the +existing outcome-blind protocol, not an outcome-driven amendment. They change +no date, role, feature, label, candidate, hypothesis, estimand, or interpretation +rule. No declared economic outcome was opened to motivate this clarification: +in particular, no declared price, quantity, buyer-maker value, class balance, +feature, label, fit, score, or test result has been inspected. The historical +coverage-only disclosure above remains the complete exception. An +implementation that cannot enforce the hardened boundary does not execute this +protocol. + +## Data calendar and completeness + +Use the complete Binance Spot daily aggregate-trade archive for both BTCUSDT and +ETHUSDT on each UTC date: + +| UTC date | Frozen role | Permitted use | +| --- | --- | --- | +| 2024-01-03 | Train | Feature construction, fitting, train-only thresholds | +| 2024-01-04 | Validation | Candidate selection only | +| 2024-01-05 | Primary test | Open once after the selected specification is locked | +| 2024-01-06 | Replication test | Open with the same locked specification; no refit | + +The dates were chosen mechanically as the four adjacent dates immediately after +the inspected 2024-01-02 development sample, not because of observed economic +outcomes. Pre-freeze coverage-only inspection does not authorize any calendar +change. Do not replace a quiet, volatile, missing, inconvenient, or unfavorable +date. + +All eight symbol/date archives must be present, checksum-verified, and complete +for `[00:00:00Z, 24:00:00Z)`. A missing archive, truncated response, failed +checksum, row cap, noncontiguous aggregate-trade ID inside a symbol/date, or data +quality error makes the study `INSUFFICIENT_DATA`. Such a failure is reported; +it is not repaired by choosing another date. Raw archives remain immutable and +uncommitted. Normalized data is partitioned by venue, symbol, and UTC date. + +Acquisition of all eight archives is **raw-only**. It may verify the exact +official `CHECKSUM` response, response lengths and hashes, and bounded ZIP +end-of-central-directory/central-directory metadata for exactly one +expected-name member and its declared sizes. It must not open, extract, or read +the CSV member; stream decompressed member bytes; parse even its header; expose +an economic field; or derive row, ID, timestamp, or class-balance coverage. +Those operations constitute economic-data opening and belong to the staged +normalization boundary below. Public `exchangeInfo` may be parsed only for the +declared symbol's status and exact tick/lot filters, with its exact response and +response sidecar preserved. + +Archive transfer and later CSV normalization must both be streaming and +byte-bounded. The byte ceilings in the machine-readable protocol are hard +safety limits, not sampling rules: + +- `max_archive_compressed_bytes` bounds each archive ZIP response body while it + is transferred; an asserted `Content-Length` does not replace streamed byte + accounting. +- `max_archive_uncompressed_bytes` bounds both the central-directory-declared + size and the actual expanded bytes of each sole CSV member. The limit is + rechecked while the member is normalized. +- `max_total_download_bytes` bounds the total immutable raw-evidence bytes + accepted for this study. The total includes every retained ZIP body, official + `CHECKSUM` body, raw-response sidecar, `exchangeInfo` metadata body and + sidecar, and every retained rejected-response prefix and its rejection + sidecar. A failed attempt or retry does not reset this total. A + content-addressed file is counted once if it is physically retained once; + distinct retained copies are counted separately. Derived normalized files, + quality reports, and aggregate manifest/checksum indexes are not raw-response + evidence and do not enter this ceiling. + +The smaller `CHECKSUM`, metadata, and rejected-prefix responses also have fixed +per-response bounds in the adapter and remain subject to the hard total above. +Before accepting another raw artifact, the acquisition layer must reserve and +account for its bounded body and sidecar; no published raw acquisition manifest +may exceed the total. Crossing any per-response, expanded, or total limit fails +closed before a research result is produced. Every accepted and rejected raw +artifact is immutable, byte-counted, hashed, and enumerated by the raw +acquisition manifest. + +## Prospective materialization and lock boundary + +The study executes in the following one-way order: + +1. Acquire and authenticate all eight raw ZIPs, all eight official `CHECKSUM` + responses, and the exact symbol-metadata responses. Publish the immutable raw + acquisition manifest without opening any CSV member. +2. Open, stream-normalize, and quality-check only the train and validation CSV + members. Publish an immutable development normalized manifest that binds + every normalized part, sidecar, quality artifact, and its raw source. +3. Select and refit using only those development rows. Persist one lock per + symbol, then an aggregate lock that commits the exact bytes and SHA-256 of + both symbol locks. Each symbol lock commits its selected specification, + development-frame identity, and deterministic final-fit policy; the aggregate + lock also commits the frozen + protocol/config, raw acquisition manifest, development normalized manifest, + and clean real Git revision. Close and `fsync` every lock and digest file and + `fsync` its containing directory. The aggregate lock is not durable until + all child locks and their directories are durable. +4. Immediately before the first decompressed CSV byte of every primary or + replication archive is read, re-read and re-hash the exact durable aggregate + lock and all identities it commits. Only then may that member be + stream-normalized and quality-checked. Both untouched dates use the same + locked fit and transformation state; there is no reselection, refit, + recalibration, threshold change, feature change, or model update after the + lock, including between primary and replication. +5. On success, publish a final normalized manifest covering all eight declared + symbol/dates. Only that final manifest may authorize endpoint evaluation and + final-bundle publication. + +For this boundary, "opened" means the first decompressed byte of a CSV member, +not a later Parquet scan. Inspecting ZIP directory metadata is not opening the +member. Merely writing a lock path is not persistence: exact bytes, hashes, +file descriptors, and containing directories must meet the durability rule +above before a held-out member-open callback can succeed. + +## Timing and continuity + +Each symbol/date is a separate continuity segment. Features reset at its first +trade, labels are censored at its final trade, and neither lookbacks nor labels +cross midnight or a sequence gap. Exchange event time is only an availability +proxy; aggregate-trade ID breaks tied timestamps. No local receipt-time claim is +permitted. + +At decision trade `i`, a feature may use `i` and earlier trades from the same +verified segment. The target is one only when the price at `i + 20` is greater +than the decision price. The target trade ID and information-end timestamp are +serialized. The longest 100-trade lookback and 20-trade label tail determine +feature readiness and right censoring. + +## Frozen features, candidates, and selection + +The feature set is fixed before acquisition: + +- one-trade log return; +- signed quantity, absolute quantity, and signed-volume imbalance over 5, 20, + and 100 trades; +- trade count and event-time intensity over 50 trades; +- realized trade-price volatility over 100 trades. + +Evaluate, separately for each symbol, the historical-prior classifier, +unpenalized logistic regression, L2 logistic regression with +`C in {0.1, 1, 10}`, and shallow decision trees with depth in `{2, 4, 6}` and +minimum leaf size 40. Median imputation, standardization where applicable, and +sigmoid calibration are learned only from chronologically earlier rows. + +The 2024-01-03 fit predicts 2024-01-04. Mean validation log loss selects one +candidate per symbol; stable candidate order is the tie breaker. After selection, +the selected candidate is refit once on 2024-01-03 plus 2024-01-04 using the +same chronological calibration rule. The selected specification and its hash +are written to an analysis lock before either test date is evaluated. The same +locked fit predicts both test dates; there is no update between primary and +replication tests. All candidate validation rows and all locked-model test rows +are published. + +## Hypotheses and estimands + +For each symbol: + +- **H0:** the validation-selected model does not reduce held-out log loss versus + the historical-prior classifier on the untouched dates. +- **H1:** the validation-selected model reduces held-out log loss versus the + prior on both the primary and replication dates. + +The primary estimands are selected-model minus prior log loss for each +symbol/date and the equal-date-weighted mean across the two test dates for each +symbol. Negative values favor the selected model. A result is +`directionally_replicated` only when both date-level point differences are +negative. Otherwise it is `mixed`, `failed`, or `insufficient_data` according to +the serialized observations. This status is descriptive and is not a +significance decision. + +Uncertainty uses paired, contiguous 40-trade blocks, resetting at every UTC date. +The same resampled blocks are used for selected and prior predictions. Report +2,000 seeded percentile draws for each date and an equal-date-weighted paired +draw for each symbol. Every interval must contain observations from the two +nonoverlapping test dates before the aggregate is emitted. + +No p-values are computed and no H0 rejection or statistical-significance claim +is authorized. The two symbol hypotheses are not pooled. Candidate, feature, +date, and regime diagnostics beyond the endpoints above are secondary and are +reported without selective omission. + +## Stability and failed-result reporting + +The run must publish, by symbol and date: + +- row counts, UTC bounds, class balance, and all exclusions/censoring; +- prior and selected-model proper scores and paired loss differences; +- feature distribution stability using bins fitted on the training date only; +- validation, primary-test, and replication-test direction consistency; +- every declared model candidate's validation score; +- explicit `supported`, `mixed`, `failed`, or `insufficient_data` status. + +No date or instrument may disappear because its result is unfavorable. Any +aggregate row must be accompanied by its component date rows. + +If primary or replication normalization, completeness validation, or data +quality fails after the aggregate lock is durable, the run stops at the first +deterministic failure and publishes immutable `INSUFFICIENT_DATA` terminal +evidence. That evidence binds the same protocol/config, clean Git revision, raw +acquisition manifest, development normalized manifest, per-symbol locks, and +aggregate lock; it records the failing symbol/date/role, typed reason, retained +partial evidence hashes, and which later members remained unopened. It contains +no endpoint result. Its checksum manifest and terminal marker are written last, +and publication uses a new atomic target followed by directory durability. + +The same run identity may only verify and reuse that terminal evidence. It may +not overwrite or delete it, reopen candidate selection, substitute an input, +replace a date, relax quality, or continue with a partial aggregate. A source +fix has a different clean Git revision and therefore a different run identity; +it still cannot erase the original failed evidence. A failure before locking is +also reported as `INSUFFICIENT_DATA`, but it cannot create a test-evaluation +bundle or claim that held-out data was opened under a lock. + +## Explicit exclusions and promotion boundary + +Aggregate trades contain no contemporaneous bid/ask, depth, cancellation, +queue, or local receipt clock. Therefore this study must serialize execution, +fills, P&L, fees-to-alpha conversion, and capacity as `NOT_RUN`. It cannot +promote a book, fill, latency, execution, or profitability claim. + +`FULL_DATA` means only that every byte of every predeclared daily trade archive +was verified and included for this narrowly defined trade-only study. It does +not mean full market observability, external validity, or deployable evidence. +The overall M8 milestone remains incomplete until a separately frozen protocol +has at least two nonoverlapping, continuous, contemporaneous L2 capture periods +per reported interval and connects their gap-safe book states to causal research +and execution artifacts. + +## Required immutable outputs + +The atomic final bundle must contain the frozen protocol and machine spec, +per-symbol and aggregate analysis locks, raw acquisition manifest, development +and final normalized manifests, exact official `CHECKSUM` responses and +sidecars, exact exchange metadata responses and sidecars, per-date quality +summary, research/evaluation frames, predictions, candidate comparison, paired +hypothesis artifact, feature stability, generated report/memo/table, resolved +configuration, and a clean real Git revision/source-tree identity. The final +manifest binds all of those exact bytes and hashes. The checksum manifest and +`_SUCCESS` are written last only after atomic publication and directory +durability. Corruption, input relocation without matching bytes, a dirty, +unborn, synthetic, or different source identity, or any incomplete date must +fail verification and reuse. diff --git a/Microstructure/docs/PROJECT_PLAN.md b/Microstructure/docs/PROJECT_PLAN.md new file mode 100644 index 0000000000000000000000000000000000000000..6f96181a0f05a413ac41c3ced2f808cd8690ebc2 --- /dev/null +++ b/Microstructure/docs/PROJECT_PLAN.md @@ -0,0 +1,135 @@ +# Project plan + +## Objective + +Answer, with defensible event-time evidence, when order-flow imbalance and +liquidity conditions predict short-horizon price movement, and how much apparent +value remains after fees, latency, fill uncertainty, adverse selection, and +inventory constraints. The system is research-only and has no live-order path. + +## Delivery strategy + +The first deliverable is one narrow, fully reproducible vertical slice. Broader +market coverage and more sophisticated models follow only after its contracts, +timing, and execution accounting are tested. + +| Milestone | State | Depends on | Deliverable | Acceptance evidence | +|---|---|---|---|---| +| M0 Repository contract | Complete | None | Instructions, plan, decisions, status, packaging | Required files exist; Python 3.12 environment installed; config/provenance tests, Ruff, and mypy pass | +| M1 Event data foundation | Complete | M0 | Binance trade adapter, optional L2 collector, schemas, manifest/checksum, partitioned Parquet | Mocked retries/metadata/pagination; UTC/schema and content-addressed storage tests pass | +| M2 Book and quality controls | Complete | M1 | Snapshot/delta replay, sequence validation, quality findings | Gap, overlap, crossed-book, duplicate, ordering, invalid value, spread, silence, and clock tests pass | +| M3 Leakage-safe dataset | Complete | M1-M2 | Trade-flow/book features and future labels | Causal lineage, future-label, censoring, and gap-isolation tests pass | +| M4 Model evaluation | Complete | M3 | Baseline, logistic/regularized linear, tree; purged walk-forward evaluation | Prior/unpenalized/L2/tree ladder, calibration, bootstrap, purge, and OOT tests pass | +| M5 Execution research | Complete | M3-M4 | Market/limit fills, latency, partial fills, costs, inventory, liquidation, sensitivity | Deterministic accounting, OOS, volume-conservation, continuity, partial-fill, and liquidation tests pass | +| M6 Reproducible vertical slice | Complete | M1-M5 | One CLI-driven sample run and machine-readable artifacts | Atomic producer and corruption/idempotence tests pass; canonical smoke requires no network | +| M7 Research communication | Complete | M6 | Generated technical report/table, IC memo, limitations, dashboard, portfolio material | Render/dashboard tests read only verified artifacts and visibly label evidence tier | +| M8 Broader empirical study | In progress | M6-M7 | Closed trade-only study plus complete software for the replacement four-date live-L2 capture/analysis campaign | Canonical trade and superseded L2-v1 authorities remain immutable; capture Aug 10--13 under one new campaign authority, publish the Aug 10/11 `LOCKED` or `NOT_CREATED` development authority before Aug 12, and publish a recursively verified result or protocol-declared insufficiency | + +## First vertical slice + +```text +small documented event fixture + -> normalized partitioned Parquet + manifest + -> explicit data-quality findings + -> causal trade-flow / liquidity-state features + -> strictly future return and direction labels + -> purged walk-forward baseline, logistic, and tree models + -> latency- and cost-aware simulation + -> JSON/CSV/Markdown run artifacts and dashboard inputs +``` + +The offline fixture is an explicitly synthetic smoke test for software +reproducibility, not empirical market evidence. `make download-sample` adds a +small public-data path without making the test suite depend on network access. + +## Dependencies + +- Python 3.12; Polars/PyArrow for bounded-memory transformation and Parquet. +- DuckDB for partition inspection and aggregation. +- scikit-learn for transparent, CPU-friendly models and calibration. +- pytest, Ruff, and mypy for verification. +- Streamlit for a local read-only research dashboard. +- Public Binance market-data endpoints only; no API key or account connection. + +## Risks and mitigations + +| Risk | Consequence | Mitigation / acceptance test | +|---|---|---| +| Snapshot/delta mismatch or sequence gap | Corrupt book state and false imbalance | Halt the affected segment, emit a finding, require a new snapshot; replay gap tests | +| Exchange timestamp is not local observability | Optimistic latency and feature timing | Retain event and receipt times; model configurable decision/order latency | +| Trade-only fixture cannot identify queue dynamics | Fill estimates are assumption-driven | Label fill results as proxy-based; keep book model interface separate | +| Overlapping horizons leak across folds | Inflated validation estimates | Purge by label end time plus optional embargo; boundary tests | +| Small/nonstationary sample | Unstable or meaningless inference | Report uncertainty and evidence tier; defer economic claims until M8 | +| Class imbalance/calibration drift | Misleading probabilities | Persist class rates, Brier/log loss, calibration diagnostics by fold/regime | +| Fee/latency/fill assumptions dominate P&L | Fragile strategy result | Publish assumption grid and sensitivity; never collapse it into model quality | +| Public endpoint/schema changes | Broken ingestion | Version adapter/schema, capture response metadata/checksum, contract tests | +| Memory/disk pressure | Local run failure | Byte-bounded response streams, hard retained-evidence reservations, disk-backed incremental DQ, batch Parquet, verified spill-capable scans, explicit eager guards; measure peak RSS on any successful full L2 production before promotion | +| Multiple testing | False discoveries | Predeclare core hypotheses, report all tested variants, use adjusted interpretation | +| Missed or invalid prospective L2 session | Outcome-driven replacement or false continuity | One frozen calendar and campaign identity; atomic `INSUFFICIENT_DATA`; no replacement date; require observed-interval and cross-symbol coverage gates | +| Source/runtime/root changes across the four captures | Sessions are not one prospective campaign | Root campaign authority binds config/protocol, outcome-blind nonce, canonical output-root filesystem identity, clean source/import origin, and hashed Python/platform/dependency runtime; reject drift before network access | +| Held-out L2 economic access without a development authority | Selection leakage | Verify Aug 10/11 control authorities and first persist either eight child locks plus one aggregate `LOCKED` authority or a control-only `NOT_CREATED` authority; only the `LOCKED` branch may expose Aug 12/13 frames, and its evaluator has no fit path | + +## Acceptance test matrix + +1. **Reproduction:** a clean environment follows `README.md`, runs + `make reproduce-sample`, and receives a run directory with provenance, + validation, folds, metrics, trades, sensitivities, and reports. +2. **Data:** normalization is deterministic; timestamps are UTC; manifest hashes + match bytes on disk; Parquet is partitioned by source/symbol/date. +3. **Book:** snapshot-plus-delta replay enforces side sorting, nonnegative depth, + sequence continuity, and uncrossed top of book. +4. **Timing:** deliberately shifted future values cause leakage tests to fail; + label intervals never enter feature windows or training folds. +5. **Models:** historical/majority, logistic or regularized linear, and tree models + run on identical time folds without selecting on the final test set. +6. **Execution:** fees, two latency components, fill probability/queue proxy, + partial fills, adverse selection, inventory cap, liquidation, turnover, and + size/capacity sensitivity are represented and unit tested. +7. **Reports:** model table and technical report are rendered from serialized + results; each carries data interval, config hash, manifests, and Git state. +8. **Claims:** synthetic and smoke outputs contain an explicit non-empirical + banner; no unverified profitability or significance claim is emitted. + +## Definition of done + +The objective's ten acceptance criteria have reproducible evidence for M0-M7: + +1. `README.md` provides a clean setup and reproduction path. +2. The canonical workflow is deterministic synthetic data and needs no download. +3. Snapshot/delta sequence, stale/overlap/gap, crossed-book, and invariant tests pass. +4. Feature/label lineage, strict-before joins, censoring, and deliberate leakage tests pass. +5. Unpenalized and regularized logistic models plus a shallow tree share frozen OOT folds. +6. Execution records fees, two latency stages, queue/fill uncertainty, partial fills, + adverse selection, inventory, liquidation, turnover, and size sensitivity. +7. Reports are rendered from serialized, checksum-verified outputs. +8. Run provenance records actual UTC coverage, config/input hashes, seed, runtime, + Git revision, dirty state, and exact tracked/non-ignored source-tree digest. +9. Synthetic watermarks and claim checks prevent an unverified profitability claim. +10. Limitations, evidence promotion rules, and the absence of evaluable failed + hypotheses are documented. + +Passing M0-M7 completes the portfolio-quality system and first vertical slice. +M8 remains the active empirical milestone. Its prospective calendar, +hypotheses, selection rule, untouched tests, uncertainty, failure policy, and +lock-before-open boundary are frozen in +`docs/M8_MULTIDATE_TRADE_PROTOCOL.md`. The raw-only acquirer and terminal +producer are implemented and adversarially tested. All eight full daily archives +and their official evidence are bound by one verified raw-only manifest, without +opening a CSV member during acquisition. The subsequent clean-commit economic +run reached a verified `INSUFFICIENT_DATA` terminal at the ETHUSDT training DQ +gate: no selection or held-out member access occurred, so the trade hypothesis +was not evaluated and the date/policy cannot be replaced. + +Book claims now depend on the separately frozen live-L2 campaign. The immutable +capture rules are in `docs/M8_L2_PROTOCOL.md`; the exhaustive downstream rules +and their exact source/semantic hashes are in +`docs/M8_L2_ANALYSIS_CONTRACT.md`. Remaining acceptance evidence is: the four +exact session terminals sharing one clean campaign authority; a durable +`LOCKED | NOT_CREATED` development authority before held-out access; unchanged +no-refit evaluation on the `LOCKED` branch; +generated descriptive/predictive/execution artifacts or an honest +`INSUFFICIENT_DATA` terminal; peak-RSS evidence below the local ceiling; and +clean-room reproduction. The producer, recursive verifier, CLI/Make interfaces, +self-contained authority snapshots, and external non-mutating report renderer +are implemented and covered by offline tests. The existing public sample remains +exploratory only. diff --git a/Microstructure/docs/PUBLICATION.md b/Microstructure/docs/PUBLICATION.md new file mode 100644 index 0000000000000000000000000000000000000000..df990c5e873b84a1ce4800e2424fbe462b9f04bb --- /dev/null +++ b/Microstructure/docs/PUBLICATION.md @@ -0,0 +1,29 @@ +# Publication policy + +## Approved public scope + +The Git-reachable source history is approved for public release under the MIT +License. The release includes source code, tests, configuration, documentation, +and small non-market fixtures or placeholders only. + +Ignored local exchange data, normalized and derived tables, fitted states, +ingestion authorities, generated dashboards, and run artifacts are excluded. +The detailed boundary is recorded in [DATA_POLICY.md](DATA_POLICY.md). + +## Evidence language + +- `SYNTHETIC_SMOKE` verifies software behavior only. +- `PUBLIC_SAMPLE_PARTIAL` supports bounded pipeline observations, not persistent + alpha, profitability, or capacity claims. +- The frozen trade-only M8 study ended at `INSUFFICIENT_DATA` after a predeclared + zero-warning gate failed. Selection, held-out evaluation, execution, and P&L + did not run. +- Superseded campaign calendars remain historical records and are not presented + as current authority. + +## Permanent destinations + +- Website: +- GitHub: +- Dataset mirror: +- Interactive Space: diff --git a/Microstructure/docs/PUBLIC_TRADE_PROTOCOL.md b/Microstructure/docs/PUBLIC_TRADE_PROTOCOL.md new file mode 100644 index 0000000000000000000000000000000000000000..179cbbefd560b56b4c82df90a6e567de1a6b8842 --- /dev/null +++ b/Microstructure/docs/PUBLIC_TRADE_PROTOCOL.md @@ -0,0 +1,99 @@ +# Public aggregate-trade exploratory protocol + +## Evidence status + +This protocol governs the first real-data research run built from the fixed, +capped Binance Spot aggregate-trade sample already acquired for 2024-01-02. It +is **retrospective and exploratory**, not a preregistered confirmatory study. The +data availability, per-symbol coverage, and class balance were inspected before +this document was frozen; model comparison and held-out results were not. + +Every output must retain the `PUBLIC_SAMPLE_PARTIAL` evidence tier. The run may +support a sample-specific data and predictability diagnostic, but it cannot +support a claim about persistent alpha, statistical significance, execution, +profitability, or capacity. + +## Question and hypotheses + +The narrow question is whether recently observed aggregate-trade direction and +size contain out-of-time information about the sign of the trade price 20 +aggregate trades later. + +- **H0:** the transparent model ladder does not improve held-out log loss over a + historical-prior classifier in this capped sample. +- **H1 (exploratory):** causal signed-volume and trade-imbalance features improve + held-out log loss relative to that prior. + +All tested model rows are published. The final test is not used for feature, +hyperparameter, calibration, or model selection. A favorable point estimate is +not called significant; the block bootstrap is a dependence diagnostic, not a +confirmatory p-value procedure. + +## Data and coverage policy + +- Instruments are BTCUSDT and ETHUSDT, evaluated separately because the fixed + 5,000-row caps produce different observed clock-time endpoints. +- The exact ingestion manifest and normalized part hashes are inputs to the run. +- Internal aggregate-trade IDs must be unique and step by one within each symbol; + the availability clock must not reverse. Only after those checks may the + derived research view assign one continuity epoch per symbol. Raw normalized + rows remain unchanged. +- Exchange event time is the only historical availability proxy. No local + receipt-time or colocated-latency claim is allowed. +- Tied exchange timestamps retain aggregate-trade-ID ordering and remain in the + same time split. + +## Causal feature and label contract + +At decision trade `i`, features may use trade `i` and earlier trades from the +same verified continuity epoch: + +- signed trade volume and absolute volume over 5, 20, and 100 trades; +- signed-volume imbalance over the same windows; +- trade count and event-time intensity; +- one-trade log return; +- realized trade-price volatility over 100 trades. + +The target is `1` when the trade price at `i + 20` is above the price at `i`, and +`0` otherwise. The target trade ID and availability timestamp are serialized. +Segment tails are right-censored. Feature-ready rows require the full longest +lookback. + +## Evaluation + +- Each instrument receives its own expanding time-ordered walk-forward plan. +- Configuration: 1,200 initial decision-time buckets, 400 validation buckets, + 400 final-test buckets, 400-bucket steps, and a 20-bucket embargo. +- Label information ending at or after an evaluation boundary is purged. +- The model ladder is historical prior, unpenalized logistic regression, the + declared L2 grid, and the declared shallow-tree grid. +- Selection metric is validation log loss. Calibration is trained only from the + chronological training/calibration region. +- The primary H0/H1 diagnostic is the paired difference in held-out log loss: + validation-selected model minus historical prior on identical `row_id` + observations. It uses the same seeded resample draw for both models within + each fixed, contiguous 40-trade block (twice the label horizon), separately + by instrument. Five hundred draws, the seed, row count, block count, point + difference, and percentile interval are serialized. Marginal per-model + intervals are secondary and are never compared as a substitute for the + paired loss difference. + +## Explicit exclusions + +There is no contemporaneous bid/ask, depth, cancellation, queue, or local +receipt-time history in this dataset. Therefore this run does not calculate: + +- order-book imbalance, microprice, spread, or liquidity recovery; +- limit-fill probability or queue position; +- market/limit execution, fees-to-alpha conversion, P&L, or capacity. + +Those analyses require continuous snapshot-plus-delta L2 epochs collected and +validated separately. + +## Promotion criteria + +This exploratory run cannot be promoted to `FULL_DATA`. A later confirmatory +study must freeze its protocol before model outcomes are inspected, use multiple +complete nontruncated dates, preserve adjacent untouched dates for final testing, +report per-date and cross-instrument stability, and add continuous L2 evidence +before making book-dependent or execution claims. diff --git a/Microstructure/docs/RESEARCH_PROTOCOL.md b/Microstructure/docs/RESEARCH_PROTOCOL.md new file mode 100644 index 0000000000000000000000000000000000000000..fc0594383aabb79f83c831c8d98af8f42291717d --- /dev/null +++ b/Microstructure/docs/RESEARCH_PROTOCOL.md @@ -0,0 +1,129 @@ +# Research protocol + +## Question and estimands + +The primary question is not whether a classifier can fit event data. It is +whether an order-flow or liquidity signal predicts a strictly future price state +out of time, whether that relationship is stable across symbols and regimes, and +whether its scale exceeds execution frictions under declared—not inferred—fill +assumptions. + +The primary predictive estimands are: + +1. the change in future mid-price direction probability associated with a + one-standard-deviation change in causal order-flow imbalance; +2. the conditional future log-mid return across predeclared event horizons; +3. the decay of that relationship as the horizon increases; +4. the interaction of order flow with contemporaneous spread, depth, volatility, + and trade intensity. + +Economic evaluation is a separate conditional exercise: given frozen OOS +predictions and a declared execution model, measure gross edge, explicit fees, +arrival cost, post-fill adverse selection, fill fraction, turnover, inventory, +and marked or liquidated net P&L. It is not an estimate of deployable capacity. + +## Predeclared core hypotheses + +- **H1 — Order-flow direction:** positive trailing signed flow and L1 OFI are + associated with positive strictly future mid returns, and vice versa. +- **H2 — Decay:** predictive association is strongest at short horizons and + decays rather than monotonically increasing with horizon. +- **H3 — Liquidity interaction:** a given flow shock has larger price impact when + displayed depth is low or relative spread/volatility is high. +- **H4 — Recovery:** after a large signed trade or spread/depth shock, liquidity + recovery time varies with the pre-shock volatility/liquidity regime. +- **H5 — Stability:** effect direction is not assumed transferable; BTCUSDT and + ETHUSDT are reported separately before any pooled conclusion. + +Rejecting or failing to support a hypothesis is a valid result and belongs in +the generated report. Synthetic smoke data cannot support or reject any market +hypothesis; it can only verify that the estimands and controls are computed. + +## Descriptive analysis contract + +The run producer persists intraday liquidity, OFI/return association, signal +decay and half-life, event-time signed impact, large-trade impact, liquidity +recovery, market regimes, model diagnostics by regime, cross-instrument effect +stability, and train-versus-test feature stability. Large-trade, shock, recovery, +and regime thresholds are fitted on the final training rows only and serialized. +These outputs carry `descriptive_only=true`; synthetic values cannot support or +reject the hypotheses above. + +## Information set + +A decision sample is keyed by `(available_ts_ns, sequence, event_id)` within a +continuous segment. A source timestamp is only an availability proxy unless a +local receipt timestamp exists. Features use observations whose availability key +is no later than the decision key. Labels start after the decision and end at +their persisted information-end key. No feature, label, or fold crosses a known +feed gap. + +Tied observations from different streams have no assumed causal ordering unless +the source supplies one. As-of joins therefore use the last strictly observable +state. Missing future targets are right-censored; they are never filled with the +last observation. + +## Evaluation protocol + +- Splits follow global UTC/event order with expanding training windows. +- Training observations whose label interval overlaps the next evaluation + boundary are purged; a configured embargo adds separation. +- Imputation, scaling, regime thresholds, feature selection, calibration, and + hyperparameter choice use training/calibration/validation data only. +- The final held-out period is evaluated once after model choice is frozen. +- Baseline, unpenalized/regularized linear, and shallow tree models share the same + features, folds, and final test observations. +- Classification reporting includes class support, log loss, Brier score, + ROC-AUC when defined, accuracy/balanced accuracy, and calibration diagnostics. +- Return models, when supported, report MAE and rank correlation without treating + statistical fit as tradable value. +- Dependent uncertainty uses contiguous event or UTC-day blocks. Fewer than two + independent blocks produces an `insufficient_blocks` result rather than a + confidence interval. + +## Multiple testing and model selection + +The core family is the two symbols × predeclared horizons × core OFI association. +Exploratory regimes, feature variants, model variants, and sensitivity grids are +reported as exploratory and are not promoted to confirmatory evidence. Where +p-values are later added for a full-data study, false-discovery-rate adjustment +is applied within the declared family and both raw and adjusted values are kept. + +Models are selected on aggregate validation log loss (classification) or MAE +(regression). Prefer the simpler model when performance is statistically +indistinguishable under the predeclared rule. The final test cannot change the +model, signal threshold, calibration, size, latency, or fee assumption. + +The frozen trade-only public protocol is narrower and is specified separately +in `docs/PUBLIC_TRADE_PROTOCOL.md`. It evaluates each symbol independently and +uses the same held-out rows and identical contiguous bootstrap draws for the +validation-selected model-minus-historical-prior log-loss difference. Marginal +model intervals are not substituted for that paired estimand. Because the input +has no contemporaneous book, execution, fill, P&L, and capacity artifacts are +serialized as `NOT_RUN`, not zero. + +## Execution scenarios + +Base market orders use the book observable at order-arrival time after separate +decision and order latencies. Available L1 depth caps fills; missing deeper depth +is not extrapolated. Passive orders join behind a declared queue proxy, fill only +against eligible opposing printed flow, can fill partially, and remain exposed +during cancel latency. Maker/taker fees, inventory caps, and end liquidation are +explicit. + +Latency, queue position, cancellation ordering, and endogenous impact are not +identified by archived exchange data. They are scenario inputs and must be shown +as sensitivity axes. A strategy that works only under the most favorable fill or +latency scenario fails the economic robustness test. + +## Promotion criteria for empirical claims + +No market conclusion may appear in “main findings” until a manifested public or +institutional data run has: + +- at least two non-overlapping UTC dates per reported confidence interval; +- a frozen final test period not used for selection; +- acceptable sequence/data-quality coverage for every book-based feature; +- results for both default instruments or an explicit single-instrument scope; +- cost/latency/fill sensitivity and failed-hypothesis disclosure; +- a clean evidence label, config hash, input checksums, and Git state. diff --git a/Microstructure/portfolio/interview_story.md b/Microstructure/portfolio/interview_story.md new file mode 100644 index 0000000000000000000000000000000000000000..b28ae744a0cc826db5773006fc1ecc3a0e2a90b6 --- /dev/null +++ b/Microstructure/portfolio/interview_story.md @@ -0,0 +1,125 @@ +# Interview story: Order Flow to Price Impact + +> **Historical calendar note (2026-08-23):** Any Aug 8–11 live-L2 schedule in +> this narrative is superseded by the v2 Aug 10–13 protocol recorded in the +> README and `docs/M8_L2_ANALYSIS_CONTRACT.md`. It is retained as research +> history, not current campaign authority. + +## One-sentence version + +I designed a reproducibility-first market-microstructure research system that +keeps leakage-safe prediction, execution assumptions, and simulated performance +separate—and refuses to turn synthetic smoke output into an alpha claim. + +## The problem + +Short-horizon market prediction is unusually easy to overstate. Events are +serially dependent, labels overlap, exchange time is not necessarily receipt +time, and an accurate forecast can still be untradeable after spread, fees, +latency, queue uncertainty, adverse selection, and inventory liquidation. Public +data also varies in depth and quality, while the target machine has 16 GB of RAM +and no paid data feed. + +The research question therefore had two parts: under what observable conditions +does order flow predict a future price change, and how much of that relationship +survives a separately specified execution model? + +## My approach + +I organized the project around immutable event and run contracts rather than a +large notebook. Raw observations remain unchanged. Normalized timestamps and +sequence identifiers make ordering explicit. Features stop at decision event +`t`; labels begin after `t`. Time-ordered folds purge overlapping label horizons +and apply an embargo before held-out evaluation. + +The model ladder begins with a historical or majority baseline, then transparent +linear and regularized alternatives, followed by bounded nonlinear models. The +execution layer records fees, two latency components, fill and queue proxies, +partial fills, adverse selection, inventory limits, liquidation, turnover, and +size sensitivity independently of predictive metrics. + +Each run freezes its resolved configuration, input checksums, actual UTC period, +random seed, runtime, and Git state. Reports and the read-only Streamlit dashboard +consume that bundle; they cannot retrain a preferred model. Synthetic input +forces a prominent software-test watermark everywhere. + +## A difficult design choice + +The initial compact data path may contain trades without complete historical +depth. It would have been easy to present a precise-looking queue simulator, but +the data cannot identify true queue priority. I treated queue position and fills +as explicit assumptions, kept the interface replaceable by later Level-2 data, +and made sensitivity—not a single fill estimate—the relevant output. + +That decision reduced the apparent sophistication of the first result while +making the inference more honest. + +## Verification strategy + +The offline smoke path is deterministic and network-free. Focused tests cover +bundle completion, checksum integrity, evidence-tier consistency, synthetic +watermarks, held-out-only comparison tables, deterministic rendering, and clear +dashboard failures for incomplete runs. Research tests separately target event +ordering, leakage, purged folds, fee accounting, latency, partial fills, and +inventory constraints. + +## What the empirical work actually produced + +The capped public trade sample remained exploratory and explicitly skipped +execution because it had no contemporaneous book. The predeclared full-archive +trade study then produced a useful negative operational result: BTCUSDT training +data passed, while ETHUSDT training data produced 53 long-silence warnings +against a zero-warning gate. The pipeline published a checksummed +`INSUFFICIENT_DATA` terminal before selection and before either held-out date was +opened. I did not relax the rule, substitute a date, or describe the absence of +a model result as a failed market hypothesis. + +For the book extension I froze four simultaneous BTCUSDT/ETHUSDT sessions and a +field-complete analysis contract before capture. The implementation binds all +dates to one outcome-blind campaign, clean source/import/runtime identity, and +canonical storage root; limits features and labels to verified observed +intervals; locks the Aug 8/9 development state before Aug 10/11; and provides +no-refit evaluation and market-only scenarios. The final producer recursively +verifies explicit path and digest authorities, snapshots them into an immutable +terminal, and renders reports externally without changing the run. Those are +software controls, not empirical L2 evidence: at the pre-capture source freeze, +no declared L2 result had been promoted. Tracked source remains unchanged during +the four-session campaign; immutable session/final bundles carry live status. + +## Evidence boundary + +No empirical economic result is claimed merely because a pipeline ran. A +synthetic smoke run proves only that the software contracts and accounting +execute as intended. The bounded public trade run supports exploratory, +interval-specific diagnostics but no execution or broad claim. The canonical +full-archive result supports only data insufficiency because evaluation never +began. Generalization still requires valid adjacent periods, both instruments, +regimes, uncertainty, and transparent failed hypotheses. + +## What I would do next + +I would operate the completed producer on the already-frozen Aug 8--11 sessions +without changing their calendar or analysis contract, then complete the +clean-room and peak-memory audits on the resulting terminal. Aug 8/9 choices +must be durably locked before Aug 10/11 data is exposed. I would accept a missed +or invalid session as `INSUFFICIENT_DATA`, not search for a replacement. Only +after stable no-refit evidence would I consider point-process models; the +criterion for complexity would be out-of-time economic evidence, not an improved +in-sample score. + +## Likely follow-up questions + +**Why not random cross-validation?** It mixes regimes and leaks information across +overlapping future horizons. Walk-forward folds better match deployment order. + +**Why report calibration?** Thresholded execution decisions consume +probabilities, so ranking alone is insufficient. Miscalibration changes trade +frequency, inventory, and cost exposure. + +**What would make you stop?** Leakage, an invalid book reconstruction, failure on +the untouched period, instability without an economic explanation, or economics +that require implausible fills or latency. + +**What makes this portfolio-quality?** The result is auditable: assumptions, +failures, provenance, and evidence boundaries are first-class artifacts rather +than caveats added after seeing performance. diff --git a/Microstructure/portfolio/resume_bullets.md b/Microstructure/portfolio/resume_bullets.md new file mode 100644 index 0000000000000000000000000000000000000000..d6f644e72203b17016c8c2d955267ffd75bd0a33 --- /dev/null +++ b/Microstructure/portfolio/resume_bullets.md @@ -0,0 +1,26 @@ +# Resume bullet variants + +These bullets intentionally make no unverified claim about alpha, profitability, +statistical significance, throughput, or data volume. Add a measured result only +after a checksum-verified public-data run supports it. + +## Research-focused + +- Designed a leakage-aware event-time market-microstructure study of order-flow + imbalance, liquidity state, future price impact, and recovery, using purged + walk-forward evaluation, calibrated baselines, uncertainty, and explicit + evidence tiers to separate synthetic tests from empirical findings. + +## Quant-trading-focused + +- Built a research-only signal-to-execution framework that separates predictive + diagnostics from fee-, latency-, fill-, adverse-selection-, inventory-, and + liquidation-aware simulation, with gross-to-net and capacity sensitivities + designed to falsify fragile short-horizon strategies. + +## Data-engineering-focused + +- Engineered a reproducible Python 3.12 microstructure platform around typed + configuration, immutable manifests, UTC event ordering, partitioned columnar + data, checksummed run bundles, deterministic reports, and a read-only Streamlit + dashboard suitable for bounded-memory local analysis. diff --git a/Microstructure/portfolio/ten_minute_presentation_outline.md b/Microstructure/portfolio/ten_minute_presentation_outline.md new file mode 100644 index 0000000000000000000000000000000000000000..893926f4b67c2eede8ad94f4aa221bbe147ba119 --- /dev/null +++ b/Microstructure/portfolio/ten_minute_presentation_outline.md @@ -0,0 +1,89 @@ +# Ten-minute presentation outline + +> **Historical calendar note (2026-08-23):** Any Aug 8–11 live-L2 schedule in +> this outline is superseded by the v2 Aug 10–13 protocol recorded in the +> README and `docs/M8_L2_ANALYSIS_CONTRACT.md`. It is retained as research +> history, not current campaign authority. + +## 0:00–0:50 — The question and the trap + +- Ask when order-flow imbalance and liquidity predict a strictly future move. +- Then ask whether the effect survives costs and uncertain execution. +- State the central trap: predictability, executability, and profitability are + different claims. + +## 0:50–1:50 — Evidence hierarchy + +- `SYNTHETIC_SMOKE`: software behavior only. +- `PUBLIC_SAMPLE_PARTIAL`: fixed interval, limited inference. +- `FULL_DATA`: broader manifested study, still simulated and venue-specific. +- `INSUFFICIENT_DATA`: a declared gate prevented evaluation; no missing estimate + is replaced with zero or a substitute date. +- Pre-capture source-freeze status: synthetic vertical slice and bounded public trade + study completed at their stated tiers; full-archive trade M8 stopped on 53 + ETHUSDT training warnings before selection or held-out access; no performance + claim and no promoted L2 result. + +## 1:50–3:05 — Event-driven data architecture + +- Public trades and optional Level-2 snapshot/delta adapters. +- UTC nanoseconds plus sequence/event identifiers establish stable order. +- Streaming normalization and partitioned Parquet keep memory bounded. +- Manifests retain source, actual period, schema version, row counts, and hashes. + +## 3:05–4:15 — Data quality and leakage controls + +- Detect duplicates, ordering and sequence gaps, crossed books, invalid values, + abnormal spreads, silence, and clock discontinuities without silent repair. +- Features use observations available through decision event `t`; labels start + after `t`. +- Use expanding walk-forward folds with purge and embargo for overlapping labels. + +## 4:15–5:30 — Economic features and model ladder + +- Spread, depth, OFI, queue imbalance, microprice, signed volume, intensity, + volatility, impact, recovery, and regimes when observable. +- Compare historical/majority, linear or logistic, regularized, and tree models. +- Select on validation only; report calibration and uncertainty on held-out data. + +## 5:30–6:55 — From prediction to execution + +- Keep model metrics and execution artifacts separate. +- Record maker/taker fees, decision and order latency, market versus limit fills, + queue proxy, partial fills, adverse selection, inventory cap, and liquidation. +- Show gross-to-net and fee/fill/latency/size sensitivity rather than one favored + P&L number. + +## 6:55–8:05 — Reproducibility and reporting + +- One frozen run bundle records resolved config, input hashes, actual UTC period, + seed, runtime, Git commit or `UNBORN`, and dirty state. +- Checksums plus exact `_SUCCESS` or typed `INSUFFICIENT_DATA` markers prevent + readers from treating partial output as a terminal bundle. +- Technical report, model table, IC memo, and Streamlit app read frozen artifacts; + they do not retrain or backfill missing metrics. +- The four-date L2 path adds an outcome-blind campaign/runtime/storage identity, + explicit session/lock/run digests, recursive verification, and external report + rendering that never mutates the empirical bundle. + +## 8:05–9:10 — What would count as evidence? + +- Stable held-out effect across BTCUSDT and ETHUSDT, adjacent periods, and regimes. +- Calibration and uncertainty, not ROC-AUC alone. +- Net economics robust to defensible fees, latency, fills, and liquidation. +- Transparent failures and multiplicity-aware interpretation. +- For frozen L2: one clean campaign identity, valid simultaneous observed + intervals, and an Aug 8/9 `LOCKED | NOT_CREATED` development authority that + predates all Aug 10/11 access; only `LOCKED` permits economic-frame access. + +## 9:10–10:00 — Limitations and next experiment + +- Public event time, queue visibility, hidden liquidity, and venue generalization + remain limitations. +- Next: use the completed frozen L2 producer to capture only the Aug 8--11 + simultaneous sessions, then run all four horizons without refit or a + replacement date and complete peak-memory/clean-room verification. Market-only + scenarios are not realized execution; capacity and profitability claims + remain forbidden. +- Close with the governance boundary: research and simulation only; no live-order + path. diff --git a/Microstructure/project.yaml b/Microstructure/project.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e14d90cb1dcb38c13c191e9ed9ea1391000fb9d3 --- /dev/null +++ b/Microstructure/project.yaml @@ -0,0 +1,45 @@ +title: Order Flow to Price Impact +slug: microstructure +summary: Reproducibility-first market-microstructure research that separates data quality, leakage-safe prediction, execution assumptions, and simulated outcomes. +research_question: When do order-flow imbalance, liquidity, and limit-order-book conditions predict short-horizon price movement, and which claims survive predeclared data-quality and execution gates? +why_it_matters: Short-horizon market research is easy to overstate. The project makes observability, temporal leakage, data gaps, fees, latency, uncertain fills, adverse selection, and inventory risk explicit before any economic claim is promoted. +research_fields: + - Market microstructure + - Quantitative finance + - Time-series machine learning +project_type: empirical-research-system +status: public-live +authors: + - Repository owner and maintainer +original_source: Microstructure workspace project +original_sample_period: Public BTCUSDT and ETHUSDT market-data studies use fixed UTC intervals declared in their protocols; deterministic synthetic fixtures exercise the software path. +updated_sample_period: The published source snapshot includes the frozen trade-only M8 terminal and the replacement live-L2 protocol through the current repository HEAD. +data_sources: + - Binance Spot public aggregate-trade endpoints and official archive metadata + - Optional public live diff-depth and REST snapshots for locally captured L2 sessions + - Deterministic synthetic fixtures for software verification +data_license: No exchange raw observations, normalized events, derived tables, fitted models, or generated run bundles are redistributed. Users obtain public market data independently under provider terms; see docs/DATA_POLICY.md. +code_license: MIT +reproduction_command: make reproduce-sample +expected_runtime: The deterministic synthetic vertical slice is suitable for a local laptop. Public-data and live-L2 studies require independent acquisition, explicit immutable authorities, and substantially more storage and compute. +outputs: + - src/ + - tests/ + - configs/ + - reports/ + - dashboard/ + - docs/ +github_url: https://github.com/YangXiaoShawn/open-economic-quant-microstructure +site_url: https://yangxiaoshawn.github.io/projects/microstructure/ +dataset_url: https://huggingface.co/datasets/ShawnChamberlain/open-economic-quant-research-data/tree/main/Microstructure +space_url: https://huggingface.co/spaces/ShawnChamberlain/open-economic-quant-research-observatory +last_updated: 2026-08-23 +limitations: The public package contains code and documentation, not exchange observations or generated run bundles. Synthetic results are software evidence only. The full-archive trade study terminated at a predeclared data-quality gate, so it published no prediction, execution, profit, capacity, or significance claim. +catalog: + field: market-microstructure + accent: violet + tags: + - Market Microstructure + - Order Flow + - Reproducible Research + metric: Predeclared evidence gates diff --git a/Microstructure/pyproject.toml b/Microstructure/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..4b286cd473df48c7bbd1970e9aadb28e87722a23 --- /dev/null +++ b/Microstructure/pyproject.toml @@ -0,0 +1,62 @@ +[build-system] +requires = ["hatchling>=1.27"] +build-backend = "hatchling.build" + +[project] +name = "event-driven-microstructure" +version = "0.1.0" +description = "Research-only event-driven order-flow and price-impact platform" +readme = "README.md" +requires-python = ">=3.12" +license = { text = "MIT" } +authors = [{ name = "Microstructure Research Project" }] +dependencies = [ + "duckdb>=1.1,<2", + "numpy>=2,<3", + "polars>=1.20,<2", + "pyarrow>=18,<24", + "requests>=2.32,<3", + "scikit-learn>=1.5,<2", + "streamlit>=1.40,<2", + "websockets>=14,<17", +] + +[project.optional-dependencies] +dev = [ + "mypy>=1.13,<2", + "pytest>=8.3,<10", + "pytest-cov>=6,<8", + "ruff>=0.8,<1", + "types-requests>=2.32,<3", +] + +[project.scripts] +microstructure = "microstructure.cli:main" + +[tool.hatch.build.targets.wheel] +packages = ["src/microstructure"] + +[tool.pytest.ini_options] +addopts = "-ra --strict-markers --strict-config" +testpaths = ["tests"] +markers = [ + "integration: exercises more than one package boundary", +] + +[tool.ruff] +target-version = "py312" +line-length = 100 +src = ["src", "tests", "dashboard"] + +[tool.ruff.lint] +select = ["E", "F", "I", "B", "UP", "SIM", "RUF"] +ignore = ["E501"] + +[tool.ruff.lint.per-file-ignores] +"tests/**/*.py" = ["S101"] + +[tool.mypy] +python_version = "3.12" +strict = true +packages = ["microstructure"] +warn_unreachable = true diff --git a/Microstructure/reports/executive_memo.md b/Microstructure/reports/executive_memo.md new file mode 100644 index 0000000000000000000000000000000000000000..8e2646948f1a6d03cd3f62f50897662bdd57388c --- /dev/null +++ b/Microstructure/reports/executive_memo.md @@ -0,0 +1,95 @@ +# Investment committee research memo + +> **STATUS: SOURCE-CONTROLLED GOVERNANCE MEMO — RUN-SPECIFIC MEMOS ARE GENERATED BY CODE** + +> **Historical calendar note (2026-08-23):** Any Aug 8–11 live-L2 schedule in +> this memo is superseded by the v2 Aug 10–13 protocol recorded in the README +> and `docs/M8_L2_ANALYSIS_CONTRACT.md`. It is retained as research history, not +> current campaign authority. + +## Page 1 — Decision and current evidence + +**Recommendation:** Continue research construction only. Authorize no capital +allocation, live trading, or connection to an account capable of placing orders. + +**Decision requested.** The proposed research asks whether order-flow imbalance +and liquidity state forecast short-horizon price movements and, separately, +whether any measured effect can survive realistic implementation frictions. The +decision today is not whether to trade a strategy. It is whether the research +design is sufficiently falsifiable, reproducible, and execution-aware to finish +the frozen four-session live-L2 campaign without changing its specification. + +**Current evidence.** The completed synthetic vertical slice supports a software +reproducibility claim only. The bounded public acquisition supports a data- +pipeline observation plus exploratory per-symbol diagnostics only: both symbol +ranges reached their declared row cap, and execution was `NOT_RUN`. The complete- +archive trade study reached a valid `INSUFFICIENT_DATA` terminal when ETHUSDT +training normalization produced 53 warnings against a zero-warning gate. +Selection never started and neither held-out date was opened. This is a supported +data-insufficiency conclusion, not an economic-model result. There is no +supported simulated return, capacity, profitability, or statistical-significance +claim. This source document therefore contains no substituted performance +figures; run-specific memos are rendered from frozen artifacts. + +**Required analytical separation.** The work will preserve three distinct layers. +First, predictive quality asks whether features observable at decision time +forecast strictly future labels on time-ordered held-out data. Second, economic +stability asks whether the relationship persists across horizons, instruments, +and liquidity or volatility regimes. Third, execution research applies fees, +spread, decision and order latency, uncertain or partial fills, adverse +selection, inventory constraints, liquidation, turnover, and size sensitivity. +Success in one layer does not establish success in another. + +**Evidence standard.** Model selection must use training and validation periods, +with purging and embargo where labels overlap. Final test results remain untouched +until specifications are fixed. Reports must identify every tested model or +sensitivity relevant to interpretation, include uncertainty, and avoid presenting +an isolated favorable specification. Every published number must trace to a +checksum-verified bundle containing actual UTC coverage, configuration and input +hashes, code state, and evidence tier. + +
+ +## Page 2 — Risks, kill criteria, and next evidence + +**Principal risks.** Exchange timestamps may not represent local observability. +Public trade data may be adequate for signed-flow research but cannot reveal true +queue position, hidden liquidity, or cancellation priority. Snapshot and delta +gaps can corrupt reconstructed books. A short or selected interval can confound +signal with regime. Repeated features, horizons, and thresholds create +multiple-testing risk. Fee, latency, fill, and liquidation assumptions can +dominate simulated results. Venue-specific cryptocurrency behavior may not +generalize to institutional instruments or other matching engines. + +**Controls.** Preserve raw events; emit validation findings without silent repair; +make ordering and label boundaries explicit; persist fold definitions; compare +against simple baselines; calibrate probabilities; report bootstrap intervals; +and show results by regime and instrument. Execution assumptions must be +configuration-controlled and shown alongside gross-to-net attribution. The +dashboard must read frozen, bounded artifacts and cannot trigger trading or +recompute a preferred result. The four L2 sessions must share one clean +campaign, runtime/import fingerprint, and canonical storage-root identity. Every +development/final command consumes explicit path plus manifest/checksum/lock +authorities. Reports are re-rendered outside the immutable run only after +recursive verification. + +**Kill criteria.** Do not escalate the research if a result depends on future +information, fails sequence or checksum validation, disappears on the untouched +test period, reverses across instruments or adjacent periods without an economic +explanation, requires implausibly favorable latency or fills, or fails to remain +competitive with the declared baseline after recorded costs. A high predictive +score without calibration or executable economics is also insufficient. + +**Next evidence requested.** Preserve the trade insufficiency terminal without a +replacement date or relaxed quality rule. Use the completed frozen +BTCUSDT/ETHUSDT live-L2 software path to collect only the declared Aug 8--11 UTC +sessions under one clean campaign identity. Publish every session gate and +quality exception; lock Aug 8/9 model, regime, calibration, and execution- +reference state before either Aug 10/11 frame is opened; then publish all +predeclared horizons, dependency-block uncertainty, equal-session stability, +market-only sensitivity scenarios, failed hypotheses, and remaining +limitations—or publish `INSUFFICIENT_DATA` if a declared gate fails. At this +pre-capture source freeze, no L2 data or metric had been promoted; the tracked +memo remains unchanged during the campaign. Only after those checks should the +committee consider broader research. Live deployment remains outside scope +regardless of the outcome. diff --git a/Microstructure/reports/methodology_limitations.md b/Microstructure/reports/methodology_limitations.md new file mode 100644 index 0000000000000000000000000000000000000000..69ba3720fb1998a74103f4a70dcb14aa0a0fd2d8 --- /dev/null +++ b/Microstructure/reports/methodology_limitations.md @@ -0,0 +1,189 @@ +# Methodology and limitations + +> **Historical calendar note (2026-08-23):** Any Aug 8–11 live-L2 schedule in +> this document is superseded by the v2 Aug 10–13 protocol recorded in the +> README and `docs/M8_L2_ANALYSIS_CONTRACT.md`. It is retained as research +> history, not current campaign authority. + +## Evidence tiers + +- `SYNTHETIC_SMOKE` verifies deterministic software behavior only. Its values are + neither market observations nor investment evidence. +- `PUBLIC_SAMPLE_PARTIAL` describes a fixed, bounded public-data interval. It may + support interval-specific research observations but not broad generalization. +- `FULL_DATA` is reserved for a manifested empirical study meeting its declared + coverage and acceptance tests. It still represents research and simulation, + not realized live performance. +- `INSUFFICIENT_DATA` is a terminal evidence status, not a lower-quality set of + model estimates. It means a predeclared input or quality gate prevented the + required evaluation; absent predictions and execution fields remain absent + rather than being imputed, rerun on replacement dates, or reported as zeros. + +Evidence tier is derived from data manifests. A synthetic source cannot be +promoted by changing a report label. + +## Time and observability + +All reported intervals are UTC. Stable event ordering uses the normalized event +timestamp plus sequence and event identifiers; tied timestamps are not reordered +arbitrarily. Exchange event time is not automatically equivalent to local receipt +time. A feature at decision event `t` may contain only values observable at or +before `t`; its label begins strictly after `t`. Decision and order latency are +separate assumptions. + +Time-ordered evaluation is necessary but not sufficient. When label intervals +overlap a fold boundary, affected training rows must be purged. Configured embargo +separates adjacent folds. The final test period is not used for model selection, +feature selection, hyperparameter tuning, threshold choice, or probability +calibration. + +## Data lineage and quality + +External raw data is immutable and excluded from Git. Each download or fixture +requires a source, retrieval time or deterministic generation rule, requested and +observed period, schema version, row count, and checksum. Normalization and later +exclusions create new artifacts rather than rewriting raw observations. + +Validation covers duplicates, out-of-order timestamps, missing sequence ranges, +crossed books, nonpositive price or quantity, abnormal spread, long silence, and +clock discontinuities. A warning does not prove an observation is harmless. A +fatal gap can require abandoning an affected reconstruction segment rather than +interpolating it. + +Public endpoints can change schema, retention, throttling, or geographic +availability. Download success does not establish completeness. Exchange +maintenance, symbol-rule changes, clock behavior, delistings, and missing markets +can bias a selected sample. + +The canonical full-archive trade M8 result illustrates this boundary. BTCUSDT +training normalization completed on 2,071,461 rows with no findings. ETHUSDT +training normalization completed on 987,297 rows with zero errors but 53 long- +silence warnings, violating the frozen zero-warning gate. Selection did not +start, neither held-out date was opened, and execution was not run. This supports +the conclusion that the declared trade study was data-insufficient; it neither +supports nor refutes the economic hypothesis. Relaxing the warning rule or +choosing another date after seeing that terminal would invalidate the protocol. + +## Market-state and feature measurement + +Order-flow imbalance, signed volume, intensity, spread, depth, queue imbalance, +microprice, volatility, price impact, liquidity recovery, and regime features are +conditional on the event types actually observed. Trade signing can be wrong. +Displayed depth can be cancelled before execution. Aggregated or trade-only data +cannot identify hidden orders, matching-engine priority, or individual queue +position. Cancellation intensity is unavailable unless the feed exposes enough +book history to measure it defensibly. + +Feature windows create serial dependence, and overlapping future labels reduce +effective sample size. Intraday and volatility regimes may be unbalanced. A +relationship can reflect a common response to news rather than a causal effect of +order flow on price. + +## Statistical modeling + +Simple historical or majority baselines anchor the model ladder. Linear and +regularized models provide interpretable comparisons; a tree model tests bounded +nonlinearity. More complex time-series or point-process models require a stated +economic reason and evidence that simpler models leave meaningful structure. + +ROC-AUC alone can obscure calibration and class imbalance. Classification reports +should include log loss, Brier score, precision-recall diagnostics where useful, +class rates, and calibration. Regression reports require scale-aware errors and a +baseline comparison. Bootstrap confidence intervals must respect temporal +dependence. Repeated instruments, horizons, regimes, features, thresholds, and +models create multiplicity; an unadjusted favorable result is exploratory. + +Model importance is not structural causality. Feature rankings can be unstable +under correlation or regime shift. A selected model may decay after the observed +period, and cryptocurrency venue behavior may not transfer to equities, futures, +or fragmented markets. + +## Execution and fills + +Predictive metrics are not execution results. Simulated economics depend on maker +and taker fees, half-spread and slippage, decision and order latency, order size, +fill probability, queue proxy, partial fills, adverse selection, inventory cap, +liquidation, and capacity assumptions. Each assumption must be serialized and +sensitivity-tested. + +A queue proxy is not true priority. A fill inferred from subsequent traded volume +can be optimistic when cancellations, hidden liquidity, competing orders, and +matching rules are unknown. Limit-order simulations can suffer severe adverse +selection; market-order simulations can understate impact. Forced end-of-period +liquidation may dominate a short sample. Capacity extrapolation from public top-of- +book data is especially uncertain. + +Annualized return or Sharpe-like statistics are inappropriate for synthetic or +very short runs. Simulated P&L excludes operational failures, exchange outages, +funding and financing where omitted, taxes, custody, counterparty risk, and live +model drift. The project contains no order-entry path and is not a deployment +system. + +The frozen live-L2 extension narrows execution further. It permits market-order +scenarios only, with threshold, reference notional/depth, lot rounding, L1 fill +cap, inventory, liquidation, fee, and decision/order latency rules fixed before +held-out access. Latencies in this campaign are event counts, not milliseconds. +Recorded L1 limits the scenario fill and any residual is cancelled; no deeper +walk, hidden liquidity, endogenous reaction, or true impact is modeled. The +frozen zero-extra-slippage setting is one transparent scenario, not evidence +that slippage is zero. Capacity, realized execution, limit-fill, queue-priority, +and profitability claims remain forbidden. + +## Prospective live-L2 boundary + +The Aug 8--11 BTCUSDT/ETHUSDT sessions must share one clean capture runtime +identity and pass the exact simultaneous observed-interval gates. Raw websocket +receipt time is available, but it is internet-path receipt time—not a colocated +clock or matching-engine acknowledgment. A long nominal session cannot conceal +gaps: features and labels are limited to verified observed intervals, and clock +targets are censored if no sufficiently fresh same-interval state exists. + +The campaign authority also binds an outcome-blind nonce, the one canonical +output-root path and filesystem identity, the loaded package/module origin, and +a hashed Python/platform/production-dependency fingerprint. These controls make +environment and storage substitution visible, but they do not make public- +internet latency colocated or prove that the exchange feed was complete. + +Regime thresholds are fit on Aug 8 only. When both development sessions are +complete, model selection and calibration use Aug 8/9 only and must be committed +in eight symbol-by-endpoint child locks plus one aggregate `LOCKED` authority +before Aug 10/11 frames are exposed. If either development session is +insufficient, a control-only `NOT_CREATED` authority is committed instead and no +economic frame from any session is opened. Held-out evaluation restores only a +`LOCKED` state without refit. Paired moving-block intervals +partially address serial dependence but do not prove independence, solve all +overlapping-horizon dependence, correct every model/horizon/regime comparison, +or authorize a p-value. Directional agreement across two adjacent one-hour +sessions is still a narrow venue- and period-specific result. + +At the pre-capture source freeze, these were software and governance controls, +not book evidence: no declared L2 session bundle or downstream L2 metric had +been promoted. This tracked file is intentionally unchanged during the four-day +campaign. The exact field-level authority is +`docs/M8_L2_ANALYSIS_CONTRACT.md`; any eventual numbers must come from a verified +generated bundle rather than this source-controlled limitations file. + +The completed final producer takes four explicit session path/manifest/checksum +authorities plus the development-authority path and SHA. A development or +held-out session failure +or no eligible label produces a checksummed `INSUFFICIENT_DATA` terminal with no +promoted evaluation or execution, rather than an opportunistic retry. A complete +run copies exact control authorities into a self-contained snapshot but still +revalidates their external originals. Reports are re-rendered from a checksummed +report-input snapshot into a separate directory; report generation cannot mutate +the immutable empirical bundle. These are integrity and governance guarantees, +not proof that the economic design or market conclusion is correct. + +## Reporting and generalizability + +Generated reports read serialized artifacts; they do not recalculate statistics. +Every surface shows evidence tier, observed UTC interval, configuration hash, +input-manifest hashes, Git commit or `UNBORN`, and dirty state. Missing values are +`N/A`, never zero. Checksums demonstrate byte integrity, not correctness of the +economic design. + +Results from BTCUSDT and ETHUSDT on one venue cannot be assumed to apply to other +symbols, venues, asset classes, tick sizes, participant mixes, or regulatory +settings. Robustness requires predeclared adjacent periods, cross-instrument and +regime comparisons, alternative defensible execution assumptions, and careful +documentation of results that fail. diff --git a/Microstructure/reports/model_comparison.md b/Microstructure/reports/model_comparison.md new file mode 100644 index 0000000000000000000000000000000000000000..e56ac24d6867e2548cd576af04f73604e14a9db3 --- /dev/null +++ b/Microstructure/reports/model_comparison.md @@ -0,0 +1,12 @@ +# Model comparison + +> **STATUS: SOURCE-CONTROLLED TEMPLATE — RUN-SPECIFIC TABLES ARE GENERATED BY CODE** + +This file intentionally contains no copied model or execution numbers. Run- +specific held-out tables are rendered from the frozen bundle by `make report`. + +The generated table will be built from serialized run artifacts and will include +the evidence tier, instrument, horizon, model, held-out split, sample count, +actual UTC test period, predictive diagnostics, gross and net execution +diagnostics, fill rate, turnover, drawdown, and the validation-only selection +criterion. Unsupported values will render as `N/A`, not zero. diff --git a/Microstructure/reports/technical_report.md b/Microstructure/reports/technical_report.md new file mode 100644 index 0000000000000000000000000000000000000000..bc940801f43bb6d74fe6e28463ecd011c8a54a93 --- /dev/null +++ b/Microstructure/reports/technical_report.md @@ -0,0 +1,80 @@ +# Technical report + +> **STATUS: SOURCE-CONTROLLED TEMPLATE — RUN-SPECIFIC REPORTS ARE GENERATED BY CODE** + +This is the canonical report location for *Order Flow to Price Impact*. It does +not contain manually copied empirical or synthetic performance results. +`make reproduce-sample` produces a checksum-verified frozen bundle containing its +evidence tier, configuration/input hashes, observed UTC interval and Git state; +`make report` then renders a run-specific document without retraining or +recomputing statistics. + +## Research question + +When do order-flow imbalance, liquidity, and observable limit-order-book state +predict short-horizon price changes, and how much apparent predictive value +survives fees, latency, uncertain fills, adverse selection, and inventory risk? + +## Planned evidence structure + +The study separates three questions that are often conflated: + +1. Does an observable feature predict a strictly future outcome on an untouched, + time-ordered test period? +2. Is the effect stable across instruments, horizons, and liquidity or volatility + regimes, with uncertainty and multiple testing acknowledged? +3. Does any apparent effect survive a separately specified execution model? + +The model ladder begins with historical-mean or majority baselines, followed by +transparent linear and regularized models and a bounded tree model. Model choice +uses training and validation data only. Overlapping label intervals require +purging and embargo before final held-out comparison. + +## Data and temporal integrity + +No data period is hard-coded in this source template. A generated report takes +its actual minimum and maximum event timestamps from the frozen bundle—not merely +from requested configuration dates. Raw observations remain +unchanged; validation findings and any downstream exclusions are recorded +separately. + +At decision event `t`, features may use only information proven observable at or +before `t`. Labels begin strictly after `t`. Exchange event time and local receipt +time are distinct where both exist. + +## Predictive model quality + +No model metrics are embedded in this template. The generated comparison reports +held-out sample size and period, ROC-AUC or regression diagnostics as applicable, +log loss, Brier score, expected calibration error, and serialized fixed-block +bootstrap intervals. Regime-level outcomes and model diagnostics are persisted as +separate descriptive analysis artifacts rather than folded into the comparison +table. Missing metrics will display as `N/A`, never as zero. + +## Execution and simulated performance + +No execution result is embedded here. Generated simulation results state maker +and taker fees, decision and order latency, queue/fill proxy, partial fills, +adverse selection, inventory limits, liquidation, turnover, and trade-size or +capacity sensitivity. Predictive metrics and execution metrics remain separate. + +## Economic interpretation + +There is currently no supported claim about predictability, profitability, +statistical significance, or deployability. The synthetic smoke run validates +software plumbing only and carries the mandatory +`SYNTHETIC_SMOKE` warning on every output surface. + +## Limitations + +See [methodology_limitations.md](methodology_limitations.md) for the maintained +methodology and limitations register. Even a completed public-data analysis will +remain venue-specific, sensitive to timestamp and fill assumptions, and distinct +from realized live execution. + +## Reproduction record + +Run `make reproduce-sample && make verify-run && make report`. The generated +report records run ID, evidence tier, observed UTC period, configuration SHA-256, +input-manifest SHA-256 values, Git commit, dirty state and runtime metadata. The +source-controlled template intentionally remains free of copied metrics. diff --git a/Microstructure/src/microstructure/__init__.py b/Microstructure/src/microstructure/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4b16cf61665aca8b78b99953272a5b40a99f5baa --- /dev/null +++ b/Microstructure/src/microstructure/__init__.py @@ -0,0 +1,10 @@ +"""Event-driven market-microstructure research package.""" + +from importlib.metadata import PackageNotFoundError, version + +try: + __version__ = version("event-driven-microstructure") +except PackageNotFoundError: # pragma: no cover - editable source without metadata + __version__ = "0+unknown" + +__all__ = ["__version__"] diff --git a/Microstructure/src/microstructure/cli.py b/Microstructure/src/microstructure/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..da20287a8242d46a55dc5b9b50c06e717b2abb0a --- /dev/null +++ b/Microstructure/src/microstructure/cli.py @@ -0,0 +1,2003 @@ +"""Command-line interface for research data, reproduction, and reporting.""" + +from __future__ import annotations + +import argparse +import asyncio +import base64 +import hashlib +import json +import os +import sys +import tempfile +import time +from collections.abc import AsyncIterator, Callable, Iterator, Mapping, Sequence +from contextlib import suppress +from dataclasses import asdict, dataclass +from decimal import Decimal +from pathlib import Path +from typing import Any, Literal, cast + +import pyarrow as pa # type: ignore[import-untyped] + +from microstructure import __version__ +from microstructure.config import ProjectConfig, datetime_to_ns, load_config +from microstructure.data.binance import ( + BinanceLiveDepthCollector, + BinancePublicClient, + CapturedDepth, + RawDepthFrame, +) +from microstructure.data.book import BookSnapshot, IncrementalBookReconstructor +from microstructure.data.quality import IncrementalQualityValidator, ValidationReport +from microstructure.data.schemas import get_schema, table_from_records +from microstructure.data.storage import write_capture_parquet, write_source_manifest +from microstructure.data.synthetic import generate_synthetic_market +from microstructure.ingestion import ( + IngestionResult, + ingest_from_config, + validate_configured_input, +) +from microstructure.m8_acquisition import ( + M8AcquisitionFailureResult, + M8AcquisitionResult, + acquire_m8_archives, +) +from microstructure.m8_config import load_m8_config +from microstructure.m8_l2_analysis_config import ( + M8L2AnalysisConfig, + load_m8_l2_analysis_config, +) +from microstructure.m8_l2_binance import BinanceM8L2Capture +from microstructure.m8_l2_capture import ( + M8L2SessionBundle, + capture_m8_l2_session, + verify_m8_l2_session_bundle, +) +from microstructure.m8_l2_config import M8L2StudyConfig, load_m8_l2_config +from microstructure.m8_l2_development import ( + L2DevelopmentInputVerifier, + L2DevelopmentLockResult, + lock_m8_l2_development, + verify_m8_l2_development_lock, +) +from microstructure.m8_l2_inputs import ( + L2CampaignRuntimeIdentity, + L2SessionFileAuthority, + verify_m8_l2_development_input, +) +from microstructure.m8_l2_pipeline import ( + L2StudySessionAuthority, + M8L2StudyRunResult, + load_m8_l2_report_data, + reproduce_m8_l2_study, + verify_m8_l2_study_run, +) +from microstructure.m8_pipeline import M8RunResult, reproduce_m8, verify_m8_result +from microstructure.pipeline import reproduce +from microstructure.provenance import read_json, sha256_file, utc_now_iso, write_json +from microstructure.reporting import ( + canonical_report_data_sha256, + load_run_bundle, + verify_checksums, + write_l2_report_set, + write_report_set, +) + + +def _json_default(value: object) -> object: + if isinstance(value, Path): + return str(value) + if isinstance(value, Decimal): + return str(value) + raise TypeError(f"cannot serialize {type(value).__name__}") + + +def _print_json(payload: object) -> None: + print(json.dumps(payload, indent=2, sort_keys=True, default=_json_default)) + + +def _ingestion_payload(result: IngestionResult) -> dict[str, Any]: + return { + "mode": result.mode, + "evidence_tier": result.evidence_tier, + "output_root": result.output_root, + "ingestion_manifest": result.ingestion_manifest_path, + "ingestion_manifest_sha256": result.ingestion_manifest_sha256, + "rows": result.rows, + "datasets": [ + { + "schema": dataset.schema_name, + "rows": dataset.rows, + "manifest": dataset.storage.manifest_path, + "manifest_sha256": dataset.storage.manifest_sha256, + "quality_errors": dataset.validation.error_count, + "quality_warnings": dataset.validation.warning_count, + } + for dataset in result.datasets + ], + "raw_artifacts": len(result.raw_artifacts), + "symbols": [ + { + "symbol": item.symbol, + "rows": item.rows, + "complete_range": item.complete_range, + "tick_size": item.metadata.tick_size, + "lot_size": item.metadata.lot_size, + } + for item in result.symbols + ], + "quality": { + "passed": result.validation.passed, + "rows_checked": result.validation.rows_checked, + "errors": result.validation.error_count, + "warnings": result.validation.warning_count, + }, + } + + +def _cmd_ingest(args: argparse.Namespace) -> int: + config = load_config(args.config) + output_root = ( + Path(args.output_root).resolve() if args.output_root else config.data.partition_root.parent + ) + result = ingest_from_config(config, output_root) + _print_json(_ingestion_payload(result)) + return 0 + + +def _m8_acquisition_payload(result: M8AcquisitionResult) -> dict[str, Any]: + return { + "status": "acquired", + "scope": "raw_only", + "output_root": result.output_root, + "raw_manifest": result.manifest_path, + "raw_manifest_sha256": result.manifest_sha256, + "metadata_responses": result.metadata_count, + "archives": result.archive_count, + "total_raw_evidence_bytes": result.total_raw_evidence_bytes, + "csv_members_opened": False, + "economic_fields_inspected": False, + } + + +def _m8_acquisition_failure_payload(result: M8AcquisitionFailureResult) -> dict[str, Any]: + failed_date = result.failed_date + return { + "status": "INSUFFICIENT_DATA", + "scope": "raw_only", + "output_root": result.output_root, + "attempt_dir": result.attempt_dir, + "failure_manifest": result.attempt_manifest_path, + "failure_manifest_sha256": result.attempt_manifest_sha256, + "checksums": result.checksums_path, + "checksums_sha256": result.checksums_sha256, + "terminal_marker": result.terminal_path, + "reason_code": result.reason_code, + "diagnostic": result.diagnostic, + "failed_symbol": result.failed_symbol, + "failed_date": None if failed_date is None else failed_date.isoformat(), + "failed_role": result.failed_role, + "completed_steps": result.completed_count, + "remaining_steps": result.remaining_count, + "retained_inventory_sha256": result.retained_inventory_sha256, + "retained_artifacts": result.retained_artifact_count, + "total_raw_evidence_bytes": result.total_raw_evidence_bytes, + "csv_members_opened": False, + "economic_fields_inspected": False, + } + + +def _cmd_acquire_m8(args: argparse.Namespace) -> int: + config = load_m8_config(args.config) + result = acquire_m8_archives(config, Path(args.output_root).resolve()) + if isinstance(result, M8AcquisitionFailureResult): + _print_json(_m8_acquisition_failure_payload(result)) + return 1 + _print_json(_m8_acquisition_payload(result)) + return 0 + + +def _synthetic_tables(config: ProjectConfig) -> dict[str, Any]: + events = config.data.events_per_symbol + if events is None: + raise ValueError("synthetic validation requires data.events_per_symbol") + generated = generate_synthetic_market( + symbols=config.data.symbols, + events_per_symbol=events, + start_ts_ns=datetime_to_ns(config.data.start), + seed=config.run.seed, + ) + return {"trades": generated.trades, "book_observations": generated.book_observations} + + +def _cmd_validate(args: argparse.Namespace) -> int: + config = load_config(args.config) + tables = _synthetic_tables(config) if config.data.mode == "synthetic" else None + summary = validate_configured_input(config, tables=tables) + _print_json( + { + "passed": summary.passed, + "rows_checked": summary.rows_checked, + "errors": summary.error_count, + "warnings": summary.warning_count, + "reports": [ + { + "dataset": report.dataset, + "rows_checked": report.rows_checked, + "errors": report.error_count, + "warnings": report.warning_count, + } + for report in summary.reports + ], + "mutation_policy": "validation did not repair or replace observations", + } + ) + return 0 if summary.passed else 1 + + +def _cmd_reproduce(args: argparse.Namespace) -> int: + config = load_config(args.config) + output = reproduce( + config, + Path(args.run_dir), + ingestion_manifest_path=args.ingestion_manifest, + ingestion_manifest_sha256=args.ingestion_manifest_sha256, + ) + bundle = load_run_bundle(output) + _print_json( + { + "run_dir": output, + "run_id": bundle.run_id, + "evidence_tier": bundle.evidence_tier, + "observed_start_utc": bundle.observed_start_utc, + "observed_end_utc": bundle.observed_end_utc, + "status": "complete", + } + ) + return 0 + + +def _cmd_reproduce_m8(args: argparse.Namespace) -> int: + config = load_m8_config(args.config) + result = reproduce_m8( + config, + Path(args.run_dir), + raw_manifest_path=Path(args.raw_manifest), + raw_manifest_sha256=str(args.raw_manifest_sha256), + ) + if result.status == "INSUFFICIENT_DATA": + _print_json(_m8_run_result_payload(result)) + return 1 + bundle = load_run_bundle(result.path) + _print_json( + { + "run_dir": result.path, + "run_id": bundle.run_id, + "evidence_tier": bundle.evidence_tier, + "observed_start_utc": bundle.observed_start_utc, + "observed_end_utc": bundle.observed_end_utc, + "status": result.status, + "raw_manifest_sha256": result.raw_manifest_sha256, + "normalized_manifest_sha256": result.normalized_manifest_sha256, + } + ) + return 0 + + +def _m8_run_result_payload(result: M8RunResult) -> dict[str, Any]: + return { + "run_dir": result.path, + "status": result.status, + "raw_manifest_sha256": result.raw_manifest_sha256, + "normalized_manifest_sha256": result.normalized_manifest_sha256, + } + + +def _cmd_verify_m8(args: argparse.Namespace) -> int: + config = load_m8_config(args.config) + result = verify_m8_result( + args.run_dir, + config, + raw_manifest_path=args.raw_manifest, + raw_manifest_sha256=args.raw_manifest_sha256, + ) + payload = _m8_run_result_payload(result) + payload.update( + { + "integrity": "verified", + "protected_files": verify_checksums(result.path), + } + ) + _print_json(payload) + return 0 + + +def _external_report_dir(run_root: Path, requested: Path | None) -> Path: + frozen_root = run_root.resolve() + output = ( + requested.resolve() + if requested is not None + else frozen_root.with_name(f"{frozen_root.name}-reports") + ) + if output == frozen_root or frozen_root in output.parents: + raise ValueError("report output directory must be outside the immutable run bundle") + return output + + +def _atomic_text(path: Path, content: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary_name = tempfile.mkstemp( + dir=path.parent, + prefix=f".{path.name}.", + suffix=".tmp", + text=True, + ) + temporary = Path(temporary_name) + try: + with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as handle: + handle.write(content) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, path) + directory = os.open(path.parent, os.O_RDONLY) + try: + os.fsync(directory) + finally: + os.close(directory) + except BaseException: + temporary.unlink(missing_ok=True) + raise + + +def _report_mapping(value: object, label: str) -> Mapping[str, Any]: + if not isinstance(value, Mapping): + raise ValueError(f"verified M8 {label} is not a JSON object") + return cast(Mapping[str, Any], value) + + +def _report_value(value: object) -> str: + if isinstance(value, (dict, list, tuple)): + rendered = json.dumps(value, sort_keys=True, separators=(",", ":")) + elif value is None: + rendered = "null" + elif value is True: + rendered = "true" + elif value is False: + rendered = "false" + else: + rendered = str(value) + return " ".join(rendered.replace("`", "'").split()) + + +def _m8_failure_period(failure: Mapping[str, Any]) -> tuple[str, str]: + dates: list[str] = [] + for key in ("completed_normalizations", "stopped_before"): + rows = failure.get(key) + if isinstance(rows, list): + dates.extend( + str(row["date"]) + for row in rows + if isinstance(row, Mapping) + and isinstance(row.get("date"), str) + and len(str(row["date"])) == 10 + ) + failed_date = failure.get("failed_date") + if isinstance(failed_date, str) and len(failed_date) == 10: + dates.append(failed_date) + if not dates: + raise ValueError("verified M8 failure does not declare its study period") + return min(dates), max(dates) + + +def _render_m8_insufficient_report(run_root: Path) -> str: + failure = _report_mapping(read_json(run_root / "failure.json"), "failure record") + provenance = _report_mapping(read_json(run_root / "provenance.json"), "provenance") + manifest = _report_mapping(read_json(run_root / "run_manifest.json"), "run manifest") + research = _report_mapping(manifest.get("research"), "run research section") + execution = _report_mapping( + manifest.get("execution_assumptions"), + "execution-assumptions section", + ) + git = _report_mapping(provenance.get("git"), "Git identity") + period_start, period_end = _m8_failure_period(failure) + completed_symbols = failure.get("selection_completed_symbols") + evaluated_symbols = failure.get("endpoint_evaluation_completed_symbols") + heldout_member = failure.get("held_out_member_opened", "not separately recorded") + return f"""# M8 study result: INSUFFICIENT_DATA + +> VERIFIED TERMINAL TRADE-ONLY RESEARCH RESULT — NO DATE REPLACEMENT, LIVE TRADING, OR PERFORMANCE CLAIM + +## Frozen scope and failure + +- Observed/attempted archive date span: `{period_start}` through `{period_end}` (UTC daily archives) +- Failed coordinate: symbol=`{_report_value(failure.get("failed_symbol"))}`, date=`{_report_value(failure.get("failed_date"))}`, role=`{_report_value(failure.get("failed_role"))}` +- Failure stage: `{_report_value(failure.get("failure_stage"))}` +- Reason code: `{_report_value(failure.get("reason_code"))}` +- Diagnostic: `{_report_value(failure.get("reason"))}` +- Replacement date selected: `{_report_value(failure.get("replacement_date_selected"))}`; reselection performed: `{_report_value(failure.get("reselection_performed"))}` + +## Immutable authority + +- Config semantic SHA-256: `{_report_value(failure.get("config_sha256"))}` +- Config source SHA-256: `{_report_value(failure.get("config_source_sha256"))}` +- Raw acquisition manifest SHA-256: `{_report_value(failure.get("raw_acquisition_manifest_sha256"))}` +- Bundled raw acquisition manifest SHA-256: `{_report_value(failure.get("bundled_raw_acquisition_manifest_sha256"))}` +- Protocol SHA-256: `{_report_value(failure.get("protocol_sha256"))}` +- Git commit: `{_report_value(git.get("commit"))}` +- Git dirty: `{_report_value(git.get("dirty"))}` +- Source-tree SHA-256: `{_report_value(git.get("source_tree_sha256"))}` + +## Terminal analysis states + +- Candidate selection started: `{_report_value(failure.get("selection_started"))}`; completed symbols: `{_report_value(completed_symbols)}` +- Aggregate analysis lock committed: `{_report_value(failure.get("aggregate_lock_committed"))}` +- Held-out member opened: `{_report_value(heldout_member)}` +- Endpoint evaluation started: `{_report_value(failure.get("endpoint_evaluation_started"))}`; completed: `{_report_value(failure.get("endpoint_evaluation_completed"))}`; completed symbols: `{_report_value(evaluated_symbols)}` +- Predictions published: `{_report_value(failure.get("predictions_published"))}`; endpoint artifacts published: `{_report_value(failure.get("endpoint_artifacts_published"))}` +- Research endpoint status: `{_report_value(research.get("endpoint_status"))}` +- Execution status: `{_report_value(execution.get("status"))}`; fills calculated: `{_report_value(execution.get("fills_calculated"))}`; P&L calculated: `{_report_value(execution.get("pnl_calculated"))}`; capacity calculated: `{_report_value(execution.get("capacity_calculated"))}` + +This terminal result preserves the frozen calendar and failure evidence. It authorizes no execution, profitability, capacity, statistical-significance, or persistent-alpha claim. +""" + + +def _cmd_report_m8(args: argparse.Namespace) -> int: + config = load_m8_config(args.config) + result = verify_m8_result( + args.run_dir, + config, + raw_manifest_path=args.raw_manifest, + raw_manifest_sha256=args.raw_manifest_sha256, + ) + output = _external_report_dir(result.path, args.output_dir) + if result.status == "COMPLETE": + bundle = load_run_bundle(result.path) + paths = write_report_set(bundle, output) + _print_json( + { + **_m8_run_result_payload(result), + "output_dir": output, + "reports_regenerated": True, + **asdict(paths), + } + ) + else: + rendered = _render_m8_insufficient_report(result.path) + confirmed = verify_m8_result( + args.run_dir, + config, + raw_manifest_path=args.raw_manifest, + raw_manifest_sha256=args.raw_manifest_sha256, + ) + if ( + confirmed.status != "INSUFFICIENT_DATA" + or confirmed.path.resolve() != result.path.resolve() + or confirmed.raw_manifest_sha256 != result.raw_manifest_sha256 + or confirmed.normalized_manifest_sha256 is not None + ): + raise ValueError("M8 failure authority changed while rendering its report") + failure_report = output / "insufficient_data.md" + _atomic_text(failure_report, rendered) + _print_json( + { + **_m8_run_result_payload(result), + "output_dir": output, + "report": failure_report, + "report_sha256": sha256_file(failure_report), + "reports_regenerated": True, + "source_bundle_modified": False, + } + ) + return 0 + + +def _lowercase_sha256(value: str) -> str: + if len(value) != 64 or any(character not in "0123456789abcdef" for character in value): + raise argparse.ArgumentTypeError("must be a 64-character lowercase SHA-256 digest") + return value + + +def _cmd_verify(args: argparse.Namespace) -> int: + bundle = load_run_bundle(args.run_dir) + protected = verify_checksums(args.run_dir) + _print_json( + { + "run_dir": bundle.root, + "run_id": bundle.run_id, + "evidence_tier": bundle.evidence_tier, + "protected_files": protected, + "integrity": "verified", + } + ) + return 0 + + +def _cmd_report(args: argparse.Namespace) -> int: + bundle = load_run_bundle(args.run_dir) + output = ( + Path(args.output_dir).resolve() + if args.output_dir + else bundle.root.with_name(f"{bundle.root.name}-reports") + ) + paths = write_report_set(bundle, output) + _print_json({"run_id": bundle.run_id, "output_dir": output, **asdict(paths)}) + return 0 + + +_LIVE_BATCH_ROWS = 1_024 +_MAX_LIVE_RAW_MESSAGE_BYTES = 1 * 1024 * 1024 +_LIVE_BATCH_ESTIMATED_BYTES = 16 * 1024 * 1024 +_VARIABLE_RECORD_OVERHEAD_FACTOR = 8 + + +@dataclass(frozen=True, slots=True) +class DepthCaptureResult: + symbol: str + messages: int + continuity_epochs: int + reconstruction_status: Literal["LIVE", "GAPPED", "INVALID"] + book_observations: int + sequence_gaps: int + stale_events: int + excluded_messages: int + final_update_id: int + quality_errors: int + quality_warnings: int + raw_path: Path + raw_manifest_path: Path + raw_manifest_sha256: str + summary_path: Path + completion_reason: str + requested_duration_seconds: float | None + elapsed_monotonic_seconds: float + receipt_coverage_seconds: float + max_continuity_epoch_seconds: float + + +@dataclass(slots=True) +class _DepthCaptureStop: + reason: str = "not_started" + elapsed_monotonic_seconds: float = 0.0 + + +@dataclass(slots=True) +class _DepthEpochCoverage: + continuity_id: str + snapshot_id: str + first_received_ns: int + last_received_ns: int + messages: int = 0 + book_observations: int = 0 + excluded_messages: int = 0 + sequence_gaps: int = 0 + reconstruction_status: Literal["LIVE", "GAPPED", "INVALID"] = "LIVE" + final_update_id: int = 0 + + @property + def duration_seconds(self) -> float: + return max(0.0, (self.last_received_ns - self.first_received_ns) / 1_000_000_000.0) + + def to_dict(self) -> dict[str, object]: + return { + "continuity_id": self.continuity_id, + "snapshot_id": self.snapshot_id, + "first_received_ns": self.first_received_ns, + "last_received_ns": self.last_received_ns, + "duration_seconds": self.duration_seconds, + "messages": self.messages, + "book_observations": self.book_observations, + "excluded_messages": self.excluded_messages, + "sequence_gaps": self.sequence_gaps, + "reconstruction_status": self.reconstruction_status, + "final_update_id": self.final_update_id, + } + + +async def _bounded_depth_items( + collector: BinanceLiveDepthCollector, + *, + max_messages: int, + duration_seconds: float | None, + stop: _DepthCaptureStop, +) -> AsyncIterator[CapturedDepth]: + """Yield a live stream until its safety cap or a graceful duration deadline.""" + + started = time.monotonic() + yielded = 0 + iterator = collector.stream(max_messages=max_messages).__aiter__() + try: + if duration_seconds is None: + async for item in iterator: + yielded += 1 + yield item + stop.reason = "message_limit" if yielded == max_messages else "stream_ended_early" + return + + deadline = started + duration_seconds + while True: + remaining = deadline - time.monotonic() + if remaining <= 0: + stop.reason = "duration_elapsed" + return + try: + item = await asyncio.wait_for(anext(iterator), timeout=remaining) + except TimeoutError: + stop.reason = "duration_elapsed" + return + except StopAsyncIteration: + stop.reason = ( + "message_safety_ceiling" if yielded == max_messages else "stream_ended_early" + ) + return + yielded += 1 + yield item + finally: + stop.elapsed_monotonic_seconds = max(0.0, time.monotonic() - started) + with suppress(BaseException): + closer = getattr(iterator, "aclose", None) + if callable(closer): + await closer() + + +@dataclass(frozen=True, slots=True) +class _PublishedRawCapture: + path: Path + sha256: str + manifest_path: Path + manifest_sha256: str + + +class _ArrowBatchSpool: + """Bounded record buffer backed by a temporary Arrow IPC stream.""" + + def __init__( + self, + *, + root: Path, + schema_name: str, + batch_rows: int, + max_buffer_bytes: int, + on_batch: Callable[[pa.RecordBatch], None] | None = None, + ) -> None: + if batch_rows < 1: + raise ValueError("batch_rows must be positive") + if max_buffer_bytes < 1: + raise ValueError("max_buffer_bytes must be positive") + self.schema_name = schema_name + self.batch_rows = batch_rows + self.max_buffer_bytes = max_buffer_bytes + self.path = root / f"{schema_name}.arrow" + self._handle = self.path.open("wb") + self._writer = pa.ipc.new_stream(self._handle, get_schema(schema_name)) + self._on_batch = on_batch + self._records: list[Mapping[str, object]] = [] + self.rows = 0 + self.max_buffered_rows = 0 + self.max_buffered_estimated_bytes = 0 + self._buffered_estimated_bytes = 0 + self._closed = False + + def append(self, record: Mapping[str, object], *, estimated_bytes: int) -> None: + if self._closed: + raise RuntimeError("cannot append to a closed Arrow spool") + if estimated_bytes < 1: + raise ValueError("estimated_bytes must be positive") + if estimated_bytes > self.max_buffer_bytes: + raise RuntimeError(f"one {self.schema_name} record exceeds the bounded batch estimate") + if ( + self._records + and self._buffered_estimated_bytes + estimated_bytes > self.max_buffer_bytes + ): + self._flush() + self._records.append(record) + self._buffered_estimated_bytes += estimated_bytes + self.max_buffered_rows = max(self.max_buffered_rows, len(self._records)) + self.max_buffered_estimated_bytes = max( + self.max_buffered_estimated_bytes, + self._buffered_estimated_bytes, + ) + if len(self._records) >= self.batch_rows: + self._flush() + + def _flush(self) -> None: + if not self._records: + return + table = table_from_records(self.schema_name, self._records) + batches = table.to_batches(max_chunksize=self.batch_rows) + if len(batches) != 1 or batches[0].num_rows > self.batch_rows: + raise RuntimeError(f"failed to construct one bounded {self.schema_name} batch") + batch = batches[0] + if self._on_batch is not None: + self._on_batch(batch) + self._writer.write_batch(batch) + self.rows += batch.num_rows + self._records.clear() + self._buffered_estimated_bytes = 0 + + def close(self) -> None: + if self._closed: + return + self._flush() + self._writer.close() + if not self._handle.closed: + self._handle.flush() + os.fsync(self._handle.fileno()) + self._handle.close() + self._closed = True + + def iter_batches(self) -> Iterator[pa.RecordBatch]: + if not self._closed: + raise RuntimeError("Arrow spool must be closed before it can be read") + with self.path.open("rb") as handle: + reader = pa.ipc.open_stream(handle) + for batch in reader: + if batch.num_rows > self.batch_rows: + raise RuntimeError( + f"spooled {self.schema_name} batch exceeds {self.batch_rows} rows" + ) + yield batch + + +class _RawMessageSpool: + """Incrementally persist an exact, typed live-capture journal.""" + + def __init__(self, *, root: Path, symbol: str, source_uri: str) -> None: + self.root = root + self.symbol = symbol + self.source_uri = source_uri + self.directory = root / "raw" / "binance_spot" / "depth_stream" / symbol + self.directory.mkdir(parents=True, exist_ok=True) + descriptor, temporary_name = tempfile.mkstemp( + dir=self.directory, + prefix=".capture-", + suffix=".ndjson.tmp", + text=True, + ) + self._temporary_path = Path(temporary_name) + self._handle = os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") + self.messages = 0 + self.snapshot_anchors = 0 + self.first_received_ns: int | None = None + self.last_received_ns: int | None = None + self._closed = False + self.published_path: Path | None = None + self._last_frame_identity: tuple[str, int, int, str] | None = None + + @property + def evidence_path(self) -> Path: + """Return the durable path, or the fsynced temporary path after publish failure.""" + return self.published_path or self._temporary_path + + def _write_event(self, event: Mapping[str, object]) -> None: + if self._closed: + raise RuntimeError("cannot append to a closed raw capture") + json.dump(event, self._handle, sort_keys=True, separators=(",", ":")) + self._handle.write("\n") + + def append_frame(self, frame: RawDepthFrame) -> int: + """Journal one exact frame before any UTF-8 or JSON parsing.""" + payload_size = len(frame.payload) + payload_sha256 = hashlib.sha256(frame.payload).hexdigest() + self._write_event( + { + "capture_seq": frame.capture_seq, + "continuity_id": frame.continuity_id, + "event_kind": "websocket_frame", + "payload_base64": base64.b64encode(frame.payload).decode("ascii"), + "payload_bytes": payload_size, + "payload_sha256": payload_sha256, + "received_ts_ns": frame.received_ts_ns, + "websocket_message_type": "text" if frame.was_text else "binary", + } + ) + self.messages += 1 + if self.first_received_ns is None: + self.first_received_ns = frame.received_ts_ns + self.last_received_ns = frame.received_ts_ns + self._last_frame_identity = ( + frame.continuity_id, + frame.capture_seq, + frame.received_ts_ns, + payload_sha256, + ) + # The oversize frame is intentionally journaled before capture fails. + if payload_size > _MAX_LIVE_RAW_MESSAGE_BYTES: + raise RuntimeError( + f"live depth message exceeds {_MAX_LIVE_RAW_MESSAGE_BYTES} raw bytes" + ) + return payload_size + + def append_captured(self, item: CapturedDepth) -> int: + """Verify callback lineage, with a fallback for injected legacy collectors.""" + received_ts_ns = item.delta.received_ts_ns + capture_seq = item.delta.capture_seq + if received_ts_ns is None or capture_seq is None: + raise RuntimeError("captured depth messages require receipt time and capture sequence") + payload = item.raw_payload.encode("utf-8") + payload_sha256 = hashlib.sha256(payload).hexdigest() + identity = ( + item.delta.continuity_id, + capture_seq, + received_ts_ns, + payload_sha256, + ) + if self._last_frame_identity != identity: + self.append_frame( + RawDepthFrame( + payload=payload, + was_text=True, + received_ts_ns=received_ts_ns, + capture_seq=capture_seq, + continuity_id=item.delta.continuity_id, + ) + ) + if item.delta.source_artifact_id != payload_sha256: + raise RuntimeError("normalized depth delta is not bound to its raw frame SHA-256") + return len(payload) + + def append_snapshot(self, snapshot: BookSnapshot) -> None: + """Bind one REST snapshot raw artifact into the capture journal.""" + raw_path = ( + self.root + / "raw" + / "binance_spot" + / "depth_snapshots" + / snapshot.symbol + / f"{snapshot.source_artifact_id}.json" + ) + if not raw_path.is_file() or sha256_file(raw_path) != snapshot.source_artifact_id: + raise RuntimeError("book snapshot is not bound to its preserved raw response") + manifest_path: Path | None = None + for candidate in raw_path.parent.glob(f"{raw_path.name}.manifest-*.json"): + payload = read_json(candidate) + if ( + isinstance(payload, dict) + and payload.get("path") == raw_path.name + and isinstance(payload.get("checksum"), dict) + and payload["checksum"].get("value") == snapshot.source_artifact_id + and (manifest_path is None or candidate.name > manifest_path.name) + ): + manifest_path = candidate + if manifest_path is None: + raise RuntimeError("book snapshot raw response has no valid source manifest") + self._write_event( + { + "continuity_id": snapshot.continuity_id, + "event_kind": "rest_snapshot_anchor", + "last_update_id": snapshot.last_update_id, + "raw_manifest_path": str(manifest_path), + "raw_manifest_sha256": sha256_file(manifest_path), + "raw_path": str(raw_path), + "raw_sha256": snapshot.source_artifact_id, + "received_ts_ns": snapshot.received_ts_ns, + "snapshot_id": snapshot.snapshot_id, + } + ) + self.snapshot_anchors += 1 + + def _close(self) -> None: + if self._closed: + return + self._handle.flush() + os.fsync(self._handle.fileno()) + self._handle.close() + self._closed = True + + def publish( + self, + *, + status: str, + error: BaseException | None = None, + ) -> _PublishedRawCapture: + self._close() + if self.published_path is not None: + destination = self.published_path + digest = sha256_file(destination) + else: + digest = sha256_file(self._temporary_path) + prefix = "capture" if status == "raw_capture_complete" else "capture-failed" + destination = self.directory / f"{prefix}-{digest}.ndjson" + if destination.exists(): + if sha256_file(destination) != digest: + raise RuntimeError(f"raw depth capture collision at {destination}") + self._temporary_path.unlink(missing_ok=True) + else: + os.replace(self._temporary_path, destination) + self.published_path = destination + response_headers = { + "x-local-capture-status": status, + "x-local-journal-format": "typed-base64-frames-v1", + "x-local-message-count": str(self.messages), + "x-local-snapshot-anchor-count": str(self.snapshot_anchors), + } + if error is not None: + response_headers["x-local-error-type"] = type(error).__name__ + response_headers["x-local-error"] = str(error)[:512] + manifest_path, manifest_sha = write_source_manifest( + destination, + source="binance_spot_public_live_capture_journal", + source_uri=self.source_uri, + downloaded_at_utc=utc_now_iso(), + requested_start_ns=self.first_received_ns, + requested_end_ns=( + self.last_received_ns + 1 if self.last_received_ns is not None else None + ), + response_headers=response_headers, + ) + return _PublishedRawCapture( + path=destination, + sha256=digest, + manifest_path=manifest_path, + manifest_sha256=manifest_sha, + ) + + def close_without_deleting(self) -> None: + self._close() + + +def _status_max( + current: Literal["LIVE", "GAPPED", "INVALID"], + observed: Literal["LIVE", "GAPPED", "INVALID"], +) -> Literal["LIVE", "GAPPED", "INVALID"]: + rank = {"LIVE": 0, "GAPPED": 1, "INVALID": 2} + return observed if rank[observed] > rank[current] else current + + +def _failure_record( + *, + output_root: Path, + capture_id: str, + symbol: str, + raw_spool: _RawMessageSpool, + raw_evidence: _PublishedRawCapture | None, + error: BaseException, +) -> None: + write_json( + output_root / "quality" / f"live_depth_capture.{capture_id}.failed.json", + { + "generated_at_utc": utc_now_iso(), + "capture_id": capture_id, + "capture_status": "FAILED", + "symbol": symbol, + "messages_preserved": raw_spool.messages, + "raw_path": str( + raw_evidence.path if raw_evidence is not None else raw_spool.evidence_path + ), + "raw_manifest": (str(raw_evidence.manifest_path) if raw_evidence is not None else None), + "error_type": type(error).__name__, + "error": str(error), + "completion_manifest_published": False, + }, + ) + + +async def _capture_depth( + *, + symbol: str, + max_messages: int, + output_root: Path, + duration_seconds: float | None = None, +) -> DepthCaptureResult: + if max_messages < 1: + raise ValueError("max_messages must be positive") + if duration_seconds is not None and duration_seconds <= 0: + raise ValueError("duration_seconds must be positive when supplied") + output_root.mkdir(parents=True, exist_ok=True) + capture_id = f"{symbol.lower()}-{time.time_ns()}" + client = BinancePublicClient() + metadata = client.fetch_exchange_info(symbol=symbol, raw_root=output_root / "raw") + raw_spool_holder: list[_RawMessageSpool] = [] + + def preserve_raw_frame(frame: RawDepthFrame) -> None: + if not raw_spool_holder: # pragma: no cover - collector cannot run during construction + raise RuntimeError("raw capture journal is not initialized") + raw_spool_holder[0].append_frame(frame) + + collector = BinanceLiveDepthCollector( + symbols=(symbol,), + tick_size=metadata.tick_size, + lot_size=metadata.lot_size, + on_raw_frame=preserve_raw_frame, + ) + raw_spool = _RawMessageSpool(root=output_root, symbol=symbol, source_uri=collector.url) + raw_spool_holder.append(raw_spool) + raw_evidence: _PublishedRawCapture | None = None + delta_validator = IncrementalQualityValidator( + "depth_deltas", + row_chunk_size=_LIVE_BATCH_ROWS, + ) + observation_validator = IncrementalQualityValidator( + "book_observations", + row_chunk_size=_LIVE_BATCH_ROWS, + ) + validators_finished = False + with tempfile.TemporaryDirectory( + dir=output_root, + prefix=f".{capture_id}.spool-", + ) as temporary_root_name: + temporary_root = Path(temporary_root_name) + spools = { + "book_snapshots": _ArrowBatchSpool( + root=temporary_root, + schema_name="book_snapshots", + batch_rows=_LIVE_BATCH_ROWS, + max_buffer_bytes=_LIVE_BATCH_ESTIMATED_BYTES, + ), + "depth_deltas": _ArrowBatchSpool( + root=temporary_root, + schema_name="depth_deltas", + batch_rows=_LIVE_BATCH_ROWS, + max_buffer_bytes=_LIVE_BATCH_ESTIMATED_BYTES, + on_batch=delta_validator.update, + ), + "book_observations": _ArrowBatchSpool( + root=temporary_root, + schema_name="book_observations", + batch_rows=_LIVE_BATCH_ROWS, + max_buffer_bytes=_LIVE_BATCH_ESTIMATED_BYTES, + on_batch=observation_validator.update, + ), + "sequence_gaps": _ArrowBatchSpool( + root=temporary_root, + schema_name="sequence_gaps", + batch_rows=_LIVE_BATCH_ROWS, + max_buffer_bytes=_LIVE_BATCH_ESTIMATED_BYTES, + ), + } + current_continuity_id: str | None = None + reconstructor: IncrementalBookReconstructor | None = None + continuity_epochs = 0 + status: Literal["LIVE", "GAPPED", "INVALID"] = "LIVE" + stale_events = 0 + excluded_messages = 0 + final_update_id = 0 + capture_stop = _DepthCaptureStop() + epoch_coverage: list[_DepthEpochCoverage] = [] + current_epoch_coverage: _DepthEpochCoverage | None = None + try: + async for item in _bounded_depth_items( + collector, + max_messages=max_messages, + duration_seconds=duration_seconds, + stop=capture_stop, + ): + raw_message_bytes = raw_spool.append_captured(item) + if item.delta.continuity_id != current_continuity_id: + snapshot = client.fetch_depth_snapshot( + symbol=symbol, + raw_root=output_root / "raw", + continuity_id=item.delta.continuity_id, + tick_size=metadata.tick_size, + lot_size=metadata.lot_size, + ) + raw_spool.append_snapshot(snapshot) + snapshot_estimated_bytes = max( + 4_096, + 128 * (len(snapshot.bids) + len(snapshot.asks)), + ) + spools["book_snapshots"].append( + snapshot.to_record(), + estimated_bytes=snapshot_estimated_bytes, + ) + reconstructor = IncrementalBookReconstructor(snapshot) + current_continuity_id = item.delta.continuity_id + continuity_epochs += 1 + received_ts_ns = item.delta.received_ts_ns + if received_ts_ns is None: # pragma: no cover - append_captured validates + raise RuntimeError("live depth delta has no receipt timestamp") + current_epoch_coverage = _DepthEpochCoverage( + continuity_id=item.delta.continuity_id, + snapshot_id=snapshot.snapshot_id, + first_received_ns=received_ts_ns, + last_received_ns=received_ts_ns, + ) + epoch_coverage.append(current_epoch_coverage) + if reconstructor is None: # pragma: no cover - guarded by epoch creation + raise RuntimeError("live depth epoch has no reconstructor") + if current_epoch_coverage is None: # pragma: no cover - guarded by epoch creation + raise RuntimeError("live depth epoch has no coverage tracker") + spools["depth_deltas"].append( + item.delta.to_record(), + estimated_bytes=max( + 4_096, + raw_message_bytes * _VARIABLE_RECORD_OVERHEAD_FACTOR, + ), + ) + step = reconstructor.update(item.delta) + if step.observation is not None: + spools["book_observations"].append( + step.observation, + estimated_bytes=4_096, + ) + else: + excluded_messages += 1 + if step.gap is not None: + spools["sequence_gaps"].append( + step.gap.to_record(), + estimated_bytes=2_048, + ) + if step.outcome == "STALE": + stale_events += 1 + status = _status_max(status, reconstructor.status) + final_update_id = reconstructor.final_update_id + received_ts_ns = item.delta.received_ts_ns + if received_ts_ns is None: # pragma: no cover - append_captured validates + raise RuntimeError("live depth delta has no receipt timestamp") + current_epoch_coverage.last_received_ns = received_ts_ns + current_epoch_coverage.messages += 1 + current_epoch_coverage.book_observations += int(step.observation is not None) + current_epoch_coverage.excluded_messages += int(step.observation is None) + current_epoch_coverage.sequence_gaps += int(step.gap is not None) + current_epoch_coverage.reconstruction_status = reconstructor.status + current_epoch_coverage.final_update_id = reconstructor.final_update_id + + if duration_seconds is None: + if raw_spool.messages != max_messages or capture_stop.reason != "message_limit": + raise RuntimeError( + f"live depth stream ended after {raw_spool.messages} of " + f"{max_messages} requested messages" + ) + else: + if capture_stop.reason == "message_safety_ceiling": + raise RuntimeError( + "live depth message safety ceiling was reached before the requested " + "capture duration elapsed" + ) + if capture_stop.reason != "duration_elapsed": + raise RuntimeError( + "live depth stream ended before the requested capture duration " + f"({capture_stop.reason})" + ) + if raw_spool.messages == 0: + raise RuntimeError("duration-bounded live depth capture received no messages") + if raw_spool.snapshot_anchors != continuity_epochs: + raise RuntimeError("not every continuity epoch has a raw snapshot anchor") + for spool in spools.values(): + spool.close() + if spools["depth_deltas"].rows != raw_spool.messages: + raise RuntimeError("captured and normalized depth-message counts diverged") + if spools["book_observations"].rows + excluded_messages != raw_spool.messages: + raise RuntimeError("not every normalized depth message has an explicit outcome") + delta_quality = delta_validator.finish() + observation_quality = observation_validator.finish() + validators_finished = True + raw_evidence = raw_spool.publish(status="raw_capture_complete") + + normalized_root = output_root / "normalized" / "captures" / capture_id + time_columns = { + "book_snapshots": "received_ts_ns", + "depth_deltas": "event_ts_ns", + "book_observations": "event_ts_ns", + "sequence_gaps": "detected_ts_ns", + } + dataset_manifests: dict[str, dict[str, object]] = {} + for schema_name, spool in spools.items(): + stored = write_capture_parquet( + spool.iter_batches(), + root=normalized_root, + dataset=schema_name, + schema_name=schema_name, + venue="binance_spot", + symbol=symbol, + capture_id=capture_id, + source="binance_spot_public_live_capture_journal", + source_uri=str(raw_evidence.path), + source_checksum_sha256=raw_evidence.sha256, + requested_start_ns=raw_spool.first_received_ns, + requested_end_ns=( + raw_spool.last_received_ns + 1 + if raw_spool.last_received_ns is not None + else None + ), + time_column=time_columns[schema_name], + max_input_batch_rows=_LIVE_BATCH_ROWS, + ) + if stored.rows != spool.rows: + raise RuntimeError( + f"stored {schema_name} row count does not match its verified spool" + ) + dataset_manifests[schema_name] = { + "data_path": str(stored.data_path) if stored.data_path is not None else None, + "data_sha256": stored.data_sha256, + "manifest_path": str(stored.manifest_path), + "manifest_sha256": stored.manifest_sha256, + "rows": stored.rows, + } + + quality_reports: tuple[ValidationReport, ...] = ( + delta_quality, + observation_quality, + ) + quality_errors = sum(report.error_count for report in quality_reports) + quality_warnings = sum(report.warning_count for report in quality_reports) + quality_root = output_root / "quality" + quality_root.mkdir(parents=True, exist_ok=True) + quality_report_paths: dict[str, str] = {} + for report in quality_reports: + report_path = quality_root / f"live_{report.dataset}.{capture_id}.validation.json" + report.write_json(report_path) + quality_report_paths[report.dataset] = str(report_path) + summary_path = quality_root / f"live_depth_capture.{capture_id}.summary.json" + receipt_coverage_seconds = ( + (raw_spool.last_received_ns - raw_spool.first_received_ns) / 1_000_000_000.0 + if raw_spool.first_received_ns is not None + and raw_spool.last_received_ns is not None + else 0.0 + ) + max_continuity_epoch_seconds = max( + (epoch.duration_seconds for epoch in epoch_coverage), + default=0.0, + ) + summary_payload = { + "generated_at_utc": utc_now_iso(), + "capture_id": capture_id, + "capture_status": "COMPLETE", + "messages": raw_spool.messages, + "continuity_epochs": continuity_epochs, + "normalized_messages": spools["depth_deltas"].rows, + "book_observations": spools["book_observations"].rows, + "sequence_gaps": spools["sequence_gaps"].rows, + "stale_events": stale_events, + "excluded_messages": excluded_messages, + "reconstruction_status": status, + "quality_errors": quality_errors, + "quality_warnings": quality_warnings, + "completion_reason": capture_stop.reason, + "requested_duration_seconds": duration_seconds, + "message_safety_ceiling": max_messages, + "elapsed_monotonic_seconds": capture_stop.elapsed_monotonic_seconds, + "receipt_coverage_seconds": receipt_coverage_seconds, + "continuity_epoch_coverage": [epoch.to_dict() for epoch in epoch_coverage], + "max_continuity_epoch_seconds": max_continuity_epoch_seconds, + "quality_reports": quality_report_paths, + "raw_path": str(raw_evidence.path), + "raw_manifest": str(raw_evidence.manifest_path), + "raw_manifest_sha256": raw_evidence.manifest_sha256, + "normalized_dataset_manifests": dataset_manifests, + "max_buffered_rows_per_dataset": { + name: spool.max_buffered_rows for name, spool in spools.items() + }, + "max_buffered_estimated_bytes_per_dataset": { + name: spool.max_buffered_estimated_bytes for name, spool in spools.items() + }, + "policy": ( + "every continuity transition receives a fresh snapshot; every captured " + "delta is normalized, and non-observed deltas are counted or gap-audited" + ), + } + # The capture-ID-specific completion marker is authoritative and published last. + write_json(summary_path, summary_payload) + with suppress(BaseException): + write_json( + quality_root / "live_depth_capture.summary.json", + { + **summary_payload, + "capture_status": "LATEST_POINTER", + "latest_capture_status": summary_payload["capture_status"], + "authoritative_summary_path": str(summary_path), + "authoritative_summary_sha256": sha256_file(summary_path), + }, + ) + return DepthCaptureResult( + symbol=symbol, + messages=raw_spool.messages, + continuity_epochs=continuity_epochs, + reconstruction_status=status, + book_observations=spools["book_observations"].rows, + sequence_gaps=spools["sequence_gaps"].rows, + stale_events=stale_events, + excluded_messages=excluded_messages, + final_update_id=final_update_id, + quality_errors=quality_errors, + quality_warnings=quality_warnings, + raw_path=raw_evidence.path, + raw_manifest_path=raw_evidence.manifest_path, + raw_manifest_sha256=raw_evidence.manifest_sha256, + summary_path=summary_path, + completion_reason=capture_stop.reason, + requested_duration_seconds=duration_seconds, + elapsed_monotonic_seconds=capture_stop.elapsed_monotonic_seconds, + receipt_coverage_seconds=receipt_coverage_seconds, + max_continuity_epoch_seconds=max_continuity_epoch_seconds, + ) + except BaseException as error: + if raw_evidence is None: + try: + raw_evidence = raw_spool.publish( + status="incomplete_capture_failure", + error=error, + ) + except BaseException: + raw_spool.close_without_deleting() + else: + with suppress(BaseException): + raw_evidence = raw_spool.publish( + status="normalization_failure", + error=error, + ) + with suppress(BaseException): + _failure_record( + output_root=output_root, + capture_id=capture_id, + symbol=symbol, + raw_spool=raw_spool, + raw_evidence=raw_evidence, + error=error, + ) + raise + finally: + for spool in spools.values(): + with suppress(BaseException): + spool.close() + if not validators_finished: + delta_validator.close() + observation_validator.close() + + +def _cmd_collect_l2(args: argparse.Namespace) -> int: + output_root = Path(args.output_root).resolve() + result = asyncio.run( + _capture_depth( + symbol=str(args.symbol).upper(), + max_messages=int(args.max_messages), + output_root=output_root, + duration_seconds=( + float(args.duration_seconds) if args.duration_seconds is not None else None + ), + ) + ) + _print_json( + { + "symbol": result.symbol, + "messages": result.messages, + "reconstruction_status": result.reconstruction_status, + "book_observations": result.book_observations, + "sequence_gaps": result.sequence_gaps, + "stale_events": result.stale_events, + "excluded_messages": result.excluded_messages, + "final_update_id": result.final_update_id, + "quality_errors": result.quality_errors, + "quality_warnings": result.quality_warnings, + "raw_manifest": result.raw_manifest_path, + "raw_manifest_sha256": result.raw_manifest_sha256, + "capture_summary": result.summary_path, + "completion_reason": result.completion_reason, + "requested_duration_seconds": result.requested_duration_seconds, + "elapsed_monotonic_seconds": result.elapsed_monotonic_seconds, + "receipt_coverage_seconds": result.receipt_coverage_seconds, + "max_continuity_epoch_seconds": result.max_continuity_epoch_seconds, + "output_root": output_root, + "live_trading": False, + } + ) + return 0 if result.reconstruction_status == "LIVE" and result.quality_errors == 0 else 1 + + +def _m8_l2_session_payload(result: M8L2SessionBundle) -> dict[str, object]: + return { + "status": result.status, + "session_id": result.session_id, + "session_date": result.session_date, + "role": result.role, + "output_root": result.root, + "session_manifest": result.manifest_path, + "session_manifest_sha256": result.manifest_sha256, + "checksums": result.checksum_path, + "terminal_marker": result.marker_path, + "reason_codes": list(getattr(result, "reason_codes", ())), + "source": "binance_spot_public_live_diff_depth", + "live_trading": False, + } + + +def _cmd_capture_m8_l2_session(args: argparse.Namespace) -> int: + config = load_m8_l2_config(args.config) + result = asyncio.run( + capture_m8_l2_session( + config, + str(args.date), + Path(args.output_root).resolve(), + BinanceM8L2Capture(), + ) + ) + _print_json(_m8_l2_session_payload(result)) + return 0 if result.status == "COMPLETE" else 1 + + +def _cmd_verify_m8_l2_session(args: argparse.Namespace) -> int: + config = load_m8_l2_config(args.config) + result = verify_m8_l2_session_bundle(args.bundle_dir, expected_config=config) + payload = _m8_l2_session_payload(result) + payload["integrity"] = "verified" + _print_json(payload) + return 0 + + +def _m8_l2_development_payload( + result: L2DevelopmentLockResult, + *, + integrity: str | None = None, +) -> dict[str, object]: + payload: dict[str, object] = { + "status": getattr(result, "status", "LOCKED"), + "development_lock_dir": result.root, + "development_lock": result.aggregate_path, + "development_lock_sha256": result.aggregate_sha256, + "terminal_marker": result.marker_path, + "created_at_utc": result.created_at_utc, + "children": [ + { + "symbol": child.symbol, + "endpoint": child.endpoint, + "lock": child.path, + "lock_sha256": child.sha256, + "selection_lock_sha256": child.selection_lock_sha256, + "fitted_state_sha256": child.fitted_state_sha256, + } + for child in result.children + ], + "reason_codes": list(getattr(result, "reason_codes", ())), + "heldout_accessed": False, + "source": "binance_spot_public_live_diff_depth", + "live_trading": False, + } + if integrity is not None: + payload["integrity"] = integrity + return payload + + +def _verify_m8_l2_session_authority( + bundle_dir: Path, + *, + expected_config: M8L2StudyConfig, + expected_date: str, + expected_role: str, + manifest_sha256: str, + checksums_sha256: str, +) -> M8L2SessionBundle: + bundle = verify_m8_l2_session_bundle(bundle_dir, expected_config=expected_config) + if bundle.session_date != expected_date or bundle.role != expected_role: + raise ValueError( + f"explicit L2 session coordinate differs from {expected_date} {expected_role}" + ) + if bundle.manifest_sha256 != manifest_sha256: + raise ValueError(f"explicit {expected_role} session manifest differs from expected SHA-256") + if sha256_file(bundle.checksum_path) != checksums_sha256: + raise ValueError(f"explicit {expected_role} session checksums differ from expected SHA-256") + return bundle + + +def _m8_l2_insufficient_development_payload( + sessions: Sequence[M8L2SessionBundle], +) -> dict[str, object]: + return { + "status": "INSUFFICIENT_DATA", + "stage": "development_lock", + "reason_code": "DEVELOPMENT_SESSION_NOT_COMPLETE", + "sessions": [ + { + "session_id": session.session_id, + "session_date": session.session_date, + "role": session.role, + "status": session.status, + "session_manifest": session.manifest_path, + "session_manifest_sha256": session.manifest_sha256, + "checksums": session.checksum_path, + "checksums_sha256": sha256_file(session.checksum_path), + "reason_codes": list(session.reason_codes), + } + for session in sessions + ], + "heldout_accessed": False, + "source": "binance_spot_public_live_diff_depth", + "live_trading": False, + } + + +def _development_session_authorities( + args: argparse.Namespace, +) -> dict[str, L2SessionFileAuthority]: + return { + "2026-08-10": L2SessionFileAuthority( + manifest_sha256=args.train_manifest_sha256, + checksums_sha256=args.train_checksums_sha256, + ), + "2026-08-11": L2SessionFileAuthority( + manifest_sha256=args.validation_manifest_sha256, + checksums_sha256=args.validation_checksums_sha256, + ), + } + + +def _explicit_development_input_loader( + authorities: Mapping[str, L2SessionFileAuthority], +) -> L2DevelopmentInputVerifier: + def load( + bundle_dir: str | Path, + *, + expected_config: M8L2StudyConfig, + expected_date: str, + expected_role: str, + expected_file_authority: object | None = None, + expected_campaign: object | None = None, + ) -> Any: + authority = authorities.get(expected_date) + if authority is None: + raise ValueError("development input date is outside the explicit authority set") + if expected_role not in ("train", "validation"): + raise ValueError("development input role is outside the explicit authority set") + if expected_file_authority is not None and expected_file_authority != authority: + raise ValueError("development input authority differs from the explicit CLI authority") + return verify_m8_l2_development_input( + bundle_dir, + expected_config=expected_config, + expected_date=expected_date, + expected_role=cast(Literal["train", "validation"], expected_role), + expected_file_authority=authority, + expected_campaign=cast(L2CampaignRuntimeIdentity | None, expected_campaign), + ) + + return load + + +def _load_explicit_development_sessions( + args: argparse.Namespace, + capture_config: M8L2StudyConfig, +) -> tuple[M8L2SessionBundle, M8L2SessionBundle]: + train = _verify_m8_l2_session_authority( + args.train_bundle_dir.absolute(), + expected_config=capture_config, + expected_date="2026-08-10", + expected_role="train", + manifest_sha256=args.train_manifest_sha256, + checksums_sha256=args.train_checksums_sha256, + ) + validation = _verify_m8_l2_session_authority( + args.validation_bundle_dir.absolute(), + expected_config=capture_config, + expected_date="2026-08-11", + expected_role="validation", + manifest_sha256=args.validation_manifest_sha256, + checksums_sha256=args.validation_checksums_sha256, + ) + return train, validation + + +def _cmd_lock_m8_l2_development(args: argparse.Namespace) -> int: + capture_config = load_m8_l2_config(args.capture_config) + analysis_config = load_m8_l2_analysis_config(args.analysis_config) + _load_explicit_development_sessions(args, capture_config) + result = lock_m8_l2_development( + capture_config, + analysis_config, + args.train_bundle_dir.absolute(), + args.validation_bundle_dir.absolute(), + args.lock_dir.absolute(), + input_loader=_explicit_development_input_loader(_development_session_authorities(args)), + expected_session_file_authorities=_development_session_authorities(args), + ) + _print_json(_m8_l2_development_payload(result)) + return 0 if getattr(result, "status", "LOCKED") == "LOCKED" else 1 + + +def _cmd_verify_m8_l2_development_lock(args: argparse.Namespace) -> int: + capture_config = load_m8_l2_config(args.capture_config) + analysis_config = load_m8_l2_analysis_config(args.analysis_config) + _load_explicit_development_sessions(args, capture_config) + result = verify_m8_l2_development_lock( + capture_config, + analysis_config, + args.train_bundle_dir.absolute(), + args.validation_bundle_dir.absolute(), + args.lock_dir.absolute(), + expected_lock_sha256=args.development_lock_sha256, + ) + _print_json(_m8_l2_development_payload(result, integrity="verified")) + return 0 if getattr(result, "status", "LOCKED") == "LOCKED" else 1 + + +def _m8_l2_study_authorities( + args: argparse.Namespace, +) -> tuple[ + L2StudySessionAuthority, + L2StudySessionAuthority, + L2StudySessionAuthority, + L2StudySessionAuthority, +]: + def authority(role: str) -> L2StudySessionAuthority: + return L2StudySessionAuthority( + bundle_path=getattr(args, f"{role}_bundle_dir").absolute(), + manifest_sha256=getattr(args, f"{role}_manifest_sha256"), + checksums_sha256=getattr(args, f"{role}_checksums_sha256"), + ) + + return ( + authority("train"), + authority("validation"), + authority("primary"), + authority("replication"), + ) + + +def _m8_l2_study_payload( + result: M8L2StudyRunResult, + *, + integrity: str | None = None, +) -> dict[str, object]: + payload: dict[str, object] = { + "status": result.status, + "run_dir": result.root, + "run_manifest": result.manifest_path, + "run_manifest_sha256": result.manifest_sha256, + "checksums": result.checksum_path, + "checksums_sha256": result.checksum_sha256, + "terminal_marker": result.marker_path, + "reason_codes": list(result.reason_codes), + "source": "binance_spot_public_live_diff_depth", + "live_trading": False, + } + if integrity is not None: + payload["integrity"] = integrity + return payload + + +def _m8_l2_study_arguments( + args: argparse.Namespace, + capture_config: M8L2StudyConfig, + analysis_config: M8L2AnalysisConfig, +) -> tuple[ + M8L2StudyConfig, + M8L2AnalysisConfig, + L2StudySessionAuthority, + L2StudySessionAuthority, + Path, + str, + L2StudySessionAuthority, + L2StudySessionAuthority, + Path, +]: + train, validation, primary, replication = _m8_l2_study_authorities(args) + return ( + capture_config, + analysis_config, + train, + validation, + args.development_lock_dir.absolute(), + args.development_lock_sha256, + primary, + replication, + args.run_dir.absolute(), + ) + + +def _cmd_reproduce_m8_l2(args: argparse.Namespace) -> int: + capture_config = load_m8_l2_config(args.capture_config) + analysis_config = load_m8_l2_analysis_config(args.analysis_config) + result = reproduce_m8_l2_study(*_m8_l2_study_arguments(args, capture_config, analysis_config)) + _print_json(_m8_l2_study_payload(result)) + return 0 if result.status == "COMPLETE" else 1 + + +def _verify_m8_l2_study_from_args( + args: argparse.Namespace, + *, + capture_config: M8L2StudyConfig, + analysis_config: M8L2AnalysisConfig, +) -> M8L2StudyRunResult: + return verify_m8_l2_study_run( + *_m8_l2_study_arguments(args, capture_config, analysis_config), + expected_manifest_sha256=args.run_manifest_sha256, + expected_checksums_sha256=args.run_checksums_sha256, + ) + + +def _cmd_verify_m8_l2_run(args: argparse.Namespace) -> int: + capture_config = load_m8_l2_config(args.capture_config) + analysis_config = load_m8_l2_analysis_config(args.analysis_config) + result = _verify_m8_l2_study_from_args( + args, + capture_config=capture_config, + analysis_config=analysis_config, + ) + _print_json(_m8_l2_study_payload(result, integrity="verified")) + return 0 if result.status == "COMPLETE" else 1 + + +def _cmd_report_m8_l2(args: argparse.Namespace) -> int: + capture_config = load_m8_l2_config(args.capture_config) + analysis_config = load_m8_l2_analysis_config(args.analysis_config) + positional = _m8_l2_study_arguments(args, capture_config, analysis_config) + result = verify_m8_l2_study_run( + *positional, + expected_manifest_sha256=args.run_manifest_sha256, + expected_checksums_sha256=args.run_checksums_sha256, + ) + output = _external_report_dir(result.root, args.output_dir) + report_data = load_m8_l2_report_data( + *positional, + expected_manifest_sha256=args.run_manifest_sha256, + expected_checksums_sha256=args.run_checksums_sha256, + ) + technical, memo, comparison = write_l2_report_set(output, report_data) + payload = _m8_l2_study_payload(result, integrity="verified") + payload.update( + { + "output_dir": output, + "technical_report": technical, + "executive_memo": memo, + "model_comparison": comparison, + "report_inputs_sha256": canonical_report_data_sha256(report_data), + "source_bundle_modified": False, + } + ) + _print_json(payload) + return 0 if result.status == "COMPLETE" else 1 + + +def _add_m8_l2_development_authority_args(parser: argparse.ArgumentParser) -> None: + parser.add_argument("--capture-config", required=True, type=Path) + parser.add_argument("--analysis-config", required=True, type=Path) + parser.add_argument("--train-bundle-dir", required=True, type=Path) + parser.add_argument( + "--train-manifest-sha256", + required=True, + type=_lowercase_sha256, + ) + parser.add_argument( + "--train-checksums-sha256", + required=True, + type=_lowercase_sha256, + ) + parser.add_argument("--validation-bundle-dir", required=True, type=Path) + parser.add_argument( + "--validation-manifest-sha256", + required=True, + type=_lowercase_sha256, + ) + parser.add_argument( + "--validation-checksums-sha256", + required=True, + type=_lowercase_sha256, + ) + parser.add_argument("--lock-dir", required=True, type=Path) + + +def _add_m8_l2_study_authority_args( + parser: argparse.ArgumentParser, + *, + require_run_authority: bool, +) -> None: + parser.add_argument("--capture-config", required=True, type=Path) + parser.add_argument("--analysis-config", required=True, type=Path) + for role in ("train", "validation", "primary", "replication"): + parser.add_argument(f"--{role}-bundle-dir", required=True, type=Path) + parser.add_argument( + f"--{role}-manifest-sha256", + required=True, + type=_lowercase_sha256, + ) + parser.add_argument( + f"--{role}-checksums-sha256", + required=True, + type=_lowercase_sha256, + ) + parser.add_argument("--development-lock-dir", required=True, type=Path) + parser.add_argument( + "--development-lock-sha256", + required=True, + type=_lowercase_sha256, + ) + parser.add_argument("--run-dir", required=True, type=Path) + if require_run_authority: + parser.add_argument( + "--run-manifest-sha256", + required=True, + type=_lowercase_sha256, + ) + parser.add_argument( + "--run-checksums-sha256", + required=True, + type=_lowercase_sha256, + ) + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="microstructure", + description="Research-only event-driven market-microstructure system", + ) + parser.add_argument("--version", action="version", version=__version__) + subparsers = parser.add_subparsers(dest="command", required=True) + + ingest = subparsers.add_parser("ingest", help="ingest configured synthetic or public data") + ingest.add_argument("--config", required=True, type=Path) + ingest.add_argument("--output-root", type=Path) + ingest.set_defaults(handler=_cmd_ingest) + + acquire_m8 = subparsers.add_parser( + "acquire-m8", + help="acquire raw M8 evidence without opening any archive CSV member", + ) + acquire_m8.add_argument("--config", required=True, type=Path) + acquire_m8.add_argument("--output-root", required=True, type=Path) + acquire_m8.set_defaults(handler=_cmd_acquire_m8) + + validate = subparsers.add_parser("validate", help="run non-mutating data validation") + validate.add_argument("--config", required=True, type=Path) + validate.set_defaults(handler=_cmd_validate) + + reproduce_parser = subparsers.add_parser( + "reproduce", help="produce or verify an immutable end-to-end sample run" + ) + reproduce_parser.add_argument("--config", required=True, type=Path) + reproduce_parser.add_argument("--run-dir", required=True, type=Path) + reproduce_parser.add_argument( + "--ingestion-manifest", + type=Path, + help="explicit public ingestion manifest; required with its SHA-256 for public mode", + ) + reproduce_parser.add_argument( + "--ingestion-manifest-sha256", + help="SHA-256 of --ingestion-manifest; required for public mode", + ) + reproduce_parser.set_defaults(handler=_cmd_reproduce) + + reproduce_m8_parser = subparsers.add_parser( + "reproduce-m8", + help="produce the frozen M8 study from one explicit raw acquisition authority", + ) + reproduce_m8_parser.add_argument("--config", required=True, type=Path) + reproduce_m8_parser.add_argument("--run-dir", required=True, type=Path) + reproduce_m8_parser.add_argument("--raw-manifest", required=True, type=Path) + reproduce_m8_parser.add_argument( + "--raw-manifest-sha256", + required=True, + type=_lowercase_sha256, + ) + reproduce_m8_parser.set_defaults(handler=_cmd_reproduce_m8) + + verify_m8_parser = subparsers.add_parser( + "verify-m8", + help="verify a complete or INSUFFICIENT_DATA M8 result and its raw authority", + ) + verify_m8_parser.add_argument("--config", required=True, type=Path) + verify_m8_parser.add_argument("--run-dir", required=True, type=Path) + verify_m8_parser.add_argument("--raw-manifest", required=True, type=Path) + verify_m8_parser.add_argument( + "--raw-manifest-sha256", + required=True, + type=_lowercase_sha256, + ) + verify_m8_parser.set_defaults(handler=_cmd_verify_m8) + + report_m8_parser = subparsers.add_parser( + "report-m8", + help="render a complete M8 result or expose its frozen failure report", + ) + report_m8_parser.add_argument("--config", required=True, type=Path) + report_m8_parser.add_argument("--run-dir", required=True, type=Path) + report_m8_parser.add_argument("--raw-manifest", required=True, type=Path) + report_m8_parser.add_argument( + "--raw-manifest-sha256", + required=True, + type=_lowercase_sha256, + ) + report_m8_parser.add_argument("--output-dir", type=Path) + report_m8_parser.set_defaults(handler=_cmd_report_m8) + + verify = subparsers.add_parser("verify", help="verify a frozen run and all checksums") + verify.add_argument("--run-dir", required=True, type=Path) + verify.set_defaults(handler=_cmd_verify) + + report = subparsers.add_parser("report", help="render reports from a frozen run") + report.add_argument("--run-dir", required=True, type=Path) + report.add_argument("--output-dir", type=Path) + report.set_defaults(handler=_cmd_report) + + collect = subparsers.add_parser( + "collect-l2", help="capture and reconstruct public live L2 data; never place orders" + ) + collect.add_argument("--symbol", choices=("BTCUSDT", "ETHUSDT"), required=True) + collect.add_argument("--max-messages", type=int, default=1_000) + collect.add_argument( + "--duration-seconds", + type=float, + help=( + "gracefully complete after this wall duration; max-messages remains a safety " + "ceiling and fails the capture if reached first" + ), + ) + collect.add_argument("--output-root", type=Path, default=Path("data")) + collect.set_defaults(handler=_cmd_collect_l2) + + capture_m8_l2 = subparsers.add_parser( + "capture-m8-l2-session", + help="capture one frozen concurrent BTCUSDT/ETHUSDT prospective L2 session", + ) + capture_m8_l2.add_argument("--config", required=True, type=Path) + capture_m8_l2.add_argument("--date", required=True) + capture_m8_l2.add_argument("--output-root", required=True, type=Path) + capture_m8_l2.set_defaults(handler=_cmd_capture_m8_l2_session) + + verify_m8_l2 = subparsers.add_parser( + "verify-m8-l2-session", + help="verify a complete or INSUFFICIENT_DATA frozen L2 session bundle", + ) + verify_m8_l2.add_argument("--config", required=True, type=Path) + verify_m8_l2.add_argument("--bundle-dir", required=True, type=Path) + verify_m8_l2.set_defaults(handler=_cmd_verify_m8_l2_session) + + lock_m8_l2_development_parser = subparsers.add_parser( + "lock-m8-l2-development", + help="fit and freeze the Aug 8/9 L2 development state before held-out access", + ) + _add_m8_l2_development_authority_args(lock_m8_l2_development_parser) + lock_m8_l2_development_parser.set_defaults(handler=_cmd_lock_m8_l2_development) + + verify_m8_l2_development_parser = subparsers.add_parser( + "verify-m8-l2-development-lock", + help="verify the frozen L2 development lock and its explicit session authorities", + ) + _add_m8_l2_development_authority_args(verify_m8_l2_development_parser) + verify_m8_l2_development_parser.add_argument( + "--development-lock-sha256", + required=True, + type=_lowercase_sha256, + ) + verify_m8_l2_development_parser.set_defaults(handler=_cmd_verify_m8_l2_development_lock) + + reproduce_m8_l2_parser = subparsers.add_parser( + "reproduce-m8-l2", + help="produce the frozen four-session prospective live-L2 study", + ) + _add_m8_l2_study_authority_args( + reproduce_m8_l2_parser, + require_run_authority=False, + ) + reproduce_m8_l2_parser.set_defaults(handler=_cmd_reproduce_m8_l2) + + verify_m8_l2_run_parser = subparsers.add_parser( + "verify-m8-l2-run", + help="verify a terminal live-L2 study and all external authorities", + ) + _add_m8_l2_study_authority_args( + verify_m8_l2_run_parser, + require_run_authority=True, + ) + verify_m8_l2_run_parser.set_defaults(handler=_cmd_verify_m8_l2_run) + + report_m8_l2_parser = subparsers.add_parser( + "report-m8-l2", + help="render verified live-L2 report inputs outside the immutable run bundle", + ) + _add_m8_l2_study_authority_args( + report_m8_l2_parser, + require_run_authority=True, + ) + report_m8_l2_parser.add_argument("--output-dir", required=True, type=Path) + report_m8_l2_parser.set_defaults(handler=_cmd_report_m8_l2) + return parser + + +def main(argv: Sequence[str] | None = None) -> int: + parser = build_parser() + args = parser.parse_args(argv) + if getattr(args, "max_messages", 1) < 1: + parser.error("--max-messages must be positive") + duration_seconds = getattr(args, "duration_seconds", None) + if duration_seconds is not None and duration_seconds <= 0: + parser.error("--duration-seconds must be positive") + handler = args.handler + try: + return int(handler(args)) + except (KeyboardInterrupt, asyncio.CancelledError): + print("operation canceled", file=sys.stderr) + return 130 + except Exception as error: + print(f"error: {error}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": # pragma: no cover + raise SystemExit(main()) diff --git a/Microstructure/src/microstructure/config.py b/Microstructure/src/microstructure/config.py new file mode 100644 index 0000000000000000000000000000000000000000..64f57fd640c4b29c4fe06a77cdaacd39e46aaf6c --- /dev/null +++ b/Microstructure/src/microstructure/config.py @@ -0,0 +1,341 @@ +"""Typed project configuration with deterministic hashing.""" + +from __future__ import annotations + +import hashlib +import json +import math +import re +import tomllib +from collections.abc import Mapping +from dataclasses import asdict, dataclass +from datetime import UTC, datetime +from pathlib import Path +from typing import Any, Literal, cast + +from microstructure.data.schemas import SCHEMA_VERSION + + +class ConfigError(ValueError): + """Raised when a project configuration is internally inconsistent.""" + + +EvidenceTier = Literal["SYNTHETIC_SMOKE", "PUBLIC_SAMPLE_PARTIAL", "FULL_DATA"] +# Adapter modes are intentionally open-ended: ingestion owns the fail-closed +# registry, while configuration validates a stable identifier that third-party +# adapters can use. Built-in modes retain their source-specific checks below. +DataMode = str +_DATA_MODE_PATTERN = re.compile(r"[a-z][a-z0-9_.-]{0,63}") + + +def _utc_datetime(value: str) -> datetime: + parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) + if parsed.tzinfo is None: + raise ConfigError(f"timestamp must include a UTC offset: {value!r}") + return parsed.astimezone(UTC) + + +@dataclass(frozen=True, slots=True) +class RunConfig: + name: str + evidence_tier: EvidenceTier + seed: int + + +@dataclass(frozen=True, slots=True) +class DataConfig: + mode: DataMode + source: str + symbols: tuple[str, ...] + start: datetime + end: datetime | None + events_per_symbol: int | None + max_events_per_symbol: int | None + raw_root: Path + partition_root: Path + schema_version: str + base_url: str + request_limit: int + timeout_seconds: float + max_retries: int + + +@dataclass(frozen=True, slots=True) +class QualityConfig: + max_spread_bps: float + max_silence_ms: int + fail_on_error: bool + + +@dataclass(frozen=True, slots=True) +class FeatureConfig: + trade_windows: tuple[int, ...] + volatility_window: int + intensity_window: int + label_horizon_events: int + large_trade_quantile: float + + +@dataclass(frozen=True, slots=True) +class EvaluationConfig: + min_train_events: int + validation_events: int + test_events: int + step_events: int + embargo_events: int + bootstrap_samples: int + calibration_bins: int + + +@dataclass(frozen=True, slots=True) +class ModelConfig: + selection_metric: str + logistic_c_values: tuple[float, ...] + tree_max_depth_values: tuple[int, ...] + tree_min_samples_leaf: int + + +@dataclass(frozen=True, slots=True) +class ExecutionConfig: + decision_latency_events: int + order_latency_events: int + maker_fee_bps: float + taker_fee_bps: float + half_spread_bps: float + slippage_bps_per_unit: float + signal_threshold: float + max_position_units: float + order_size_units: float + limit_fill_base_probability: float + queue_ahead_units: float + limit_max_age_events: int + cancel_latency_events: int + liquidate_at_end: bool + capacity_multipliers: tuple[float, ...] + + +@dataclass(frozen=True, slots=True) +class ProjectConfig: + path: Path + project_root: Path + run: RunConfig + data: DataConfig + quality: QualityConfig + features: FeatureConfig + evaluation: EvaluationConfig + models: ModelConfig + execution: ExecutionConfig + canonical: Mapping[str, Any] + + @property + def hash(self) -> str: + """Return a stable SHA-256 hash of the source configuration.""" + payload = json.dumps(self.canonical, sort_keys=True, separators=(",", ":")) + return hashlib.sha256(payload.encode("utf-8")).hexdigest() + + def public_dict(self) -> dict[str, Any]: + """Return a JSON-safe representation with resolved paths and timestamps.""" + result = asdict(self) + result.pop("canonical") + result["path"] = str(self.path) + result["project_root"] = str(self.project_root) + data = cast(dict[str, Any], result["data"]) + data["start"] = self.data.start.isoformat().replace("+00:00", "Z") + data["end"] = self.data.end.isoformat().replace("+00:00", "Z") if self.data.end else None + data["raw_root"] = str(self.data.raw_root) + data["partition_root"] = str(self.data.partition_root) + return result + + +def _section(raw: Mapping[str, Any], name: str) -> Mapping[str, Any]: + value = raw.get(name) + if not isinstance(value, Mapping): + raise ConfigError(f"missing TOML section [{name}]") + return cast(Mapping[str, Any], value) + + +def _resolve(project_root: Path, value: str) -> Path: + candidate = Path(value) + return candidate if candidate.is_absolute() else (project_root / candidate).resolve() + + +def load_config(path: str | Path) -> ProjectConfig: + """Load and validate a project TOML configuration.""" + config_path = Path(path).resolve() + with config_path.open("rb") as handle: + raw: dict[str, Any] = tomllib.load(handle) + + project_root = config_path.parent.parent.resolve() + run_raw = _section(raw, "run") + data_raw = _section(raw, "data") + quality_raw = _section(raw, "quality") + feature_raw = _section(raw, "features") + evaluation_raw = _section(raw, "evaluation") + model_raw = _section(raw, "models") + execution_raw = _section(raw, "execution") + + evidence_tier = str(run_raw["evidence_tier"]) + if evidence_tier not in {"SYNTHETIC_SMOKE", "PUBLIC_SAMPLE_PARTIAL", "FULL_DATA"}: + raise ConfigError(f"unsupported evidence tier: {evidence_tier}") + mode = str(data_raw["mode"]) + if _DATA_MODE_PATTERN.fullmatch(mode) is None: + raise ConfigError( + "data.mode must be a lowercase adapter identifier containing only " + "letters, digits, underscores, dots, or hyphens" + ) + + start = _utc_datetime(str(data_raw["start"])) + end_value = data_raw.get("end") + end = _utc_datetime(str(end_value)) if end_value is not None else None + if end is not None and end <= start: + raise ConfigError("data.end must be after data.start") + + run = RunConfig( + name=str(run_raw["name"]), + evidence_tier=cast(EvidenceTier, evidence_tier), + seed=int(run_raw["seed"]), + ) + data = DataConfig( + mode=mode, + source=str(data_raw["source"]), + symbols=tuple(str(symbol).upper() for symbol in data_raw["symbols"]), + start=start, + end=end, + events_per_symbol=( + int(data_raw["events_per_symbol"]) + if data_raw.get("events_per_symbol") is not None + else None + ), + max_events_per_symbol=( + int(data_raw["max_events_per_symbol"]) + if data_raw.get("max_events_per_symbol") is not None + else None + ), + raw_root=_resolve(project_root, str(data_raw.get("raw_root", "data/raw"))), + partition_root=_resolve(project_root, str(data_raw["partition_root"])), + schema_version=str(data_raw["schema_version"]), + base_url=str(data_raw.get("base_url", "https://data-api.binance.vision")).rstrip("/"), + request_limit=int(data_raw.get("request_limit", 1000)), + timeout_seconds=float(data_raw.get("timeout_seconds", 30.0)), + max_retries=int(data_raw.get("max_retries", 5)), + ) + quality = QualityConfig( + max_spread_bps=float(quality_raw["max_spread_bps"]), + max_silence_ms=int(quality_raw["max_silence_ms"]), + fail_on_error=bool(quality_raw["fail_on_error"]), + ) + features = FeatureConfig( + trade_windows=tuple(int(window) for window in feature_raw["trade_windows"]), + volatility_window=int(feature_raw["volatility_window"]), + intensity_window=int(feature_raw["intensity_window"]), + label_horizon_events=int(feature_raw["label_horizon_events"]), + large_trade_quantile=float(feature_raw["large_trade_quantile"]), + ) + evaluation = EvaluationConfig( + min_train_events=int(evaluation_raw["min_train_events"]), + validation_events=int(evaluation_raw["validation_events"]), + test_events=int(evaluation_raw["test_events"]), + step_events=int(evaluation_raw["step_events"]), + embargo_events=int(evaluation_raw["embargo_events"]), + bootstrap_samples=int(evaluation_raw["bootstrap_samples"]), + calibration_bins=int(evaluation_raw["calibration_bins"]), + ) + models = ModelConfig( + selection_metric=str(model_raw["selection_metric"]), + logistic_c_values=tuple(float(value) for value in model_raw["logistic_c_values"]), + tree_max_depth_values=tuple(int(value) for value in model_raw["tree_max_depth_values"]), + tree_min_samples_leaf=int(model_raw["tree_min_samples_leaf"]), + ) + execution = ExecutionConfig( + decision_latency_events=int(execution_raw["decision_latency_events"]), + order_latency_events=int(execution_raw["order_latency_events"]), + maker_fee_bps=float(execution_raw["maker_fee_bps"]), + taker_fee_bps=float(execution_raw["taker_fee_bps"]), + half_spread_bps=float(execution_raw["half_spread_bps"]), + slippage_bps_per_unit=float(execution_raw["slippage_bps_per_unit"]), + signal_threshold=float(execution_raw["signal_threshold"]), + max_position_units=float(execution_raw["max_position_units"]), + order_size_units=float(execution_raw["order_size_units"]), + limit_fill_base_probability=float(execution_raw["limit_fill_base_probability"]), + queue_ahead_units=float(execution_raw["queue_ahead_units"]), + limit_max_age_events=int(execution_raw["limit_max_age_events"]), + cancel_latency_events=int(execution_raw["cancel_latency_events"]), + liquidate_at_end=bool(execution_raw["liquidate_at_end"]), + capacity_multipliers=tuple(float(value) for value in execution_raw["capacity_multipliers"]), + ) + + if not data.symbols: + raise ConfigError("data.symbols must not be empty") + if data.mode == "synthetic" and (data.events_per_symbol is None or data.events_per_symbol < 1): + raise ConfigError("synthetic mode requires positive data.events_per_symbol") + if data.mode == "synthetic" and run.evidence_tier != "SYNTHETIC_SMOKE": + raise ConfigError("synthetic inputs must use the SYNTHETIC_SMOKE evidence tier") + if data.mode == "binance_rest" and run.evidence_tier == "SYNTHETIC_SMOKE": + raise ConfigError("public inputs cannot use the SYNTHETIC_SMOKE evidence tier") + if data.mode == "binance_rest" and data.end is None: + raise ConfigError("binance_rest mode requires a bounded data.end") + if data.mode == "binance_rest" and ( + data.max_events_per_symbol is None or data.max_events_per_symbol < 1 + ): + raise ConfigError("binance_rest mode requires positive data.max_events_per_symbol") + if data.schema_version != SCHEMA_VERSION: + raise ConfigError( + f"unsupported data.schema_version {data.schema_version!r}; expected {SCHEMA_VERSION!r}" + ) + if not all(window > 1 for window in features.trade_windows): + raise ConfigError("all feature trade windows must exceed one event") + if features.label_horizon_events < 1: + raise ConfigError("label_horizon_events must be positive") + if evaluation.embargo_events < features.label_horizon_events: + raise ConfigError("embargo_events must cover label_horizon_events") + if not 0.5 < execution.signal_threshold < 1.0: + raise ConfigError("signal_threshold must be between 0.5 and 1.0") + if not 0.0 <= execution.limit_fill_base_probability <= 1.0: + raise ConfigError("limit_fill_base_probability must be in [0, 1]") + if execution.limit_max_age_events < 1 or execution.cancel_latency_events < 0: + raise ConfigError("limit order age must be positive and cancel latency nonnegative") + if execution.decision_latency_events < 0 or execution.order_latency_events < 0: + raise ConfigError("decision and order latency must be nonnegative") + if execution.max_position_units <= 0 or execution.order_size_units <= 0: + raise ConfigError("execution position and order sizes must be positive") + execution_floats = ( + execution.maker_fee_bps, + execution.taker_fee_bps, + execution.half_spread_bps, + execution.slippage_bps_per_unit, + execution.max_position_units, + execution.order_size_units, + execution.queue_ahead_units, + ) + if not all(math.isfinite(value) for value in execution_floats): + raise ConfigError("execution numeric assumptions must be finite") + if execution.queue_ahead_units < 0: + raise ConfigError("execution queue_ahead_units must be nonnegative") + if execution.half_spread_bps < 0 or execution.slippage_bps_per_unit < 0: + raise ConfigError("execution spread and slippage assumptions must be nonnegative") + if not execution.capacity_multipliers or not all( + math.isfinite(value) and value > 0 for value in execution.capacity_multipliers + ): + raise ConfigError("execution capacity_multipliers must be finite and positive") + if not 0.0 < features.large_trade_quantile < 1.0: + raise ConfigError("large_trade_quantile must lie strictly between zero and one") + + return ProjectConfig( + path=config_path, + project_root=project_root, + run=run, + data=data, + quality=quality, + features=features, + evaluation=evaluation, + models=models, + execution=execution, + canonical=raw, + ) + + +def datetime_to_ns(value: datetime) -> int: + """Convert an aware UTC datetime to integer epoch nanoseconds.""" + if value.tzinfo is None: + raise ConfigError("datetime must be timezone aware") + return int(value.timestamp() * 1_000_000_000) diff --git a/Microstructure/src/microstructure/data/__init__.py b/Microstructure/src/microstructure/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0dd2bb32f94bf1fc926dc9c1447ab807c0239432 --- /dev/null +++ b/Microstructure/src/microstructure/data/__init__.py @@ -0,0 +1,33 @@ +"""Market-data ingestion, normalization, storage, and validation primitives. + +The package deliberately contains no authenticated or order-entry API. Binance +support is restricted to public market-data endpoints. +""" + +from microstructure.data.book import ( + BookSnapshot, + DepthDelta, + ReconstructionResult, + reconstruct_snapshot_and_deltas, +) +from microstructure.data.quality import QualityFinding, ValidationReport, validate_table +from microstructure.data.schemas import SCHEMA_VERSION, get_schema, table_from_records +from microstructure.data.storage import DatasetWriteResult, write_partitioned_parquet +from microstructure.data.synthetic import SyntheticMarketData, generate_synthetic_market + +__all__ = [ + "SCHEMA_VERSION", + "BookSnapshot", + "DatasetWriteResult", + "DepthDelta", + "QualityFinding", + "ReconstructionResult", + "SyntheticMarketData", + "ValidationReport", + "generate_synthetic_market", + "get_schema", + "reconstruct_snapshot_and_deltas", + "table_from_records", + "validate_table", + "write_partitioned_parquet", +] diff --git a/Microstructure/src/microstructure/data/binance.py b/Microstructure/src/microstructure/data/binance.py new file mode 100644 index 0000000000000000000000000000000000000000..56577e6fbd96ebe276ea45e2610b2e2835e28644 --- /dev/null +++ b/Microstructure/src/microstructure/data/binance.py @@ -0,0 +1,1330 @@ +"""Public Binance Spot market-data adapters; no authenticated/trading endpoints.""" + +from __future__ import annotations + +import asyncio +import hashlib +import json +import os +import random +import tempfile +import time +from collections.abc import AsyncIterator, Callable, Iterator, Mapping +from contextlib import nullcontext +from dataclasses import dataclass +from decimal import Decimal, InvalidOperation +from enum import StrEnum +from pathlib import Path +from typing import Any, Literal, Protocol, cast + +import pyarrow as pa # type: ignore[import-untyped] +import requests +import websockets +from websockets.exceptions import WebSocketException + +from microstructure.data.book import BookSnapshot, DepthDelta +from microstructure.data.evidence_budget import RetainedEvidenceBudget +from microstructure.data.schemas import SCHEMA_VERSION, get_schema, table_from_records +from microstructure.data.storage import write_source_manifest +from microstructure.provenance import sha256_file + +_NS_PER_MILLISECOND = 1_000_000 +_NS_PER_MICROSECOND = 1_000 + + +class BinanceError(RuntimeError): + """Base error for public Binance market-data collection.""" + + +class BinanceHTTPError(BinanceError): + """Raised when a public market-data GET cannot be completed safely.""" + + def __init__( + self, + message: str, + *, + status_code: int | None = None, + retry_exhausted: bool = False, + ) -> None: + super().__init__(message) + self.status_code = status_code + self.retry_exhausted = retry_exhausted + + +class BinancePayloadError(BinanceError): + """Raised when Binance returns malformed or scale-incompatible data.""" + + def __init__(self, message: str, *, transient: bool = False) -> None: + super().__init__(message) + self.transient = transient + + +class BinanceMetadataContractError(BinancePayloadError): + """A bounded exchangeInfo response violates the declared metadata contract.""" + + +class BinanceResponseSizeLimitError(BinancePayloadError): + """A public response violates its frozen body-size contract.""" + + +@dataclass(frozen=True, slots=True) +class RetryPolicy: + max_retries: int = 5 + base_delay_seconds: float = 0.5 + max_delay_seconds: float = 30.0 + + def __post_init__(self) -> None: + if self.max_retries < 0: + raise ValueError("max_retries must not be negative") + if self.base_delay_seconds < 0.0 or self.max_delay_seconds < 0.0: + raise ValueError("retry delays must not be negative") + + +@dataclass(frozen=True, slots=True) +class RawPage: + path: Path + manifest_path: Path + sha256: str + request_uri: str + row_count: int + + +@dataclass(frozen=True, slots=True) +class BinanceDownloadResult: + trades: pa.Table + raw_pages: tuple[RawPage, ...] + requested_start_ns: int + requested_end_ns: int + complete_range: bool + + +class BinanceTradeStreamStopReason(StrEnum): + """Why a normally exhausted historical-trade stream stopped.""" + + EMPTY_PAGE = "empty_page" + SHORT_PAGE = "short_page" + RANGE_END = "range_end" + EVENT_CAP = "event_cap" + + +@dataclass(frozen=True, slots=True) +class BinanceTradeStreamSummary: + """Constant-size terminal metadata for a historical-trade stream.""" + + requested_start_ns: int + requested_end_ns: int + rows_yielded: int + raw_page_count: int + stop_reason: BinanceTradeStreamStopReason + complete_range: bool + last_raw_page: RawPage | None + + +@dataclass(frozen=True, slots=True) +class CapturedDepth: + raw_payload: str + delta: DepthDelta + + +@dataclass(frozen=True, slots=True) +class RawDepthFrame: + """One exact websocket frame timestamped before UTF-8/JSON normalization.""" + + payload: bytes + was_text: bool + received_ts_ns: int + capture_seq: int + continuity_id: str + + +@dataclass(frozen=True, slots=True) +class SymbolMetadata: + """Public symbol filters captured before tick/lot normalization.""" + + venue: str + symbol: str + status: str + base_asset: str + quote_asset: str + tick_size: Decimal + lot_size: Decimal + min_price: Decimal + max_price: Decimal + min_quantity: Decimal + max_quantity: Decimal + observed_ts_ns: int + source_artifact_id: str + source_path: Path + source_manifest_path: Path + + +class _WebSocketConnection(Protocol): + def __aiter__(self) -> AsyncIterator[str | bytes]: ... + + +class _WebSocketContext(Protocol): + async def __aenter__(self) -> _WebSocketConnection: ... + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: object | None, + ) -> bool | None: ... + + +ConnectFactory = Callable[[str], _WebSocketContext] +RawDepthFrameCallback = Callable[[RawDepthFrame], None] + + +def _scaled_integer(value: str | Decimal, quantum: Decimal, label: str) -> int: + try: + decimal_value = value if isinstance(value, Decimal) else Decimal(value) + scaled = decimal_value / quantum + except (InvalidOperation, ZeroDivisionError) as exc: + raise BinancePayloadError(f"invalid {label}: {value!r}") from exc + integral = scaled.to_integral_value() + if scaled != integral: + raise BinancePayloadError( + f"{label} {decimal_value} is not aligned to configured scale {quantum}" + ) + return int(integral) + + +def _event_timestamp_ns(value: int, unit: Literal["ms", "us"]) -> int: + if value < 0: + raise BinancePayloadError("event timestamp must not be negative") + return value * (_NS_PER_MILLISECOND if unit == "ms" else _NS_PER_MICROSECOND) + + +def _safe_response_headers(headers: Mapping[str, str]) -> dict[str, str]: + allowed = {"content-length", "content-type", "etag", "last-modified", "retry-after"} + return { + str(key): str(value) + for key, value in headers.items() + if key.lower() in allowed or key.lower().startswith("x-mbx-used-weight") + } + + +def _close_response(response: object) -> None: + close = getattr(response, "close", None) + if callable(close): + cast(Callable[[], object], close)() + + +def _fsync_directory(path: Path) -> None: + descriptor = os.open(path, os.O_RDONLY) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + + +class BinancePublicClient: + """Retrying client for market-data-only GET endpoints.""" + + def __init__( + self, + *, + base_url: str = "https://data-api.binance.vision", + timeout_seconds: float = 30.0, + retry_policy: RetryPolicy | None = None, + session: requests.Session | None = None, + sleep: Callable[[float], None] = time.sleep, + random_value: Callable[[], float] = random.random, + max_response_bytes: int = 8 * 1024 * 1024, + retained_evidence_budget: RetainedEvidenceBudget | None = None, + ) -> None: + if max_response_bytes < 1: + raise ValueError("max_response_bytes must be positive") + self.base_url = base_url.rstrip("/") + self.timeout_seconds = timeout_seconds + self.retry_policy = retry_policy or RetryPolicy() + self.session = session or requests.Session() + self._sleep = sleep + self._random_value = random_value + self.max_response_bytes = max_response_bytes + self.retained_evidence_budget = retained_evidence_budget + + def _session_get( + self, + url: str, + params: Mapping[str, str | int], + *, + stream_response: bool, + ) -> requests.Response: + if not stream_response: + return self.session.get(url, params=params, timeout=self.timeout_seconds) + try: + return self.session.get( + url, + params=params, + timeout=self.timeout_seconds, + stream=True, + ) + except TypeError as exc: + # Older injected test sessions may implement only the original + # three-argument boundary. Production requests.Session accepts + # ``stream`` and therefore always takes the bounded transport path. + if "unexpected keyword argument 'stream'" not in str(exc): + raise + return self.session.get(url, params=params, timeout=self.timeout_seconds) + + def _request( + self, + path: str, + params: Mapping[str, str | int], + *, + stream_response: bool = False, + ) -> requests.Response: + url = f"{self.base_url}{path}" + last_error: BaseException | None = None + for attempt in range(self.retry_policy.max_retries + 1): + response: requests.Response | None = None + try: + response = self._session_get( + url, + params, + stream_response=stream_response, + ) + except requests.RequestException as exc: + last_error = exc + retryable = True + else: + if response.status_code == 200: + return response + retryable = response.status_code in {408, 418, 429} or response.status_code >= 500 + response_detail = ( + "response body intentionally not materialized" + if stream_response + else response.text[:200] + ) + last_error = BinanceHTTPError( + f"GET {response.url} returned HTTP {response.status_code}: {response_detail}", + status_code=response.status_code, + ) + if not retryable: + _close_response(response) + raise last_error + + if not retryable or attempt >= self.retry_policy.max_retries: + if response is not None: + _close_response(response) + break + retry_after: float | None = None + if response is not None and response.status_code in {418, 429}: + raw_retry_after = response.headers.get("Retry-After") + if raw_retry_after is not None: + try: + retry_after = max(0.0, float(raw_retry_after)) + except ValueError: + retry_after = None + exponential_cap = min( + self.retry_policy.max_delay_seconds, + self.retry_policy.base_delay_seconds * (2**attempt), + ) + delay = ( + retry_after if retry_after is not None else exponential_cap * self._random_value() + ) + if response is not None: + _close_response(response) + self._sleep(delay) + status_code = last_error.status_code if isinstance(last_error, BinanceHTTPError) else None + raise BinanceHTTPError( + f"public Binance GET failed after {self.retry_policy.max_retries + 1} attempts", + status_code=status_code, + retry_exhausted=True, + ) from last_error + + def _bounded_request_body( + self, + path: str, + params: Mapping[str, str | int], + *, + raw_root: Path, + rejected_dataset: str, + symbol: str, + requested_start_ns: int | None, + requested_end_ns: int | None, + max_response_bytes: int | None = None, + ) -> tuple[bytes, str, dict[str, str], int]: + """Read one bounded body, retrying recoverable transport interruptions. + + Every interrupted attempt is persisted before retry. Payload/size + violations remain non-retryable because another identical response is + not evidence of a transient network failure. + """ + byte_ceiling = max_response_bytes or self.max_response_bytes + for attempt in range(self.retry_policy.max_retries + 1): + response = self._request(path, params, stream_response=True) + observed_ts_ns = time.time_ns() + request_uri = str(response.url) + response_headers = _safe_response_headers(response.headers) + bounded_body = _read_bounded_response_body( + response, + max_response_bytes=byte_ceiling, + ) + if bounded_body.error_message is None: + return ( + bounded_body.content, + request_uri, + response_headers, + observed_ts_ns, + ) + + rejected_headers = _rejected_response_headers(response_headers, bounded_body) + rejected_headers["x-local-body-attempt"] = str(attempt + 1) + _write_raw_response( + bounded_body.content, + raw_root=raw_root, + dataset=rejected_dataset, + symbol=symbol, + request_uri=request_uri, + downloaded_at_utc=_iso_from_ns(observed_ts_ns), + requested_start_ns=requested_start_ns, + requested_end_ns=requested_end_ns, + response_headers=rejected_headers, + retained_evidence_budget=self.retained_evidence_budget, + ) + if not bounded_body.retryable or attempt >= self.retry_policy.max_retries: + if bounded_body.retryable: + raise BinancePayloadError(bounded_body.error_message, transient=True) + raise BinanceResponseSizeLimitError(bounded_body.error_message) + exponential_cap = min( + self.retry_policy.max_delay_seconds, + self.retry_policy.base_delay_seconds * (2**attempt), + ) + self._sleep(exponential_cap * self._random_value()) + raise AssertionError("bounded response retry loop exhausted without a terminal result") + + def fetch_exchange_info(self, *, symbol: str, raw_root: str | Path) -> SymbolMetadata: + """Fetch public symbol status and exact PRICE_FILTER/LOT_SIZE scales.""" + symbol = symbol.upper() + content, request_uri, response_headers, observed_ts_ns = self._bounded_request_body( + "/api/v3/exchangeInfo", + {"symbol": symbol}, + raw_root=Path(raw_root), + rejected_dataset="exchange_info_rejected", + symbol=symbol, + requested_start_ns=None, + requested_end_ns=None, + ) + raw_page = _write_raw_response( + content, + raw_root=Path(raw_root), + dataset="exchange_info", + symbol=symbol, + request_uri=request_uri, + downloaded_at_utc=_iso_from_ns(observed_ts_ns), + requested_start_ns=None, + requested_end_ns=None, + response_headers=response_headers, + retained_evidence_budget=self.retained_evidence_budget, + ) + try: + payload = cast(dict[str, Any], json.loads(content)) + symbols = cast(list[dict[str, Any]], payload["symbols"]) + if len(symbols) != 1 or str(symbols[0]["symbol"]).upper() != symbol: + raise BinanceMetadataContractError( + "exchangeInfo did not return exactly the requested symbol" + ) + item = symbols[0] + filters = { + str(value["filterType"]): value + for value in cast(list[dict[str, Any]], item["filters"]) + } + price_filter = filters["PRICE_FILTER"] + lot_filter = filters["LOT_SIZE"] + tick_size = Decimal(str(price_filter["tickSize"])) + lot_size = Decimal(str(lot_filter["stepSize"])) + if tick_size <= 0 or lot_size <= 0: + raise BinanceMetadataContractError( + "exchangeInfo returned a nonpositive tick or lot size" + ) + return SymbolMetadata( + venue="binance_spot", + symbol=symbol, + status=str(item["status"]), + base_asset=str(item["baseAsset"]), + quote_asset=str(item["quoteAsset"]), + tick_size=tick_size, + lot_size=lot_size, + min_price=Decimal(str(price_filter["minPrice"])), + max_price=Decimal(str(price_filter["maxPrice"])), + min_quantity=Decimal(str(lot_filter["minQty"])), + max_quantity=Decimal(str(lot_filter["maxQty"])), + observed_ts_ns=observed_ts_ns, + source_artifact_id=raw_page.sha256, + source_path=raw_page.path, + source_manifest_path=raw_page.manifest_path, + ) + except (BinanceMetadataContractError, BinanceResponseSizeLimitError): + raise + except BinancePayloadError as exc: + if exc.transient: + raise + raise BinanceMetadataContractError(str(exc)) from exc + except (InvalidOperation, KeyError, TypeError, ValueError) as exc: + raise BinanceMetadataContractError("malformed Binance exchangeInfo response") from exc + + def fetch_depth_snapshot( + self, + *, + symbol: str, + raw_root: str | Path, + continuity_id: str, + tick_size: Decimal | None = None, + lot_size: Decimal | None = None, + limit: int = 5000, + ) -> BookSnapshot: + """Fetch a public REST anchor; it intentionally has no exchange event time.""" + if limit not in {5, 10, 20, 50, 100, 500, 1000, 5000}: + raise ValueError("unsupported Binance depth snapshot limit") + symbol = symbol.upper() + if (tick_size is None) != (lot_size is None): + raise ValueError("tick_size and lot_size must be supplied together") + if tick_size is None or lot_size is None: + metadata = self.fetch_exchange_info(symbol=symbol, raw_root=raw_root) + tick_size = metadata.tick_size + lot_size = metadata.lot_size + request_ts_ns = time.time_ns() + content, request_uri, response_headers, received_ts_ns = self._bounded_request_body( + "/api/v3/depth", + {"symbol": symbol, "limit": limit}, + raw_root=Path(raw_root), + rejected_dataset="depth_snapshots_rejected", + symbol=symbol, + requested_start_ns=None, + requested_end_ns=None, + ) + raw_page = _write_raw_response( + content, + raw_root=Path(raw_root), + dataset="depth_snapshots", + symbol=symbol, + request_uri=request_uri, + downloaded_at_utc=_iso_from_ns(received_ts_ns), + requested_start_ns=None, + requested_end_ns=None, + response_headers=response_headers, + retained_evidence_budget=self.retained_evidence_budget, + ) + try: + payload = cast(dict[str, Any], json.loads(content)) + bids = tuple( + ( + _scaled_integer(str(item[0]), tick_size, "bid price"), + _scaled_integer(str(item[1]), lot_size, "bid quantity"), + ) + for item in payload["bids"] + ) + asks = tuple( + ( + _scaled_integer(str(item[0]), tick_size, "ask price"), + _scaled_integer(str(item[1]), lot_size, "ask quantity"), + ) + for item in payload["asks"] + ) + last_update_id = int(payload["lastUpdateId"]) + except (KeyError, TypeError, ValueError) as exc: + raise BinancePayloadError("malformed Binance depth snapshot") from exc + return BookSnapshot( + venue="binance_spot", + symbol=symbol, + snapshot_id=raw_page.sha256, + request_ts_ns=request_ts_ns, + received_ts_ns=received_ts_ns, + available_ts_ns=received_ts_ns, + continuity_id=continuity_id, + last_update_id=last_update_id, + depth_limit=limit, + bids=bids, + asks=asks, + tick_size=float(tick_size), + lot_size=float(lot_size), + source_artifact_id=raw_page.sha256, + ) + + +@dataclass(frozen=True, slots=True) +class _ParsedAggregateTrade: + aggregate_id: int + first_trade_id: int + last_trade_id: int + event_ts_ns: int + price: Decimal + quantity: Decimal + buyer_is_maker: bool + + +def _response_header(headers: Mapping[str, str], name: str) -> str | None: + normalized_name = name.lower() + for key, value in headers.items(): + if str(key).lower() == normalized_name: + return str(value) + return None + + +@dataclass(frozen=True, slots=True) +class _BoundedResponseBody: + content: bytes + error_message: str | None + observed_bytes_lower_bound: int + retryable: bool = False + + +def _rejected_response_headers( + response_headers: Mapping[str, str], + body: _BoundedResponseBody, +) -> dict[str, str]: + """Describe a bounded rejected response in its immutable raw sidecar.""" + result = dict(response_headers) + result.update( + { + "x-local-capture-status": ( + "rejected_partial_response" if body.content else "rejected_headers_only" + ), + "x-local-captured-bytes": str(len(body.content)), + "x-local-observed-bytes-lower-bound": str(body.observed_bytes_lower_bound), + "x-local-rejection-reason": body.error_message or "unknown", + } + ) + return result + + +def _read_bounded_response_body( + response: requests.Response, + *, + max_response_bytes: int, +) -> _BoundedResponseBody: + """Read one response with a hard prefix bound on the production transport. + + A real ``requests.Response`` exposes ``iter_content`` and is consumed a + chunk at a time. Injected legacy test responses without that method fall + back to their already-materialized ``content`` attribute for compatibility. + """ + headers = response.headers + declared = _response_header(headers, "content-length") + try: + if declared is not None: + try: + declared_size = int(declared) + except ValueError: + return _BoundedResponseBody( + content=b"", + error_message="aggregate-trade response has invalid Content-Length", + observed_bytes_lower_bound=0, + ) + if declared_size < 0: + return _BoundedResponseBody( + content=b"", + error_message="aggregate-trade response has invalid Content-Length", + observed_bytes_lower_bound=0, + ) + if declared_size > max_response_bytes: + return _BoundedResponseBody( + content=b"", + error_message=( + "aggregate-trade response Content-Length exceeded the response-byte ceiling" + ), + observed_bytes_lower_bound=0, + ) + + iter_content = getattr(response, "iter_content", None) + if callable(iter_content): + chunks: list[bytes] = [] + captured_bytes = 0 + chunk_size = min(64 * 1024, max_response_bytes + 1) + iterator = cast( + Callable[..., Iterator[object]], + iter_content, + ) + try: + for raw_chunk in iterator(chunk_size=chunk_size): + if not raw_chunk: + continue + if not isinstance(raw_chunk, bytes): + return _BoundedResponseBody( + content=b"".join(chunks), + error_message=( + "aggregate-trade response yielded a non-bytes body chunk" + ), + observed_bytes_lower_bound=captured_bytes, + ) + remaining = max_response_bytes - captured_bytes + if len(raw_chunk) > remaining: + if remaining: + chunks.append(raw_chunk[:remaining]) + return _BoundedResponseBody( + content=b"".join(chunks), + error_message=( + "aggregate-trade response body exceeded the response-byte ceiling" + ), + observed_bytes_lower_bound=captured_bytes + len(raw_chunk), + ) + chunks.append(raw_chunk) + captured_bytes += len(raw_chunk) + except requests.RequestException as exc: + return _BoundedResponseBody( + content=b"".join(chunks), + error_message=( + "aggregate-trade response body was interrupted after " + f"{captured_bytes} bytes: {type(exc).__name__}" + ), + observed_bytes_lower_bound=captured_bytes, + retryable=True, + ) + return _BoundedResponseBody( + content=b"".join(chunks), + error_message=None, + observed_bytes_lower_bound=captured_bytes, + ) + + # Compatibility path for minimal injected responses. This is not used + # by requests.Response and therefore is not the production transport. + content = bytes(response.content) + if len(content) > max_response_bytes: + return _BoundedResponseBody( + content=content[:max_response_bytes], + error_message=("aggregate-trade response body exceeded the response-byte ceiling"), + observed_bytes_lower_bound=len(content), + ) + return _BoundedResponseBody( + content=content, + error_message=None, + observed_bytes_lower_bound=len(content), + ) + finally: + _close_response(response) + + +def _parse_aggregate_trade_page( + content: bytes, + *, + request_limit: int, +) -> list[_ParsedAggregateTrade]: + try: + decoded = json.loads(content) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise BinancePayloadError("malformed Binance aggregate-trade page") from exc + if not isinstance(decoded, list): + raise BinancePayloadError("malformed Binance aggregate-trade page") + if len(decoded) > request_limit: + raise BinancePayloadError("aggregate-trade response exceeded the requested page-size bound") + + parsed: list[_ParsedAggregateTrade] = [] + previous_id: int | None = None + previous_ts_ns: int | None = None + for raw_item in decoded: + if not isinstance(raw_item, dict): + raise BinancePayloadError("malformed aggregate-trade record") + item = cast(dict[str, Any], raw_item) + try: + aggregate_id = int(item["a"]) + first_trade_id = int(item.get("f", aggregate_id)) + last_trade_id = int(item.get("l", aggregate_id)) + event_ts_ns = _event_timestamp_ns(int(item["T"]), "ms") + price = Decimal(str(item["p"])) + quantity = Decimal(str(item["q"])) + buyer_is_maker = item["m"] + except (KeyError, InvalidOperation, TypeError, ValueError) as exc: + raise BinancePayloadError("malformed aggregate-trade record") from exc + if not isinstance(buyer_is_maker, bool): + raise BinancePayloadError("malformed aggregate-trade record") + if aggregate_id < 0 or first_trade_id < 0 or last_trade_id < first_trade_id: + raise BinancePayloadError("invalid aggregate-trade identifiers") + if previous_id is not None and aggregate_id <= previous_id: + raise BinancePayloadError("aggregate-trade page IDs are not strictly increasing") + if previous_ts_ns is not None and event_ts_ns < previous_ts_ns: + raise BinancePayloadError("aggregate-trade page event times are not ordered") + parsed.append( + _ParsedAggregateTrade( + aggregate_id=aggregate_id, + first_trade_id=first_trade_id, + last_trade_id=last_trade_id, + event_ts_ns=event_ts_ns, + price=price, + quantity=quantity, + buyer_is_maker=buyer_is_maker, + ) + ) + previous_id = aggregate_id + previous_ts_ns = event_ts_ns + return parsed + + +class BinanceTradeBatchStream(Iterator[pa.RecordBatch]): + """Lazy, page-bounded iterator over normalized aggregate trades. + + No HTTP request is made until the first call to :func:`next`. Each + nonempty batch comes from one retained raw response and has no more rows + than the downloader's request limit. The iterator retains only terminal + counters and the latest raw-page descriptor; callers that need every raw + descriptor can process them incrementally with ``on_raw_page``. Production + HTTP responses are consumed incrementally and stop after the first chunk + crossing ``max_response_bytes``. Minimal injected responses that do not + implement ``iter_content`` retain a compatibility-only ``content`` fallback. + """ + + def __init__( + self, + *, + client: BinancePublicClient, + raw_root: Path, + request_limit: int, + max_response_bytes: int, + tick_size: Decimal | None, + lot_size: Decimal | None, + symbol: str, + start_ts_ns: int, + end_ts_ns: int, + max_events: int, + on_raw_page: Callable[[RawPage], None] | None, + ) -> None: + if end_ts_ns <= start_ts_ns: + raise ValueError("end_ts_ns must be after start_ts_ns") + if max_events < 1: + raise ValueError("max_events must be positive") + self._client = client + self._raw_root = raw_root + self._request_limit = request_limit + self._max_response_bytes = max_response_bytes + self._tick_size = tick_size + self._lot_size = lot_size + self._symbol = symbol.upper() + self._start_ts_ns = start_ts_ns + self._end_ts_ns = end_ts_ns + self._max_events = max_events + self._on_raw_page = on_raw_page + self._params: dict[str, str | int] = { + "symbol": self._symbol, + "startTime": start_ts_ns // _NS_PER_MILLISECOND, + "endTime": (end_ts_ns - 1) // _NS_PER_MILLISECOND, + "limit": request_limit, + } + self._rows_yielded = 0 + self._raw_page_count = 0 + self._last_raw_page: RawPage | None = None + self._previous_last_id: int | None = None + self._previous_last_event_ts_ns: int | None = None + self._summary: BinanceTradeStreamSummary | None = None + self._failed = False + + def __iter__(self) -> BinanceTradeBatchStream: + return self + + @property + def rows_yielded(self) -> int: + return self._rows_yielded + + @property + def raw_page_count(self) -> int: + return self._raw_page_count + + @property + def last_raw_page(self) -> RawPage | None: + return self._last_raw_page + + @property + def summary(self) -> BinanceTradeStreamSummary: + """Return terminal metadata, failing closed before normal exhaustion.""" + if self._summary is None: + raise RuntimeError("trade stream summary is unavailable before normal exhaustion") + return self._summary + + def __next__(self) -> pa.RecordBatch: + if self._summary is not None: + raise StopIteration + if self._failed: + raise RuntimeError("trade stream cannot resume after a previous failure") + try: + return self._next_batch() + except StopIteration: + raise + except Exception: + self._failed = True + raise + + def _resolve_scales(self) -> tuple[Decimal, Decimal]: + if self._tick_size is None or self._lot_size is None: + metadata = self._client.fetch_exchange_info( + symbol=self._symbol, + raw_root=self._raw_root, + ) + self._tick_size = metadata.tick_size + self._lot_size = metadata.lot_size + return self._tick_size, self._lot_size + + def _record_page(self, raw_page: RawPage) -> None: + self._raw_page_count += 1 + self._last_raw_page = raw_page + if self._on_raw_page is not None: + self._on_raw_page(raw_page) + + def _finish(self, reason: BinanceTradeStreamStopReason) -> None: + self._summary = BinanceTradeStreamSummary( + requested_start_ns=self._start_ts_ns, + requested_end_ns=self._end_ts_ns, + rows_yielded=self._rows_yielded, + raw_page_count=self._raw_page_count, + stop_reason=reason, + complete_range=( + reason is not BinanceTradeStreamStopReason.EVENT_CAP and self._rows_yielded > 0 + ), + last_raw_page=self._last_raw_page, + ) + + def _normalize_records( + self, + items: list[_ParsedAggregateTrade], + *, + source_artifact_id: str, + tick_size: Decimal, + lot_size: Decimal, + ) -> list[dict[str, object]]: + records: list[dict[str, object]] = [] + for item in items: + price_ticks = _scaled_integer(item.price, tick_size, "trade price") + quantity_lots = _scaled_integer(item.quantity, lot_size, "trade quantity") + price = float(item.price) + quantity = float(item.quantity) + records.append( + { + "schema_version": SCHEMA_VERSION, + "venue": "binance_spot", + "symbol": self._symbol, + "event_ts_ns": item.event_ts_ns, + "received_ts_ns": None, + "available_ts_ns": item.event_ts_ns, + "availability_basis": "exchange_event_time_proxy", + "capture_seq": None, + "continuity_id": None, + "trade_id": item.aggregate_id, + "first_trade_id": item.first_trade_id, + "last_trade_id": item.last_trade_id, + "price_ticks": price_ticks, + "quantity_lots": quantity_lots, + "tick_size": float(tick_size), + "lot_size": float(lot_size), + "price": price, + "quantity": quantity, + "quote_quantity": price * quantity, + "aggressor_side": "sell" if item.buyer_is_maker else "buy", + "buyer_is_maker": item.buyer_is_maker, + "source_artifact_id": source_artifact_id, + } + ) + return records + + def _next_batch(self) -> pa.RecordBatch: + tick_size, lot_size = self._resolve_scales() + while True: + content, request_uri, response_headers, downloaded_ns = ( + self._client._bounded_request_body( + "/api/v3/aggTrades", + self._params, + raw_root=self._raw_root, + rejected_dataset="agg_trades_rejected", + symbol=self._symbol, + requested_start_ns=self._start_ts_ns, + requested_end_ns=self._end_ts_ns, + max_response_bytes=self._max_response_bytes, + ) + ) + raw_page_base = _write_raw_response( + content, + raw_root=self._raw_root, + dataset="agg_trades", + symbol=self._symbol, + request_uri=request_uri, + downloaded_at_utc=_iso_from_ns(downloaded_ns), + requested_start_ns=self._start_ts_ns, + requested_end_ns=self._end_ts_ns, + response_headers=response_headers, + retained_evidence_budget=self._client.retained_evidence_budget, + ) + parsed = _parse_aggregate_trade_page(content, request_limit=self._request_limit) + raw_page = RawPage( + path=raw_page_base.path, + manifest_path=raw_page_base.manifest_path, + sha256=raw_page_base.sha256, + request_uri=raw_page_base.request_uri, + row_count=len(parsed), + ) + self._record_page(raw_page) + if not parsed: + self._finish(BinanceTradeStreamStopReason.EMPTY_PAGE) + raise StopIteration + + first = parsed[0] + last = parsed[-1] + if self._previous_last_id is not None and first.aggregate_id <= self._previous_last_id: + raise BinancePayloadError("aggregate-trade pagination did not advance") + if ( + self._previous_last_event_ts_ns is not None + and first.event_ts_ns < self._previous_last_event_ts_ns + ): + raise BinancePayloadError("aggregate-trade pages are not time ordered") + self._previous_last_id = last.aggregate_id + self._previous_last_event_ts_ns = last.event_ts_ns + + in_range = [ + item for item in parsed if self._start_ts_ns <= item.event_ts_ns < self._end_ts_ns + ] + remaining = self._max_events - self._rows_yielded + selected = in_range[:remaining] + records = self._normalize_records( + selected, + source_artifact_id=raw_page.sha256, + tick_size=tick_size, + lot_size=lot_size, + ) + self._rows_yielded += len(records) + + terminal_reason: BinanceTradeStreamStopReason | None = None + if len(in_range) >= remaining: + terminal_reason = BinanceTradeStreamStopReason.EVENT_CAP + elif last.event_ts_ns >= self._end_ts_ns: + terminal_reason = BinanceTradeStreamStopReason.RANGE_END + elif len(parsed) < self._request_limit: + terminal_reason = BinanceTradeStreamStopReason.SHORT_PAGE + else: + self._params = { + "symbol": self._symbol, + "fromId": last.aggregate_id + 1, + "limit": self._request_limit, + } + + if terminal_reason is not None: + self._finish(terminal_reason) + if records: + table = table_from_records("trades", records) + batches = table.to_batches(max_chunksize=self._request_limit) + if len(batches) != 1: + raise BinancePayloadError("failed to construct one bounded trade batch") + return batches[0] + if terminal_reason is not None: + raise StopIteration + + +class BinanceHistoricalTradeDownloader: + """Historical aggregate-trade downloader with lazy and guarded materialized APIs.""" + + def __init__( + self, + *, + client: BinancePublicClient, + raw_root: str | Path, + request_limit: int = 1000, + max_response_bytes: int = 8 * 1024 * 1024, + materialization_max_rows: int = 100_000, + tick_size: Decimal | None = None, + lot_size: Decimal | None = None, + ) -> None: + if not 1 <= request_limit <= 1000: + raise ValueError("request_limit must be in [1, 1000]") + if max_response_bytes < 1: + raise ValueError("max_response_bytes must be positive") + if materialization_max_rows < 1: + raise ValueError("materialization_max_rows must be positive") + self.client = client + self.raw_root = Path(raw_root) + self.request_limit = request_limit + self.max_response_bytes = max_response_bytes + self.materialization_max_rows = materialization_max_rows + if (tick_size is None) != (lot_size is None): + raise ValueError("tick_size and lot_size must be supplied together") + self.tick_size = tick_size + self.lot_size = lot_size + + def stream( + self, + *, + symbol: str, + start_ts_ns: int, + end_ts_ns: int, + max_events: int, + on_raw_page: Callable[[RawPage], None] | None = None, + ) -> BinanceTradeBatchStream: + """Create a lazy ``[start, end)`` page stream without making an HTTP call.""" + return BinanceTradeBatchStream( + client=self.client, + raw_root=self.raw_root, + request_limit=self.request_limit, + max_response_bytes=self.max_response_bytes, + tick_size=self.tick_size, + lot_size=self.lot_size, + symbol=symbol, + start_ts_ns=start_ts_ns, + end_ts_ns=end_ts_ns, + max_events=max_events, + on_raw_page=on_raw_page, + ) + + def download( + self, + *, + symbol: str, + start_ts_ns: int, + end_ts_ns: int, + max_events: int, + ) -> BinanceDownloadResult: + """Materialize the lazy stream for backwards-compatible small downloads.""" + if max_events > self.materialization_max_rows: + raise ValueError( + "max_events exceeds the guarded download() materialization limit; " + "consume stream() incrementally for larger histories" + ) + raw_pages: list[RawPage] = [] + stream = self.stream( + symbol=symbol, + start_ts_ns=start_ts_ns, + end_ts_ns=end_ts_ns, + max_events=max_events, + on_raw_page=raw_pages.append, + ) + batches = list(stream) + trades = ( + pa.Table.from_batches(batches, schema=get_schema("trades")) + if batches + else table_from_records("trades", []) + ) + return BinanceDownloadResult( + trades=trades, + raw_pages=tuple(raw_pages), + requested_start_ns=start_ts_ns, + requested_end_ns=end_ts_ns, + complete_range=stream.summary.complete_range, + ) + + +def _iso_from_ns(timestamp_ns: int) -> str: + seconds, nanoseconds = divmod(timestamp_ns, 1_000_000_000) + base = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(seconds)) + return f"{base}.{nanoseconds:09d}Z" + + +def _write_raw_response( + content: bytes, + *, + raw_root: Path, + dataset: str, + symbol: str, + request_uri: str, + downloaded_at_utc: str, + requested_start_ns: int | None, + requested_end_ns: int | None, + response_headers: Mapping[str, str], + retained_evidence_budget: RetainedEvidenceBudget | None = None, +) -> RawPage: + checksum = hashlib.sha256(content).hexdigest() + directory = raw_root / "binance_spot" / dataset / symbol.upper() + destination = directory / f"{checksum}.json" + if retained_evidence_budget is not None: + retained_evidence_budget.assert_contains(destination) + transaction = ( + retained_evidence_budget.write_transaction() + if retained_evidence_budget is not None + else nullcontext() + ) + with transaction: + directory.mkdir(parents=True, exist_ok=True) + body_reservation = None + created_body = False + if destination.exists(): + if sha256_file(destination) != checksum: + raise BinancePayloadError(f"raw content-address collision at {destination}") + else: + if retained_evidence_budget is not None: + body_reservation = retained_evidence_budget.reserve( + len(content), + label=f"raw Binance response {destination.name}", + ) + try: + handle, temporary_name = tempfile.mkstemp( + dir=directory, + prefix=".raw-", + suffix=".tmp", + ) + except BaseException: + if body_reservation is not None and body_reservation.active: + body_reservation.release() + raise + try: + with os.fdopen(handle, "wb") as stream: + stream.write(content) + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary_name, destination) + _fsync_directory(directory) + created_body = True + except BaseException: + Path(temporary_name).unlink(missing_ok=True) + if body_reservation is not None and body_reservation.active: + body_reservation.release() + raise + try: + manifest_path, _ = write_source_manifest( + destination, + source="binance_spot_public_api", + source_uri=request_uri, + downloaded_at_utc=downloaded_at_utc, + requested_start_ns=requested_start_ns, + requested_end_ns=requested_end_ns, + response_headers=response_headers, + retained_evidence_budget=retained_evidence_budget, + ) + if body_reservation is not None: + body_reservation.commit() + except BaseException: + if created_body: + destination.unlink(missing_ok=True) + if body_reservation is not None and body_reservation.active: + body_reservation.release() + raise + return RawPage( + path=destination, + manifest_path=manifest_path, + sha256=checksum, + request_uri=request_uri, + row_count=0, + ) + + +def parse_depth_message( + raw_message: str | bytes, + *, + received_ts_ns: int, + capture_seq: int, + continuity_id: str, + tick_size: Decimal = Decimal("0.00000001"), + lot_size: Decimal = Decimal("0.00000001"), + timestamp_unit: Literal["ms", "us"] = "us", +) -> DepthDelta: + """Normalize raw or combined-stream Spot ``U/u`` depth payloads.""" + raw_bytes = raw_message.encode() if isinstance(raw_message, str) else raw_message + try: + decoded = json.loads(raw_bytes) + payload = decoded.get("data", decoded) + if payload.get("e") != "depthUpdate": + raise BinancePayloadError(f"unexpected websocket event: {payload.get('e')!r}") + symbol = str(payload["s"]).upper() + bids = tuple( + ( + _scaled_integer(str(item[0]), tick_size, "bid price"), + _scaled_integer(str(item[1]), lot_size, "bid quantity"), + ) + for item in payload["b"] + ) + asks = tuple( + ( + _scaled_integer(str(item[0]), tick_size, "ask price"), + _scaled_integer(str(item[1]), lot_size, "ask quantity"), + ) + for item in payload["a"] + ) + event_ts_ns = _event_timestamp_ns(int(payload["E"]), timestamp_unit) + first_update_id = int(payload["U"]) + last_update_id = int(payload["u"]) + previous = payload.get("pu") + except BinancePayloadError: + raise + except (KeyError, TypeError, ValueError, json.JSONDecodeError) as exc: + raise BinancePayloadError("malformed Binance depth websocket message") from exc + return DepthDelta( + venue="binance_spot", + symbol=symbol, + event_ts_ns=event_ts_ns, + received_ts_ns=received_ts_ns, + available_ts_ns=received_ts_ns, + availability_basis="local_receive_time", + capture_seq=capture_seq, + continuity_id=continuity_id, + first_update_id=first_update_id, + last_update_id=last_update_id, + previous_update_id=int(previous) if previous is not None else None, + bids=bids, + asks=asks, + tick_size=float(tick_size), + lot_size=float(lot_size), + source_artifact_id=hashlib.sha256(raw_bytes).hexdigest(), + ) + + +class BinanceLiveDepthCollector: + """Optional reconnecting collector for public diff-depth streams.""" + + def __init__( + self, + *, + symbols: tuple[str, ...], + websocket_base_url: str = "wss://data-stream.binance.vision", + tick_size: Decimal = Decimal("0.00000001"), + lot_size: Decimal = Decimal("0.00000001"), + max_reconnects: int = 5, + connect_factory: ConnectFactory | None = None, + on_raw_frame: RawDepthFrameCallback | None = None, + ) -> None: + if not symbols: + raise ValueError("symbols must not be empty") + self.symbols = tuple(symbol.upper() for symbol in symbols) + streams = "/".join(f"{symbol.lower()}@depth@100ms" for symbol in self.symbols) + self.url = f"{websocket_base_url.rstrip('/')}/stream?streams={streams}&timeUnit=MICROSECOND" + self.tick_size = tick_size + self.lot_size = lot_size + self.max_reconnects = max_reconnects + self._connect_factory = connect_factory or cast(ConnectFactory, websockets.connect) + self._on_raw_frame = on_raw_frame + + async def stream(self, *, max_messages: int | None = None) -> AsyncIterator[CapturedDepth]: + """Yield exact raw payloads plus normalized deltas across continuity epochs.""" + capture_seq = 0 + yielded = 0 + reconnect = 0 + while reconnect <= self.max_reconnects: + continuity_id = f"binance-live-{time.time_ns()}-{reconnect}" + try: + async with self._connect_factory(self.url) as connection: + async for raw in connection: + received_ts_ns = time.time_ns() + if isinstance(raw, bytes): + raw_bytes = raw + was_text = False + else: + raw_bytes = raw.encode("utf-8") + was_text = True + if self._on_raw_frame is not None: + self._on_raw_frame( + RawDepthFrame( + payload=raw_bytes, + was_text=was_text, + received_ts_ns=received_ts_ns, + capture_seq=capture_seq, + continuity_id=continuity_id, + ) + ) + raw_text = raw_bytes.decode("utf-8") if isinstance(raw, bytes) else raw + delta = parse_depth_message( + raw_text, + received_ts_ns=received_ts_ns, + capture_seq=capture_seq, + continuity_id=continuity_id, + tick_size=self.tick_size, + lot_size=self.lot_size, + timestamp_unit="us", + ) + yield CapturedDepth(raw_payload=raw_text, delta=delta) + capture_seq += 1 + yielded += 1 + if max_messages is not None and yielded >= max_messages: + return + reconnect += 1 + except (OSError, WebSocketException): + reconnect += 1 + if reconnect > self.max_reconnects: + raise + await asyncio.sleep(min(30.0, 0.5 * (2 ** (reconnect - 1)))) + + +def depth_deltas_table(captured: tuple[CapturedDepth, ...] | list[CapturedDepth]) -> pa.Table: + return table_from_records("depth_deltas", [item.delta.to_record() for item in captured]) diff --git a/Microstructure/src/microstructure/data/binance_archive.py b/Microstructure/src/microstructure/data/binance_archive.py new file mode 100644 index 0000000000000000000000000000000000000000..00ddcd31191cb0c7172153d663c1f2134e1ce2e6 --- /dev/null +++ b/Microstructure/src/microstructure/data/binance_archive.py @@ -0,0 +1,1459 @@ +"""Bounded acquisition and one-shot normalization of Binance daily trade archives. + +The acquisition boundary deliberately stops after authenticating the exact ZIP +bytes and inspecting bounded ZIP metadata. CSV rows are not opened until a +caller explicitly requests a normalized stream. That separation lets a study +write an analysis lock before either held-out archive is exposed to research +code. +""" + +from __future__ import annotations + +import hashlib +import math +import os +import random +import re +import stat +import struct +import tempfile +import time +import zipfile +from collections.abc import Callable, Generator, Iterator, Mapping +from contextlib import nullcontext +from dataclasses import dataclass +from datetime import UTC, date, datetime, timedelta +from decimal import Decimal, InvalidOperation +from pathlib import Path +from typing import Any, BinaryIO, Literal, Protocol, cast +from urllib.parse import urlsplit + +import pyarrow as pa # type: ignore[import-untyped] +import requests + +from microstructure.data.binance import RetryPolicy +from microstructure.data.evidence_budget import ( + EvidenceBudgetError, + EvidenceReservation, + RetainedEvidenceBudget, +) +from microstructure.data.schemas import SCHEMA_VERSION, table_from_records +from microstructure.data.storage import write_source_manifest +from microstructure.provenance import sha256_file, utc_now_iso + +_DEFAULT_BASE_URL = "https://data.binance.vision" +_SAFE_SYMBOL = re.compile(r"^[A-Z0-9]{2,20}$") +_SAFE_ARCHIVE_NAME = re.compile(r"^[A-Z0-9]{2,20}-aggTrades-\d{4}-\d{2}-\d{2}\.zip$") +_CHECKSUM_LINE = re.compile(rb"([0-9a-f]{64}) ([A-Za-z0-9_.-]+)(?:\r\n|\n)?") +_UNSIGNED_INTEGER = re.compile(rb"(?:0|[1-9][0-9]*)") +_EOCD_SIGNATURE = b"PK\x05\x06" +_EOCD_STRUCT = struct.Struct("<4s4H2LH") +_LOCAL_FILE_SIGNATURE = b"PK\x03\x04" +_LOCAL_FILE_STRUCT = struct.Struct("<4s5H3L2H") +_MAX_EOCD_BYTES = 22 + 65_535 +_MAX_ZIP_ENTRY_METADATA_BYTES = 256 * 1_024 +_MAX_DECIMAL_FIELD_BYTES = 64 +_MAX_INT64 = (1 << 63) - 1 +_MICROSECOND_ARCHIVE_START = date(2025, 1, 1) + + +class BinanceArchiveError(RuntimeError): + """Base failure for immutable Binance archive acquisition or parsing.""" + + +class BinanceArchiveHTTPError(BinanceArchiveError): + """Raised when a bounded public archive response cannot be acquired.""" + + def __init__( + self, + message: str, + *, + status_code: int | None = None, + retry_exhausted: bool = False, + ) -> None: + super().__init__(message) + self.status_code = status_code + self.retry_exhausted = retry_exhausted + + +class BinanceArchivePayloadError(BinanceArchiveError): + """Raised when archive bytes or CSV rows violate their frozen contract.""" + + +ArchiveAcquisitionReasonCode = Literal[ + "CHECKSUM_CONTRACT", + "ZIP_CONTRACT", + "RESPONSE_SIZE_LIMIT", +] + + +class BinanceArchiveContractError(BinanceArchivePayloadError): + """A deterministic raw archive/checksum contract failure before CSV open.""" + + def __init__(self, message: str, *, reason_code: ArchiveAcquisitionReasonCode) -> None: + super().__init__(message) + self.reason_code = reason_code + + +class _RetryableDownloadError(BinanceArchiveHTTPError): + """Internal marker for one recoverable, already-evidenced HTTP attempt.""" + + def __init__(self, message: str, *, retry_after_seconds: float | None = None) -> None: + super().__init__(message) + self.retry_after_seconds = retry_after_seconds + + +class _StreamingResponse(Protocol): + status_code: int + headers: Mapping[str, str] + url: str + + def iter_content(self, *, chunk_size: int) -> Iterator[bytes]: ... + + def close(self) -> object: ... + + +class _StreamingSession(Protocol): + def get(self, url: str, *, timeout: float, stream: bool) -> _StreamingResponse: ... + + +@dataclass(frozen=True, slots=True) +class DailyArchiveRequest: + """One exact official UTC-day archive plus normalization scales.""" + + symbol: str + date: date + tick_size: Decimal + lot_size: Decimal + + def __post_init__(self) -> None: + if not isinstance(self.symbol, str) or _SAFE_SYMBOL.fullmatch(self.symbol) is None: + raise ValueError("archive symbol must be uppercase ASCII letters/digits") + if type(self.date) is not date: + raise ValueError("archive date must be a datetime.date") + if not isinstance(self.tick_size, Decimal): + raise ValueError("tick_size must be a Decimal") + if ( + not self.tick_size.is_finite() + or self.tick_size <= 0 + or not math.isfinite(float(self.tick_size)) + or float(self.tick_size) <= 0 + ): + raise ValueError("tick_size must be a positive finite Decimal") + if not isinstance(self.lot_size, Decimal): + raise ValueError("lot_size must be a Decimal") + if ( + not self.lot_size.is_finite() + or self.lot_size <= 0 + or not math.isfinite(float(self.lot_size)) + or float(self.lot_size) <= 0 + ): + raise ValueError("lot_size must be a positive finite Decimal") + + @property + def archive_name(self) -> str: + return f"{self.symbol}-aggTrades-{self.date.isoformat()}.zip" + + @property + def member_name(self) -> str: + return self.archive_name.removesuffix(".zip") + ".csv" + + @property + def continuity_id(self) -> str: + return f"binance_spot:{self.symbol}:{self.date.isoformat()}" + + +@dataclass(frozen=True, slots=True) +class ArchiveDownloadLimits: + """Hard transport, expansion, and record-boundary ceilings.""" + + max_compressed_bytes: int + max_uncompressed_bytes: int + max_checksum_bytes: int = 4_096 + transfer_chunk_bytes: int = 64 * 1_024 + max_csv_line_bytes: int = 16 * 1_024 + + def __post_init__(self) -> None: + values = ( + self.max_compressed_bytes, + self.max_uncompressed_bytes, + self.max_checksum_bytes, + self.transfer_chunk_bytes, + self.max_csv_line_bytes, + ) + if any( + isinstance(value, bool) or not isinstance(value, int) or value < 1 for value in values + ): + raise ValueError("all archive byte limits must be positive integers") + + +@dataclass(frozen=True, slots=True) +class RawArchiveArtifact: + """Immutable descriptor for an exact public response body.""" + + kind: Literal["archive_zip", "archive_checksum", "rejected_prefix"] + path: Path + manifest_path: Path + sha256: str + manifest_sha256: str + bytes: int + source_uri: str + + +@dataclass(frozen=True, slots=True) +class DailyArchiveSummary: + """Non-economic coverage facts available only after full stream exhaustion.""" + + symbol: str + date: str + rows: int + first_trade_id: int + last_trade_id: int + first_event_ts_ns: int + last_event_ts_ns: int + compressed_bytes: int + expanded_bytes: int + source_archive_sha256: str + member_name: str + continuity_id: str + + +@dataclass(frozen=True, slots=True) +class _ZipDescriptor: + member_name: str + declared_uncompressed_bytes: int + + +@dataclass(frozen=True, slots=True) +class _ZipDirectoryBounds: + offset: int + bytes: int + + +@dataclass(frozen=True, slots=True) +class _DownloadedBody: + temporary_path: Path + sha256: str + bytes: int + response_headers: Mapping[str, str] + downloaded_at_utc: str + evidence_reservations: tuple[EvidenceReservation, ...] + + +@dataclass(frozen=True, slots=True) +class AcquiredDailyArchive: + """Checksum-authenticated raw bytes whose CSV has not yet been opened.""" + + request: DailyArchiveRequest + archive_artifact: RawArchiveArtifact + checksum_artifact: RawArchiveArtifact + upstream_sha256: str + declared_uncompressed_bytes: int + limits: ArchiveDownloadLimits + requires_member_open_guard: bool = False + + def iter_normalized_batches( + self, + *, + batch_rows: int = 65_536, + before_member_open: Callable[[], None] | None = None, + ) -> DailyArchiveTradeStream: + """Create a fresh one-shot normalized stream over the authenticated ZIP. + + ``before_member_open`` is a fail-closed held-out-data guard. It runs + after bounded ZIP-directory validation and immediately before the CSV + member is opened. A raised exception therefore exposes zero member + bytes. Acquisition callers normally leave it unset; prospective + research pipelines use it to revalidate their durable analysis lock + at the actual economic-data boundary. + + Handles reconstructed for a frozen held-out role set + ``requires_member_open_guard``. Such a stream refuses to advance at + all unless this callback is supplied; the generic archive adapter and + development-date handles retain their backward-compatible default. + """ + if isinstance(batch_rows, bool) or not isinstance(batch_rows, int) or batch_rows < 1: + raise ValueError("batch_rows must be a positive integer") + return DailyArchiveTradeStream( + _stream_normalized_batches( + self, + batch_rows=batch_rows, + before_member_open=before_member_open, + ) + ) + + +class DailyArchiveTradeStream(Iterator[pa.RecordBatch]): + """One-shot RecordBatch iterator with a terminal-only coverage summary.""" + + def __init__( + self, + generator: Generator[pa.RecordBatch, None, DailyArchiveSummary], + ) -> None: + self._generator = generator + self._summary: DailyArchiveSummary | None = None + self._closed = False + + def __iter__(self) -> DailyArchiveTradeStream: + return self + + def __next__(self) -> pa.RecordBatch: + if self._closed: + raise StopIteration + try: + return next(self._generator) + except StopIteration as stop: + self._closed = True + self._summary = cast(DailyArchiveSummary, stop.value) + raise + except BaseException: + self._closed = True + raise + + @property + def summary(self) -> DailyArchiveSummary: + if self._summary is None: + raise RuntimeError("archive summary is unavailable before full stream exhaustion") + return self._summary + + def close(self) -> None: + if not self._closed: + self._generator.close() + self._closed = True + + +def _day_bounds_ns(value: date) -> tuple[int, int]: + start = datetime(value.year, value.month, value.day, tzinfo=UTC) + end = start + timedelta(days=1) + return int(start.timestamp()) * 1_000_000_000, int(end.timestamp()) * 1_000_000_000 + + +def _safe_headers(headers: Mapping[str, str]) -> dict[str, str]: + allowed = { + "content-length", + "content-type", + "etag", + "last-modified", + "retry-after", + } + return {str(key): str(value) for key, value in headers.items() if str(key).lower() in allowed} + + +def _header(headers: Mapping[str, str], name: str) -> str | None: + lowered = name.lower() + for key, value in headers.items(): + if str(key).lower() == lowered: + return str(value) + return None + + +def _content_length(headers: Mapping[str, str]) -> int | None: + raw = _header(headers, "content-length") + if raw is None: + return None + if not raw.isascii() or not raw.isdecimal(): + raise BinanceArchivePayloadError("response Content-Length must be an unsigned integer") + return int(raw) + + +def _retry_after_seconds(headers: Mapping[str, str]) -> float | None: + raw = _header(headers, "retry-after") + if raw is None: + return None + try: + value = float(raw) + except ValueError: + return None + if not math.isfinite(value) or value < 0: + return None + return value + + +def _validate_base_url(value: str) -> str: + normalized = value.rstrip("/") + parsed = urlsplit(normalized) + if parsed.scheme != "https" or not parsed.netloc or parsed.path not in {"", "/"}: + raise ValueError("archive base_url must be an HTTPS origin without path/query") + if parsed.query or parsed.fragment or parsed.username or parsed.password: + raise ValueError("archive base_url must not contain credentials, query, or fragment") + return normalized + + +def _archive_urls(base_url: str, request: DailyArchiveRequest) -> tuple[str, str]: + archive = f"{base_url}/data/spot/daily/aggTrades/{request.symbol}/{request.archive_name}" + return archive, f"{archive}.CHECKSUM" + + +def _release_evidence_reservations( + reservations: tuple[EvidenceReservation, ...] | list[EvidenceReservation], +) -> None: + for reservation in reservations: + if reservation.active: + reservation.release() + + +def _commit_evidence_reservations( + reservations: tuple[EvidenceReservation, ...] | list[EvidenceReservation], +) -> None: + for reservation in reservations: + reservation.commit() + + +def _discard_download(body: _DownloadedBody) -> None: + body.temporary_path.unlink(missing_ok=True) + _release_evidence_reservations(body.evidence_reservations) + + +def _fsync_directory(path: Path) -> None: + descriptor = os.open(path, os.O_RDONLY) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + + +def _publish_temp( + temporary: Path, + *, + destination_directory: Path, + suffix: str, + destination_name: str | None = None, + kind: Literal["archive_zip", "archive_checksum", "rejected_prefix"], + source: str, + source_uri: str, + downloaded_at_utc: str, + request: DailyArchiveRequest, + sha256: str, + response_headers: Mapping[str, str], + upstream_checksum_sha256: str | None, + retained_evidence_budget: RetainedEvidenceBudget | None = None, + evidence_reservations: tuple[EvidenceReservation, ...] = (), +) -> RawArchiveArtifact: + destination = destination_directory / (destination_name or f"{sha256}{suffix}") + if retained_evidence_budget is None and evidence_reservations: + raise BinanceArchiveError("download reservations require a retained-evidence budget") + if retained_evidence_budget is not None: + retained_evidence_budget.assert_contains(temporary) + retained_evidence_budget.assert_contains(destination) + transaction = ( + retained_evidence_budget.write_transaction() + if retained_evidence_budget is not None + else nullcontext() + ) + created_destination = False + try: + with transaction: + destination_directory.mkdir(parents=True, exist_ok=True) + if destination.exists(): + if sha256_file(destination) != sha256: + raise BinanceArchivePayloadError(f"content-address collision at {destination}") + temporary.unlink(missing_ok=True) + _release_evidence_reservations(evidence_reservations) + else: + os.replace(temporary, destination) + _fsync_directory(destination_directory) + created_destination = True + start_ns, end_ns = _day_bounds_ns(request.date) + manifest_path, manifest_sha = write_source_manifest( + destination, + source=source, + source_uri=source_uri, + downloaded_at_utc=downloaded_at_utc, + requested_start_ns=start_ns, + requested_end_ns=end_ns, + upstream_checksum_sha256=upstream_checksum_sha256, + response_headers=response_headers, + retained_evidence_budget=retained_evidence_budget, + ) + if created_destination: + _commit_evidence_reservations(evidence_reservations) + return RawArchiveArtifact( + kind=kind, + path=destination, + manifest_path=manifest_path, + sha256=sha256, + manifest_sha256=manifest_sha, + bytes=destination.stat().st_size, + source_uri=source_uri, + ) + except BaseException: + temporary.unlink(missing_ok=True) + if created_destination: + destination.unlink(missing_ok=True) + _release_evidence_reservations(evidence_reservations) + raise + + +def _publish_rejected( + temporary: Path, + *, + raw_root: Path, + request: DailyArchiveRequest, + source_uri: str, + downloaded_at_utc: str, + response_headers: Mapping[str, str], + reason: str, + suffix: str, + attempt_number: int | None = None, + retained_evidence_budget: RetainedEvidenceBudget | None = None, + evidence_reservations: tuple[EvidenceReservation, ...] = (), +) -> RawArchiveArtifact: + digest = sha256_file(temporary) + headers = dict(response_headers) + headers.update( + { + "x-local-capture-status": "rejected_bounded_prefix", + "x-local-rejection-reason": reason, + "x-local-captured-bytes": str(temporary.stat().st_size), + } + ) + if attempt_number is not None: + headers["x-local-download-attempt"] = str(attempt_number) + return _publish_temp( + temporary, + destination_directory=( + raw_root + / "binance_spot" + / "daily_agg_trades_archive_rejected" + / request.symbol + / request.date.isoformat() + ), + suffix=suffix, + kind="rejected_prefix", + source="binance_spot_daily_aggtrades_archive_rejected", + source_uri=source_uri, + downloaded_at_utc=downloaded_at_utc, + request=request, + sha256=digest, + response_headers=headers, + upstream_checksum_sha256=None, + retained_evidence_budget=retained_evidence_budget, + evidence_reservations=evidence_reservations, + ) + + +def _bounded_download_once( + session: _StreamingSession, + *, + url: str, + raw_root: Path, + request: DailyArchiveRequest, + byte_limit: int, + chunk_bytes: int, + timeout_seconds: float, + rejected_suffix: str, + attempt_number: int, + retained_evidence_budget: RetainedEvidenceBudget | None, +) -> _DownloadedBody: + work = raw_root / "binance_spot" / ".archive_downloads" + if retained_evidence_budget is not None: + retained_evidence_budget.assert_contains(work) + work.mkdir(parents=True, exist_ok=True) + descriptor, temporary_name = tempfile.mkstemp(dir=work, prefix=".download-", suffix=".tmp") + temporary = Path(temporary_name) + response: _StreamingResponse | None = None + downloaded_at = utc_now_iso() + safe_headers: dict[str, str] = {} + digest = hashlib.sha256() + captured = 0 + error: BaseException | None = None + evidence_reservations: list[EvidenceReservation] = [] + + def write_chunk(sink: Any, chunk: bytes) -> None: + reservation = ( + retained_evidence_budget.reserve( + len(chunk), + label=f"raw Binance archive response from {url}", + ) + if retained_evidence_budget is not None + else None + ) + if reservation is not None: + evidence_reservations.append(reservation) + try: + sink.write(chunk) + except BaseException: + if reservation is not None: + evidence_reservations.pop() + reservation.release() + raise + + try: + with os.fdopen(descriptor, "wb") as sink: + descriptor = -1 + try: + response = session.get(url, timeout=timeout_seconds, stream=True) + except requests.RequestException as exc: + raise _RetryableDownloadError(f"GET {url} failed before a response") from exc + safe_headers = _safe_headers(response.headers) + if str(response.url) != url: + raise BinanceArchiveHTTPError("archive response redirected away from exact URL") + if response.status_code != 200: + status_code = response.status_code + message = f"GET {url} returned HTTP {status_code}" + if status_code in {408, 418, 429} or 500 <= status_code <= 599: + retry_after = ( + _retry_after_seconds(response.headers) + if status_code in {418, 429} + else None + ) + raise _RetryableDownloadError( + message, + retry_after_seconds=retry_after, + ) + raise BinanceArchiveHTTPError(message, status_code=status_code) + declared = _content_length(response.headers) + if declared is not None and declared > byte_limit: + raise BinanceArchivePayloadError( + f"response Content-Length {declared} exceeds byte ceiling {byte_limit}" + ) + try: + chunks = response.iter_content(chunk_size=chunk_bytes) + for chunk in chunks: + if not isinstance(chunk, bytes): + raise BinanceArchivePayloadError("streaming response emitted non-bytes") + if not chunk: + continue + remaining = byte_limit - captured + if len(chunk) > remaining: + prefix = chunk[:remaining] + if prefix: + write_chunk(sink, prefix) + digest.update(prefix) + captured += len(prefix) + raise BinanceArchivePayloadError( + f"response body exceeds byte ceiling {byte_limit}" + ) + write_chunk(sink, chunk) + digest.update(chunk) + captured += len(chunk) + except requests.RequestException as exc: + raise _RetryableDownloadError( + f"GET {url} body interrupted after {captured} bytes" + ) from exc + if declared is not None and captured < declared: + raise _RetryableDownloadError( + f"GET {url} body truncated at {captured} of {declared} Content-Length bytes" + ) + if declared is not None and captured > declared: + raise BinanceArchivePayloadError( + f"GET {url} body length {captured} exceeds Content-Length {declared}" + ) + sink.flush() + os.fsync(sink.fileno()) + except BaseException as exc: + error = exc + finally: + if descriptor >= 0: + os.close(descriptor) + if response is not None: + try: + response.close() + except BaseException as exc: + if error is None: + error = BinanceArchiveHTTPError(f"GET {url} response could not be closed") + error.__cause__ = exc + + if error is not None: + try: + _publish_rejected( + temporary, + raw_root=raw_root, + request=request, + source_uri=url, + downloaded_at_utc=downloaded_at, + response_headers=safe_headers, + reason=str(error), + suffix=rejected_suffix, + attempt_number=attempt_number, + retained_evidence_budget=retained_evidence_budget, + evidence_reservations=tuple(evidence_reservations), + ) + except BaseException as evidence_error: + temporary.unlink(missing_ok=True) + _release_evidence_reservations(evidence_reservations) + if isinstance(evidence_error, EvidenceBudgetError): + raise + if not isinstance(evidence_error, Exception): + raise + raise BinanceArchiveError( + f"could not retain rejected download attempt {attempt_number}" + ) from evidence_error + raise error + return _DownloadedBody( + temporary_path=temporary, + sha256=digest.hexdigest(), + bytes=captured, + response_headers=safe_headers, + downloaded_at_utc=downloaded_at, + evidence_reservations=tuple(evidence_reservations), + ) + + +def _bounded_download( + session: _StreamingSession, + *, + url: str, + raw_root: Path, + request: DailyArchiveRequest, + byte_limit: int, + chunk_bytes: int, + timeout_seconds: float, + rejected_suffix: str, + retry_policy: RetryPolicy, + sleep: Callable[[float], None], + random_value: Callable[[], float], + retained_evidence_budget: RetainedEvidenceBudget | None, +) -> _DownloadedBody: + attempts = retry_policy.max_retries + 1 + for attempt_index in range(attempts): + try: + return _bounded_download_once( + session, + url=url, + raw_root=raw_root, + request=request, + byte_limit=byte_limit, + chunk_bytes=chunk_bytes, + timeout_seconds=timeout_seconds, + rejected_suffix=rejected_suffix, + attempt_number=attempt_index + 1, + retained_evidence_budget=retained_evidence_budget, + ) + except _RetryableDownloadError as error: + if attempt_index >= retry_policy.max_retries: + error.add_note(f"exhausted {attempts} bounded download attempts") + error.retry_exhausted = True + raise + if error.retry_after_seconds is not None: + delay = error.retry_after_seconds + else: + exponential_cap = min( + retry_policy.max_delay_seconds, + retry_policy.base_delay_seconds * (2**attempt_index), + ) + jitter = random_value() + if ( + isinstance(jitter, bool) + or not isinstance(jitter, (int, float)) + or not math.isfinite(jitter) + or not 0 <= jitter <= 1 + ): + raise ValueError("random_value must return a finite number in [0, 1]") from None + delay = exponential_cap * jitter + sleep(delay) + raise AssertionError("archive retry loop exhausted without a terminal result") + + +def _read_bounded_file(path: Path, *, byte_limit: int) -> bytes: + with path.open("rb") as source: + content = source.read(byte_limit + 1) + if len(content) > byte_limit: + raise BinanceArchivePayloadError(f"artifact exceeds read ceiling {byte_limit}") + return content + + +def _parse_checksum(content: bytes, *, archive_name: str) -> str: + match = _CHECKSUM_LINE.fullmatch(content) + if match is None: + raise BinanceArchivePayloadError( + "archive CHECKSUM must be one lowercase SHA-256 and exact basename" + ) + digest = match.group(1).decode("ascii") + filename = match.group(2).decode("ascii") + if filename != archive_name or _SAFE_ARCHIVE_NAME.fullmatch(filename) is None: + raise BinanceArchivePayloadError("archive CHECKSUM names an unexpected file") + return digest + + +def _preflight_eocd_handle(source: BinaryIO, size: int) -> _ZipDirectoryBounds: + if size < _EOCD_STRUCT.size: + raise BinanceArchivePayloadError("archive is too small to contain a ZIP directory") + tail_size = min(size, _MAX_EOCD_BYTES) + source.seek(size - tail_size) + tail = source.read(tail_size) + offset = tail.rfind(_EOCD_SIGNATURE) + if offset < 0 or len(tail) - offset < _EOCD_STRUCT.size: + raise BinanceArchivePayloadError("archive ZIP end-of-directory record is missing") + values = _EOCD_STRUCT.unpack_from(tail, offset) + _, disk, central_disk, entries_disk, entries_total, central_bytes, central_offset, comment = ( + values + ) + absolute_offset = size - tail_size + offset + if absolute_offset + _EOCD_STRUCT.size + comment != size: + raise BinanceArchivePayloadError("archive ZIP has trailing or malformed directory bytes") + if disk != 0 or central_disk != 0 or entries_disk != 1 or entries_total != 1: + raise BinanceArchivePayloadError("archive ZIP must contain exactly one single-disk member") + if central_bytes == 0 or central_bytes > _MAX_ZIP_ENTRY_METADATA_BYTES: + raise BinanceArchivePayloadError( + "archive ZIP central directory exceeds its metadata byte ceiling" + ) + if central_offset + central_bytes != absolute_offset: + raise BinanceArchivePayloadError("archive ZIP central-directory bounds are invalid") + return _ZipDirectoryBounds(offset=central_offset, bytes=central_bytes) + + +def _validate_local_file_header_handle( + source: BinaryIO, + *, + info: zipfile.ZipInfo, + expected_member: str, + central_offset: int, +) -> None: + header_offset = int(info.header_offset) + if header_offset < 0 or header_offset + _LOCAL_FILE_STRUCT.size > central_offset: + raise BinanceArchivePayloadError("archive ZIP local-header bounds are invalid") + source.seek(header_offset) + header = source.read(_LOCAL_FILE_STRUCT.size) + if len(header) != _LOCAL_FILE_STRUCT.size: + raise BinanceArchivePayloadError("archive ZIP local header is truncated") + ( + signature, + _version, + flags, + compression, + _modified_time, + _modified_date, + _crc32, + _compressed_bytes, + _uncompressed_bytes, + filename_bytes, + extra_bytes, + ) = _LOCAL_FILE_STRUCT.unpack(header) + if signature != _LOCAL_FILE_SIGNATURE: + raise BinanceArchivePayloadError("archive ZIP local-header signature is invalid") + metadata_bytes = filename_bytes + extra_bytes + if metadata_bytes > _MAX_ZIP_ENTRY_METADATA_BYTES: + raise BinanceArchivePayloadError( + "archive ZIP local header exceeds its metadata byte ceiling" + ) + if header_offset + _LOCAL_FILE_STRUCT.size + metadata_bytes > central_offset: + raise BinanceArchivePayloadError("archive ZIP local-header bounds are invalid") + local_name = source.read(filename_bytes) + if local_name != expected_member.encode("ascii"): + raise BinanceArchivePayloadError("archive ZIP local member path/name is invalid") + if flags != info.flag_bits or compression != info.compress_type: + raise BinanceArchivePayloadError("archive ZIP local and central metadata disagree") + + +def _validate_zip_structure_handle( + source: BinaryIO, + size: int, + *, + expected_member: str, + max_uncompressed_bytes: int, +) -> _ZipDescriptor: + try: + directory = _preflight_eocd_handle(source, size) + source.seek(0) + with zipfile.ZipFile(source) as archive: + infos = archive.infolist() + if len(infos) != 1: + raise BinanceArchivePayloadError("archive ZIP must contain exactly one member") + info = infos[0] + mode = info.external_attr >> 16 + if ( + info.filename != expected_member + or Path(info.filename).name != info.filename + or "\\" in info.filename + or info.is_dir() + ): + raise BinanceArchivePayloadError("archive ZIP member path/name is invalid") + if stat.S_ISLNK(mode) or info.flag_bits & 0x1: + raise BinanceArchivePayloadError( + "archive ZIP member must be regular and unencrypted" + ) + if info.compress_type not in {zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED}: + raise BinanceArchivePayloadError("archive ZIP uses an unsupported compression type") + if info.file_size < 1 or info.file_size > max_uncompressed_bytes: + raise BinanceArchiveContractError( + "archive member declared uncompressed bytes outside configured ceiling", + reason_code="RESPONSE_SIZE_LIMIT", + ) + _validate_local_file_header_handle( + source, + info=info, + expected_member=expected_member, + central_offset=directory.offset, + ) + return _ZipDescriptor( + member_name=info.filename, + declared_uncompressed_bytes=int(info.file_size), + ) + except BinanceArchivePayloadError: + raise + except (OSError, RuntimeError, zipfile.BadZipFile) as exc: + raise BinanceArchivePayloadError("cannot inspect archive ZIP structure") from exc + + +def _validate_zip_structure( + path: Path, + *, + expected_member: str, + max_uncompressed_bytes: int, +) -> _ZipDescriptor: + with path.open("rb") as source: + return _validate_zip_structure_handle( + source, + os.fstat(source.fileno()).st_size, + expected_member=expected_member, + max_uncompressed_bytes=max_uncompressed_bytes, + ) + + +class BinanceArchiveClient: + """HTTP boundary for official checksum-authenticated daily Spot archives.""" + + def __init__( + self, + *, + session: _StreamingSession | None = None, + base_url: str = _DEFAULT_BASE_URL, + timeout_seconds: float = 30.0, + retry_policy: RetryPolicy | None = None, + sleep: Callable[[float], None] = time.sleep, + random_value: Callable[[], float] = random.random, + retained_evidence_budget: RetainedEvidenceBudget | None = None, + ) -> None: + if ( + isinstance(timeout_seconds, bool) + or not isinstance(timeout_seconds, (int, float)) + or not math.isfinite(timeout_seconds) + or timeout_seconds <= 0 + ): + raise ValueError("timeout_seconds must be positive") + self.session = ( + session + if session is not None + else cast(_StreamingSession, cast(object, requests.Session())) + ) + self.base_url = _validate_base_url(base_url) + self.timeout_seconds = timeout_seconds + self.retry_policy = retry_policy or RetryPolicy() + self._sleep = sleep + self._random_value = random_value + self.retained_evidence_budget = retained_evidence_budget + + def acquire( + self, + request: DailyArchiveRequest, + *, + raw_root: str | Path, + limits: ArchiveDownloadLimits, + ) -> AcquiredDailyArchive: + """Acquire exact raw bytes without opening the archive CSV member.""" + destination_root = Path(raw_root).resolve() + archive_url, checksum_url = _archive_urls(self.base_url, request) + try: + checksum_body = _bounded_download( + self.session, + url=checksum_url, + raw_root=destination_root, + request=request, + byte_limit=limits.max_checksum_bytes, + chunk_bytes=min(limits.transfer_chunk_bytes, limits.max_checksum_bytes), + timeout_seconds=self.timeout_seconds, + rejected_suffix=".CHECKSUM.rejected", + retry_policy=self.retry_policy, + sleep=self._sleep, + random_value=self._random_value, + retained_evidence_budget=self.retained_evidence_budget, + ) + except BinanceArchiveContractError: + raise + except BinanceArchivePayloadError as exc: + raise BinanceArchiveContractError( + str(exc), + reason_code="RESPONSE_SIZE_LIMIT", + ) from exc + try: + checksum_directory = ( + destination_root + / "binance_spot" + / "daily_agg_trades_archive_checksums" + / request.symbol + / request.date.isoformat() + ) + checksum_destination = checksum_directory / f"{request.archive_name}.CHECKSUM" + if ( + checksum_destination.exists() + and sha256_file(checksum_destination) != checksum_body.sha256 + ): + _publish_rejected( + checksum_body.temporary_path, + raw_root=destination_root, + request=request, + source_uri=checksum_url, + downloaded_at_utc=checksum_body.downloaded_at_utc, + response_headers=checksum_body.response_headers, + reason="official CHECKSUM basename already contains different immutable bytes", + suffix=".CHECKSUM.rejected", + retained_evidence_budget=self.retained_evidence_budget, + evidence_reservations=checksum_body.evidence_reservations, + ) + raise BinanceArchivePayloadError( + "official CHECKSUM basename collides with different immutable bytes" + ) + checksum_artifact = _publish_temp( + checksum_body.temporary_path, + destination_directory=checksum_directory, + suffix=".CHECKSUM", + destination_name=f"{request.archive_name}.CHECKSUM", + kind="archive_checksum", + source="binance_spot_daily_aggtrades_archive_checksum", + source_uri=checksum_url, + downloaded_at_utc=checksum_body.downloaded_at_utc, + request=request, + sha256=checksum_body.sha256, + response_headers=checksum_body.response_headers, + upstream_checksum_sha256=None, + retained_evidence_budget=self.retained_evidence_budget, + evidence_reservations=checksum_body.evidence_reservations, + ) + except BaseException: + _discard_download(checksum_body) + raise + try: + upstream_sha = _parse_checksum( + _read_bounded_file(checksum_artifact.path, byte_limit=limits.max_checksum_bytes), + archive_name=request.archive_name, + ) + except BinanceArchivePayloadError as exc: + raise BinanceArchiveContractError( + str(exc), + reason_code="CHECKSUM_CONTRACT", + ) from exc + + try: + archive_body = _bounded_download( + self.session, + url=archive_url, + raw_root=destination_root, + request=request, + byte_limit=limits.max_compressed_bytes, + chunk_bytes=limits.transfer_chunk_bytes, + timeout_seconds=self.timeout_seconds, + rejected_suffix=".zip.rejected", + retry_policy=self.retry_policy, + sleep=self._sleep, + random_value=self._random_value, + retained_evidence_budget=self.retained_evidence_budget, + ) + except BinanceArchivePayloadError as exc: + raise BinanceArchiveContractError( + str(exc), + reason_code="RESPONSE_SIZE_LIMIT", + ) from exc + try: + if archive_body.sha256 != upstream_sha: + _publish_rejected( + archive_body.temporary_path, + raw_root=destination_root, + request=request, + source_uri=archive_url, + downloaded_at_utc=archive_body.downloaded_at_utc, + response_headers=archive_body.response_headers, + reason=( + f"archive SHA-256 {archive_body.sha256} disagrees with official {upstream_sha}" + ), + suffix=".zip.rejected", + retained_evidence_budget=self.retained_evidence_budget, + evidence_reservations=archive_body.evidence_reservations, + ) + raise BinanceArchiveContractError( + "archive SHA-256 disagrees with official CHECKSUM", + reason_code="CHECKSUM_CONTRACT", + ) + + archive_directory = ( + destination_root + / "binance_spot" + / "daily_agg_trades_archive" + / request.symbol + / request.date.isoformat() + ) + official_destination = archive_directory / request.archive_name + if ( + official_destination.exists() + and sha256_file(official_destination) != archive_body.sha256 + ): + _publish_rejected( + archive_body.temporary_path, + raw_root=destination_root, + request=request, + source_uri=archive_url, + downloaded_at_utc=archive_body.downloaded_at_utc, + response_headers=archive_body.response_headers, + reason="official archive basename already contains different immutable bytes", + suffix=".zip.rejected", + retained_evidence_budget=self.retained_evidence_budget, + evidence_reservations=archive_body.evidence_reservations, + ) + raise BinanceArchivePayloadError( + "official archive basename collides with different immutable bytes" + ) + archive_artifact = _publish_temp( + archive_body.temporary_path, + destination_directory=archive_directory, + suffix=".zip", + destination_name=request.archive_name, + kind="archive_zip", + source="binance_spot_daily_aggtrades_archive", + source_uri=archive_url, + downloaded_at_utc=archive_body.downloaded_at_utc, + request=request, + sha256=archive_body.sha256, + response_headers=archive_body.response_headers, + upstream_checksum_sha256=upstream_sha, + retained_evidence_budget=self.retained_evidence_budget, + evidence_reservations=archive_body.evidence_reservations, + ) + except BaseException: + _discard_download(archive_body) + raise + try: + zip_descriptor = _validate_zip_structure( + archive_artifact.path, + expected_member=request.member_name, + max_uncompressed_bytes=limits.max_uncompressed_bytes, + ) + except BinanceArchiveContractError: + raise + except BinanceArchivePayloadError as exc: + if isinstance(exc.__cause__, OSError): + raise + raise BinanceArchiveContractError( + str(exc), + reason_code="ZIP_CONTRACT", + ) from exc + return AcquiredDailyArchive( + request=request, + archive_artifact=archive_artifact, + checksum_artifact=checksum_artifact, + upstream_sha256=upstream_sha, + declared_uncompressed_bytes=zip_descriptor.declared_uncompressed_bytes, + limits=limits, + ) + + +def _parse_unsigned(value: bytes, *, label: str) -> int: + if len(value) > 19: + raise BinanceArchivePayloadError(f"{label} exceeds signed int64") + if _UNSIGNED_INTEGER.fullmatch(value) is None: + raise BinanceArchivePayloadError(f"{label} must be a canonical unsigned integer") + parsed = int(value) + if parsed > _MAX_INT64: + raise BinanceArchivePayloadError(f"{label} exceeds signed int64") + return parsed + + +def _parse_boolean(value: bytes, *, label: str) -> bool: + lowered = value.lower() + if lowered == b"true": + return True + if lowered == b"false": + return False + raise BinanceArchivePayloadError(f"{label} must be true or false") + + +def _scaled_decimal(value: bytes, *, quantum: Decimal, label: str) -> tuple[Decimal, int]: + if len(value) > _MAX_DECIMAL_FIELD_BYTES: + raise BinanceArchivePayloadError(f"{label} exceeds its field byte ceiling") + try: + text = value.decode("ascii") + decimal = Decimal(text) + if not decimal.is_finite() or decimal <= 0: + raise BinanceArchivePayloadError(f"{label} must be positive and finite") + scaled = decimal / quantum + integral = scaled.to_integral_value() + except (UnicodeDecodeError, InvalidOperation, ZeroDivisionError) as exc: + raise BinanceArchivePayloadError(f"{label} is not a valid decimal") from exc + if scaled != integral: + raise BinanceArchivePayloadError(f"{label} is not aligned to declared scale") + integer = int(integral) + if integer < 1 or integer > _MAX_INT64: + raise BinanceArchivePayloadError(f"{label} scaled value is outside signed int64") + return decimal, integer + + +def _line_chunks( + source: Any, + *, + max_uncompressed_bytes: int, + chunk_bytes: int, + max_line_bytes: int, +) -> Generator[bytes, None, int]: + pending = b"" + expanded = 0 + while True: + chunk = source.read(chunk_bytes) + if not isinstance(chunk, bytes): + raise BinanceArchivePayloadError("archive member emitted non-bytes") + if not chunk: + break + expanded += len(chunk) + if expanded > max_uncompressed_bytes: + raise BinanceArchivePayloadError("archive expansion exceeds configured byte ceiling") + combined = pending + chunk + pieces = combined.split(b"\n") + pending = pieces.pop() + if len(pending) > max_line_bytes: + raise BinanceArchivePayloadError("archive CSV line exceeds configured byte ceiling") + for line in pieces: + if line.endswith(b"\r"): + line = line[:-1] + if len(line) > max_line_bytes: + raise BinanceArchivePayloadError("archive CSV line exceeds configured byte ceiling") + yield line + if pending: + if pending.endswith(b"\r"): + pending = pending[:-1] + if len(pending) > max_line_bytes: + raise BinanceArchivePayloadError("archive CSV line exceeds configured byte ceiling") + yield pending + return expanded + + +def _record_from_line( + line: bytes, + *, + row_number: int, + acquired: AcquiredDailyArchive, + previous_trade_id: int | None, + previous_event_ts_ns: int | None, + start_ns: int, + end_ns: int, +) -> tuple[dict[str, object], int, int]: + fields = line.split(b",") + if len(fields) != 8: + raise BinanceArchivePayloadError( + f"archive CSV row {row_number} must contain exactly 8 fields" + ) + aggregate_id = _parse_unsigned(fields[0], label=f"row {row_number} aggregate trade ID") + first_trade_id = _parse_unsigned(fields[3], label=f"row {row_number} first trade ID") + last_trade_id = _parse_unsigned(fields[4], label=f"row {row_number} last trade ID") + if first_trade_id > last_trade_id: + raise BinanceArchivePayloadError( + f"archive CSV row {row_number} first trade ID exceeds last trade ID" + ) + if previous_trade_id is not None and aggregate_id != previous_trade_id + 1: + raise BinanceArchivePayloadError( + f"archive aggregate trade IDs are noncontiguous at row {row_number}" + ) + raw_timestamp = _parse_unsigned(fields[5], label=f"row {row_number} timestamp") + multiplier = 1_000 if acquired.request.date >= _MICROSECOND_ARCHIVE_START else 1_000_000 + if raw_timestamp > _MAX_INT64 // multiplier: + raise BinanceArchivePayloadError(f"archive CSV row {row_number} timestamp overflows ns") + event_ts_ns = raw_timestamp * multiplier + if not start_ns <= event_ts_ns < end_ns: + raise BinanceArchivePayloadError( + f"archive CSV row {row_number} timestamp is outside declared UTC date" + ) + if previous_event_ts_ns is not None and event_ts_ns < previous_event_ts_ns: + raise BinanceArchivePayloadError(f"archive event time reverses at row {row_number}") + price, price_ticks = _scaled_decimal( + fields[1], quantum=acquired.request.tick_size, label=f"row {row_number} price" + ) + quantity, quantity_lots = _scaled_decimal( + fields[2], quantum=acquired.request.lot_size, label=f"row {row_number} quantity" + ) + buyer_is_maker = _parse_boolean(fields[6], label=f"row {row_number} buyer-maker flag") + _parse_boolean(fields[7], label=f"row {row_number} best-match flag") + record: dict[str, object] = { + "schema_version": SCHEMA_VERSION, + "venue": "binance_spot", + "symbol": acquired.request.symbol, + "event_ts_ns": event_ts_ns, + "received_ts_ns": None, + "available_ts_ns": event_ts_ns, + "availability_basis": "exchange_event_time_proxy", + "capture_seq": None, + "continuity_id": acquired.request.continuity_id, + "trade_id": aggregate_id, + "first_trade_id": first_trade_id, + "last_trade_id": last_trade_id, + "price_ticks": price_ticks, + "quantity_lots": quantity_lots, + "tick_size": float(acquired.request.tick_size), + "lot_size": float(acquired.request.lot_size), + "price": float(price), + "quantity": float(quantity), + "quote_quantity": float(price * quantity), + "aggressor_side": "sell" if buyer_is_maker else "buy", + "buyer_is_maker": buyer_is_maker, + "source_artifact_id": acquired.archive_artifact.sha256, + } + return record, aggregate_id, event_ts_ns + + +def _sha256_open_file(source: BinaryIO) -> str: + digest = hashlib.sha256() + source.seek(0) + while chunk := source.read(1024 * 1024): + digest.update(chunk) + source.seek(0) + return digest.hexdigest() + + +def _stream_normalized_batches( + acquired: AcquiredDailyArchive, + *, + batch_rows: int, + before_member_open: Callable[[], None] | None, +) -> Generator[pa.RecordBatch, None, DailyArchiveSummary]: + if acquired.requires_member_open_guard and before_member_open is None: + raise BinanceArchivePayloadError("held-out archive requires a member-open authority guard") + archive_path = acquired.archive_artifact.path + nofollow = getattr(os, "O_NOFOLLOW", 0) + try: + raw_descriptor = os.open(archive_path, os.O_RDONLY | nofollow) + except OSError as exc: + raise BinanceArchivePayloadError("archive bytes are unavailable after acquisition") from exc + try: + archive_source = os.fdopen(raw_descriptor, "rb") + except BaseException: + os.close(raw_descriptor) + raise + + start_ns, end_ns = _day_bounds_ns(acquired.request.date) + rows = 0 + first_trade_id: int | None = None + last_trade_id: int | None = None + first_event_ts_ns: int | None = None + last_event_ts_ns: int | None = None + records: list[dict[str, object]] = [] + expanded_bytes = 0 + with archive_source: + try: + observed = os.fstat(archive_source.fileno()) + if not stat.S_ISREG(observed.st_mode): + raise BinanceArchivePayloadError("archive bytes are not a regular file") + if observed.st_size != acquired.archive_artifact.bytes: + raise BinanceArchivePayloadError("archive bytes changed after acquisition") + if _sha256_open_file(archive_source) != acquired.archive_artifact.sha256: + raise BinanceArchivePayloadError("archive checksum changed after acquisition") + descriptor = _validate_zip_structure_handle( + archive_source, + observed.st_size, + expected_member=acquired.request.member_name, + max_uncompressed_bytes=acquired.limits.max_uncompressed_bytes, + ) + if descriptor.declared_uncompressed_bytes != acquired.declared_uncompressed_bytes: + raise BinanceArchivePayloadError( + "archive uncompressed-size claim changed after acquisition" + ) + archive_source.seek(0) + archive_context = zipfile.ZipFile(archive_source) + except BinanceArchivePayloadError: + raise + except (OSError, RuntimeError, ValueError, zipfile.BadZipFile) as exc: + raise BinanceArchivePayloadError("cannot stream archive CSV safely") from exc + with archive_context as archive: + # The same already-hashed file descriptor backs both ZipFile and + # member decompression. The path may change, but the guarded bytes + # cannot switch inode between authority verification and open. + if before_member_open is not None: + before_member_open() + try: + with archive.open(descriptor.member_name, "r") as member: + lines = _line_chunks( + member, + max_uncompressed_bytes=acquired.limits.max_uncompressed_bytes, + chunk_bytes=acquired.limits.transfer_chunk_bytes, + max_line_bytes=acquired.limits.max_csv_line_bytes, + ) + while True: + try: + line = next(lines) + except StopIteration as stop: + expanded_bytes = int(stop.value) + break + row_number = rows + 1 + record, trade_id, event_ts_ns = _record_from_line( + line, + row_number=row_number, + acquired=acquired, + previous_trade_id=last_trade_id, + previous_event_ts_ns=last_event_ts_ns, + start_ns=start_ns, + end_ns=end_ns, + ) + if first_trade_id is None: + first_trade_id = trade_id + first_event_ts_ns = event_ts_ns + last_trade_id = trade_id + last_event_ts_ns = event_ts_ns + records.append(record) + rows += 1 + if len(records) == batch_rows: + table = table_from_records("trades", records) + batches = table.to_batches(max_chunksize=batch_rows) + if len(batches) != 1 or batches[0].num_rows > batch_rows: + raise BinanceArchivePayloadError( + "archive normalizer violated its RecordBatch bound" + ) + yield batches[0] + records = [] + if records: + table = table_from_records("trades", records) + batches = table.to_batches(max_chunksize=batch_rows) + if len(batches) != 1 or batches[0].num_rows > batch_rows: + raise BinanceArchivePayloadError( + "archive normalizer violated its RecordBatch bound" + ) + yield batches[0] + except BinanceArchivePayloadError: + raise + except ( + OSError, + RuntimeError, + UnicodeError, + ValueError, + OverflowError, + zipfile.BadZipFile, + ) as exc: + raise BinanceArchivePayloadError("cannot stream archive CSV safely") from exc + + if ( + rows < 1 + or first_trade_id is None + or last_trade_id is None + or first_event_ts_ns is None + or last_event_ts_ns is None + ): + raise BinanceArchivePayloadError("archive CSV contains no trade rows") + if expanded_bytes != acquired.declared_uncompressed_bytes: + raise BinanceArchivePayloadError( + "streamed archive bytes disagree with ZIP uncompressed-size claim" + ) + return DailyArchiveSummary( + symbol=acquired.request.symbol, + date=acquired.request.date.isoformat(), + rows=rows, + first_trade_id=first_trade_id, + last_trade_id=last_trade_id, + first_event_ts_ns=first_event_ts_ns, + last_event_ts_ns=last_event_ts_ns, + compressed_bytes=acquired.archive_artifact.bytes, + expanded_bytes=expanded_bytes, + source_archive_sha256=acquired.archive_artifact.sha256, + member_name=descriptor.member_name, + continuity_id=acquired.request.continuity_id, + ) + + +__all__ = [ + "AcquiredDailyArchive", + "ArchiveAcquisitionReasonCode", + "ArchiveDownloadLimits", + "BinanceArchiveClient", + "BinanceArchiveContractError", + "BinanceArchiveError", + "BinanceArchiveHTTPError", + "BinanceArchivePayloadError", + "DailyArchiveRequest", + "DailyArchiveSummary", + "DailyArchiveTradeStream", + "RawArchiveArtifact", + "RetryPolicy", +] diff --git a/Microstructure/src/microstructure/data/book.py b/Microstructure/src/microstructure/data/book.py new file mode 100644 index 0000000000000000000000000000000000000000..59f3ae952a5bdc2a5d89ae2a4b2b41275e27253d --- /dev/null +++ b/Microstructure/src/microstructure/data/book.py @@ -0,0 +1,483 @@ +"""Pure snapshot-plus-delta order-book reconstruction. + +Sequence order is authoritative. Exchange timestamps are never used to sort +updates, so a timestamp reversal is reportable without concealing or inventing +book continuity. +""" + +from __future__ import annotations + +import math +from collections.abc import Mapping +from dataclasses import dataclass +from typing import Literal + +import pyarrow as pa # type: ignore[import-untyped] + +from microstructure.data.schemas import SCHEMA_VERSION, table_from_records + +BookLevel = tuple[int, int] +_MAX_BOOK_LEVELS_PER_SIDE = 10_000 + + +class BookInvariantError(ValueError): + """Raised when a snapshot or delta contains an impossible book level.""" + + +class _BookCapacityError(BookInvariantError): + """Raised before retained book state can exceed its hard memory bound.""" + + +@dataclass(frozen=True, slots=True) +class BookSnapshot: + venue: str + symbol: str + snapshot_id: str + request_ts_ns: int + received_ts_ns: int + available_ts_ns: int + continuity_id: str + last_update_id: int + depth_limit: int + bids: tuple[BookLevel, ...] + asks: tuple[BookLevel, ...] + tick_size: float + lot_size: float + source_artifact_id: str + + def to_record(self) -> dict[str, object]: + return { + "schema_version": SCHEMA_VERSION, + "venue": self.venue, + "symbol": self.symbol, + "snapshot_id": self.snapshot_id, + "request_ts_ns": self.request_ts_ns, + "received_ts_ns": self.received_ts_ns, + "available_ts_ns": self.available_ts_ns, + "continuity_id": self.continuity_id, + "last_update_id": self.last_update_id, + "depth_limit": self.depth_limit, + "bids": [ + {"price_ticks": price, "quantity_lots": quantity} for price, quantity in self.bids + ], + "asks": [ + {"price_ticks": price, "quantity_lots": quantity} for price, quantity in self.asks + ], + "tick_size": self.tick_size, + "lot_size": self.lot_size, + "source_artifact_id": self.source_artifact_id, + } + + +@dataclass(frozen=True, slots=True) +class DepthDelta: + venue: str + symbol: str + event_ts_ns: int + received_ts_ns: int | None + available_ts_ns: int + availability_basis: str + capture_seq: int | None + continuity_id: str + first_update_id: int + last_update_id: int + previous_update_id: int | None + bids: tuple[BookLevel, ...] + asks: tuple[BookLevel, ...] + tick_size: float + lot_size: float + source_artifact_id: str + + def to_record(self) -> dict[str, object]: + return { + "schema_version": SCHEMA_VERSION, + "venue": self.venue, + "symbol": self.symbol, + "event_ts_ns": self.event_ts_ns, + "received_ts_ns": self.received_ts_ns, + "available_ts_ns": self.available_ts_ns, + "availability_basis": self.availability_basis, + "capture_seq": self.capture_seq, + "continuity_id": self.continuity_id, + "first_update_id": self.first_update_id, + "last_update_id": self.last_update_id, + "previous_update_id": self.previous_update_id, + "bids": [ + {"price_ticks": price, "quantity_lots": quantity} for price, quantity in self.bids + ], + "asks": [ + {"price_ticks": price, "quantity_lots": quantity} for price, quantity in self.asks + ], + "tick_size": self.tick_size, + "lot_size": self.lot_size, + "source_artifact_id": self.source_artifact_id, + } + + +@dataclass(frozen=True, slots=True) +class SequenceGap: + venue: str + symbol: str + continuity_id: str + expected_sequence: int + observed_sequence_start: int + observed_sequence_end: int + missing_start: int + missing_end: int + detected_ts_ns: int + reason: str + source_artifact_id: str + + def to_record(self) -> dict[str, object]: + return { + "schema_version": SCHEMA_VERSION, + "venue": self.venue, + "symbol": self.symbol, + "continuity_id": self.continuity_id, + "expected_sequence": self.expected_sequence, + "observed_sequence_start": self.observed_sequence_start, + "observed_sequence_end": self.observed_sequence_end, + "missing_start": self.missing_start, + "missing_end": self.missing_end, + "detected_ts_ns": self.detected_ts_ns, + "reason": self.reason, + "source_artifact_id": self.source_artifact_id, + } + + +@dataclass(frozen=True, slots=True) +class ReconstructionResult: + status: Literal["LIVE", "GAPPED", "INVALID"] + observations: pa.Table + gaps: pa.Table + stale_events: int + final_update_id: int + + +ReconstructionOutcome = Literal[ + "OBSERVED", + "STALE", + "GAP", + "INVALID", + "EXCLUDED_AFTER_TERMINAL", +] + + +@dataclass(frozen=True, slots=True) +class ReconstructionStep: + """Bounded result of applying one delta to one continuity epoch.""" + + outcome: ReconstructionOutcome + observation: Mapping[str, object] | None + gap: SequenceGap | None + + +def _levels_to_book(levels: tuple[BookLevel, ...], side: str) -> dict[int, int]: + if len(levels) > _MAX_BOOK_LEVELS_PER_SIDE: + raise _BookCapacityError( + f"{side} snapshot exceeds {_MAX_BOOK_LEVELS_PER_SIDE} retained levels" + ) + result: dict[int, int] = {} + for price, quantity in levels: + if price <= 0: + raise BookInvariantError(f"{side} snapshot price must be positive: {price}") + if quantity <= 0: + raise BookInvariantError(f"{side} snapshot quantity must be positive: {quantity}") + if price in result: + raise BookInvariantError(f"duplicate {side} snapshot price: {price}") + result[price] = quantity + if not result: + raise BookInvariantError(f"{side} snapshot must not be empty") + return result + + +def _apply_side(book: dict[int, int], changes: tuple[BookLevel, ...], side: str) -> None: + for price, quantity in changes: + if price <= 0: + raise BookInvariantError(f"{side} delta price must be positive: {price}") + if quantity < 0: + raise BookInvariantError(f"{side} delta quantity must not be negative: {quantity}") + if quantity == 0: + book.pop(price, None) + else: + book[price] = quantity + if len(book) > _MAX_BOOK_LEVELS_PER_SIDE: + raise _BookCapacityError(f"{side} book exceeds {_MAX_BOOK_LEVELS_PER_SIDE} retained levels") + + +def _depth(book: dict[int, int], *, bids: bool, levels: int, lot_size: float) -> float: + ordered = sorted(book, reverse=bids)[:levels] + return sum(book[price] for price in ordered) * lot_size + + +def _queue_imbalance(bid_depth: float, ask_depth: float) -> float: + total = bid_depth + ask_depth + return (bid_depth - ask_depth) / total if total > 0.0 else 0.0 + + +def _observation( + *, + snapshot: BookSnapshot, + delta: DepthDelta, + bids: dict[int, int], + asks: dict[int, int], + valid: bool, +) -> dict[str, object]: + if not bids or not asks: + raise BookInvariantError("delta removed every price level from one side of the book") + best_bid_ticks = max(bids) + best_ask_ticks = min(asks) + bid_quantity_lots = bids[best_bid_ticks] + ask_quantity_lots = asks[best_ask_ticks] + best_bid = best_bid_ticks * snapshot.tick_size + best_ask = best_ask_ticks * snapshot.tick_size + bid_quantity = bid_quantity_lots * snapshot.lot_size + ask_quantity = ask_quantity_lots * snapshot.lot_size + mid_price = (best_bid + best_ask) / 2.0 + microprice = (best_ask * bid_quantity + best_bid * ask_quantity) / (bid_quantity + ask_quantity) + depth_bid_1 = _depth(bids, bids=True, levels=1, lot_size=snapshot.lot_size) + depth_ask_1 = _depth(asks, bids=False, levels=1, lot_size=snapshot.lot_size) + depth_bid_5 = _depth(bids, bids=True, levels=5, lot_size=snapshot.lot_size) + depth_ask_5 = _depth(asks, bids=False, levels=5, lot_size=snapshot.lot_size) + depth_bid_10 = _depth(bids, bids=True, levels=10, lot_size=snapshot.lot_size) + depth_ask_10 = _depth(asks, bids=False, levels=10, lot_size=snapshot.lot_size) + return { + "schema_version": SCHEMA_VERSION, + "venue": snapshot.venue, + "symbol": snapshot.symbol, + "event_ts_ns": delta.event_ts_ns, + "received_ts_ns": delta.received_ts_ns, + "available_ts_ns": max(snapshot.available_ts_ns, delta.available_ts_ns), + "availability_basis": delta.availability_basis, + "capture_seq": delta.capture_seq, + "continuity_id": snapshot.continuity_id, + "sequence_start": delta.first_update_id, + "sequence_end": delta.last_update_id, + "is_valid": valid, + "best_bid_ticks": best_bid_ticks, + "best_ask_ticks": best_ask_ticks, + "bid_quantity_lots": bid_quantity_lots, + "ask_quantity_lots": ask_quantity_lots, + "tick_size": snapshot.tick_size, + "lot_size": snapshot.lot_size, + "best_bid": best_bid, + "best_ask": best_ask, + "bid_quantity": bid_quantity, + "ask_quantity": ask_quantity, + "spread": best_ask - best_bid, + "mid_price": mid_price, + "microprice": microprice, + "depth_bid_1": depth_bid_1, + "depth_ask_1": depth_ask_1, + "depth_bid_5": depth_bid_5, + "depth_ask_5": depth_ask_5, + "depth_bid_10": depth_bid_10, + "depth_ask_10": depth_ask_10, + "queue_imbalance_1": _queue_imbalance(depth_bid_1, depth_ask_1), + "queue_imbalance_5": _queue_imbalance(depth_bid_5, depth_ask_5), + "queue_imbalance_10": _queue_imbalance(depth_bid_10, depth_ask_10), + "source_artifact_id": delta.source_artifact_id, + } + + +def _gap(snapshot: BookSnapshot, delta: DepthDelta, expected: int, reason: str) -> SequenceGap: + missing_end = max(expected, delta.first_update_id - 1) + return SequenceGap( + venue=snapshot.venue, + symbol=snapshot.symbol, + continuity_id=snapshot.continuity_id, + expected_sequence=expected, + observed_sequence_start=delta.first_update_id, + observed_sequence_end=delta.last_update_id, + missing_start=expected, + missing_end=missing_end, + detected_ts_ns=delta.available_ts_ns, + reason=reason, + source_artifact_id=delta.source_artifact_id, + ) + + +class IncrementalBookReconstructor: + """Stateful O(book-depth) snapshot-plus-delta reconstruction. + + The class retains only the current epoch's book. Every input delta returns + an explicit outcome; after a gap or invalidation, later deltas receive an + ``EXCLUDED_AFTER_TERMINAL`` gap record rather than disappearing silently. + """ + + def __init__(self, snapshot: BookSnapshot) -> None: + if snapshot.available_ts_ns < snapshot.received_ts_ns: + raise BookInvariantError("snapshot cannot be available before it was received") + if ( + not math.isfinite(snapshot.tick_size) + or not math.isfinite(snapshot.lot_size) + or snapshot.tick_size <= 0 + or snapshot.lot_size <= 0 + ): + raise BookInvariantError("snapshot tick and lot sizes must be finite and positive") + if snapshot.depth_limit < 1 or snapshot.depth_limit > _MAX_BOOK_LEVELS_PER_SIDE: + raise BookInvariantError( + f"snapshot depth_limit must be within 1..{_MAX_BOOK_LEVELS_PER_SIDE}" + ) + bids = _levels_to_book(snapshot.bids, "bid") + asks = _levels_to_book(snapshot.asks, "ask") + if max(bids) >= min(asks): + raise BookInvariantError("snapshot is crossed or locked") + self.snapshot = snapshot + self._bids = bids + self._asks = asks + self._last_update_id = snapshot.last_update_id + self._stale_events = 0 + self._status: Literal["LIVE", "GAPPED", "INVALID"] = "LIVE" + + @property + def status(self) -> Literal["LIVE", "GAPPED", "INVALID"]: + return self._status + + @property + def stale_events(self) -> int: + return self._stale_events + + @property + def final_update_id(self) -> int: + return self._last_update_id + + def _validate_identity(self, delta: DepthDelta) -> None: + if delta.venue != self.snapshot.venue or delta.symbol != self.snapshot.symbol: + raise BookInvariantError("delta venue/symbol does not match snapshot") + if delta.tick_size != self.snapshot.tick_size or delta.lot_size != self.snapshot.lot_size: + raise BookInvariantError("delta tick/lot scales do not match snapshot metadata") + + def update(self, delta: DepthDelta) -> ReconstructionStep: + """Apply exactly one delta and return its explicit reconstruction disposition.""" + self._validate_identity(delta) + expected = self._last_update_id + 1 + if self._status != "LIVE": + return ReconstructionStep( + outcome="EXCLUDED_AFTER_TERMINAL", + observation=None, + gap=_gap( + self.snapshot, + delta, + expected, + f"epoch_already_{self._status.lower()}", + ), + ) + if delta.continuity_id != self.snapshot.continuity_id: + self._status = "GAPPED" + return ReconstructionStep( + outcome="GAP", + observation=None, + gap=_gap(self.snapshot, delta, expected, "continuity_id_mismatch"), + ) + if delta.last_update_id < delta.first_update_id: + self._status = "INVALID" + return ReconstructionStep( + outcome="INVALID", + observation=None, + gap=_gap(self.snapshot, delta, expected, "invalid_sequence_range"), + ) + if delta.last_update_id <= self._last_update_id: + self._stale_events += 1 + return ReconstructionStep(outcome="STALE", observation=None, gap=None) + if ( + delta.previous_update_id is not None + and delta.previous_update_id != self._last_update_id + ): + self._status = "GAPPED" + return ReconstructionStep( + outcome="GAP", + observation=None, + gap=_gap(self.snapshot, delta, expected, "previous_update_id_mismatch"), + ) + if delta.first_update_id > expected: + self._status = "GAPPED" + return ReconstructionStep( + outcome="GAP", + observation=None, + gap=_gap(self.snapshot, delta, expected, "forward_sequence_gap"), + ) + if delta.last_update_id < expected: + self._stale_events += 1 + return ReconstructionStep(outcome="STALE", observation=None, gap=None) + + candidate_bids = self._bids.copy() + candidate_asks = self._asks.copy() + try: + _apply_side(candidate_bids, delta.bids, "bid") + _apply_side(candidate_asks, delta.asks, "ask") + if not candidate_bids or not candidate_asks: + raise BookInvariantError("delta emptied one side of the order book") + crossed = max(candidate_bids) >= min(candidate_asks) + observation = _observation( + snapshot=self.snapshot, + delta=delta, + bids=candidate_bids, + asks=candidate_asks, + valid=not crossed, + ) + except _BookCapacityError: + self._status = "INVALID" + return ReconstructionStep( + outcome="INVALID", + observation=None, + gap=_gap(self.snapshot, delta, expected, "book_level_limit_exceeded"), + ) + except BookInvariantError: + self._status = "INVALID" + return ReconstructionStep( + outcome="INVALID", + observation=None, + gap=_gap(self.snapshot, delta, expected, "invalid_book_level"), + ) + + self._bids = candidate_bids + self._asks = candidate_asks + self._last_update_id = delta.last_update_id + if crossed: + self._status = "INVALID" + return ReconstructionStep( + outcome="INVALID", + observation=observation, + gap=_gap(self.snapshot, delta, expected, "crossed_or_locked_book"), + ) + return ReconstructionStep(outcome="OBSERVED", observation=observation, gap=None) + + +def reconstruct_snapshot_and_deltas( + snapshot: BookSnapshot, deltas: tuple[DepthDelta, ...] | list[DepthDelta] +) -> ReconstructionResult: + """Apply buffered/live deltas until an explicit gap or invariant failure. + + Stale events (``u <= last_update_id``) are counted and ignored. A usable + event must cover the next expected update ID, allowing safe overlap. A + forward gap invalidates the continuity epoch; later events are not emitted. + """ + reconstructor = IncrementalBookReconstructor(snapshot) + observation_records: list[dict[str, object]] = [] + gaps: list[SequenceGap] = [] + + for delta in deltas: + step = reconstructor.update(delta) + if step.observation is not None: + observation_records.append(dict(step.observation)) + if step.gap is not None: + gaps.append(step.gap) + if step.outcome in {"GAP", "INVALID"}: + break + + return ReconstructionResult( + status=reconstructor.status, + observations=table_from_records("book_observations", observation_records), + gaps=table_from_records("sequence_gaps", [item.to_record() for item in gaps]), + stale_events=reconstructor.stale_events, + final_update_id=reconstructor.final_update_id, + ) + + +def snapshots_table(snapshots: list[BookSnapshot] | tuple[BookSnapshot, ...]) -> pa.Table: + return table_from_records("book_snapshots", [snapshot.to_record() for snapshot in snapshots]) + + +def deltas_table(deltas: list[DepthDelta] | tuple[DepthDelta, ...]) -> pa.Table: + return table_from_records("depth_deltas", [delta.to_record() for delta in deltas]) diff --git a/Microstructure/src/microstructure/data/evidence_budget.py b/Microstructure/src/microstructure/data/evidence_budget.py new file mode 100644 index 0000000000000000000000000000000000000000..a6cfe4a936b4b02682ae50deba762c8fccb741ee --- /dev/null +++ b/Microstructure/src/microstructure/data/evidence_budget.py @@ -0,0 +1,208 @@ +"""Fail-closed accounting for retained raw-evidence bytes.""" + +from __future__ import annotations + +import os +import threading +from collections.abc import Iterator +from contextlib import contextmanager +from pathlib import Path + + +class EvidenceBudgetError(RuntimeError): + """Base error for retained-evidence budget failures.""" + + +class EvidenceBudgetExceeded(EvidenceBudgetError): + """Raised before a retained artifact would exceed its byte budget.""" + + +class EvidenceBudgetStateError(EvidenceBudgetError): + """Raised when a reservation is finalized more than once.""" + + +def _scan_regular_file_bytes(root: Path) -> int: + """Return logical bytes below *root* without following symbolic links.""" + if root.is_symlink(): + raise EvidenceBudgetError(f"evidence-budget root must not be a symlink: {root}") + if not root.exists(): + return 0 + if not root.is_dir(): + raise EvidenceBudgetError(f"evidence-budget root is not a directory: {root}") + + total = 0 + pending = [root] + try: + while pending: + directory = pending.pop() + with os.scandir(directory) as entries: + for entry in entries: + if entry.is_symlink(): + continue + if entry.is_dir(follow_symlinks=False): + pending.append(Path(entry.path)) + elif entry.is_file(follow_symlinks=False): + total += entry.stat(follow_symlinks=False).st_size + except OSError as exc: + raise EvidenceBudgetError(f"cannot scan retained evidence below {root}") from exc + return total + + +class EvidenceReservation: + """One exclusive byte reservation, committed only after durable retention.""" + + __slots__ = ("_budget", "_bytes_reserved", "_label", "_state") + + def __init__( + self, + budget: RetainedEvidenceBudget, + bytes_reserved: int, + label: str, + ) -> None: + self._budget = budget + self._bytes_reserved = bytes_reserved + self._label = label + self._state = "active" + + @property + def bytes_reserved(self) -> int: + return self._bytes_reserved + + @property + def label(self) -> str: + return self._label + + @property + def active(self) -> bool: + return self._state == "active" + + def commit(self) -> None: + """Charge the reservation after its bytes have been retained.""" + if self._state != "active": + raise EvidenceBudgetStateError(f"reservation is already {self._state}") + self._budget._commit(self._bytes_reserved) + self._state = "committed" + + def release(self) -> None: + """Return an unused reservation to the available budget.""" + if self._state != "active": + raise EvidenceBudgetStateError(f"reservation is already {self._state}") + self._budget._release(self._bytes_reserved) + self._state = "released" + + def __enter__(self) -> EvidenceReservation: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: object | None, + ) -> None: + if self.active: + self.release() + + +class RetainedEvidenceBudget: + """Thread-safe accounting for a bounded directory of immutable evidence. + + Existing regular files are counted once at construction. Symbolic links + are neither counted nor traversed. Callers must share one instance across + writers targeting the same root so outstanding reservations cannot + oversubscribe the limit. + """ + + __slots__ = ("_limit_bytes", "_lock", "_reserved_bytes", "_root", "_used_bytes") + + def __init__(self, root: str | Path, limit_bytes: int) -> None: + if isinstance(limit_bytes, bool) or limit_bytes < 0: + raise ValueError("limit_bytes must be a nonnegative integer") + self._root = Path(root).expanduser().absolute() + self._limit_bytes = limit_bytes + self._lock = threading.RLock() + self._reserved_bytes = 0 + self._used_bytes = _scan_regular_file_bytes(self._root) + if self._used_bytes > self._limit_bytes: + raise EvidenceBudgetExceeded( + "preexisting retained evidence exceeds the configured byte budget: " + f"used={self._used_bytes}, limit={self._limit_bytes}, root={self._root}" + ) + + @property + def root(self) -> Path: + return self._root + + @property + def limit_bytes(self) -> int: + return self._limit_bytes + + @property + def used_bytes(self) -> int: + with self._lock: + return self._used_bytes + + @property + def reserved_bytes(self) -> int: + with self._lock: + return self._reserved_bytes + + @property + def remaining_bytes(self) -> int: + with self._lock: + return self._limit_bytes - self._used_bytes - self._reserved_bytes + + def assert_contains(self, path: str | Path) -> None: + """Reject targets outside the budget root or below an in-root symlink.""" + target = Path(os.path.abspath(Path(path).expanduser())) + if not target.is_relative_to(self._root): + raise EvidenceBudgetError( + f"retained-evidence target is outside budget root: target={target}, " + f"root={self._root}" + ) + current = self._root + for component in target.relative_to(self._root).parts: + current /= component + if current.is_symlink(): + raise EvidenceBudgetError( + f"retained-evidence target traverses a symlink: {current}" + ) + + @contextmanager + def write_transaction(self) -> Iterator[None]: + """Serialize deduplication checks, reservations, and artifact commits.""" + with self._lock: + yield + + def reserve( + self, + bytes_to_add: int, + *, + label: str = "retained evidence", + ) -> EvidenceReservation: + """Atomically reserve bytes or fail before the caller writes them.""" + if isinstance(bytes_to_add, bool) or bytes_to_add < 0: + raise ValueError("bytes_to_add must be a nonnegative integer") + with self._lock: + projected = self._used_bytes + self._reserved_bytes + bytes_to_add + if projected > self._limit_bytes: + raise EvidenceBudgetExceeded( + f"{label} would exceed retained-evidence budget: " + f"requested={bytes_to_add}, used={self._used_bytes}, " + f"reserved={self._reserved_bytes}, limit={self._limit_bytes}, " + f"root={self._root}" + ) + self._reserved_bytes += bytes_to_add + return EvidenceReservation(self, bytes_to_add, label) + + def _commit(self, bytes_reserved: int) -> None: + with self._lock: + if bytes_reserved > self._reserved_bytes: + raise EvidenceBudgetStateError("reservation accounting underflow on commit") + self._reserved_bytes -= bytes_reserved + self._used_bytes += bytes_reserved + + def _release(self, bytes_reserved: int) -> None: + with self._lock: + if bytes_reserved > self._reserved_bytes: + raise EvidenceBudgetStateError("reservation accounting underflow on release") + self._reserved_bytes -= bytes_reserved diff --git a/Microstructure/src/microstructure/data/quality.py b/Microstructure/src/microstructure/data/quality.py new file mode 100644 index 0000000000000000000000000000000000000000..eaaa46db791ac532ce2fb260d5f2a1070ae7fc49 --- /dev/null +++ b/Microstructure/src/microstructure/data/quality.py @@ -0,0 +1,1103 @@ +"""Non-mutating data-quality rules with explicit, machine-readable findings.""" + +from __future__ import annotations + +import json +import os +import sqlite3 +import tempfile +from collections.abc import Iterable, Mapping +from dataclasses import asdict, dataclass +from pathlib import Path +from typing import Any, Literal, Protocol, TextIO + +import pyarrow as pa # type: ignore[import-untyped] + +from microstructure.data.schemas import ensure_schema, get_schema +from microstructure.provenance import utc_now_iso, write_json + +Severity = Literal["ERROR", "WARNING"] + + +@dataclass(frozen=True, slots=True) +class QualityFinding: + rule_id: str + severity: Severity + dataset: str + row_index: int | None + symbol: str | None + event_ts_ns: int | None + message: str + details: Mapping[str, Any] + + +@dataclass(frozen=True, slots=True) +class ValidationReport: + dataset: str + rows_checked: int + findings: tuple[QualityFinding, ...] + total_errors: int | None = None + total_warnings: int | None = None + findings_jsonl_path: str | None = None + + def __post_init__(self) -> None: + if self.rows_checked < 0: + raise ValueError("rows_checked must be non-negative") + if (self.total_errors is None) != (self.total_warnings is None): + raise ValueError("total_errors and total_warnings must be supplied together") + retained_errors = sum(item.severity == "ERROR" for item in self.findings) + retained_warnings = sum(item.severity == "WARNING" for item in self.findings) + if self.total_errors is not None and self.total_errors < retained_errors: + raise ValueError("total_errors cannot be smaller than retained error findings") + if self.total_warnings is not None and self.total_warnings < retained_warnings: + raise ValueError("total_warnings cannot be smaller than retained warning findings") + + @property + def has_errors(self) -> bool: + return self.error_count > 0 + + @property + def error_count(self) -> int: + if self.total_errors is not None: + return self.total_errors + return sum(item.severity == "ERROR" for item in self.findings) + + @property + def warning_count(self) -> int: + if self.total_warnings is not None: + return self.total_warnings + return sum(item.severity == "WARNING" for item in self.findings) + + @property + def findings_truncated(self) -> bool: + """Whether ``findings`` is only an in-memory preview of the full result.""" + return len(self.findings) < self.error_count + self.warning_count + + def to_dict(self) -> dict[str, Any]: + payload: dict[str, Any] = { + "generated_at_utc": utc_now_iso(), + "dataset": self.dataset, + "rows_checked": self.rows_checked, + "summary": {"errors": self.error_count, "warnings": self.warning_count}, + "findings": [asdict(item) for item in self.findings], + "mutation_policy": "observations were not changed or repaired", + } + if self.findings_truncated: + payload["findings_preview"] = { + "retained": len(self.findings), + "total": self.error_count + self.warning_count, + "truncated": True, + } + if self.findings_jsonl_path is not None: + payload["findings_jsonl_path"] = self.findings_jsonl_path + return payload + + def write_json(self, path: str | Path) -> None: + write_json(path, self.to_dict()) + + +class _FindingTarget(Protocol): + def append(self, finding: QualityFinding) -> None: ... + + +class _FindingAccumulator: + """Count every finding while retaining only a bounded in-memory preview.""" + + def __init__( + self, + *, + max_findings: int | None, + findings_jsonl_path: str | Path | None, + ) -> None: + if max_findings is not None and max_findings < 0: + raise ValueError("max_findings must be non-negative or None") + self._max_findings = max_findings + self._findings: list[QualityFinding] = [] + self.error_count = 0 + self.warning_count = 0 + self.path = Path(findings_jsonl_path) if findings_jsonl_path is not None else None + self._temporary_path: Path | None = None + self._sink: TextIO | None = None + if self.path is not None: + self.path.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary_name = tempfile.mkstemp( + dir=self.path.parent, + prefix=f".{self.path.name}.", + suffix=".tmp", + text=True, + ) + self._temporary_path = Path(temporary_name) + self._sink = os.fdopen(descriptor, "w", encoding="utf-8") + + @property + def findings(self) -> tuple[QualityFinding, ...]: + return tuple(self._findings) + + def append(self, finding: QualityFinding) -> None: + if finding.severity == "ERROR": + self.error_count += 1 + else: + self.warning_count += 1 + if self._max_findings is None or len(self._findings) < self._max_findings: + self._findings.append(finding) + if self._sink is not None: + self._sink.write( + json.dumps( + asdict(finding), + ensure_ascii=False, + separators=(",", ":"), + sort_keys=True, + ) + ) + self._sink.write("\n") + + def flush(self) -> None: + if self._sink is not None: + self._sink.flush() + + def publish(self) -> None: + if self._sink is not None: + self._sink.flush() + os.fsync(self._sink.fileno()) + self._sink.close() + self._sink = None + if self.path is not None and self._temporary_path is not None: + os.replace(self._temporary_path, self.path) + self._temporary_path = None + + def close(self) -> None: + if self._sink is not None: + self._sink.close() + self._sink = None + if self._temporary_path is not None: + self._temporary_path.unlink(missing_ok=True) + self._temporary_path = None + + +def _continuity_key(continuity_id: object) -> tuple[int, str]: + if continuity_id is None: + return (1, "") + return (0, str(continuity_id)) + + +class _SpillState: + """Disk-backed exact state whose RAM use does not grow with row history.""" + + def __init__(self) -> None: + # An empty SQLite filename creates a private temporary on-disk database + # which is deleted when the connection closes. + self._connection = sqlite3.connect("") + self._connection.execute("PRAGMA cache_size = -2048") + self._connection.execute("PRAGMA temp_store = FILE") + self._connection.execute("PRAGMA journal_mode = OFF") + self._connection.execute("PRAGMA synchronous = OFF") + self._connection.executescript( + """ + CREATE TABLE event_state ( + venue TEXT NOT NULL, + symbol TEXT NOT NULL, + continuity_is_null INTEGER NOT NULL, + continuity_id TEXT NOT NULL, + event_ts_ns INTEGER NOT NULL, + received_ts_ns INTEGER, + row_index INTEGER NOT NULL, + PRIMARY KEY (venue, symbol, continuity_is_null, continuity_id) + ) WITHOUT ROWID; + CREATE TABLE sequence_state ( + sequence_kind TEXT NOT NULL, + venue TEXT NOT NULL, + symbol TEXT NOT NULL, + continuity_is_null INTEGER NOT NULL, + continuity_id TEXT NOT NULL, + sequence_end INTEGER NOT NULL, + PRIMARY KEY ( + sequence_kind, + venue, + symbol, + continuity_is_null, + continuity_id + ) + ) WITHOUT ROWID; + CREATE TABLE trade_identity ( + venue TEXT NOT NULL, + symbol TEXT NOT NULL, + trade_id INTEGER NOT NULL, + first_row INTEGER NOT NULL, + PRIMARY KEY (venue, symbol, trade_id) + ) WITHOUT ROWID; + """ + ) + + def get_event(self, key: tuple[str, str, str | None]) -> tuple[int, int | None, int] | None: + continuity_is_null, continuity_id = _continuity_key(key[2]) + result = self._connection.execute( + """ + SELECT event_ts_ns, received_ts_ns, row_index + FROM event_state + WHERE venue = ? AND symbol = ? + AND continuity_is_null = ? AND continuity_id = ? + """, + (key[0], key[1], continuity_is_null, continuity_id), + ).fetchone() + if result is None: + return None + event_ts_ns, received_ts_ns, row_index = result + return ( + int(event_ts_ns), + int(received_ts_ns) if received_ts_ns is not None else None, + int(row_index), + ) + + def set_event( + self, + key: tuple[str, str, str | None], + value: tuple[int, int | None, int], + ) -> None: + continuity_is_null, continuity_id = _continuity_key(key[2]) + self._connection.execute( + """ + INSERT INTO event_state ( + venue, symbol, continuity_is_null, continuity_id, + event_ts_ns, received_ts_ns, row_index + ) VALUES (?, ?, ?, ?, ?, ?, ?) + ON CONFLICT (venue, symbol, continuity_is_null, continuity_id) + DO UPDATE SET + event_ts_ns = excluded.event_ts_ns, + received_ts_ns = excluded.received_ts_ns, + row_index = excluded.row_index + """, + (*key[:2], continuity_is_null, continuity_id, *value), + ) + + def get_sequence(self, kind: str, key: tuple[str, str, str | None]) -> int | None: + continuity_is_null, continuity_id = _continuity_key(key[2]) + result = self._connection.execute( + """ + SELECT sequence_end + FROM sequence_state + WHERE sequence_kind = ? AND venue = ? AND symbol = ? + AND continuity_is_null = ? AND continuity_id = ? + """, + (kind, key[0], key[1], continuity_is_null, continuity_id), + ).fetchone() + return int(result[0]) if result is not None else None + + def set_sequence( + self, + kind: str, + key: tuple[str, str, str | None], + sequence_end: int, + ) -> None: + continuity_is_null, continuity_id = _continuity_key(key[2]) + self._connection.execute( + """ + INSERT INTO sequence_state ( + sequence_kind, venue, symbol, continuity_is_null, + continuity_id, sequence_end + ) VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT ( + sequence_kind, venue, symbol, continuity_is_null, continuity_id + ) DO UPDATE SET sequence_end = excluded.sequence_end + """, + (kind, key[0], key[1], continuity_is_null, continuity_id, sequence_end), + ) + + def first_trade_row_or_insert( + self, identity: tuple[str, str, int], row_index: int + ) -> int | None: + try: + self._connection.execute( + """ + INSERT INTO trade_identity (venue, symbol, trade_id, first_row) + VALUES (?, ?, ?, ?) + """, + (*identity, row_index), + ) + except sqlite3.IntegrityError: + result = self._connection.execute( + """ + SELECT first_row FROM trade_identity + WHERE venue = ? AND symbol = ? AND trade_id = ? + """, + identity, + ).fetchone() + if result is None: # pragma: no cover - guarded by the primary key + raise RuntimeError("duplicate identity disappeared from quality state") from None + return int(result[0]) + return None + + def commit(self) -> None: + self._connection.commit() + + def close(self) -> None: + self._connection.close() + + +class _ValidationState(Protocol): + def get_event(self, key: tuple[str, str, str | None]) -> tuple[int, int | None, int] | None: ... + + def set_event( + self, + key: tuple[str, str, str | None], + value: tuple[int, int | None, int], + ) -> None: ... + + def get_sequence(self, kind: str, key: tuple[str, str, str | None]) -> int | None: ... + + def set_sequence( + self, + kind: str, + key: tuple[str, str, str | None], + sequence_end: int, + ) -> None: ... + + def first_trade_row_or_insert( + self, identity: tuple[str, str, int], row_index: int + ) -> int | None: ... + + +class _MemoryState: + def __init__(self) -> None: + self._events: dict[tuple[str, str, str | None], tuple[int, int | None, int]] = {} + self._sequences: dict[tuple[str, str, str, str | None], int] = {} + self._trade_identities: dict[tuple[str, str, int], int] = {} + + def get_event(self, key: tuple[str, str, str | None]) -> tuple[int, int | None, int] | None: + return self._events.get(key) + + def set_event( + self, + key: tuple[str, str, str | None], + value: tuple[int, int | None, int], + ) -> None: + self._events[key] = value + + def get_sequence(self, kind: str, key: tuple[str, str, str | None]) -> int | None: + return self._sequences.get((kind, *key)) + + def set_sequence( + self, + kind: str, + key: tuple[str, str, str | None], + sequence_end: int, + ) -> None: + self._sequences[(kind, *key)] = sequence_end + + def first_trade_row_or_insert( + self, identity: tuple[str, str, int], row_index: int + ) -> int | None: + first_row = self._trade_identities.get(identity) + if first_row is None: + self._trade_identities[identity] = row_index + return first_row + + +def _finding( + findings: _FindingTarget, + *, + rule_id: str, + severity: Severity, + dataset: str, + row_index: int | None, + row: Mapping[str, Any] | None, + message: str, + details: Mapping[str, Any] | None = None, +) -> None: + findings.append( + QualityFinding( + rule_id=rule_id, + severity=severity, + dataset=dataset, + row_index=row_index, + symbol=str(row["symbol"]) if row is not None and row.get("symbol") else None, + event_ts_ns=( + int(row["event_ts_ns"]) + if row is not None and row.get("event_ts_ns") is not None + else None + ), + message=message, + details=details or {}, + ) + ) + + +def _validate_event_clocks( + rows: list[dict[str, Any]], + *, + dataset: str, + findings: _FindingTarget, + max_silence_ns: int, + row_offset: int = 0, + state: _ValidationState | None = None, +) -> None: + validation_state = state if state is not None else _MemoryState() + for local_index, row in enumerate(rows): + index = row_offset + local_index + event_ts = int(row["event_ts_ns"]) + available_ts = int(row["available_ts_ns"]) + received = row.get("received_ts_ns") + received_ts = int(received) if received is not None else None + if available_ts < event_ts: + _finding( + findings, + rule_id="temporal.available_before_event", + severity="ERROR", + dataset=dataset, + row_index=index, + row=row, + message="observation is marked available before its exchange event time", + details={"event_ts_ns": event_ts, "available_ts_ns": available_ts}, + ) + if received_ts is not None and available_ts < received_ts: + _finding( + findings, + rule_id="temporal.available_before_receipt", + severity="ERROR", + dataset=dataset, + row_index=index, + row=row, + message="live observation is marked available before local receipt", + details={"received_ts_ns": received_ts, "available_ts_ns": available_ts}, + ) + + key = (str(row["venue"]), str(row["symbol"]), row.get("continuity_id")) + prior = validation_state.get_event(key) + if prior is not None: + previous_event, previous_received, previous_index = prior + if event_ts < previous_event: + _finding( + findings, + rule_id="temporal.out_of_order_event_time", + severity="WARNING", + dataset=dataset, + row_index=index, + row=row, + message="exchange timestamps reversed in source/capture order", + details={ + "previous_row": previous_index, + "previous_event_ts_ns": previous_event, + }, + ) + if event_ts - previous_event > max_silence_ns: + _finding( + findings, + rule_id="temporal.long_silence", + severity="WARNING", + dataset=dataset, + row_index=index, + row=row, + message="time between events exceeded configured silence threshold", + details={"silence_ns": event_ts - previous_event}, + ) + if ( + received_ts is not None + and previous_received is not None + and received_ts < previous_received + ): + _finding( + findings, + rule_id="temporal.receive_clock_reversal", + severity="WARNING", + dataset=dataset, + row_index=index, + row=row, + message="wall-clock receipt timestamp moved backwards", + details={ + "previous_row": previous_index, + "previous_received_ts_ns": previous_received, + }, + ) + validation_state.set_event(key, (event_ts, received_ts, index)) + + +def _validate_trades( + rows: list[dict[str, Any]], + dataset: str, + findings: _FindingTarget, + *, + row_offset: int = 0, + state: _ValidationState | None = None, +) -> None: + validation_state = state if state is not None else _MemoryState() + for local_index, row in enumerate(rows): + index = row_offset + local_index + identity = (str(row["venue"]), str(row["symbol"]), int(row["trade_id"])) + first_row = validation_state.first_trade_row_or_insert(identity, index) + if first_row is not None: + _finding( + findings, + rule_id="trade.duplicate", + severity="ERROR", + dataset=dataset, + row_index=index, + row=row, + message="duplicate trade identity was preserved", + details={"first_row": first_row, "trade_id": identity[2]}, + ) + if int(row["price_ticks"]) <= 0 or float(row["price"]) <= 0.0: + _finding( + findings, + rule_id="trade.nonpositive_price", + severity="ERROR", + dataset=dataset, + row_index=index, + row=row, + message="trade price is zero or negative", + ) + if int(row["quantity_lots"]) <= 0 or float(row["quantity"]) <= 0.0: + _finding( + findings, + rule_id="trade.nonpositive_quantity", + severity="ERROR", + dataset=dataset, + row_index=index, + row=row, + message="trade quantity is zero or negative", + ) + expected_price = int(row["price_ticks"]) * float(row["tick_size"]) + expected_quantity = int(row["quantity_lots"]) * float(row["lot_size"]) + if abs(expected_price - float(row["price"])) > max(1e-12, abs(expected_price) * 1e-12): + _finding( + findings, + rule_id="trade.price_scale_mismatch", + severity="ERROR", + dataset=dataset, + row_index=index, + row=row, + message="floating price does not match exact ticks and tick size", + ) + if abs(expected_quantity - float(row["quantity"])) > max( + 1e-12, abs(expected_quantity) * 1e-12 + ): + _finding( + findings, + rule_id="trade.quantity_scale_mismatch", + severity="ERROR", + dataset=dataset, + row_index=index, + row=row, + message="floating quantity does not match exact lots and lot size", + ) + if row["aggressor_side"] not in {"buy", "sell"}: + _finding( + findings, + rule_id="trade.invalid_aggressor_side", + severity="ERROR", + dataset=dataset, + row_index=index, + row=row, + message="aggressor side is outside the normalized enum", + ) + + +def _validate_book_sequences( + rows: list[dict[str, Any]], + dataset: str, + findings: _FindingTarget, + *, + row_offset: int = 0, + state: _ValidationState | None = None, +) -> None: + validation_state = state if state is not None else _MemoryState() + for local_index, row in enumerate(rows): + index = row_offset + local_index + start = int(row["sequence_start"]) + end = int(row["sequence_end"]) + if end < start: + _finding( + findings, + rule_id="sequence.invalid_range", + severity="ERROR", + dataset=dataset, + row_index=index, + row=row, + message="sequence range ends before it starts", + ) + continue + key = (str(row["venue"]), str(row["symbol"]), row.get("continuity_id")) + prior = validation_state.get_sequence("book_observations", key) + if prior is not None: + expected = prior + 1 + if start > expected: + _finding( + findings, + rule_id="sequence.missing_range", + severity="ERROR", + dataset=dataset, + row_index=index, + row=row, + message="book sequence has a forward gap", + details={ + "expected_sequence": expected, + "observed_start": start, + "missing_start": expected, + "missing_end": start - 1, + }, + ) + elif end <= prior: + _finding( + findings, + rule_id="sequence.stale_or_duplicate", + severity="WARNING", + dataset=dataset, + row_index=index, + row=row, + message="sequence event is fully stale or duplicated", + details={"previous_end": prior}, + ) + validation_state.set_sequence( + "book_observations", + key, + max(prior if prior is not None else end, end), + ) + + +def _validate_books( + rows: list[dict[str, Any]], + dataset: str, + findings: _FindingTarget, + max_spread_bps: float, + *, + row_offset: int = 0, + state: _ValidationState | None = None, +) -> None: + _validate_book_sequences( + rows, + dataset, + findings, + row_offset=row_offset, + state=state, + ) + for local_index, row in enumerate(rows): + index = row_offset + local_index + bid = float(row["best_bid"]) + ask = float(row["best_ask"]) + bid_quantity = float(row["bid_quantity"]) + ask_quantity = float(row["ask_quantity"]) + mid = float(row["mid_price"]) + tick_size = float(row["tick_size"]) + lot_size = float(row["lot_size"]) + expected_bid = int(row["best_bid_ticks"]) * tick_size + expected_ask = int(row["best_ask_ticks"]) * tick_size + expected_bid_quantity = int(row["bid_quantity_lots"]) * lot_size + expected_ask_quantity = int(row["ask_quantity_lots"]) * lot_size + if abs(expected_bid - bid) > max(1e-12, abs(expected_bid) * 1e-12) or abs( + expected_ask - ask + ) > max(1e-12, abs(expected_ask) * 1e-12): + _finding( + findings, + rule_id="book.price_scale_mismatch", + severity="ERROR", + dataset=dataset, + row_index=index, + row=row, + message="floating best prices do not match exact ticks and tick size", + ) + if abs(expected_bid_quantity - bid_quantity) > max( + 1e-12, abs(expected_bid_quantity) * 1e-12 + ) or abs(expected_ask_quantity - ask_quantity) > max( + 1e-12, abs(expected_ask_quantity) * 1e-12 + ): + _finding( + findings, + rule_id="book.quantity_scale_mismatch", + severity="ERROR", + dataset=dataset, + row_index=index, + row=row, + message="floating best quantities do not match exact lots and lot size", + ) + if bid <= 0.0 or ask <= 0.0: + _finding( + findings, + rule_id="book.nonpositive_price", + severity="ERROR", + dataset=dataset, + row_index=index, + row=row, + message="best price is zero or negative", + ) + if bid_quantity <= 0.0 or ask_quantity <= 0.0: + _finding( + findings, + rule_id="book.nonpositive_quantity", + severity="ERROR", + dataset=dataset, + row_index=index, + row=row, + message="best-level quantity is zero or negative", + ) + if bid >= ask: + _finding( + findings, + rule_id="book.crossed_or_locked", + severity="ERROR", + dataset=dataset, + row_index=index, + row=row, + message="best bid is greater than or equal to best ask", + details={"best_bid": bid, "best_ask": ask}, + ) + if mid > 0.0: + relative_spread_bps = (ask - bid) / mid * 10_000.0 + if relative_spread_bps > max_spread_bps: + _finding( + findings, + rule_id="book.abnormal_spread", + severity="WARNING", + dataset=dataset, + row_index=index, + row=row, + message="relative spread exceeded configured threshold", + details={ + "spread_bps": relative_spread_bps, + "threshold_bps": max_spread_bps, + }, + ) + microprice = float(row["microprice"]) + if not bid <= microprice <= ask: + _finding( + findings, + rule_id="book.microprice_outside_quotes", + severity="ERROR", + dataset=dataset, + row_index=index, + row=row, + message="microprice is outside the contemporaneous quotes", + ) + for side in ("bid", "ask"): + depth_1 = float(row[f"depth_{side}_1"]) + depth_5 = float(row[f"depth_{side}_5"]) + depth_10 = float(row[f"depth_{side}_10"]) + if not 0.0 < depth_1 <= depth_5 <= depth_10: + _finding( + findings, + rule_id="book.nonmonotone_depth", + severity="ERROR", + dataset=dataset, + row_index=index, + row=row, + message=f"cumulative {side} depth is not positive and monotone", + ) + if not bool(row["is_valid"]): + _finding( + findings, + rule_id="book.invalid_state", + severity="ERROR", + dataset=dataset, + row_index=index, + row=row, + message="reconstructor marked this state invalid", + ) + + +def _validate_depth_deltas( + rows: list[dict[str, Any]], + dataset: str, + findings: _FindingTarget, + *, + row_offset: int = 0, + state: _ValidationState | None = None, +) -> None: + validation_state = state if state is not None else _MemoryState() + for local_index, row in enumerate(rows): + index = row_offset + local_index + start = int(row["first_update_id"]) + end = int(row["last_update_id"]) + if end < start: + _finding( + findings, + rule_id="sequence.invalid_range", + severity="ERROR", + dataset=dataset, + row_index=index, + row=row, + message="delta sequence range ends before it starts", + ) + else: + key = (str(row["venue"]), str(row["symbol"]), row.get("continuity_id")) + prior = validation_state.get_sequence("depth_deltas", key) + if prior is not None: + expected = prior + 1 + previous_hint = row.get("previous_update_id") + if previous_hint is not None and int(previous_hint) != prior: + _finding( + findings, + rule_id="sequence.previous_id_mismatch", + severity="ERROR", + dataset=dataset, + row_index=index, + row=row, + message="delta previous-update hint does not match the prior event", + details={"expected_previous": prior, "observed_previous": previous_hint}, + ) + if start > expected: + _finding( + findings, + rule_id="sequence.missing_range", + severity="ERROR", + dataset=dataset, + row_index=index, + row=row, + message="depth delta sequence has a forward gap", + details={ + "expected_sequence": expected, + "observed_start": start, + "missing_start": expected, + "missing_end": start - 1, + }, + ) + elif end <= prior: + _finding( + findings, + rule_id="sequence.stale_or_duplicate", + severity="WARNING", + dataset=dataset, + row_index=index, + row=row, + message="depth delta is fully stale or duplicated", + details={"previous_end": prior}, + ) + validation_state.set_sequence( + "depth_deltas", + key, + max(prior if prior is not None else end, end), + ) + for side in ("bids", "asks"): + seen_prices: set[int] = set() + for level in row[side]: + price_ticks = int(level["price_ticks"]) + quantity_lots = int(level["quantity_lots"]) + if price_ticks <= 0: + _finding( + findings, + rule_id="depth.nonpositive_price", + severity="ERROR", + dataset=dataset, + row_index=index, + row=row, + message="depth change contains a zero or negative price", + ) + # Zero is a documented delete instruction, not bad quantity. + if quantity_lots < 0: + _finding( + findings, + rule_id="depth.negative_quantity", + severity="ERROR", + dataset=dataset, + row_index=index, + row=row, + message="depth change contains a negative quantity", + ) + if price_ticks in seen_prices: + _finding( + findings, + rule_id="depth.duplicate_price_in_event", + severity="WARNING", + dataset=dataset, + row_index=index, + row=row, + message="one delta updates the same side/price more than once", + details={"side": side, "price_ticks": price_ticks}, + ) + seen_prices.add(price_ticks) + + +class IncrementalQualityValidator: + """Validate normalized Arrow batches without retaining the row history. + + Clock, sequence, and exact trade-identity state spill to a private temporary + SQLite database. ``findings`` in the final report is a bounded preview, while + total severity counts remain exact. Supplying ``findings_jsonl_path`` streams + every finding to JSONL in detection order. + """ + + def __init__( + self, + schema_name: str, + *, + max_spread_bps: float = 100.0, + max_silence_ns: int = 5_000_000_000, + max_findings: int | None = 1_000, + findings_jsonl_path: str | Path | None = None, + row_chunk_size: int = 16_384, + ) -> None: + get_schema(schema_name) + if row_chunk_size <= 0: + raise ValueError("row_chunk_size must be positive") + self.schema_name = schema_name + self.max_spread_bps = max_spread_bps + self.max_silence_ns = max_silence_ns + self.row_chunk_size = row_chunk_size + self._state = _SpillState() + try: + self._findings = _FindingAccumulator( + max_findings=max_findings, + findings_jsonl_path=findings_jsonl_path, + ) + except BaseException: + self._state.close() + raise + self._rows_checked = 0 + self._closed = False + self._report: ValidationReport | None = None + + def __enter__(self) -> IncrementalQualityValidator: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: object, + ) -> None: + self.close() + + @property + def rows_checked(self) -> int: + return self._rows_checked + + def _require_open(self) -> None: + if self._closed: + raise RuntimeError("incremental quality validator is already closed") + + def _validate_rows(self, rows: list[dict[str, Any]]) -> None: + row_offset = self._rows_checked + if self.schema_name in {"trades", "book_observations", "depth_deltas"}: + _validate_event_clocks( + rows, + dataset=self.schema_name, + findings=self._findings, + max_silence_ns=self.max_silence_ns, + row_offset=row_offset, + state=self._state, + ) + if self.schema_name == "trades": + _validate_trades( + rows, + self.schema_name, + self._findings, + row_offset=row_offset, + state=self._state, + ) + elif self.schema_name == "book_observations": + _validate_books( + rows, + self.schema_name, + self._findings, + self.max_spread_bps, + row_offset=row_offset, + state=self._state, + ) + elif self.schema_name == "depth_deltas": + _validate_depth_deltas( + rows, + self.schema_name, + self._findings, + row_offset=row_offset, + state=self._state, + ) + self._rows_checked += len(rows) + + def update(self, batch: pa.Table | pa.RecordBatch) -> None: + """Consume one table or record batch without changing its observations.""" + self._require_open() + if not isinstance(batch, (pa.Table, pa.RecordBatch)): + raise TypeError("batch must be a pyarrow Table or RecordBatch") + if batch.num_rows == 0: + ensure_schema(batch, self.schema_name) + return + for start in range(0, batch.num_rows, self.row_chunk_size): + chunk = batch.slice(start, self.row_chunk_size) + ensure_schema(chunk, self.schema_name) + self._validate_rows(chunk.to_pylist()) + self._state.commit() + self._findings.flush() + + def finish(self) -> ValidationReport: + """Close spill resources and return the exact-count validation report.""" + if self._report is not None: + return self._report + self._require_open() + self._state.commit() + self._findings.flush() + self._findings.publish() + self._state.close() + self._closed = True + jsonl_path = self._findings.path + self._report = ValidationReport( + dataset=self.schema_name, + rows_checked=self._rows_checked, + findings=self._findings.findings, + total_errors=self._findings.error_count, + total_warnings=self._findings.warning_count, + findings_jsonl_path=str(jsonl_path.resolve()) if jsonl_path is not None else None, + ) + return self._report + + def close(self) -> None: + """Release resources without fabricating a report for unfinished input.""" + if self._closed: + return + self._findings.close() + self._state.close() + self._closed = True + + +def validate_batches( + batches: Iterable[pa.Table | pa.RecordBatch], + schema_name: str, + *, + max_spread_bps: float = 100.0, + max_silence_ns: int = 5_000_000_000, + max_findings: int | None = 1_000, + findings_jsonl_path: str | Path | None = None, + row_chunk_size: int = 16_384, +) -> ValidationReport: + """Consume an iterable once and validate it with bounded retained state.""" + validator = IncrementalQualityValidator( + schema_name, + max_spread_bps=max_spread_bps, + max_silence_ns=max_silence_ns, + max_findings=max_findings, + findings_jsonl_path=findings_jsonl_path, + row_chunk_size=row_chunk_size, + ) + try: + for batch in batches: + validator.update(batch) + return validator.finish() + except BaseException: + validator.close() + raise + + +def validate_table( + table: pa.Table, + schema_name: str, + *, + max_spread_bps: float = 100.0, + max_silence_ns: int = 5_000_000_000, +) -> ValidationReport: + """Validate without sorting, de-duplicating, clipping, or changing rows.""" + ensure_schema(table, schema_name) + rows = table.to_pylist() + findings: list[QualityFinding] = [] + if schema_name in {"trades", "book_observations", "depth_deltas"}: + _validate_event_clocks( + rows, + dataset=schema_name, + findings=findings, + max_silence_ns=max_silence_ns, + ) + if schema_name == "trades": + _validate_trades(rows, schema_name, findings) + elif schema_name == "book_observations": + _validate_books(rows, schema_name, findings, max_spread_bps) + elif schema_name == "depth_deltas": + _validate_depth_deltas(rows, schema_name, findings) + return ValidationReport( + dataset=schema_name, + rows_checked=table.num_rows, + findings=tuple(findings), + ) diff --git a/Microstructure/src/microstructure/data/schemas.py b/Microstructure/src/microstructure/data/schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..07dae2dd758c0b9dfb74c1cfbbc1a0fe47e55412 --- /dev/null +++ b/Microstructure/src/microstructure/data/schemas.py @@ -0,0 +1,223 @@ +"""Versioned normalized Arrow schemas and their temporal contract. + +All timestamps are signed UTC epoch nanoseconds. ``available_ts_ns`` is the +earliest time at which a row may enter a research information set. Archive +rows explicitly identify exchange event time as a proxy; live rows use local +receipt time. Prices and quantities retain exact integer tick/lot columns and +also expose documented floating convenience columns for research consumers. +""" + +from __future__ import annotations + +from collections.abc import Iterable, Mapping +from typing import Any + +import pyarrow as pa # type: ignore[import-untyped] + +SCHEMA_VERSION = "1.0.0" + + +class SchemaError(ValueError): + """Raised when a normalized table violates its declared schema.""" + + +def _metadata(name: str) -> dict[bytes, bytes]: + return { + b"schema_name": name.encode(), + b"schema_version": SCHEMA_VERSION.encode(), + b"timestamp_unit": b"UTC epoch nanoseconds", + b"temporal_contract": ( + b"available_ts_ns is the information-set clock; event_ts_ns alone is not receipt proof" + ), + b"numeric_contract": ( + b"price_ticks and quantity_lots are exact; float columns are convenience units" + ), + } + + +_COMMON_EVENT_FIELDS = [ + pa.field("schema_version", pa.string(), nullable=False), + pa.field("venue", pa.string(), nullable=False), + pa.field("symbol", pa.string(), nullable=False), + pa.field("event_ts_ns", pa.int64(), nullable=False), + pa.field("received_ts_ns", pa.int64()), + pa.field("available_ts_ns", pa.int64(), nullable=False), + pa.field("availability_basis", pa.string(), nullable=False), + pa.field("capture_seq", pa.int64()), + pa.field("continuity_id", pa.string()), +] + + +TRADE_SCHEMA = pa.schema( + [ + *_COMMON_EVENT_FIELDS, + pa.field("trade_id", pa.int64(), nullable=False), + pa.field("first_trade_id", pa.int64()), + pa.field("last_trade_id", pa.int64()), + pa.field("price_ticks", pa.int64(), nullable=False), + pa.field("quantity_lots", pa.int64(), nullable=False), + pa.field("tick_size", pa.float64(), nullable=False), + pa.field("lot_size", pa.float64(), nullable=False), + pa.field("price", pa.float64(), nullable=False), + pa.field("quantity", pa.float64(), nullable=False), + pa.field("quote_quantity", pa.float64(), nullable=False), + pa.field("aggressor_side", pa.string(), nullable=False), + pa.field("buyer_is_maker", pa.bool_(), nullable=False), + pa.field("source_artifact_id", pa.string(), nullable=False), + ], + metadata=_metadata("trades"), +) + + +BOOK_OBSERVATION_SCHEMA = pa.schema( + [ + *_COMMON_EVENT_FIELDS, + pa.field("sequence_start", pa.int64(), nullable=False), + pa.field("sequence_end", pa.int64(), nullable=False), + pa.field("is_valid", pa.bool_(), nullable=False), + pa.field("best_bid_ticks", pa.int64(), nullable=False), + pa.field("best_ask_ticks", pa.int64(), nullable=False), + pa.field("bid_quantity_lots", pa.int64(), nullable=False), + pa.field("ask_quantity_lots", pa.int64(), nullable=False), + pa.field("tick_size", pa.float64(), nullable=False), + pa.field("lot_size", pa.float64(), nullable=False), + pa.field("best_bid", pa.float64(), nullable=False), + pa.field("best_ask", pa.float64(), nullable=False), + pa.field("bid_quantity", pa.float64(), nullable=False), + pa.field("ask_quantity", pa.float64(), nullable=False), + pa.field("spread", pa.float64(), nullable=False), + pa.field("mid_price", pa.float64(), nullable=False), + pa.field("microprice", pa.float64(), nullable=False), + pa.field("depth_bid_1", pa.float64(), nullable=False), + pa.field("depth_ask_1", pa.float64(), nullable=False), + pa.field("depth_bid_5", pa.float64(), nullable=False), + pa.field("depth_ask_5", pa.float64(), nullable=False), + pa.field("depth_bid_10", pa.float64(), nullable=False), + pa.field("depth_ask_10", pa.float64(), nullable=False), + pa.field("queue_imbalance_1", pa.float64(), nullable=False), + pa.field("queue_imbalance_5", pa.float64(), nullable=False), + pa.field("queue_imbalance_10", pa.float64(), nullable=False), + pa.field("source_artifact_id", pa.string(), nullable=False), + ], + metadata=_metadata("book_observations"), +) + + +LEVEL_TYPE = pa.struct( + [ + pa.field("price_ticks", pa.int64(), nullable=False), + pa.field("quantity_lots", pa.int64(), nullable=False), + ] +) + + +DEPTH_DELTA_SCHEMA = pa.schema( + [ + *_COMMON_EVENT_FIELDS, + pa.field("first_update_id", pa.int64(), nullable=False), + pa.field("last_update_id", pa.int64(), nullable=False), + pa.field("previous_update_id", pa.int64()), + pa.field("bids", pa.list_(LEVEL_TYPE), nullable=False), + pa.field("asks", pa.list_(LEVEL_TYPE), nullable=False), + pa.field("tick_size", pa.float64(), nullable=False), + pa.field("lot_size", pa.float64(), nullable=False), + pa.field("source_artifact_id", pa.string(), nullable=False), + ], + metadata=_metadata("depth_deltas"), +) + + +BOOK_SNAPSHOT_SCHEMA = pa.schema( + [ + pa.field("schema_version", pa.string(), nullable=False), + pa.field("venue", pa.string(), nullable=False), + pa.field("symbol", pa.string(), nullable=False), + pa.field("snapshot_id", pa.string(), nullable=False), + pa.field("request_ts_ns", pa.int64(), nullable=False), + pa.field("received_ts_ns", pa.int64(), nullable=False), + pa.field("available_ts_ns", pa.int64(), nullable=False), + pa.field("continuity_id", pa.string(), nullable=False), + pa.field("last_update_id", pa.int64(), nullable=False), + pa.field("depth_limit", pa.int32(), nullable=False), + pa.field("bids", pa.list_(LEVEL_TYPE), nullable=False), + pa.field("asks", pa.list_(LEVEL_TYPE), nullable=False), + pa.field("tick_size", pa.float64(), nullable=False), + pa.field("lot_size", pa.float64(), nullable=False), + pa.field("source_artifact_id", pa.string(), nullable=False), + ], + metadata=_metadata("book_snapshots"), +) + + +SEQUENCE_GAP_SCHEMA = pa.schema( + [ + pa.field("schema_version", pa.string(), nullable=False), + pa.field("venue", pa.string(), nullable=False), + pa.field("symbol", pa.string(), nullable=False), + pa.field("continuity_id", pa.string(), nullable=False), + pa.field("expected_sequence", pa.int64(), nullable=False), + pa.field("observed_sequence_start", pa.int64(), nullable=False), + pa.field("observed_sequence_end", pa.int64(), nullable=False), + pa.field("missing_start", pa.int64(), nullable=False), + pa.field("missing_end", pa.int64(), nullable=False), + pa.field("detected_ts_ns", pa.int64(), nullable=False), + pa.field("reason", pa.string(), nullable=False), + pa.field("source_artifact_id", pa.string(), nullable=False), + ], + metadata=_metadata("sequence_gaps"), +) + + +SCHEMAS: Mapping[str, pa.Schema] = { + "trades": TRADE_SCHEMA, + "book_observations": BOOK_OBSERVATION_SCHEMA, + "depth_deltas": DEPTH_DELTA_SCHEMA, + "book_snapshots": BOOK_SNAPSHOT_SCHEMA, + "sequence_gaps": SEQUENCE_GAP_SCHEMA, +} + + +def get_schema(name: str, version: str = SCHEMA_VERSION) -> pa.Schema: + """Return a schema by stable name and fail closed on unknown versions.""" + if version != SCHEMA_VERSION: + raise SchemaError(f"unsupported schema version {version!r}; expected {SCHEMA_VERSION!r}") + try: + return SCHEMAS[name] + except KeyError as exc: + raise SchemaError(f"unknown normalized schema: {name!r}") from exc + + +def table_from_records(name: str, records: Iterable[Mapping[str, Any]]) -> pa.Table: + """Construct a table using the registry rather than inferred Arrow types.""" + schema = get_schema(name) + try: + return pa.Table.from_pylist(list(records), schema=schema) + except (pa.ArrowException, TypeError, ValueError) as exc: + raise SchemaError(f"records do not conform to {name} {SCHEMA_VERSION}: {exc}") from exc + + +def ensure_schema(table: pa.Table | pa.RecordBatch, name: str) -> None: + """Require exact field order/types/nullability; metadata may be absent on batches.""" + expected = get_schema(name) + actual = table.schema + if not actual.equals(expected, check_metadata=False): + raise SchemaError(f"schema mismatch for {name}: expected {expected}, got {actual}") + metadata = actual.metadata or {} + declared_name = metadata.get(b"schema_name") + declared_version = metadata.get(b"schema_version") + if declared_name is not None and declared_name != name.encode(): + raise SchemaError( + f"schema metadata name mismatch: expected {name!r}, got {declared_name.decode()}" + ) + if declared_version is not None and declared_version != SCHEMA_VERSION.encode(): + raise SchemaError( + "schema metadata version mismatch: " + f"expected {SCHEMA_VERSION!r}, got {declared_version.decode()}" + ) + version_column = table.column(actual.get_field_index("schema_version")) + observed_versions = set(version_column.to_pylist()) + if observed_versions.difference({SCHEMA_VERSION}): + raise SchemaError( + f"row schema_version mismatch: expected only {SCHEMA_VERSION!r}, " + f"got {sorted(observed_versions)!r}" + ) diff --git a/Microstructure/src/microstructure/data/storage.py b/Microstructure/src/microstructure/data/storage.py new file mode 100644 index 0000000000000000000000000000000000000000..a8eb3f14f13bc279e55bd370bbd0a79c0ed4aad8 --- /dev/null +++ b/Microstructure/src/microstructure/data/storage.py @@ -0,0 +1,605 @@ +"""Streaming, content-addressed Parquet storage and immutable data manifests.""" + +from __future__ import annotations + +import hashlib +import json +import os +import re +import tempfile +from collections import defaultdict +from collections.abc import Iterable, Mapping, Sequence +from contextlib import nullcontext, suppress +from dataclasses import dataclass +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +import pyarrow as pa # type: ignore[import-untyped] +import pyarrow.compute as pc # type: ignore[import-untyped] +import pyarrow.parquet as pq # type: ignore[import-untyped] + +from microstructure.data.evidence_budget import RetainedEvidenceBudget +from microstructure.data.schemas import SCHEMA_VERSION, ensure_schema, get_schema +from microstructure.provenance import read_json, sha256_file, utc_now_iso, write_json + +MANIFEST_VERSION = "1.0.0" +_SAFE_COMPONENT = re.compile(r"^[A-Za-z0-9_.-]+$") +_NS_PER_SECOND = 1_000_000_000 + + +class StorageError(RuntimeError): + """Raised for an unsafe path or inconsistent immutable artifact.""" + + +@dataclass(frozen=True, slots=True) +class PartitionArtifact: + dataset: str + venue: str + symbol: str + partition_date: str + rows: int + write_ordinal: int + observed_start_ns: int + observed_end_inclusive_ns: int + data_path: Path + manifest_path: Path + data_sha256: str + manifest_sha256: str + + +@dataclass(frozen=True, slots=True) +class DatasetWriteResult: + dataset: str + schema_version: str + rows: int + artifacts: tuple[PartitionArtifact, ...] + manifest_path: Path + manifest_sha256: str + + +@dataclass(frozen=True, slots=True) +class CaptureDatasetWriteResult: + """Constant-descriptor result for one bounded-memory live capture.""" + + dataset: str + schema_version: str + rows: int + data_path: Path | None + data_sha256: str | None + manifest_path: Path + manifest_sha256: str + + +def _safe(value: str, label: str) -> str: + if not value or _SAFE_COMPONENT.fullmatch(value) is None: + raise StorageError(f"unsafe {label} path component: {value!r}") + return value + + +def _stable_sha(payload: Mapping[str, Any]) -> str: + encoded = json.dumps(payload, sort_keys=True, separators=(",", ":"), allow_nan=False) + return hashlib.sha256(encoded.encode()).hexdigest() + + +def _partition_date(timestamp_ns: int) -> str: + seconds = timestamp_ns // _NS_PER_SECOND + return datetime.fromtimestamp(seconds, tz=UTC).date().isoformat() + + +def _immutable_json( + directory: Path, + stem: str, + payload: Mapping[str, Any], + *, + retained_evidence_budget: RetainedEvidenceBudget | None = None, +) -> tuple[Path, str]: + identity = _stable_sha(payload) + destination = directory / f"{stem}-{identity[:20]}.json" + if retained_evidence_budget is not None: + retained_evidence_budget.assert_contains(destination) + transaction = ( + retained_evidence_budget.write_transaction() + if retained_evidence_budget is not None + else nullcontext() + ) + with transaction: + if destination.exists(): + existing = read_json(destination) + if existing != dict(payload): + raise StorageError(f"immutable manifest collision at {destination}") + else: + encoded = ( + json.dumps(payload, indent=2, sort_keys=True, allow_nan=False) + "\n" + ).encode() + reservation = ( + retained_evidence_budget.reserve( + len(encoded), + label=f"raw source manifest {destination.name}", + ) + if retained_evidence_budget is not None + else None + ) + try: + write_json(destination, payload) + if destination.stat().st_size != len(encoded): + raise StorageError( + f"source manifest byte count changed while writing {destination}" + ) + if reservation is not None: + reservation.commit() + except BaseException: + destination.unlink(missing_ok=True) + if reservation is not None and reservation.active: + reservation.release() + raise + return destination, sha256_file(destination) + + +def write_source_manifest( + raw_path: str | Path, + *, + source: str, + source_uri: str, + downloaded_at_utc: str, + requested_start_ns: int | None, + requested_end_ns: int | None, + upstream_checksum_sha256: str | None = None, + response_headers: Mapping[str, str] | None = None, + retained_evidence_budget: RetainedEvidenceBudget | None = None, +) -> tuple[Path, str]: + """Write an immutable sidecar for an untouched raw response or archive.""" + path = Path(raw_path) + if not path.is_file(): + raise StorageError(f"raw artifact does not exist: {path}") + checksum = sha256_file(path) + payload: dict[str, Any] = { + "manifest_version": MANIFEST_VERSION, + "artifact_kind": "raw_source", + "source": source, + "source_uri": source_uri, + "downloaded_at_utc": downloaded_at_utc, + "requested_range_ns": {"start": requested_start_ns, "end_exclusive": requested_end_ns}, + "checksum": {"algorithm": "sha256", "value": checksum}, + "upstream_checksum_sha256": upstream_checksum_sha256, + "bytes": path.stat().st_size, + "path": path.name, + "response_headers": dict(sorted((response_headers or {}).items())), + } + manifest_path, manifest_sha = _immutable_json( + path.parent, + f"{path.name}.manifest", + payload, + retained_evidence_budget=retained_evidence_budget, + ) + return manifest_path, manifest_sha + + +def _write_parquet_part( + *, + table: pa.Table, + root: Path, + dataset: str, + schema_name: str, + venue: str, + symbol: str, + date: str, + source: str, + source_uri: str, + downloaded_at_utc: str, + source_checksum_sha256: str | None, + requested_start_ns: int | None, + requested_end_ns: int | None, + time_column: str, + compression: str, + write_ordinal: int, +) -> PartitionArtifact: + partition = ( + root + / _safe(dataset, "dataset") + / f"schema-{_safe(SCHEMA_VERSION, 'schema version')}" + / f"venue-{_safe(venue, 'venue')}" + / f"symbol-{_safe(symbol, 'symbol')}" + / f"date-{_safe(date, 'date')}" + ) + partition.mkdir(parents=True, exist_ok=True) + handle, temporary_name = tempfile.mkstemp(dir=partition, prefix=".part-", suffix=".parquet.tmp") + os.close(handle) + temporary = Path(temporary_name) + try: + table = table.replace_schema_metadata(get_schema(schema_name).metadata) + pq.write_table( + table, + temporary, + compression=compression, + use_dictionary=True, + write_statistics=True, + ) + checksum = sha256_file(temporary) + destination = partition / f"part-{checksum[:20]}.parquet" + if destination.exists(): + if sha256_file(destination) != checksum: + raise StorageError(f"content-address collision at {destination}") + temporary.unlink() + else: + os.replace(temporary, destination) + except BaseException: + temporary.unlink(missing_ok=True) + raise + + time_bounds = pc.min_max(table.column(time_column)).as_py() + if time_bounds is None or time_bounds["min"] is None or time_bounds["max"] is None: + raise StorageError("cannot manifest a Parquet part without a timestamp range") + manifest_payload: dict[str, Any] = { + "manifest_version": MANIFEST_VERSION, + "artifact_kind": "normalized_parquet", + "dataset": dataset, + "schema_name": schema_name, + "schema_version": SCHEMA_VERSION, + "venue": venue, + "symbol": symbol, + "partition_date": date, + "write_ordinal": write_ordinal, + "source": source, + "source_uri": source_uri, + "downloaded_at_utc": downloaded_at_utc, + "requested_range_ns": {"start": requested_start_ns, "end_exclusive": requested_end_ns}, + "observed_range_ns": { + "start": int(time_bounds["min"]), + "end_inclusive": int(time_bounds["max"]), + }, + "source_checksum_sha256": source_checksum_sha256, + "checksum": {"algorithm": "sha256", "value": checksum}, + "rows": table.num_rows, + "bytes": destination.stat().st_size, + "path": str(destination.relative_to(root)), + "transformations": [ + "normalized field names and types", + "UTC epoch-nanosecond timestamp conversion", + "exact integer tick/lot conversion where scale supplied", + ], + } + manifest_path, manifest_sha = _immutable_json( + partition, f"part-{checksum[:20]}.manifest", manifest_payload + ) + return PartitionArtifact( + dataset=dataset, + venue=venue, + symbol=symbol, + partition_date=date, + rows=table.num_rows, + write_ordinal=write_ordinal, + observed_start_ns=int(time_bounds["min"]), + observed_end_inclusive_ns=int(time_bounds["max"]), + data_path=destination, + manifest_path=manifest_path, + data_sha256=checksum, + manifest_sha256=manifest_sha, + ) + + +def _as_table(batch: pa.RecordBatch | pa.Table) -> pa.Table: + return batch if isinstance(batch, pa.Table) else pa.Table.from_batches([batch]) + + +def write_partitioned_parquet( + batches: Iterable[pa.RecordBatch | pa.Table], + *, + root: str | Path, + dataset: str, + schema_name: str, + source: str, + source_uri: str = "synthetic://local", + downloaded_at_utc: str | None = None, + source_checksum_sha256: str | None = None, + requested_start_ns: int | None = None, + requested_end_ns: int | None = None, + time_column: str = "event_ts_ns", + max_rows_per_file: int = 250_000, + max_input_batch_rows: int = 250_000, + compression: str = "zstd", +) -> DatasetWriteResult: + """Stream batches into immutable Parquet parts partitioned by venue/symbol/day. + + Each input batch is split only within that bounded batch, so this function + never requires the complete data set in memory. Existing content-addressed + parts are reused rather than overwritten. + """ + if max_rows_per_file < 1: + raise ValueError("max_rows_per_file must be positive") + if max_input_batch_rows < 1: + raise ValueError("max_input_batch_rows must be positive") + destination_root = Path(root) + destination_root.mkdir(parents=True, exist_ok=True) + download_time = downloaded_at_utc or utc_now_iso() + artifacts: list[PartitionArtifact] = [] + + for raw_batch in batches: + table = _as_table(raw_batch) + if table.num_rows > max_input_batch_rows: + raise StorageError( + f"input batch has {table.num_rows} rows, above the bounded-memory limit " + f"{max_input_batch_rows}" + ) + ensure_schema(table, schema_name) + if time_column not in table.column_names: + raise StorageError(f"partition time column is missing: {time_column}") + groups: dict[tuple[str, str, str], list[int]] = defaultdict(list) + venues = table.column("venue").to_pylist() + symbols = table.column("symbol").to_pylist() + timestamps = table.column(time_column).to_pylist() + for row_index, (venue, symbol, timestamp_ns) in enumerate( + zip(venues, symbols, timestamps, strict=True) + ): + groups[(str(venue), str(symbol), _partition_date(int(timestamp_ns)))].append(row_index) + + for (venue, symbol, date), indices in groups.items(): + for offset in range(0, len(indices), max_rows_per_file): + selected = indices[offset : offset + max_rows_per_file] + part = table.take(pa.array(selected, type=pa.int64())) + artifacts.append( + _write_parquet_part( + table=part, + root=destination_root, + dataset=dataset, + schema_name=schema_name, + venue=venue, + symbol=symbol, + date=date, + source=source, + source_uri=source_uri, + downloaded_at_utc=download_time, + source_checksum_sha256=source_checksum_sha256, + requested_start_ns=requested_start_ns, + requested_end_ns=requested_end_ns, + time_column=time_column, + compression=compression, + write_ordinal=len(artifacts), + ) + ) + + artifact_entries = [ + { + "data_path": str(item.data_path.relative_to(destination_root)), + "manifest_path": str(item.manifest_path.relative_to(destination_root)), + "data_sha256": item.data_sha256, + "manifest_sha256": item.manifest_sha256, + "rows": item.rows, + "write_ordinal": item.write_ordinal, + "observed_range_ns": { + "start": item.observed_start_ns, + "end_inclusive": item.observed_end_inclusive_ns, + }, + } + for item in artifacts + ] + stable_identity: dict[str, Any] = { + "manifest_version": MANIFEST_VERSION, + "dataset": dataset, + "schema_version": SCHEMA_VERSION, + "source": source, + "source_uri": source_uri, + "downloaded_at_utc": download_time, + "requested_range_ns": {"start": requested_start_ns, "end_exclusive": requested_end_ns}, + "artifacts": artifact_entries, + "rows": sum(item.rows for item in artifacts), + } + manifest_directory = destination_root / "_manifests" + manifest_directory.mkdir(parents=True, exist_ok=True) + manifest_path, manifest_sha = _immutable_json( + manifest_directory, f"{_safe(dataset, 'dataset')}.manifest", stable_identity + ) + return DatasetWriteResult( + dataset=dataset, + schema_version=SCHEMA_VERSION, + rows=sum(item.rows for item in artifacts), + artifacts=tuple(artifacts), + manifest_path=manifest_path, + manifest_sha256=manifest_sha, + ) + + +def write_capture_parquet( + batches: Iterable[pa.RecordBatch | pa.Table], + *, + root: str | Path, + dataset: str, + schema_name: str, + venue: str, + symbol: str, + capture_id: str, + source: str, + source_uri: str, + downloaded_at_utc: str | None = None, + source_checksum_sha256: str | None = None, + requested_start_ns: int | None = None, + requested_end_ns: int | None = None, + time_column: str = "event_ts_ns", + max_input_batch_rows: int = 16_384, + compression: str = "zstd", +) -> CaptureDatasetWriteResult: + """Write one live-capture Parquet artifact from a bounded batch iterator. + + The Parquet writer emits one bounded row group per input batch and retains + exactly one output descriptor, independent of capture length. Live capture + data is partitioned by immutable ``capture_id`` rather than UTC day because + capture-order quality evidence must not be reordered to satisfy a partition. + """ + if max_input_batch_rows < 1: + raise ValueError("max_input_batch_rows must be positive") + safe_dataset = _safe(dataset, "dataset") + safe_schema = _safe(SCHEMA_VERSION, "schema version") + safe_venue = _safe(venue, "venue") + safe_symbol = _safe(symbol, "symbol") + safe_capture_id = _safe(capture_id, "capture ID") + schema = get_schema(schema_name) + if time_column not in schema.names: + raise StorageError(f"partition time column is missing: {time_column}") + + destination_root = Path(root) + partition = ( + destination_root + / safe_dataset + / f"schema-{safe_schema}" + / f"venue-{safe_venue}" + / f"symbol-{safe_symbol}" + / f"capture-{safe_capture_id}" + ) + partition.mkdir(parents=True, exist_ok=True) + descriptor, temporary_name = tempfile.mkstemp( + dir=partition, + prefix=".capture-", + suffix=".parquet.tmp", + ) + os.close(descriptor) + temporary = Path(temporary_name) + writer: pq.ParquetWriter | None = None + rows = 0 + observed_start_ns: int | None = None + observed_end_ns: int | None = None + destination: Path | None = None + checksum: str | None = None + try: + writer = pq.ParquetWriter( + temporary, + schema, + compression=compression, + use_dictionary=True, + write_statistics=True, + ) + for raw_batch in batches: + table = _as_table(raw_batch) + if table.num_rows > max_input_batch_rows: + raise StorageError( + f"input batch has {table.num_rows} rows, above the bounded-memory " + f"limit {max_input_batch_rows}" + ) + ensure_schema(table, schema_name) + if table.num_rows == 0: + continue + if set(table.column("venue").to_pylist()) != {venue}: + raise StorageError("live capture batch contains an unexpected venue") + if set(table.column("symbol").to_pylist()) != {symbol}: + raise StorageError("live capture batch contains an unexpected symbol") + bounds = pc.min_max(table.column(time_column)).as_py() + if bounds is None or bounds["min"] is None or bounds["max"] is None: + raise StorageError("cannot write a live capture batch without timestamps") + batch_start = int(bounds["min"]) + batch_end = int(bounds["max"]) + observed_start_ns = ( + batch_start if observed_start_ns is None else min(observed_start_ns, batch_start) + ) + observed_end_ns = ( + batch_end if observed_end_ns is None else max(observed_end_ns, batch_end) + ) + writer.write_table(table, row_group_size=max_input_batch_rows) + rows += table.num_rows + writer.close() + writer = None + if rows == 0: + temporary.unlink() + else: + with temporary.open("rb") as handle: + os.fsync(handle.fileno()) + checksum = sha256_file(temporary) + destination = partition / f"capture-{checksum[:20]}.parquet" + if destination.exists(): + if sha256_file(destination) != checksum: + raise StorageError(f"content-address collision at {destination}") + temporary.unlink() + else: + os.replace(temporary, destination) + except BaseException: + if writer is not None: + with suppress(BaseException): + writer.close() + temporary.unlink(missing_ok=True) + raise + + download_time = downloaded_at_utc or utc_now_iso() + data_path = destination + data_sha256 = checksum + artifact_entry: dict[str, Any] | None = None + if data_path is not None and data_sha256 is not None: + artifact_payload: dict[str, Any] = { + "manifest_version": MANIFEST_VERSION, + "artifact_kind": "normalized_live_capture_parquet", + "dataset": dataset, + "schema_name": schema_name, + "schema_version": SCHEMA_VERSION, + "venue": venue, + "symbol": symbol, + "capture_id": capture_id, + "source": source, + "source_uri": source_uri, + "downloaded_at_utc": download_time, + "requested_range_ns": { + "start": requested_start_ns, + "end_exclusive": requested_end_ns, + }, + "observed_range_ns": { + "start": observed_start_ns, + "end_inclusive": observed_end_ns, + }, + "source_checksum_sha256": source_checksum_sha256, + "checksum": {"algorithm": "sha256", "value": data_sha256}, + "rows": rows, + "bytes": data_path.stat().st_size, + "path": str(data_path.relative_to(destination_root)), + "transformations": [ + "normalized field names and types", + "UTC epoch-nanosecond timestamp conversion", + "exact integer tick/lot conversion where scale supplied", + ], + } + artifact_manifest_path, artifact_manifest_sha = _immutable_json( + partition, + f"capture-{data_sha256[:20]}.manifest", + artifact_payload, + ) + artifact_entry = { + "data_path": str(data_path.relative_to(destination_root)), + "manifest_path": str(artifact_manifest_path.relative_to(destination_root)), + "data_sha256": data_sha256, + "manifest_sha256": artifact_manifest_sha, + "rows": rows, + "write_ordinal": 0, + "observed_range_ns": artifact_payload["observed_range_ns"], + } + + dataset_payload: dict[str, Any] = { + "manifest_version": MANIFEST_VERSION, + "dataset": dataset, + "schema_version": SCHEMA_VERSION, + "source": source, + "source_uri": source_uri, + "downloaded_at_utc": download_time, + "requested_range_ns": { + "start": requested_start_ns, + "end_exclusive": requested_end_ns, + }, + "partitioning": {"kind": "capture_id", "value": capture_id}, + "artifacts": [artifact_entry] if artifact_entry is not None else [], + "rows": rows, + } + manifest_directory = destination_root / "_manifests" + manifest_directory.mkdir(parents=True, exist_ok=True) + manifest_path, manifest_sha = _immutable_json( + manifest_directory, + f"{safe_dataset}.capture-{safe_capture_id}.manifest", + dataset_payload, + ) + return CaptureDatasetWriteResult( + dataset=dataset, + schema_version=SCHEMA_VERSION, + rows=rows, + data_path=data_path, + data_sha256=data_sha256, + manifest_path=manifest_path, + manifest_sha256=manifest_sha, + ) + + +def parquet_paths(result: DatasetWriteResult) -> Sequence[Path]: + """Return concrete parts in manifest order for Polars/DuckDB consumers.""" + return tuple(item.data_path for item in result.artifacts) diff --git a/Microstructure/src/microstructure/data/synthetic.py b/Microstructure/src/microstructure/data/synthetic.py new file mode 100644 index 0000000000000000000000000000000000000000..6deb92ea7581e9ad80bcdac4e11e9041ec2ba08d --- /dev/null +++ b/Microstructure/src/microstructure/data/synthetic.py @@ -0,0 +1,229 @@ +"""Deterministic, explicitly synthetic L1 and trade event generation.""" + +from __future__ import annotations + +import hashlib +import random +from collections.abc import Iterator, Sequence +from dataclasses import dataclass + +import pyarrow as pa # type: ignore[import-untyped] + +from microstructure.data.schemas import SCHEMA_VERSION, table_from_records + +_NS_PER_MILLISECOND = 1_000_000 + + +@dataclass(frozen=True, slots=True) +class SyntheticMarketData: + """Small synthetic market tables; never evidence of observed market behavior.""" + + trades: pa.Table + book_observations: pa.Table + evidence_tier: str = "SYNTHETIC_SMOKE" + + +def _symbol_seed(seed: int, symbol: str) -> int: + material = f"{seed}:{symbol}".encode() + return int.from_bytes(hashlib.sha256(material).digest()[:8], "big") + + +def _initial_mid_ticks(symbol: str) -> int: + if symbol.upper().startswith("BTC"): + return 3_000_000 + if symbol.upper().startswith("ETH"): + return 200_000 + return 100_000 + + +def _imbalance(bid: float, ask: float) -> float: + total = bid + ask + return (bid - ask) / total if total > 0.0 else 0.0 + + +def _symbol_records( + *, + symbol: str, + events: int, + start_ts_ns: int, + seed: int, + event_spacing_ns: int, + tick_size: float, + lot_size: float, +) -> tuple[list[dict[str, object]], list[dict[str, object]]]: + rng = random.Random(_symbol_seed(seed, symbol)) + mid_ticks = _initial_mid_ticks(symbol) + trades: list[dict[str, object]] = [] + books: list[dict[str, object]] = [] + continuity_id = f"synthetic:{symbol}:0" + source_artifact_id = f"synthetic-v1-seed-{seed}" + + for index in range(events): + event_ts_ns = start_ts_ns + index * event_spacing_ns + bid_level_lots = rng.randint(50, 250) + ask_level_lots = rng.randint(50, 250) + imbalance_1 = _imbalance(float(bid_level_lots), float(ask_level_lots)) + + movement_draw = rng.random() + upward_probability = 0.50 + 0.20 * imbalance_1 + if movement_draw < upward_probability - 0.10: + mid_ticks += 1 + elif movement_draw > upward_probability + 0.10: + mid_ticks -= 1 + mid_ticks = max(mid_ticks, 10) + + spread_ticks = 1 if rng.random() < 0.85 else 2 + best_bid_ticks = mid_ticks - spread_ticks // 2 + best_ask_ticks = best_bid_ticks + spread_ticks + + extra_bid_5 = sum(rng.randint(30, 180) for _ in range(4)) + extra_ask_5 = sum(rng.randint(30, 180) for _ in range(4)) + extra_bid_10 = sum(rng.randint(20, 140) for _ in range(5)) + extra_ask_10 = sum(rng.randint(20, 140) for _ in range(5)) + depth_bid_1_lots = bid_level_lots + depth_ask_1_lots = ask_level_lots + depth_bid_5_lots = depth_bid_1_lots + extra_bid_5 + depth_ask_5_lots = depth_ask_1_lots + extra_ask_5 + depth_bid_10_lots = depth_bid_5_lots + extra_bid_10 + depth_ask_10_lots = depth_ask_5_lots + extra_ask_10 + + best_bid = best_bid_ticks * tick_size + best_ask = best_ask_ticks * tick_size + bid_quantity = bid_level_lots * lot_size + ask_quantity = ask_level_lots * lot_size + mid_price = (best_bid + best_ask) / 2.0 + microprice = (best_ask * bid_quantity + best_bid * ask_quantity) / ( + bid_quantity + ask_quantity + ) + received_ts_ns = event_ts_ns + 100_000 + + books.append( + { + "schema_version": SCHEMA_VERSION, + "venue": "synthetic", + "symbol": symbol, + "event_ts_ns": event_ts_ns, + "received_ts_ns": received_ts_ns, + "available_ts_ns": received_ts_ns, + "availability_basis": "synthetic_receipt", + "capture_seq": index * 2, + "continuity_id": continuity_id, + "sequence_start": index + 1, + "sequence_end": index + 1, + "is_valid": True, + "best_bid_ticks": best_bid_ticks, + "best_ask_ticks": best_ask_ticks, + "bid_quantity_lots": bid_level_lots, + "ask_quantity_lots": ask_level_lots, + "tick_size": tick_size, + "lot_size": lot_size, + "best_bid": best_bid, + "best_ask": best_ask, + "bid_quantity": bid_quantity, + "ask_quantity": ask_quantity, + "spread": best_ask - best_bid, + "mid_price": mid_price, + "microprice": microprice, + "depth_bid_1": depth_bid_1_lots * lot_size, + "depth_ask_1": depth_ask_1_lots * lot_size, + "depth_bid_5": depth_bid_5_lots * lot_size, + "depth_ask_5": depth_ask_5_lots * lot_size, + "depth_bid_10": depth_bid_10_lots * lot_size, + "depth_ask_10": depth_ask_10_lots * lot_size, + "queue_imbalance_1": _imbalance(float(depth_bid_1_lots), float(depth_ask_1_lots)), + "queue_imbalance_5": _imbalance(float(depth_bid_5_lots), float(depth_ask_5_lots)), + "queue_imbalance_10": _imbalance( + float(depth_bid_10_lots), float(depth_ask_10_lots) + ), + "source_artifact_id": source_artifact_id, + } + ) + + buy_probability = 0.50 + 0.25 * imbalance_1 + aggressor_side = "buy" if rng.random() < buy_probability else "sell" + price_ticks = best_ask_ticks if aggressor_side == "buy" else best_bid_ticks + quantity_lots = rng.randint(1, 40) + trade_price = price_ticks * tick_size + trade_quantity = quantity_lots * lot_size + trade_event_ts_ns = event_ts_ns + 20_000 + trade_received_ts_ns = event_ts_ns + 150_000 + trades.append( + { + "schema_version": SCHEMA_VERSION, + "venue": "synthetic", + "symbol": symbol, + "event_ts_ns": trade_event_ts_ns, + "received_ts_ns": trade_received_ts_ns, + "available_ts_ns": trade_received_ts_ns, + "availability_basis": "synthetic_receipt", + "capture_seq": index * 2 + 1, + "continuity_id": continuity_id, + "trade_id": index + 1, + "first_trade_id": index + 1, + "last_trade_id": index + 1, + "price_ticks": price_ticks, + "quantity_lots": quantity_lots, + "tick_size": tick_size, + "lot_size": lot_size, + "price": trade_price, + "quantity": trade_quantity, + "quote_quantity": trade_price * trade_quantity, + "aggressor_side": aggressor_side, + "buyer_is_maker": aggressor_side == "sell", + "source_artifact_id": source_artifact_id, + } + ) + + return trades, books + + +def generate_synthetic_market( + *, + symbols: Sequence[str], + events_per_symbol: int, + start_ts_ns: int, + seed: int, + event_spacing_ns: int = 100 * _NS_PER_MILLISECOND, + tick_size: float = 0.01, + lot_size: float = 0.001, +) -> SyntheticMarketData: + """Generate deterministic bounded tables for smoke tests and demos. + + The generator is intentionally labelled synthetic in every row and result. + It is not calibrated to Binance and must never be reported as market data. + """ + if events_per_symbol < 1: + raise ValueError("events_per_symbol must be positive") + if event_spacing_ns < 1: + raise ValueError("event_spacing_ns must be positive") + if tick_size <= 0.0 or lot_size <= 0.0: + raise ValueError("tick_size and lot_size must be positive") + if not symbols: + raise ValueError("symbols must not be empty") + + trade_records: list[dict[str, object]] = [] + book_records: list[dict[str, object]] = [] + for raw_symbol in symbols: + symbol = raw_symbol.upper() + trades, books = _symbol_records( + symbol=symbol, + events=events_per_symbol, + start_ts_ns=start_ts_ns, + seed=seed, + event_spacing_ns=event_spacing_ns, + tick_size=tick_size, + lot_size=lot_size, + ) + trade_records.extend(trades) + book_records.extend(books) + return SyntheticMarketData( + trades=table_from_records("trades", trade_records), + book_observations=table_from_records("book_observations", book_records), + ) + + +def iter_table_batches(table: pa.Table, batch_size: int = 100_000) -> Iterator[pa.RecordBatch]: + """Expose bounded RecordBatches for the streaming storage interface.""" + if batch_size < 1: + raise ValueError("batch_size must be positive") + yield from table.to_batches(max_chunksize=batch_size) diff --git a/Microstructure/src/microstructure/execution/__init__.py b/Microstructure/src/microstructure/execution/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6c93347ab0b92c4171ec4287679f279ea6155122 --- /dev/null +++ b/Microstructure/src/microstructure/execution/__init__.py @@ -0,0 +1,9 @@ +"""Research-grade, account-free execution simulation.""" + +from microstructure.execution.simulator import ( + SimulationResult, + run_execution_sensitivity, + simulate_predictions, +) + +__all__ = ["SimulationResult", "run_execution_sensitivity", "simulate_predictions"] diff --git a/Microstructure/src/microstructure/execution/simulator.py b/Microstructure/src/microstructure/execution/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..353116da39ccf9cf4d033f38b7a379841b04253f --- /dev/null +++ b/Microstructure/src/microstructure/execution/simulator.py @@ -0,0 +1,803 @@ +"""Deterministic event-driven simulation with explicit fill assumptions. + +The simulator consumes historical market states and out-of-sample predictions. +It never connects to an exchange and it deliberately leaves the replay exogenous: +capacity sweeps expose, but cannot identify, endogenous market impact. +""" + +from __future__ import annotations + +import hashlib +import math +from collections import defaultdict +from dataclasses import dataclass +from typing import Any, Literal, cast + +import numpy as np +import polars as pl + +from microstructure.config import ExecutionConfig + +OrderType = Literal["market", "limit"] + + +@dataclass(frozen=True, slots=True) +class SimulationResult: + """Serialized tables and accounting metrics from one simulation scenario.""" + + orders: pl.DataFrame + fills: pl.DataFrame + positions: pl.DataFrame + metrics: dict[str, Any] + assumptions: dict[str, Any] + + +@dataclass(slots=True) +class _ActiveLimit: + order: dict[str, Any] + remaining_quantity: float + queue_ahead: float + cancel_effective_position: int + + +def _number(row: dict[str, Any], *names: str, default: float | None = None) -> float: + for name in names: + value = row.get(name) + if value is not None: + return float(value) + if default is not None: + return default + raise ValueError(f"market event is missing all required columns: {names}") + + +def _object_float(value: object) -> float: + return float(cast(Any, value)) + + +def _object_int(value: object) -> int: + return int(cast(Any, value)) + + +def _integer(row: dict[str, Any], *names: str) -> int: + for name in names: + value = row.get(name) + if value is not None: + return int(value) + raise ValueError(f"row is missing all required identifier columns: {names}") + + +def _mid(row: dict[str, Any]) -> float: + direct = row.get("mid_price") + if direct is not None: + return float(direct) + bid = _number(row, "best_bid", "bid_price_1") + ask = _number(row, "best_ask", "ask_price_1") + return 0.5 * (bid + ask) + + +def _prediction_probability(row: dict[str, Any]) -> float: + return _number(row, "probability", "probability_up", "prediction", "y_probability") + + +def _event_identifier(row: dict[str, Any]) -> int: + return _integer( + row, + "decision_sequence", + "sequence_end", + "sample_id", + "event_index", + "event_id", + "row_id", + ) + + +def _timestamp(row: dict[str, Any]) -> int: + return _integer(row, "event_ts_ns", "decision_ts_ns", "available_ts_ns") + + +def _continuity(row: dict[str, Any]) -> str: + value = row.get("continuity_id") + return str(value) if value is not None else "__NO_CONTINUITY_ID__" + + +def _trade_side(row: dict[str, Any]) -> int: + value = row.get("trade_side", row.get("aggressor_side", row.get("side", 0))) + if isinstance(value, str): + normalized = value.lower() + if normalized == "buy": + return 1 + if normalized == "sell": + return -1 + return 0 + return _object_int(value) if value is not None else 0 + + +def _displayed_depth(row: dict[str, Any], side: int) -> float: + if side == 1: + return _number( + row, "ask_depth_1", "depth_ask_1", "ask_quantity_1", "ask_quantity", default=0.0 + ) + return _number(row, "bid_depth_1", "depth_bid_1", "bid_quantity_1", "bid_quantity", default=0.0) + + +def _seeded_uniform(seed: int, order_id: object, event_id: int) -> float: + payload = f"{seed}:{order_id}:{event_id}".encode() + integer = int.from_bytes(hashlib.sha256(payload).digest()[:8], "big") + return integer / float(2**64) + + +def _round_quantity(quantity: float, row: dict[str, Any]) -> float: + lot_size = _number(row, "lot_size", default=0.0) + if lot_size <= 0: + return quantity + return math.floor((quantity + lot_size * 1e-12) / lot_size) * lot_size + + +def _round_price_adversely(price: float, side: int, row: dict[str, Any]) -> float: + tick_size = _number(row, "tick_size", default=0.0) + if tick_size <= 0: + return price + scaled = price / tick_size + ticks = math.ceil(scaled - 1e-12) if side == 1 else math.floor(scaled + 1e-12) + return ticks * tick_size + + +def _empty_frame(columns: dict[str, Any]) -> pl.DataFrame: + return pl.DataFrame(schema=columns) + + +def _portfolio_max_drawdown(equity_rows: list[dict[str, Any]]) -> float: + """Return zero-capital marked net-equity peak-to-trough drawdown.""" + latest_equity: dict[str, float] = {} + peak = 0.0 + maximum_drawdown = 0.0 + ordered = sorted( + equity_rows, + key=lambda item: (int(item["event_ts_ns"]), int(item["observation_id"])), + ) + index = 0 + while index < len(ordered): + timestamp = int(ordered[index]["event_ts_ns"]) + while index < len(ordered) and int(ordered[index]["event_ts_ns"]) == timestamp: + row = ordered[index] + latest_equity[str(row["symbol"])] = float(row["net_equity"]) + index += 1 + portfolio_equity = sum(latest_equity.values()) + peak = max(peak, portfolio_equity) + maximum_drawdown = max(maximum_drawdown, peak - portfolio_equity) + return maximum_drawdown + + +def simulate_predictions( + events: pl.DataFrame, + predictions: pl.DataFrame, + config: ExecutionConfig, + *, + order_type: OrderType = "market", + size_multiplier: float = 1.0, + seed: int = 0, + markout_events: int = 20, +) -> SimulationResult: + """Replay a prediction policy with fees, latency, depth, and inventory limits. + + Event rows must contain a symbol, event/sample identifier, timestamp, top of + book, displayed L1 depth, and—when passive fills are requested—signed trade + quantity. A positive trade side is buyer initiated. Predictions must be + explicitly out of sample when an ``is_oos`` column is present. + """ + if order_type not in {"market", "limit"}: + raise ValueError(f"unsupported order_type: {order_type}") + if not math.isfinite(size_multiplier) or size_multiplier <= 0: + raise ValueError("size_multiplier must be finite and positive") + if markout_events < 0: + raise ValueError("markout_events must be nonnegative") + if config.decision_latency_events < 0 or config.order_latency_events < 0: + raise ValueError("decision and order latency must be nonnegative") + if not math.isfinite(config.queue_ahead_units) or config.queue_ahead_units < 0: + raise ValueError("queue_ahead_units must be finite and nonnegative") + if events.is_empty(): + raise ValueError("events must not be empty") + required_prediction_columns = {"symbol", "is_oos", "split"} + missing_prediction_columns = sorted(required_prediction_columns.difference(predictions.columns)) + if missing_prediction_columns: + raise ValueError( + "execution predictions require explicit OOS provenance columns: " + f"{missing_prediction_columns}" + ) + if not bool(predictions.get_column("is_oos").fill_null(False).all()): + raise ValueError("execution simulation rejects non-OOS predictions") + invalid_splits = predictions.filter( + ~pl.col("split") + .cast(pl.String) + .str.to_lowercase() + .is_in(["test", "final_test", "holdout", "held_out"]) + ) + if not invalid_splits.is_empty(): + raise ValueError("execution simulation accepts held-out test predictions only") + + event_rows = events.to_dicts() + prediction_rows = predictions.to_dicts() + by_symbol: dict[str, list[dict[str, Any]]] = defaultdict(list) + for row in event_rows: + by_symbol[str(row["symbol"])].append(row) + for rows in by_symbol.values(): + rows.sort(key=lambda item: (_timestamp(item), _event_identifier(item))) + identifiers = [_event_identifier(row) for row in rows] + if len(set(identifiers)) != len(identifiers): + raise ValueError("market event identifiers must be unique within each symbol") + + prediction_by_symbol: dict[str, list[dict[str, Any]]] = defaultdict(list) + for row in prediction_rows: + prediction_by_symbol[str(row["symbol"])].append(row) + probability = _prediction_probability(row) + if not math.isfinite(probability) or not 0.0 <= probability <= 1.0: + raise ValueError("prediction probabilities must be finite and lie in [0, 1]") + unknown_symbols = sorted(set(prediction_by_symbol).difference(by_symbol)) + if unknown_symbols: + raise ValueError(f"predictions reference symbols absent from events: {unknown_symbols}") + + order_rows: list[dict[str, Any]] = [] + fill_rows: list[dict[str, Any]] = [] + position_rows: list[dict[str, Any]] = [] + equity_rows: list[dict[str, Any]] = [] + gross_cash: dict[str, float] = defaultdict(float) + positions: dict[str, float] = defaultdict(float) + fees_by_symbol: dict[str, float] = defaultdict(float) + turnover_by_symbol: dict[str, float] = defaultdict(float) + maximum_inventory_by_symbol: dict[str, float] = defaultdict(float) + final_mid: dict[str, float] = {} + total_fees = 0.0 + maker_fees = 0.0 + taker_fees = 0.0 + turnover_notional = 0.0 + maximum_inventory = 0.0 + forced_liquidation_quantity = 0.0 + unliquidated_quantity = 0.0 + next_order_id = 0 + next_fill_id = 0 + next_equity_observation_id = 0 + + def record_equity(row: dict[str, Any], symbol: str) -> None: + nonlocal next_equity_observation_id + next_equity_observation_id += 1 + gross_equity = gross_cash[symbol] + positions[symbol] * _mid(row) + equity_rows.append( + { + "observation_id": next_equity_observation_id, + "symbol": symbol, + "event_ts_ns": _timestamp(row), + "net_equity": gross_equity - fees_by_symbol[symbol], + } + ) + + def record_fill( + *, + order: dict[str, Any], + row: dict[str, Any], + rows: list[dict[str, Any]], + position_index: int, + price: float, + quantity: float, + liquidity: Literal["maker", "taker"], + queue_ahead_before: float | None, + forced_liquidation: bool = False, + ) -> None: + nonlocal total_fees, maker_fees, taker_fees, turnover_notional + nonlocal maximum_inventory, next_fill_id + symbol = str(order["symbol"]) + side = _object_int(order["side"]) + notional = price * quantity + fee_rate_bps = config.maker_fee_bps if liquidity == "maker" else config.taker_fee_bps + fee = notional * fee_rate_bps / 10_000.0 + gross_cash[symbol] -= side * notional + positions[symbol] += side * quantity + total_fees += fee + turnover_notional += notional + fees_by_symbol[symbol] += fee + turnover_by_symbol[symbol] += notional + if liquidity == "maker": + maker_fees += fee + else: + taker_fees += fee + maximum_inventory = max(maximum_inventory, abs(positions[symbol])) + maximum_inventory_by_symbol[symbol] = max( + maximum_inventory_by_symbol[symbol], abs(positions[symbol]) + ) + + requested_markout_position = position_index + markout_events + markout_available = ( + not forced_liquidation + and requested_markout_position < len(rows) + and _continuity(rows[requested_markout_position]) == _continuity(row) + ) + markout_mid = _mid(rows[requested_markout_position]) if markout_available else None + post_fill_markout_bps = ( + side * (markout_mid - price) / price * 10_000.0 if markout_mid is not None else None + ) + decision_mid = _object_float(order["decision_mid_price"]) + arrival_cost_bps = side * (price - decision_mid) / decision_mid * 10_000.0 + next_fill_id += 1 + fill_rows.append( + { + "fill_id": next_fill_id, + "order_id": order["order_id"], + "sample_id": order["sample_id"], + "symbol": symbol, + "event_id": _event_identifier(row), + "event_ts_ns": _timestamp(row), + "side": side, + "price": price, + "quantity": quantity, + "notional": notional, + "liquidity": liquidity, + "fee": fee, + "queue_ahead_before": queue_ahead_before, + "arrival_cost_bps": arrival_cost_bps, + "post_fill_markout_bps": post_fill_markout_bps, + "adverse_selection_bps": ( + -post_fill_markout_bps if post_fill_markout_bps is not None else None + ), + "requested_markout_events": markout_events, + "markout_available": markout_available, + "forced_liquidation": forced_liquidation, + } + ) + gross_equity = gross_cash[symbol] + positions[symbol] * _mid(row) + position_rows.append( + { + "fill_id": next_fill_id, + "symbol": symbol, + "event_ts_ns": _timestamp(row), + "position_units": positions[symbol], + "gross_cash": gross_cash[symbol], + "mid_price": _mid(row), + "gross_equity": gross_equity, + "symbol_cumulative_fees": fees_by_symbol[symbol], + "net_equity": gross_equity - fees_by_symbol[symbol], + } + ) + record_equity(row, symbol) + + latency_events = config.decision_latency_events + config.order_latency_events + for symbol in sorted(by_symbol): + rows = by_symbol[symbol] + identifier_to_position = {_event_identifier(row): index for index, row in enumerate(rows)} + scheduled: dict[int, list[dict[str, Any]]] = defaultdict(list) + + for prediction in prediction_by_symbol.get(symbol, []): + probability = _prediction_probability(prediction) + if probability >= config.signal_threshold: + side = 1 + elif probability <= 1.0 - config.signal_threshold: + side = -1 + else: + continue + sample_id = _event_identifier(prediction) + decision_position = identifier_to_position.get(sample_id) + if decision_position is None: + raise ValueError(f"prediction sample {sample_id} has no matching {symbol} event") + arrival_position = decision_position + latency_events + next_order_id += 1 + decision_row = rows[decision_position] + order = { + "order_id": next_order_id, + "sample_id": sample_id, + "symbol": symbol, + "decision_event_ts_ns": _timestamp(decision_row), + "decision_position": decision_position, + "decision_continuity_id": _continuity(decision_row), + "arrival_position": arrival_position, + "arrival_event_ts_ns": ( + _timestamp(rows[arrival_position]) if arrival_position < len(rows) else None + ), + "side": side, + "order_type": order_type, + "requested_quantity": config.order_size_units * size_multiplier, + "accepted_quantity": 0.0, + "filled_quantity": 0.0, + "decision_mid_price": _mid(decision_row), + "limit_price": None, + "status": "scheduled" if arrival_position < len(rows) else "expired_before_arrival", + "rejection_reason": None, + } + order_rows.append(order) + if arrival_position < len(rows): + scheduled[arrival_position].append(order) + + active_limits: list[_ActiveLimit] = [] + previous_continuity: str | None = None + for position_index, row in enumerate(rows): + current_continuity = _continuity(row) + if previous_continuity is not None and current_continuity != previous_continuity: + for active in active_limits: + active.order["status"] = ( + "partially_filled_continuity_gap" + if _object_float(active.order["filled_quantity"]) > 0 + else "canceled_continuity_gap" + ) + active_limits.clear() + previous_continuity = current_continuity + + trade_side = _trade_side(row) + trade_quantity = abs(_number(row, "trade_quantity", "quantity", default=0.0)) + trade_price = _number(row, "trade_price", "price", default=_mid(row)) + remaining_trade_quantity = trade_quantity + + # Exchange events at this position execute before newly arriving orders. + for active in list(active_limits): + order = active.order + crosses = ( + _object_int(order["side"]) == 1 + and trade_side < 0 + and trade_price <= _object_float(order["limit_price"]) + ) or ( + _object_int(order["side"]) == -1 + and trade_side > 0 + and trade_price >= _object_float(order["limit_price"]) + ) + if crosses and remaining_trade_quantity > 0: + queue_before = active.queue_ahead + queue_consumed = min(active.queue_ahead, remaining_trade_quantity) + active.queue_ahead -= queue_consumed + remaining_trade_quantity -= queue_consumed + if ( + remaining_trade_quantity > 0 + and _seeded_uniform(seed, order["order_id"], _event_identifier(row)) + <= config.limit_fill_base_probability + ): + inventory_room = ( + config.max_position_units - positions[symbol] + if _object_int(order["side"]) == 1 + else config.max_position_units + positions[symbol] + ) + fill_quantity = min( + active.remaining_quantity, + remaining_trade_quantity, + max(0.0, inventory_room), + ) + if fill_quantity > 0: + record_fill( + order=order, + row=row, + rows=rows, + position_index=position_index, + price=_object_float(order["limit_price"]), + quantity=fill_quantity, + liquidity="maker", + queue_ahead_before=queue_before, + ) + active.remaining_quantity -= fill_quantity + remaining_trade_quantity -= fill_quantity + order["filled_quantity"] = ( + _object_float(order["filled_quantity"]) + fill_quantity + ) + order["status"] = ( + ( + "filled" + if _object_float(order["filled_quantity"]) + >= _object_float(order["requested_quantity"]) - 1e-12 + else "inventory_clipped_filled" + ) + if active.remaining_quantity <= 1e-12 + else "partially_filled" + ) + elif remaining_trade_quantity > 0 and active.queue_ahead <= 1e-12: + # A failed fill draw represents unobserved queue ahead; the + # printed volume cannot also fill another simulated order. + remaining_trade_quantity = 0.0 + if active.remaining_quantity <= 1e-12: + active_limits.remove(active) + continue + if position_index >= active.cancel_effective_position: + order["status"] = ( + "partially_filled_expired" + if _object_float(order["filled_quantity"]) > 0 + else "expired" + ) + active_limits.remove(active) + + for order in scheduled.get(position_index, []): + if _continuity(row) != str(order["decision_continuity_id"]): + order["status"] = "canceled_continuity_gap" + order["rejection_reason"] = "arrival_crossed_continuity_gap" + continue + side = _object_int(order["side"]) + inventory_room = ( + config.max_position_units - positions[symbol] + if side == 1 + else config.max_position_units + positions[symbol] + ) + requested = _object_float(order["requested_quantity"]) + accepted = _round_quantity(min(requested, max(0.0, inventory_room)), row) + order["accepted_quantity"] = accepted + if accepted <= 1e-12: + order["status"] = "rejected" + order["rejection_reason"] = "inventory_limit" + continue + + if order_type == "market": + price = ( + _number(row, "best_ask", "ask_price_1") + if side == 1 + else _number(row, "best_bid", "bid_price_1") + ) + displayed = _displayed_depth(row, side) + fill_quantity = _round_quantity(min(accepted, max(0.0, displayed)), row) + if fill_quantity <= 1e-12: + order["status"] = "canceled_no_liquidity" + continue + depth_ratio = fill_quantity / max(displayed, 1e-12) + slippage_bps = config.slippage_bps_per_unit * depth_ratio + price = _round_price_adversely( + price * (1.0 + side * slippage_bps / 10_000.0), side, row + ) + record_fill( + order=order, + row=row, + rows=rows, + position_index=position_index, + price=price, + quantity=fill_quantity, + liquidity="taker", + queue_ahead_before=None, + ) + order["filled_quantity"] = fill_quantity + order["status"] = ( + "filled" + if fill_quantity >= requested - 1e-12 + else "partially_filled_canceled" + ) + else: + limit_price = ( + _number(row, "best_bid", "bid_price_1") + if side == 1 + else _number(row, "best_ask", "ask_price_1") + ) + order["limit_price"] = limit_price + order["status"] = "working" + active_limits.append( + _ActiveLimit( + order=order, + remaining_quantity=accepted, + queue_ahead=config.queue_ahead_units, + cancel_effective_position=( + position_index + + config.limit_max_age_events + + config.cancel_latency_events + ), + ) + ) + + # Mark open inventory at every replay event, including events with no fill. + record_equity(row, symbol) + + for active in active_limits: + active.order["status"] = ( + "partially_filled_end_of_data" + if _object_float(active.order["filled_quantity"]) > 0 + else "end_of_data" + ) + + final_mid[symbol] = _mid(rows[-1]) + if config.liquidate_at_end and abs(positions[symbol]) > 1e-12: + final_row = rows[-1] + side = -1 if positions[symbol] > 0 else 1 + quantity = abs(positions[symbol]) + displayed = _displayed_depth(final_row, side) + fill_quantity = _round_quantity(min(quantity, max(0.0, displayed)), final_row) + next_order_id += 1 + liquidation_order = { + "order_id": next_order_id, + "sample_id": _event_identifier(final_row), + "symbol": symbol, + "decision_event_ts_ns": _timestamp(final_row), + "decision_position": len(rows) - 1, + "decision_continuity_id": _continuity(final_row), + "arrival_position": len(rows) - 1, + "arrival_event_ts_ns": _timestamp(final_row), + "side": side, + "order_type": "market", + "requested_quantity": quantity, + "accepted_quantity": fill_quantity, + "filled_quantity": fill_quantity, + "decision_mid_price": _mid(final_row), + "limit_price": None, + "status": "forced_liquidation", + "rejection_reason": None, + } + order_rows.append(liquidation_order) + if fill_quantity > 0: + price = ( + _number(final_row, "best_bid", "bid_price_1") + if side == -1 + else _number(final_row, "best_ask", "ask_price_1") + ) + liquidation_depth_ratio = fill_quantity / max(displayed, 1e-12) + liquidation_slippage_bps = config.slippage_bps_per_unit * liquidation_depth_ratio + price = _round_price_adversely( + price * (1.0 + side * liquidation_slippage_bps / 10_000.0), + side, + final_row, + ) + record_fill( + order=liquidation_order, + row=final_row, + rows=rows, + position_index=len(rows) - 1, + price=price, + quantity=fill_quantity, + liquidity="taker", + queue_ahead_before=None, + forced_liquidation=True, + ) + forced_liquidation_quantity += fill_quantity + unliquidated_quantity += abs(positions[symbol]) + + gross_pnl_by_symbol = { + symbol: gross_cash[symbol] + positions[symbol] * final_mid[symbol] for symbol in final_mid + } + gross_pnl = sum(gross_pnl_by_symbol.values()) + net_pnl = gross_pnl - total_fees + maximum_drawdown = _portfolio_max_drawdown(equity_rows) + requested_quantity = sum( + _object_float(order["requested_quantity"]) + for order in order_rows + if order["status"] != "forced_liquidation" + ) + accepted_quantity = sum( + _object_float(order["accepted_quantity"]) + for order in order_rows + if order["status"] != "forced_liquidation" + ) + filled_quantity = sum( + _object_float(order["filled_quantity"]) + for order in order_rows + if order["status"] != "forced_liquidation" + ) + partially_filled = sum( + 1 for order in order_rows if str(order["status"]).startswith("partially_filled") + ) + strategy_orders = sum(1 for order in order_rows if order["status"] != "forced_liquidation") + strategy_fills = [fill for fill in fill_rows if not bool(fill["forced_liquidation"])] + available_markouts = [ + fill for fill in strategy_fills if fill["post_fill_markout_bps"] is not None + ] + mean_markout = ( + float( + np.average( + [_object_float(fill["post_fill_markout_bps"]) for fill in available_markouts], + weights=[_object_float(fill["notional"]) for fill in available_markouts], + ) + ) + if available_markouts + else None + ) + mean_arrival_cost = ( + float( + np.average( + [_object_float(fill["arrival_cost_bps"]) for fill in strategy_fills], + weights=[_object_float(fill["notional"]) for fill in strategy_fills], + ) + ) + if strategy_fills + else None + ) + unliquidated_by_symbol = { + symbol: abs(position) for symbol, position in positions.items() if abs(position) > 1e-12 + } + net_pnl_by_symbol = { + symbol: gross_pnl_by_symbol[symbol] - fees_by_symbol[symbol] + for symbol in gross_pnl_by_symbol + } + metrics: dict[str, Any] = { + "order_type": order_type, + "size_multiplier": size_multiplier, + "strategy_orders": strategy_orders, + "strategy_fills": len(strategy_fills), + "forced_liquidation_fills": len(fill_rows) - len(strategy_fills), + "requested_quantity": requested_quantity, + "accepted_quantity": accepted_quantity, + "filled_quantity": filled_quantity, + "fill_ratio": filled_quantity / accepted_quantity if accepted_quantity else None, + "fill_ratio_requested": ( + filled_quantity / requested_quantity if requested_quantity else None + ), + "partial_fill_order_ratio": partially_filled / strategy_orders if strategy_orders else None, + "gross_pnl": gross_pnl, + "marked_gross_pnl": gross_pnl, + "gross_pnl_by_symbol": gross_pnl_by_symbol, + "maker_fees": maker_fees, + "taker_fees": taker_fees, + "total_fees": total_fees, + "net_pnl": net_pnl, + "marked_net_pnl": net_pnl, + "net_pnl_by_symbol": net_pnl_by_symbol, + "maximum_drawdown": maximum_drawdown, + "maximum_drawdown_bps_of_turnover": ( + maximum_drawdown / turnover_notional * 10_000.0 if turnover_notional else None + ), + "turnover_notional": turnover_notional, + "turnover_notional_by_symbol": dict(turnover_by_symbol), + "gross_edge_bps": gross_pnl / turnover_notional * 10_000.0 if turnover_notional else None, + "net_edge_bps": net_pnl / turnover_notional * 10_000.0 if turnover_notional else None, + "mean_arrival_cost_bps": mean_arrival_cost, + "mean_post_fill_markout_bps": mean_markout, + "mean_adverse_selection_bps": -mean_markout if mean_markout is not None else None, + "maximum_absolute_inventory": maximum_inventory, + "maximum_absolute_inventory_by_symbol": dict(maximum_inventory_by_symbol), + "forced_liquidation_quantity": forced_liquidation_quantity, + "unliquidated_quantity": unliquidated_quantity, + "unliquidated_quantity_by_symbol": unliquidated_by_symbol, + "unliquidated_valuation": ( + "final_mid_mark_not_realized" if unliquidated_by_symbol else "none" + ), + } + assumptions: dict[str, Any] = { + "replay_is_exogenous": True, + "live_trading": False, + "decision_latency_events": config.decision_latency_events, + "order_latency_events": config.order_latency_events, + "maker_fee_bps": config.maker_fee_bps, + "taker_fee_bps": config.taker_fee_bps, + "signal_threshold": config.signal_threshold, + "base_order_size_units": config.order_size_units, + "scenario_size_multiplier": size_multiplier, + "half_spread_bps_fallback": config.half_spread_bps, + "slippage_bps_per_unit_of_displayed_depth": config.slippage_bps_per_unit, + "spread_source": "observed top of book; configured half-spread fallback is not used", + "market_depth": "L1 only; residual size is canceled rather than extrapolated", + "limit_fill_model": ( + "opposing printed volume depletes a fixed queue-ahead proxy; eligible residual volume " + "fills with a seeded Bernoulli probability" + ), + "limit_fill_base_probability": config.limit_fill_base_probability, + "queue_ahead_units": config.queue_ahead_units, + "limit_max_age_events": config.limit_max_age_events, + "cancel_latency_events": config.cancel_latency_events, + "inventory_limit_units_per_symbol": config.max_position_units, + "end_liquidation": config.liquidate_at_end, + "capacity_multipliers": list(config.capacity_multipliers), + "markout_policy": "censored at end of data or continuity boundary; never shortened", + "residual_inventory_valuation": "final midpoint mark, explicitly unrealized", + "multi_instrument_units": "quantity and inventory maps are reported per symbol", + } + + orders_frame = pl.DataFrame(order_rows) if order_rows else _empty_frame({"order_id": pl.Int64}) + fills_frame = pl.DataFrame(fill_rows) if fill_rows else _empty_frame({"fill_id": pl.Int64}) + positions_frame = ( + pl.DataFrame(position_rows).sort(["event_ts_ns", "symbol", "fill_id"]) + if position_rows + else _empty_frame({"fill_id": pl.Int64, "position_units": pl.Float64}) + ) + return SimulationResult( + orders=orders_frame, + fills=fills_frame, + positions=positions_frame, + metrics=metrics, + assumptions=assumptions, + ) + + +def run_execution_sensitivity( + events: pl.DataFrame, + predictions: pl.DataFrame, + config: ExecutionConfig, + *, + seed: int, + markout_events: int, +) -> pl.DataFrame: + """Evaluate market/limit execution over the declared capacity grid.""" + rows: list[dict[str, Any]] = [] + for order_type in cast(tuple[OrderType, ...], ("market", "limit")): + for multiplier in config.capacity_multipliers: + result = simulate_predictions( + events, + predictions, + config, + order_type=order_type, + size_multiplier=multiplier, + seed=seed, + markout_events=markout_events, + ) + rows.append(result.metrics) + return pl.DataFrame(rows) diff --git a/Microstructure/src/microstructure/exploratory_trade_study.py b/Microstructure/src/microstructure/exploratory_trade_study.py new file mode 100644 index 0000000000000000000000000000000000000000..79f446babc102087705c99293d2426784a30d84f --- /dev/null +++ b/Microstructure/src/microstructure/exploratory_trade_study.py @@ -0,0 +1,858 @@ +"""One explicit four-day public aggregate-trade exploratory study. + +This producer is deliberately separate from the frozen M8 trade and live-L2 +authorities. It reuses their bounded archive, normalization, causal-feature, +and numeric fitted-state primitives without weakening either frozen contract. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import shutil +import tempfile +import tomllib +from collections.abc import Mapping, Sequence +from dataclasses import asdict +from datetime import date +from pathlib import Path +from typing import Any, cast + +import polars as pl + +from microstructure.config import FeatureConfig, ModelConfig +from microstructure.data.binance import BinancePublicClient, SymbolMetadata +from microstructure.data.binance_archive import ( + AcquiredDailyArchive, + ArchiveDownloadLimits, + BinanceArchiveClient, + DailyArchiveRequest, +) +from microstructure.data.evidence_budget import RetainedEvidenceBudget +from microstructure.m8_config import ( + M8Claims, + M8Features, + M8Models, + M8Period, + M8Quality, + M8Study, + M8StudyConfig, +) +from microstructure.m8_manifest import M8ArchiveEntry, M8SymbolMetadata +from microstructure.m8_normalization import normalize_m8_archive +from microstructure.provenance import ( + git_source_tree_sha256, + read_json, + sha256_file, + strict_git_state, + utc_now_iso, +) +from microstructure.research.multidate import ( + AnalysisLock, + LockedSelection, + evaluate_locked_multidate_tests, + select_multidate_model, +) +from microstructure.research.trade_only import ( + build_trade_only_research_frame, + validate_trade_only_temporal_contract, +) + +SCHEMA_VERSION = "exploratory-aggtrades-study-v1" +EVIDENCE_TIER = "PUBLIC_ARCHIVE_EXPLORATORY" +EXPECTED_DATES = ( + ("2026-08-05", "train"), + ("2026-08-06", "validation"), + ("2026-08-07", "primary_test"), + ("2026-08-08", "replication_test"), +) +EXPECTED_SYMBOLS = ("BTCUSDT", "ETHUSDT") +PROTOCOL_RELATIVE_PATH = "docs/EXPLORATORY_AGGTRADES_2026_08_05_08.md" +SUCCESS_BYTES = b"complete\n" + + +class ExploratoryStudyError(RuntimeError): + """Raised when the exploratory producer cannot preserve its authority.""" + + +def _canonical_bytes(value: object) -> bytes: + return json.dumps( + value, + sort_keys=True, + separators=(",", ":"), + allow_nan=False, + ).encode("utf-8") + + +def _sha_bytes(value: bytes) -> str: + return hashlib.sha256(value).hexdigest() + + +def _atomic_write(path: Path, content: bytes) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + descriptor, raw_temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent) + temporary = Path(raw_temporary) + try: + with os.fdopen(descriptor, "wb") as handle: + handle.write(content) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, path) + parent = os.open(path.parent, os.O_RDONLY) + try: + os.fsync(parent) + finally: + os.close(parent) + finally: + temporary.unlink(missing_ok=True) + + +def _write_json(path: Path, value: object) -> None: + _atomic_write(path, _canonical_bytes(value) + b"\n") + + +def _mapping(value: object, label: str) -> Mapping[str, Any]: + if not isinstance(value, Mapping) or not all(isinstance(key, str) for key in value): + raise ExploratoryStudyError(f"{label} must be a string-keyed table") + return cast(Mapping[str, Any], value) + + +def _exact_keys(value: Mapping[str, Any], expected: set[str], label: str) -> None: + if set(value) != expected: + raise ExploratoryStudyError(f"{label} keys differ from the exploratory contract") + + +def _load_config(path: Path) -> M8StudyConfig: + source_path = path.resolve() + source = source_path.read_bytes() + try: + payload = tomllib.loads(source.decode("utf-8")) + except (UnicodeDecodeError, tomllib.TOMLDecodeError) as error: + raise ExploratoryStudyError("cannot parse exploratory configuration") from error + root = _mapping(payload, "configuration") + _exact_keys(root, {"study", "periods", "features", "models", "quality", "claims"}, "config") + study_raw = _mapping(root["study"], "study") + periods_raw = root["periods"] + features_raw = _mapping(root["features"], "features") + models_raw = _mapping(root["models"], "models") + quality_raw = _mapping(root["quality"], "quality") + claims_raw = _mapping(root["claims"], "claims") + if not isinstance(periods_raw, list) or len(periods_raw) != 4: + raise ExploratoryStudyError("periods must declare exactly four dates") + + study = M8Study( + name=str(study_raw["name"]), + protocol_version=str(study_raw["protocol_version"]), + evidence_tier=str(study_raw["evidence_tier"]), + seed=int(study_raw["seed"]), + source=str(study_raw["source"]), + symbols=tuple(str(value) for value in cast(Sequence[object], study_raw["symbols"])), + selection_metric=str(study_raw["selection_metric"]), + target=str(study_raw["target"]), + label_horizon_events=int(study_raw["label_horizon_events"]), + calibration_fraction=float(study_raw["calibration_fraction"]), + bootstrap_samples=int(study_raw["bootstrap_samples"]), + bootstrap_block_events=int(study_raw["bootstrap_block_events"]), + feature_stability_bins=int(study_raw["feature_stability_bins"]), + max_archive_compressed_bytes=int(study_raw["max_archive_compressed_bytes"]), + max_archive_uncompressed_bytes=int(study_raw["max_archive_uncompressed_bytes"]), + max_total_download_bytes=int(study_raw["max_total_download_bytes"]), + ) + periods = tuple( + M8Period( + date=date.fromisoformat(str(_mapping(value, "period")["date"])), + role=cast(Any, str(_mapping(value, "period")["role"])), + ) + for value in periods_raw + ) + features = M8Features( + trade_windows=tuple( + int(cast(Any, value)) for value in cast(Sequence[object], features_raw["trade_windows"]) + ), + volatility_window=int(features_raw["volatility_window"]), + intensity_window=int(features_raw["intensity_window"]), + large_trade_quantile=float(features_raw["large_trade_quantile"]), + ) + models = M8Models( + logistic_c_values=tuple( + float(cast(Any, value)) + for value in cast(Sequence[object], models_raw["logistic_c_values"]) + ), + tree_max_depth_values=tuple( + int(cast(Any, value)) + for value in cast(Sequence[object], models_raw["tree_max_depth_values"]) + ), + tree_min_samples_leaf=int(models_raw["tree_min_samples_leaf"]), + ) + quality = M8Quality( + fail_on_error=bool(quality_raw["fail_on_error"]), + require_complete_daily_archive=bool(quality_raw["require_complete_daily_archive"]), + require_contiguous_trade_ids_within_symbol_date=bool( + quality_raw["require_contiguous_trade_ids_within_symbol_date"] + ), + require_nondecreasing_event_time=bool(quality_raw["require_nondecreasing_event_time"]), + allow_quality_warnings=bool(quality_raw["allow_quality_warnings"]), + ) + claims = M8Claims( + allow_p_values=bool(claims_raw["allow_p_values"]), + allow_significance_claim=bool(claims_raw["allow_significance_claim"]), + allow_cross_instrument_pooling=bool(claims_raw["allow_cross_instrument_pooling"]), + allow_execution_claim=bool(claims_raw["allow_execution_claim"]), + allow_profitability_claim=bool(claims_raw["allow_profitability_claim"]), + ) + config = M8StudyConfig( + path=source_path, + source_sha256=_sha_bytes(source), + study=study, + periods=periods, + features=features, + models=models, + quality=quality, + claims=claims, + ) + observed_dates = tuple((item.date.isoformat(), item.role) for item in config.periods) + if ( + config.study.name != "binance-aggtrades-2026-08-05-08-exploratory" + or config.study.protocol_version != "1.0.0" + or config.study.evidence_tier != EVIDENCE_TIER + or config.study.source != "binance_spot_daily_aggtrades_archive" + or config.study.symbols != EXPECTED_SYMBOLS + or observed_dates != EXPECTED_DATES + or config.study.selection_metric != "log_loss" + or config.study.target != "future_trade_up" + or config.study.label_horizon_events != 20 + or not config.quality.fail_on_error + or not config.quality.allow_quality_warnings + or any(asdict(config.claims).values()) + ): + raise ExploratoryStudyError("configuration differs from the declared exploratory study") + if config.study.max_total_download_bytes < 1: + raise ExploratoryStudyError("total retained-evidence budget must be positive") + return config + + +def _protocol_path(config: M8StudyConfig) -> Path: + result = config.path.parent.parent / PROTOCOL_RELATIVE_PATH + if not result.is_file() or result.is_symlink(): + raise ExploratoryStudyError("exploratory protocol document is missing or symbolic") + return result + + +def _metadata_authority(value: SymbolMetadata) -> M8SymbolMetadata: + sidecar = _mapping(read_json(value.source_manifest_path), "exchangeInfo sidecar") + source_uri = sidecar.get("source_uri") + if type(source_uri) is not str or not source_uri: + raise ExploratoryStudyError("exchangeInfo sidecar lacks its source URI") + return M8SymbolMetadata( + symbol=value.symbol, + status=value.status, + tick_size=value.tick_size, + lot_size=value.lot_size, + observed_ts_ns=value.observed_ts_ns, + raw_path=value.source_path.resolve(), + raw_sha256=sha256_file(value.source_path), + raw_bytes=value.source_path.stat().st_size, + source_uri=source_uri, + source_manifest_path=value.source_manifest_path.resolve(), + source_manifest_sha256=sha256_file(value.source_manifest_path), + source_manifest_bytes=value.source_manifest_path.stat().st_size, + ) + + +def _feature_config(config: M8StudyConfig) -> FeatureConfig: + return FeatureConfig( + trade_windows=config.features.trade_windows, + volatility_window=config.features.volatility_window, + intensity_window=config.features.intensity_window, + label_horizon_events=config.study.label_horizon_events, + large_trade_quantile=config.features.large_trade_quantile, + ) + + +def _model_config(config: M8StudyConfig) -> ModelConfig: + return ModelConfig( + selection_metric=config.study.selection_metric, + logistic_c_values=config.models.logistic_c_values, + tree_max_depth_values=config.models.tree_max_depth_values, + tree_min_samples_leaf=config.models.tree_min_samples_leaf, + ) + + +def _feature_columns(config: M8StudyConfig) -> tuple[str, ...]: + columns = ["log_trade_return_1"] + for window in config.features.trade_windows: + columns.extend( + ( + f"signed_trade_volume_w{window}", + f"trade_volume_w{window}", + f"trade_imbalance_w{window}", + ) + ) + columns.extend( + ( + f"trade_count_w{config.features.intensity_window}", + f"trade_intensity_w{config.features.intensity_window}", + f"realized_volatility_w{config.features.volatility_window}", + ) + ) + return tuple(dict.fromkeys(columns)) + + +def _evaluation_columns(config: M8StudyConfig) -> tuple[str, ...]: + return ( + "study_date", + "study_role", + "symbol", + "decision_ts_ns", + "decision_sequence", + "decision_trade_id", + "continuity_id", + "feature_continuity_id", + "label_continuity_id", + "max_feature_source_ts_ns", + "max_feature_source_trade_id", + "label_start_ts_ns", + "label_start_trade_id", + "label_information_end_ts_ns", + "label_information_end_trade_id", + "feature_ready", + "right_censored", + config.study.target, + *_feature_columns(config), + ) + + +def _entry_payload(entry: M8ArchiveEntry, root: Path) -> dict[str, object]: + return { + "symbol": entry.symbol, + "date": entry.date.isoformat(), + "role": entry.role, + "rows": entry.rows, + "first_trade_id": entry.first_trade_id, + "last_trade_id": entry.last_trade_id, + "observed_start_ns": entry.observed_start_ns, + "observed_end_inclusive_ns": entry.observed_end_inclusive_ns, + "quality_errors": entry.quality_errors, + "quality_warnings": entry.quality_warnings, + "raw_zip": { + "path": str(entry.raw_zip_path.relative_to(root)), + "sha256": entry.raw_zip_sha256, + "bytes": entry.raw_zip_bytes, + }, + "official_checksum": { + "path": str(entry.raw_checksum_path.relative_to(root)), + "sha256": entry.raw_checksum_sha256, + "bytes": entry.raw_checksum_bytes, + }, + "normalized_manifest": { + "path": str(entry.normalized_dataset_manifest_path.relative_to(root)), + "sha256": entry.normalized_dataset_manifest_sha256, + "bytes": entry.normalized_dataset_manifest_bytes, + }, + "parts": [ + { + "path": str(item.data_path.relative_to(root)), + "sha256": item.data_sha256, + "bytes": item.data_bytes, + "rows": item.rows, + } + for item in entry.normalized_parts + ], + "quality_report": { + "path": str(entry.quality_report_path.relative_to(root)), + "sha256": entry.quality_report_sha256, + "bytes": entry.quality_report_bytes, + }, + "quality_findings": { + "path": str(entry.quality_findings_path.relative_to(root)), + "sha256": entry.quality_findings_sha256, + "bytes": entry.quality_findings_bytes, + }, + } + + +def _build_evaluation_frame( + entry: M8ArchiveEntry, + config: M8StudyConfig, + data_root: Path, +) -> Path: + paths = [item.data_path for item in entry.normalized_parts] + frame = pl.read_parquet(paths, rechunk=False) + research = build_trade_only_research_frame(frame, _feature_config(config)).with_columns( + pl.lit(entry.date.isoformat()).alias("study_date"), + pl.lit(entry.role).alias("study_role"), + ) + validate_trade_only_temporal_contract(research) + result = research.select(_evaluation_columns(config)) + output = data_root / "derived" / "research" / entry.symbol / entry.date.isoformat() + output.mkdir(parents=True, exist_ok=True) + destination = output / "evaluation.parquet" + result.write_parquet(destination, compression="zstd", statistics=True) + del frame, research, result + return destination + + +def _source_authority(project_root: Path) -> dict[str, object]: + state = strict_git_state(project_root) + if state.dirty: + raise ExploratoryStudyError("exploratory producer requires a clean committed source") + return { + "commit": state.commit, + "dirty": False, + "source_tree_sha256": git_source_tree_sha256(project_root), + } + + +def _raw_manifest( + config: M8StudyConfig, + metadata: Mapping[str, M8SymbolMetadata], + archives: Mapping[tuple[str, str], AcquiredDailyArchive], + data_root: Path, +) -> tuple[Path, str]: + raw_root = data_root / "raw" + payload = { + "schema_version": "exploratory-aggtrades-raw-v1", + "config_sha256": config.hash, + "config_source_sha256": config.source_sha256, + "protocol_sha256": sha256_file(_protocol_path(config)), + "csv_members_opened": False, + "metadata": [ + { + "symbol": symbol, + "status": item.status, + "tick_size": str(item.tick_size), + "lot_size": str(item.lot_size), + "path": str(item.raw_path.relative_to(raw_root)), + "sha256": item.raw_sha256, + "bytes": item.raw_bytes, + "sidecar_path": str(item.source_manifest_path.relative_to(raw_root)), + "sidecar_sha256": item.source_manifest_sha256, + "sidecar_bytes": item.source_manifest_bytes, + } + for symbol, item in sorted(metadata.items()) + ], + "archives": [ + { + "symbol": symbol, + "date": day, + "role": next(item.role for item in config.periods if item.date.isoformat() == day), + "zip_path": str(value.archive_artifact.path.relative_to(raw_root)), + "zip_sha256": value.archive_artifact.sha256, + "zip_bytes": value.archive_artifact.bytes, + "zip_sidecar_path": str(value.archive_artifact.manifest_path.relative_to(raw_root)), + "zip_sidecar_sha256": value.archive_artifact.manifest_sha256, + "checksum_path": str(value.checksum_artifact.path.relative_to(raw_root)), + "checksum_sha256": value.checksum_artifact.sha256, + "checksum_bytes": value.checksum_artifact.bytes, + "checksum_sidecar_path": str( + value.checksum_artifact.manifest_path.relative_to(raw_root) + ), + "checksum_sidecar_sha256": value.checksum_artifact.manifest_sha256, + "official_zip_sha256": value.upstream_sha256, + "declared_uncompressed_bytes": value.declared_uncompressed_bytes, + } + for (symbol, day), value in sorted(archives.items()) + ], + } + destination = data_root / "raw_manifest.json" + if destination.exists(): + raise ExploratoryStudyError("raw manifest target already exists") + _write_json(destination, payload) + return destination, sha256_file(destination) + + +def _persist_locks( + selections: Mapping[str, LockedSelection], + stage: Path, + *, + config: M8StudyConfig, + raw_manifest_sha256: str, + source: Mapping[str, object], +) -> tuple[Path, str]: + child_claims: dict[str, dict[str, object]] = {} + for symbol, selection in sorted(selections.items()): + child = stage / "analysis" / "locks" / f"{symbol}.selection.json" + _atomic_write(child, selection.lock.payload_json.encode("utf-8") + b"\n") + child_claims[symbol] = { + "path": str(child.relative_to(stage)), + "sha256": sha256_file(child), + "selection_lock_sha256": selection.lock.sha256, + "fitted_state_sha256": selection.fitted_state.sha256, + "selected_model": selection.selected_model, + } + comparison = stage / "models" / f"{symbol}.validation_candidates.parquet" + comparison.parent.mkdir(parents=True, exist_ok=True) + selection.validation_comparison.write_parquet(comparison, compression="zstd") + payload = { + "schema_version": "exploratory-aggtrades-analysis-lock-v1", + "created_at_utc": utc_now_iso(), + "config_sha256": config.hash, + "config_source_sha256": config.source_sha256, + "protocol_sha256": sha256_file(_protocol_path(config)), + "raw_manifest_sha256": raw_manifest_sha256, + "source": dict(source), + "children": child_claims, + "development_dates": ["2026-08-05", "2026-08-06"], + "heldout_dates": ["2026-08-07", "2026-08-08"], + "heldout_csv_members_opened_before_lock": False, + } + aggregate = stage / "analysis" / "analysis_lock.json" + _write_json(aggregate, payload) + digest = sha256_file(aggregate) + _atomic_write(aggregate.with_suffix(".sha256"), f"{digest} {aggregate.name}\n".encode()) + return aggregate, digest + + +def _lock_guard( + *, + aggregate_path: Path, + aggregate_sha256: str, + config: M8StudyConfig, + project_root: Path, + source: Mapping[str, object], +) -> None: + if sha256_file(config.path) != config.source_sha256: + raise ExploratoryStudyError("configuration changed before held-out member open") + if sha256_file(_protocol_path(config)) != cast( + str, read_json(aggregate_path)["protocol_sha256"] + ): + raise ExploratoryStudyError("protocol changed before held-out member open") + if sha256_file(aggregate_path) != aggregate_sha256: + raise ExploratoryStudyError("aggregate lock changed before held-out member open") + if _source_authority(project_root) != dict(source): + raise ExploratoryStudyError("source identity changed before held-out member open") + aggregate = _mapping(read_json(aggregate_path), "analysis lock") + children = _mapping(aggregate["children"], "analysis lock children") + for claim in children.values(): + child = _mapping(claim, "child lock claim") + path = aggregate_path.parents[1] / str(child["path"]) + if sha256_file(path) != child["sha256"]: + raise ExploratoryStudyError("child lock changed before held-out member open") + + +def _checksums(root: Path) -> tuple[Path, str]: + paths = sorted( + item + for item in root.rglob("*") + if item.is_file() and item.name not in {"CHECKSUMS.sha256", "_SUCCESS"} + ) + lines = [f"{sha256_file(item)} {item.relative_to(root).as_posix()}" for item in paths] + destination = root / "CHECKSUMS.sha256" + _atomic_write(destination, ("\n".join(lines) + "\n").encode("utf-8")) + return destination, sha256_file(destination) + + +def verify_exploratory_run(run_dir: str | Path) -> dict[str, object]: + root = Path(run_dir).resolve() + marker = root / "_SUCCESS" + if marker.read_bytes() != SUCCESS_BYTES: + raise ExploratoryStudyError("run success marker is missing or invalid") + checksums = root / "CHECKSUMS.sha256" + for line in checksums.read_text(encoding="utf-8").splitlines(): + digest, relative = line.split(" ", 1) + path = root / relative + if not path.is_file() or path.is_symlink() or sha256_file(path) != digest: + raise ExploratoryStudyError(f"run artifact failed checksum verification: {relative}") + evidence = _mapping(read_json(root / "data" / "input_evidence.json"), "input evidence") + for item in cast(Sequence[object], evidence["files"]): + claim = _mapping(item, "input evidence file") + path = Path(str(claim["absolute_path"])) + if path.stat().st_size != int(claim["bytes"]) or sha256_file(path) != claim["sha256"]: + raise ExploratoryStudyError(f"external input changed: {path}") + manifest = root / "run_manifest.json" + return { + "status": "COMPLETE", + "integrity": "verified", + "run_dir": str(root), + "run_manifest": str(manifest), + "run_manifest_sha256": sha256_file(manifest), + "checksums": str(checksums), + "checksums_sha256": sha256_file(checksums), + } + + +def run_exploratory_study( + config_path: str | Path, + data_root: str | Path, + run_dir: str | Path, +) -> dict[str, object]: + config = _load_config(Path(config_path)) + project_root = config.path.parent.parent.resolve() + source = _source_authority(project_root) + destination_data = Path(data_root).resolve() + destination_run = Path(run_dir).resolve() + if destination_run.exists(): + raise ExploratoryStudyError("run target already exists; immutable runs are not overwritten") + if (destination_data / "derived").exists() or (destination_data / "raw_manifest.json").exists(): + raise ExploratoryStudyError("derived/input-manifest target already exists") + destination_data.mkdir(parents=True, exist_ok=True) + raw_root = destination_data / "raw" + budget = RetainedEvidenceBudget(raw_root, config.study.max_total_download_bytes) + metadata_client = BinancePublicClient(retained_evidence_budget=budget) + archive_client = BinanceArchiveClient(retained_evidence_budget=budget) + metadata: dict[str, M8SymbolMetadata] = {} + raw_metadata: dict[str, SymbolMetadata] = {} + for symbol in config.study.symbols: + observed = metadata_client.fetch_exchange_info(symbol=symbol, raw_root=raw_root) + raw_metadata[symbol] = observed + metadata[symbol] = _metadata_authority(observed) + limits = ArchiveDownloadLimits( + max_compressed_bytes=config.study.max_archive_compressed_bytes, + max_uncompressed_bytes=config.study.max_archive_uncompressed_bytes, + ) + archives: dict[tuple[str, str], AcquiredDailyArchive] = {} + for period in config.periods: + for symbol in config.study.symbols: + item = raw_metadata[symbol] + archives[(symbol, period.date.isoformat())] = archive_client.acquire( + DailyArchiveRequest( + symbol=symbol, + date=period.date, + tick_size=item.tick_size, + lot_size=item.lot_size, + ), + raw_root=raw_root, + limits=limits, + ) + raw_manifest_path, raw_manifest_sha256 = _raw_manifest( + config, metadata, archives, destination_data + ) + if sha256_file(config.path) != config.source_sha256: + raise ExploratoryStudyError("configuration changed during raw acquisition") + + stage = destination_run.parent / f".{destination_run.name}.staging-{os.getpid()}" + if stage.exists(): + raise ExploratoryStudyError("run staging directory already exists") + stage.mkdir(parents=True) + normalized: dict[tuple[str, str], M8ArchiveEntry] = {} + evaluation_paths: dict[tuple[str, str], Path] = {} + selections: dict[str, LockedSelection] = {} + try: + development = config.periods[:2] + heldout = config.periods[2:] + for period in development: + for symbol in config.study.symbols: + normalized_result = normalize_m8_archive( + config, + period, + metadata[symbol], + archives[(symbol, period.date.isoformat())], + raw_root, + output_root=destination_data / "derived", + ) + normalized[(symbol, period.date.isoformat())] = normalized_result.entry + evaluation_paths[(symbol, period.date.isoformat())] = _build_evaluation_frame( + normalized_result.entry, config, destination_data + ) + for symbol_index, symbol in enumerate(config.study.symbols): + frames = [ + pl.read_parquet(evaluation_paths[(symbol, period.date.isoformat())]) + for period in development + ] + selections[symbol] = select_multidate_model( + frames, + _model_config(config), + feature_columns=_feature_columns(config), + declared_test_dates=[item.date.isoformat() for item in heldout], + seed=config.study.seed + symbol_index, + calibration_bins=config.study.feature_stability_bins, + target=config.study.target, + calibration_fraction=config.study.calibration_fraction, + bootstrap_draws=config.study.bootstrap_samples, + block_width_events=config.study.bootstrap_block_events, + ) + del frames + aggregate_path, aggregate_sha256 = _persist_locks( + selections, + stage, + config=config, + raw_manifest_sha256=raw_manifest_sha256, + source=source, + ) + for period in heldout: + for symbol in config.study.symbols: + normalized_result = normalize_m8_archive( + config, + period, + metadata[symbol], + archives[(symbol, period.date.isoformat())], + raw_root, + output_root=destination_data / "derived", + before_member_open=lambda: _lock_guard( + aggregate_path=aggregate_path, + aggregate_sha256=aggregate_sha256, + config=config, + project_root=project_root, + source=source, + ), + ) + normalized[(symbol, period.date.isoformat())] = normalized_result.entry + evaluation_paths[(symbol, period.date.isoformat())] = _build_evaluation_frame( + normalized_result.entry, config, destination_data + ) + + summaries: dict[str, object] = {} + for symbol in config.study.symbols: + development_frames = [ + pl.read_parquet(evaluation_paths[(symbol, period.date.isoformat())]) + for period in development + ] + test_frames = [ + pl.read_parquet(evaluation_paths[(symbol, period.date.isoformat())]) + for period in heldout + ] + locked = AnalysisLock.restore( + selections[symbol].lock.payload_json, + selections[symbol].lock.sha256, + ) + evaluation_result = evaluate_locked_multidate_tests( + development_frames, test_frames, locked + ) + model_root = stage / "models" / symbol + metric_root = stage / "metrics" / symbol + model_root.mkdir(parents=True, exist_ok=True) + metric_root.mkdir(parents=True, exist_ok=True) + evaluation_result.predictions.write_parquet( + model_root / "selected_and_prior_predictions.parquet", compression="zstd" + ) + evaluation_result.paired_log_loss.per_date.write_parquet( + metric_root / "paired_log_loss_by_date.parquet", compression="zstd" + ) + evaluation_result.feature_stability.write_parquet( + metric_root / "feature_stability.parquet", compression="zstd" + ) + aggregate = evaluation_result.paired_log_loss.aggregate + summaries[symbol] = { + "selected_model": evaluation_result.selected_model, + "selection_lock_sha256": evaluation_result.lock_sha256, + "replication_status": evaluation_result.paired_log_loss.replication_status, + "equal_date_selected_minus_prior_log_loss": { + "point_estimate": aggregate.point_estimate, + "ci_low": aggregate.lower, + "ci_high": aggregate.upper, + "bootstrap_samples": aggregate.n_bootstrap, + "blocks": aggregate.n_blocks, + "status": aggregate.status, + }, + "per_date": evaluation_result.paired_log_loss.per_date.to_dicts(), + } + del development_frames, test_frames, evaluation_result + + evidence_files: list[dict[str, object]] = [] + for path in sorted( + item for item in destination_data.rglob("*") if item.is_file() and not item.is_symlink() + ): + evidence_files.append( + { + "absolute_path": str(path), + "sha256": sha256_file(path), + "bytes": path.stat().st_size, + } + ) + _write_json( + stage / "data" / "input_evidence.json", + { + "raw_manifest": str(raw_manifest_path), + "raw_manifest_sha256": raw_manifest_sha256, + "files": evidence_files, + }, + ) + archive_rows = [ + _entry_payload(normalized[(symbol, period.date.isoformat())], destination_data) + for period in config.periods + for symbol in config.study.symbols + ] + _write_json(stage / "metrics" / "exploratory_summary.json", summaries) + _write_json( + stage / "run_manifest.json", + { + "schema_version": SCHEMA_VERSION, + "status": "COMPLETE", + "evidence_tier": EVIDENCE_TIER, + "evidence_scope": "trade_only_complete_public_daily_archives_retrospective", + "generated_at_utc": utc_now_iso(), + "config": config.public_dict(), + "protocol": { + "path": PROTOCOL_RELATIVE_PATH, + "sha256": sha256_file(_protocol_path(config)), + }, + "source": source, + "raw_manifest_sha256": raw_manifest_sha256, + "analysis_lock_sha256": aggregate_sha256, + "archive_evidence": archive_rows, + "symbol_results": summaries, + "claims": { + "p_values_computed": False, + "significance_claim_authorized": False, + "cross_instrument_pooling": False, + "execution": "NOT_RUN", + "profitability_claim_authorized": False, + "live_l2_claim_authorized": False, + }, + }, + ) + report_lines = [ + "# August 5-8 aggregate-trade exploratory result", + "", + "**PUBLIC_ARCHIVE_EXPLORATORY — retrospective trade-only evidence.**", + "", + "This result contains no L2, execution, profitability, capacity, or significance claim.", + "", + ] + for symbol in config.study.symbols: + summary = cast(Mapping[str, Any], summaries[symbol]) + report_aggregate = cast( + Mapping[str, Any], summary["equal_date_selected_minus_prior_log_loss"] + ) + report_lines.extend( + [ + f"## {symbol}", + "", + f"- Selected model: `{summary['selected_model']}`", + f"- Equal-date selected-minus-prior log-loss delta: `{report_aggregate['point_estimate']}`", + f"- Descriptive 95% interval: `[{report_aggregate['ci_low']}, {report_aggregate['ci_high']}]`", + f"- Directional replication status: `{summary['replication_status']}`", + "", + ] + ) + _atomic_write(stage / "reports" / "technical_report.md", "\n".join(report_lines).encode()) + _checksums(stage) + _atomic_write(stage / "_SUCCESS", SUCCESS_BYTES) + destination_run.parent.mkdir(parents=True, exist_ok=True) + os.rename(stage, destination_run) + parent = os.open(destination_run.parent, os.O_RDONLY) + try: + os.fsync(parent) + finally: + os.close(parent) + except BaseException: + if stage.exists(): + shutil.rmtree(stage) + raise + return verify_exploratory_run(destination_run) + + +def _parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--config", required=True, type=Path) + parser.add_argument("--data-root", required=True, type=Path) + parser.add_argument("--run-dir", required=True, type=Path) + parser.add_argument("--verify-only", action="store_true") + return parser + + +def main() -> int: + args = _parser().parse_args() + result = ( + verify_exploratory_run(args.run_dir) + if args.verify_only + else run_exploratory_study(args.config, args.data_root, args.run_dir) + ) + print(json.dumps(result, sort_keys=True, allow_nan=False)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/Microstructure/src/microstructure/ingestion.py b/Microstructure/src/microstructure/ingestion.py new file mode 100644 index 0000000000000000000000000000000000000000..0193f7e2ce252667749d71b362e49fb6ee3d9b50 --- /dev/null +++ b/Microstructure/src/microstructure/ingestion.py @@ -0,0 +1,1312 @@ +"""Config-driven, research-only data ingestion boundary. + +This module composes the lower-level adapters without hiding provenance or data +quality. A caller-supplied output root keeps every run bundle isolated from the +configured default data directories, which is useful for atomic pipeline staging. +""" + +from __future__ import annotations + +import hashlib +import json +import random +import time +from collections.abc import Callable, Iterable, Iterator, Mapping +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Protocol + +import pyarrow as pa # type: ignore[import-untyped] +import pyarrow.parquet as pq # type: ignore[import-untyped] +import requests + +from microstructure.config import ProjectConfig, datetime_to_ns +from microstructure.data.binance import ( + BinanceHistoricalTradeDownloader, + BinancePublicClient, + BinanceTradeStreamSummary, + RawPage, + RetryPolicy, + SymbolMetadata, +) +from microstructure.data.quality import ( + IncrementalQualityValidator, + ValidationReport, + validate_batches, + validate_table, +) +from microstructure.data.storage import DatasetWriteResult, write_partitioned_parquet +from microstructure.data.synthetic import generate_synthetic_market +from microstructure.provenance import read_json, sha256_file, utc_now_iso, write_json + +SUPPORTED_BINANCE_SYMBOLS = frozenset({"BTCUSDT", "ETHUSDT"}) + +__all__ = [ + "ConfiguredDataAdapter", + "DataAdapterRegistry", + "DataQualityGateError", + "IngestionError", + "IngestionResult", + "NormalizedDatasetResult", + "RawArtifactResult", + "SymbolDownloadResult", + "ValidationSummary", + "builtin_data_adapter_registry", + "ingest_from_config", + "ingest_public_trades", + "ingest_synthetic", + "validate_configured_input", + "validate_only", +] + + +class IngestionError(RuntimeError): + """Raised when a configuration cannot safely drive the requested ingestion.""" + + +class DataQualityGateError(IngestionError): + """Raised after preservation when configured error-level quality findings exist.""" + + def __init__(self, summary: ValidationSummary, output_root: Path) -> None: + super().__init__( + f"data-quality gate failed with {summary.error_count} error findings; " + f"preserved bundle is under {output_root}" + ) + self.summary = summary + self.output_root = output_root + + +@dataclass(frozen=True, slots=True) +class ValidationSummary: + reports: tuple[ValidationReport, ...] + report_paths: tuple[Path, ...] + rows_checked: int + error_count: int + warning_count: int + + @property + def passed(self) -> bool: + return self.error_count == 0 + + def report_for(self, dataset: str) -> ValidationReport: + for report in self.reports: + if report.dataset == dataset: + return report + raise KeyError(dataset) + + +@dataclass(frozen=True, slots=True) +class NormalizedDatasetResult: + schema_name: str + rows: int + table: pa.Table | None + validation: ValidationReport + storage: DatasetWriteResult + + def materialize(self, *, max_rows: int) -> pa.Table: + """Explicitly load a bounded result, verifying its row claim first. + + Synthetic smoke results remain resident and are returned directly. A + streamed public result deliberately carries no table; callers that truly + need one must opt into a finite bound before any Parquet part is read. + """ + if max_rows < 0: + raise ValueError("max_rows must not be negative") + if self.rows > max_rows: + raise IngestionError( + f"dataset {self.schema_name!r} has {self.rows} rows, above " + f"materialization bound {max_rows}" + ) + if self.table is not None: + if self.table.num_rows != self.rows: + raise IngestionError( + f"resident {self.schema_name!r} table disagrees with its row claim" + ) + return self.table + + artifacts = self.storage.artifacts + if not artifacts: + raise IngestionError(f"streamed {self.schema_name!r} dataset has no Parquet artifacts") + observed_rows = sum(pq.ParquetFile(item.data_path).metadata.num_rows for item in artifacts) + if observed_rows != self.rows: + raise IngestionError( + f"stored {self.schema_name!r} rows {observed_rows} disagree with " + f"manifested rows {self.rows}" + ) + # The row-count check above proves this eager compatibility path cannot + # exceed the caller's explicit bound. + return pa.concat_tables([pq.read_table(item.data_path) for item in artifacts]) + + +@dataclass(frozen=True, slots=True) +class RawArtifactResult: + path: Path + manifest_path: Path + sha256: str + manifest_sha256: str + + +@dataclass(frozen=True, slots=True) +class SymbolDownloadResult: + symbol: str + metadata: SymbolMetadata + stream_summary: BinanceTradeStreamSummary + + @property + def rows(self) -> int: + return self.stream_summary.rows_yielded + + @property + def complete_range(self) -> bool: + return self.stream_summary.complete_range + + @property + def raw_page_count(self) -> int: + return self.stream_summary.raw_page_count + + @property + def stop_reason(self) -> str: + return str(self.stream_summary.stop_reason) + + @property + def last_raw_page_sha256(self) -> str | None: + page = self.stream_summary.last_raw_page + return page.sha256 if page is not None else None + + +@dataclass(frozen=True, slots=True) +class IngestionResult: + mode: str + evidence_tier: str + output_root: Path + datasets: tuple[NormalizedDatasetResult, ...] + validation: ValidationSummary + raw_artifacts: tuple[RawArtifactResult, ...] + symbols: tuple[SymbolDownloadResult, ...] + ingestion_manifest_path: Path + ingestion_manifest_sha256: str + + @property + def rows(self) -> int: + return sum(dataset.rows for dataset in self.datasets) + + @property + def manifest_sha256s(self) -> tuple[str, ...]: + return tuple(dataset.storage.manifest_sha256 for dataset in self.datasets) + + def dataset(self, schema_name: str) -> NormalizedDatasetResult: + for dataset in self.datasets: + if dataset.schema_name == schema_name: + return dataset + raise KeyError(schema_name) + + +class ConfiguredDataAdapter(Protocol): + """Adapter contract for a configured, normalized ingestion implementation.""" + + @property + def mode(self) -> str: ... + + def ingest( + self, + config: ProjectConfig, + output_root: str | Path, + ) -> IngestionResult: ... + + +class DataAdapterRegistry: + """Explicit, fail-closed mapping from configuration modes to adapters. + + Registries are deliberately instance-scoped. Tests and embedding + applications can inject a registry without mutating process-global state, + and duplicate registrations require an explicit replacement request. + """ + + __slots__ = ("_adapters",) + + def __init__(self, adapters: Iterable[ConfiguredDataAdapter] = ()) -> None: + self._adapters: dict[str, ConfiguredDataAdapter] = {} + for adapter in adapters: + self.register(adapter) + + @property + def modes(self) -> tuple[str, ...]: + """Return registered modes in deterministic order.""" + return tuple(sorted(self._adapters)) + + def register( + self, + adapter: ConfiguredDataAdapter, + *, + replace_existing: bool = False, + ) -> None: + """Register ``adapter`` and reject accidental mode shadowing.""" + mode = adapter.mode + if not isinstance(mode, str) or not mode: + raise IngestionError("adapter mode must be a nonempty string") + if mode in self._adapters and not replace_existing: + raise IngestionError(f"data adapter mode {mode!r} is already registered") + self._adapters[mode] = adapter + + def resolve(self, mode: str) -> ConfiguredDataAdapter: + """Resolve exactly one mode or fail without selecting a fallback.""" + try: + return self._adapters[mode] + except KeyError as exc: + available = ", ".join(self.modes) if self._adapters else "none" + raise IngestionError( + f"no data adapter registered for mode {mode!r}; registered modes: {available}" + ) from exc + + +def validate_only( + tables: Mapping[str, pa.Table], + config: ProjectConfig, + *, + output_root: str | Path | None = None, +) -> ValidationSummary: + """Return validation-only summaries without repairing or replacing any table.""" + reports: list[ValidationReport] = [] + paths: list[Path] = [] + quality_root = Path(output_root) / "quality" if output_root is not None else None + quality_token = f"{time.time_ns():x}" if quality_root is not None else None + for schema_name in sorted(tables): + report = validate_table( + tables[schema_name], + schema_name, + max_spread_bps=config.quality.max_spread_bps, + max_silence_ns=config.quality.max_silence_ms * 1_000_000, + ) + reports.append(report) + if quality_root is not None: + path = quality_root / f"{schema_name}.validation-{quality_token}.json" + report.write_json(path) + paths.append(path) + return ValidationSummary( + reports=tuple(reports), + report_paths=tuple(paths), + rows_checked=sum(report.rows_checked for report in reports), + error_count=sum(report.error_count for report in reports), + warning_count=sum(report.warning_count for report in reports), + ) + + +def _write_dataset( + *, + table: pa.Table, + schema_name: str, + config: ProjectConfig, + output_root: Path, + requested_start_ns: int, + requested_end_ns: int | None, + source_uri: str, +) -> DatasetWriteResult: + return write_partitioned_parquet( + table.to_batches(max_chunksize=100_000), + root=output_root / "normalized", + dataset=schema_name, + schema_name=schema_name, + source=config.data.source, + source_uri=source_uri, + requested_start_ns=requested_start_ns, + requested_end_ns=requested_end_ns, + ) + + +def _dataset_results( + tables: Mapping[str, pa.Table], + stores: Mapping[str, DatasetWriteResult], + summary: ValidationSummary, +) -> tuple[NormalizedDatasetResult, ...]: + return tuple( + NormalizedDatasetResult( + schema_name=name, + rows=tables[name].num_rows, + table=tables[name], + validation=summary.report_for(name), + storage=stores[name], + ) + for name in sorted(tables) + ) + + +def _quality_gate(config: ProjectConfig, summary: ValidationSummary, output_root: Path) -> None: + if config.quality.fail_on_error and not summary.passed: + raise DataQualityGateError(summary, output_root) + + +def _persist_ingestion_manifest( + *, + config: ProjectConfig, + destination: Path, + mode: str, + evidence_tier: str, + datasets: tuple[NormalizedDatasetResult, ...], + raw_artifacts: tuple[RawArtifactResult, ...], + quality_artifacts: tuple[Path, ...], + symbol_coverage: list[dict[str, object]], + row_cap_per_symbol: int | None, +) -> tuple[Path, str]: + payload: dict[str, object] = { + "manifest_version": "1.0.0", + "artifact_kind": "ingestion_run", + "created_at_utc": utc_now_iso(), + "mode": mode, + "evidence_tier": evidence_tier, + "requested_evidence_tier": config.run.evidence_tier, + "source": config.data.source, + "schema_version": config.data.schema_version, + "requested_range_ns": { + "start": datetime_to_ns(config.data.start), + "end_exclusive": ( + datetime_to_ns(config.data.end) if config.data.end is not None else None + ), + }, + "row_cap_per_symbol": row_cap_per_symbol, + "all_requested_ranges_complete": all( + bool(item["complete_range"]) for item in symbol_coverage + ), + "symbols": symbol_coverage, + "normalized_datasets": [ + { + "schema_name": item.schema_name, + "rows": item.rows, + "manifest_path": str(item.storage.manifest_path.relative_to(destination)), + "manifest_sha256": item.storage.manifest_sha256, + } + for item in datasets + ], + "raw_artifacts": [ + { + "path": str(item.path.relative_to(destination)), + "sha256": item.sha256, + "manifest_path": str(item.manifest_path.relative_to(destination)), + "manifest_sha256": item.manifest_sha256, + } + for item in raw_artifacts + ], + "quality_artifacts": [ + { + "path": str(path.resolve().relative_to(destination)), + "sha256": sha256_file(path), + "bytes": path.stat().st_size, + } + for path in quality_artifacts + ], + } + identity = hashlib.sha256( + json.dumps(payload, sort_keys=True, separators=(",", ":")).encode() + ).hexdigest() + manifest_dir = destination / "_ingestion_manifests" + manifest_dir.mkdir(parents=True, exist_ok=True) + path = manifest_dir / f"ingestion.manifest-{identity[:20]}.json" + if path.exists(): + if read_json(path) != payload: + raise IngestionError(f"immutable ingestion-manifest collision at {path}") + else: + write_json(path, payload) + return path, sha256_file(path) + + +def ingest_synthetic(config: ProjectConfig, output_root: str | Path) -> IngestionResult: + """Generate, validate, and persist the deterministic offline smoke data set.""" + if config.data.mode != "synthetic": + raise IngestionError("ingest_synthetic requires data.mode='synthetic'") + events = config.data.events_per_symbol + if events is None or events < 1: + raise IngestionError("synthetic ingestion requires a positive events_per_symbol") + destination = Path(output_root).resolve() + destination.mkdir(parents=True, exist_ok=True) + start_ns = datetime_to_ns(config.data.start) + generated = generate_synthetic_market( + symbols=config.data.symbols, + events_per_symbol=events, + start_ts_ns=start_ns, + seed=config.run.seed, + ) + tables = { + "trades": generated.trades, + "book_observations": generated.book_observations, + } + summary = validate_only(tables, config, output_root=destination) + observed_end_ns = ( + max(max(table.column("event_ts_ns").to_pylist()) for table in tables.values()) + 1 + ) + stores = { + name: _write_dataset( + table=table, + schema_name=name, + config=config, + output_root=destination, + requested_start_ns=start_ns, + requested_end_ns=observed_end_ns, + source_uri=f"synthetic://seed/{config.run.seed}", + ) + for name, table in tables.items() + } + dataset_results = _dataset_results(tables, stores, summary) + manifest_path, manifest_sha = _persist_ingestion_manifest( + config=config, + destination=destination, + mode="synthetic", + evidence_tier="SYNTHETIC_SMOKE", + datasets=dataset_results, + raw_artifacts=(), + quality_artifacts=summary.report_paths, + symbol_coverage=[ + {"symbol": symbol, "rows": events, "complete_range": True} + for symbol in config.data.symbols + ], + row_cap_per_symbol=events, + ) + result = IngestionResult( + mode="synthetic", + evidence_tier="SYNTHETIC_SMOKE", + output_root=destination, + datasets=dataset_results, + validation=summary, + raw_artifacts=(), + symbols=(), + ingestion_manifest_path=manifest_path, + ingestion_manifest_sha256=manifest_sha, + ) + _quality_gate(config, summary, destination) + return result + + +def _raw_artifacts(raw_root: Path) -> tuple[RawArtifactResult, ...]: + results: list[RawArtifactResult] = [] + if not raw_root.exists(): + return () + for raw_path in sorted(raw_root.rglob("*.json")): + if ".manifest-" in raw_path.name: + continue + manifests = sorted(raw_path.parent.glob(f"{raw_path.name}.manifest-*.json")) + if not manifests: + raise IngestionError(f"raw artifact has no immutable manifest: {raw_path}") + for manifest_path in manifests: + results.append( + RawArtifactResult( + path=raw_path, + manifest_path=manifest_path, + sha256=sha256_file(raw_path), + manifest_sha256=sha256_file(manifest_path), + ) + ) + return tuple(results) + + +def _raw_page_result(page: RawPage) -> RawArtifactResult: + """Bind one downloader callback to its immutable raw bytes and sidecar.""" + observed_sha256 = sha256_file(page.path) + if observed_sha256 != page.sha256: + raise IngestionError(f"raw page checksum disagrees with callback metadata: {page.path}") + return RawArtifactResult( + path=page.path, + manifest_path=page.manifest_path, + sha256=observed_sha256, + manifest_sha256=sha256_file(page.manifest_path), + ) + + +def _public_trade_batches( + *, + config: ProjectConfig, + client: BinancePublicClient, + raw_root: Path, + start_ns: int, + end_ns: int, + row_cap: int, + validator: IncrementalQualityValidator, + used_raw_artifacts: list[RawArtifactResult], + symbol_results: list[SymbolDownloadResult], +) -> Iterator[pa.RecordBatch]: + """Yield each normalized public page once while collecting bounded metadata.""" + for symbol in config.data.symbols: + metadata = client.fetch_exchange_info(symbol=symbol, raw_root=raw_root) + metadata_sha256 = sha256_file(metadata.source_path) + if metadata_sha256 != metadata.source_artifact_id: + raise IngestionError(f"exchangeInfo checksum disagrees with metadata for {symbol}") + used_raw_artifacts.append( + RawArtifactResult( + path=metadata.source_path, + manifest_path=metadata.source_manifest_path, + sha256=metadata_sha256, + manifest_sha256=sha256_file(metadata.source_manifest_path), + ) + ) + downloader = BinanceHistoricalTradeDownloader( + client=client, + raw_root=raw_root, + request_limit=config.data.request_limit, + tick_size=metadata.tick_size, + lot_size=metadata.lot_size, + ) + captured_page_count = 0 + last_captured_page: RawPage | None = None + + def capture_raw_page(page: RawPage) -> None: + nonlocal captured_page_count, last_captured_page + captured_page_count += 1 + last_captured_page = page + used_raw_artifacts.append(_raw_page_result(page)) + + stream = downloader.stream( + symbol=symbol, + start_ts_ns=start_ns, + end_ts_ns=end_ns, + max_events=row_cap, + on_raw_page=capture_raw_page, + ) + observed_rows = 0 + for batch in stream: + if batch.num_rows < 1 or batch.num_rows > config.data.request_limit: + raise IngestionError( + f"Binance stream yielded an invalid batch size for {symbol}: {batch.num_rows}" + ) + validator.update(batch) + observed_rows += batch.num_rows + yield batch + + terminal = stream.summary + if terminal.requested_start_ns != start_ns or terminal.requested_end_ns != end_ns: + raise IngestionError(f"Binance stream requested-range summary disagrees for {symbol}") + if terminal.rows_yielded != observed_rows: + raise IngestionError( + f"Binance stream row summary disagrees with yielded rows for {symbol}" + ) + if observed_rows > row_cap: + raise IngestionError(f"Binance adapter exceeded row cap for {symbol}") + if captured_page_count != terminal.raw_page_count: + raise IngestionError( + f"Binance stream raw-page summary disagrees with callbacks for {symbol}" + ) + if last_captured_page != terminal.last_raw_page: + raise IngestionError( + f"Binance stream last-page identity disagrees with callback for {symbol}" + ) + if observed_rows == 0: + raise IngestionError( + f"Binance returned no aggregate trades for {symbol}; raw responses were preserved" + ) + symbol_results.append( + SymbolDownloadResult( + symbol=symbol, + metadata=metadata, + stream_summary=terminal, + ) + ) + + +def ingest_public_trades( + config: ProjectConfig, + output_root: str | Path, + *, + client: BinancePublicClient | None = None, + session: requests.Session | None = None, + sleep: Callable[[float], None] | None = None, + random_value: Callable[[], float] | None = None, +) -> IngestionResult: + """Download bounded public BTC/ETH aggregate trades with exact symbol scales.""" + if config.data.mode != "binance_rest": + raise IngestionError("Binance ingestion requires data.mode='binance_rest'") + unsupported = set(config.data.symbols) - SUPPORTED_BINANCE_SYMBOLS + if unsupported: + raise IngestionError(f"unsupported public-sample symbols: {sorted(unsupported)}") + if config.data.end is None: + raise IngestionError("bounded Binance ingestion requires data.end") + row_cap = config.data.max_events_per_symbol + if row_cap is None or row_cap < 1: + raise IngestionError("bounded Binance ingestion requires max_events_per_symbol") + if client is not None and session is not None: + raise IngestionError("supply either client or session, not both") + + destination = Path(output_root).resolve() + destination.mkdir(parents=True, exist_ok=True) + raw_root = destination / "raw" + if client is None: + client = BinancePublicClient( + base_url=config.data.base_url, + timeout_seconds=config.data.timeout_seconds, + retry_policy=RetryPolicy(max_retries=config.data.max_retries), + session=session, + sleep=sleep if sleep is not None else time.sleep, + random_value=random_value if random_value is not None else random.random, + ) + + start_ns = datetime_to_ns(config.data.start) + end_ns = datetime_to_ns(config.data.end) + symbol_results: list[SymbolDownloadResult] = [] + used_raw_artifacts: list[RawArtifactResult] = [] + quality_root = destination / "quality" + quality_root.mkdir(parents=True, exist_ok=True) + quality_token = f"{time.time_ns():x}" + findings_path = quality_root / f"trades.findings-{quality_token}.jsonl" + with IncrementalQualityValidator( + "trades", + max_spread_bps=config.quality.max_spread_bps, + max_silence_ns=config.quality.max_silence_ms * 1_000_000, + findings_jsonl_path=findings_path, + ) as validator: + batches = _public_trade_batches( + config=config, + client=client, + raw_root=raw_root, + start_ns=start_ns, + end_ns=end_ns, + row_cap=row_cap, + validator=validator, + used_raw_artifacts=used_raw_artifacts, + symbol_results=symbol_results, + ) + store = write_partitioned_parquet( + batches, + root=destination / "normalized", + dataset="trades", + schema_name="trades", + source=config.data.source, + source_uri=f"{config.data.base_url}/api/v3/aggTrades", + requested_start_ns=start_ns, + requested_end_ns=end_ns, + max_input_batch_rows=config.data.request_limit, + ) + report = validator.finish() + report_path = quality_root / f"trades.validation-{quality_token}.json" + report.write_json(report_path) + summary = ValidationSummary( + reports=(report,), + report_paths=(report_path,), + rows_checked=report.rows_checked, + error_count=report.error_count, + warning_count=report.warning_count, + ) + expected_rows = sum(item.rows for item in symbol_results) + if store.rows != expected_rows or report.rows_checked != expected_rows: + raise IngestionError("public stream storage, validation, and symbol row counts disagree") + dataset_results = ( + NormalizedDatasetResult( + schema_name="trades", + rows=store.rows, + table=None, + validation=report, + storage=store, + ), + ) + unique_raw_artifacts: dict[tuple[Path, Path], RawArtifactResult] = {} + for item in used_raw_artifacts: + unique_raw_artifacts[(item.path, item.manifest_path)] = item + raw_artifacts = tuple(unique_raw_artifacts.values()) + all_requested_ranges_complete = all(item.complete_range for item in symbol_results) + effective_evidence_tier = ( + config.run.evidence_tier if all_requested_ranges_complete else "PUBLIC_SAMPLE_PARTIAL" + ) + manifest_path, manifest_sha = _persist_ingestion_manifest( + config=config, + destination=destination, + mode="binance_rest", + evidence_tier=effective_evidence_tier, + datasets=dataset_results, + raw_artifacts=raw_artifacts, + quality_artifacts=(report_path, findings_path), + symbol_coverage=[ + { + "symbol": item.symbol, + "rows": item.rows, + "complete_range": item.complete_range, + "raw_page_count": item.raw_page_count, + "stop_reason": item.stop_reason, + "last_raw_page_sha256": item.last_raw_page_sha256, + "tick_size": str(item.metadata.tick_size), + "lot_size": str(item.metadata.lot_size), + "stream_summary": { + "requested_start_ns": item.stream_summary.requested_start_ns, + "requested_end_ns": item.stream_summary.requested_end_ns, + "rows_yielded": item.stream_summary.rows_yielded, + "raw_page_count": item.stream_summary.raw_page_count, + "stop_reason": str(item.stream_summary.stop_reason), + "complete_range": item.stream_summary.complete_range, + "last_raw_page": ( + { + "path": str( + item.stream_summary.last_raw_page.path.relative_to(destination) + ), + "manifest_path": str( + item.stream_summary.last_raw_page.manifest_path.relative_to( + destination + ) + ), + "sha256": item.stream_summary.last_raw_page.sha256, + "request_uri": item.stream_summary.last_raw_page.request_uri, + "row_count": item.stream_summary.last_raw_page.row_count, + } + if item.stream_summary.last_raw_page is not None + else None + ), + }, + } + for item in symbol_results + ], + row_cap_per_symbol=row_cap, + ) + result = IngestionResult( + mode="binance_rest", + evidence_tier=effective_evidence_tier, + output_root=destination, + datasets=dataset_results, + validation=summary, + raw_artifacts=raw_artifacts, + symbols=tuple(symbol_results), + ingestion_manifest_path=manifest_path, + ingestion_manifest_sha256=manifest_sha, + ) + _quality_gate(config, summary, destination) + return result + + +class _SyntheticDataAdapter: + """Registry wrapper around the stable synthetic ingestion API.""" + + mode = "synthetic" + + def ingest( + self, + config: ProjectConfig, + output_root: str | Path, + ) -> IngestionResult: + return ingest_synthetic(config, output_root) + + +@dataclass(frozen=True, slots=True) +class _BinanceRestDataAdapter: + """Registry wrapper that carries optional HTTP-boundary test dependencies.""" + + client: BinancePublicClient | None = None + session: requests.Session | None = None + sleep: Callable[[float], None] | None = None + random_value: Callable[[], float] | None = None + + @property + def mode(self) -> str: + return "binance_rest" + + def ingest( + self, + config: ProjectConfig, + output_root: str | Path, + ) -> IngestionResult: + return ingest_public_trades( + config, + output_root, + client=self.client, + session=self.session, + sleep=self.sleep, + random_value=self.random_value, + ) + + +def builtin_data_adapter_registry( + *, + client: BinancePublicClient | None = None, + session: requests.Session | None = None, + sleep: Callable[[float], None] | None = None, + random_value: Callable[[], float] | None = None, +) -> DataAdapterRegistry: + """Build an isolated registry containing the supported built-in adapters. + + A new registry is returned on every call, preventing one test or embedding + application from changing dispatcher behavior process-wide. Binance HTTP + dependencies are captured by its adapter so the dispatcher itself remains + source-agnostic. + """ + return DataAdapterRegistry( + ( + _SyntheticDataAdapter(), + _BinanceRestDataAdapter( + client=client, + session=session, + sleep=sleep, + random_value=random_value, + ), + ) + ) + + +def ingest_from_config( + config: ProjectConfig, + output_root: str | Path, + *, + client: BinancePublicClient | None = None, + session: requests.Session | None = None, + sleep: Callable[[float], None] | None = None, + random_value: Callable[[], float] | None = None, + adapter: ConfiguredDataAdapter | None = None, + registry: DataAdapterRegistry | None = None, +) -> IngestionResult: + """Resolve and run exactly the adapter named by ``config.data.mode``. + + ``adapter`` preserves the original one-off injection API. ``registry`` is + the scalable extension path for configured third-party modes. The two are + mutually exclusive, and unresolved modes never fall through to a different + source implementation. + """ + if adapter is not None and registry is not None: + raise IngestionError("supply either adapter or registry, not both") + if adapter is not None: + if adapter.mode != config.data.mode: + raise IngestionError( + f"adapter mode {adapter.mode!r} does not match config mode {config.data.mode!r}" + ) + selected_registry = DataAdapterRegistry((adapter,)) + elif registry is not None: + if any(value is not None for value in (client, session, sleep, random_value)): + raise IngestionError( + "HTTP dependency hooks cannot be combined with an explicit registry; " + "capture them in the registered adapter" + ) + selected_registry = registry + else: + selected_registry = builtin_data_adapter_registry( + client=client, + session=session, + sleep=sleep, + random_value=random_value, + ) + selected = selected_registry.resolve(config.data.mode) + return selected.ingest(config, output_root) + + +@dataclass(frozen=True, slots=True) +class _DatasetManifestClaim: + rows_by_path: tuple[tuple[Path, int], ...] + write_order: tuple[Path, ...] | None + + +@dataclass(frozen=True, slots=True) +class _ParquetSourceKey: + path: Path + venue: str + symbol: str + continuity_id: str | None + identity_start: int + identity_end: int + + @property + def group_key(self) -> tuple[str, str, tuple[int, str]]: + continuity = (0, "") if self.continuity_id is None else (1, self.continuity_id) + return (self.venue, self.symbol, continuity) + + +def _manifest_integer(value: object, label: str, *, minimum: int = 0) -> int: + if isinstance(value, bool) or not isinstance(value, int) or value < minimum: + raise IngestionError(f"{label} must be an integer >= {minimum}") + return value + + +def _manifest_sha256(value: object, label: str) -> str: + if ( + not isinstance(value, str) + or len(value) != 64 + or any(character not in "0123456789abcdef" for character in value) + ): + raise IngestionError(f"{label} must be a lowercase SHA-256 digest") + return value + + +def _verify_dataset_artifact_claim( + *, + label: str, + normalized_root: Path, + dataset_root: Path, + data_path: Path, + rows: int, + raw_artifact: Mapping[str, object], + schema_name: str, + schema_version: str, + write_ordinal: int | None, +) -> None: + claimed_data_sha = _manifest_sha256(raw_artifact.get("data_sha256"), f"{label}.data_sha256") + observed_data_sha = sha256_file(data_path) + if observed_data_sha != claimed_data_sha: + raise IngestionError(f"{label}.data_sha256 checksum mismatch: {data_path}") + + relative_manifest = raw_artifact.get("manifest_path") + if not isinstance(relative_manifest, str) or not relative_manifest: + raise IngestionError(f"{label}.manifest_path must be a nonempty string") + manifest_path = (normalized_root / relative_manifest).resolve() + if not manifest_path.is_relative_to(dataset_root) or not manifest_path.is_file(): + raise IngestionError(f"{label}.manifest_path is not a declared dataset sidecar") + claimed_manifest_sha = _manifest_sha256( + raw_artifact.get("manifest_sha256"), f"{label}.manifest_sha256" + ) + if sha256_file(manifest_path) != claimed_manifest_sha: + raise IngestionError(f"{label}.manifest_sha256 checksum mismatch: {manifest_path}") + + sidecar = read_json(manifest_path) + if not isinstance(sidecar, dict): + raise IngestionError(f"{label}.manifest_path is not a JSON object") + expected_identity = { + "artifact_kind": "normalized_parquet", + "dataset": schema_name, + "schema_name": schema_name, + "schema_version": schema_version, + "rows": rows, + "path": str(data_path.relative_to(normalized_root)), + } + for key, expected in expected_identity.items(): + if sidecar.get(key) != expected: + raise IngestionError(f"{label} sidecar {key!r} claim is inconsistent") + checksum = sidecar.get("checksum") + if ( + not isinstance(checksum, dict) + or checksum.get("algorithm") != "sha256" + or checksum.get("value") != claimed_data_sha + ): + raise IngestionError(f"{label} sidecar checksum claim is inconsistent") + if write_ordinal is not None and sidecar.get("write_ordinal") != write_ordinal: + raise IngestionError(f"{label} sidecar write_ordinal claim is inconsistent") + + +def _load_dataset_manifest_claim( + path: Path, + *, + normalized_root: Path, + dataset_root: Path, + schema_name: str, + schema_version: str, +) -> _DatasetManifestClaim: + payload = read_json(path) + if not isinstance(payload, dict): + raise IngestionError(f"normalized dataset manifest is not an object: {path}") + if payload.get("dataset") != schema_name or payload.get("schema_version") != schema_version: + raise IngestionError(f"normalized dataset manifest identity mismatch: {path}") + raw_artifacts = payload.get("artifacts") + if not isinstance(raw_artifacts, list) or not raw_artifacts: + raise IngestionError(f"normalized dataset manifest has no artifacts: {path}") + + rows_by_path: list[tuple[Path, int]] = [] + ordinal_paths: list[tuple[int, Path]] = [] + ordinal_presence: set[bool] = set() + seen: set[Path] = set() + for index, raw_artifact in enumerate(raw_artifacts): + label = f"{path.name}.artifacts[{index}]" + if not isinstance(raw_artifact, dict): + raise IngestionError(f"{label} must be an object") + relative = raw_artifact.get("data_path") + if not isinstance(relative, str) or not relative: + raise IngestionError(f"{label}.data_path must be a nonempty string") + data_path = (normalized_root / relative).resolve() + if not data_path.is_relative_to(dataset_root) or not data_path.is_file(): + raise IngestionError(f"{label}.data_path is not a declared dataset Parquet file") + if data_path in seen: + raise IngestionError(f"{label}.data_path is duplicated") + seen.add(data_path) + rows = _manifest_integer(raw_artifact.get("rows"), f"{label}.rows", minimum=1) + rows_by_path.append((data_path, rows)) + has_ordinal = "write_ordinal" in raw_artifact + ordinal_presence.add(has_ordinal) + write_ordinal: int | None = None + if has_ordinal: + write_ordinal = _manifest_integer( + raw_artifact.get("write_ordinal"), + f"{label}.write_ordinal", + ) + ordinal_paths.append( + ( + write_ordinal, + data_path, + ) + ) + _verify_dataset_artifact_claim( + label=label, + normalized_root=normalized_root, + dataset_root=dataset_root, + data_path=data_path, + rows=rows, + raw_artifact=raw_artifact, + schema_name=schema_name, + schema_version=schema_version, + write_ordinal=write_ordinal, + ) + + if len(ordinal_presence) != 1: + raise IngestionError( + f"normalized dataset manifest mixes ordered and legacy artifacts: {path}" + ) + declared_rows = _manifest_integer(payload.get("rows"), f"{path.name}.rows", minimum=1) + if declared_rows != sum(rows for _, rows in rows_by_path): + raise IngestionError(f"normalized dataset manifest row total is inconsistent: {path}") + + write_order: tuple[Path, ...] | None = None + if ordinal_paths: + observed_ordinals = sorted(ordinal for ordinal, _ in ordinal_paths) + if observed_ordinals != list(range(len(ordinal_paths))): + raise IngestionError( + f"normalized dataset manifest write ordinals are not contiguous: {path}" + ) + write_order = tuple( + data_path for _, data_path in sorted(ordinal_paths, key=lambda item: item[0]) + ) + return _DatasetManifestClaim( + rows_by_path=tuple(sorted(rows_by_path, key=lambda item: str(item[0]))), + write_order=write_order, + ) + + +def _manifest_write_order( + *, + normalized_root: Path, + dataset_root: Path, + schema_name: str, + schema_version: str, + discovered_paths: tuple[Path, ...], +) -> tuple[Path, ...] | None: + manifest_root = normalized_root / "_manifests" + manifest_paths = ( + sorted(manifest_root.glob(f"{schema_name}.manifest-*.json")) + if manifest_root.exists() + else [] + ) + if not manifest_paths: + return None + claims = [ + _load_dataset_manifest_claim( + path, + normalized_root=normalized_root, + dataset_root=dataset_root, + schema_name=schema_name, + schema_version=schema_version, + ) + for path in manifest_paths + ] + expected_paths = frozenset(discovered_paths) + first_rows = claims[0].rows_by_path + for claim in claims: + if frozenset(path for path, _ in claim.rows_by_path) != expected_paths: + raise IngestionError( + f"{schema_name} dataset manifests do not cover exactly the discovered parts" + ) + if claim.rows_by_path != first_rows: + raise IngestionError( + f"multiple {schema_name} dataset manifests have ambiguous row claims" + ) + for data_path, claimed_rows in first_rows: + observed_rows = pq.ParquetFile(data_path).metadata.num_rows + if observed_rows != claimed_rows: + raise IngestionError( + f"{schema_name} dataset manifest rows disagree with Parquet metadata: {data_path}" + ) + explicit_orders = {claim.write_order for claim in claims if claim.write_order is not None} + if len(explicit_orders) > 1: + raise IngestionError(f"multiple {schema_name} dataset manifests have ambiguous write order") + return next(iter(explicit_orders)) if explicit_orders else None + + +def _parquet_column_bounds( + parquet: pq.ParquetFile, + column_name: str, + *, + label: str, + allow_all_null: bool = False, +) -> tuple[object | None, object | None]: + column_index = parquet.schema_arrow.get_field_index(column_name) + if column_index < 0: + raise IngestionError(f"{label} is missing ordering column {column_name!r}") + minima: list[Any] = [] + maxima: list[Any] = [] + total_nulls = 0 + metadata = parquet.metadata + for row_group_index in range(metadata.num_row_groups): + row_group = metadata.row_group(row_group_index) + statistics = row_group.column(column_index).statistics + if statistics is None or statistics.null_count is None: + raise IngestionError(f"{label} lacks bounded statistics for {column_name!r}") + null_count = int(statistics.null_count) + total_nulls += null_count + if statistics.has_min_max: + minima.append(statistics.min) + maxima.append(statistics.max) + elif null_count != row_group.num_rows: + raise IngestionError(f"{label} lacks min/max statistics for {column_name!r}") + if total_nulls == metadata.num_rows and allow_all_null: + return None, None + if total_nulls != 0 or not minima or not maxima: + raise IngestionError(f"{label} has ambiguous nulls for ordering column {column_name!r}") + try: + return min(minima), max(maxima) + except TypeError as exc: + raise IngestionError(f"{label} has incomparable statistics for {column_name!r}") from exc + + +def _required_text_stat(value: object | None, label: str) -> str: + if isinstance(value, bytes): + try: + return value.decode() + except UnicodeDecodeError as exc: + raise IngestionError(f"{label} is not valid UTF-8") from exc + if not isinstance(value, str) or not value: + raise IngestionError(f"{label} must be a nonempty string") + return value + + +def _required_int_stat(value: object | None, label: str) -> int: + if isinstance(value, bool) or not isinstance(value, int): + raise IngestionError(f"{label} must be an integer") + return value + + +def _parquet_source_key(path: Path, schema_name: str) -> _ParquetSourceKey: + parquet = pq.ParquetFile(path) + if parquet.metadata.num_rows < 1: + raise IngestionError(f"cannot order an empty Parquet part: {path}") + venue_min, venue_max = _parquet_column_bounds(parquet, "venue", label=str(path)) + symbol_min, symbol_max = _parquet_column_bounds(parquet, "symbol", label=str(path)) + venue = _required_text_stat(venue_min, f"{path}.venue") + symbol = _required_text_stat(symbol_min, f"{path}.symbol") + if venue != _required_text_stat(venue_max, f"{path}.venue") or symbol != ( + _required_text_stat(symbol_max, f"{path}.symbol") + ): + raise IngestionError(f"Parquet part spans multiple venue/symbol keys: {path}") + + continuity_min, continuity_max = _parquet_column_bounds( + parquet, + "continuity_id", + label=str(path), + allow_all_null=True, + ) + if continuity_min is None and continuity_max is None: + continuity_id = None + else: + continuity_id = _required_text_stat(continuity_min, f"{path}.continuity_id") + if continuity_id != _required_text_stat(continuity_max, f"{path}.continuity_id"): + raise IngestionError(f"Parquet part spans multiple continuity IDs: {path}") + + identity_columns = { + "trades": ("trade_id", "trade_id"), + "book_observations": ("sequence_start", "sequence_end"), + "depth_deltas": ("first_update_id", "last_update_id"), + } + start_column, end_column = identity_columns[schema_name] + identity_start_raw, _ = _parquet_column_bounds(parquet, start_column, label=str(path)) + _, identity_end_raw = _parquet_column_bounds(parquet, end_column, label=str(path)) + identity_start = _required_int_stat(identity_start_raw, f"{path}.{start_column}") + identity_end = _required_int_stat(identity_end_raw, f"{path}.{end_column}") + if identity_end < identity_start: + raise IngestionError(f"Parquet part has an invalid source-identity range: {path}") + return _ParquetSourceKey( + path=path, + venue=venue, + symbol=symbol, + continuity_id=continuity_id, + identity_start=identity_start, + identity_end=identity_end, + ) + + +def _legacy_source_order(paths: tuple[Path, ...], schema_name: str) -> tuple[Path, ...]: + descriptors = [_parquet_source_key(path, schema_name) for path in paths] + if schema_name == "trades": + descriptors.sort( + key=lambda item: (item.venue, item.symbol, item.identity_start, str(item.path)) + ) + else: + descriptors.sort(key=lambda item: (*item.group_key, item.identity_start, str(item.path))) + previous_by_group: dict[object, _ParquetSourceKey] = {} + for descriptor in descriptors: + group_key: object = ( + (descriptor.venue, descriptor.symbol) + if schema_name == "trades" + else descriptor.group_key + ) + previous = previous_by_group.get(group_key) + if previous is not None and previous.identity_end >= descriptor.identity_start: + raise IngestionError( + f"legacy {schema_name} Parquet source ranges overlap; part order is ambiguous" + ) + previous_by_group[group_key] = descriptor + return tuple(item.path for item in descriptors) + + +def _ordered_parquet_paths( + *, + config: ProjectConfig, + dataset_root: Path, + schema_name: str, + discovered_paths: tuple[Path, ...], +) -> tuple[Path, ...]: + normalized_root = config.data.partition_root.resolve() + manifest_order = _manifest_write_order( + normalized_root=normalized_root, + dataset_root=dataset_root.resolve(), + schema_name=schema_name, + schema_version=config.data.schema_version, + discovered_paths=discovered_paths, + ) + if manifest_order is not None: + return manifest_order + return _legacy_source_order(discovered_paths, schema_name) + + +def validate_configured_input( + config: ProjectConfig, *, tables: Mapping[str, pa.Table] | None = None +) -> ValidationSummary: + """Validate supplied normalized tables or discover them under configured storage.""" + if tables is not None: + return validate_only(tables, config) + + configured_row_limit = ( + config.data.events_per_symbol + if config.data.mode == "synthetic" + else config.data.max_events_per_symbol + ) + if configured_row_limit is None: + raise IngestionError("configured validation requires a finite per-symbol row limit") + maximum_rows = configured_row_limit * len(config.data.symbols) + reports: list[ValidationReport] = [] + for schema_name in ("book_observations", "depth_deltas", "trades"): + dataset_root = config.data.partition_root / schema_name + discovered_paths = ( + tuple(sorted(path.resolve() for path in dataset_root.rglob("*.parquet"))) + if dataset_root.exists() + else () + ) + if discovered_paths: + ordered_paths = _ordered_parquet_paths( + config=config, + dataset_root=dataset_root, + schema_name=schema_name, + discovered_paths=discovered_paths, + ) + rows = sum(pq.ParquetFile(path).metadata.num_rows for path in ordered_paths) + if rows > maximum_rows: + raise IngestionError( + f"{schema_name} contains {rows} rows, above configured validation bound " + f"{maximum_rows}; validate bounded partitions separately" + ) + batches = ( + batch + for path in ordered_paths + for batch in pq.ParquetFile(path).iter_batches(batch_size=16_384) + ) + report = validate_batches( + batches, + schema_name, + max_spread_bps=config.quality.max_spread_bps, + max_silence_ns=config.quality.max_silence_ms * 1_000_000, + ) + if report.rows_checked != rows: + raise IngestionError( + f"streaming validation checked {report.rows_checked} {schema_name} rows, " + f"but Parquet metadata declared {rows}" + ) + reports.append(report) + if not reports: + raise IngestionError( + f"no normalized Parquet inputs found under {config.data.partition_root}" + ) + return ValidationSummary( + reports=tuple(reports), + report_paths=(), + rows_checked=sum(report.rows_checked for report in reports), + error_count=sum(report.error_count for report in reports), + warning_count=sum(report.warning_count for report in reports), + ) diff --git a/Microstructure/src/microstructure/m8_acquisition.py b/Microstructure/src/microstructure/m8_acquisition.py new file mode 100644 index 0000000000000000000000000000000000000000..82fbc8304e15aa335815f356904ab52f892066c5 --- /dev/null +++ b/Microstructure/src/microstructure/m8_acquisition.py @@ -0,0 +1,3202 @@ +"""Outcome-blind raw acquisition authority for the frozen M8 study. + +This module is deliberately unable to normalize an aggregate-trade row. It +captures the two permitted exchangeInfo responses, authenticates the eight +official daily ZIPs, and inspects ZIP directory metadata only. The CSV member +is first opened later by :mod:`microstructure.m8_normalization`, after the +analysis lock has become durable. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import re +import shutil +import stat +import struct +import tempfile +import zipfile +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass, replace +from datetime import UTC, datetime +from datetime import date as Date +from decimal import Decimal, InvalidOperation +from pathlib import Path +from types import MappingProxyType +from typing import Any, Literal, Protocol, cast +from urllib.parse import parse_qsl, urlparse + +from microstructure.data.binance import ( + BinanceHTTPError, + BinanceMetadataContractError, + BinancePublicClient, + BinanceResponseSizeLimitError, + SymbolMetadata, +) +from microstructure.data.binance_archive import ( + AcquiredDailyArchive, + ArchiveDownloadLimits, + BinanceArchiveClient, + BinanceArchiveContractError, + BinanceArchiveHTTPError, + DailyArchiveRequest, + RawArchiveArtifact, +) +from microstructure.data.evidence_budget import EvidenceBudgetExceeded, RetainedEvidenceBudget +from microstructure.m8_config import M8PeriodRole, M8StudyConfig, load_m8_config +from microstructure.provenance import sha256_file + +M8_ACQUISITION_SCHEMA_VERSION = "1.0.0" + +_DIGEST = re.compile(r"^[0-9a-f]{64}$") +_MANIFEST_NAME = re.compile(r"^m8-acquisition\.manifest-([0-9a-f]{20})\.json$") +_SOURCE_MANIFEST_NAME = re.compile(r"^.+\.manifest-[0-9a-f]{20}\.json$") +_SAFE_SYMBOL = re.compile(r"^[A-Z0-9]{2,20}$") +_UTC_TIMESTAMP = re.compile( + r"^(?P\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})" + r"(?:\.(?P\d{1,9}))?Z$" +) +_MAX_MANIFEST_BYTES = 8 * 1024 * 1024 +_MAX_METADATA_BYTES = 8 * 1024 * 1024 +_MAX_EOCD_BYTES = 22 + 65_535 +_MAX_ZIP_DIRECTORY_BYTES = 256 * 1024 +_EOCD_SIGNATURE = b"PK\x05\x06" +_EOCD_STRUCT = struct.Struct("<4s4H2LH") +_LOCAL_FILE_SIGNATURE = b"PK\x03\x04" +_LOCAL_FILE_STRUCT = struct.Struct("<4s5H3L2H") +_RAW_ROOT_NAME = "raw" +_MANIFEST_DIRECTORY_NAME = "_manifests" +_ATTEMPT_DIRECTORY_NAME = "_attempts" +_FAILURE_MANIFEST_NAME = "failure.json" +_FAILURE_CHECKSUMS_NAME = "checksums.sha256" +_FAILURE_TERMINAL_NAME = "INSUFFICIENT_DATA" +_FAILURE_TERMINAL_BYTES = b"terminal\n" +_FAILURE_ATTEMPT_NAME = re.compile(r"^m8-acquisition-attempt-([0-9a-f]{20})$") +_RAW_SIDECAR_KEYS = frozenset( + { + "artifact_kind", + "bytes", + "checksum", + "downloaded_at_utc", + "manifest_version", + "path", + "requested_range_ns", + "response_headers", + "source", + "source_uri", + "upstream_checksum_sha256", + } +) + +RetainedArtifactKind = Literal[ + "metadata_body", + "archive_zip", + "archive_checksum", + "rejected_prefix", + "source_manifest", +] + +M8AcquisitionReasonCode = Literal[ + "DECLARED_OBJECT_UNAVAILABLE", + "METADATA_CONTRACT", + "CHECKSUM_CONTRACT", + "ZIP_CONTRACT", + "RESPONSE_SIZE_LIMIT", + "TOTAL_EVIDENCE_BUDGET", +] + +M8AcquisitionStepKind = Literal["metadata", "archive"] + + +class M8AcquisitionError(RuntimeError): + """Raised when an M8 raw acquisition authority cannot be trusted.""" + + +class _M8MetadataResponseContractError(M8AcquisitionError): + """A deterministic contract defect in an already-retained exchangeInfo body.""" + + +@dataclass(frozen=True, slots=True) +class _RegularFileSnapshot: + content: bytes + device: int + inode: int + size: int + modified_ns: int + changed_ns: int + + +class _MetadataProvider(Protocol): + def fetch_exchange_info(self, *, symbol: str, raw_root: str | Path) -> SymbolMetadata: ... + + +class _ArchiveProvider(Protocol): + def acquire( + self, + request: DailyArchiveRequest, + *, + raw_root: str | Path, + limits: ArchiveDownloadLimits, + ) -> AcquiredDailyArchive: ... + + +@dataclass(frozen=True, slots=True) +class M8RetainedArtifact: + """One physically retained raw-response body or source sidecar.""" + + path: str + sha256: str + bytes: int + kind: RetainedArtifactKind + source_uri: str + paired_body_path: str | None + + +@dataclass(frozen=True, slots=True) +class M8RawSymbolMetadata: + """Verified exchangeInfo evidence used only for tick/lot normalization.""" + + venue: str + symbol: str + status: str + base_asset: str + quote_asset: str + tick_size: Decimal + lot_size: Decimal + min_price: Decimal + max_price: Decimal + min_quantity: Decimal + max_quantity: Decimal + observed_ts_ns: int + raw_path: Path + raw_sha256: str + raw_bytes: int + source_uri: str + source_manifest_path: Path + source_manifest_sha256: str + source_manifest_bytes: int + + +@dataclass(frozen=True, slots=True) +class M8RawArchiveEntry: + """Raw-only descriptor for one frozen symbol/date archive.""" + + root: Path + symbol: str + date: Date + role: M8PeriodRole + tick_size: Decimal + lot_size: Decimal + archive_path: Path + archive_sha256: str + archive_bytes: int + archive_source_uri: str + archive_source_manifest_path: Path + archive_source_manifest_sha256: str + archive_source_manifest_bytes: int + checksum_path: Path + checksum_sha256: str + checksum_bytes: int + checksum_source_uri: str + checksum_source_manifest_path: Path + checksum_source_manifest_sha256: str + checksum_source_manifest_bytes: int + upstream_sha256: str + member_name: str + declared_uncompressed_bytes: int + max_compressed_bytes: int + max_uncompressed_bytes: int + max_checksum_bytes: int + transfer_chunk_bytes: int + max_csv_line_bytes: int + csv_member_opened: bool = False + economic_fields_inspected: bool = False + + +@dataclass(frozen=True, slots=True) +class M8RawArchiveDescriptor: + """A verified, reconstructable archive reference with no row-reading API.""" + + entry: M8RawArchiveEntry + + @property + def symbol(self) -> str: + return self.entry.symbol + + @property + def date(self) -> Date: + return self.entry.date + + @property + def role(self) -> M8PeriodRole: + return self.entry.role + + def reconstruct(self) -> AcquiredDailyArchive: + """Re-hash raw bytes and reconstruct the authenticated archive handle.""" + + _verify_archive_entry_files(self.entry) + request = DailyArchiveRequest( + symbol=self.entry.symbol, + date=self.entry.date, + tick_size=self.entry.tick_size, + lot_size=self.entry.lot_size, + ) + limits = ArchiveDownloadLimits( + max_compressed_bytes=self.entry.max_compressed_bytes, + max_uncompressed_bytes=self.entry.max_uncompressed_bytes, + max_checksum_bytes=self.entry.max_checksum_bytes, + transfer_chunk_bytes=self.entry.transfer_chunk_bytes, + max_csv_line_bytes=self.entry.max_csv_line_bytes, + ) + return AcquiredDailyArchive( + request=request, + archive_artifact=RawArchiveArtifact( + kind="archive_zip", + path=self.entry.archive_path, + manifest_path=self.entry.archive_source_manifest_path, + sha256=self.entry.archive_sha256, + manifest_sha256=self.entry.archive_source_manifest_sha256, + bytes=self.entry.archive_bytes, + source_uri=self.entry.archive_source_uri, + ), + checksum_artifact=RawArchiveArtifact( + kind="archive_checksum", + path=self.entry.checksum_path, + manifest_path=self.entry.checksum_source_manifest_path, + sha256=self.entry.checksum_sha256, + manifest_sha256=self.entry.checksum_source_manifest_sha256, + bytes=self.entry.checksum_bytes, + source_uri=self.entry.checksum_source_uri, + ), + upstream_sha256=self.entry.upstream_sha256, + declared_uncompressed_bytes=self.entry.declared_uncompressed_bytes, + limits=limits, + requires_member_open_guard=self.entry.role in {"primary_test", "replication_test"}, + ) + + +@dataclass(frozen=True, slots=True) +class M8AcquisitionManifest: + """Verified authority for the exact raw evidence of one M8 study.""" + + root: Path + path: Path + sha256: str + config_sha256: str + config_source_sha256: str + protocol_version: str + protocol_document_sha256: str + copied_from_manifest_sha256: str | None + evidence_set_sha256: str + symbol_metadata: tuple[M8RawSymbolMetadata, ...] + archives: tuple[M8RawArchiveEntry, ...] + retained_artifacts: tuple[M8RetainedArtifact, ...] + total_raw_evidence_bytes: int + total_accepted_zip_bytes: int + config: M8StudyConfig + + @property + def entries(self) -> tuple[M8RawArchiveEntry, ...]: + return self.archives + + @property + def metadata_count(self) -> int: + return len(self.symbol_metadata) + + @property + def archive_count(self) -> int: + return len(self.archives) + + @property + def content_identity_sha256(self) -> str: + """Root-independent identity of every semantic claim and raw byte.""" + + return self.evidence_set_sha256 + + def metadata_for(self, symbol: str) -> M8RawSymbolMetadata: + for metadata in self.symbol_metadata: + if metadata.symbol == symbol: + return metadata + raise KeyError(f"no verified M8 symbol metadata for {symbol}") + + def archive_descriptor_for(self, symbol: str, date: Date | str) -> M8RawArchiveDescriptor: + date_text = date.isoformat() if isinstance(date, Date) else date + for entry in self.archives: + if entry.symbol == symbol and entry.date.isoformat() == date_text: + return M8RawArchiveDescriptor(entry) + raise KeyError(f"no verified M8 raw archive for {symbol}/{date_text}") + + +@dataclass(frozen=True, slots=True) +class M8AcquisitionResult: + """Stable CLI-facing result for one completed raw-only acquisition.""" + + output_root: Path + manifest_path: Path + manifest_sha256: str + metadata_count: int + archive_count: int + total_raw_evidence_bytes: int + manifest: M8AcquisitionManifest + + @property + def status(self) -> Literal["ACQUIRED"]: + return "ACQUIRED" + + +@dataclass(frozen=True, slots=True) +class M8AcquisitionStep: + """One declared raw acquisition unit in frozen execution order.""" + + kind: M8AcquisitionStepKind + symbol: str + date: Date | None + role: str + + +@dataclass(frozen=True, slots=True) +class M8AcquisitionFailureManifest: + """Verified immutable authority for a deterministic raw-only failure.""" + + root: Path + attempt_dir: Path + path: Path + sha256: str + checksums_path: Path + checksums_sha256: str + terminal_path: Path + reason_code: M8AcquisitionReasonCode + diagnostic: str + failed_step: M8AcquisitionStep + completed_steps: tuple[M8AcquisitionStep, ...] + remaining_steps: tuple[M8AcquisitionStep, ...] + retained_artifacts: tuple[M8RetainedArtifact, ...] + retained_inventory_sha256: str + total_raw_evidence_bytes: int + config: M8StudyConfig + + +@dataclass(frozen=True, slots=True) +class M8AcquisitionFailureResult: + """CLI-facing result for one immutable deterministic acquisition failure.""" + + output_root: Path + attempt_dir: Path + attempt_manifest_path: Path + attempt_manifest_sha256: str + checksums_path: Path + checksums_sha256: str + terminal_path: Path + reason_code: M8AcquisitionReasonCode + diagnostic: str + failed_symbol: str + failed_date: Date | None + failed_role: str + completed_count: int + remaining_count: int + retained_inventory_sha256: str + retained_artifact_count: int + total_raw_evidence_bytes: int + manifest: M8AcquisitionFailureManifest + status: Literal["INSUFFICIENT_DATA"] = "INSUFFICIENT_DATA" + + +M8AcquisitionOutcome = M8AcquisitionResult | M8AcquisitionFailureResult + + +def _require_exact_keys(value: Mapping[str, Any], expected: frozenset[str], label: str) -> None: + observed = frozenset(value) + if observed != expected: + missing = sorted(expected - observed) + extra = sorted(observed - expected) + raise M8AcquisitionError(f"{label} keys differ: missing={missing}, extra={extra}") + + +def _object(value: object, label: str) -> Mapping[str, Any]: + if not isinstance(value, Mapping) or not all(type(key) is str for key in value): + raise M8AcquisitionError(f"{label} must be a JSON object with string keys") + return cast(Mapping[str, Any], value) + + +def _array(value: object, label: str) -> list[Any]: + if not isinstance(value, list): + raise M8AcquisitionError(f"{label} must be a JSON array") + return value + + +def _text(value: object, label: str) -> str: + if type(value) is not str or not value: + raise M8AcquisitionError(f"{label} must be a non-empty string") + return value + + +def _integer(value: object, label: str, *, minimum: int = 0) -> int: + if isinstance(value, bool) or not isinstance(value, int) or value < minimum: + raise M8AcquisitionError(f"{label} must be an integer >= {minimum}") + return value + + +def _boolean(value: object, label: str) -> bool: + if type(value) is not bool: + raise M8AcquisitionError(f"{label} must be a boolean") + return value + + +def _digest(value: object, label: str) -> str: + text = _text(value, label) + if _DIGEST.fullmatch(text) is None: + raise M8AcquisitionError(f"{label} must be one lowercase SHA-256") + return text + + +def _decimal(value: object, label: str, *, positive: bool = False) -> Decimal: + text = _text(value, label) + try: + parsed = Decimal(text) + except InvalidOperation as exc: + raise M8AcquisitionError(f"{label} must be a canonical decimal") from exc + if not parsed.is_finite() or (positive and parsed <= 0) or format(parsed, "f") != text: + raise M8AcquisitionError(f"{label} is not a valid canonical decimal") + return parsed + + +def _canonical_json_bytes(value: Mapping[str, Any]) -> bytes: + return ( + json.dumps( + value, + sort_keys=True, + separators=(",", ":"), + ensure_ascii=True, + allow_nan=False, + ) + + "\n" + ).encode("utf-8") + + +def _read_bounded_regular_snapshot( + path: Path, + label: str, + *, + byte_limit: int, +) -> _RegularFileSnapshot: + """Read one regular file from one fd and reject path/inode replacement.""" + + nofollow = getattr(os, "O_NOFOLLOW", 0) + try: + descriptor = os.open(path, os.O_RDONLY | nofollow) + with os.fdopen(descriptor, "rb") as source: + before = os.fstat(source.fileno()) + if not stat.S_ISREG(before.st_mode): + raise M8AcquisitionError(f"{label} is not a regular file") + if before.st_size > byte_limit: + raise M8AcquisitionError(f"{label} exceeds its byte ceiling") + content = source.read(byte_limit + 1) + after = os.fstat(source.fileno()) + if len(content) > byte_limit: + raise M8AcquisitionError(f"{label} exceeds its byte ceiling") + if len(content) != before.st_size or ( + before.st_dev, + before.st_ino, + before.st_size, + before.st_mtime_ns, + before.st_ctime_ns, + ) != ( + after.st_dev, + after.st_ino, + after.st_size, + after.st_mtime_ns, + after.st_ctime_ns, + ): + raise M8AcquisitionError(f"{label} changed while it was read") + linked = os.stat(path, follow_symlinks=False) + if not stat.S_ISREG(linked.st_mode) or (linked.st_dev, linked.st_ino) != ( + before.st_dev, + before.st_ino, + ): + raise M8AcquisitionError(f"{label} path changed while it was read") + return _RegularFileSnapshot( + content=content, + device=before.st_dev, + inode=before.st_ino, + size=before.st_size, + modified_ns=before.st_mtime_ns, + changed_ns=before.st_ctime_ns, + ) + except M8AcquisitionError: + raise + except OSError as exc: + raise M8AcquisitionError(f"cannot read {label}: {path}") from exc + + +def _assert_snapshot_path(path: Path, snapshot: _RegularFileSnapshot, label: str) -> None: + try: + observed = os.stat(path, follow_symlinks=False) + except OSError as exc: + raise M8AcquisitionError(f"{label} path disappeared after snapshot") from exc + if not stat.S_ISREG(observed.st_mode) or ( + observed.st_dev, + observed.st_ino, + observed.st_size, + observed.st_mtime_ns, + observed.st_ctime_ns, + ) != ( + snapshot.device, + snapshot.inode, + snapshot.size, + snapshot.modified_ns, + snapshot.changed_ns, + ): + raise M8AcquisitionError(f"{label} path changed after snapshot") + + +def _read_bounded_regular_bytes(path: Path, label: str, *, byte_limit: int) -> bytes: + return _read_bounded_regular_snapshot(path, label, byte_limit=byte_limit).content + + +def _parse_json_bytes(content: bytes, label: str) -> Mapping[str, Any]: + try: + + def reject_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + raise M8AcquisitionError(f"{label} contains duplicate key {key!r}") + result[key] = value + return result + + def reject_constant(value: str) -> object: + raise M8AcquisitionError(f"{label} contains forbidden JSON constant {value}") + + parsed = json.loads( + content, + object_pairs_hook=reject_duplicates, + parse_constant=reject_constant, + ) + except M8AcquisitionError: + raise + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise M8AcquisitionError(f"cannot parse {label}") from exc + return _object(parsed, label) + + +def _read_json( + path: Path, label: str, *, byte_limit: int = _MAX_MANIFEST_BYTES +) -> Mapping[str, Any]: + try: + content = _read_bounded_regular_bytes(path, label, byte_limit=byte_limit) + if len(content) > byte_limit: + raise M8AcquisitionError(f"{label} exceeds its JSON byte ceiling") + return _parse_json_bytes(content, label) + except M8AcquisitionError: + raise + except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc: + raise M8AcquisitionError(f"cannot parse {label}: {path}") from exc + + +def _protocol_path(config: M8StudyConfig) -> Path: + path = config.path.parent.parent / "docs" / "M8_MULTIDATE_TRADE_PROTOCOL.md" + if not path.is_file() or path.is_symlink(): + raise M8AcquisitionError(f"frozen M8 protocol document is missing: {path}") + return path.resolve() + + +def _verify_config_sources(config: M8StudyConfig) -> str: + if not config.path.is_file() or config.path.is_symlink(): + raise M8AcquisitionError("frozen M8 machine specification is missing or symbolic") + if sha256_file(config.path) != config.source_sha256: + raise M8AcquisitionError("frozen M8 machine specification bytes changed") + try: + reloaded = load_m8_config(config.path) + except Exception as exc: + raise M8AcquisitionError("cannot re-validate frozen M8 machine specification") from exc + if reloaded.hash != config.hash or reloaded.source_sha256 != config.source_sha256: + raise M8AcquisitionError("in-memory M8 configuration differs from its frozen source") + return sha256_file(_protocol_path(config)) + + +def _relative(root: Path, path: Path, label: str) -> str: + root_resolved = root.resolve() + path_absolute = path.absolute() + if path_absolute.is_symlink(): + raise M8AcquisitionError(f"{label} must not be a symbolic link: {path}") + resolved = path.resolve() + if not resolved.is_relative_to(root_resolved) or not resolved.is_file(): + raise M8AcquisitionError(f"{label} is missing or escapes acquisition root: {path}") + relative = resolved.relative_to(root_resolved).as_posix() + if relative.startswith(f"{_MANIFEST_DIRECTORY_NAME}/"): + raise M8AcquisitionError(f"{label} incorrectly points into manifest storage") + return relative + + +def _declared_file(root: Path, value: object, label: str) -> Path: + raw = _text(value, label) + declared = Path(raw) + if ( + declared.is_absolute() + or "\\" in raw + or raw != declared.as_posix() + or not declared.parts + or any(part in {"", ".", ".."} for part in declared.parts) + or declared.parts[0] != _RAW_ROOT_NAME + ): + raise M8AcquisitionError(f"{label} must be one canonical relative raw-evidence path") + current = root.resolve() + for component in declared.parts: + current /= component + if current.is_symlink(): + raise M8AcquisitionError(f"{label} traverses a symbolic link: {current}") + resolved = current.resolve() + if not resolved.is_relative_to(root.resolve()) or not resolved.is_file(): + raise M8AcquisitionError(f"{label} is missing or escapes acquisition root: {raw}") + return resolved + + +def _verify_file(path: Path, digest: str, byte_count: int, label: str) -> None: + try: + if path.is_symlink() or not path.is_file(): + raise M8AcquisitionError(f"{label} is missing or symbolic: {path}") + observed_bytes = path.stat().st_size + if observed_bytes != byte_count: + raise M8AcquisitionError( + f"{label} byte count changed: expected {byte_count}, observed {observed_bytes}" + ) + observed_sha = sha256_file(path) + except M8AcquisitionError: + raise + except OSError as exc: + raise M8AcquisitionError(f"cannot verify {label}: {path}") from exc + if observed_sha != digest: + raise M8AcquisitionError( + f"{label} SHA-256 changed: expected {digest}, observed {observed_sha}" + ) + + +def _utc_ns(value: object, label: str) -> int: + text = _text(value, label) + match = _UTC_TIMESTAMP.fullmatch(text) + if match is None: + raise M8AcquisitionError(f"{label} must be a canonical UTC timestamp") + try: + second = datetime.strptime(match.group("second"), "%Y-%m-%dT%H:%M:%S").replace(tzinfo=UTC) + except ValueError as exc: + raise M8AcquisitionError(f"{label} is not a real UTC timestamp") from exc + fraction = (match.group("fraction") or "").ljust(9, "0") + seconds = int(second.timestamp()) + result = seconds * 1_000_000_000 + int(fraction or "0") + if result < 1: + raise M8AcquisitionError(f"{label} must be after the Unix epoch") + return result + + +def _day_bounds_ns(day: Date) -> tuple[int, int]: + start = int(datetime(day.year, day.month, day.day, tzinfo=UTC).timestamp()) * 1_000_000_000 + return start, start + 86_400 * 1_000_000_000 + + +def _expected_archive_uri(symbol: str, day: Date, *, checksum: bool = False) -> str: + name = f"{symbol}-aggTrades-{day.isoformat()}.zip" + suffix = ".CHECKSUM" if checksum else "" + return f"https://data.binance.vision/data/spot/daily/aggTrades/{symbol}/{name}{suffix}" + + +def _verify_exchange_info_uri(value: str, symbol: str) -> None: + try: + parsed = urlparse(value) + port = parsed.port + query = parse_qsl( + parsed.query, keep_blank_values=True, strict_parsing=True, max_num_fields=2 + ) + except ValueError as exc: + raise M8AcquisitionError("exchangeInfo source URI is malformed") from exc + if ( + parsed.scheme != "https" + or parsed.netloc != "data-api.binance.vision" + or parsed.hostname != "data-api.binance.vision" + or port is not None + or parsed.username is not None + or parsed.password is not None + or parsed.path != "/api/v3/exchangeInfo" + or parsed.params + or parsed.fragment + or query != [("symbol", symbol)] + or any(ord(character) < 0x20 or ord(character) == 0x7F for character in value) + ): + raise M8AcquisitionError( + f"metadata source URI is not the exact official exchangeInfo request for {symbol}" + ) + + +def _verify_official_uri(value: str, expected: str, label: str) -> None: + try: + parsed = urlparse(value) + port = parsed.port + except ValueError as exc: + raise M8AcquisitionError(f"{label} is malformed") from exc + expected_parsed = urlparse(expected) + if ( + value != expected + or parsed.scheme != "https" + or parsed.netloc != "data.binance.vision" + or parsed.hostname != "data.binance.vision" + or port is not None + or parsed.username is not None + or parsed.password is not None + or parsed.path != expected_parsed.path + or parsed.params + or parsed.query + or parsed.fragment + ): + raise M8AcquisitionError(f"{label} is not the exact official Binance archive URI") + + +def _format_decimal(value: Decimal) -> str: + if not value.is_finite(): + raise M8AcquisitionError("metadata contains a non-finite decimal") + return format(value, "f") + + +def _expected_raw_path(root: Path, relative: str, observed: Path, label: str) -> None: + expected = (root / relative).resolve() + if observed.resolve() != expected: + raise M8AcquisitionError(f"{label} is not stored at its canonical raw path") + + +def _source_manifest_path_is_canonical(body: Path, sidecar: Path, label: str) -> None: + if sidecar.parent != body.parent or _SOURCE_MANIFEST_NAME.fullmatch(sidecar.name) is None: + raise M8AcquisitionError(f"{label} path is not the canonical content-addressed sidecar") + if not sidecar.name.startswith(f"{body.name}.manifest-"): + raise M8AcquisitionError(f"{label} does not name its paired raw body") + + +def _verify_source_manifest_identity( + body: Path, + sidecar: Path, + payload: Mapping[str, Any], + label: str, +) -> None: + try: + stable = json.dumps( + payload, + sort_keys=True, + separators=(",", ":"), + allow_nan=False, + ).encode("utf-8") + except (TypeError, ValueError) as exc: + raise M8AcquisitionError(f"{label} is not stable JSON") from exc + identity = hashlib.sha256(stable).hexdigest() + if sidecar.name != f"{body.name}.manifest-{identity[:20]}.json": + raise M8AcquisitionError(f"{label} filename is not content-addressed by its claims") + + +def _verify_source_sidecar( + sidecar_path: Path, + *, + body_path: Path, + body_sha256: str, + body_bytes: int, + expected_source: str, + expected_source_uri: str, + expected_range: tuple[int | None, int | None], + expected_upstream: str | None, + label: str, +) -> Mapping[str, Any]: + _source_manifest_path_is_canonical(body_path, sidecar_path, label) + sidecar = _read_json(sidecar_path, label) + _verify_source_manifest_identity(body_path, sidecar_path, sidecar, label) + _require_exact_keys(sidecar, _RAW_SIDECAR_KEYS, label) + if sidecar["manifest_version"] != "1.0.0" or sidecar["artifact_kind"] != "raw_source": + raise M8AcquisitionError(f"{label} has unsupported source-manifest identity") + expected: dict[str, object] = { + "source": expected_source, + "source_uri": expected_source_uri, + "bytes": body_bytes, + "path": body_path.name, + "upstream_checksum_sha256": expected_upstream, + } + if any(sidecar[key] != value for key, value in expected.items()): + raise M8AcquisitionError(f"{label} lineage claims do not match its raw body") + checksum = _object(sidecar["checksum"], f"{label}.checksum") + _require_exact_keys(checksum, frozenset({"algorithm", "value"}), f"{label}.checksum") + if checksum["algorithm"] != "sha256" or checksum["value"] != body_sha256: + raise M8AcquisitionError(f"{label} checksum claim does not match its raw body") + requested = _object(sidecar["requested_range_ns"], f"{label}.requested_range_ns") + _require_exact_keys( + requested, + frozenset({"start", "end_exclusive"}), + f"{label}.requested_range_ns", + ) + if (requested["start"], requested["end_exclusive"]) != expected_range: + raise M8AcquisitionError(f"{label} requested range is not the frozen range") + headers = _object(sidecar["response_headers"], f"{label}.response_headers") + if not all(type(key) is str and type(value) is str for key, value in headers.items()): + raise M8AcquisitionError(f"{label} response headers must contain only strings") + _utc_ns(sidecar["downloaded_at_utc"], f"{label}.downloaded_at_utc") + return sidecar + + +def _preflight_zip_directory(path: Path) -> tuple[int, int]: + """Bound EOCD and central-directory bytes before ``zipfile`` sees them.""" + + try: + size = path.stat().st_size + if size < _EOCD_STRUCT.size: + raise M8AcquisitionError("M8 archive is too small for a ZIP directory") + tail_size = min(size, _MAX_EOCD_BYTES) + with path.open("rb") as source: + source.seek(size - tail_size) + tail = source.read(tail_size) + offset = tail.rfind(_EOCD_SIGNATURE) + if offset < 0 or len(tail) - offset < _EOCD_STRUCT.size: + raise M8AcquisitionError("M8 archive ZIP end-of-directory record is missing") + ( + _signature, + disk, + central_disk, + entries_disk, + entries_total, + central_bytes, + central_offset, + comment_bytes, + ) = _EOCD_STRUCT.unpack_from(tail, offset) + absolute_offset = size - tail_size + offset + if absolute_offset + _EOCD_STRUCT.size + comment_bytes != size: + raise M8AcquisitionError("M8 archive ZIP has trailing or malformed directory bytes") + if disk != 0 or central_disk != 0 or entries_disk != 1 or entries_total != 1: + raise M8AcquisitionError("M8 archive ZIP must contain one single-disk member") + if central_bytes < 1 or central_bytes > _MAX_ZIP_DIRECTORY_BYTES: + raise M8AcquisitionError("M8 archive ZIP central directory exceeds its byte ceiling") + if central_offset + central_bytes != absolute_offset: + raise M8AcquisitionError("M8 archive ZIP central-directory bounds are invalid") + return int(central_offset), int(central_bytes) + except M8AcquisitionError: + raise + except (OSError, struct.error) as exc: + raise M8AcquisitionError("cannot preflight bounded M8 ZIP directory metadata") from exc + + +def _verify_local_zip_header( + path: Path, + member: zipfile.ZipInfo, + expected_member: str, + central_offset: int, +) -> None: + header_offset = int(member.header_offset) + if header_offset < 0 or header_offset + _LOCAL_FILE_STRUCT.size > central_offset: + raise M8AcquisitionError("M8 archive ZIP local-header bounds are invalid") + try: + with path.open("rb") as source: + source.seek(header_offset) + raw_header = source.read(_LOCAL_FILE_STRUCT.size) + if len(raw_header) != _LOCAL_FILE_STRUCT.size: + raise M8AcquisitionError("M8 archive ZIP local header is truncated") + ( + signature, + _version, + flags, + compression, + _modified_time, + _modified_date, + _crc32, + _compressed_bytes, + _expanded_bytes, + filename_bytes, + extra_bytes, + ) = _LOCAL_FILE_STRUCT.unpack(raw_header) + if signature != _LOCAL_FILE_SIGNATURE: + raise M8AcquisitionError("M8 archive ZIP local-header signature is invalid") + metadata_bytes = filename_bytes + extra_bytes + if metadata_bytes > _MAX_ZIP_DIRECTORY_BYTES: + raise M8AcquisitionError("M8 archive ZIP local metadata exceeds its byte ceiling") + if header_offset + _LOCAL_FILE_STRUCT.size + metadata_bytes > central_offset: + raise M8AcquisitionError("M8 archive ZIP local-header metadata bounds are invalid") + local_name = source.read(filename_bytes) + except M8AcquisitionError: + raise + except (OSError, struct.error) as exc: + raise M8AcquisitionError("cannot inspect bounded M8 ZIP local metadata") from exc + if local_name != expected_member.encode("ascii"): + raise M8AcquisitionError("M8 archive ZIP local member name is unexpected") + if flags != member.flag_bits or compression != member.compress_type: + raise M8AcquisitionError("M8 archive ZIP local and central metadata disagree") + + +def _zip_directory_member(path: Path, expected_member: str, limit: int) -> int: + """Inspect central-directory metadata without opening the CSV member.""" + + central_offset, _central_bytes = _preflight_zip_directory(path) + try: + with zipfile.ZipFile(path) as archive: + members = archive.infolist() + if len(members) != 1: + raise M8AcquisitionError("M8 archive ZIP must contain exactly one member") + member = members[0] + mode = member.external_attr >> 16 + if ( + member.filename != expected_member + or Path(member.filename).name != member.filename + or "\\" in member.filename + or member.is_dir() + or stat.S_ISLNK(mode) + or member.flag_bits & 0x1 + ): + raise M8AcquisitionError("M8 archive ZIP member is unsafe or unexpected") + if member.compress_type not in {zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED}: + raise M8AcquisitionError("M8 archive ZIP compression method is unsupported") + if member.file_size < 1 or member.file_size > limit: + raise M8AcquisitionError("M8 archive declared expansion exceeds its ceiling") + _verify_local_zip_header(path, member, expected_member, central_offset) + return int(member.file_size) + except M8AcquisitionError: + raise + except (OSError, RuntimeError, zipfile.BadZipFile, ValueError) as exc: + raise M8AcquisitionError("cannot inspect bounded M8 ZIP directory metadata") from exc + + +def _parse_checksum_body(path: Path, archive_name: str) -> str: + try: + content = path.read_bytes() + except OSError as exc: + raise M8AcquisitionError("cannot read official M8 CHECKSUM response") from exc + endings = (b"", b"\n", b"\r\n") + for ending in endings: + suffix = b" " + archive_name.encode("ascii") + ending + if len(content) == 64 + len(suffix) and content[64:] == suffix: + try: + digest = content[:64].decode("ascii", errors="strict") + except UnicodeDecodeError as exc: + raise M8AcquisitionError( + "official M8 CHECKSUM digest is not lowercase ASCII" + ) from exc + if _DIGEST.fullmatch(digest) is not None: + return digest + raise M8AcquisitionError("official M8 CHECKSUM response has malformed exact bytes") + + +def _metadata_payload_values( + path: Path, + symbol: str, + *, + expected_sha256: str, + expected_bytes: int, +) -> dict[str, object]: + """Validate response semantics only after a bounded raw-file identity snapshot. + + I/O, path, and hash failures deliberately remain ``M8AcquisitionError``. + Only parsing and semantic failures attributable to the exact retained body + become ``_M8MetadataResponseContractError`` and may terminalize acquisition. + """ + + label = f"{symbol} exchangeInfo body" + snapshot = _read_bounded_regular_snapshot(path, label, byte_limit=_MAX_METADATA_BYTES) + if snapshot.size != expected_bytes or hashlib.sha256(snapshot.content).hexdigest() != ( + expected_sha256 + ): + raise M8AcquisitionError(f"{label} identity changed before semantic validation") + try: + payload = _parse_json_bytes(snapshot.content, label) + symbols = _array(payload.get("symbols"), f"{symbol} exchangeInfo symbols") + if len(symbols) != 1: + raise M8AcquisitionError(f"{symbol} exchangeInfo must contain exactly one symbol") + item = _object(symbols[0], f"{symbol} exchangeInfo symbol") + if item.get("symbol") != symbol: + raise M8AcquisitionError(f"{symbol} exchangeInfo returned another symbol") + filters_raw = _array(item.get("filters"), f"{symbol} exchangeInfo filters") + filters: dict[str, Mapping[str, Any]] = {} + for index, raw_filter in enumerate(filters_raw): + filter_item = _object(raw_filter, f"{symbol} exchangeInfo filters[{index}]") + filter_type = _text( + filter_item.get("filterType"), + f"{symbol} exchangeInfo filters[{index}].filterType", + ) + if filter_type in filters: + raise M8AcquisitionError(f"{symbol} exchangeInfo repeats filter {filter_type}") + filters[filter_type] = filter_item + price = filters["PRICE_FILTER"] + lot = filters["LOT_SIZE"] + result: dict[str, object] = { + "venue": "binance_spot", + "symbol": symbol, + "status": _text(item.get("status"), f"{symbol} exchangeInfo status"), + "base_asset": _text(item.get("baseAsset"), f"{symbol} exchangeInfo baseAsset"), + "quote_asset": _text(item.get("quoteAsset"), f"{symbol} exchangeInfo quoteAsset"), + "tick_size": _decimal(price.get("tickSize"), f"{symbol} tickSize", positive=True), + "lot_size": _decimal(lot.get("stepSize"), f"{symbol} stepSize", positive=True), + "min_price": _decimal(price.get("minPrice"), f"{symbol} minPrice"), + "max_price": _decimal(price.get("maxPrice"), f"{symbol} maxPrice"), + "min_quantity": _decimal(lot.get("minQty"), f"{symbol} minQty"), + "max_quantity": _decimal(lot.get("maxQty"), f"{symbol} maxQty"), + } + if result["status"] != "TRADING": + raise M8AcquisitionError(f"{symbol} exchangeInfo status is not TRADING") + except _M8MetadataResponseContractError: + raise + except M8AcquisitionError as exc: + raise _M8MetadataResponseContractError(str(exc)) from exc + except KeyError as exc: + raise _M8MetadataResponseContractError( + f"{symbol} exchangeInfo lacks a frozen filter" + ) from exc + _assert_snapshot_path(path, snapshot, label) + return result + + +def _verify_metadata_files(root: Path, metadata: M8RawSymbolMetadata) -> None: + if _SAFE_SYMBOL.fullmatch(metadata.symbol) is None: + raise M8AcquisitionError("M8 metadata symbol is unsafe") + if metadata.venue != "binance_spot": + raise M8AcquisitionError(f"{metadata.symbol} metadata venue is not binance_spot") + if metadata.observed_ts_ns < 1: + raise M8AcquisitionError(f"{metadata.symbol} metadata observation time is invalid") + _verify_exchange_info_uri(metadata.source_uri, metadata.symbol) + expected_raw = ( + f"{_RAW_ROOT_NAME}/binance_spot/exchange_info/{metadata.symbol}/{metadata.raw_sha256}.json" + ) + _expected_raw_path(root, expected_raw, metadata.raw_path, f"{metadata.symbol} metadata body") + _verify_file( + metadata.raw_path, + metadata.raw_sha256, + metadata.raw_bytes, + f"{metadata.symbol} metadata body", + ) + _verify_file( + metadata.source_manifest_path, + metadata.source_manifest_sha256, + metadata.source_manifest_bytes, + f"{metadata.symbol} metadata source sidecar", + ) + sidecar = _verify_source_sidecar( + metadata.source_manifest_path, + body_path=metadata.raw_path, + body_sha256=metadata.raw_sha256, + body_bytes=metadata.raw_bytes, + expected_source="binance_spot_public_api", + expected_source_uri=metadata.source_uri, + expected_range=(None, None), + expected_upstream=None, + label=f"{metadata.symbol} metadata source sidecar", + ) + if ( + _utc_ns(sidecar["downloaded_at_utc"], f"{metadata.symbol} metadata timestamp") + != metadata.observed_ts_ns + ): + raise M8AcquisitionError(f"{metadata.symbol} observed time differs from raw sidecar") + observed = _metadata_payload_values( + metadata.raw_path, + metadata.symbol, + expected_sha256=metadata.raw_sha256, + expected_bytes=metadata.raw_bytes, + ) + expected: dict[str, object] = { + "venue": metadata.venue, + "symbol": metadata.symbol, + "status": metadata.status, + "base_asset": metadata.base_asset, + "quote_asset": metadata.quote_asset, + "tick_size": metadata.tick_size, + "lot_size": metadata.lot_size, + "min_price": metadata.min_price, + "max_price": metadata.max_price, + "min_quantity": metadata.min_quantity, + "max_quantity": metadata.max_quantity, + } + if observed != expected: + raise M8AcquisitionError(f"{metadata.symbol} parsed metadata differs from raw exchangeInfo") + + +def _raw_metadata_from_symbol_metadata( + root: Path, + metadata: SymbolMetadata, + expected_symbol: str, +) -> M8RawSymbolMetadata: + if metadata.symbol != expected_symbol: + raise M8AcquisitionError( + f"metadata provider returned {metadata.symbol!r} for {expected_symbol}" + ) + raw_path = metadata.source_path.resolve() + sidecar_path = metadata.source_manifest_path.resolve() + raw_sha = sha256_file(raw_path) + sidecar_sha = sha256_file(sidecar_path) + sidecar = _read_json(sidecar_path, f"{expected_symbol} source sidecar") + source_uri = _text(sidecar.get("source_uri"), f"{expected_symbol} source URI") + result = M8RawSymbolMetadata( + venue=metadata.venue, + symbol=metadata.symbol, + status=metadata.status, + base_asset=metadata.base_asset, + quote_asset=metadata.quote_asset, + tick_size=metadata.tick_size, + lot_size=metadata.lot_size, + min_price=metadata.min_price, + max_price=metadata.max_price, + min_quantity=metadata.min_quantity, + max_quantity=metadata.max_quantity, + observed_ts_ns=metadata.observed_ts_ns, + raw_path=raw_path, + raw_sha256=raw_sha, + raw_bytes=raw_path.stat().st_size, + source_uri=source_uri, + source_manifest_path=sidecar_path, + source_manifest_sha256=sidecar_sha, + source_manifest_bytes=sidecar_path.stat().st_size, + ) + if metadata.source_artifact_id != raw_sha: + raise M8AcquisitionError(f"{expected_symbol} metadata artifact ID is not its raw SHA") + _verify_metadata_files(root, result) + return result + + +def _verify_archive_entry_files(entry: M8RawArchiveEntry) -> None: + label = f"{entry.symbol}/{entry.date.isoformat()}" + if entry.csv_member_opened or entry.economic_fields_inspected: + raise M8AcquisitionError(f"{label} raw authority claims an economic-data inspection") + if entry.tick_size <= 0 or entry.lot_size <= 0: + raise M8AcquisitionError(f"{label} archive scales must be positive") + archive_name = f"{entry.symbol}-aggTrades-{entry.date.isoformat()}.zip" + expected_member = archive_name.removesuffix(".zip") + ".csv" + if entry.member_name != expected_member: + raise M8AcquisitionError(f"{label} archive declares an unexpected CSV member") + archive_uri = _expected_archive_uri(entry.symbol, entry.date) + checksum_uri = _expected_archive_uri(entry.symbol, entry.date, checksum=True) + _verify_official_uri(entry.archive_source_uri, archive_uri, f"{label} archive URI") + _verify_official_uri(entry.checksum_source_uri, checksum_uri, f"{label} checksum URI") + expected_archive_path = ( + f"{_RAW_ROOT_NAME}/binance_spot/daily_agg_trades_archive/{entry.symbol}/" + f"{entry.date.isoformat()}/{archive_name}" + ) + expected_checksum_path = ( + f"{_RAW_ROOT_NAME}/binance_spot/daily_agg_trades_archive_checksums/{entry.symbol}/" + f"{entry.date.isoformat()}/{archive_name}.CHECKSUM" + ) + _expected_raw_path(entry.root, expected_archive_path, entry.archive_path, f"{label} ZIP") + _expected_raw_path(entry.root, expected_checksum_path, entry.checksum_path, f"{label} CHECKSUM") + _verify_file(entry.archive_path, entry.archive_sha256, entry.archive_bytes, f"{label} ZIP") + _verify_file( + entry.archive_source_manifest_path, + entry.archive_source_manifest_sha256, + entry.archive_source_manifest_bytes, + f"{label} ZIP source sidecar", + ) + _verify_file( + entry.checksum_path, entry.checksum_sha256, entry.checksum_bytes, f"{label} CHECKSUM" + ) + _verify_file( + entry.checksum_source_manifest_path, + entry.checksum_source_manifest_sha256, + entry.checksum_source_manifest_bytes, + f"{label} CHECKSUM source sidecar", + ) + if entry.archive_bytes < 1 or entry.archive_bytes > entry.max_compressed_bytes: + raise M8AcquisitionError(f"{label} compressed archive exceeds its hard ceiling") + if entry.checksum_bytes < 1 or entry.checksum_bytes > entry.max_checksum_bytes: + raise M8AcquisitionError(f"{label} checksum response exceeds its hard ceiling") + upstream = _parse_checksum_body(entry.checksum_path, archive_name) + if upstream != entry.upstream_sha256 or upstream != entry.archive_sha256: + raise M8AcquisitionError(f"{label} official CHECKSUM does not authenticate the ZIP") + observed_expanded = _zip_directory_member( + entry.archive_path, + expected_member, + entry.max_uncompressed_bytes, + ) + if observed_expanded != entry.declared_uncompressed_bytes: + raise M8AcquisitionError(f"{label} ZIP declared expansion changed") + day_range = _day_bounds_ns(entry.date) + _verify_source_sidecar( + entry.archive_source_manifest_path, + body_path=entry.archive_path, + body_sha256=entry.archive_sha256, + body_bytes=entry.archive_bytes, + expected_source="binance_spot_daily_aggtrades_archive", + expected_source_uri=entry.archive_source_uri, + expected_range=day_range, + expected_upstream=entry.archive_sha256, + label=f"{label} ZIP source sidecar", + ) + _verify_source_sidecar( + entry.checksum_source_manifest_path, + body_path=entry.checksum_path, + body_sha256=entry.checksum_sha256, + body_bytes=entry.checksum_bytes, + expected_source="binance_spot_daily_aggtrades_archive_checksum", + expected_source_uri=entry.checksum_source_uri, + expected_range=day_range, + expected_upstream=None, + label=f"{label} CHECKSUM source sidecar", + ) + + +def _raw_entry_from_acquired( + root: Path, + acquired: AcquiredDailyArchive, + *, + role: M8PeriodRole, + expected_symbol: str, + expected_date: Date, + limits: ArchiveDownloadLimits, +) -> M8RawArchiveEntry: + request = acquired.request + if request.symbol != expected_symbol or request.date != expected_date: + raise M8AcquisitionError("archive provider returned a different symbol/date") + if acquired.limits != limits: + raise M8AcquisitionError("archive provider returned different byte ceilings") + archive = acquired.archive_artifact + checksum = acquired.checksum_artifact + entry = M8RawArchiveEntry( + root=root, + symbol=request.symbol, + date=request.date, + role=role, + tick_size=request.tick_size, + lot_size=request.lot_size, + archive_path=archive.path.resolve(), + archive_sha256=archive.sha256, + archive_bytes=archive.bytes, + archive_source_uri=archive.source_uri, + archive_source_manifest_path=archive.manifest_path.resolve(), + archive_source_manifest_sha256=archive.manifest_sha256, + archive_source_manifest_bytes=archive.manifest_path.stat().st_size, + checksum_path=checksum.path.resolve(), + checksum_sha256=checksum.sha256, + checksum_bytes=checksum.bytes, + checksum_source_uri=checksum.source_uri, + checksum_source_manifest_path=checksum.manifest_path.resolve(), + checksum_source_manifest_sha256=checksum.manifest_sha256, + checksum_source_manifest_bytes=checksum.manifest_path.stat().st_size, + upstream_sha256=acquired.upstream_sha256, + member_name=request.member_name, + declared_uncompressed_bytes=acquired.declared_uncompressed_bytes, + max_compressed_bytes=limits.max_compressed_bytes, + max_uncompressed_bytes=limits.max_uncompressed_bytes, + max_checksum_bytes=limits.max_checksum_bytes, + transfer_chunk_bytes=limits.transfer_chunk_bytes, + max_csv_line_bytes=limits.max_csv_line_bytes, + ) + _verify_archive_entry_files(entry) + return entry + + +_METADATA_KEYS = frozenset( + { + "base_asset", + "lot_size", + "max_price", + "max_quantity", + "min_price", + "min_quantity", + "observed_ts_ns", + "quote_asset", + "raw_bytes", + "raw_path", + "raw_sha256", + "source_manifest_bytes", + "source_manifest_path", + "source_manifest_sha256", + "source_uri", + "status", + "symbol", + "tick_size", + "venue", + } +) +_ARCHIVE_KEYS = frozenset( + { + "archive_bytes", + "archive_path", + "archive_sha256", + "archive_source_manifest_bytes", + "archive_source_manifest_path", + "archive_source_manifest_sha256", + "archive_source_uri", + "checksum_bytes", + "checksum_path", + "checksum_sha256", + "checksum_source_manifest_bytes", + "checksum_source_manifest_path", + "checksum_source_manifest_sha256", + "checksum_source_uri", + "csv_member_opened", + "date", + "declared_uncompressed_bytes", + "economic_fields_inspected", + "lot_size", + "max_checksum_bytes", + "max_compressed_bytes", + "max_csv_line_bytes", + "max_uncompressed_bytes", + "member_name", + "role", + "symbol", + "tick_size", + "transfer_chunk_bytes", + "upstream_sha256", + } +) +_RETAINED_KEYS = frozenset({"bytes", "kind", "paired_body_path", "path", "sha256", "source_uri"}) +_TOP_LEVEL_KEYS = frozenset( + { + "archives", + "artifact_kind", + "config", + "copied_from_manifest_sha256", + "evidence_set_sha256", + "outcome_boundary", + "retained_artifacts", + "schema_version", + "symbol_metadata", + "totals", + } +) +_FAILURE_TOP_LEVEL_KEYS = frozenset( + { + "artifact_kind", + "completed", + "config", + "diagnostic", + "failed", + "outcome_boundary", + "reason_code", + "remaining", + "retained_artifacts", + "retained_inventory_sha256", + "schema_version", + "status", + "terminal_marker", + "totals", + } +) +_FAILURE_STEP_KEYS = frozenset({"date", "kind", "role", "symbol"}) +_FAILURE_TOTAL_KEYS = frozenset( + { + "completed_count", + "declared_step_count", + "remaining_count", + "retained_artifact_count", + "total_raw_evidence_bytes", + } +) +_FAILURE_REASON_CODES: frozenset[str] = frozenset( + { + "DECLARED_OBJECT_UNAVAILABLE", + "METADATA_CONTRACT", + "CHECKSUM_CONTRACT", + "ZIP_CONTRACT", + "RESPONSE_SIZE_LIMIT", + "TOTAL_EVIDENCE_BUDGET", + } +) + + +def _metadata_payload(root: Path, metadata: M8RawSymbolMetadata) -> dict[str, object]: + return { + "venue": metadata.venue, + "symbol": metadata.symbol, + "status": metadata.status, + "base_asset": metadata.base_asset, + "quote_asset": metadata.quote_asset, + "tick_size": _format_decimal(metadata.tick_size), + "lot_size": _format_decimal(metadata.lot_size), + "min_price": _format_decimal(metadata.min_price), + "max_price": _format_decimal(metadata.max_price), + "min_quantity": _format_decimal(metadata.min_quantity), + "max_quantity": _format_decimal(metadata.max_quantity), + "observed_ts_ns": metadata.observed_ts_ns, + "raw_path": _relative(root, metadata.raw_path, f"{metadata.symbol} metadata body"), + "raw_sha256": metadata.raw_sha256, + "raw_bytes": metadata.raw_bytes, + "source_uri": metadata.source_uri, + "source_manifest_path": _relative( + root, + metadata.source_manifest_path, + f"{metadata.symbol} metadata source sidecar", + ), + "source_manifest_sha256": metadata.source_manifest_sha256, + "source_manifest_bytes": metadata.source_manifest_bytes, + } + + +def _archive_payload(root: Path, entry: M8RawArchiveEntry) -> dict[str, object]: + return { + "symbol": entry.symbol, + "date": entry.date.isoformat(), + "role": entry.role, + "tick_size": _format_decimal(entry.tick_size), + "lot_size": _format_decimal(entry.lot_size), + "archive_path": _relative(root, entry.archive_path, f"{entry.symbol}/{entry.date} ZIP"), + "archive_sha256": entry.archive_sha256, + "archive_bytes": entry.archive_bytes, + "archive_source_uri": entry.archive_source_uri, + "archive_source_manifest_path": _relative( + root, + entry.archive_source_manifest_path, + f"{entry.symbol}/{entry.date} ZIP source sidecar", + ), + "archive_source_manifest_sha256": entry.archive_source_manifest_sha256, + "archive_source_manifest_bytes": entry.archive_source_manifest_bytes, + "checksum_path": _relative( + root, + entry.checksum_path, + f"{entry.symbol}/{entry.date} CHECKSUM", + ), + "checksum_sha256": entry.checksum_sha256, + "checksum_bytes": entry.checksum_bytes, + "checksum_source_uri": entry.checksum_source_uri, + "checksum_source_manifest_path": _relative( + root, + entry.checksum_source_manifest_path, + f"{entry.symbol}/{entry.date} CHECKSUM source sidecar", + ), + "checksum_source_manifest_sha256": entry.checksum_source_manifest_sha256, + "checksum_source_manifest_bytes": entry.checksum_source_manifest_bytes, + "upstream_sha256": entry.upstream_sha256, + "member_name": entry.member_name, + "declared_uncompressed_bytes": entry.declared_uncompressed_bytes, + "max_compressed_bytes": entry.max_compressed_bytes, + "max_uncompressed_bytes": entry.max_uncompressed_bytes, + "max_checksum_bytes": entry.max_checksum_bytes, + "transfer_chunk_bytes": entry.transfer_chunk_bytes, + "max_csv_line_bytes": entry.max_csv_line_bytes, + "csv_member_opened": entry.csv_member_opened, + "economic_fields_inspected": entry.economic_fields_inspected, + } + + +def _retained_payload(artifact: M8RetainedArtifact) -> dict[str, object]: + return { + "path": artifact.path, + "sha256": artifact.sha256, + "bytes": artifact.bytes, + "kind": artifact.kind, + "source_uri": artifact.source_uri, + "paired_body_path": artifact.paired_body_path, + } + + +def _config_payload(config: M8StudyConfig, protocol_sha256: str) -> dict[str, object]: + return { + "study_name": config.study.name, + "protocol_version": config.study.protocol_version, + "protocol_document_sha256": protocol_sha256, + "config_sha256": config.hash, + "config_source_sha256": config.source_sha256, + "evidence_tier": config.study.evidence_tier, + "source": config.study.source, + "symbols": list(config.study.symbols), + "periods": [ + {"date": period.date.isoformat(), "role": period.role} for period in config.periods + ], + "byte_limits": { + "max_archive_compressed_bytes": config.study.max_archive_compressed_bytes, + "max_archive_uncompressed_bytes": config.study.max_archive_uncompressed_bytes, + "max_total_download_bytes": config.study.max_total_download_bytes, + "max_checksum_bytes": 4_096, + "transfer_chunk_bytes": 64 * 1_024, + "max_csv_line_bytes": 16 * 1_024, + "max_metadata_response_bytes": 8 * 1024 * 1024, + }, + } + + +def _evidence_payload( + *, + config: M8StudyConfig, + protocol_sha256: str, + root: Path, + metadata: Sequence[M8RawSymbolMetadata], + archives: Sequence[M8RawArchiveEntry], + retained: Sequence[M8RetainedArtifact], +) -> dict[str, object]: + total_raw = sum(item.bytes for item in retained) + total_zip = sum(item.archive_bytes for item in archives) + return { + "config": _config_payload(config, protocol_sha256), + "outcome_boundary": { + "acquisition_mode": "raw_only", + "csv_member_opened": False, + "economic_fields_inspected": False, + "permitted_zip_inspection": "end_of_central_directory_and_directory_metadata_only", + }, + "symbol_metadata": [_metadata_payload(root, item) for item in metadata], + "archives": [_archive_payload(root, item) for item in archives], + "retained_artifacts": [_retained_payload(item) for item in retained], + "totals": { + "metadata_count": len(metadata), + "archive_count": len(archives), + "retained_artifact_count": len(retained), + "total_raw_evidence_bytes": total_raw, + "total_accepted_zip_bytes": total_zip, + }, + } + + +def _manifest_payload( + *, + config: M8StudyConfig, + protocol_sha256: str, + root: Path, + metadata: Sequence[M8RawSymbolMetadata], + archives: Sequence[M8RawArchiveEntry], + retained: Sequence[M8RetainedArtifact], + copied_from_manifest_sha256: str | None, +) -> dict[str, object]: + evidence = _evidence_payload( + config=config, + protocol_sha256=protocol_sha256, + root=root, + metadata=metadata, + archives=archives, + retained=retained, + ) + evidence_identity = hashlib.sha256(_canonical_json_bytes(evidence)).hexdigest() + return { + "schema_version": M8_ACQUISITION_SCHEMA_VERSION, + "artifact_kind": "m8_raw_acquisition_manifest", + "copied_from_manifest_sha256": copied_from_manifest_sha256, + "evidence_set_sha256": evidence_identity, + **evidence, + } + + +def _fsync_directory(path: Path) -> None: + descriptor = os.open(path, os.O_RDONLY) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + + +def _fsync_tree(root: Path) -> None: + """Durably flush every regular file and directory without following links.""" + + if root.is_symlink() or not root.is_dir(): + raise M8AcquisitionError(f"durability root is missing or symbolic: {root}") + nofollow = getattr(os, "O_NOFOLLOW", 0) + try: + for directory_name, directory_names, file_names in os.walk( + root.resolve(), + topdown=False, + followlinks=False, + ): + directory = Path(directory_name) + for child_name in directory_names: + child = directory / child_name + if child.is_symlink() or not child.is_dir(): + raise M8AcquisitionError( + f"durability tree contains a non-directory or symlink: {child}" + ) + for file_name in file_names: + path = directory / file_name + if path.is_symlink() or not stat.S_ISREG(path.lstat().st_mode): + raise M8AcquisitionError( + f"durability tree contains a non-regular file or symlink: {path}" + ) + descriptor = os.open(path, os.O_RDONLY | nofollow) + try: + if not stat.S_ISREG(os.fstat(descriptor).st_mode): + raise M8AcquisitionError( + f"durability tree entry changed while opened: {path}" + ) + os.fsync(descriptor) + finally: + os.close(descriptor) + _fsync_directory(directory) + except M8AcquisitionError: + raise + except OSError as exc: + raise M8AcquisitionError(f"cannot durably flush acquisition tree: {root}") from exc + + +def _write_manifest_payload(root: Path, payload: Mapping[str, Any]) -> tuple[Path, str]: + encoded = _canonical_json_bytes(payload) + digest = hashlib.sha256(encoded).hexdigest() + directory = root / _MANIFEST_DIRECTORY_NAME + directory.mkdir(parents=True, exist_ok=True) + _fsync_directory(root) + destination = directory / f"m8-acquisition.manifest-{digest[:20]}.json" + if destination.exists(): + observed = _read_bounded_regular_bytes( + destination, + "existing M8 acquisition manifest", + byte_limit=_MAX_MANIFEST_BYTES, + ) + if destination.is_symlink() or observed != encoded: + raise M8AcquisitionError(f"immutable M8 acquisition manifest collision: {destination}") + return destination.resolve(), digest + descriptor, temporary_name = tempfile.mkstemp( + dir=directory, + prefix=".m8-acquisition.", + suffix=".tmp", + ) + temporary = Path(temporary_name) + try: + with os.fdopen(descriptor, "wb") as sink: + sink.write(encoded) + sink.flush() + os.fsync(sink.fileno()) + os.replace(temporary, destination) + _fsync_directory(directory) + except BaseException: + temporary.unlink(missing_ok=True) + raise + return destination.resolve(), digest + + +def _parse_metadata(root: Path, value: object, expected_symbol: str) -> M8RawSymbolMetadata: + raw = _object(value, f"symbol_metadata[{expected_symbol}]") + _require_exact_keys(raw, _METADATA_KEYS, f"symbol_metadata[{expected_symbol}]") + symbol = _text(raw["symbol"], "metadata symbol") + if symbol != expected_symbol: + raise M8AcquisitionError("M8 metadata is outside the frozen symbol order") + metadata = M8RawSymbolMetadata( + venue=_text(raw["venue"], f"{symbol}.venue"), + symbol=symbol, + status=_text(raw["status"], f"{symbol}.status"), + base_asset=_text(raw["base_asset"], f"{symbol}.base_asset"), + quote_asset=_text(raw["quote_asset"], f"{symbol}.quote_asset"), + tick_size=_decimal(raw["tick_size"], f"{symbol}.tick_size", positive=True), + lot_size=_decimal(raw["lot_size"], f"{symbol}.lot_size", positive=True), + min_price=_decimal(raw["min_price"], f"{symbol}.min_price"), + max_price=_decimal(raw["max_price"], f"{symbol}.max_price"), + min_quantity=_decimal(raw["min_quantity"], f"{symbol}.min_quantity"), + max_quantity=_decimal(raw["max_quantity"], f"{symbol}.max_quantity"), + observed_ts_ns=_integer(raw["observed_ts_ns"], f"{symbol}.observed_ts_ns", minimum=1), + raw_path=_declared_file(root, raw["raw_path"], f"{symbol} metadata body"), + raw_sha256=_digest(raw["raw_sha256"], f"{symbol} metadata SHA"), + raw_bytes=_integer(raw["raw_bytes"], f"{symbol} metadata bytes", minimum=1), + source_uri=_text(raw["source_uri"], f"{symbol} metadata source URI"), + source_manifest_path=_declared_file( + root, + raw["source_manifest_path"], + f"{symbol} metadata source sidecar", + ), + source_manifest_sha256=_digest( + raw["source_manifest_sha256"], + f"{symbol} metadata sidecar SHA", + ), + source_manifest_bytes=_integer( + raw["source_manifest_bytes"], + f"{symbol} metadata sidecar bytes", + minimum=1, + ), + ) + _verify_metadata_files(root, metadata) + return metadata + + +def _parse_archive( + root: Path, + value: object, + *, + expected_symbol: str, + expected_date: Date, + expected_role: M8PeriodRole, + config: M8StudyConfig, +) -> M8RawArchiveEntry: + label = f"{expected_symbol}/{expected_date.isoformat()}" + raw = _object(value, f"archives[{label}]") + _require_exact_keys(raw, _ARCHIVE_KEYS, f"archives[{label}]") + symbol = _text(raw["symbol"], f"{label}.symbol") + try: + day = Date.fromisoformat(_text(raw["date"], f"{label}.date")) + except ValueError as exc: + raise M8AcquisitionError(f"{label}.date is not canonical ISO") from exc + role = _text(raw["role"], f"{label}.role") + if (symbol, day, role) != (expected_symbol, expected_date, expected_role): + raise M8AcquisitionError(f"{label} raw archive is outside the frozen order") + if role not in {"train", "validation", "primary_test", "replication_test"}: + raise M8AcquisitionError(f"{label} raw archive role is unsupported") + entry = M8RawArchiveEntry( + root=root, + symbol=symbol, + date=day, + role=cast(M8PeriodRole, role), + tick_size=_decimal(raw["tick_size"], f"{label}.tick_size", positive=True), + lot_size=_decimal(raw["lot_size"], f"{label}.lot_size", positive=True), + archive_path=_declared_file(root, raw["archive_path"], f"{label} ZIP"), + archive_sha256=_digest(raw["archive_sha256"], f"{label} ZIP SHA"), + archive_bytes=_integer(raw["archive_bytes"], f"{label} ZIP bytes", minimum=1), + archive_source_uri=_text(raw["archive_source_uri"], f"{label} ZIP URI"), + archive_source_manifest_path=_declared_file( + root, + raw["archive_source_manifest_path"], + f"{label} ZIP source sidecar", + ), + archive_source_manifest_sha256=_digest( + raw["archive_source_manifest_sha256"], + f"{label} ZIP source sidecar SHA", + ), + archive_source_manifest_bytes=_integer( + raw["archive_source_manifest_bytes"], + f"{label} ZIP source sidecar bytes", + minimum=1, + ), + checksum_path=_declared_file(root, raw["checksum_path"], f"{label} CHECKSUM"), + checksum_sha256=_digest(raw["checksum_sha256"], f"{label} CHECKSUM SHA"), + checksum_bytes=_integer(raw["checksum_bytes"], f"{label} CHECKSUM bytes", minimum=1), + checksum_source_uri=_text(raw["checksum_source_uri"], f"{label} CHECKSUM URI"), + checksum_source_manifest_path=_declared_file( + root, + raw["checksum_source_manifest_path"], + f"{label} CHECKSUM source sidecar", + ), + checksum_source_manifest_sha256=_digest( + raw["checksum_source_manifest_sha256"], + f"{label} CHECKSUM source sidecar SHA", + ), + checksum_source_manifest_bytes=_integer( + raw["checksum_source_manifest_bytes"], + f"{label} CHECKSUM source sidecar bytes", + minimum=1, + ), + upstream_sha256=_digest(raw["upstream_sha256"], f"{label} upstream SHA"), + member_name=_text(raw["member_name"], f"{label} member name"), + declared_uncompressed_bytes=_integer( + raw["declared_uncompressed_bytes"], + f"{label} expanded bytes", + minimum=1, + ), + max_compressed_bytes=_integer( + raw["max_compressed_bytes"], + f"{label} max compressed bytes", + minimum=1, + ), + max_uncompressed_bytes=_integer( + raw["max_uncompressed_bytes"], + f"{label} max expanded bytes", + minimum=1, + ), + max_checksum_bytes=_integer( + raw["max_checksum_bytes"], + f"{label} max checksum bytes", + minimum=1, + ), + transfer_chunk_bytes=_integer( + raw["transfer_chunk_bytes"], + f"{label} transfer chunk bytes", + minimum=1, + ), + max_csv_line_bytes=_integer( + raw["max_csv_line_bytes"], + f"{label} max CSV line bytes", + minimum=1, + ), + csv_member_opened=_boolean(raw["csv_member_opened"], f"{label}.csv_member_opened"), + economic_fields_inspected=_boolean( + raw["economic_fields_inspected"], + f"{label}.economic_fields_inspected", + ), + ) + expected_limits = ( + config.study.max_archive_compressed_bytes, + config.study.max_archive_uncompressed_bytes, + 4_096, + 64 * 1_024, + 16 * 1_024, + ) + observed_limits = ( + entry.max_compressed_bytes, + entry.max_uncompressed_bytes, + entry.max_checksum_bytes, + entry.transfer_chunk_bytes, + entry.max_csv_line_bytes, + ) + if observed_limits != expected_limits: + raise M8AcquisitionError(f"{label} archive byte ceilings differ from frozen config") + _verify_archive_entry_files(entry) + return entry + + +def _parse_retained(value: object, index: int) -> M8RetainedArtifact: + label = f"retained_artifacts[{index}]" + raw = _object(value, label) + _require_exact_keys(raw, _RETAINED_KEYS, label) + kind = _text(raw["kind"], f"{label}.kind") + allowed = { + "metadata_body", + "archive_zip", + "archive_checksum", + "rejected_prefix", + "source_manifest", + } + if kind not in allowed: + raise M8AcquisitionError(f"{label}.kind is unsupported") + paired_raw = raw["paired_body_path"] + paired = None if paired_raw is None else _text(paired_raw, f"{label}.paired_body_path") + return M8RetainedArtifact( + path=_text(raw["path"], f"{label}.path"), + sha256=_digest(raw["sha256"], f"{label}.sha256"), + bytes=_integer(raw["bytes"], f"{label}.bytes", minimum=0), + kind=cast(RetainedArtifactKind, kind), + source_uri=_text(raw["source_uri"], f"{label}.source_uri"), + paired_body_path=paired, + ) + + +def _walk_raw_files(root: Path) -> tuple[Path, ...]: + raw_root = root / _RAW_ROOT_NAME + if raw_root.is_symlink() or not raw_root.is_dir(): + raise M8AcquisitionError("M8 acquisition raw root is missing or symbolic") + pending = [raw_root] + files: list[Path] = [] + try: + while pending: + directory = pending.pop() + with os.scandir(directory) as entries: + for item in entries: + path = Path(item.path) + if item.is_symlink(): + raise M8AcquisitionError( + f"symbolic links are forbidden in raw evidence: {path}" + ) + if item.is_dir(follow_symlinks=False): + pending.append(path) + elif item.is_file(follow_symlinks=False): + if ( + item.name.endswith(".tmp") + or item.name.startswith(".download-") + or item.name.startswith(".raw-") + ): + raise M8AcquisitionError( + f"unpaired temporary file remains in raw evidence: {path}" + ) + files.append(path.resolve()) + else: + raise M8AcquisitionError( + f"non-regular raw evidence entry is forbidden: {path}" + ) + except M8AcquisitionError: + raise + except OSError as exc: + raise M8AcquisitionError("cannot enumerate retained M8 raw evidence") from exc + return tuple(sorted(files, key=lambda item: item.relative_to(root).as_posix())) + + +def _is_rejected_path(root: Path, path: Path) -> bool: + relative = path.relative_to(root) + return any(component.endswith("_rejected") for component in relative.parts) + + +def _historical_metadata_symbol(root: Path, path: Path, source_uri: str) -> str | None: + relative = path.relative_to(root).parts + if len(relative) < 5 or relative[:3] != ( + _RAW_ROOT_NAME, + "binance_spot", + "exchange_info", + ): + return None + symbol = relative[3] + try: + _verify_exchange_info_uri(source_uri, symbol) + except M8AcquisitionError: + return None + return symbol + + +def _common_sidecar_pair(root: Path, sidecar_path: Path) -> tuple[Path, str]: + label = f"retained source sidecar {sidecar_path.relative_to(root).as_posix()}" + sidecar = _read_json(sidecar_path, label) + _require_exact_keys(sidecar, _RAW_SIDECAR_KEYS, label) + if sidecar["manifest_version"] != "1.0.0" or sidecar["artifact_kind"] != "raw_source": + raise M8AcquisitionError(f"{label} identity is unsupported") + body_name = _text(sidecar["path"], f"{label}.path") + if Path(body_name).name != body_name: + raise M8AcquisitionError(f"{label} names a non-basename raw body") + body_path = (sidecar_path.parent / body_name).resolve() + if not body_path.is_relative_to((root / _RAW_ROOT_NAME).resolve()) or not body_path.is_file(): + raise M8AcquisitionError(f"{label} has no contained paired raw body") + checksum = _object(sidecar["checksum"], f"{label}.checksum") + _require_exact_keys(checksum, frozenset({"algorithm", "value"}), f"{label}.checksum") + body_sha = _digest(checksum["value"], f"{label}.checksum.value") + body_bytes = _integer(sidecar["bytes"], f"{label}.bytes", minimum=0) + if checksum["algorithm"] != "sha256": + raise M8AcquisitionError(f"{label} uses a non-SHA-256 checksum") + _verify_file(body_path, body_sha, body_bytes, f"{label} paired raw body") + requested = _object(sidecar["requested_range_ns"], f"{label}.requested_range_ns") + _require_exact_keys( + requested, + frozenset({"start", "end_exclusive"}), + f"{label}.requested_range_ns", + ) + start = requested["start"] + end = requested["end_exclusive"] + if (start is None) != (end is None): + raise M8AcquisitionError(f"{label} requested range is half-null") + if start is not None: + start_value = _integer(start, f"{label}.requested_range_ns.start") + end_value = _integer(end, f"{label}.requested_range_ns.end_exclusive") + if end_value <= start_value: + raise M8AcquisitionError(f"{label} requested range is empty") + upstream = sidecar["upstream_checksum_sha256"] + if upstream is not None: + _digest(upstream, f"{label}.upstream_checksum_sha256") + headers = _object(sidecar["response_headers"], f"{label}.response_headers") + if not all(type(key) is str and type(value) is str for key, value in headers.items()): + raise M8AcquisitionError(f"{label} response headers must contain only strings") + _utc_ns(sidecar["downloaded_at_utc"], f"{label}.downloaded_at_utc") + _text(sidecar["source"], f"{label}.source") + source_uri = _text(sidecar["source_uri"], f"{label}.source_uri") + _source_manifest_path_is_canonical(body_path, sidecar_path, label) + _verify_source_manifest_identity(body_path, sidecar_path, sidecar, label) + return body_path, source_uri + + +def _scan_retained_inventory( + root: Path, + metadata: Sequence[M8RawSymbolMetadata], + archives: Sequence[M8RawArchiveEntry], +) -> tuple[M8RetainedArtifact, ...]: + """Enumerate every physical raw file and reject unpaired or extra accepted data.""" + + files = _walk_raw_files(root) + accepted_bodies: dict[Path, tuple[RetainedArtifactKind, str]] = {} + accepted_sidecars: dict[Path, tuple[Path, str]] = {} + for metadata_item in metadata: + accepted_bodies[metadata_item.raw_path] = ("metadata_body", metadata_item.source_uri) + accepted_sidecars[metadata_item.source_manifest_path] = ( + metadata_item.raw_path, + metadata_item.source_uri, + ) + for archive_item in archives: + accepted_bodies[archive_item.archive_path] = ( + "archive_zip", + archive_item.archive_source_uri, + ) + accepted_bodies[archive_item.checksum_path] = ( + "archive_checksum", + archive_item.checksum_source_uri, + ) + accepted_sidecars[archive_item.archive_source_manifest_path] = ( + archive_item.archive_path, + archive_item.archive_source_uri, + ) + accepted_sidecars[archive_item.checksum_source_manifest_path] = ( + archive_item.checksum_path, + archive_item.checksum_source_uri, + ) + if len(accepted_bodies) != len(metadata) + 2 * len(archives): + raise M8AcquisitionError("accepted raw bodies are not physically distinct") + if len(accepted_sidecars) != len(metadata) + 2 * len(archives): + raise M8AcquisitionError("accepted source sidecars are not physically distinct") + + sidecar_pairs: dict[Path, tuple[Path, str]] = {} + references: dict[Path, list[tuple[Path, str]]] = {} + for path in files: + if _SOURCE_MANIFEST_NAME.fullmatch(path.name) is None: + continue + pair = _common_sidecar_pair(root, path) + sidecar_pairs[path] = pair + references.setdefault(pair[0], []).append((path, pair[1])) + + artifacts: list[M8RetainedArtifact] = [] + for path in files: + relative = path.relative_to(root).as_posix() + if path in sidecar_pairs: + body_path, source_uri = sidecar_pairs[path] + expected = accepted_sidecars.get(path) + if expected is None: + accepted_body = accepted_bodies.get(body_path) + historical_symbol = _historical_metadata_symbol(root, body_path, source_uri) + if ( + accepted_body is not None and accepted_body[1] == source_uri + ) or historical_symbol in {item.symbol for item in metadata}: + pass + elif not _is_rejected_path(root, path) or not _is_rejected_path(root, body_path): + raise M8AcquisitionError(f"unexpected accepted source sidecar: {relative}") + elif expected != (body_path, source_uri): + raise M8AcquisitionError(f"accepted source sidecar changed pairing: {relative}") + artifacts.append( + M8RetainedArtifact( + path=relative, + sha256=sha256_file(path), + bytes=path.stat().st_size, + kind="source_manifest", + source_uri=source_uri, + paired_body_path=body_path.relative_to(root).as_posix(), + ) + ) + continue + + paired = references.get(path, []) + if not paired: + raise M8AcquisitionError(f"unpaired retained raw body: {relative}") + source_uris = {source_uri for _, source_uri in paired} + if len(source_uris) != 1: + raise M8AcquisitionError(f"retained raw body has ambiguous source URIs: {relative}") + source_uri = next(iter(source_uris)) + accepted = accepted_bodies.get(path) + kind: RetainedArtifactKind + if accepted is None: + if not _is_rejected_path(root, path): + historical_symbol = _historical_metadata_symbol(root, path, source_uri) + if historical_symbol not in {item.symbol for item in metadata}: + raise M8AcquisitionError(f"unexpected extra accepted raw body: {relative}") + kind = "metadata_body" + else: + kind = "rejected_prefix" + else: + kind, expected_uri = accepted + if source_uri != expected_uri: + raise M8AcquisitionError(f"accepted raw body changed source URI: {relative}") + artifacts.append( + M8RetainedArtifact( + path=relative, + sha256=sha256_file(path), + bytes=path.stat().st_size, + kind=kind, + source_uri=source_uri, + paired_body_path=None, + ) + ) + + if set(accepted_bodies) - set(files) or set(accepted_sidecars) - set(files): + raise M8AcquisitionError("accepted M8 raw evidence is missing from retained inventory") + return tuple(sorted(artifacts, key=lambda item: item.path)) + + +def _failure_body_kind(root: Path, path: Path, source_uri: str) -> RetainedArtifactKind: + """Classify a partial body without parsing metadata or opening a ZIP member.""" + + if _is_rejected_path(root, path): + return "rejected_prefix" + parts = path.relative_to(root).parts + if len(parts) == 5 and parts[:3] == ( + _RAW_ROOT_NAME, + "binance_spot", + "exchange_info", + ): + symbol = parts[3] + if _SAFE_SYMBOL.fullmatch(symbol) is None or parts[4] != f"{sha256_file(path)}.json": + raise M8AcquisitionError("partial metadata body is not content-addressed canonically") + _verify_exchange_info_uri(source_uri, symbol) + return "metadata_body" + if len(parts) == 6 and parts[:2] == (_RAW_ROOT_NAME, "binance_spot"): + dataset, symbol, date_text, filename = parts[2:] + if _SAFE_SYMBOL.fullmatch(symbol) is None: + raise M8AcquisitionError("partial archive body has an unsafe symbol") + try: + day = Date.fromisoformat(date_text) + except ValueError as exc: + raise M8AcquisitionError("partial archive body has a noncanonical date") from exc + archive_name = f"{symbol}-aggTrades-{date_text}.zip" + if dataset == "daily_agg_trades_archive" and filename == archive_name: + _verify_official_uri(source_uri, _expected_archive_uri(symbol, day), "partial ZIP URI") + return "archive_zip" + if ( + dataset == "daily_agg_trades_archive_checksums" + and filename == f"{archive_name}.CHECKSUM" + ): + _verify_official_uri( + source_uri, + _expected_archive_uri(symbol, day, checksum=True), + "partial CHECKSUM URI", + ) + return "archive_checksum" + raise M8AcquisitionError( + f"unexpected accepted partial raw body: {path.relative_to(root).as_posix()}" + ) + + +def _scan_failure_retained_inventory(root: Path) -> tuple[M8RetainedArtifact, ...]: + """Enumerate a raw-only partial attempt without interpreting economic bytes.""" + + files = _walk_raw_files(root) + sidecar_pairs: dict[Path, tuple[Path, str]] = {} + references: dict[Path, list[tuple[Path, str]]] = {} + for path in files: + if _SOURCE_MANIFEST_NAME.fullmatch(path.name) is None: + continue + pair = _common_sidecar_pair(root, path) + sidecar_pairs[path] = pair + references.setdefault(pair[0], []).append((path, pair[1])) + + artifacts: list[M8RetainedArtifact] = [] + for path in files: + relative = path.relative_to(root).as_posix() + if path in sidecar_pairs: + body_path, source_uri = sidecar_pairs[path] + _failure_body_kind(root, body_path, source_uri) + artifacts.append( + M8RetainedArtifact( + path=relative, + sha256=sha256_file(path), + bytes=path.stat().st_size, + kind="source_manifest", + source_uri=source_uri, + paired_body_path=body_path.relative_to(root).as_posix(), + ) + ) + continue + paired = references.get(path, []) + if not paired: + raise M8AcquisitionError(f"unpaired retained partial body: {relative}") + source_uris = {source_uri for _, source_uri in paired} + if len(source_uris) != 1: + raise M8AcquisitionError(f"partial raw body has ambiguous source URIs: {relative}") + source_uri = next(iter(source_uris)) + artifacts.append( + M8RetainedArtifact( + path=relative, + sha256=sha256_file(path), + bytes=path.stat().st_size, + kind=_failure_body_kind(root, path, source_uri), + source_uri=source_uri, + paired_body_path=None, + ) + ) + return tuple(sorted(artifacts, key=lambda item: item.path)) + + +def _retained_inventory_sha256(retained: Sequence[M8RetainedArtifact]) -> str: + payload = {"retained_artifacts": [_retained_payload(item) for item in retained]} + return hashlib.sha256(_canonical_json_bytes(payload)).hexdigest() + + +def _verify_manifest_config( + raw: object, + config: M8StudyConfig, + protocol_sha256: str, +) -> None: + observed = _object(raw, "M8 acquisition config binding") + expected = _config_payload(config, protocol_sha256) + if observed != expected: + raise M8AcquisitionError("M8 acquisition manifest is bound to another protocol/config") + + +def _manifest_evidence_object(payload: Mapping[str, Any]) -> dict[str, object]: + return { + "config": payload["config"], + "outcome_boundary": payload["outcome_boundary"], + "symbol_metadata": payload["symbol_metadata"], + "archives": payload["archives"], + "retained_artifacts": payload["retained_artifacts"], + "totals": payload["totals"], + } + + +def _acquisition_steps(config: M8StudyConfig) -> tuple[M8AcquisitionStep, ...]: + metadata = tuple( + M8AcquisitionStep(kind="metadata", symbol=symbol, date=None, role="metadata") + for symbol in config.study.symbols + ) + archives = tuple( + M8AcquisitionStep( + kind="archive", + symbol=symbol, + date=period.date, + role=period.role, + ) + for period in config.periods + for symbol in config.study.symbols + ) + return metadata + archives + + +def _step_payload(step: M8AcquisitionStep) -> dict[str, object]: + return { + "kind": step.kind, + "symbol": step.symbol, + "date": None if step.date is None else step.date.isoformat(), + "role": step.role, + } + + +def _parse_failure_step(value: object, label: str) -> M8AcquisitionStep: + raw = _object(value, label) + _require_exact_keys(raw, _FAILURE_STEP_KEYS, label) + kind = _text(raw["kind"], f"{label}.kind") + if kind not in {"metadata", "archive"}: + raise M8AcquisitionError(f"{label}.kind is unsupported") + symbol = _text(raw["symbol"], f"{label}.symbol") + if _SAFE_SYMBOL.fullmatch(symbol) is None: + raise M8AcquisitionError(f"{label}.symbol is unsafe") + role = _text(raw["role"], f"{label}.role") + date_raw = raw["date"] + if kind == "metadata": + if date_raw is not None or role != "metadata": + raise M8AcquisitionError(f"{label} metadata coordinates are invalid") + day = None + else: + if type(date_raw) is not str: + raise M8AcquisitionError(f"{label}.date must be a canonical date") + try: + day = Date.fromisoformat(date_raw) + except ValueError as exc: + raise M8AcquisitionError(f"{label}.date is invalid") from exc + if day.isoformat() != date_raw: + raise M8AcquisitionError(f"{label}.date is noncanonical") + return M8AcquisitionStep( + kind=cast(M8AcquisitionStepKind, kind), + symbol=symbol, + date=day, + role=role, + ) + + +def _failure_payload( + *, + config: M8StudyConfig, + protocol_sha256: str, + reason_code: M8AcquisitionReasonCode, + diagnostic: str, + failed: M8AcquisitionStep, + completed: Sequence[M8AcquisitionStep], + remaining: Sequence[M8AcquisitionStep], + retained: Sequence[M8RetainedArtifact], +) -> dict[str, object]: + inventory_sha = _retained_inventory_sha256(retained) + return { + "schema_version": M8_ACQUISITION_SCHEMA_VERSION, + "artifact_kind": "m8_raw_acquisition_failure", + "status": "INSUFFICIENT_DATA", + "terminal_marker": _FAILURE_TERMINAL_NAME, + "config": _config_payload(config, protocol_sha256), + "outcome_boundary": { + "acquisition_mode": "raw_only", + "csv_member_opened": False, + "economic_fields_inspected": False, + "terminal_before_csv_open": True, + }, + "reason_code": reason_code, + "diagnostic": diagnostic, + "failed": _step_payload(failed), + "completed": [_step_payload(step) for step in completed], + "remaining": [_step_payload(step) for step in remaining], + "retained_artifacts": [_retained_payload(item) for item in retained], + "retained_inventory_sha256": inventory_sha, + "totals": { + "completed_count": len(completed), + "remaining_count": len(remaining), + "declared_step_count": len(completed) + 1 + len(remaining), + "retained_artifact_count": len(retained), + "total_raw_evidence_bytes": sum(item.bytes for item in retained), + }, + } + + +def _failure_checksums_bytes( + manifest_sha256: str, + retained: Sequence[M8RetainedArtifact], +) -> bytes: + marker_sha = hashlib.sha256(_FAILURE_TERMINAL_BYTES).hexdigest() + lines = [ + f"{manifest_sha256} {_FAILURE_MANIFEST_NAME}", + f"{marker_sha} {_FAILURE_TERMINAL_NAME}", + ] + lines.extend(f"{item.sha256} ../../{item.path}" for item in retained) + return ("\n".join(lines) + "\n").encode("utf-8") + + +def _write_new_durable_file(path: Path, content: bytes) -> None: + descriptor = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644) + with os.fdopen(descriptor, "wb") as sink: + sink.write(content) + sink.flush() + os.fsync(sink.fileno()) + _fsync_directory(path.parent) + + +def _publish_failure_authority( + root: Path, + *, + payload: Mapping[str, Any], + retained: Sequence[M8RetainedArtifact], + config: M8StudyConfig, +) -> M8AcquisitionFailureManifest: + encoded = _canonical_json_bytes(payload) + manifest_sha = hashlib.sha256(encoded).hexdigest() + attempt_root = root / _ATTEMPT_DIRECTORY_NAME + attempt_root.mkdir(parents=True, exist_ok=True) + _fsync_directory(root) + destination = attempt_root / f"m8-acquisition-attempt-{manifest_sha[:20]}" + if destination.exists(): + return read_m8_acquisition_failure( + destination / _FAILURE_MANIFEST_NAME, + expected_sha256=manifest_sha, + config=config, + ) + stage = Path(tempfile.mkdtemp(prefix=".m8-acquisition-attempt-", dir=attempt_root)) + try: + _write_new_durable_file(stage / _FAILURE_MANIFEST_NAME, encoded) + checksums = _failure_checksums_bytes(manifest_sha, retained) + _write_new_durable_file(stage / _FAILURE_CHECKSUMS_NAME, checksums) + _write_new_durable_file(stage / _FAILURE_TERMINAL_NAME, _FAILURE_TERMINAL_BYTES) + _fsync_tree(stage) + try: + os.replace(stage, destination) + except OSError: + if not destination.is_dir(): + raise + _fsync_directory(attempt_root) + _fsync_directory(root) + return read_m8_acquisition_failure( + destination / _FAILURE_MANIFEST_NAME, + expected_sha256=manifest_sha, + config=config, + ) + finally: + if stage.exists(): + shutil.rmtree(stage) + + +def read_m8_acquisition_manifest( + path: str | Path, + *, + expected_sha256: str, + config: M8StudyConfig, +) -> M8AcquisitionManifest: + """Verify one explicitly named raw manifest; never discover or open a CSV.""" + + expected_digest = _digest(expected_sha256, "expected acquisition manifest SHA-256") + explicit = Path(path).expanduser().absolute() + if explicit.is_symlink() or not explicit.is_file(): + raise M8AcquisitionError("explicit M8 acquisition manifest is missing or symbolic") + name_match = _MANIFEST_NAME.fullmatch(explicit.name) + if name_match is None or name_match.group(1) != expected_digest[:20]: + raise M8AcquisitionError("M8 acquisition manifest filename is not content-addressed") + if explicit.parent.name != _MANIFEST_DIRECTORY_NAME: + raise M8AcquisitionError("M8 acquisition manifest is outside canonical manifest storage") + root = explicit.parent.parent + if root.is_symlink() or not root.is_dir(): + raise M8AcquisitionError("M8 acquisition root is missing or symbolic") + _validate_root_layout(root) + manifest_snapshot = _read_bounded_regular_snapshot( + explicit, + "M8 acquisition manifest", + byte_limit=_MAX_MANIFEST_BYTES, + ) + manifest_bytes = manifest_snapshot.content + observed_digest = hashlib.sha256(manifest_bytes).hexdigest() + if observed_digest != expected_digest: + raise M8AcquisitionError("M8 acquisition manifest bytes disagree with supplied SHA-256") + payload = _parse_json_bytes(manifest_bytes, "M8 acquisition manifest") + if manifest_bytes != _canonical_json_bytes(payload): + raise M8AcquisitionError("M8 acquisition manifest is not canonical JSON") + _require_exact_keys(payload, _TOP_LEVEL_KEYS, "M8 acquisition manifest") + if ( + payload["schema_version"] != M8_ACQUISITION_SCHEMA_VERSION + or payload["artifact_kind"] != "m8_raw_acquisition_manifest" + ): + raise M8AcquisitionError("M8 acquisition manifest identity is unsupported") + protocol_sha = _verify_config_sources(config) + _verify_manifest_config(payload["config"], config, protocol_sha) + boundary = _object(payload["outcome_boundary"], "M8 outcome boundary") + expected_boundary = { + "acquisition_mode": "raw_only", + "csv_member_opened": False, + "economic_fields_inspected": False, + "permitted_zip_inspection": "end_of_central_directory_and_directory_metadata_only", + } + if boundary != expected_boundary: + raise M8AcquisitionError("M8 acquisition boundary permits economic-data inspection") + copied_raw = payload["copied_from_manifest_sha256"] + copied_from = None if copied_raw is None else _digest(copied_raw, "copied-from manifest SHA") + evidence_identity = _digest(payload["evidence_set_sha256"], "M8 evidence-set SHA") + recomputed_identity = hashlib.sha256( + _canonical_json_bytes(_manifest_evidence_object(payload)) + ).hexdigest() + if evidence_identity != recomputed_identity: + raise M8AcquisitionError("M8 acquisition evidence-set identity does not match claims") + + raw_metadata = _array(payload["symbol_metadata"], "M8 symbol metadata") + if len(raw_metadata) != 2 or len(raw_metadata) != len(config.study.symbols): + raise M8AcquisitionError("M8 acquisition requires exactly two metadata responses") + metadata = tuple( + _parse_metadata(root, value, symbol) + for value, symbol in zip(raw_metadata, config.study.symbols, strict=True) + ) + raw_archives = _array(payload["archives"], "M8 raw archives") + expected_order = tuple( + (symbol, period.date, period.role) + for period in config.periods + for symbol in config.study.symbols + ) + if len(raw_archives) != 8 or len(raw_archives) != len(expected_order): + raise M8AcquisitionError("M8 acquisition requires exactly eight raw archives") + archives = tuple( + _parse_archive( + root, + value, + expected_symbol=symbol, + expected_date=day, + expected_role=role, + config=config, + ) + for value, (symbol, day, role) in zip(raw_archives, expected_order, strict=True) + ) + metadata_by_symbol = {item.symbol: item for item in metadata} + if any( + item.tick_size != metadata_by_symbol[item.symbol].tick_size + or item.lot_size != metadata_by_symbol[item.symbol].lot_size + for item in archives + ): + raise M8AcquisitionError("archive tick/lot scales differ from verified symbol metadata") + + raw_retained = _array(payload["retained_artifacts"], "M8 retained inventory") + retained = tuple(_parse_retained(value, index) for index, value in enumerate(raw_retained)) + if tuple(item.path for item in retained) != tuple(sorted(item.path for item in retained)): + raise M8AcquisitionError("M8 retained inventory is not in canonical path order") + if len({item.path for item in retained}) != len(retained): + raise M8AcquisitionError("M8 retained inventory repeats a physical path") + observed_inventory = _scan_retained_inventory(root, metadata, archives) + if retained != observed_inventory: + raise M8AcquisitionError("M8 retained inventory differs from physical raw evidence") + total_raw = sum(item.bytes for item in retained) + total_zip = sum(item.archive_bytes for item in archives) + totals = _object(payload["totals"], "M8 acquisition totals") + expected_totals = { + "metadata_count": 2, + "archive_count": 8, + "retained_artifact_count": len(retained), + "total_raw_evidence_bytes": total_raw, + "total_accepted_zip_bytes": total_zip, + } + if totals != expected_totals: + raise M8AcquisitionError("M8 acquisition totals disagree with exact retained inventory") + if total_raw > config.study.max_total_download_bytes: + raise M8AcquisitionError("M8 retained raw evidence exceeds frozen total-byte ceiling") + _assert_snapshot_path(explicit, manifest_snapshot, "M8 acquisition manifest") + return M8AcquisitionManifest( + root=root.resolve(), + path=explicit, + sha256=expected_digest, + config_sha256=config.hash, + config_source_sha256=config.source_sha256, + protocol_version=config.study.protocol_version, + protocol_document_sha256=protocol_sha, + copied_from_manifest_sha256=copied_from, + evidence_set_sha256=evidence_identity, + symbol_metadata=metadata, + archives=archives, + retained_artifacts=retained, + total_raw_evidence_bytes=total_raw, + total_accepted_zip_bytes=total_zip, + config=config, + ) + + +def read_m8_acquisition_failure( + path: str | Path, + *, + expected_sha256: str, + config: M8StudyConfig, +) -> M8AcquisitionFailureManifest: + """Verify one immutable deterministic acquisition failure without opening CSV.""" + + expected_digest = _digest(expected_sha256, "expected acquisition failure SHA-256") + explicit = Path(path).expanduser().absolute() + if ( + explicit.name != _FAILURE_MANIFEST_NAME + or explicit.parent.parent.name != _ATTEMPT_DIRECTORY_NAME + ): + raise M8AcquisitionError("M8 acquisition failure is outside canonical attempt storage") + attempt_match = _FAILURE_ATTEMPT_NAME.fullmatch(explicit.parent.name) + if attempt_match is None or attempt_match.group(1) != expected_digest[:20]: + raise M8AcquisitionError("M8 acquisition attempt directory is not content-addressed") + root = explicit.parent.parent.parent + if root.is_symlink() or not root.is_dir(): + raise M8AcquisitionError("M8 acquisition failure root is missing or symbolic") + _validate_root_layout(root) + manifest_snapshot = _read_bounded_regular_snapshot( + explicit, + "M8 acquisition failure manifest", + byte_limit=_MAX_MANIFEST_BYTES, + ) + manifest_bytes = manifest_snapshot.content + observed_digest = hashlib.sha256(manifest_bytes).hexdigest() + if observed_digest != expected_digest: + raise M8AcquisitionError("M8 acquisition failure bytes disagree with supplied SHA-256") + payload = _parse_json_bytes(manifest_bytes, "M8 acquisition failure manifest") + if manifest_bytes != _canonical_json_bytes(payload): + raise M8AcquisitionError("M8 acquisition failure manifest is not canonical JSON") + _require_exact_keys(payload, _FAILURE_TOP_LEVEL_KEYS, "M8 acquisition failure manifest") + if ( + payload["schema_version"] != M8_ACQUISITION_SCHEMA_VERSION + or payload["artifact_kind"] != "m8_raw_acquisition_failure" + or payload["status"] != "INSUFFICIENT_DATA" + or payload["terminal_marker"] != _FAILURE_TERMINAL_NAME + ): + raise M8AcquisitionError("M8 acquisition failure identity is unsupported") + protocol_sha = _verify_config_sources(config) + _verify_manifest_config(payload["config"], config, protocol_sha) + expected_boundary = { + "acquisition_mode": "raw_only", + "csv_member_opened": False, + "economic_fields_inspected": False, + "terminal_before_csv_open": True, + } + if _object(payload["outcome_boundary"], "M8 failure outcome boundary") != expected_boundary: + raise M8AcquisitionError("M8 acquisition failure crosses the raw-only boundary") + reason_text = _text(payload["reason_code"], "M8 acquisition failure reason code") + if reason_text not in _FAILURE_REASON_CODES: + raise M8AcquisitionError("M8 acquisition failure reason code is unsupported") + reason_code = cast(M8AcquisitionReasonCode, reason_text) + diagnostic = _text(payload["diagnostic"], "M8 acquisition failure diagnostic") + if diagnostic.strip() != diagnostic or "\n" in diagnostic or "\r" in diagnostic: + raise M8AcquisitionError("M8 acquisition failure diagnostic is noncanonical") + + failed = _parse_failure_step(payload["failed"], "M8 acquisition failed step") + completed = tuple( + _parse_failure_step(value, f"M8 acquisition completed[{index}]") + for index, value in enumerate(_array(payload["completed"], "M8 completed steps")) + ) + remaining = tuple( + _parse_failure_step(value, f"M8 acquisition remaining[{index}]") + for index, value in enumerate(_array(payload["remaining"], "M8 remaining steps")) + ) + declared_steps = _acquisition_steps(config) + if (*completed, failed, *remaining) != declared_steps: + raise M8AcquisitionError("M8 acquisition failure steps do not partition frozen order") + + retained = tuple( + _parse_retained(value, index) + for index, value in enumerate( + _array(payload["retained_artifacts"], "M8 failure retained inventory") + ) + ) + if tuple(item.path for item in retained) != tuple(sorted(item.path for item in retained)): + raise M8AcquisitionError("M8 failure retained inventory is not in canonical order") + if len({item.path for item in retained}) != len(retained): + raise M8AcquisitionError("M8 failure retained inventory repeats a path") + observed_inventory = _scan_failure_retained_inventory(root) + observed_by_path = {item.path: item for item in observed_inventory} + if any(observed_by_path.get(item.path) != item for item in retained): + raise M8AcquisitionError("M8 failure inventory differs from retained physical evidence") + inventory_sha = _digest( + payload["retained_inventory_sha256"], + "M8 failure retained-inventory SHA", + ) + if inventory_sha != _retained_inventory_sha256(retained): + raise M8AcquisitionError("M8 failure retained-inventory SHA disagrees with claims") + total_raw = sum(item.bytes for item in retained) + totals = _object(payload["totals"], "M8 acquisition failure totals") + _require_exact_keys(totals, _FAILURE_TOTAL_KEYS, "M8 acquisition failure totals") + expected_totals = { + "completed_count": len(completed), + "remaining_count": len(remaining), + "declared_step_count": len(declared_steps), + "retained_artifact_count": len(retained), + "total_raw_evidence_bytes": total_raw, + } + if totals != expected_totals: + raise M8AcquisitionError("M8 acquisition failure totals disagree with inventory") + if reason_code != "TOTAL_EVIDENCE_BUDGET" and total_raw > config.study.max_total_download_bytes: + raise M8AcquisitionError("M8 failure retained evidence exceeds frozen byte ceiling") + + terminal_path = explicit.parent / _FAILURE_TERMINAL_NAME + terminal_snapshot = _read_bounded_regular_snapshot( + terminal_path, + "M8 acquisition failure terminal marker", + byte_limit=len(_FAILURE_TERMINAL_BYTES), + ) + if terminal_snapshot.content != _FAILURE_TERMINAL_BYTES: + raise M8AcquisitionError("M8 acquisition failure terminal marker bytes are invalid") + checksums_path = explicit.parent / _FAILURE_CHECKSUMS_NAME + checksums_snapshot = _read_bounded_regular_snapshot( + checksums_path, + "M8 acquisition failure checksums", + byte_limit=_MAX_MANIFEST_BYTES, + ) + checksums_bytes = checksums_snapshot.content + if checksums_bytes != _failure_checksums_bytes(expected_digest, retained): + raise M8AcquisitionError("M8 acquisition failure checksum manifest is invalid") + checksums_sha = hashlib.sha256(checksums_bytes).hexdigest() + _assert_snapshot_path(explicit, manifest_snapshot, "M8 acquisition failure manifest") + _assert_snapshot_path( + checksums_path, + checksums_snapshot, + "M8 acquisition failure checksums", + ) + _assert_snapshot_path( + terminal_path, + terminal_snapshot, + "M8 acquisition failure terminal marker", + ) + return M8AcquisitionFailureManifest( + root=root, + attempt_dir=explicit.parent, + path=explicit, + sha256=expected_digest, + checksums_path=checksums_path, + checksums_sha256=checksums_sha, + terminal_path=terminal_path, + reason_code=reason_code, + diagnostic=diagnostic, + failed_step=failed, + completed_steps=completed, + remaining_steps=remaining, + retained_artifacts=retained, + retained_inventory_sha256=inventory_sha, + total_raw_evidence_bytes=total_raw, + config=config, + ) + + +verify_m8_acquisition_manifest = read_m8_acquisition_manifest +verify_m8_acquisition_failure = read_m8_acquisition_failure + + +def _validate_root_layout(root: Path) -> None: + allowed = {_RAW_ROOT_NAME, _MANIFEST_DIRECTORY_NAME, _ATTEMPT_DIRECTORY_NAME} + try: + for child in root.iterdir(): + if child.is_symlink(): + raise M8AcquisitionError(f"symbolic link is forbidden in acquisition root: {child}") + if child.name not in allowed: + raise M8AcquisitionError(f"unexpected acquisition-root artifact: {child}") + if not child.is_dir(): + raise M8AcquisitionError(f"acquisition-root component is not a directory: {child}") + manifest_directory = root / _MANIFEST_DIRECTORY_NAME + if manifest_directory.exists(): + for child in manifest_directory.iterdir(): + if ( + child.is_symlink() + or not child.is_file() + or _MANIFEST_NAME.fullmatch(child.name) is None + ): + raise M8AcquisitionError( + f"unpaired or noncanonical acquisition manifest artifact: {child}" + ) + attempt_directory = root / _ATTEMPT_DIRECTORY_NAME + if attempt_directory.exists(): + for attempt in attempt_directory.iterdir(): + if ( + attempt.is_symlink() + or not attempt.is_dir() + or _FAILURE_ATTEMPT_NAME.fullmatch(attempt.name) is None + ): + raise M8AcquisitionError( + f"unpaired or noncanonical acquisition attempt artifact: {attempt}" + ) + observed_names: set[str] = set() + for child in attempt.iterdir(): + if child.is_symlink() or not child.is_file(): + raise M8AcquisitionError( + f"acquisition attempt contains a non-regular artifact: {child}" + ) + observed_names.add(child.name) + expected_names = { + _FAILURE_MANIFEST_NAME, + _FAILURE_CHECKSUMS_NAME, + _FAILURE_TERMINAL_NAME, + } + if observed_names != expected_names: + raise M8AcquisitionError( + f"acquisition attempt file set is noncanonical: {attempt}" + ) + except M8AcquisitionError: + raise + except OSError as exc: + raise M8AcquisitionError("cannot validate M8 acquisition-root layout") from exc + + +def _ordered_supplied_metadata( + supplied: Mapping[str, SymbolMetadata] | Sequence[SymbolMetadata], + symbols: tuple[str, ...], +) -> tuple[SymbolMetadata, ...]: + if isinstance(supplied, Mapping): + if set(supplied) != set(symbols): + raise M8AcquisitionError("supplied M8 metadata keys differ from frozen symbols") + return tuple(supplied[symbol] for symbol in symbols) + ordered = tuple(supplied) + if tuple(item.symbol for item in ordered) != symbols: + raise M8AcquisitionError("supplied M8 metadata is outside frozen symbol order") + return ordered + + +def _fetch_provider_metadata( + provider: _MetadataProvider | Callable[[str, Path], SymbolMetadata], + symbol: str, + raw_root: Path, +) -> SymbolMetadata: + method = getattr(provider, "fetch_exchange_info", None) + if callable(method): + result = method(symbol=symbol, raw_root=raw_root) + elif callable(provider): + result = provider(symbol, raw_root) + else: + raise M8AcquisitionError("metadata_provider has no supported fetch boundary") + if not isinstance(result, SymbolMetadata): + raise M8AcquisitionError("metadata_provider returned a non-SymbolMetadata value") + return result + + +def _deterministic_failure_reason(exc: BaseException) -> M8AcquisitionReasonCode | None: + if isinstance(exc, EvidenceBudgetExceeded): + return "TOTAL_EVIDENCE_BUDGET" + if isinstance(exc, (BinanceMetadataContractError, _M8MetadataResponseContractError)): + return "METADATA_CONTRACT" + if isinstance(exc, BinanceResponseSizeLimitError): + return "RESPONSE_SIZE_LIMIT" + if isinstance(exc, BinanceArchiveContractError): + return cast(M8AcquisitionReasonCode, exc.reason_code) + if ( + isinstance(exc, (BinanceHTTPError, BinanceArchiveHTTPError)) + and not exc.retry_exhausted + and exc.status_code in {404, 410} + ): + return "DECLARED_OBJECT_UNAVAILABLE" + return None + + +def _failure_diagnostic(exc: BaseException) -> str: + text = " ".join(str(exc).replace("\r", " ").replace("\n", " ").split()) + if not text: + text = type(exc).__name__ + return f"{type(exc).__name__}: {text}"[:2_000].rstrip() + + +def _finalize_deterministic_failure( + *, + root: Path, + raw_root: Path, + config: M8StudyConfig, + protocol_sha256: str, + reason_code: M8AcquisitionReasonCode, + cause: BaseException, + failed: M8AcquisitionStep, + completed: Sequence[M8AcquisitionStep], + remaining: Sequence[M8AcquisitionStep], + budget: RetainedEvidenceBudget | None, +) -> M8AcquisitionFailureResult: + if budget is not None and budget.reserved_bytes != 0: + raise M8AcquisitionError( + "cannot publish deterministic failure with unfinished evidence reservations" + ) from cause + retained = _scan_failure_retained_inventory(root) + _fsync_tree(raw_root) + durable_retained = _scan_failure_retained_inventory(root) + if durable_retained != retained: + raise M8AcquisitionError( + "raw inventory changed across failure durability barrier" + ) from cause + total_raw = sum(item.bytes for item in retained) + if reason_code != "TOTAL_EVIDENCE_BUDGET" and total_raw > config.study.max_total_download_bytes: + raise M8AcquisitionError( + "deterministic failure evidence exceeds frozen byte ceiling" + ) from cause + if budget is not None and budget.used_bytes != total_raw: + raise M8AcquisitionError( + "retained-evidence budget disagrees with failure inventory" + ) from cause + payload = _failure_payload( + config=config, + protocol_sha256=protocol_sha256, + reason_code=reason_code, + diagnostic=_failure_diagnostic(cause), + failed=failed, + completed=completed, + remaining=remaining, + retained=retained, + ) + authority = _publish_failure_authority( + root, + payload=payload, + retained=retained, + config=config, + ) + return M8AcquisitionFailureResult( + output_root=root.resolve(), + attempt_dir=authority.attempt_dir, + attempt_manifest_path=authority.path, + attempt_manifest_sha256=authority.sha256, + checksums_path=authority.checksums_path, + checksums_sha256=authority.checksums_sha256, + terminal_path=authority.terminal_path, + reason_code=authority.reason_code, + diagnostic=authority.diagnostic, + failed_symbol=authority.failed_step.symbol, + failed_date=authority.failed_step.date, + failed_role=authority.failed_step.role, + completed_count=len(authority.completed_steps), + remaining_count=len(authority.remaining_steps), + retained_inventory_sha256=authority.retained_inventory_sha256, + retained_artifact_count=len(authority.retained_artifacts), + total_raw_evidence_bytes=authority.total_raw_evidence_bytes, + manifest=authority, + ) + + +def acquire_m8_archives( + config: M8StudyConfig, + output_root: str | Path, + *, + archive_client: _ArchiveProvider | None = None, + metadata_provider: _MetadataProvider | Callable[[str, Path], SymbolMetadata] | None = None, + supplied_metadata: Mapping[str, SymbolMetadata] | Sequence[SymbolMetadata] | None = None, +) -> M8AcquisitionOutcome: + """Acquire the exact 2+8 raw authorities without opening a CSV member.""" + + if metadata_provider is not None and supplied_metadata is not None: + raise M8AcquisitionError("metadata_provider and supplied_metadata are mutually exclusive") + root = Path(output_root).expanduser().absolute() + if root.is_symlink(): + raise M8AcquisitionError("M8 acquisition output root must not be a symbolic link") + root.mkdir(parents=True, exist_ok=True) + _validate_root_layout(root) + raw_root = root / _RAW_ROOT_NAME + raw_root.mkdir(parents=True, exist_ok=True) + protocol_sha = _verify_config_sources(config) + steps = _acquisition_steps(config) + try: + budget = RetainedEvidenceBudget(raw_root, config.study.max_total_download_bytes) + except EvidenceBudgetExceeded as exc: + return _finalize_deterministic_failure( + root=root, + raw_root=raw_root, + config=config, + protocol_sha256=protocol_sha, + reason_code="TOTAL_EVIDENCE_BUDGET", + cause=exc, + failed=steps[0], + completed=(), + remaining=steps[1:], + budget=None, + ) + using_default_archive = archive_client is None + if archive_client is None: + archive_provider: _ArchiveProvider = BinanceArchiveClient(retained_evidence_budget=budget) + else: + archive_provider = archive_client + using_budgeted_metadata = supplied_metadata is not None or metadata_provider is None + if metadata_provider is None and supplied_metadata is None: + metadata_fetcher: _MetadataProvider | Callable[[str, Path], SymbolMetadata] = ( + BinancePublicClient(retained_evidence_budget=budget) + ) + elif metadata_provider is not None: + metadata_fetcher = metadata_provider + else: + metadata_fetcher = BinancePublicClient(retained_evidence_budget=budget) + + try: + ordered_supplied = ( + None + if supplied_metadata is None + else _ordered_supplied_metadata(supplied_metadata, config.study.symbols) + ) + completed_steps: list[M8AcquisitionStep] = [] + metadata_items: list[M8RawSymbolMetadata] = [] + for index, symbol in enumerate(config.study.symbols): + step = steps[len(completed_steps)] + try: + source_item = ( + _fetch_provider_metadata(metadata_fetcher, symbol, raw_root) + if ordered_supplied is None + else ordered_supplied[index] + ) + metadata_item = _raw_metadata_from_symbol_metadata(root, source_item, symbol) + except Exception as exc: + reason = _deterministic_failure_reason(exc) + if reason is None: + raise + return _finalize_deterministic_failure( + root=root, + raw_root=raw_root, + config=config, + protocol_sha256=protocol_sha, + reason_code=reason, + cause=exc, + failed=step, + completed=completed_steps, + remaining=steps[len(completed_steps) + 1 :], + budget=(budget if using_default_archive and using_budgeted_metadata else None), + ) + metadata_items.append(metadata_item) + completed_steps.append(step) + metadata = tuple(metadata_items) + metadata_by_symbol = MappingProxyType({item.symbol: item for item in metadata}) + limits = ArchiveDownloadLimits( + max_compressed_bytes=config.study.max_archive_compressed_bytes, + max_uncompressed_bytes=config.study.max_archive_uncompressed_bytes, + ) + archives: list[M8RawArchiveEntry] = [] + for period in config.periods: + for symbol in config.study.symbols: + symbol_metadata = metadata_by_symbol[symbol] + request = DailyArchiveRequest( + symbol=symbol, + date=period.date, + tick_size=symbol_metadata.tick_size, + lot_size=symbol_metadata.lot_size, + ) + step = steps[len(completed_steps)] + try: + acquired = archive_provider.acquire( + request, + raw_root=raw_root, + limits=limits, + ) + except Exception as exc: + reason = _deterministic_failure_reason(exc) + if reason is None: + raise + return _finalize_deterministic_failure( + root=root, + raw_root=raw_root, + config=config, + protocol_sha256=protocol_sha, + reason_code=reason, + cause=exc, + failed=step, + completed=completed_steps, + remaining=steps[len(completed_steps) + 1 :], + budget=( + budget if using_default_archive and using_budgeted_metadata else None + ), + ) + if not isinstance(acquired, AcquiredDailyArchive): + raise M8AcquisitionError( + "archive_client returned a non-AcquiredDailyArchive value" + ) + archives.append( + _raw_entry_from_acquired( + root, + acquired, + role=period.role, + expected_symbol=symbol, + expected_date=period.date, + limits=limits, + ) + ) + completed_steps.append(step) + retained = _scan_retained_inventory(root, metadata, archives) + total_raw = sum(item.bytes for item in retained) + if total_raw > config.study.max_total_download_bytes: + budget_failure = EvidenceBudgetExceeded( + "retained raw evidence exceeds the frozen total-byte ceiling" + ) + return _finalize_deterministic_failure( + root=root, + raw_root=raw_root, + config=config, + protocol_sha256=protocol_sha, + reason_code="TOTAL_EVIDENCE_BUDGET", + cause=budget_failure, + failed=steps[-1], + completed=steps[:-1], + remaining=(), + budget=None, + ) + if budget.reserved_bytes != 0: + raise M8AcquisitionError("retained-evidence budget has unfinished reservations") + if using_default_archive and using_budgeted_metadata and budget.used_bytes != total_raw: + raise M8AcquisitionError( + "shared retained-evidence budget disagrees with the physical inventory" + ) + _fsync_tree(raw_root) + durable_retained = _scan_retained_inventory(root, metadata, archives) + if durable_retained != retained: + raise M8AcquisitionError("raw inventory changed across success durability barrier") + retained = durable_retained + payload = _manifest_payload( + config=config, + protocol_sha256=protocol_sha, + root=root, + metadata=metadata, + archives=archives, + retained=retained, + copied_from_manifest_sha256=None, + ) + manifest_path, manifest_sha = _write_manifest_payload(root, payload) + if budget.used_bytes > config.study.max_total_download_bytes: + raise M8AcquisitionError("manifest publication changed the raw-evidence budget") + _validate_root_layout(root) + manifest = read_m8_acquisition_manifest( + manifest_path, + expected_sha256=manifest_sha, + config=config, + ) + except M8AcquisitionError: + raise + except Exception as exc: + raise M8AcquisitionError(f"M8 raw-only acquisition failed closed: {exc}") from exc + return M8AcquisitionResult( + output_root=root.resolve(), + manifest_path=manifest.path, + manifest_sha256=manifest.sha256, + metadata_count=manifest.metadata_count, + archive_count=manifest.archive_count, + total_raw_evidence_bytes=manifest.total_raw_evidence_bytes, + manifest=manifest, + ) + + +def _atomic_copy_exact( + source: Path, + destination: Path, + *, + expected_sha256: str, + expected_bytes: int, +) -> None: + if source.is_symlink() or not source.is_file(): + raise M8AcquisitionError(f"copy source is missing or symbolic: {source}") + destination.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary_name = tempfile.mkstemp( + dir=destination.parent, + prefix=f".{destination.name}.", + suffix=".tmp", + ) + temporary = Path(temporary_name) + try: + with source.open("rb") as source_handle, os.fdopen(descriptor, "wb") as sink: + shutil.copyfileobj(source_handle, sink, length=1024 * 1024) + sink.flush() + os.fsync(sink.fileno()) + _verify_file(temporary, expected_sha256, expected_bytes, "staged raw-evidence copy") + os.replace(temporary, destination) + _fsync_directory(destination.parent) + except BaseException: + temporary.unlink(missing_ok=True) + raise + + +def _rebased_evidence( + authority: M8AcquisitionManifest, + new_root: Path, +) -> tuple[tuple[M8RawSymbolMetadata, ...], tuple[M8RawArchiveEntry, ...]]: + metadata = tuple( + replace( + item, + raw_path=(new_root / item.raw_path.relative_to(authority.root)).resolve(), + source_manifest_path=( + new_root / item.source_manifest_path.relative_to(authority.root) + ).resolve(), + ) + for item in authority.symbol_metadata + ) + archives = tuple( + replace( + item, + root=new_root.resolve(), + archive_path=(new_root / item.archive_path.relative_to(authority.root)).resolve(), + archive_source_manifest_path=( + new_root / item.archive_source_manifest_path.relative_to(authority.root) + ).resolve(), + checksum_path=(new_root / item.checksum_path.relative_to(authority.root)).resolve(), + checksum_source_manifest_path=( + new_root / item.checksum_source_manifest_path.relative_to(authority.root) + ).resolve(), + ) + for item in authority.archives + ) + return metadata, archives + + +def _assert_distinct_copy_budget(total_raw_bytes: int, max_total_bytes: int) -> None: + if total_raw_bytes > max_total_bytes - total_raw_bytes: + raise M8AcquisitionError( + "external raw evidence plus its distinct self-contained copy exceeds the frozen " + "total-byte ceiling" + ) + + +def copy_m8_acquisition_into( + authority: M8AcquisitionManifest, + input_root: str | Path, +) -> M8AcquisitionManifest: + """Atomically copy the complete raw inventory into a self-contained input root.""" + + verified = read_m8_acquisition_manifest( + authority.path, + expected_sha256=authority.sha256, + config=authority.config, + ) + _assert_distinct_copy_budget( + verified.total_raw_evidence_bytes, + verified.config.study.max_total_download_bytes, + ) + destination = Path(input_root).expanduser().absolute() + source_root = verified.root.resolve() + destination_parent = destination.parent + destination_parent.mkdir(parents=True, exist_ok=True) + if destination.exists() or destination.is_symlink(): + raise M8AcquisitionError("self-contained M8 input root must not already exist") + destination_resolved = destination.resolve(strict=False) + if ( + destination_resolved == source_root + or destination_resolved.is_relative_to(source_root) + or source_root.is_relative_to(destination_resolved) + ): + raise M8AcquisitionError("M8 acquisition source and copy roots must not overlap") + stage = Path( + tempfile.mkdtemp(prefix=f".{destination.name}.copy-", dir=destination_parent) + ).resolve() + try: + for artifact in verified.retained_artifacts: + source = verified.root / artifact.path + target = stage / artifact.path + _atomic_copy_exact( + source, + target, + expected_sha256=artifact.sha256, + expected_bytes=artifact.bytes, + ) + metadata, archives = _rebased_evidence(verified, stage) + retained = _scan_retained_inventory(stage, metadata, archives) + if retained != verified.retained_artifacts: + raise M8AcquisitionError("self-contained copy inventory differs from authority") + _fsync_tree(stage / _RAW_ROOT_NAME) + durable_retained = _scan_retained_inventory(stage, metadata, archives) + if durable_retained != retained: + raise M8AcquisitionError("copied raw inventory changed across durability barrier") + retained = durable_retained + payload = _manifest_payload( + config=verified.config, + protocol_sha256=verified.protocol_document_sha256, + root=stage, + metadata=metadata, + archives=archives, + retained=retained, + copied_from_manifest_sha256=verified.sha256, + ) + stage_manifest_path, stage_manifest_sha = _write_manifest_payload(stage, payload) + _validate_root_layout(stage) + read_m8_acquisition_manifest( + stage_manifest_path, + expected_sha256=stage_manifest_sha, + config=verified.config, + ) + _fsync_tree(stage) + os.replace(stage, destination) + _fsync_directory(destination_parent) + final_manifest_path = destination / _MANIFEST_DIRECTORY_NAME / stage_manifest_path.name + copied = read_m8_acquisition_manifest( + final_manifest_path, + expected_sha256=stage_manifest_sha, + config=verified.config, + ) + if ( + copied.copied_from_manifest_sha256 != verified.sha256 + or copied.content_identity_sha256 != verified.content_identity_sha256 + or copied.retained_artifacts != verified.retained_artifacts + or copied.total_raw_evidence_bytes != verified.total_raw_evidence_bytes + or copied.total_accepted_zip_bytes != verified.total_accepted_zip_bytes + ): + raise M8AcquisitionError("self-contained acquisition copy is not source-equivalent") + return copied + except BaseException: + if stage.exists(): + shutil.rmtree(stage) + raise + + +__all__ = [ + "M8_ACQUISITION_SCHEMA_VERSION", + "M8AcquisitionError", + "M8AcquisitionFailureManifest", + "M8AcquisitionFailureResult", + "M8AcquisitionManifest", + "M8AcquisitionOutcome", + "M8AcquisitionReasonCode", + "M8AcquisitionResult", + "M8AcquisitionStep", + "M8RawArchiveDescriptor", + "M8RawArchiveEntry", + "M8RawSymbolMetadata", + "M8RetainedArtifact", + "acquire_m8_archives", + "copy_m8_acquisition_into", + "read_m8_acquisition_failure", + "read_m8_acquisition_manifest", + "verify_m8_acquisition_failure", + "verify_m8_acquisition_manifest", +] diff --git a/Microstructure/src/microstructure/m8_config.py b/Microstructure/src/microstructure/m8_config.py new file mode 100644 index 0000000000000000000000000000000000000000..8a4c42a673bbef10fdd10d2c673419811f8859bb --- /dev/null +++ b/Microstructure/src/microstructure/m8_config.py @@ -0,0 +1,528 @@ +"""Fail-closed parser for the frozen M8 multi-date trade study. + +This module intentionally does not reuse the exploratory sample configuration. +Protocol version 1.0.2 is a fixed, outcome-blind study contract: changing any +date, role, source, feature, model, safety ceiling, or claim permission requires +a new protocol version and corresponding parser review. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import tomllib +from collections.abc import Mapping +from dataclasses import dataclass +from datetime import date as Date +from pathlib import Path +from typing import Any, Literal, cast + +M8PeriodRole = Literal["train", "validation", "primary_test", "replication_test"] + +_TOP_LEVEL_KEYS = frozenset({"study", "periods", "features", "models", "quality", "claims"}) +_STUDY_KEYS = frozenset( + { + "name", + "protocol_version", + "evidence_tier", + "seed", + "source", + "symbols", + "selection_metric", + "target", + "label_horizon_events", + "calibration_fraction", + "bootstrap_samples", + "bootstrap_block_events", + "feature_stability_bins", + "max_archive_compressed_bytes", + "max_archive_uncompressed_bytes", + "max_total_download_bytes", + } +) +_PERIOD_KEYS = frozenset({"date", "role"}) +_FEATURE_KEYS = frozenset( + {"trade_windows", "volatility_window", "intensity_window", "large_trade_quantile"} +) +_MODEL_KEYS = frozenset({"logistic_c_values", "tree_max_depth_values", "tree_min_samples_leaf"}) +_QUALITY_KEYS = frozenset( + { + "fail_on_error", + "require_complete_daily_archive", + "require_contiguous_trade_ids_within_symbol_date", + "require_nondecreasing_event_time", + "allow_quality_warnings", + } +) +_CLAIM_KEYS = frozenset( + { + "allow_p_values", + "allow_significance_claim", + "allow_cross_instrument_pooling", + "allow_execution_claim", + "allow_profitability_claim", + } +) + +_FROZEN_PERIODS: tuple[tuple[str, M8PeriodRole], ...] = ( + ("2024-01-03", "train"), + ("2024-01-04", "validation"), + ("2024-01-05", "primary_test"), + ("2024-01-06", "replication_test"), +) +_FROZEN_SYMBOLS = ("BTCUSDT", "ETHUSDT") + + +class M8ConfigError(ValueError): + """Raised when an M8 study file violates its frozen protocol contract.""" + + +@dataclass(frozen=True, slots=True) +class M8Study: + name: str + protocol_version: str + evidence_tier: str + seed: int + source: str + symbols: tuple[str, ...] + selection_metric: str + target: str + label_horizon_events: int + calibration_fraction: float + bootstrap_samples: int + bootstrap_block_events: int + feature_stability_bins: int + max_archive_compressed_bytes: int + max_archive_uncompressed_bytes: int + max_total_download_bytes: int + + +@dataclass(frozen=True, slots=True) +class M8Period: + date: Date + role: M8PeriodRole + + +@dataclass(frozen=True, slots=True) +class M8Features: + trade_windows: tuple[int, ...] + volatility_window: int + intensity_window: int + large_trade_quantile: float + + +@dataclass(frozen=True, slots=True) +class M8Models: + logistic_c_values: tuple[float, ...] + tree_max_depth_values: tuple[int, ...] + tree_min_samples_leaf: int + + +@dataclass(frozen=True, slots=True) +class M8Quality: + fail_on_error: bool + require_complete_daily_archive: bool + require_contiguous_trade_ids_within_symbol_date: bool + require_nondecreasing_event_time: bool + allow_quality_warnings: bool + + +@dataclass(frozen=True, slots=True) +class M8Claims: + allow_p_values: bool + allow_significance_claim: bool + allow_cross_instrument_pooling: bool + allow_execution_claim: bool + allow_profitability_claim: bool + + +@dataclass(frozen=True, slots=True) +class M8StudyConfig: + """Typed, immutable representation of the frozen M8 study specification.""" + + path: Path + source_sha256: str + study: M8Study + periods: tuple[M8Period, ...] + features: M8Features + models: M8Models + quality: M8Quality + claims: M8Claims + + def _semantic_payload(self) -> dict[str, object]: + return { + "study": { + "name": self.study.name, + "protocol_version": self.study.protocol_version, + "evidence_tier": self.study.evidence_tier, + "seed": self.study.seed, + "source": self.study.source, + "symbols": list(self.study.symbols), + "selection_metric": self.study.selection_metric, + "target": self.study.target, + "label_horizon_events": self.study.label_horizon_events, + "calibration_fraction": self.study.calibration_fraction, + "bootstrap_samples": self.study.bootstrap_samples, + "bootstrap_block_events": self.study.bootstrap_block_events, + "feature_stability_bins": self.study.feature_stability_bins, + "max_archive_compressed_bytes": self.study.max_archive_compressed_bytes, + "max_archive_uncompressed_bytes": self.study.max_archive_uncompressed_bytes, + "max_total_download_bytes": self.study.max_total_download_bytes, + }, + "periods": [ + {"date": period.date.isoformat(), "role": period.role} for period in self.periods + ], + "features": { + "trade_windows": list(self.features.trade_windows), + "volatility_window": self.features.volatility_window, + "intensity_window": self.features.intensity_window, + "large_trade_quantile": self.features.large_trade_quantile, + }, + "models": { + "logistic_c_values": list(self.models.logistic_c_values), + "tree_max_depth_values": list(self.models.tree_max_depth_values), + "tree_min_samples_leaf": self.models.tree_min_samples_leaf, + }, + "quality": { + "fail_on_error": self.quality.fail_on_error, + "require_complete_daily_archive": self.quality.require_complete_daily_archive, + "require_contiguous_trade_ids_within_symbol_date": ( + self.quality.require_contiguous_trade_ids_within_symbol_date + ), + "require_nondecreasing_event_time": self.quality.require_nondecreasing_event_time, + "allow_quality_warnings": self.quality.allow_quality_warnings, + }, + "claims": { + "allow_p_values": self.claims.allow_p_values, + "allow_significance_claim": self.claims.allow_significance_claim, + "allow_cross_instrument_pooling": self.claims.allow_cross_instrument_pooling, + "allow_execution_claim": self.claims.allow_execution_claim, + "allow_profitability_claim": self.claims.allow_profitability_claim, + }, + } + + @property + def hash(self) -> str: + """Return a location- and formatting-independent semantic SHA-256.""" + + encoded = json.dumps( + self._semantic_payload(), + sort_keys=True, + separators=(",", ":"), + allow_nan=False, + ).encode("utf-8") + return hashlib.sha256(encoded).hexdigest() + + def public_dict(self) -> dict[str, object]: + """Return a JSON-safe representation with both semantic and byte hashes.""" + + return { + "path": str(self.path), + "config_sha256": self.hash, + "source_sha256": self.source_sha256, + **self._semantic_payload(), + } + + +def _mapping(value: object, label: str) -> Mapping[str, Any]: + if not isinstance(value, Mapping): + raise M8ConfigError(f"{label} must be a TOML table") + if not all(isinstance(key, str) for key in value): + raise M8ConfigError(f"{label} contains a non-string key") + return cast(Mapping[str, Any], value) + + +def _exact_keys(value: Mapping[str, Any], expected: frozenset[str], label: str) -> None: + observed = frozenset(value) + missing = sorted(expected - observed) + unknown = sorted(observed - expected) + if missing or unknown: + details: list[str] = [] + if missing: + details.append("missing=" + ",".join(missing)) + if unknown: + details.append("unknown=" + ",".join(unknown)) + raise M8ConfigError(f"{label} keys do not match the frozen contract ({'; '.join(details)})") + + +def _text(value: object, label: str) -> str: + if type(value) is not str: + raise M8ConfigError(f"{label} must be a string") + return value + + +def _integer(value: object, label: str) -> int: + if type(value) is not int: + raise M8ConfigError(f"{label} must be an integer") + return value + + +def _number(value: object, label: str) -> float: + if type(value) not in {int, float}: + raise M8ConfigError(f"{label} must be a finite number") + result = float(cast(int | float, value)) + if not math.isfinite(result): + raise M8ConfigError(f"{label} must be a finite number") + return result + + +def _boolean(value: object, label: str) -> bool: + if type(value) is not bool: + raise M8ConfigError(f"{label} must be a boolean") + return value + + +def _list(value: object, label: str) -> list[Any]: + if not isinstance(value, list): + raise M8ConfigError(f"{label} must be an array") + return value + + +def _text_tuple(value: object, label: str) -> tuple[str, ...]: + return tuple(_text(item, f"{label}[{index}]") for index, item in enumerate(_list(value, label))) + + +def _integer_tuple(value: object, label: str) -> tuple[int, ...]: + return tuple( + _integer(item, f"{label}[{index}]") for index, item in enumerate(_list(value, label)) + ) + + +def _number_tuple(value: object, label: str) -> tuple[float, ...]: + return tuple( + _number(item, f"{label}[{index}]") for index, item in enumerate(_list(value, label)) + ) + + +def _require_equal(observed: object, expected: object, label: str) -> None: + if observed != expected: + raise M8ConfigError(f"{label} is frozen at {expected!r}, observed {observed!r}") + + +def _parse_study(raw: object) -> M8Study: + table = _mapping(raw, "study") + _exact_keys(table, _STUDY_KEYS, "study") + study = M8Study( + name=_text(table["name"], "study.name"), + protocol_version=_text(table["protocol_version"], "study.protocol_version"), + evidence_tier=_text(table["evidence_tier"], "study.evidence_tier"), + seed=_integer(table["seed"], "study.seed"), + source=_text(table["source"], "study.source"), + symbols=_text_tuple(table["symbols"], "study.symbols"), + selection_metric=_text(table["selection_metric"], "study.selection_metric"), + target=_text(table["target"], "study.target"), + label_horizon_events=_integer(table["label_horizon_events"], "study.label_horizon_events"), + calibration_fraction=_number(table["calibration_fraction"], "study.calibration_fraction"), + bootstrap_samples=_integer(table["bootstrap_samples"], "study.bootstrap_samples"), + bootstrap_block_events=_integer( + table["bootstrap_block_events"], "study.bootstrap_block_events" + ), + feature_stability_bins=_integer( + table["feature_stability_bins"], "study.feature_stability_bins" + ), + max_archive_compressed_bytes=_integer( + table["max_archive_compressed_bytes"], "study.max_archive_compressed_bytes" + ), + max_archive_uncompressed_bytes=_integer( + table["max_archive_uncompressed_bytes"], "study.max_archive_uncompressed_bytes" + ), + max_total_download_bytes=_integer( + table["max_total_download_bytes"], "study.max_total_download_bytes" + ), + ) + if len(set(study.symbols)) != len(study.symbols): + raise M8ConfigError("study.symbols must be unique") + + expected: dict[str, object] = { + "name": "binance-m8-multidate-trades", + "protocol_version": "1.0.2", + "evidence_tier": "FULL_DATA", + "seed": 20260807, + "source": "binance_spot_daily_aggtrades_archive", + "symbols": _FROZEN_SYMBOLS, + "selection_metric": "log_loss", + "target": "future_trade_up", + "label_horizon_events": 20, + "calibration_fraction": 0.20, + "bootstrap_samples": 2000, + "bootstrap_block_events": 40, + "feature_stability_bins": 10, + "max_archive_compressed_bytes": 268_435_456, + "max_archive_uncompressed_bytes": 2_147_483_648, + "max_total_download_bytes": 8_589_934_592, + } + for field, frozen in expected.items(): + _require_equal(getattr(study, field), frozen, f"study.{field}") + if not ( + study.max_archive_compressed_bytes + < study.max_archive_uncompressed_bytes + < study.max_total_download_bytes + ): + raise M8ConfigError("study byte ceilings must increase from compressed to total") + return study + + +def _parse_periods(raw: object) -> tuple[M8Period, ...]: + items = _list(raw, "periods") + periods: list[M8Period] = [] + for index, item in enumerate(items): + table = _mapping(item, f"periods[{index}]") + _exact_keys(table, _PERIOD_KEYS, f"periods[{index}]") + raw_date = _text(table["date"], f"periods[{index}].date") + try: + parsed_date = Date.fromisoformat(raw_date) + except ValueError as exc: + raise M8ConfigError(f"periods[{index}].date must be an ISO UTC date") from exc + if parsed_date.isoformat() != raw_date: + raise M8ConfigError(f"periods[{index}].date must use canonical YYYY-MM-DD form") + raw_role = _text(table["role"], f"periods[{index}].role") + if raw_role not in {"train", "validation", "primary_test", "replication_test"}: + raise M8ConfigError(f"periods[{index}].role is unsupported: {raw_role!r}") + periods.append(M8Period(date=parsed_date, role=cast(M8PeriodRole, raw_role))) + + if len({period.date for period in periods}) != len(periods): + raise M8ConfigError("period dates must be unique") + observed = tuple((period.date.isoformat(), period.role) for period in periods) + _require_equal(observed, _FROZEN_PERIODS, "period date/role order") + return tuple(periods) + + +def _parse_features(raw: object) -> M8Features: + table = _mapping(raw, "features") + _exact_keys(table, _FEATURE_KEYS, "features") + features = M8Features( + trade_windows=_integer_tuple(table["trade_windows"], "features.trade_windows"), + volatility_window=_integer(table["volatility_window"], "features.volatility_window"), + intensity_window=_integer(table["intensity_window"], "features.intensity_window"), + large_trade_quantile=_number( + table["large_trade_quantile"], "features.large_trade_quantile" + ), + ) + expected: dict[str, object] = { + "trade_windows": (5, 20, 100), + "volatility_window": 100, + "intensity_window": 50, + "large_trade_quantile": 0.95, + } + for field, frozen in expected.items(): + _require_equal(getattr(features, field), frozen, f"features.{field}") + return features + + +def _parse_models(raw: object) -> M8Models: + table = _mapping(raw, "models") + _exact_keys(table, _MODEL_KEYS, "models") + models = M8Models( + logistic_c_values=_number_tuple(table["logistic_c_values"], "models.logistic_c_values"), + tree_max_depth_values=_integer_tuple( + table["tree_max_depth_values"], "models.tree_max_depth_values" + ), + tree_min_samples_leaf=_integer( + table["tree_min_samples_leaf"], "models.tree_min_samples_leaf" + ), + ) + expected: dict[str, object] = { + "logistic_c_values": (0.1, 1.0, 10.0), + "tree_max_depth_values": (2, 4, 6), + "tree_min_samples_leaf": 40, + } + for field, frozen in expected.items(): + _require_equal(getattr(models, field), frozen, f"models.{field}") + return models + + +def _parse_quality(raw: object) -> M8Quality: + table = _mapping(raw, "quality") + _exact_keys(table, _QUALITY_KEYS, "quality") + quality = M8Quality( + fail_on_error=_boolean(table["fail_on_error"], "quality.fail_on_error"), + require_complete_daily_archive=_boolean( + table["require_complete_daily_archive"], + "quality.require_complete_daily_archive", + ), + require_contiguous_trade_ids_within_symbol_date=_boolean( + table["require_contiguous_trade_ids_within_symbol_date"], + "quality.require_contiguous_trade_ids_within_symbol_date", + ), + require_nondecreasing_event_time=_boolean( + table["require_nondecreasing_event_time"], + "quality.require_nondecreasing_event_time", + ), + allow_quality_warnings=_boolean( + table["allow_quality_warnings"], "quality.allow_quality_warnings" + ), + ) + expected = { + "fail_on_error": True, + "require_complete_daily_archive": True, + "require_contiguous_trade_ids_within_symbol_date": True, + "require_nondecreasing_event_time": True, + "allow_quality_warnings": False, + } + for field, frozen in expected.items(): + _require_equal(getattr(quality, field), frozen, f"quality.{field}") + return quality + + +def _parse_claims(raw: object) -> M8Claims: + table = _mapping(raw, "claims") + _exact_keys(table, _CLAIM_KEYS, "claims") + claims = M8Claims( + allow_p_values=_boolean(table["allow_p_values"], "claims.allow_p_values"), + allow_significance_claim=_boolean( + table["allow_significance_claim"], "claims.allow_significance_claim" + ), + allow_cross_instrument_pooling=_boolean( + table["allow_cross_instrument_pooling"], + "claims.allow_cross_instrument_pooling", + ), + allow_execution_claim=_boolean( + table["allow_execution_claim"], "claims.allow_execution_claim" + ), + allow_profitability_claim=_boolean( + table["allow_profitability_claim"], "claims.allow_profitability_claim" + ), + ) + for field in _CLAIM_KEYS: + _require_equal(getattr(claims, field), False, f"claims.{field}") + return claims + + +def load_m8_config(path: str | Path) -> M8StudyConfig: + """Load and validate the exact M8 protocol-v1.0.2 machine specification.""" + + config_path = Path(path).resolve() + source_bytes = config_path.read_bytes() + try: + decoded = source_bytes.decode("utf-8") + raw = tomllib.loads(decoded) + except (UnicodeDecodeError, tomllib.TOMLDecodeError) as exc: + raise M8ConfigError(f"cannot parse M8 TOML configuration: {exc}") from exc + + root = _mapping(raw, "configuration") + _exact_keys(root, _TOP_LEVEL_KEYS, "configuration") + return M8StudyConfig( + path=config_path, + source_sha256=hashlib.sha256(source_bytes).hexdigest(), + study=_parse_study(root["study"]), + periods=_parse_periods(root["periods"]), + features=_parse_features(root["features"]), + models=_parse_models(root["models"]), + quality=_parse_quality(root["quality"]), + claims=_parse_claims(root["claims"]), + ) + + +__all__ = [ + "M8Claims", + "M8ConfigError", + "M8Features", + "M8Models", + "M8Period", + "M8PeriodRole", + "M8Quality", + "M8Study", + "M8StudyConfig", + "load_m8_config", +] diff --git a/Microstructure/src/microstructure/m8_ingestion.py b/Microstructure/src/microstructure/m8_ingestion.py new file mode 100644 index 0000000000000000000000000000000000000000..5d46fe4f940a61134c17bb5f2340f5cf6c3db1d9 --- /dev/null +++ b/Microstructure/src/microstructure/m8_ingestion.py @@ -0,0 +1,48 @@ +"""Compatibility tombstone for the retired pre-lock M8 ingestion workflow. + +The original entry point normalized all eight declared archive members before +the analysis lock existed. Keeping that behavior callable would create a +direct held-out-data bypass. Raw acquisition now lives in +``microstructure.m8_acquisition``; lock-gated, one-archive normalization lives +in ``microstructure.m8_normalization``. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from pathlib import Path + +from microstructure.data.binance import SymbolMetadata +from microstructure.m8_config import M8StudyConfig + + +class M8IngestionError(RuntimeError): + """Raised whenever the retired all-calendar ingestion API is invoked.""" + + +def ingest_m8_archives( + config: M8StudyConfig, + output_root: str | Path, + *, + archive_client: object | None = None, + metadata_provider: object | None = None, + supplied_metadata: Mapping[str, SymbolMetadata] | None = None, + batch_rows: int = 65_536, +) -> None: + """Fail closed instead of opening held-out economic data before its lock.""" + + del ( + config, + output_root, + archive_client, + metadata_provider, + supplied_metadata, + batch_rows, + ) + raise M8IngestionError( + "ingest_m8_archives is retired because it opens held-out economic data " + "before the analysis lock; use acquire_m8_archives followed by reproduce_m8" + ) + + +__all__ = ["M8IngestionError", "ingest_m8_archives"] diff --git a/Microstructure/src/microstructure/m8_l2_analysis_config.py b/Microstructure/src/microstructure/m8_l2_analysis_config.py new file mode 100644 index 0000000000000000000000000000000000000000..78278e0af18510e77a7018447c6f17b618e7cd77 --- /dev/null +++ b/Microstructure/src/microstructure/m8_l2_analysis_config.py @@ -0,0 +1,757 @@ +"""Exact, outcome-blind contract for the frozen M8 live-L2 analysis. + +The capture configuration controls what is observed. This independent file +controls how already-verified session bundles may be analysed. The authority +loader requires both the frozen semantics and the exact reviewed TOML bytes; +the semantic-hash helper exists only for provenance comparisons and does not +authorize a differently encoded configuration. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import tomllib +from collections.abc import Mapping +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Literal, cast + +M8L2AnalysisRole = Literal["train", "validation", "primary_test", "replication_test"] +M8L2EndpointDomain = Literal["event", "clock"] +M8L2EndpointUnit = Literal["events", "milliseconds"] + +M8_L2_ANALYSIS_CONFIG_SOURCE_SHA256 = ( + "0d786d5f4109bb5bf773a6197df3fa861c9b7eb61c16c957bd49fb56147fd7d8" +) +M8_L2_ANALYSIS_CONFIG_SEMANTIC_SHA256 = ( + "17c91f64765f35195ab03a4caac93d8ff9c5f009c16e785fd84ebd9569d6f84b" +) + +_TOP_LEVEL_KEYS = frozenset( + { + "study", + "features", + "endpoints", + "regimes", + "calibration", + "bootstrap", + "signed_impact", + "execution", + "claims", + } +) +_STUDY_KEYS = frozenset( + { + "name", + "protocol_version", + "seed", + "source", + "capture_config_source_sha256", + "capture_protocol_sha256", + "symbols", + "training_role", + "selection_role", + "primary_endpoint_role", + "replication_endpoint_role", + } +) +_FEATURE_KEYS = frozenset( + { + "decision_scope", + "flat_direction_policy", + "rolling_windows", + "volatility_window", + "model_feature_columns", + "clock_max_state_age_ms", + "clock_target_policy", + "clock_label_information_end", + "clock_record_target_sequence", + "clock_censor_if_no_eligible_state", + } +) +_ENDPOINT_KEYS = frozenset( + { + "name", + "domain", + "horizon_value", + "unit", + "paired_block_width", + "paired_block_unit", + "nominal_event_block_width", + } +) +_REGIME_KEYS = frozenset({"fit_role", "feature", "quantile_numerators", "quantile_denominator"}) +_CALIBRATION_KEYS = frozenset({"bins"}) +_BOOTSTRAP_KEYS = frozenset({"method", "samples"}) +_SIGNED_IMPACT_KEYS = frozenset({"metric", "side_rule", "price_rule"}) +_EXECUTION_KEYS = frozenset( + { + "market_orders_only", + "probability_threshold", + "symmetric_probability_thresholds", + "order_notional_usd", + "max_l1_participation", + "inventory_order_multiples", + "reference_price_fit_role", + "reference_depth_fit_role", + "reference_price_statistic", + "reference_depth_statistic", + "reference_quantity_policy", + "l1_fill_policy", + "scenario_reset_policy", + "extra_slippage_bps", + "liquidate_at_end", + } +) +_CLAIM_KEYS = frozenset( + { + "allow_capacity_claim", + "allow_realized_execution_claim", + "allow_profitability_claim", + } +) + +_CAPTURE_CONFIG_SOURCE_SHA256 = "b1bf3b4e2820e24e4555bfeb9cb0957f9a0bcdef62039f7d92360e0a97d0dd39" +_CAPTURE_PROTOCOL_SHA256 = "4c77a2099a4cabd049d10e0f8264d3b4c66704d8e87cbaf0c817fd085f4bbd83" +_MODEL_FEATURE_COLUMNS = ( + "spread_bps", + "depth_total_l1", + "depth_total_l5", + "depth_total_l10", + "queue_imbalance_l1", + "queue_imbalance_l5", + "queue_imbalance_l10", + "microprice_deviation_bps", + "ofi_l1", + "ofi_w20", + "ofi_w100", + "cancellation_intensity_w20", + "cancellation_intensity_w100", + "realized_volatility_w20", + "realized_volatility_w100", + "volatility_regime_low", + "volatility_regime_high", + "liquidity_regime_liquid", + "liquidity_regime_stressed", +) + + +class M8L2AnalysisConfigError(ValueError): + """Raised when an analysis file differs from the frozen contract.""" + + +@dataclass(frozen=True, slots=True) +class M8L2AnalysisStudy: + name: str + protocol_version: str + seed: int + source: str + capture_config_source_sha256: str + capture_protocol_sha256: str + symbols: tuple[str, ...] + training_role: M8L2AnalysisRole + selection_role: M8L2AnalysisRole + primary_endpoint_role: M8L2AnalysisRole + replication_endpoint_role: M8L2AnalysisRole + + +@dataclass(frozen=True, slots=True) +class M8L2AnalysisFeatures: + decision_scope: str + flat_direction_policy: str + rolling_windows: tuple[int, ...] + volatility_window: int + model_feature_columns: tuple[str, ...] + clock_max_state_age_ms: int + clock_target_policy: str + clock_label_information_end: str + clock_record_target_sequence: bool + clock_censor_if_no_eligible_state: bool + + +@dataclass(frozen=True, slots=True) +class M8L2AnalysisEndpoint: + name: str + domain: M8L2EndpointDomain + horizon_value: int + unit: M8L2EndpointUnit + paired_block_width: int + paired_block_unit: M8L2EndpointUnit + nominal_event_block_width: int + + +@dataclass(frozen=True, slots=True) +class M8L2AnalysisRegimes: + fit_role: M8L2AnalysisRole + feature: str + quantile_numerators: tuple[int, ...] + quantile_denominator: int + + +@dataclass(frozen=True, slots=True) +class M8L2AnalysisCalibration: + bins: int + + +@dataclass(frozen=True, slots=True) +class M8L2AnalysisBootstrap: + method: str + samples: int + + +@dataclass(frozen=True, slots=True) +class M8L2AnalysisSignedImpact: + metric: str + side_rule: str + price_rule: str + + +@dataclass(frozen=True, slots=True) +class M8L2AnalysisExecution: + market_orders_only: bool + probability_threshold: float + symmetric_probability_thresholds: bool + order_notional_usd: float + max_l1_participation: float + inventory_order_multiples: int + reference_price_fit_role: M8L2AnalysisRole + reference_depth_fit_role: M8L2AnalysisRole + reference_price_statistic: str + reference_depth_statistic: str + reference_quantity_policy: str + l1_fill_policy: str + scenario_reset_policy: str + extra_slippage_bps: float + liquidate_at_end: bool + + +@dataclass(frozen=True, slots=True) +class M8L2AnalysisClaims: + allow_capacity_claim: bool + allow_realized_execution_claim: bool + allow_profitability_claim: bool + + +@dataclass(frozen=True, slots=True) +class M8L2AnalysisConfig: + """Typed analysis contract, with separate semantic and exact-byte identities.""" + + path: Path + source_sha256: str + study: M8L2AnalysisStudy + features: M8L2AnalysisFeatures + endpoints: tuple[M8L2AnalysisEndpoint, ...] + regimes: M8L2AnalysisRegimes + calibration: M8L2AnalysisCalibration + bootstrap: M8L2AnalysisBootstrap + signed_impact: M8L2AnalysisSignedImpact + execution: M8L2AnalysisExecution + claims: M8L2AnalysisClaims + + def _semantic_payload(self) -> dict[str, object]: + return { + "study": {name: getattr(self.study, name) for name in self.study.__dataclass_fields__}, + "features": { + "decision_scope": self.features.decision_scope, + "flat_direction_policy": self.features.flat_direction_policy, + "rolling_windows": list(self.features.rolling_windows), + "volatility_window": self.features.volatility_window, + "model_feature_columns": list(self.features.model_feature_columns), + "clock_max_state_age_ms": self.features.clock_max_state_age_ms, + "clock_target_policy": self.features.clock_target_policy, + "clock_label_information_end": self.features.clock_label_information_end, + "clock_record_target_sequence": self.features.clock_record_target_sequence, + "clock_censor_if_no_eligible_state": ( + self.features.clock_censor_if_no_eligible_state + ), + }, + "endpoints": [ + {name: getattr(endpoint, name) for name in endpoint.__dataclass_fields__} + for endpoint in self.endpoints + ], + "regimes": { + "fit_role": self.regimes.fit_role, + "feature": self.regimes.feature, + "quantile_numerators": list(self.regimes.quantile_numerators), + "quantile_denominator": self.regimes.quantile_denominator, + }, + "calibration": {"bins": self.calibration.bins}, + "bootstrap": { + name: getattr(self.bootstrap, name) for name in self.bootstrap.__dataclass_fields__ + }, + "signed_impact": { + "metric": self.signed_impact.metric, + "side_rule": self.signed_impact.side_rule, + "price_rule": self.signed_impact.price_rule, + }, + "execution": { + name: getattr(self.execution, name) for name in self.execution.__dataclass_fields__ + }, + "claims": { + name: getattr(self.claims, name) for name in self.claims.__dataclass_fields__ + }, + } + + @property + def semantic_sha256(self) -> str: + encoded = json.dumps( + self._semantic_payload(), sort_keys=True, separators=(",", ":"), allow_nan=False + ).encode("utf-8") + return hashlib.sha256(encoded).hexdigest() + + @property + def hash(self) -> str: + """Compatibility alias for the formatting-independent semantic identity.""" + + return self.semantic_sha256 + + def public_dict(self) -> dict[str, object]: + return { + "path": str(self.path), + "config_sha256": self.semantic_sha256, + "semantic_sha256": self.semantic_sha256, + "source_sha256": self.source_sha256, + **self._semantic_payload(), + } + + +def _mapping(value: object, label: str) -> Mapping[str, Any]: + if not isinstance(value, Mapping) or not all(type(key) is str for key in value): + raise M8L2AnalysisConfigError(f"{label} must be a TOML table with string keys") + return cast(Mapping[str, Any], value) + + +def _exact_keys(value: Mapping[str, Any], expected: frozenset[str], label: str) -> None: + observed = frozenset(value) + if observed != expected: + raise M8L2AnalysisConfigError( + f"{label} keys differ (missing={sorted(expected - observed)}, " + f"unknown={sorted(observed - expected)})" + ) + + +def _list(value: object, label: str) -> list[Any]: + if not isinstance(value, list): + raise M8L2AnalysisConfigError(f"{label} must be an array") + return value + + +def _text(value: object, label: str) -> str: + if type(value) is not str: + raise M8L2AnalysisConfigError(f"{label} must be a string") + return value + + +def _integer(value: object, label: str) -> int: + if type(value) is not int: + raise M8L2AnalysisConfigError(f"{label} must be an integer") + return value + + +def _number(value: object, label: str) -> float: + if type(value) not in {int, float}: + raise M8L2AnalysisConfigError(f"{label} must be a finite number") + result = float(cast(int | float, value)) + if not math.isfinite(result): + raise M8L2AnalysisConfigError(f"{label} must be a finite number") + return result + + +def _boolean(value: object, label: str) -> bool: + if type(value) is not bool: + raise M8L2AnalysisConfigError(f"{label} must be a boolean") + return value + + +def _text_tuple(value: object, label: str) -> tuple[str, ...]: + return tuple(_text(item, f"{label}[{index}]") for index, item in enumerate(_list(value, label))) + + +def _integer_tuple(value: object, label: str) -> tuple[int, ...]: + return tuple( + _integer(item, f"{label}[{index}]") for index, item in enumerate(_list(value, label)) + ) + + +def _frozen(observed: object, expected: object, label: str) -> None: + if observed != expected: + raise M8L2AnalysisConfigError(f"{label} is frozen at {expected!r}, observed {observed!r}") + + +def _role(value: object, label: str) -> M8L2AnalysisRole: + observed = _text(value, label) + if observed not in {"train", "validation", "primary_test", "replication_test"}: + raise M8L2AnalysisConfigError(f"{label} is not a supported frozen-session role") + return cast(M8L2AnalysisRole, observed) + + +def _parse_study(raw: object) -> M8L2AnalysisStudy: + table = _mapping(raw, "study") + _exact_keys(table, _STUDY_KEYS, "study") + result = M8L2AnalysisStudy( + name=_text(table["name"], "study.name"), + protocol_version=_text(table["protocol_version"], "study.protocol_version"), + seed=_integer(table["seed"], "study.seed"), + source=_text(table["source"], "study.source"), + capture_config_source_sha256=_text( + table["capture_config_source_sha256"], "study.capture_config_source_sha256" + ), + capture_protocol_sha256=_text( + table["capture_protocol_sha256"], "study.capture_protocol_sha256" + ), + symbols=_text_tuple(table["symbols"], "study.symbols"), + training_role=_role(table["training_role"], "study.training_role"), + selection_role=_role(table["selection_role"], "study.selection_role"), + primary_endpoint_role=_role(table["primary_endpoint_role"], "study.primary_endpoint_role"), + replication_endpoint_role=_role( + table["replication_endpoint_role"], "study.replication_endpoint_role" + ), + ) + expected = M8L2AnalysisStudy( + name="binance-m8-live-l2-analysis-v2", + protocol_version="2.0.0", + seed=20260807, + source="verified_m8_l2_session_bundles", + capture_config_source_sha256=_CAPTURE_CONFIG_SOURCE_SHA256, + capture_protocol_sha256=_CAPTURE_PROTOCOL_SHA256, + symbols=("BTCUSDT", "ETHUSDT"), + training_role="train", + selection_role="validation", + primary_endpoint_role="primary_test", + replication_endpoint_role="replication_test", + ) + _frozen(result, expected, "study contract") + return result + + +def _parse_features(raw: object) -> M8L2AnalysisFeatures: + table = _mapping(raw, "features") + _exact_keys(table, _FEATURE_KEYS, "features") + result = M8L2AnalysisFeatures( + decision_scope=_text(table["decision_scope"], "features.decision_scope"), + flat_direction_policy=_text( + table["flat_direction_policy"], "features.flat_direction_policy" + ), + rolling_windows=_integer_tuple(table["rolling_windows"], "features.rolling_windows"), + volatility_window=_integer(table["volatility_window"], "features.volatility_window"), + model_feature_columns=_text_tuple( + table["model_feature_columns"], "features.model_feature_columns" + ), + clock_max_state_age_ms=_integer( + table["clock_max_state_age_ms"], + "features.clock_max_state_age_ms", + ), + clock_target_policy=_text(table["clock_target_policy"], "features.clock_target_policy"), + clock_label_information_end=_text( + table["clock_label_information_end"], "features.clock_label_information_end" + ), + clock_record_target_sequence=_boolean( + table["clock_record_target_sequence"], "features.clock_record_target_sequence" + ), + clock_censor_if_no_eligible_state=_boolean( + table["clock_censor_if_no_eligible_state"], + "features.clock_censor_if_no_eligible_state", + ), + ) + if any(value <= 0 for value in (*result.rolling_windows, result.volatility_window)): + raise M8L2AnalysisConfigError("feature windows must be positive") + if result.clock_max_state_age_ms < 0: + raise M8L2AnalysisConfigError("features.clock_max_state_age_ms must be nonnegative") + _frozen( + result, + M8L2AnalysisFeatures( + decision_scope="per_symbol_verified_observed_intervals", + flat_direction_policy="flat_is_non_up", + rolling_windows=(20, 100), + volatility_window=100, + model_feature_columns=_MODEL_FEATURE_COLUMNS, + clock_max_state_age_ms=500, + clock_target_policy="exact_target_locf_same_valid_observed_interval", + clock_label_information_end="exact_target", + clock_record_target_sequence=True, + clock_censor_if_no_eligible_state=True, + ), + "features contract", + ) + return result + + +def _parse_endpoints(raw: object) -> tuple[M8L2AnalysisEndpoint, ...]: + result: list[M8L2AnalysisEndpoint] = [] + for index, item in enumerate(_list(raw, "endpoints")): + table = _mapping(item, f"endpoints[{index}]") + _exact_keys(table, _ENDPOINT_KEYS, f"endpoints[{index}]") + raw_domain = _text(table["domain"], f"endpoints[{index}].domain") + if raw_domain not in {"event", "clock"}: + raise M8L2AnalysisConfigError(f"endpoints[{index}].domain is unsupported") + raw_unit = _text(table["unit"], f"endpoints[{index}].unit") + if raw_unit not in {"events", "milliseconds"}: + raise M8L2AnalysisConfigError(f"endpoints[{index}].unit is unsupported") + raw_block_unit = _text(table["paired_block_unit"], f"endpoints[{index}].paired_block_unit") + if raw_block_unit not in {"events", "milliseconds"}: + raise M8L2AnalysisConfigError(f"endpoints[{index}].paired_block_unit is unsupported") + endpoint = M8L2AnalysisEndpoint( + name=_text(table["name"], f"endpoints[{index}].name"), + domain=cast(M8L2EndpointDomain, raw_domain), + horizon_value=_integer(table["horizon_value"], f"endpoints[{index}].horizon_value"), + unit=cast(M8L2EndpointUnit, raw_unit), + paired_block_width=_integer( + table["paired_block_width"], f"endpoints[{index}].paired_block_width" + ), + paired_block_unit=cast(M8L2EndpointUnit, raw_block_unit), + nominal_event_block_width=_integer( + table["nominal_event_block_width"], + f"endpoints[{index}].nominal_event_block_width", + ), + ) + if ( + endpoint.horizon_value <= 0 + or endpoint.paired_block_width <= 0 + or endpoint.nominal_event_block_width <= 0 + ): + raise M8L2AnalysisConfigError("endpoint horizons and block widths must be positive") + expected_unit = "events" if endpoint.domain == "event" else "milliseconds" + if endpoint.unit != expected_unit or endpoint.paired_block_unit != expected_unit: + raise M8L2AnalysisConfigError( + f"endpoints[{index}] units do not match its endpoint domain" + ) + result.append(endpoint) + expected = ( + M8L2AnalysisEndpoint("event_20", "event", 20, "events", 40, "events", 40), + M8L2AnalysisEndpoint("event_100", "event", 100, "events", 200, "events", 200), + M8L2AnalysisEndpoint( + "clock_1000ms", "clock", 1000, "milliseconds", 2000, "milliseconds", 20 + ), + M8L2AnalysisEndpoint( + "clock_5000ms", "clock", 5000, "milliseconds", 10000, "milliseconds", 100 + ), + ) + _frozen(tuple(result), expected, "endpoint order/contract") + return tuple(result) + + +def _parse_regimes(raw: object) -> M8L2AnalysisRegimes: + table = _mapping(raw, "regimes") + _exact_keys(table, _REGIME_KEYS, "regimes") + result = M8L2AnalysisRegimes( + fit_role=_role(table["fit_role"], "regimes.fit_role"), + feature=_text(table["feature"], "regimes.feature"), + quantile_numerators=_integer_tuple( + table["quantile_numerators"], "regimes.quantile_numerators" + ), + quantile_denominator=_integer( + table["quantile_denominator"], "regimes.quantile_denominator" + ), + ) + if result.quantile_denominator <= 0 or any( + value <= 0 or value >= result.quantile_denominator for value in result.quantile_numerators + ): + raise M8L2AnalysisConfigError("regime quantiles must lie strictly between zero and one") + _frozen( + result, + M8L2AnalysisRegimes("train", "realized_volatility_w100", (1, 2), 3), + "regimes contract", + ) + return result + + +def _parse_calibration(raw: object) -> M8L2AnalysisCalibration: + table = _mapping(raw, "calibration") + _exact_keys(table, _CALIBRATION_KEYS, "calibration") + result = M8L2AnalysisCalibration(bins=_integer(table["bins"], "calibration.bins")) + if result.bins < 2: + raise M8L2AnalysisConfigError("calibration.bins must be at least two") + _frozen(result, M8L2AnalysisCalibration(10), "calibration contract") + return result + + +def _parse_bootstrap(raw: object) -> M8L2AnalysisBootstrap: + table = _mapping(raw, "bootstrap") + _exact_keys(table, _BOOTSTRAP_KEYS, "bootstrap") + result = M8L2AnalysisBootstrap( + method=_text(table["method"], "bootstrap.method"), + samples=_integer(table["samples"], "bootstrap.samples"), + ) + if result.samples <= 0: + raise M8L2AnalysisConfigError("bootstrap.samples must be positive") + _frozen(result, M8L2AnalysisBootstrap("paired_moving_block", 2000), "bootstrap contract") + return result + + +def _parse_signed_impact(raw: object) -> M8L2AnalysisSignedImpact: + table = _mapping(raw, "signed_impact") + _exact_keys(table, _SIGNED_IMPACT_KEYS, "signed_impact") + result = M8L2AnalysisSignedImpact( + metric=_text(table["metric"], "signed_impact.metric"), + side_rule=_text(table["side_rule"], "signed_impact.side_rule"), + price_rule=_text(table["price_rule"], "signed_impact.price_rule"), + ) + _frozen( + result, + M8L2AnalysisSignedImpact( + "ofi_signed_future_mid_markout", + "sign_of_horizon_matched_ofi", + "ofi_sign_times_future_log_mid_return_bps", + ), + "signed-impact contract", + ) + return result + + +def _parse_execution(raw: object) -> M8L2AnalysisExecution: + table = _mapping(raw, "execution") + _exact_keys(table, _EXECUTION_KEYS, "execution") + result = M8L2AnalysisExecution( + market_orders_only=_boolean(table["market_orders_only"], "execution.market_orders_only"), + probability_threshold=_number( + table["probability_threshold"], "execution.probability_threshold" + ), + symmetric_probability_thresholds=_boolean( + table["symmetric_probability_thresholds"], + "execution.symmetric_probability_thresholds", + ), + order_notional_usd=_number(table["order_notional_usd"], "execution.order_notional_usd"), + max_l1_participation=_number( + table["max_l1_participation"], "execution.max_l1_participation" + ), + inventory_order_multiples=_integer( + table["inventory_order_multiples"], "execution.inventory_order_multiples" + ), + reference_price_fit_role=_role( + table["reference_price_fit_role"], "execution.reference_price_fit_role" + ), + reference_depth_fit_role=_role( + table["reference_depth_fit_role"], "execution.reference_depth_fit_role" + ), + reference_price_statistic=_text( + table["reference_price_statistic"], "execution.reference_price_statistic" + ), + reference_depth_statistic=_text( + table["reference_depth_statistic"], "execution.reference_depth_statistic" + ), + reference_quantity_policy=_text( + table["reference_quantity_policy"], "execution.reference_quantity_policy" + ), + l1_fill_policy=_text(table["l1_fill_policy"], "execution.l1_fill_policy"), + scenario_reset_policy=_text( + table["scenario_reset_policy"], "execution.scenario_reset_policy" + ), + extra_slippage_bps=_number(table["extra_slippage_bps"], "execution.extra_slippage_bps"), + liquidate_at_end=_boolean(table["liquidate_at_end"], "execution.liquidate_at_end"), + ) + if not 0.5 < result.probability_threshold < 1.0: + raise M8L2AnalysisConfigError("execution.probability_threshold must be between 0.5 and 1") + if result.order_notional_usd <= 0: + raise M8L2AnalysisConfigError("execution.order_notional_usd must be positive") + if not 0.0 < result.max_l1_participation <= 1.0: + raise M8L2AnalysisConfigError("execution.max_l1_participation must be in (0, 1]") + if result.inventory_order_multiples <= 0: + raise M8L2AnalysisConfigError("execution.inventory_order_multiples must be positive") + if result.extra_slippage_bps < 0: + raise M8L2AnalysisConfigError("execution.extra_slippage_bps must be nonnegative") + expected = M8L2AnalysisExecution( + market_orders_only=True, + probability_threshold=0.55, + symmetric_probability_thresholds=True, + order_notional_usd=100.0, + max_l1_participation=0.10, + inventory_order_multiples=10, + reference_price_fit_role="train", + reference_depth_fit_role="train", + reference_price_statistic="train_median_mid_price", + reference_depth_statistic="train_q05_min_bid_ask_l1_depth", + reference_quantity_policy=("min_100usd_and_10pct_train_q05_l1_depth_rounded_down_to_lot"), + l1_fill_policy="fill_up_to_recorded_l1_depth_cancel_remainder", + scenario_reset_policy="per_symbol_session_endpoint_latency_pair", + extra_slippage_bps=0.0, + liquidate_at_end=True, + ) + _frozen(result, expected, "execution contract") + return result + + +def _parse_claims(raw: object) -> M8L2AnalysisClaims: + table = _mapping(raw, "claims") + _exact_keys(table, _CLAIM_KEYS, "claims") + result = M8L2AnalysisClaims( + allow_capacity_claim=_boolean(table["allow_capacity_claim"], "claims.allow_capacity_claim"), + allow_realized_execution_claim=_boolean( + table["allow_realized_execution_claim"], "claims.allow_realized_execution_claim" + ), + allow_profitability_claim=_boolean( + table["allow_profitability_claim"], "claims.allow_profitability_claim" + ), + ) + _frozen(result, M8L2AnalysisClaims(False, False, False), "claims contract") + return result + + +def _parse_source(path: Path, source: bytes) -> M8L2AnalysisConfig: + try: + raw = tomllib.loads(source.decode("utf-8")) + except (UnicodeDecodeError, tomllib.TOMLDecodeError) as error: + raise M8L2AnalysisConfigError(f"cannot parse M8 live-L2 analysis TOML: {error}") from error + root = _mapping(raw, "configuration") + _exact_keys(root, _TOP_LEVEL_KEYS, "configuration") + return M8L2AnalysisConfig( + path=path, + source_sha256=hashlib.sha256(source).hexdigest(), + study=_parse_study(root["study"]), + features=_parse_features(root["features"]), + endpoints=_parse_endpoints(root["endpoints"]), + regimes=_parse_regimes(root["regimes"]), + calibration=_parse_calibration(root["calibration"]), + bootstrap=_parse_bootstrap(root["bootstrap"]), + signed_impact=_parse_signed_impact(root["signed_impact"]), + execution=_parse_execution(root["execution"]), + claims=_parse_claims(root["claims"]), + ) + + +def semantic_hash_m8_l2_analysis_config(path: str | Path) -> str: + """Hash validated semantics; this does not authorize non-frozen source bytes.""" + + config_path = Path(path).resolve() + return _parse_source(config_path, config_path.read_bytes()).semantic_sha256 + + +def load_m8_l2_analysis_config(path: str | Path) -> M8L2AnalysisConfig: + """Load only the exact reviewed, outcome-blind M8 L2 analysis contract.""" + + config_path = Path(path).resolve() + result = _parse_source(config_path, config_path.read_bytes()) + if result.semantic_sha256 != M8_L2_ANALYSIS_CONFIG_SEMANTIC_SHA256: + raise M8L2AnalysisConfigError( + "configuration semantics do not match the code-bound outcome-blind freeze " + f"{M8_L2_ANALYSIS_CONFIG_SEMANTIC_SHA256}" + ) + if result.source_sha256 != M8_L2_ANALYSIS_CONFIG_SOURCE_SHA256: + raise M8L2AnalysisConfigError( + "configuration bytes do not match the outcome-blind freeze " + f"{M8_L2_ANALYSIS_CONFIG_SOURCE_SHA256}" + ) + return result + + +__all__ = [ + "M8_L2_ANALYSIS_CONFIG_SEMANTIC_SHA256", + "M8_L2_ANALYSIS_CONFIG_SOURCE_SHA256", + "M8L2AnalysisBootstrap", + "M8L2AnalysisCalibration", + "M8L2AnalysisClaims", + "M8L2AnalysisConfig", + "M8L2AnalysisConfigError", + "M8L2AnalysisEndpoint", + "M8L2AnalysisExecution", + "M8L2AnalysisFeatures", + "M8L2AnalysisRegimes", + "M8L2AnalysisRole", + "M8L2AnalysisSignedImpact", + "M8L2AnalysisStudy", + "M8L2EndpointDomain", + "M8L2EndpointUnit", + "load_m8_l2_analysis_config", + "semantic_hash_m8_l2_analysis_config", +] diff --git a/Microstructure/src/microstructure/m8_l2_binance.py b/Microstructure/src/microstructure/m8_l2_binance.py new file mode 100644 index 0000000000000000000000000000000000000000..aae3c518320a6649e560c72ff422c47e2a678060 --- /dev/null +++ b/Microstructure/src/microstructure/m8_l2_binance.py @@ -0,0 +1,1217 @@ +"""Production Binance adapter for one frozen prospective M8 L2 symbol. + +The cross-symbol/session authority lives in :mod:`microstructure.m8_l2_capture`. +This module owns only the public market-data transport, bounded raw journaling, +snapshot-plus-delta reconstruction, and the exhaustive per-symbol artifact +descriptor returned across that typed boundary. It has no authenticated or +order-entry path. +""" + +from __future__ import annotations + +import asyncio +import base64 +import hashlib +import json +import os +import tempfile +import time +from collections import deque +from collections.abc import AsyncIterator, Callable, Iterator, Mapping +from contextlib import suppress +from dataclasses import dataclass +from pathlib import Path +from typing import Literal, Protocol, cast + +import pyarrow as pa # type: ignore[import-untyped] +from websockets.exceptions import WebSocketException + +from microstructure.data.binance import ( + BinanceHTTPError, + BinanceLiveDepthCollector, + BinanceMetadataContractError, + BinancePayloadError, + BinancePublicClient, + BinanceResponseSizeLimitError, + CapturedDepth, + RawDepthFrame, + SymbolMetadata, +) +from microstructure.data.book import BookInvariantError, BookSnapshot, IncrementalBookReconstructor +from microstructure.data.quality import IncrementalQualityValidator, ValidationReport +from microstructure.data.schemas import get_schema, table_from_records +from microstructure.data.storage import write_capture_parquet, write_source_manifest +from microstructure.m8_l2_capture import ( + CapturedArtifact, + M8L2DataFailure, + ObservedInterval, + SymbolCaptureResult, +) +from microstructure.m8_l2_config import M8L2CaptureLimits +from microstructure.provenance import read_json, sha256_file, utc_now_iso, write_json + +_BATCH_ROWS = 1_024 +_VARIABLE_RECORD_OVERHEAD_FACTOR = 8 +_MAX_OBSERVED_SILENCE_NS = 5_000_000_000 +_DEFAULT_RECEIVER_QUEUE_CAPACITY = 1_024 +_SOURCE_URI = "wss://data-stream.binance.vision" + + +class _Collector(Protocol): + url: str + + def stream(self, *, max_messages: int | None = None) -> AsyncIterator[CapturedDepth]: ... + + +class _Client(Protocol): + def fetch_exchange_info(self, *, symbol: str, raw_root: Path) -> SymbolMetadata: ... + + def fetch_depth_snapshot( + self, + *, + symbol: str, + raw_root: Path, + continuity_id: str, + tick_size: object, + lot_size: object, + ) -> BookSnapshot: ... + + +class _DataCaptureIssue(RuntimeError): + """Internal deterministic capture failure converted after evidence finalization.""" + + def __init__(self, reason_code: str, phase: str, message: str) -> None: + super().__init__(message) + self.reason_code = reason_code + self.phase = phase + + +class _ScheduledEndReached(RuntimeError): + """Stop the collector before it decodes the first out-of-window frame.""" + + +class _LocalEvidenceSystemError(RuntimeError): + """Keep local journal/storage faults out of public-transport classification.""" + + +async def _to_thread_joined[**P, T]( + function: Callable[P, T], /, *args: P.args, **kwargs: P.kwargs +) -> T: + """Make cancellation wait for a public REST worker that may still write raw bytes.""" + + task = asyncio.create_task(asyncio.to_thread(function, *args, **kwargs)) + try: + return await asyncio.shield(task) + except asyncio.CancelledError as canceled: + try: + await task + except BaseException as worker_error: + canceled.add_note( + f"joined REST worker also failed with {type(worker_error).__name__}: {worker_error}" + ) + raise + + +@dataclass(frozen=True, slots=True) +class _PublishedJournal: + path: Path + sha256: str + manifest_path: Path + manifest_sha256: str + + +class _RawJournal: + """Write exact websocket bytes before decode and retain FIFO lineage.""" + + def __init__( + self, + *, + root: Path, + symbol: str, + source_uri: str, + scheduled_start_ns: int, + scheduled_end_ns: int, + max_frame_bytes: int, + max_messages: int, + ) -> None: + self.root = root + self.symbol = symbol + self.source_uri = source_uri + self.scheduled_start_ns = scheduled_start_ns + self.scheduled_end_ns = scheduled_end_ns + self.max_frame_bytes = max_frame_bytes + self.max_messages = max_messages + self.directory = root / "raw" / "binance_spot" / "depth_stream" / symbol + self.directory.mkdir(parents=True, exist_ok=True) + descriptor, name = tempfile.mkstemp( + dir=self.directory, + prefix=".m8-l2-", + suffix=".ndjson.tmp", + ) + self._temporary_path = Path(name) + self._handle = os.fdopen(descriptor, "wb") + self._pending: deque[tuple[str, int, int, str]] = deque() + self.messages = 0 + self.snapshot_anchors = 0 + self.first_received_ns: int | None = None + self.last_received_ns: int | None = None + self.max_frame_bytes_observed = 0 + self._closed = False + self._published: _PublishedJournal | None = None + + @property + def evidence_path(self) -> Path: + return self._published.path if self._published is not None else self._temporary_path + + def _write(self, payload: Mapping[str, object]) -> None: + if self._closed: + raise RuntimeError("cannot append to a closed raw journal") + encoded = json.dumps( + dict(payload), sort_keys=True, separators=(",", ":"), allow_nan=False + ).encode("utf-8") + self._handle.write(encoded) + self._handle.write(b"\n") + + def append_frame(self, frame: RawDepthFrame) -> None: + """Persist an in-window frame; the collector calls this before parsing.""" + + if not (self.scheduled_start_ns <= frame.received_ts_ns < self.scheduled_end_ns): + return + payload_size = len(frame.payload) + payload_sha256 = hashlib.sha256(frame.payload).hexdigest() + self._write( + { + "capture_seq": frame.capture_seq, + "continuity_id": frame.continuity_id, + "event_kind": "websocket_frame", + "payload_base64": base64.b64encode(frame.payload).decode("ascii"), + "payload_bytes": payload_size, + "payload_sha256": payload_sha256, + "received_ts_ns": frame.received_ts_ns, + "websocket_message_type": "text" if frame.was_text else "binary", + } + ) + self.messages += 1 + self.max_frame_bytes_observed = max(self.max_frame_bytes_observed, payload_size) + if self.first_received_ns is None: + self.first_received_ns = frame.received_ts_ns + self.last_received_ns = frame.received_ts_ns + self._pending.append( + (frame.continuity_id, frame.capture_seq, frame.received_ts_ns, payload_sha256) + ) + if payload_size > self.max_frame_bytes: + raise _DataCaptureIssue( + "RAW_FRAME_BYTES_EXCEEDED", + "RAW_CAPTURE", + f"raw frame has {payload_size} bytes; maximum is {self.max_frame_bytes}", + ) + # The ceiling is a failure boundary, never an alternate stopping target. + if self.messages >= self.max_messages: + raise _DataCaptureIssue( + "MESSAGE_SAFETY_CEILING_REACHED", + "RAW_CAPTURE", + f"message ceiling {self.max_messages} reached before scheduled end", + ) + + def consume_captured(self, item: CapturedDepth) -> None: + received_ns = item.delta.received_ts_ns + capture_seq = item.delta.capture_seq + if received_ns is None or capture_seq is None: + raise _DataCaptureIssue( + "MISSING_RAW_LINEAGE", + "NORMALIZATION", + "captured depth delta lacks receipt time or capture sequence", + ) + identity = ( + item.delta.continuity_id, + capture_seq, + received_ns, + hashlib.sha256(item.raw_payload.encode("utf-8")).hexdigest(), + ) + if not self._pending or self._pending[0] != identity: + raise _DataCaptureIssue( + "RAW_LINEAGE_MISMATCH", + "NORMALIZATION", + "normalized depth delta is not the next preserved raw frame", + ) + self._pending.popleft() + if item.delta.source_artifact_id != identity[-1]: + raise _DataCaptureIssue( + "RAW_LINEAGE_MISMATCH", + "NORMALIZATION", + "normalized depth source digest differs from preserved raw bytes", + ) + + def append_snapshot( + self, + snapshot: BookSnapshot, + *, + raw_path: Path, + manifest_path: Path, + ) -> None: + self._write( + { + "continuity_id": snapshot.continuity_id, + "event_kind": "rest_snapshot_anchor", + "last_update_id": snapshot.last_update_id, + "raw_manifest_path": raw_path.parent.joinpath(manifest_path.name) + .relative_to(self.root) + .as_posix(), + "raw_manifest_sha256": sha256_file(manifest_path), + "raw_path": raw_path.relative_to(self.root).as_posix(), + "raw_sha256": snapshot.source_artifact_id, + "received_ts_ns": snapshot.received_ts_ns, + "snapshot_id": snapshot.snapshot_id, + } + ) + self.snapshot_anchors += 1 + + def _close(self) -> None: + if self._closed: + return + self._handle.flush() + os.fsync(self._handle.fileno()) + self._handle.close() + self._closed = True + + def publish(self, *, capture_status: str, error: BaseException | None) -> _PublishedJournal: + if self._published is not None: + return self._published + self._close() + digest = sha256_file(self._temporary_path) + destination = self.directory / f"capture-{digest}.ndjson" + if destination.exists(): + if sha256_file(destination) != digest: + raise RuntimeError(f"raw journal content-address collision at {destination}") + self._temporary_path.unlink(missing_ok=True) + else: + os.replace(self._temporary_path, destination) + headers = { + "x-local-capture-status": capture_status, + "x-local-journal-format": "typed-base64-frames-v1", + "x-local-message-count": str(self.messages), + "x-local-snapshot-anchor-count": str(self.snapshot_anchors), + "x-local-scheduled-start-ns": str(self.scheduled_start_ns), + "x-local-scheduled-end-ns-exclusive": str(self.scheduled_end_ns), + } + if error is not None: + headers["x-local-error-type"] = type(error).__name__ + headers["x-local-error"] = str(error)[:512] + manifest_path, manifest_sha256 = write_source_manifest( + destination, + source="binance_spot_public_live_capture_journal", + source_uri=self.source_uri, + downloaded_at_utc=utc_now_iso(), + requested_start_ns=self.scheduled_start_ns, + requested_end_ns=self.scheduled_end_ns, + response_headers=headers, + ) + self._published = _PublishedJournal( + path=destination, + sha256=digest, + manifest_path=manifest_path, + manifest_sha256=manifest_sha256, + ) + return self._published + + def close_without_publish(self) -> None: + self._close() + + +class _ArrowSpool: + """Bounded record buffer backed by an Arrow IPC stream on disk.""" + + def __init__( + self, + *, + root: Path, + schema_name: str, + max_batch_bytes: int, + on_batch: Callable[[pa.RecordBatch], None] | None = None, + ) -> None: + self.schema_name = schema_name + self.max_batch_bytes = max_batch_bytes + self.path = root / f"{schema_name}.arrow" + self._handle = self.path.open("wb") + self._writer = pa.ipc.new_stream(self._handle, get_schema(schema_name)) + self._on_batch = on_batch + self._records: list[Mapping[str, object]] = [] + self._estimated_bytes = 0 + self.rows = 0 + self.max_batch_bytes_observed = 0 + self._closed = False + + def append(self, record: Mapping[str, object], *, estimated_bytes: int) -> None: + if self._closed: + raise RuntimeError("cannot append to a closed Arrow spool") + if estimated_bytes < 1: + raise RuntimeError("Arrow record estimate must be positive") + if estimated_bytes > self.max_batch_bytes: + raise _DataCaptureIssue( + "ARROW_BATCH_BYTES_EXCEEDED", + "NORMALIZATION", + f"one {self.schema_name} record estimate exceeds the Arrow batch ceiling", + ) + if self._records and self._estimated_bytes + estimated_bytes > self.max_batch_bytes: + self._flush() + self._records.append(record) + self._estimated_bytes += estimated_bytes + if len(self._records) >= _BATCH_ROWS: + self._flush() + + def _flush(self) -> None: + if not self._records: + return + table = table_from_records(self.schema_name, self._records) + batches = table.to_batches(max_chunksize=_BATCH_ROWS) + if len(batches) != 1: + raise RuntimeError(f"failed to build one bounded {self.schema_name} Arrow batch") + batch = batches[0] + observed_bytes = max(self._estimated_bytes, batch.nbytes) + self.max_batch_bytes_observed = max(self.max_batch_bytes_observed, observed_bytes) + if observed_bytes > self.max_batch_bytes: + raise _DataCaptureIssue( + "ARROW_BATCH_BYTES_EXCEEDED", + "NORMALIZATION", + f"{self.schema_name} Arrow batch exceeds {self.max_batch_bytes} bytes", + ) + if self._on_batch is not None: + self._on_batch(batch) + self._writer.write_batch(batch) + self.rows += batch.num_rows + self._records.clear() + self._estimated_bytes = 0 + + def close(self) -> None: + if self._closed: + return + self._flush() + self._writer.close() + self._handle.flush() + os.fsync(self._handle.fileno()) + self._handle.close() + self._closed = True + + def iter_batches(self) -> Iterator[pa.RecordBatch]: + if not self._closed: + raise RuntimeError("Arrow spool must be closed before reading") + with self.path.open("rb") as handle: + for batch in pa.ipc.open_stream(handle): + if batch.num_rows > _BATCH_ROWS or batch.nbytes > self.max_batch_bytes: + raise RuntimeError(f"persisted {self.schema_name} batch exceeds its bound") + yield batch + + +class _ObservedIntervals: + """Track only receipt spans confirmed by consecutive OBSERVED states.""" + + def __init__(self) -> None: + self._continuity_id: str | None = None + self._previous_ns: int | None = None + self._active_start_ns: int | None = None + self._active_end_ns: int | None = None + self._intervals: list[ObservedInterval] = [] + + def _finish_active(self) -> None: + if ( + self._continuity_id is not None + and self._active_start_ns is not None + and self._active_end_ns is not None + and self._active_end_ns > self._active_start_ns + ): + self._intervals.append( + ObservedInterval( + continuity_id=self._continuity_id, + start_received_ns=self._active_start_ns, + end_received_ns_exclusive=self._active_end_ns, + ) + ) + self._active_start_ns = None + self._active_end_ns = None + + def break_continuity(self) -> None: + self._finish_active() + self._continuity_id = None + self._previous_ns = None + + def excluded(self, continuity_id: str) -> None: + if self._continuity_id == continuity_id: + self._finish_active() + else: + self._finish_active() + self._continuity_id = continuity_id + self._previous_ns = None + + def observed(self, continuity_id: str, received_ns: int) -> None: + if self._continuity_id != continuity_id: + self.break_continuity() + self._continuity_id = continuity_id + previous = self._previous_ns + if ( + previous is not None + and received_ns > previous + and received_ns - previous <= _MAX_OBSERVED_SILENCE_NS + ): + if self._active_start_ns is None: + self._active_start_ns = previous + self._active_end_ns = received_ns + 1 + else: + self._finish_active() + self._previous_ns = received_ns + + def finish(self) -> tuple[ObservedInterval, ...]: + self._finish_active() + return tuple(self._intervals) + + +def _snapshot_files(root: Path, snapshot: BookSnapshot) -> tuple[Path, Path]: + directory = root / "raw" / "binance_spot" / "depth_snapshots" / snapshot.symbol + raw_path = directory / f"{snapshot.source_artifact_id}.json" + if raw_path.is_symlink() or not raw_path.is_file(): + raise RuntimeError("snapshot raw response is not a regular preserved artifact") + if sha256_file(raw_path) != snapshot.source_artifact_id: + raise RuntimeError("snapshot raw response digest does not match its source identity") + candidates: list[tuple[Path, Mapping[str, object]]] = [] + for path in directory.glob(f"{raw_path.name}.manifest-*.json"): + payload = read_json(path) + checksum = payload.get("checksum") if isinstance(payload, dict) else None + if ( + isinstance(payload, dict) + and payload.get("path") == raw_path.name + and isinstance(checksum, dict) + and checksum.get("value") == snapshot.source_artifact_id + ): + candidates.append((path, payload)) + if len(candidates) == 1: + return raw_path, candidates[0][0] + seconds, nanoseconds = divmod(snapshot.received_ts_ns, 1_000_000_000) + expected_downloaded = ( + time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(seconds)) + f".{nanoseconds:09d}Z" + ) + current = [ + path + for path, payload in candidates + if payload.get("downloaded_at_utc") == expected_downloaded + ] + if len(current) != 1: + raise RuntimeError( + "snapshot does not have one source manifest bound to its receipt timestamp" + ) + return raw_path, current[0] + + +def _verify_metadata_files(root: Path, metadata: SymbolMetadata) -> None: + for label, path in ( + ("exchange metadata raw response", metadata.source_path), + ("exchange metadata source manifest", metadata.source_manifest_path), + ): + if path.is_symlink() or not path.is_file(): + raise RuntimeError(f"{label} is not a regular file") + try: + path.resolve().relative_to(root.resolve()) + except ValueError as error: + raise RuntimeError(f"{label} escapes the single-symbol capture stage") from error + if sha256_file(metadata.source_path) != metadata.source_artifact_id: + raise RuntimeError("exchange metadata digest differs from its raw response") + manifest = read_json(metadata.source_manifest_path) + checksum = manifest.get("checksum") if isinstance(manifest, dict) else None + if not ( + isinstance(manifest, dict) + and manifest.get("path") == metadata.source_path.name + and isinstance(checksum, dict) + and checksum.get("value") == metadata.source_artifact_id + ): + raise RuntimeError("exchange metadata source manifest is not bound to its raw response") + + +def _artifact_kind(path: Path, root: Path) -> str: + relative = path.relative_to(root).as_posix() + name = path.name + if "/depth_stream/" in f"/{relative}" and name.endswith(".ndjson"): + return "raw_journal" + if "/depth_stream/" in f"/{relative}" and ".ndjson.manifest-" in name: + return "raw_journal_manifest" + if "/depth_snapshots/" in f"/{relative}" and ".json.manifest-" in name: + return "raw_snapshot_manifest" + if "/depth_snapshots/" in f"/{relative}" and name.endswith(".json"): + return "raw_snapshot" + if "/exchange_info/" in f"/{relative}" and ".json.manifest-" in name: + return "raw_metadata_manifest" + if "/exchange_info/" in f"/{relative}" and name.endswith(".json"): + return "raw_metadata" + if relative.startswith("normalized/") and name.endswith(".parquet"): + return "normalized_data" + if relative.startswith("normalized/") and name.endswith(".json"): + return "normalized_manifest" + if relative.startswith("quality/") and name.endswith(".summary.json"): + return "capture_summary" + if relative.startswith("quality/") and name.endswith(".json"): + return "quality_report" + return "partial_evidence" + + +def _artifacts(root: Path) -> tuple[CapturedArtifact, ...]: + result: list[CapturedArtifact] = [] + for path in sorted(root.rglob("*"), key=lambda item: item.as_posix()): + relative_parts = path.relative_to(root).parts + if relative_parts and relative_parts[0].startswith(".arrow-spool-"): + continue + if path.is_symlink(): + raise RuntimeError(f"symbol evidence contains a symlink: {path}") + if path.is_file(): + result.append( + CapturedArtifact( + path=path, + kind=_artifact_kind(path, root), + sha256=sha256_file(path), + ) + ) + return tuple(result) + + +def _classify_binance_data_error(error: BaseException) -> _DataCaptureIssue | None: + if isinstance(error, UnicodeDecodeError): + return _DataCaptureIssue("RAW_UTF8_DECODE_FAILED", "NORMALIZATION", str(error)) + if isinstance(error, BinanceHTTPError): + if error.status_code in {404, 410} and not error.retry_exhausted: + return _DataCaptureIssue("DECLARED_OBJECT_UNAVAILABLE", "PUBLIC_METADATA", str(error)) + return _DataCaptureIssue("PUBLIC_TRANSPORT_UNAVAILABLE", "PUBLIC_METADATA", str(error)) + if isinstance(error, (BinanceMetadataContractError, BinanceResponseSizeLimitError)): + return _DataCaptureIssue("PUBLIC_PAYLOAD_CONTRACT_FAILED", "PUBLIC_METADATA", str(error)) + if isinstance(error, BinancePayloadError) and not error.transient: + return _DataCaptureIssue("PUBLIC_PAYLOAD_CONTRACT_FAILED", "NORMALIZATION", str(error)) + if isinstance(error, BookInvariantError): + return _DataCaptureIssue("BOOK_INVARIANT_FAILED", "RECONSTRUCTION", str(error)) + return None + + +@dataclass(slots=True) +class _CaptureState: + current_continuity_id: str | None = None + reconstructor: IncrementalBookReconstructor | None = None + continuity_epochs: int = 0 + reconstruction_status: Literal["LIVE", "GAPPED", "INVALID", "NOT_STARTED"] = "NOT_STARTED" + excluded_rows: int = 0 + sequence_gaps: int = 0 + stale_rows: int = 0 + max_queue_depth: int = 0 + max_queue_estimated_bytes: int = 0 + + +class BinanceM8L2Capture: + """Callable production implementation of the frozen ``CaptureOne`` protocol.""" + + def __init__( + self, + *, + client_factory: Callable[[], _Client] | None = None, + collector_factory: Callable[..., _Collector] | None = None, + clock_ns: Callable[[], int] = time.time_ns, + receiver_queue_capacity: int = _DEFAULT_RECEIVER_QUEUE_CAPACITY, + ) -> None: + if receiver_queue_capacity < 1: + raise ValueError("receiver_queue_capacity must be positive") + self._client_factory = client_factory or cast(Callable[[], _Client], BinancePublicClient) + self._collector_factory = collector_factory or cast( + Callable[..., _Collector], BinanceLiveDepthCollector + ) + self._clock_ns = clock_ns + self._receiver_queue_capacity = receiver_queue_capacity + + async def __call__( + self, + *, + symbol: str, + scheduled_start_ns: int, + scheduled_end_ns: int, + stage_root: Path, + limits: M8L2CaptureLimits, + session_id: str, + ) -> SymbolCaptureResult: + if scheduled_end_ns <= scheduled_start_ns: + raise ValueError("scheduled_end_ns must be after scheduled_start_ns") + if limits.max_messages_per_symbol < 1: + raise ValueError("message ceiling must be positive") + if limits.max_raw_frame_bytes < 1 or limits.max_arrow_batch_bytes < 1: + raise ValueError("capture byte ceilings must be positive") + normalized_symbol = symbol.upper() + if normalized_symbol not in {"BTCUSDT", "ETHUSDT"}: + raise ValueError(f"unsupported frozen L2 symbol: {symbol}") + stage = stage_root.resolve() + stage.mkdir(parents=True, exist_ok=True) + if any(stage.iterdir()): + raise RuntimeError("single-symbol capture stage must start empty") + capture_id = f"{normalized_symbol.lower()}-{session_id[:20]}" + queue_capacity = min( + self._receiver_queue_capacity, + limits.max_messages_per_symbol, + ) + queue_byte_budget = limits.max_arrow_batch_bytes + journal = _RawJournal( + root=stage, + symbol=normalized_symbol, + source_uri=_SOURCE_URI, + scheduled_start_ns=scheduled_start_ns, + scheduled_end_ns=scheduled_end_ns, + max_frame_bytes=limits.max_raw_frame_bytes, + max_messages=limits.max_messages_per_symbol, + ) + state = _CaptureState() + interval_tracker = _ObservedIntervals() + client = self._client_factory() + receiver_task: asyncio.Task[None] | None = None + capture_error: BaseException | None = None + completion_reason = "capture_failed" + metadata: SymbolMetadata | None = None + raw_evidence: _PublishedJournal | None = None + validation_reports: tuple[ValidationReport, ValidationReport] | None = None + + with tempfile.TemporaryDirectory(dir=stage, prefix=".arrow-spool-") as spool_name: + spool_root = Path(spool_name) + delta_validator = IncrementalQualityValidator( + "depth_deltas", row_chunk_size=_BATCH_ROWS + ) + observation_validator = IncrementalQualityValidator( + "book_observations", row_chunk_size=_BATCH_ROWS + ) + validators_finished = False + spools = { + "book_snapshots": _ArrowSpool( + root=spool_root, + schema_name="book_snapshots", + max_batch_bytes=limits.max_arrow_batch_bytes, + ), + "depth_deltas": _ArrowSpool( + root=spool_root, + schema_name="depth_deltas", + max_batch_bytes=limits.max_arrow_batch_bytes, + on_batch=delta_validator.update, + ), + "book_observations": _ArrowSpool( + root=spool_root, + schema_name="book_observations", + max_batch_bytes=limits.max_arrow_batch_bytes, + on_batch=observation_validator.update, + ), + "sequence_gaps": _ArrowSpool( + root=spool_root, + schema_name="sequence_gaps", + max_batch_bytes=limits.max_arrow_batch_bytes, + ), + } + try: + if self._clock_ns() >= scheduled_end_ns: + raise _DataCaptureIssue( + "MISSED_WINDOW", "CAPTURE_START", "scheduled capture window already ended" + ) + try: + metadata = await _to_thread_joined( + client.fetch_exchange_info, + symbol=normalized_symbol, + raw_root=stage / "raw", + ) + except BaseException as error: + classified = _classify_binance_data_error(error) + if classified is not None: + raise classified from error + raise + _verify_metadata_files(stage, metadata) + if metadata.symbol != normalized_symbol or metadata.venue != "binance_spot": + raise _DataCaptureIssue( + "METADATA_IDENTITY_MISMATCH", + "PUBLIC_METADATA", + "exchange metadata venue/symbol differs from the requested feed", + ) + if metadata.status != "TRADING": + raise _DataCaptureIssue( + "SYMBOL_NOT_TRADING", + "PUBLIC_METADATA", + f"{normalized_symbol} exchange status is {metadata.status!r}", + ) + if self._clock_ns() >= scheduled_end_ns: + raise _DataCaptureIssue( + "METADATA_EXHAUSTED_WINDOW", + "PUBLIC_METADATA", + "metadata acquisition consumed the scheduled capture window", + ) + + def preserve_in_window_frame(frame: RawDepthFrame) -> None: + if frame.received_ts_ns >= scheduled_end_ns: + raise _ScheduledEndReached + try: + journal.append_frame(frame) + except (_DataCaptureIssue, _ScheduledEndReached): + raise + except OSError as error: + raise _LocalEvidenceSystemError("local raw-journal write failed") from error + + collector = self._collector_factory( + symbols=(normalized_symbol,), + tick_size=metadata.tick_size, + lot_size=metadata.lot_size, + on_raw_frame=preserve_in_window_frame, + ) + journal.source_uri = collector.url + queue: asyncio.Queue[tuple[CapturedDepth, int]] = asyncio.Queue( + maxsize=queue_capacity + ) + queue_condition = asyncio.Condition() + queued_estimated_bytes = 0 + + async def receive() -> None: + nonlocal queued_estimated_bytes + iterator = collector.stream(max_messages=None).__aiter__() + try: + while True: + remaining_ns = scheduled_end_ns - self._clock_ns() + if remaining_ns <= 0: + return + try: + item = await asyncio.wait_for( + anext(iterator), + timeout=remaining_ns / 1_000_000_000, + ) + except _ScheduledEndReached: + return + except TimeoutError: + # Re-read absolute wall time. Suspend/resume or a + # wall-clock adjustment must not turn this into a + # relative-duration completion. + continue + except PermissionError: + raise + except (OSError, WebSocketException) as error: + raise _DataCaptureIssue( + "PUBLIC_STREAM_UNAVAILABLE", + "RAW_CAPTURE", + "public websocket transport was exhausted during the " + "declared frozen window", + ) from error + except StopAsyncIteration: + if self._clock_ns() < scheduled_end_ns: + raise _DataCaptureIssue( + "STREAM_ENDED_EARLY", + "RAW_CAPTURE", + "public depth stream ended before scheduled UTC end", + ) from None + return + received_ns = item.delta.received_ts_ns + if received_ns is None: + raise _DataCaptureIssue( + "MISSING_RAW_LINEAGE", + "NORMALIZATION", + "captured message lacks local receipt time", + ) + if received_ns < scheduled_start_ns: + continue + if received_ns >= scheduled_end_ns: + return + journal.consume_captured(item) + raw_size = len(item.raw_payload.encode("utf-8")) + item_estimated_bytes = max( + 4_096, raw_size * _VARIABLE_RECORD_OVERHEAD_FACTOR + ) + if item_estimated_bytes > queue_byte_budget: + raise _DataCaptureIssue( + "RECEIVER_QUEUE_ITEM_BYTES_EXCEEDED", + "RAW_CAPTURE", + "one parsed frame exceeds the bounded receiver queue budget", + ) + async with queue_condition: + while ( + queued_estimated_bytes + item_estimated_bytes + > queue_byte_budget + or queue.full() + ): + remaining_ns = scheduled_end_ns - self._clock_ns() + if remaining_ns <= 0: + raise _DataCaptureIssue( + "PROCESSING_BACKLOG_AT_END", + "RAW_CAPTURE", + "bounded receiver queue remained full at scheduled end", + ) + try: + await asyncio.wait_for( + queue_condition.wait(), + timeout=remaining_ns / 1_000_000_000, + ) + except TimeoutError: + raise _DataCaptureIssue( + "PROCESSING_BACKLOG_AT_END", + "RAW_CAPTURE", + "bounded receiver queue remained full at scheduled end", + ) from None + queue.put_nowait((item, item_estimated_bytes)) + queued_estimated_bytes += item_estimated_bytes + state.max_queue_depth = max(state.max_queue_depth, queue.qsize()) + state.max_queue_estimated_bytes = max( + state.max_queue_estimated_bytes, queued_estimated_bytes + ) + finally: + closer = getattr(iterator, "aclose", None) + if callable(closer): + with suppress(BaseException): + await closer() + + receiver_task = asyncio.create_task( + receive(), name=f"m8-l2-receiver-{normalized_symbol}" + ) + + async def release_item(queued: tuple[CapturedDepth, int]) -> CapturedDepth: + nonlocal queued_estimated_bytes + item, estimated_bytes = queued + async with queue_condition: + queued_estimated_bytes -= estimated_bytes + if queued_estimated_bytes < 0: # pragma: no cover - accounting invariant + raise RuntimeError("receiver queue byte accounting became negative") + queue_condition.notify_all() + return item + + async def next_item() -> CapturedDepth | None: + if not queue.empty(): + return await release_item(queue.get_nowait()) + if receiver_task is None: # pragma: no cover - construction invariant + raise RuntimeError("receiver task was not initialized") + if receiver_task.done(): + await receiver_task + return None + get_task = asyncio.create_task(queue.get()) + done, _ = await asyncio.wait( + {get_task, receiver_task}, return_when=asyncio.FIRST_COMPLETED + ) + if get_task in done: + return await release_item(get_task.result()) + get_task.cancel() + with suppress(asyncio.CancelledError): + await get_task + if not queue.empty(): + return await release_item(queue.get_nowait()) + await receiver_task + return None + + while True: + item = await next_item() + if item is None: + break + delta = item.delta + received_ns = delta.received_ts_ns + if received_ns is None: # pragma: no cover - receiver checks + raise RuntimeError("processed delta has no receipt timestamp") + if delta.continuity_id != state.current_continuity_id: + interval_tracker.break_continuity() + try: + snapshot = await _to_thread_joined( + client.fetch_depth_snapshot, + symbol=normalized_symbol, + raw_root=stage / "raw", + continuity_id=delta.continuity_id, + tick_size=metadata.tick_size, + lot_size=metadata.lot_size, + ) + except BaseException as error: + classified = _classify_binance_data_error(error) + if classified is not None: + classified.phase = "SNAPSHOT_ANCHOR" + raise classified from error + raise + if not (scheduled_start_ns <= snapshot.received_ts_ns < scheduled_end_ns): + raise _DataCaptureIssue( + "SNAPSHOT_OUTSIDE_WINDOW", + "SNAPSHOT_ANCHOR", + "continuity snapshot was not received inside the frozen window", + ) + raw_snapshot, snapshot_manifest = _snapshot_files(stage, snapshot) + journal.append_snapshot( + snapshot, + raw_path=raw_snapshot, + manifest_path=snapshot_manifest, + ) + spools["book_snapshots"].append( + snapshot.to_record(), + estimated_bytes=max( + 4_096, 128 * (len(snapshot.bids) + len(snapshot.asks)) + ), + ) + state.reconstructor = IncrementalBookReconstructor(snapshot) + state.current_continuity_id = delta.continuity_id + state.continuity_epochs += 1 + state.reconstruction_status = "LIVE" + + reconstructor = state.reconstructor + if reconstructor is None: # pragma: no cover - guarded above + raise RuntimeError("continuity has no snapshot reconstructor") + raw_bytes = len(item.raw_payload.encode("utf-8")) + spools["depth_deltas"].append( + delta.to_record(), + estimated_bytes=max(4_096, raw_bytes * _VARIABLE_RECORD_OVERHEAD_FACTOR), + ) + try: + step = reconstructor.update(delta) + except BaseException as error: + classified = _classify_binance_data_error(error) + if classified is not None: + raise classified from error + raise + if step.observation is not None: + spools["book_observations"].append(step.observation, estimated_bytes=4_096) + else: + state.excluded_rows += 1 + if step.gap is not None: + spools["sequence_gaps"].append(step.gap.to_record(), estimated_bytes=2_048) + state.sequence_gaps += 1 + if step.outcome == "OBSERVED": + if step.observation is None: # pragma: no cover - outcome invariant + raise RuntimeError("OBSERVED step lacks its book observation") + available_ns = step.observation["available_ts_ns"] + if isinstance(available_ns, bool) or not isinstance(available_ns, int): + raise RuntimeError( + "OBSERVED book availability timestamp is not an integer" + ) + interval_tracker.observed( + delta.continuity_id, + available_ns, + ) + else: + interval_tracker.excluded(delta.continuity_id) + if step.outcome == "STALE": + state.stale_rows += 1 + state.reconstruction_status = reconstructor.status + if step.outcome in {"GAP", "INVALID", "EXCLUDED_AFTER_TERMINAL"}: + raise _DataCaptureIssue( + "SEQUENCE_CONTINUITY_FAILED", + "RECONSTRUCTION", + f"{normalized_symbol} reconstruction outcome was {step.outcome}", + ) + + if journal.messages == 0: + raise _DataCaptureIssue( + "NO_IN_WINDOW_MESSAGES", + "RAW_CAPTURE", + "scheduled window contained no accepted depth frames", + ) + if self._clock_ns() < scheduled_end_ns: + raise _DataCaptureIssue( + "SCHEDULED_END_NOT_REACHED", + "RAW_CAPTURE", + "capture transport stopped before the absolute scheduled UTC end", + ) + completion_reason = "scheduled_end_reached" + except BaseException as error: + capture_error = _classify_binance_data_error(error) or error + finally: + if receiver_task is not None and not receiver_task.done(): + receiver_task.cancel() + with suppress(BaseException): + await receiver_task + + finalization_error: BaseException | None = None + try: + for spool in spools.values(): + spool.close() + validation_reports = ( + delta_validator.finish(), + observation_validator.finish(), + ) + validators_finished = True + raw_evidence = journal.publish( + capture_status=( + "raw_capture_complete" if capture_error is None else "incomplete_capture" + ), + error=capture_error, + ) + normalized_root = stage / "normalized" / "captures" / capture_id + time_columns = { + "book_snapshots": "received_ts_ns", + "depth_deltas": "event_ts_ns", + "book_observations": "event_ts_ns", + "sequence_gaps": "detected_ts_ns", + } + dataset_manifests: dict[str, dict[str, object]] = {} + for schema_name, spool in spools.items(): + stored = write_capture_parquet( + spool.iter_batches(), + root=normalized_root, + dataset=schema_name, + schema_name=schema_name, + venue="binance_spot", + symbol=normalized_symbol, + capture_id=capture_id, + source="binance_spot_public_live_capture_journal", + source_uri=str(raw_evidence.path.relative_to(stage)), + source_checksum_sha256=raw_evidence.sha256, + requested_start_ns=scheduled_start_ns, + requested_end_ns=scheduled_end_ns, + time_column=time_columns[schema_name], + max_input_batch_rows=_BATCH_ROWS, + ) + if stored.rows != spool.rows: + raise RuntimeError( + f"stored {schema_name} rows differ from its verified Arrow spool" + ) + dataset_manifests[schema_name] = { + "data_path": ( + str(stored.data_path.relative_to(stage)) + if stored.data_path is not None + else None + ), + "data_sha256": stored.data_sha256, + "manifest_path": str(stored.manifest_path.relative_to(stage)), + "manifest_sha256": stored.manifest_sha256, + "rows": stored.rows, + } + + quality_root = stage / "quality" + quality_root.mkdir(parents=True, exist_ok=True) + quality_paths: dict[str, str] = {} + for report in validation_reports: + report_path = quality_root / f"{report.dataset}.validation.json" + report.write_json(report_path) + quality_paths[report.dataset] = report_path.relative_to(stage).as_posix() + intervals = interval_tracker.finish() + quality_errors = sum(item.error_count for item in validation_reports) + quality_warnings = sum(item.warning_count for item in validation_reports) + summary_path = quality_root / "capture.summary.json" + inventory_without_summary = _artifacts(stage) + summary_payload: dict[str, object] = { + "schema_version": "m8-binance-l2-symbol-capture-v1", + "generated_at_utc": utc_now_iso(), + "capture_id": capture_id, + "symbol": normalized_symbol, + "capture_status": "COMPLETE" if capture_error is None else "FAILED", + "completion_reason": completion_reason, + "failure_reason_code": ( + capture_error.reason_code + if isinstance(capture_error, _DataCaptureIssue) + else None + ), + "failure_phase": ( + capture_error.phase + if isinstance(capture_error, _DataCaptureIssue) + else None + ), + "failure_type": ( + type(capture_error).__name__ if capture_error is not None else None + ), + "failure_message": ( + str(capture_error)[:2048] if capture_error is not None else None + ), + "scheduled_range_ns": { + "start": scheduled_start_ns, + "end_exclusive": scheduled_end_ns, + }, + "messages": journal.messages, + "first_raw_received_ns": journal.first_received_ns, + "last_raw_received_ns": journal.last_received_ns, + "normalized_rows": spools["depth_deltas"].rows, + "reconstructed_rows": spools["book_observations"].rows, + "excluded_rows": spools["depth_deltas"].rows - spools["book_observations"].rows, + "continuity_epochs": state.continuity_epochs, + "snapshot_anchors": journal.snapshot_anchors, + "sequence_gaps": spools["sequence_gaps"].rows, + "stale_rows": state.stale_rows, + "reconstruction_status": state.reconstruction_status, + "quality_errors": quality_errors, + "quality_warnings": quality_warnings, + "quality_reports": quality_paths, + "valid_observed_intervals": [item.to_dict() for item in intervals], + "raw_journal": raw_evidence.path.relative_to(stage).as_posix(), + "raw_journal_sha256": raw_evidence.sha256, + "raw_journal_manifest": raw_evidence.manifest_path.relative_to( + stage + ).as_posix(), + "raw_journal_manifest_sha256": raw_evidence.manifest_sha256, + "normalized_dataset_manifests": dataset_manifests, + "artifact_inventory_without_summary": [ + { + "path": item.path.relative_to(stage).as_posix(), + "kind": item.kind, + "sha256": item.sha256, + "bytes": item.path.stat().st_size, + } + for item in inventory_without_summary + ], + "receiver_queue_capacity": queue_capacity, + "receiver_queue_estimated_byte_budget": queue_byte_budget, + "max_receiver_queue_depth": state.max_queue_depth, + "max_receiver_queue_estimated_bytes": state.max_queue_estimated_bytes, + "max_raw_frame_bytes_observed": journal.max_frame_bytes_observed, + "max_arrow_batch_bytes_observed": max( + spool.max_batch_bytes_observed for spool in spools.values() + ), + "live_trading": False, + "policy": ( + "raw websocket bytes precede parsing; snapshots are fresh per continuity; " + "only consecutive OBSERVED receipts with no >5s silence form coverage" + ), + } + write_json(summary_path, summary_payload) + except BaseException as error: + finalization_error = error + finally: + if not validators_finished: + delta_validator.close() + observation_validator.close() + if raw_evidence is None: + with suppress(BaseException): + raw_evidence = journal.publish( + capture_status="finalization_failure", error=finalization_error + ) + journal.close_without_publish() + + if finalization_error is not None: + if capture_error is not None: + finalization_error.add_note( + f"capture also failed with {type(capture_error).__name__}: {capture_error}" + ) + raise finalization_error + + if validation_reports is None or raw_evidence is None: + raise RuntimeError("capture finalization omitted required evidence") + intervals = interval_tracker.finish() + quality_errors = sum(item.error_count for item in validation_reports) + quality_warnings = sum(item.warning_count for item in validation_reports) + result = SymbolCaptureResult( + symbol=normalized_symbol, + capture_id=capture_id, + status="FAILED" if capture_error is not None else "COMPLETE", + completion_reason=completion_reason, + reconstruction_status=state.reconstruction_status, + messages=journal.messages, + normalized_rows=spools["depth_deltas"].rows, + reconstructed_rows=spools["book_observations"].rows, + excluded_rows=spools["depth_deltas"].rows - spools["book_observations"].rows, + continuity_epochs=state.continuity_epochs, + snapshot_anchors=journal.snapshot_anchors, + sequence_gaps=spools["sequence_gaps"].rows, + quality_errors=quality_errors, + quality_warnings=quality_warnings, + max_raw_frame_bytes_observed=journal.max_frame_bytes_observed, + max_arrow_batch_bytes_observed=max( + spool.max_batch_bytes_observed for spool in spools.values() + ), + first_raw_received_ns=journal.first_received_ns, + last_raw_received_ns=journal.last_received_ns, + valid_observed_intervals=intervals, + artifacts=_artifacts(stage), + failure_reason_code=( + capture_error.reason_code + if isinstance(capture_error, _DataCaptureIssue) + else None + ), + failure_phase=( + capture_error.phase if isinstance(capture_error, _DataCaptureIssue) else None + ), + ) + if capture_error is None: + return result + if isinstance(capture_error, _DataCaptureIssue): + raise M8L2DataFailure( + capture_error.reason_code, + phase=capture_error.phase, + message=str(capture_error), + partial_result=result, + ) from capture_error + raise capture_error + + +__all__ = ["BinanceM8L2Capture"] diff --git a/Microstructure/src/microstructure/m8_l2_capture.py b/Microstructure/src/microstructure/m8_l2_capture.py new file mode 100644 index 0000000000000000000000000000000000000000..6d321cd1c52ec301f354e364ab757dfd3e67db51 --- /dev/null +++ b/Microstructure/src/microstructure/m8_l2_capture.py @@ -0,0 +1,3456 @@ +"""Cross-symbol authority and terminal publication for frozen M8 L2 sessions. + +This module deliberately depends on an injected, typed single-symbol capture +producer. It does not import the exploratory CLI collector and contains no +exchange connection or order-entry path. +""" + +from __future__ import annotations + +import asyncio +import base64 +import binascii +import hashlib +import importlib.metadata as importlib_metadata +import json +import os +import platform +import secrets +import shutil +import stat +import subprocess +import sys +import tempfile +import time +from collections.abc import Mapping, Sequence +from contextlib import suppress +from dataclasses import dataclass +from pathlib import Path, PurePosixPath +from typing import Any, Literal, Protocol, cast + +import pyarrow.parquet as pq # type: ignore[import-untyped] + +from microstructure.data.schemas import SCHEMA_VERSION, get_schema +from microstructure.m8_l2_config import ( + M8_L2_CONFIG_SOURCE_SHA256, + M8_L2_FREEZE_COMMIT, + M8_L2_PROTOCOL_SHA256, + M8L2CaptureLimits, + M8L2Session, + M8L2StudyConfig, + load_m8_l2_config, +) +from microstructure.provenance import ( + ImportOriginError, + assert_project_module_origins, + sha256_file, + utc_now_iso, + write_json, +) + +_SESSION_SCHEMA_VERSION = "m8-live-l2-session-v3" +_CAMPAIGN_SCHEMA_VERSION = "m8-live-l2-campaign-authority-v2" +_RUNTIME_SCHEMA_VERSION = "m8-live-l2-runtime-fingerprint-v1" +_CAMPAIGN_AUTHORITY_NAME = "campaign_authority.json" +_CHECKSUM_NAME = "CHECKSUMS.sha256" +_COMPLETE_MARKER = "_SUCCESS" +_INSUFFICIENT_MARKER = "INSUFFICIENT_DATA" +_COMPLETE_BYTES = b"complete\n" +_INSUFFICIENT_BYTES = b"terminal\n" +_NANOSECONDS_PER_SECOND = 1_000_000_000 +_MAX_JSON_AUTHORITY_BYTES = 8 * 1024 * 1024 +_MAX_CAMPAIGN_AUTHORITY_BYTES = 16 * 1024 +_RUNTIME_DISTRIBUTIONS = ( + "duckdb", + "numpy", + "polars", + "pyarrow", + "requests", + "scikit-learn", + "streamlit", + "websockets", +) +_SYMBOL_SUMMARY_SCHEMA_VERSION = "m8-binance-l2-symbol-capture-v1" +_REQUIRED_CAPTURE_ARTIFACT_KINDS = frozenset( + { + "capture_summary", + "normalized_data", + "normalized_manifest", + "quality_report", + "raw_journal", + "raw_journal_manifest", + "raw_snapshot", + "raw_snapshot_manifest", + } +) + +SessionStatus = Literal["COMPLETE", "INSUFFICIENT_DATA"] +CaptureStatus = Literal["COMPLETE", "FAILED"] +ReconstructionStatus = Literal["LIVE", "GAPPED", "INVALID", "NOT_STARTED"] + + +class M8L2CaptureError(RuntimeError): + """Base class for orchestration, authority, and verification failures.""" + + +class M8L2VerificationError(M8L2CaptureError): + """Raised when a session bundle is not an exact immutable authority.""" + + +class M8L2CaptureSystemError(M8L2CaptureError): + """A nonterminal program/I/O failure; captured raw evidence is retained.""" + + def __init__(self, message: str, *, evidence_root: Path | None = None) -> None: + super().__init__(message) + self.evidence_root = evidence_root + + +class M8L2DataFailure(M8L2CaptureError): + """Typed prospective-session failure that may terminalize as insufficient.""" + + def __init__( + self, + reason_code: str, + *, + phase: str, + message: str, + partial_result: SymbolCaptureResult | None = None, + ) -> None: + _validate_code(reason_code, "reason code") + _validate_code(phase, "failure phase") + super().__init__(message) + self.reason_code = reason_code + self.phase = phase + self.partial_result = partial_result + + +@dataclass(frozen=True, slots=True) +class CaptureSourceIdentity: + """Clean runtime source identity bound into one prospective session.""" + + commit: str + source_tree_sha256: str + dirty: bool + + +@dataclass(frozen=True, slots=True) +class _RuntimeFingerprint: + """Canonical production interpreter/dependency identity.""" + + python_implementation: str + python_version: str + platform_system: str + platform_release: str + platform_machine: str + dependencies: tuple[tuple[str, str], ...] + sha256: str + + def payload(self) -> dict[str, object]: + return _runtime_payload( + python_implementation=self.python_implementation, + python_version=self.python_version, + platform_system=self.platform_system, + platform_release=self.platform_release, + platform_machine=self.platform_machine, + dependencies=self.dependencies, + ) + + +@dataclass(frozen=True, slots=True) +class _CampaignAuthority: + """Exact durable campaign identity shared by all four frozen sessions.""" + + path: Path + sha256: str + raw: bytes + source: CaptureSourceIdentity + runtime: _RuntimeFingerprint + nonce: str + output_root_path: str + output_root_device: int + output_root_inode: int + + +@dataclass(frozen=True, slots=True) +class ObservedInterval: + """One continuous interval backed only by OBSERVED reconstructed states.""" + + continuity_id: str + start_received_ns: int + end_received_ns_exclusive: int + + def __post_init__(self) -> None: + if not self.continuity_id: + raise ValueError("observed interval continuity_id must not be empty") + if self.start_received_ns < 0: + raise ValueError("observed interval start must be nonnegative") + if self.end_received_ns_exclusive <= self.start_received_ns: + raise ValueError("observed interval end must be after start") + + @property + def duration_ns(self) -> int: + return self.end_received_ns_exclusive - self.start_received_ns + + def to_dict(self) -> dict[str, object]: + return { + "continuity_id": self.continuity_id, + "start_received_ns": self.start_received_ns, + "end_received_ns_exclusive": self.end_received_ns_exclusive, + "duration_ns": self.duration_ns, + "duration_seconds": self.duration_ns / _NANOSECONDS_PER_SECOND, + } + + +@dataclass(frozen=True, slots=True) +class CapturedArtifact: + """Explicit file coordinate returned by a single-symbol capture producer.""" + + path: Path + kind: str + sha256: str + + +@dataclass(frozen=True, slots=True) +class SymbolCaptureResult: + """Bounded descriptor for one symbol's complete or partial capture evidence.""" + + symbol: str + capture_id: str + status: CaptureStatus + completion_reason: str + reconstruction_status: ReconstructionStatus + messages: int + normalized_rows: int + reconstructed_rows: int + excluded_rows: int + continuity_epochs: int + snapshot_anchors: int + sequence_gaps: int + quality_errors: int + quality_warnings: int + max_raw_frame_bytes_observed: int + max_arrow_batch_bytes_observed: int + first_raw_received_ns: int | None + last_raw_received_ns: int | None + valid_observed_intervals: tuple[ObservedInterval, ...] + artifacts: tuple[CapturedArtifact, ...] + failure_reason_code: str | None = None + failure_phase: str | None = None + + +class CaptureOne(Protocol): + """Injected adapter boundary for one duration- and boundary-aware capture.""" + + async def __call__( + self, + *, + symbol: str, + scheduled_start_ns: int, + scheduled_end_ns: int, + stage_root: Path, + limits: M8L2CaptureLimits, + session_id: str, + ) -> SymbolCaptureResult: ... + + +class CaptureClock(Protocol): + def time_ns(self) -> int: ... + + async def sleep(self, seconds: float) -> None: ... + + +class _SystemClock: + def time_ns(self) -> int: + return time.time_ns() + + async def sleep(self, seconds: float) -> None: + await asyncio.sleep(seconds) + + +@dataclass(frozen=True, slots=True) +class M8L2SessionBundle: + root: Path + status: SessionStatus + session_id: str + session_date: str + role: str + manifest_path: Path + manifest_sha256: str + checksum_path: Path + marker_path: Path + reason_codes: tuple[str, ...] + + +def _validate_code(value: str, label: str) -> None: + if not value or any( + character not in "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_" for character in value + ): + raise ValueError(f"{label} must use uppercase letters, digits, and underscores") + + +def _is_lower_sha256(value: str) -> bool: + return len(value) == 64 and all(character in "0123456789abcdef" for character in value) + + +def _stable_sha256(payload: Mapping[str, object]) -> str: + encoded = json.dumps( + dict(payload), sort_keys=True, separators=(",", ":"), allow_nan=False + ).encode() + return hashlib.sha256(encoded).hexdigest() + + +def _run_git_text(project_root: Path, arguments: Sequence[str], *, label: str) -> str: + try: + result = subprocess.run( + ["git", *arguments], + cwd=project_root, + check=False, + capture_output=True, + text=True, + env={**os.environ, "GIT_OPTIONAL_LOCKS": "0"}, + ) + except (OSError, UnicodeError) as error: + raise M8L2CaptureSystemError(f"cannot execute Git {label}") from error + if result.returncode != 0: + raise M8L2CaptureSystemError(f"Git {label} failed with exit {result.returncode}") + return result.stdout + + +def _run_git_bytes(project_root: Path, arguments: Sequence[str], *, label: str) -> bytes: + try: + result = subprocess.run( + ["git", *arguments], + cwd=project_root, + check=False, + capture_output=True, + env={**os.environ, "GIT_OPTIONAL_LOCKS": "0"}, + ) + except OSError as error: + raise M8L2CaptureSystemError(f"cannot execute Git {label}") from error + if result.returncode != 0: + raise M8L2CaptureSystemError(f"Git {label} failed with exit {result.returncode}") + return result.stdout + + +def _strict_git_revision(project_root: Path) -> str: + output = _run_git_text(project_root, ("rev-parse", "HEAD"), label="revision lookup") + lines = output.splitlines() + if len(lines) != 1: + raise M8L2CaptureSystemError("Git revision lookup returned a noncanonical result") + return lines[0] + + +def _strict_git_status(project_root: Path) -> str: + return _run_git_text( + project_root, + ("status", "--porcelain=v1", "--untracked-files=normal"), + label="status lookup", + ) + + +def _hash_regular_nofollow(path: Path, metadata: os.stat_result) -> str: + flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) + try: + descriptor = os.open(path, flags) + except OSError as error: + raise M8L2CaptureSystemError(f"cannot open Git source file: {path}") from error + try: + opened = os.fstat(descriptor) + if not stat.S_ISREG(opened.st_mode) or ( + opened.st_dev, + opened.st_ino, + opened.st_size, + opened.st_mtime_ns, + opened.st_ctime_ns, + ) != ( + metadata.st_dev, + metadata.st_ino, + metadata.st_size, + metadata.st_mtime_ns, + metadata.st_ctime_ns, + ): + raise M8L2CaptureSystemError(f"Git source file changed before hashing: {path}") + digest = hashlib.sha256() + while chunk := os.read(descriptor, 1024 * 1024): + digest.update(chunk) + after = os.fstat(descriptor) + named = path.lstat() + coordinates = ( + opened.st_dev, + opened.st_ino, + opened.st_size, + opened.st_mtime_ns, + opened.st_ctime_ns, + ) + if coordinates != ( + after.st_dev, + after.st_ino, + after.st_size, + after.st_mtime_ns, + after.st_ctime_ns, + ) or coordinates != ( + named.st_dev, + named.st_ino, + named.st_size, + named.st_mtime_ns, + named.st_ctime_ns, + ): + raise M8L2CaptureSystemError(f"Git source file changed while hashing: {path}") + return digest.hexdigest() + except OSError as error: + raise M8L2CaptureSystemError(f"cannot hash Git source file: {path}") from error + finally: + os.close(descriptor) + + +def _strict_source_tree_sha256(repository_root: Path, listing: bytes) -> str: + encoded_paths = [item for item in listing.split(b"\0") if item] + if len(encoded_paths) != len(set(encoded_paths)): + raise M8L2CaptureSystemError("Git source-tree listing contains duplicate paths") + digest = hashlib.sha256() + for encoded_relative in sorted(encoded_paths): + relative = Path(os.fsdecode(encoded_relative)) + if relative.is_absolute() or not relative.parts or ".." in relative.parts: + raise M8L2CaptureSystemError("Git source-tree listing contains an unsafe path") + path = repository_root / relative + digest.update(len(encoded_relative).to_bytes(8, "big")) + digest.update(encoded_relative) + try: + metadata = path.lstat() + except FileNotFoundError: + digest.update(b"MISSING\0") + continue + except OSError as error: + raise M8L2CaptureSystemError(f"cannot inspect Git source path: {path}") from error + digest.update((metadata.st_mode & 0o7777).to_bytes(4, "big")) + if stat.S_ISLNK(metadata.st_mode): + try: + target = os.readlink(path).encode("utf-8", errors="surrogateescape") + repeated = path.lstat() + except OSError as error: + raise M8L2CaptureSystemError(f"cannot hash Git source symlink: {path}") from error + if (metadata.st_dev, metadata.st_ino, metadata.st_mtime_ns, metadata.st_ctime_ns) != ( + repeated.st_dev, + repeated.st_ino, + repeated.st_mtime_ns, + repeated.st_ctime_ns, + ): + raise M8L2CaptureSystemError(f"Git source symlink changed while hashing: {path}") + digest.update(b"SYMLINK\0") + digest.update(len(target).to_bytes(8, "big")) + digest.update(target) + elif stat.S_ISREG(metadata.st_mode): + digest.update(b"FILE\0") + digest.update(_hash_regular_nofollow(path, metadata).encode()) + else: + digest.update(b"OTHER\0") + return digest.hexdigest() + + +def _source_identity(project_root: Path) -> CaptureSourceIdentity: + """Take one fail-closed clean Git snapshot without lenient provenance fallbacks.""" + + first_revision = _strict_git_revision(project_root) + first_status = _strict_git_status(project_root) + if first_status.strip(): + raise M8L2CaptureSystemError( + "prospective live-L2 capture requires a clean runtime source tree" + ) + top_level_raw = _run_git_text( + project_root, + ("rev-parse", "--show-toplevel"), + label="repository-root lookup", + ) + top_level_lines = top_level_raw.splitlines() + if len(top_level_lines) != 1 or not top_level_lines[0]: + raise M8L2CaptureSystemError("Git repository-root lookup returned a noncanonical result") + repository_root = Path(top_level_lines[0]).resolve() + try: + project_root.resolve().relative_to(repository_root) + except ValueError as error: + raise M8L2CaptureSystemError("capture project root escapes the Git repository") from error + listing = _run_git_bytes( + repository_root, + ("ls-files", "-z", "--cached", "--others", "--exclude-standard"), + label="source-tree listing", + ) + source_tree_sha256 = _strict_source_tree_sha256(repository_root, listing) + second_status = _strict_git_status(project_root) + second_revision = _strict_git_revision(project_root) + if second_status.strip() or first_revision != second_revision: + raise M8L2CaptureSystemError("runtime Git identity changed during source snapshot") + return CaptureSourceIdentity( + commit=first_revision, + source_tree_sha256=source_tree_sha256, + dirty=False, + ) + + +def _runtime_payload( + *, + python_implementation: str, + python_version: str, + platform_system: str, + platform_release: str, + platform_machine: str, + dependencies: tuple[tuple[str, str], ...], +) -> dict[str, object]: + return { + "schema_version": _RUNTIME_SCHEMA_VERSION, + "python": { + "implementation": python_implementation, + "version": python_version, + }, + "platform": { + "system": platform_system, + "release": platform_release, + "machine": platform_machine, + }, + "dependencies": dict(dependencies), + } + + +def _runtime_fingerprint() -> _RuntimeFingerprint: + try: + dependencies = tuple( + (distribution, importlib_metadata.version(distribution)) + for distribution in _RUNTIME_DISTRIBUTIONS + ) + except importlib_metadata.PackageNotFoundError as error: + raise M8L2CaptureSystemError( + f"production runtime dependency is not installed: {error.name}" + ) from error + implementation = platform.python_implementation() + version = platform.python_version() + system = platform.system() + release = platform.release() + machine = platform.machine() + payload = _runtime_payload( + python_implementation=implementation, + python_version=version, + platform_system=system, + platform_release=release, + platform_machine=machine, + dependencies=dependencies, + ) + return _RuntimeFingerprint( + python_implementation=implementation, + python_version=version, + platform_system=system, + platform_release=release, + platform_machine=machine, + dependencies=dependencies, + sha256=_stable_sha256(payload), + ) + + +def current_m8_l2_runtime_fingerprint_sha256() -> str: + """Return the canonical production runtime digest used by L2 authorities.""" + + return _runtime_fingerprint().sha256 + + +def _runtime_from_recorded(value: object, sha256: object) -> _RuntimeFingerprint: + if not isinstance(value, Mapping) or set(value) != { + "schema_version", + "python", + "platform", + "dependencies", + }: + raise M8L2CaptureSystemError("recorded runtime fingerprint payload is not exact") + if value.get("schema_version") != _RUNTIME_SCHEMA_VERSION: + raise M8L2CaptureSystemError("recorded runtime fingerprint schema is unsupported") + python_payload = value.get("python") + platform_payload = value.get("platform") + dependencies_payload = value.get("dependencies") + if not isinstance(python_payload, Mapping) or set(python_payload) != { + "implementation", + "version", + }: + raise M8L2CaptureSystemError("recorded Python runtime identity is not exact") + if not isinstance(platform_payload, Mapping) or set(platform_payload) != { + "system", + "release", + "machine", + }: + raise M8L2CaptureSystemError("recorded platform runtime identity is not exact") + if not isinstance(dependencies_payload, Mapping) or set(dependencies_payload) != set( + _RUNTIME_DISTRIBUTIONS + ): + raise M8L2CaptureSystemError("recorded production dependency identity is not exact") + implementation = python_payload.get("implementation") + version = python_payload.get("version") + system = platform_payload.get("system") + release = platform_payload.get("release") + machine = platform_payload.get("machine") + if ( + type(implementation) is not str + or not implementation + or type(version) is not str + or not version + or type(system) is not str + or not system + or type(release) is not str + or not release + or type(machine) is not str + or not machine + ): + raise M8L2CaptureSystemError("recorded Python runtime identity is malformed") + dependencies: list[tuple[str, str]] = [] + for distribution in _RUNTIME_DISTRIBUTIONS: + dependency_version = dependencies_payload.get(distribution) + if type(dependency_version) is not str or not dependency_version: + raise M8L2CaptureSystemError( + f"recorded dependency version is malformed: {distribution}" + ) + dependencies.append((distribution, dependency_version)) + canonical_payload = _runtime_payload( + python_implementation=implementation, + python_version=version, + platform_system=system, + platform_release=release, + platform_machine=machine, + dependencies=tuple(dependencies), + ) + observed_sha256 = _stable_sha256(canonical_payload) + if type(sha256) is not str or not _is_lower_sha256(sha256) or sha256 != observed_sha256: + raise M8L2CaptureSystemError("recorded runtime fingerprint digest is invalid") + if dict(value) != canonical_payload: + raise M8L2CaptureSystemError("recorded runtime fingerprint payload is not canonical") + return _RuntimeFingerprint( + python_implementation=implementation, + python_version=version, + platform_system=system, + platform_release=release, + platform_machine=machine, + dependencies=tuple(dependencies), + sha256=observed_sha256, + ) + + +def _validate_source_identity(identity: CaptureSourceIdentity) -> None: + if identity.dirty: + raise M8L2CaptureSystemError( + "prospective live-L2 capture requires a clean runtime source tree" + ) + if len(identity.commit) != 40 or any( + character not in "0123456789abcdef" for character in identity.commit + ): + raise M8L2CaptureSystemError("runtime Git commit must be a lowercase 40-character SHA-1") + if not _is_lower_sha256(identity.source_tree_sha256): + raise M8L2CaptureSystemError("runtime source-tree digest is not a lowercase SHA-256") + + +def _assert_loaded_source_root(project_root: Path) -> None: + try: + assert_project_module_origins(project_root, "microstructure.m8_l2_capture") + except ImportOriginError as error: + raise M8L2CaptureSystemError( + "loaded microstructure code does not come from the hashed capture project root" + ) from error + + +def _assert_production_capture_origin(project_root: Path, capture_one: CaptureOne) -> None: + """Bind the real network adapter and every critical dependency to one checkout.""" + + capture_type = type(capture_one) + module_name = getattr(capture_type, "__module__", None) + if ( + module_name != "microstructure.m8_l2_binance" + or capture_type.__name__ != "BinanceM8L2Capture" + ): + raise M8L2CaptureSystemError( + "production CaptureOne must be the exact BinanceM8L2Capture adapter" + ) + adapter_module = sys.modules.get(module_name) + if adapter_module is None or getattr(adapter_module, "BinanceM8L2Capture", None) is not ( + capture_type + ): + raise M8L2CaptureSystemError( + "production BinanceM8L2Capture class lacks its canonical loaded module" + ) + try: + assert_project_module_origins( + project_root, + adapter_module, + "microstructure.data.binance", + "microstructure.data.book", + "microstructure.data.quality", + "microstructure.data.schemas", + "microstructure.data.storage", + ) + except ImportOriginError as error: + raise M8L2CaptureSystemError( + "production capture adapter has a foreign or mixed import origin" + ) from error + + +def _revalidate_runtime_authority( + *, + config: M8L2StudyConfig, + protocol: Path, + expected_source: CaptureSourceIdentity, + expected_runtime: _RuntimeFingerprint, + source_identity_was_injected: bool, +) -> None: + if not source_identity_was_injected: + _assert_loaded_source_root(config.path.parent.parent.resolve()) + try: + reloaded = load_m8_l2_config(config.path) + except (OSError, ValueError) as error: + raise M8L2CaptureSystemError( + "frozen live-L2 config changed during session orchestration" + ) from error + if reloaded != config or reloaded.hash != config.hash: + raise M8L2CaptureSystemError( + "in-memory live-L2 config differs from its exact frozen byte authority" + ) + _assert_protocol(protocol) + if _runtime_fingerprint() != expected_runtime: + raise M8L2CaptureSystemError( + "production runtime fingerprint changed during session orchestration" + ) + if source_identity_was_injected: + return + observed = _source_identity(config.path.parent.parent.resolve()) + _validate_source_identity(observed) + if observed != expected_source: + raise M8L2CaptureSystemError( + "runtime commit/source-tree identity changed during session orchestration" + ) + + +def merge_observed_intervals(intervals: Sequence[ObservedInterval]) -> tuple[ObservedInterval, ...]: + """Merge overlap only within the same continuity epoch and return time order.""" + + by_continuity: dict[str, list[ObservedInterval]] = {} + for interval in intervals: + by_continuity.setdefault(interval.continuity_id, []).append(interval) + merged: list[ObservedInterval] = [] + for continuity_id, values in by_continuity.items(): + ordered = sorted( + values, key=lambda item: (item.start_received_ns, item.end_received_ns_exclusive) + ) + current_start: int | None = None + current_end: int | None = None + for item in ordered: + if current_start is None or current_end is None: + current_start = item.start_received_ns + current_end = item.end_received_ns_exclusive + elif item.start_received_ns <= current_end: + current_end = max(current_end, item.end_received_ns_exclusive) + else: + merged.append(ObservedInterval(continuity_id, current_start, current_end)) + current_start = item.start_received_ns + current_end = item.end_received_ns_exclusive + if current_start is not None and current_end is not None: + merged.append(ObservedInterval(continuity_id, current_start, current_end)) + return tuple( + sorted( + merged, + key=lambda item: ( + item.start_received_ns, + item.end_received_ns_exclusive, + item.continuity_id, + ), + ) + ) + + +def _numeric_union(intervals: Sequence[ObservedInterval]) -> list[tuple[int, int]]: + ordered = sorted( + ( + (item.start_received_ns, item.end_received_ns_exclusive) + for item in merge_observed_intervals(intervals) + ), + key=lambda item: item, + ) + result: list[tuple[int, int]] = [] + for start, end in ordered: + if result and start <= result[-1][1]: + result[-1] = (result[-1][0], max(result[-1][1], end)) + else: + result.append((start, end)) + return result + + +def overlapping_observed_coverage_ns( + left: Sequence[ObservedInterval], right: Sequence[ObservedInterval] +) -> int: + """Return exact union-intersection coverage without bridging either feed's gaps.""" + + left_union = _numeric_union(left) + right_union = _numeric_union(right) + left_index = 0 + right_index = 0 + total = 0 + while left_index < len(left_union) and right_index < len(right_union): + left_start, left_end = left_union[left_index] + right_start, right_end = right_union[right_index] + total += max(0, min(left_end, right_end) - max(left_start, right_start)) + if left_end <= right_end: + left_index += 1 + else: + right_index += 1 + return total + + +def _session_identity( + *, + config: M8L2StudyConfig, + session: M8L2Session, + source: CaptureSourceIdentity, + campaign_authority_sha256: str, +) -> str: + if not _is_lower_sha256(campaign_authority_sha256): + raise M8L2CaptureSystemError("session campaign authority digest is invalid") + return _stable_sha256( + { + "schema_version": _SESSION_SCHEMA_VERSION, + "config_sha256": config.hash, + "config_source_sha256": config.source_sha256, + "protocol_sha256": M8_L2_PROTOCOL_SHA256, + "protocol_freeze_commit": M8_L2_FREEZE_COMMIT, + "runtime_commit": source.commit, + "runtime_source_tree_sha256": source.source_tree_sha256, + "campaign_authority_sha256": campaign_authority_sha256, + "date": session.date.isoformat(), + "role": session.role, + "scheduled_start_ns": session.start_ns, + "scheduled_end_ns": session.end_ns, + } + ) + + +def _terminal_root(output_root: Path, session: M8L2Session, session_id: str) -> Path: + return output_root / "sessions" / f"{session.date.isoformat()}-{session.role}-{session_id[:20]}" + + +def _directory_identity(path: Path, *, label: str) -> tuple[int, int]: + try: + metadata = path.lstat() + except OSError as error: + raise M8L2CaptureSystemError(f"cannot inspect {label}: {path}") from error + if not stat.S_ISDIR(metadata.st_mode): + raise M8L2CaptureSystemError(f"{label} is not a non-symlink directory: {path}") + return metadata.st_dev, metadata.st_ino + + +def _reject_existing_symlink_components(path: Path, *, label: str) -> None: + absolute = path.absolute() + current = Path(absolute.anchor) + for part in absolute.parts[1:]: + current /= part + if not current.exists() and not current.is_symlink(): + continue + try: + if stat.S_ISLNK(current.lstat().st_mode): + raise M8L2CaptureSystemError(f"{label} traverses a symlink: {current}") + except OSError as error: + raise M8L2CaptureSystemError(f"cannot inspect {label}: {current}") from error + + +def _prepare_output_root(output_root: str | Path) -> tuple[Path, tuple[int, int], tuple[int, int]]: + requested = Path(output_root) + _reject_existing_symlink_components(requested, label="live-L2 output root") + requested.mkdir(parents=True, exist_ok=True) + root = requested.resolve() + root_identity = _directory_identity(root, label="live-L2 output root") + sessions = root / "sessions" + if sessions.is_symlink(): + raise M8L2CaptureSystemError("live-L2 sessions directory must not be a symlink") + sessions.mkdir(exist_ok=True) + sessions_identity = _directory_identity(sessions, label="live-L2 sessions directory") + return root, root_identity, sessions_identity + + +def _revalidate_output_layout( + root: Path, + *, + root_identity: tuple[int, int], + sessions_identity: tuple[int, int], + target: Path, +) -> None: + if _directory_identity(root, label="live-L2 output root") != root_identity: + raise M8L2CaptureSystemError("live-L2 output root identity changed") + sessions = root / "sessions" + if _directory_identity(sessions, label="live-L2 sessions directory") != sessions_identity: + raise M8L2CaptureSystemError("live-L2 sessions directory identity changed") + if target.parent != sessions or target.absolute().parent != sessions.absolute(): + raise M8L2CaptureSystemError("live-L2 target escapes its sessions directory") + + +def _assert_protocol(path: Path) -> str: + if path.is_symlink() or not path.is_file(): + raise M8L2CaptureSystemError(f"frozen live-L2 protocol does not exist: {path}") + observed = sha256_file(path) + if observed != M8_L2_PROTOCOL_SHA256: + raise M8L2CaptureSystemError("live-L2 protocol bytes differ from the outcome-blind freeze") + return observed + + +def _assert_no_symlink_components(path: Path, root: Path, label: str) -> None: + try: + relative = path.relative_to(root) + except ValueError as error: + raise M8L2CaptureSystemError(f"{label} escapes its evidence root: {path}") from error + current = root + for part in relative.parts: + current = current / part + try: + mode = current.lstat().st_mode + except OSError as error: + raise M8L2CaptureSystemError(f"cannot inspect {label}: {current}") from error + if stat.S_ISLNK(mode): + raise M8L2CaptureSystemError(f"{label} contains a symlink: {current}") + + +def _assert_regular_inside(path: Path, root: Path, label: str) -> Path: + absolute_root = root.absolute() + absolute_path = path.absolute() + _assert_no_symlink_components(absolute_path, absolute_root, label) + try: + mode = absolute_path.lstat().st_mode + except OSError as error: + raise M8L2CaptureSystemError(f"cannot inspect {label}: {path}") from error + if not stat.S_ISREG(mode): + raise M8L2CaptureSystemError(f"{label} is not a regular file: {path}") + resolved = absolute_path.resolve() + try: + resolved.relative_to(root.resolve()) + except ValueError as error: + raise M8L2CaptureSystemError(f"{label} escapes its symbol stage: {path}") from error + return resolved + + +def _relative(path: Path, root: Path) -> str: + return path.absolute().relative_to(root.absolute()).as_posix() + + +def _walk_regular_evidence(root: Path) -> tuple[tuple[Path, ...], tuple[Path, ...]]: + """Walk evidence without following links and reject every special entry.""" + + try: + root_mode = root.lstat().st_mode + except OSError as error: + raise M8L2CaptureSystemError(f"cannot inspect session evidence root: {root}") from error + if not stat.S_ISDIR(root_mode): + raise M8L2CaptureSystemError(f"session evidence root is not a regular directory: {root}") + files: list[Path] = [] + directories: list[Path] = [root] + pending = [root] + while pending: + directory = pending.pop() + try: + entries = tuple(os.scandir(directory)) + except OSError as error: + raise M8L2CaptureSystemError( + f"cannot enumerate session evidence: {directory}" + ) from error + for entry in entries: + path = Path(entry.path) + try: + mode = entry.stat(follow_symlinks=False).st_mode + except OSError as error: + raise M8L2CaptureSystemError(f"cannot inspect session evidence: {path}") from error + if stat.S_ISREG(mode): + files.append(path) + elif stat.S_ISDIR(mode): + directories.append(path) + pending.append(path) + else: + raise M8L2CaptureSystemError( + f"session evidence contains a non-regular filesystem entry: {path}" + ) + return ( + tuple(sorted(files, key=lambda item: _relative(item, root))), + tuple(sorted(directories, key=lambda item: _relative(item, root))), + ) + + +def _all_regular_files(root: Path) -> tuple[Path, ...]: + return _walk_regular_evidence(root)[0] + + +def _canonical_json_bytes(value: object) -> bytes: + return (json.dumps(value, indent=2, sort_keys=True, allow_nan=False) + "\n").encode() + + +def _decode_canonical_json(raw: bytes, *, label: str) -> object: + try: + text = raw.decode("utf-8") + + def reject_duplicate(pairs: list[tuple[str, object]]) -> dict[str, object]: + result: dict[str, object] = {} + for key, value in pairs: + if key in result: + raise ValueError(f"duplicate JSON key: {key}") + result[key] = value + return result + + value = json.loads( + text, + object_pairs_hook=reject_duplicate, + parse_constant=lambda token: (_ for _ in ()).throw( + ValueError(f"invalid JSON number: {token}") + ), + ) + except (UnicodeError, ValueError, json.JSONDecodeError) as error: + raise M8L2CaptureSystemError(f"cannot parse canonical {label}") from error + if raw != _canonical_json_bytes(value): + raise M8L2CaptureSystemError(f"{label} is not canonical stable JSON") + return value + + +def _read_bounded_regular_nofollow( + path: Path, *, label: str, maximum_bytes: int = _MAX_JSON_AUTHORITY_BYTES +) -> bytes: + """Read one stable regular file through a no-follow descriptor.""" + + flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) + try: + descriptor = os.open(path, flags) + except OSError as error: + raise M8L2CaptureSystemError( + f"cannot open {label} without following links: {path}" + ) from error + try: + before = os.fstat(descriptor) + if not stat.S_ISREG(before.st_mode) or before.st_size < 1 or before.st_size > maximum_bytes: + raise M8L2CaptureSystemError(f"{label} is not a bounded nonempty regular file: {path}") + chunks: list[bytes] = [] + remaining = maximum_bytes + 1 + while remaining: + chunk = os.read(descriptor, min(64 * 1024, remaining)) + if not chunk: + break + chunks.append(chunk) + remaining -= len(chunk) + raw = b"".join(chunks) + after = os.fstat(descriptor) + current = path.lstat() + stable_coordinates = ( + before.st_dev, + before.st_ino, + before.st_size, + before.st_mtime_ns, + before.st_ctime_ns, + ) == ( + after.st_dev, + after.st_ino, + after.st_size, + after.st_mtime_ns, + after.st_ctime_ns, + ) + path_still_names_descriptor = ( + current.st_dev, + current.st_ino, + current.st_size, + ) == ( + after.st_dev, + after.st_ino, + after.st_size, + ) and stat.S_ISREG(current.st_mode) + if ( + len(raw) > maximum_bytes + or len(raw) != before.st_size + or not stable_coordinates + or not path_still_names_descriptor + ): + raise M8L2CaptureSystemError(f"{label} changed during its bounded read: {path}") + return raw + except OSError as error: + raise M8L2CaptureSystemError(f"cannot read {label}: {path}") from error + finally: + os.close(descriptor) + + +def _strict_json(path: Path, *, label: str) -> object: + """Read a bounded canonical JSON authority with duplicate/NaN rejection.""" + + raw = _read_bounded_regular_nofollow(path, label=label) + return _decode_canonical_json(raw, label=f"{label}: {path}") + + +def _validate_symbol_result( + result: SymbolCaptureResult, + *, + expected_symbol: str, + symbol_root: Path, + session: M8L2Session, +) -> SymbolCaptureResult: + if result.symbol != expected_symbol: + raise M8L2CaptureSystemError( + f"capture result symbol {result.symbol!r} does not match {expected_symbol!r}" + ) + if not result.capture_id or "/" in result.capture_id or "\\" in result.capture_id: + raise M8L2CaptureSystemError("single-symbol capture returned an unsafe capture_id") + for name in ( + "messages", + "normalized_rows", + "reconstructed_rows", + "excluded_rows", + "continuity_epochs", + "snapshot_anchors", + "sequence_gaps", + "quality_errors", + "quality_warnings", + "max_raw_frame_bytes_observed", + "max_arrow_batch_bytes_observed", + ): + value = getattr(result, name) + if isinstance(value, bool) or not isinstance(value, int) or value < 0: + raise M8L2CaptureSystemError(f"capture result {name} must be a nonnegative integer") + if result.status == "FAILED": + if result.failure_reason_code is None or result.failure_phase is None: + raise M8L2CaptureSystemError("FAILED capture result lacks typed failure coordinates") + _validate_code(result.failure_reason_code, "capture failure reason") + _validate_code(result.failure_phase, "capture failure phase") + elif result.failure_reason_code is not None or result.failure_phase is not None: + raise M8L2CaptureSystemError("COMPLETE capture result cannot carry a failure") + + if (result.first_raw_received_ns is None) != (result.last_raw_received_ns is None): + raise M8L2CaptureSystemError("raw receipt bounds must be both null or both present") + if ( + result.first_raw_received_ns is not None + and result.last_raw_received_ns is not None + and not ( + session.start_ns + <= result.first_raw_received_ns + <= result.last_raw_received_ns + < session.end_ns + ) + ): + raise M8L2CaptureSystemError( + "raw receipt bounds fall outside the frozen [start, end) session" + ) + merged = merge_observed_intervals(result.valid_observed_intervals) + if tuple(result.valid_observed_intervals) != merged: + raise M8L2CaptureSystemError( + "OBSERVED intervals must already be canonical, disjoint, and time ordered" + ) + continuity_ids = {item.continuity_id for item in merged} + if len(continuity_ids) > result.continuity_epochs: + raise M8L2CaptureSystemError( + "OBSERVED continuity IDs exceed the declared reconstruction epochs" + ) + for interval in merged: + if not ( + session.start_ns + <= interval.start_received_ns + < interval.end_received_ns_exclusive + <= session.end_ns + ): + raise M8L2CaptureSystemError( + "OBSERVED interval falls outside the frozen [start, end) session" + ) + if result.first_raw_received_ns is None or result.last_raw_received_ns is None: + raise M8L2CaptureSystemError("OBSERVED intervals require raw receipt bounds") + if ( + interval.start_received_ns < result.first_raw_received_ns + or interval.end_received_ns_exclusive > result.last_raw_received_ns + 1 + ): + raise M8L2CaptureSystemError("OBSERVED interval exceeds its raw receipt evidence") + + declared: dict[str, CapturedArtifact] = {} + for artifact in result.artifacts: + if not artifact.kind: + raise M8L2CaptureSystemError("captured artifact kind must not be empty") + if not _is_lower_sha256(artifact.sha256): + raise M8L2CaptureSystemError("captured artifact digest is not lowercase SHA-256") + path = _assert_regular_inside(artifact.path, symbol_root, "captured artifact") + relative = _relative(path, symbol_root) + if relative in declared: + raise M8L2CaptureSystemError(f"duplicate captured artifact coordinate: {relative}") + if sha256_file(path) != artifact.sha256: + raise M8L2CaptureSystemError(f"captured artifact digest mismatch: {relative}") + declared[relative] = artifact + actual = {_relative(path, symbol_root) for path in _all_regular_files(symbol_root)} + if actual != set(declared): + raise M8L2CaptureSystemError( + "single-symbol capture artifact inventory differs from files on disk " + f"(missing={sorted(actual - set(declared))}, extra={sorted(set(declared) - actual)})" + ) + if any(item.kind == "capture_summary" for item in result.artifacts): + _validate_capture_summary(result, symbol_root=symbol_root, session=session) + return result + + +def _gate( + gates: list[dict[str, object]], + *, + gate_id: str, + passed: bool, + observed: object, + required: object, + symbol: str | None = None, +) -> None: + entry: dict[str, object] = { + "gate_id": gate_id, + "passed": passed, + "observed": observed, + "required": required, + } + if symbol is not None: + entry["symbol"] = symbol + gates.append(entry) + + +def _symbol_payload(result: SymbolCaptureResult, *, stage_root: Path) -> dict[str, object]: + intervals = merge_observed_intervals(result.valid_observed_intervals) + return { + "symbol": result.symbol, + "capture_id": result.capture_id, + "status": result.status, + "completion_reason": result.completion_reason, + "reconstruction_status": result.reconstruction_status, + "messages": result.messages, + "normalized_rows": result.normalized_rows, + "reconstructed_rows": result.reconstructed_rows, + "excluded_rows": result.excluded_rows, + "continuity_epochs": result.continuity_epochs, + "snapshot_anchors": result.snapshot_anchors, + "sequence_gaps": result.sequence_gaps, + "quality_errors": result.quality_errors, + "quality_warnings": result.quality_warnings, + "max_raw_frame_bytes_observed": result.max_raw_frame_bytes_observed, + "max_arrow_batch_bytes_observed": result.max_arrow_batch_bytes_observed, + "first_raw_received_ns": result.first_raw_received_ns, + "last_raw_received_ns": result.last_raw_received_ns, + "valid_observed_intervals": [item.to_dict() for item in intervals], + "max_valid_continuity_epoch_seconds": max( + (item.duration_ns for item in intervals), default=0 + ) + / _NANOSECONDS_PER_SECOND, + "failure_reason_code": result.failure_reason_code, + "failure_phase": result.failure_phase, + "artifacts": [ + { + "path": _relative(artifact.path, stage_root), + "kind": artifact.kind, + "sha256": artifact.sha256, + "bytes": artifact.path.stat().st_size, + } + for artifact in sorted( + result.artifacts, key=lambda item: _relative(item.path, stage_root) + ) + ], + } + + +def _summary_artifact_map( + result: SymbolCaptureResult, *, symbol_root: Path +) -> dict[str, CapturedArtifact]: + return { + _relative(item.path, symbol_root): item + for item in result.artifacts + if item.kind != "capture_summary" + } + + +def _require_summary_reference( + value: object, + *, + artifacts: Mapping[str, CapturedArtifact], + kind: str, + label: str, +) -> CapturedArtifact: + if type(value) is not str: + raise M8L2CaptureSystemError(f"capture summary {label} must be a relative path") + relative = _safe_checksum_relative(value) + artifact = artifacts.get(relative) + if artifact is None or artifact.kind != kind: + raise M8L2CaptureSystemError( + f"capture summary {label} does not name a declared {kind} artifact" + ) + return artifact + + +def _load_compact_json_line(raw: bytes, *, label: str) -> Mapping[str, Any]: + try: + text = raw.decode("utf-8") + + def reject_duplicate(pairs: list[tuple[str, object]]) -> dict[str, object]: + result: dict[str, object] = {} + for key, value in pairs: + if key in result: + raise ValueError(f"duplicate JSON key: {key}") + result[key] = value + return result + + value = json.loads( + text, + object_pairs_hook=reject_duplicate, + parse_constant=lambda token: (_ for _ in ()).throw( + ValueError(f"invalid JSON number: {token}") + ), + ) + except (UnicodeError, ValueError, json.JSONDecodeError) as error: + raise M8L2CaptureSystemError(f"cannot parse {label}") from error + if not isinstance(value, Mapping) or not all(type(key) is str for key in value): + raise M8L2CaptureSystemError(f"{label} must be a JSON object") + canonical = json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode() + if raw != canonical: + raise M8L2CaptureSystemError(f"{label} is not canonical compact JSON") + return cast(Mapping[str, Any], value) + + +def _validate_raw_journal( + result: SymbolCaptureResult, + *, + journal: CapturedArtifact, + artifacts: Mapping[str, CapturedArtifact], + session: M8L2Session, +) -> None: + websocket_receipts: list[int] = [] + max_frame_bytes = 0 + anchor_ids: set[str] = set() + anchor_count = 0 + try: + with journal.path.open("rb") as handle: + line_number = 0 + while True: + line = handle.readline(2 * _MAX_JSON_AUTHORITY_BYTES + 1) + if not line: + break + line_number += 1 + if len(line) > 2 * _MAX_JSON_AUTHORITY_BYTES or not line.endswith(b"\n"): + raise M8L2CaptureSystemError("raw journal contains an oversized/partial line") + entry = _load_compact_json_line(line[:-1], label=f"raw journal line {line_number}") + event_kind = entry.get("event_kind") + if event_kind == "websocket_frame": + received = entry.get("received_ts_ns") + payload_bytes = entry.get("payload_bytes") + payload_base64 = entry.get("payload_base64") + payload_sha256 = entry.get("payload_sha256") + if ( + type(received) is not int + or not session.start_ns <= received < session.end_ns + or type(payload_bytes) is not int + or payload_bytes < 0 + or type(payload_base64) is not str + or type(payload_sha256) is not str + or not _is_lower_sha256(payload_sha256) + ): + raise M8L2CaptureSystemError("raw websocket lineage has invalid bounds") + try: + decoded = base64.b64decode(payload_base64, validate=True) + except (ValueError, binascii.Error) as error: + raise M8L2CaptureSystemError( + "raw websocket lineage has invalid base64 bytes" + ) from error + if len(decoded) != payload_bytes or hashlib.sha256(decoded).hexdigest() != ( + payload_sha256 + ): + raise M8L2CaptureSystemError( + "raw websocket lineage size/digest differs from preserved bytes" + ) + if websocket_receipts and received < websocket_receipts[-1]: + raise M8L2CaptureSystemError("raw websocket receipts are not FIFO ordered") + websocket_receipts.append(received) + max_frame_bytes = max(max_frame_bytes, payload_bytes) + elif event_kind == "rest_snapshot_anchor": + continuity_id = entry.get("continuity_id") + if type(continuity_id) is not str or not continuity_id: + raise M8L2CaptureSystemError("raw snapshot anchor lacks continuity ID") + if continuity_id in anchor_ids: + raise M8L2CaptureSystemError( + "raw journal repeats a snapshot anchor continuity ID" + ) + anchor_ids.add(continuity_id) + anchor_count += 1 + raw_snapshot = _require_summary_reference( + entry.get("raw_path"), + artifacts=artifacts, + kind="raw_snapshot", + label="raw journal snapshot path", + ) + raw_snapshot_manifest = _require_summary_reference( + entry.get("raw_manifest_path"), + artifacts=artifacts, + kind="raw_snapshot_manifest", + label="raw journal snapshot manifest path", + ) + if ( + entry.get("raw_sha256") != raw_snapshot.sha256 + or entry.get("raw_manifest_sha256") != raw_snapshot_manifest.sha256 + ): + raise M8L2CaptureSystemError("raw snapshot anchor digest is inconsistent") + else: + raise M8L2CaptureSystemError("raw journal has an unsupported event kind") + except OSError as error: + raise M8L2CaptureSystemError("cannot stream the raw journal authority") from error + if len(websocket_receipts) != result.messages: + raise M8L2CaptureSystemError("raw journal message count differs from returned claims") + observed_first = websocket_receipts[0] if websocket_receipts else None + observed_last = websocket_receipts[-1] if websocket_receipts else None + if ( + observed_first != result.first_raw_received_ns + or observed_last != result.last_raw_received_ns + or max_frame_bytes != result.max_raw_frame_bytes_observed + ): + raise M8L2CaptureSystemError("raw journal receipt/frame claims are inconsistent") + if anchor_count != result.snapshot_anchors or anchor_count != result.continuity_epochs: + raise M8L2CaptureSystemError("raw journal anchors differ from reconstruction epochs") + if not {item.continuity_id for item in result.valid_observed_intervals}.issubset(anchor_ids): + raise M8L2CaptureSystemError("OBSERVED intervals lack a matching raw snapshot anchor") + + +def _validate_capture_summary( + result: SymbolCaptureResult, *, symbol_root: Path, session: M8L2Session +) -> None: + summaries = [item for item in result.artifacts if item.kind == "capture_summary"] + if len(summaries) != 1: + raise M8L2CaptureSystemError("capture result must declare exactly one capture summary") + summary_artifact = summaries[0] + if _relative(summary_artifact.path, symbol_root) != "quality/capture.summary.json": + raise M8L2CaptureSystemError("capture summary path is not the canonical coordinate") + payload = _strict_json(summary_artifact.path, label="symbol capture summary") + if not isinstance(payload, Mapping) or not all(type(key) is str for key in payload): + raise M8L2CaptureSystemError("symbol capture summary must be a JSON object") + summary = cast(Mapping[str, Any], payload) + expected_claims: dict[str, object] = { + "schema_version": _SYMBOL_SUMMARY_SCHEMA_VERSION, + "symbol": result.symbol, + "capture_id": result.capture_id, + "capture_status": result.status, + "completion_reason": result.completion_reason, + "reconstruction_status": result.reconstruction_status, + "failure_reason_code": result.failure_reason_code, + "failure_phase": result.failure_phase, + "messages": result.messages, + "normalized_rows": result.normalized_rows, + "reconstructed_rows": result.reconstructed_rows, + "excluded_rows": result.excluded_rows, + "continuity_epochs": result.continuity_epochs, + "snapshot_anchors": result.snapshot_anchors, + "sequence_gaps": result.sequence_gaps, + "quality_errors": result.quality_errors, + "quality_warnings": result.quality_warnings, + "max_raw_frame_bytes_observed": result.max_raw_frame_bytes_observed, + "max_arrow_batch_bytes_observed": result.max_arrow_batch_bytes_observed, + "first_raw_received_ns": result.first_raw_received_ns, + "last_raw_received_ns": result.last_raw_received_ns, + "valid_observed_intervals": [item.to_dict() for item in result.valid_observed_intervals], + "scheduled_range_ns": { + "start": session.start_ns, + "end_exclusive": session.end_ns, + }, + } + mismatches = [ + name for name, expected in expected_claims.items() if summary.get(name) != expected + ] + if mismatches: + raise M8L2CaptureSystemError( + "symbol capture summary differs from returned claims: " + ", ".join(mismatches) + ) + + artifacts = _summary_artifact_map(result, symbol_root=symbol_root) + inventory_raw = summary.get("artifact_inventory_without_summary") + if not isinstance(inventory_raw, list): + raise M8L2CaptureSystemError( + "symbol capture summary lacks artifact_inventory_without_summary" + ) + summary_inventory: dict[str, tuple[str, str, int]] = {} + for index, raw in enumerate(inventory_raw): + if not isinstance(raw, Mapping) or set(raw) != {"path", "kind", "sha256", "bytes"}: + raise M8L2CaptureSystemError( + f"symbol capture summary inventory entry {index} is malformed" + ) + relative_value = raw.get("path") + if type(relative_value) is not str: + raise M8L2CaptureSystemError("symbol capture summary inventory path is invalid") + relative = _safe_checksum_relative(relative_value) + kind = raw.get("kind") + digest = raw.get("sha256") + size = raw.get("bytes") + if ( + type(kind) is not str + or type(digest) is not str + or not _is_lower_sha256(digest) + or type(size) is not int + or size < 0 + or relative in summary_inventory + ): + raise M8L2CaptureSystemError("symbol capture summary inventory entry is invalid") + summary_inventory[relative] = (kind, digest, size) + expected_inventory = { + relative: (item.kind, item.sha256, item.path.stat().st_size) + for relative, item in artifacts.items() + } + if summary_inventory != expected_inventory or list(summary_inventory) != sorted( + summary_inventory + ): + raise M8L2CaptureSystemError( + "symbol capture summary artifact inventory is not exact and canonical" + ) + + raw_journal = _require_summary_reference( + summary.get("raw_journal"), + artifacts=artifacts, + kind="raw_journal", + label="raw_journal", + ) + raw_manifest = _require_summary_reference( + summary.get("raw_journal_manifest"), + artifacts=artifacts, + kind="raw_journal_manifest", + label="raw_journal_manifest", + ) + if ( + summary.get("raw_journal_sha256") != raw_journal.sha256 + or summary.get("raw_journal_manifest_sha256") != raw_manifest.sha256 + ): + raise M8L2CaptureSystemError("symbol capture summary raw digests are inconsistent") + _validate_raw_journal( + result, + journal=raw_journal, + artifacts=artifacts, + session=session, + ) + raw_manifest_payload = _strict_json(raw_manifest.path, label="raw journal manifest") + if not isinstance(raw_manifest_payload, Mapping): + raise M8L2CaptureSystemError("raw journal manifest must be a JSON object") + raw_checksum = raw_manifest_payload.get("checksum") + raw_range = raw_manifest_payload.get("requested_range_ns") + raw_headers = raw_manifest_payload.get("response_headers") + if ( + raw_manifest_payload.get("artifact_kind") != "raw_source" + or not isinstance(raw_checksum, Mapping) + or raw_checksum.get("algorithm") != "sha256" + or raw_checksum.get("value") != raw_journal.sha256 + or raw_manifest_payload.get("bytes") != raw_journal.path.stat().st_size + or raw_manifest_payload.get("path") != raw_journal.path.name + or raw_range != {"start": session.start_ns, "end_exclusive": session.end_ns} + or not isinstance(raw_headers, Mapping) + or raw_headers.get("x-local-message-count") != str(result.messages) + or raw_headers.get("x-local-snapshot-anchor-count") != str(result.snapshot_anchors) + ): + raise M8L2CaptureSystemError("raw journal manifest differs from capture claims") + + datasets_raw = summary.get("normalized_dataset_manifests") + expected_rows = { + "book_snapshots": result.snapshot_anchors, + "depth_deltas": result.normalized_rows, + "book_observations": result.reconstructed_rows, + "sequence_gaps": result.sequence_gaps, + } + if not isinstance(datasets_raw, Mapping) or set(datasets_raw) != set(expected_rows): + raise M8L2CaptureSystemError("symbol capture summary normalized manifests are incomplete") + for dataset, expected_row_count in expected_rows.items(): + raw_entry = datasets_raw[dataset] + if not isinstance(raw_entry, Mapping): + raise M8L2CaptureSystemError("normalized dataset summary entry must be an object") + manifest = _require_summary_reference( + raw_entry.get("manifest_path"), + artifacts=artifacts, + kind="normalized_manifest", + label=f"normalized_dataset_manifests.{dataset}.manifest_path", + ) + if raw_entry.get("manifest_sha256") != manifest.sha256: + raise M8L2CaptureSystemError("normalized dataset manifest digest is inconsistent") + if raw_entry.get("rows") != expected_row_count: + raise M8L2CaptureSystemError("normalized dataset row count differs from claims") + data_path = raw_entry.get("data_path") + data_sha = raw_entry.get("data_sha256") + if expected_row_count == 0: + if data_path is not None or data_sha is not None: + raise M8L2CaptureSystemError("empty normalized dataset unexpectedly has data") + else: + data = _require_summary_reference( + data_path, + artifacts=artifacts, + kind="normalized_data", + label=f"normalized_dataset_manifests.{dataset}.data_path", + ) + if data_sha != data.sha256: + raise M8L2CaptureSystemError("normalized dataset digest is inconsistent") + _validate_normalized_parquet( + data.path, + dataset=dataset, + expected_rows=expected_row_count, + ) + normalized_manifest_payload = _strict_json( + manifest.path, label=f"{dataset} normalized manifest" + ) + if not isinstance(normalized_manifest_payload, Mapping): + raise M8L2CaptureSystemError("normalized dataset manifest must be an object") + if ( + normalized_manifest_payload.get("dataset") != dataset + or normalized_manifest_payload.get("rows") != expected_row_count + or normalized_manifest_payload.get("requested_range_ns") + != {"start": session.start_ns, "end_exclusive": session.end_ns} + ): + raise M8L2CaptureSystemError("normalized manifest essentials differ from claims") + + reports_raw = summary.get("quality_reports") + if not isinstance(reports_raw, Mapping) or set(reports_raw) != { + "depth_deltas", + "book_observations", + }: + raise M8L2CaptureSystemError("symbol capture summary quality reports are incomplete") + report_counts = {"errors": 0, "warnings": 0} + for dataset in ("depth_deltas", "book_observations"): + report = _require_summary_reference( + reports_raw[dataset], + artifacts=artifacts, + kind="quality_report", + label=f"quality_reports.{dataset}", + ) + report_payload = _strict_json(report.path, label=f"{dataset} quality report") + if not isinstance(report_payload, Mapping) or report_payload.get("dataset") != dataset: + raise M8L2CaptureSystemError("quality report dataset differs from its coordinate") + report_summary = report_payload.get("summary") + if not isinstance(report_summary, Mapping): + raise M8L2CaptureSystemError("quality report lacks its summary counts") + for name in report_counts: + value = report_summary.get(name) + if type(value) is not int or value < 0: + raise M8L2CaptureSystemError("quality report count is invalid") + report_counts[name] += value + if report_counts != {"errors": result.quality_errors, "warnings": result.quality_warnings}: + raise M8L2CaptureSystemError("quality report counts differ from returned claims") + + +def _validate_normalized_parquet(path: Path, *, dataset: str, expected_rows: int) -> None: + """Bound footer reads before PyArrow metadata/schema validation.""" + + try: + size = path.stat().st_size + if size < 12: + raise M8L2CaptureSystemError("normalized data is too short to be Parquet") + flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) + descriptor = os.open(path, flags) + try: + if not stat.S_ISREG(os.fstat(descriptor).st_mode): + raise M8L2CaptureSystemError("normalized data is not a regular file") + if os.pread(descriptor, 4, 0) != b"PAR1": + raise M8L2CaptureSystemError("normalized data lacks the Parquet header") + trailer = os.pread(descriptor, 8, size - 8) + if len(trailer) != 8 or trailer[4:] != b"PAR1": + raise M8L2CaptureSystemError("normalized data lacks the Parquet trailer") + footer_bytes = int.from_bytes(trailer[:4], "little") + if footer_bytes > _MAX_JSON_AUTHORITY_BYTES or footer_bytes + 12 > size: + raise M8L2CaptureSystemError("normalized Parquet footer exceeds its bound") + finally: + os.close(descriptor) + parquet = pq.ParquetFile(path) + if parquet.metadata.num_rows != expected_rows: + raise M8L2CaptureSystemError("Parquet footer row count differs from capture claims") + if parquet.schema_arrow != get_schema(dataset): + raise M8L2CaptureSystemError("normalized Parquet schema differs from the registry") + metadata = parquet.schema_arrow.metadata or {} + if metadata.get(b"schema_version") != SCHEMA_VERSION.encode(): + raise M8L2CaptureSystemError("normalized Parquet schema version is not frozen") + except M8L2CaptureSystemError: + raise + except (OSError, ValueError) as error: + raise M8L2CaptureSystemError("cannot validate normalized Parquet metadata") from error + + +def _evaluate_gates( + results: Mapping[str, SymbolCaptureResult], + *, + config: M8L2StudyConfig, +) -> tuple[list[dict[str, object]], list[str], int]: + limits = config.capture + gates: list[dict[str, object]] = [] + reasons: list[str] = [] + for symbol in config.study.symbols: + result = results.get(symbol) + if result is None: + reasons.append(f"MISSING_SYMBOL_{symbol}") + _gate( + gates, + gate_id="SYMBOL_RESULT_PRESENT", + passed=False, + observed=False, + required=True, + symbol=symbol, + ) + continue + artifact_kinds = {artifact.kind for artifact in result.artifacts} + snapshot_artifact_count = sum( + artifact.kind == "raw_snapshot" for artifact in result.artifacts + ) + snapshot_manifest_count = sum( + artifact.kind == "raw_snapshot_manifest" for artifact in result.artifacts + ) + checks: tuple[tuple[str, bool, object, object], ...] = ( + ( + "CAPTURE_STATUS_COMPLETE", + (not limits.require_complete_status) or result.status == "COMPLETE", + result.status, + "COMPLETE", + ), + ( + "SCHEDULED_END_REACHED", + result.completion_reason == "scheduled_end_reached", + result.completion_reason, + "scheduled_end_reached", + ), + ( + "RAW_RECEIPT_BOUNDS_PRESENT", + result.first_raw_received_ns is not None + and result.last_raw_received_ns is not None, + { + "first": result.first_raw_received_ns, + "last": result.last_raw_received_ns, + }, + "both present inside [start,end)", + ), + ( + "MESSAGE_CEILING", + result.messages <= limits.max_messages_per_symbol, + result.messages, + {"maximum": limits.max_messages_per_symbol}, + ), + ( + "MESSAGE_NORMALIZATION_RECONCILIATION", + result.messages == result.normalized_rows + and result.normalized_rows == result.reconstructed_rows + result.excluded_rows, + { + "messages": result.messages, + "normalized": result.normalized_rows, + "reconstructed": result.reconstructed_rows, + "excluded": result.excluded_rows, + }, + "messages == normalized == reconstructed + excluded", + ), + ( + "SNAPSHOT_ANCHOR_RECONCILIATION", + result.continuity_epochs > 0 + and result.snapshot_anchors == result.continuity_epochs, + { + "epochs": result.continuity_epochs, + "snapshot_anchors": result.snapshot_anchors, + }, + "positive epochs and one anchor per epoch", + ), + ( + "LIVE_RECONSTRUCTION", + (not limits.require_live_reconstruction) or result.reconstruction_status == "LIVE", + result.reconstruction_status, + "LIVE", + ), + ( + "SEQUENCE_GAPS", + result.sequence_gaps <= limits.max_sequence_gaps, + result.sequence_gaps, + {"maximum": limits.max_sequence_gaps}, + ), + ( + "QUALITY_ERRORS", + result.quality_errors <= limits.max_quality_errors, + result.quality_errors, + {"maximum": limits.max_quality_errors}, + ), + ( + "QUALITY_WARNINGS", + result.quality_warnings <= limits.max_quality_warnings, + result.quality_warnings, + {"maximum": limits.max_quality_warnings}, + ), + ( + "RAW_FRAME_BYTES", + result.max_raw_frame_bytes_observed <= limits.max_raw_frame_bytes, + result.max_raw_frame_bytes_observed, + {"maximum": limits.max_raw_frame_bytes}, + ), + ( + "ARROW_BATCH_BYTES", + result.max_arrow_batch_bytes_observed <= limits.max_arrow_batch_bytes, + result.max_arrow_batch_bytes_observed, + {"maximum": limits.max_arrow_batch_bytes}, + ), + ( + "VALID_CONTINUITY_EPOCH", + max( + ( + item.duration_ns + for item in merge_observed_intervals(result.valid_observed_intervals) + ), + default=0, + ) + >= limits.min_single_continuity_epoch_seconds * _NANOSECONDS_PER_SECOND, + max( + ( + item.duration_ns + for item in merge_observed_intervals(result.valid_observed_intervals) + ), + default=0, + ) + / _NANOSECONDS_PER_SECOND, + {"minimum_seconds": limits.min_single_continuity_epoch_seconds}, + ), + ( + "CAPTURE_ARTIFACTS_PRESENT", + _REQUIRED_CAPTURE_ARTIFACT_KINDS.issubset(artifact_kinds), + { + "kinds": sorted(artifact_kinds), + "raw_snapshots": snapshot_artifact_count, + "raw_snapshot_manifests": snapshot_manifest_count, + }, + { + "required_kinds": sorted(_REQUIRED_CAPTURE_ARTIFACT_KINDS), + "snapshot anchors are cross-bound in the raw journal": True, + }, + ), + ) + if result.failure_reason_code is not None: + reasons.append(result.failure_reason_code) + for gate_id, passed, observed, required in checks: + _gate( + gates, + gate_id=gate_id, + passed=passed, + observed=observed, + required=required, + symbol=symbol, + ) + if not passed: + reasons.append(f"GATE_{gate_id}_{symbol}") + + overlap_ns = 0 + if all(symbol in results for symbol in config.study.symbols): + left = results[config.study.symbols[0]].valid_observed_intervals + right = results[config.study.symbols[1]].valid_observed_intervals + overlap_ns = overlapping_observed_coverage_ns(left, right) + overlap_passed = overlap_ns >= limits.min_overlapping_coverage_seconds * _NANOSECONDS_PER_SECOND + _gate( + gates, + gate_id="CROSS_SYMBOL_OBSERVED_OVERLAP", + passed=overlap_passed, + observed=overlap_ns / _NANOSECONDS_PER_SECOND, + required={"minimum_seconds": limits.min_overlapping_coverage_seconds}, + ) + if not overlap_passed: + reasons.append("GATE_CROSS_SYMBOL_OBSERVED_OVERLAP") + return gates, sorted(set(reasons)), overlap_ns + + +def _write_bytes_durable(path: Path, payload: bytes) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary_name = tempfile.mkstemp( + dir=path.parent, prefix=f".{path.name}.", suffix=".tmp" + ) + try: + with os.fdopen(descriptor, "wb") as handle: + handle.write(payload) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary_name, path) + _fsync_directory(path.parent) + except BaseException: + Path(temporary_name).unlink(missing_ok=True) + raise + + +def _fsync_directory(path: Path) -> None: + descriptor = os.open(path, os.O_RDONLY) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + + +def _campaign_payload( + *, + config: M8L2StudyConfig, + source: CaptureSourceIdentity, + runtime: _RuntimeFingerprint, + nonce: str, + root: Path, + root_identity: tuple[int, int], +) -> dict[str, object]: + _validate_source_identity(source) + if not _is_lower_sha256(nonce): + raise M8L2CaptureSystemError("live-L2 campaign nonce is not 256-bit lowercase hex") + if runtime != _runtime_from_recorded(runtime.payload(), runtime.sha256): + raise M8L2CaptureSystemError("live-L2 runtime fingerprint is not canonical") + return { + "schema_version": _CAMPAIGN_SCHEMA_VERSION, + "artifact_kind": "m8_prospective_live_l2_campaign_authority", + "campaign_nonce": nonce, + "output_root": { + "canonical_path": str(root), + "device": root_identity[0], + "inode": root_identity[1], + }, + "config_sha256": config.hash, + "config_source_sha256": config.source_sha256, + "protocol_sha256": M8_L2_PROTOCOL_SHA256, + "protocol_freeze_commit": M8_L2_FREEZE_COMMIT, + "runtime_commit": source.commit, + "runtime_source_tree_sha256": source.source_tree_sha256, + "runtime_dirty": False, + "runtime_fingerprint": runtime.payload(), + "runtime_fingerprint_sha256": runtime.sha256, + } + + +def _recorded_output_root(value: object) -> tuple[str, int, int]: + if not isinstance(value, Mapping) or set(value) != { + "canonical_path", + "device", + "inode", + }: + raise M8L2CaptureSystemError("campaign output-root identity is not exact") + canonical_path = value.get("canonical_path") + device = value.get("device") + inode = value.get("inode") + if ( + type(canonical_path) is not str + or not canonical_path + or "\x00" in canonical_path + or not PurePosixPath(canonical_path).is_absolute() + or ".." in PurePosixPath(canonical_path).parts + or PurePosixPath(canonical_path).as_posix() != canonical_path + ): + raise M8L2CaptureSystemError("campaign output-root path is not canonical") + if type(device) is not int or device < 0 or type(inode) is not int or inode < 0: + raise M8L2CaptureSystemError("campaign output-root device/inode is malformed") + return canonical_path, device, inode + + +def _validate_campaign_bytes( + raw: bytes, + *, + path: Path, + config: M8L2StudyConfig, + source: CaptureSourceIdentity, + expected_runtime: _RuntimeFingerprint | None = None, + expected_root: Path | None = None, + expected_root_identity: tuple[int, int] | None = None, + expected_sha256: str | None = None, +) -> _CampaignAuthority: + value = _decode_canonical_json(raw, label=f"live-L2 campaign authority: {path}") + if not isinstance(value, Mapping) or set(value) != { + "schema_version", + "artifact_kind", + "campaign_nonce", + "output_root", + "config_sha256", + "config_source_sha256", + "protocol_sha256", + "protocol_freeze_commit", + "runtime_commit", + "runtime_source_tree_sha256", + "runtime_dirty", + "runtime_fingerprint", + "runtime_fingerprint_sha256", + }: + raise M8L2CaptureSystemError("live-L2 campaign authority schema is not exact") + expected_claims = { + "schema_version": _CAMPAIGN_SCHEMA_VERSION, + "artifact_kind": "m8_prospective_live_l2_campaign_authority", + "config_sha256": config.hash, + "config_source_sha256": config.source_sha256, + "protocol_sha256": M8_L2_PROTOCOL_SHA256, + "protocol_freeze_commit": M8_L2_FREEZE_COMMIT, + "runtime_commit": source.commit, + "runtime_source_tree_sha256": source.source_tree_sha256, + "runtime_dirty": False, + } + if any(value.get(name) != expected for name, expected in expected_claims.items()): + raise M8L2CaptureSystemError( + "live-L2 campaign authority differs from the frozen configuration/source identity" + ) + nonce = value.get("campaign_nonce") + if type(nonce) is not str or not _is_lower_sha256(nonce): + raise M8L2CaptureSystemError("live-L2 campaign nonce is malformed") + output_path, output_device, output_inode = _recorded_output_root(value.get("output_root")) + if (expected_root is None) != (expected_root_identity is None): + raise M8L2CaptureSystemError("campaign root validation coordinates are incomplete") + if ( + expected_root is not None + and expected_root_identity is not None + and ( + output_path != str(expected_root) + or (output_device, output_inode) != expected_root_identity + ) + ): + raise M8L2CaptureSystemError( + "live-L2 campaign authority differs from the current output-root identity" + ) + runtime = _runtime_from_recorded( + value.get("runtime_fingerprint"), value.get("runtime_fingerprint_sha256") + ) + if expected_runtime is not None and runtime != expected_runtime: + raise M8L2CaptureSystemError( + "live-L2 campaign authority differs from the current production runtime" + ) + digest = hashlib.sha256(raw).hexdigest() + if expected_sha256 is not None and digest != expected_sha256: + raise M8L2CaptureSystemError("live-L2 campaign authority digest changed") + return _CampaignAuthority( + path=path, + sha256=digest, + raw=raw, + source=source, + runtime=runtime, + nonce=nonce, + output_root_path=output_path, + output_root_device=output_device, + output_root_inode=output_inode, + ) + + +def _verify_campaign_authority( + root: Path, + *, + root_identity: tuple[int, int], + config: M8L2StudyConfig, + source: CaptureSourceIdentity, + runtime: _RuntimeFingerprint, + expected_sha256: str | None = None, +) -> _CampaignAuthority: + if _directory_identity(root, label="live-L2 output root") != root_identity: + raise M8L2CaptureSystemError("live-L2 output root identity changed") + path = root / _CAMPAIGN_AUTHORITY_NAME + _assert_no_symlink_components(path, root, "live-L2 campaign authority") + raw = _read_bounded_regular_nofollow( + path, + label="live-L2 campaign authority", + maximum_bytes=_MAX_CAMPAIGN_AUTHORITY_BYTES, + ) + if _directory_identity(root, label="live-L2 output root") != root_identity: + raise M8L2CaptureSystemError("live-L2 output root changed during campaign verification") + return _validate_campaign_bytes( + raw, + path=path, + config=config, + source=source, + expected_runtime=runtime, + expected_root=root, + expected_root_identity=root_identity, + expected_sha256=expected_sha256, + ) + + +def _create_campaign_authority_once( + root: Path, *, root_identity: tuple[int, int], raw: bytes +) -> None: + """Atomically link one fsynced authority into place without replacement.""" + + descriptor, temporary_name = tempfile.mkstemp( + dir=root, prefix=".campaign-authority-", suffix=".tmp" + ) + temporary = Path(temporary_name) + root_descriptor = -1 + try: + with os.fdopen(descriptor, "wb") as handle: + handle.write(raw) + handle.flush() + os.fsync(handle.fileno()) + directory_flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0) + root_descriptor = os.open(root, directory_flags) + root_metadata = os.fstat(root_descriptor) + if (root_metadata.st_dev, root_metadata.st_ino) != root_identity: + raise M8L2CaptureSystemError( + "live-L2 output root changed before campaign authority creation" + ) + with suppress(FileExistsError): + os.link( + temporary.name, + _CAMPAIGN_AUTHORITY_NAME, + src_dir_fd=root_descriptor, + dst_dir_fd=root_descriptor, + follow_symlinks=False, + ) + # This fsync makes either our new link or a concurrent creator's link + # durable before either caller may proceed toward a network connection. + os.fsync(root_descriptor) + os.unlink(temporary.name, dir_fd=root_descriptor) + temporary = Path() + os.fsync(root_descriptor) + finally: + if root_descriptor >= 0: + os.close(root_descriptor) + if temporary != Path(): + with suppress(OSError): + temporary.unlink(missing_ok=True) + + +def _ensure_campaign_authority( + root: Path, + *, + root_identity: tuple[int, int], + config: M8L2StudyConfig, + source: CaptureSourceIdentity, + runtime: _RuntimeFingerprint, +) -> _CampaignAuthority: + path = root / _CAMPAIGN_AUTHORITY_NAME + try: + path.lstat() + except FileNotFoundError: + _create_campaign_authority_once( + root, + root_identity=root_identity, + raw=_canonical_json_bytes( + _campaign_payload( + config=config, + source=source, + runtime=runtime, + nonce=secrets.token_hex(32), + root=root, + root_identity=root_identity, + ) + ), + ) + except OSError as error: + raise M8L2CaptureSystemError( + f"cannot inspect live-L2 campaign authority: {path}" + ) from error + return _verify_campaign_authority( + root, + root_identity=root_identity, + config=config, + source=source, + runtime=runtime, + ) + + +def _verify_bundled_campaign_authority( + path: Path, + *, + config: M8L2StudyConfig, + source: CaptureSourceIdentity, + expected_sha256: str, +) -> _CampaignAuthority: + raw = _read_bounded_regular_nofollow( + path, + label="bundled live-L2 campaign authority", + maximum_bytes=_MAX_CAMPAIGN_AUTHORITY_BYTES, + ) + return _validate_campaign_bytes( + raw, + path=path, + config=config, + source=source, + expected_sha256=expected_sha256, + ) + + +def _fsync_tree(root: Path) -> None: + files, directories = _walk_regular_evidence(root) + for path in files: + flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) + descriptor = os.open(path, flags) + try: + if not stat.S_ISREG(os.fstat(descriptor).st_mode): + raise M8L2CaptureSystemError(f"cannot fsync non-regular evidence: {path}") + os.fsync(descriptor) + finally: + os.close(descriptor) + for directory in sorted(directories, key=lambda item: len(item.parts), reverse=True): + _fsync_directory(directory) + + +def _inventory(root: Path, *, exclude: frozenset[str] = frozenset()) -> list[dict[str, object]]: + result: list[dict[str, object]] = [] + for path in _all_regular_files(root): + relative = _relative(path, root) + if relative in exclude: + continue + result.append( + { + "path": relative, + "sha256": sha256_file(path), + "bytes": path.stat().st_size, + } + ) + return result + + +def _write_checksums(stage: Path) -> Path: + protected = _inventory( + stage, + exclude=frozenset({_CHECKSUM_NAME, _COMPLETE_MARKER, _INSUFFICIENT_MARKER}), + ) + content = "".join(f"{entry['sha256']} {entry['path']}\n" for entry in protected).encode() + path = stage / _CHECKSUM_NAME + _write_bytes_durable(path, content) + return path + + +def _publish_terminal( + *, + stage: Path, + target: Path, + config: M8L2StudyConfig, + protocol: Path, + session: M8L2Session, + session_id: str, + source: CaptureSourceIdentity, + runtime: _RuntimeFingerprint, + source_identity_was_injected: bool, + campaign: _CampaignAuthority, + status: SessionStatus, + reason_codes: Sequence[str], + phase_ledger: Sequence[Mapping[str, object]], + gates: Sequence[Mapping[str, object]], + results: Mapping[str, SymbolCaptureResult], + barrier_released_ns: int | None, + overlap_ns: int, + capture_finished_ns: int | None, + root_identity: tuple[int, int], + sessions_identity: tuple[int, int], +) -> M8L2SessionBundle: + observed_campaign = _verify_campaign_authority( + target.parent.parent, + root_identity=root_identity, + config=config, + source=source, + runtime=runtime, + expected_sha256=campaign.sha256, + ) + if observed_campaign.raw != campaign.raw: + raise M8L2CaptureSystemError("live-L2 campaign authority bytes changed") + _verify_bundled_campaign_authority( + stage / "authority" / _CAMPAIGN_AUTHORITY_NAME, + config=config, + source=source, + expected_sha256=campaign.sha256, + ) + authority_inventory = _inventory(stage) + marker_name = _COMPLETE_MARKER if status == "COMPLETE" else _INSUFFICIENT_MARKER + manifest_payload: dict[str, object] = { + "schema_version": _SESSION_SCHEMA_VERSION, + "artifact_kind": "m8_prospective_live_l2_session", + "generated_at_utc": utc_now_iso(), + "status": status, + "session_id": session_id, + "study_name": config.study.name, + "protocol_version": config.study.protocol_version, + "evidence_tier": config.study.evidence_tier, + "live_trading": False, + "session": { + "date": session.date.isoformat(), + "role": session.role, + "scheduled_start_ns": session.start_ns, + "scheduled_end_ns": session.end_ns, + "scheduled_duration_seconds": (session.end_ns - session.start_ns) + / _NANOSECONDS_PER_SECOND, + "barrier_released_ns": barrier_released_ns, + "barrier_lateness_ns": ( + max(0, barrier_released_ns - session.start_ns) + if barrier_released_ns is not None + else None + ), + "capture_finished_ns": capture_finished_ns, + }, + "authority": { + "campaign_authority_sha256": campaign.sha256, + "config_sha256": config.hash, + "config_source_sha256": config.source_sha256, + "protocol_sha256": M8_L2_PROTOCOL_SHA256, + "protocol_freeze_commit": M8_L2_FREEZE_COMMIT, + "runtime_commit": source.commit, + "runtime_source_tree_sha256": source.source_tree_sha256, + "runtime_dirty": source.dirty, + "runtime_fingerprint": campaign.runtime.payload(), + "runtime_fingerprint_sha256": campaign.runtime.sha256, + }, + "symbols": { + symbol: _symbol_payload(result, stage_root=stage) + for symbol, result in sorted(results.items()) + }, + "cross_symbol_observed_overlap_seconds": overlap_ns / _NANOSECONDS_PER_SECOND, + "gates": [dict(item) for item in gates], + "reason_codes": list(sorted(set(reason_codes))), + "phase_ledger": [dict(item) for item in phase_ledger], + "artifact_inventory": authority_inventory, + "terminal_marker": { + "path": marker_name, + "bytes": "complete\\n" if status == "COMPLETE" else "terminal\\n", + }, + "policy": ( + "both symbols share one frozen session authority; only OBSERVED continuity intervals " + "count toward overlap; failed gates publish no research result" + ), + } + manifest_path = stage / "session_manifest.json" + write_json(manifest_path, manifest_payload) + _write_checksums(stage) + _fsync_tree(stage) + _revalidate_runtime_authority( + config=config, + protocol=protocol, + expected_source=source, + expected_runtime=runtime, + source_identity_was_injected=source_identity_was_injected, + ) + marker_campaign = _verify_campaign_authority( + target.parent.parent, + root_identity=root_identity, + config=config, + source=source, + runtime=runtime, + expected_sha256=campaign.sha256, + ) + if marker_campaign.raw != campaign.raw: + raise M8L2CaptureSystemError( + "live-L2 campaign authority changed immediately before marker materialization" + ) + marker_path = stage / marker_name + _write_bytes_durable( + marker_path, + _COMPLETE_BYTES if status == "COMPLETE" else _INSUFFICIENT_BYTES, + ) + _fsync_directory(stage) + _revalidate_output_layout( + target.parent.parent, + root_identity=root_identity, + sessions_identity=sessions_identity, + target=target, + ) + if target.exists() or target.is_symlink(): + raise M8L2CaptureSystemError(f"refusing to overwrite existing session authority: {target}") + source_parent = stage.parent + directory_flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0) + source_parent_descriptor = os.open(source_parent, directory_flags) + target_parent_descriptor = os.open(target.parent, directory_flags) + try: + if ( + os.fstat(source_parent_descriptor).st_dev, + os.fstat(source_parent_descriptor).st_ino, + ) != (root_identity): + raise M8L2CaptureSystemError("live-L2 stage parent identity changed before rename") + if ( + os.fstat(target_parent_descriptor).st_dev, + os.fstat(target_parent_descriptor).st_ino, + ) != sessions_identity: + raise M8L2CaptureSystemError("live-L2 target parent identity changed before rename") + _revalidate_runtime_authority( + config=config, + protocol=protocol, + expected_source=source, + expected_runtime=runtime, + source_identity_was_injected=source_identity_was_injected, + ) + final_campaign = _verify_campaign_authority( + target.parent.parent, + root_identity=root_identity, + config=config, + source=source, + runtime=runtime, + expected_sha256=campaign.sha256, + ) + if final_campaign.raw != campaign.raw: + raise M8L2CaptureSystemError( + "live-L2 campaign authority changed immediately before terminal publication" + ) + os.rename( + stage.name, + target.name, + src_dir_fd=source_parent_descriptor, + dst_dir_fd=target_parent_descriptor, + ) + # A cross-directory rename mutates both directory entries. Durability + # therefore requires both the old and the new parent directory fsyncs. + os.fsync(source_parent_descriptor) + os.fsync(target_parent_descriptor) + finally: + os.close(target_parent_descriptor) + os.close(source_parent_descriptor) + _revalidate_output_layout( + target.parent.parent, + root_identity=root_identity, + sessions_identity=sessions_identity, + target=target, + ) + return verify_m8_l2_session_bundle(target, expected_config=config) + + +def _retain_system_failure( + *, + stage: Path, + output_root: Path, + session_id: str, + session: M8L2Session, + error: BaseException, +) -> Path: + evidence_root = stage + try: + inventory = _inventory(stage) + write_json( + stage / "SYSTEM_FAILURE.json", + { + "schema_version": _SESSION_SCHEMA_VERSION, + "artifact_kind": "m8_live_l2_nonterminal_system_failure", + "generated_at_utc": utc_now_iso(), + "terminal": False, + "research_result": False, + "session_id": session_id, + "session_date": session.date.isoformat(), + "role": session.role, + "error_type": type(error).__name__, + "error": str(error)[:2048], + "preserved_inventory_before_record": inventory, + "policy": "incomplete evidence only; no terminal marker and no research reuse", + }, + ) + _fsync_tree(stage) + incomplete_root = output_root / "incomplete" + _reject_existing_symlink_components( + incomplete_root, label="live-L2 incomplete-evidence directory" + ) + incomplete_root.mkdir(parents=True, exist_ok=True) + _directory_identity(incomplete_root, label="live-L2 incomplete-evidence directory") + destination = incomplete_root / f"SYSTEM_FAILURE-{session_id[:20]}-{stage.name[-12:]}" + if destination.exists(): + raise FileExistsError(destination) + old_parent = stage.parent + os.rename(stage, destination) + _fsync_directory(old_parent) + _fsync_directory(incomplete_root) + evidence_root = destination + except BaseException: + # The original stage is intentionally never deleted; it may contain the + # sole copy of already-received raw frames. + evidence_root = stage + return evidence_root + + +def _publish_or_retain_system_failure( + *, + stage: Path, + target: Path, + output_root: Path, + config: M8L2StudyConfig, + protocol: Path, + session: M8L2Session, + session_id: str, + source: CaptureSourceIdentity, + runtime: _RuntimeFingerprint, + source_identity_was_injected: bool, + campaign: _CampaignAuthority, + status: SessionStatus, + reason_codes: Sequence[str], + phase_ledger: Sequence[Mapping[str, object]], + gates: Sequence[Mapping[str, object]], + results: Mapping[str, SymbolCaptureResult], + barrier_released_ns: int | None, + overlap_ns: int, + capture_finished_ns: int | None, + root_identity: tuple[int, int], + sessions_identity: tuple[int, int], +) -> M8L2SessionBundle: + """Publish terminally or demote every publication fault to preserved evidence.""" + + try: + return _publish_terminal( + stage=stage, + target=target, + config=config, + protocol=protocol, + session=session, + session_id=session_id, + source=source, + runtime=runtime, + source_identity_was_injected=source_identity_was_injected, + campaign=campaign, + status=status, + reason_codes=reason_codes, + phase_ledger=phase_ledger, + gates=gates, + results=results, + barrier_released_ns=barrier_released_ns, + overlap_ns=overlap_ns, + capture_finished_ns=capture_finished_ns, + root_identity=root_identity, + sessions_identity=sessions_identity, + ) + except BaseException as error: + # If rename already succeeded but verification failed, demote our newly + # published directory. A concurrent pre-existing target is never touched + # while our private stage still exists. + evidence_stage = stage if stage.exists() else target + for marker_name in (_COMPLETE_MARKER, _INSUFFICIENT_MARKER): + marker = evidence_stage / marker_name + with suppress(OSError): + marker.unlink(missing_ok=True) + evidence_root = _retain_system_failure( + stage=evidence_stage, + output_root=output_root, + session_id=session_id, + session=session, + error=error, + ) + raise M8L2CaptureSystemError( + f"live-L2 terminal publication failed without a terminal result: " + f"{type(error).__name__}: {error}", + evidence_root=evidence_root, + ) from error + + +def _data_failure_result( + *, + symbol: str, + reason_code: str, + phase: str, + stage_root: Path, +) -> SymbolCaptureResult: + artifacts = tuple( + CapturedArtifact(path=path, kind="partial_evidence", sha256=sha256_file(path)) + for path in _all_regular_files(stage_root) + ) + return SymbolCaptureResult( + symbol=symbol, + capture_id=f"{symbol.lower()}-failed", + status="FAILED", + completion_reason="capture_failed", + reconstruction_status="NOT_STARTED", + messages=0, + normalized_rows=0, + reconstructed_rows=0, + excluded_rows=0, + continuity_epochs=0, + snapshot_anchors=0, + sequence_gaps=0, + quality_errors=0, + quality_warnings=0, + max_raw_frame_bytes_observed=0, + max_arrow_batch_bytes_observed=0, + first_raw_received_ns=None, + last_raw_received_ns=None, + valid_observed_intervals=(), + artifacts=artifacts, + failure_reason_code=reason_code, + failure_phase=phase, + ) + + +async def _wait_for_start(clock: CaptureClock, start_ns: int) -> int: + while True: + now = clock.time_ns() + if now >= start_ns: + return now + # Recheck wall time at short intervals so suspend/resume and wall-clock + # adjustments cannot silently convert the absolute UTC boundary into a + # relative duration. + await clock.sleep(min(30.0, (start_ns - now) / _NANOSECONDS_PER_SECOND)) + + +async def capture_m8_l2_session( + config: M8L2StudyConfig, + session_date: str, + output_root: str | Path, + capture_one: CaptureOne, + *, + protocol_path: str | Path | None = None, + clock: CaptureClock | None = None, + _test_source_identity: CaptureSourceIdentity | None = None, + _test_allow_injected_capture: bool = False, +) -> M8L2SessionBundle: + """Capture both symbols under one absolute-time, immutable session authority.""" + + try: + canonical_config = load_m8_l2_config(config.path) + except (OSError, ValueError) as error: + raise M8L2CaptureSystemError( + "configuration is not the frozen live-L2 byte authority" + ) from error + if canonical_config != config or canonical_config.hash != config.hash: + raise M8L2CaptureSystemError( + "in-memory configuration differs from the frozen live-L2 byte authority" + ) + session = config.session_for_date(session_date) + if ( + session.end_ns - session.start_ns + != config.capture.duration_seconds * _NANOSECONDS_PER_SECOND + ): + raise M8L2CaptureSystemError("frozen session duration and capture duration disagree") + project_root = config.path.parent.parent.resolve() + requested_protocol = ( + Path(protocol_path) + if protocol_path is not None + else project_root / "docs" / "M8_L2_PROTOCOL.md" + ) + if requested_protocol.is_symlink(): + raise M8L2CaptureSystemError("frozen live-L2 protocol must not be a symlink") + protocol = requested_protocol.resolve() + _assert_protocol(protocol) + if _test_source_identity is not None and clock is None: + raise M8L2CaptureSystemError( + "test source identity injection requires an explicitly injected test clock" + ) + if _test_allow_injected_capture and clock is None: + raise M8L2CaptureSystemError( + "test capture injection requires an explicitly injected test clock" + ) + source_identity_was_injected = _test_source_identity is not None + if not source_identity_was_injected: + _assert_loaded_source_root(project_root) + if not source_identity_was_injected and not _test_allow_injected_capture: + # These private keyword-only values are unit-test seams for injected + # collectors. The production CLI supplies neither and therefore + # cannot bypass the exact adapter-origin gate. + _assert_production_capture_origin(project_root, capture_one) + source = _test_source_identity or _source_identity(project_root) + _validate_source_identity(source) + runtime = _runtime_fingerprint() + _revalidate_runtime_authority( + config=config, + protocol=protocol, + expected_source=source, + expected_runtime=runtime, + source_identity_was_injected=source_identity_was_injected, + ) + root, root_identity, sessions_identity = _prepare_output_root(output_root) + campaign = _ensure_campaign_authority( + root, + root_identity=root_identity, + config=config, + source=source, + runtime=runtime, + ) + session_id = _session_identity( + config=config, + session=session, + source=source, + campaign_authority_sha256=campaign.sha256, + ) + target = _terminal_root(root, session, session_id) + _revalidate_output_layout( + root, + root_identity=root_identity, + sessions_identity=sessions_identity, + target=target, + ) + if target.exists() or target.is_symlink(): + return verify_m8_l2_session_bundle(target, expected_config=config) + + stage = Path(tempfile.mkdtemp(dir=root, prefix=f".m8-l2-{session_id[:12]}-")) + authority_root = stage / "authority" + authority_root.mkdir(parents=True, exist_ok=True) + shutil.copyfile(config.path, authority_root / "m8_l2_capture_study.toml") + shutil.copyfile(protocol, authority_root / "M8_L2_PROTOCOL.md") + _write_bytes_durable( + authority_root / _CAMPAIGN_AUTHORITY_NAME, + campaign.raw, + ) + capture_clock = clock or _SystemClock() + now = capture_clock.time_ns() + phase_ledger: list[dict[str, object]] = [ + {"phase": "PREFLIGHT", "status": "COMPLETE", "at_ns": now} + ] + if now >= session.end_ns: + phase_ledger.extend( + [ + {"phase": "BOUNDARY_WAIT", "status": "MISSED", "at_ns": now}, + {"phase": "DUAL_CAPTURE", "status": "NOT_RUN"}, + {"phase": "SESSION_GATES", "status": "FAILED"}, + {"phase": "TERMINALIZATION", "status": "READY"}, + ] + ) + return _publish_or_retain_system_failure( + stage=stage, + target=target, + output_root=root, + config=config, + protocol=protocol, + session=session, + session_id=session_id, + source=source, + runtime=runtime, + source_identity_was_injected=source_identity_was_injected, + campaign=campaign, + status="INSUFFICIENT_DATA", + reason_codes=("MISSED_WINDOW",), + phase_ledger=phase_ledger, + gates=(), + results={}, + barrier_released_ns=None, + overlap_ns=0, + capture_finished_ns=None, + root_identity=root_identity, + sessions_identity=sessions_identity, + ) + + try: + barrier_ns = await _wait_for_start(capture_clock, session.start_ns) + except asyncio.CancelledError: + # Before the declared interval, cancellation is restartable and does not + # consume or terminalize the future session. + raise + if barrier_ns >= session.end_ns: + try: + _revalidate_runtime_authority( + config=config, + protocol=protocol, + expected_source=source, + expected_runtime=runtime, + source_identity_was_injected=source_identity_was_injected, + ) + _verify_campaign_authority( + root, + root_identity=root_identity, + config=config, + source=source, + runtime=runtime, + expected_sha256=campaign.sha256, + ) + except BaseException as error: + evidence_root = _retain_system_failure( + stage=stage, + output_root=root, + session_id=session_id, + session=session, + error=error, + ) + raise M8L2CaptureSystemError( + "live-L2 authority changed while waiting for the frozen window", + evidence_root=evidence_root, + ) from error + phase_ledger.extend( + [ + {"phase": "BOUNDARY_WAIT", "status": "MISSED", "at_ns": barrier_ns}, + {"phase": "DUAL_CAPTURE", "status": "NOT_RUN"}, + {"phase": "SESSION_GATES", "status": "FAILED"}, + {"phase": "TERMINALIZATION", "status": "READY"}, + ] + ) + return _publish_or_retain_system_failure( + stage=stage, + target=target, + output_root=root, + config=config, + protocol=protocol, + session=session, + session_id=session_id, + source=source, + runtime=runtime, + source_identity_was_injected=source_identity_was_injected, + campaign=campaign, + status="INSUFFICIENT_DATA", + reason_codes=("MISSED_WINDOW",), + phase_ledger=phase_ledger, + gates=(), + results={}, + barrier_released_ns=barrier_ns, + overlap_ns=0, + capture_finished_ns=None, + root_identity=root_identity, + sessions_identity=sessions_identity, + ) + phase_ledger.append({"phase": "BOUNDARY_WAIT", "status": "COMPLETE", "at_ns": barrier_ns}) + + try: + _revalidate_runtime_authority( + config=config, + protocol=protocol, + expected_source=source, + expected_runtime=runtime, + source_identity_was_injected=source_identity_was_injected, + ) + _verify_campaign_authority( + root, + root_identity=root_identity, + config=config, + source=source, + runtime=runtime, + expected_sha256=campaign.sha256, + ) + except BaseException as error: + evidence_root = _retain_system_failure( + stage=stage, + output_root=root, + session_id=session_id, + session=session, + error=error, + ) + raise M8L2CaptureSystemError( + "live-L2 authority changed before dual-symbol capture", + evidence_root=evidence_root, + ) from error + + tasks: dict[str, asyncio.Task[SymbolCaptureResult]] = {} + for symbol in config.study.symbols: + symbol_root = stage / "symbols" / symbol + symbol_root.mkdir(parents=True, exist_ok=True) + tasks[symbol] = asyncio.create_task( + capture_one( + symbol=symbol, + scheduled_start_ns=session.start_ns, + scheduled_end_ns=session.end_ns, + stage_root=symbol_root, + limits=config.capture, + session_id=session_id, + ), + name=f"m8-l2-{session.date.isoformat()}-{symbol}", + ) + + outer_canceled = False + try: + outcomes = await asyncio.gather(*tasks.values(), return_exceptions=True) + except asyncio.CancelledError: + outer_canceled = True + for task in tasks.values(): + task.cancel() + outcomes = await asyncio.gather(*tasks.values(), return_exceptions=True) + capture_finished_ns = capture_clock.time_ns() + + results: dict[str, SymbolCaptureResult] = {} + data_reasons: list[str] = [] + system_errors: list[BaseException] = [] + for symbol, outcome in zip(tasks, outcomes, strict=True): + symbol_root = stage / "symbols" / symbol + if isinstance(outcome, SymbolCaptureResult): + try: + results[symbol] = _validate_symbol_result( + outcome, + expected_symbol=symbol, + symbol_root=symbol_root, + session=session, + ) + except BaseException as error: + system_errors.append(error) + elif isinstance(outcome, M8L2DataFailure): + data_reasons.append(outcome.reason_code) + partial = outcome.partial_result + if partial is None: + partial = _data_failure_result( + symbol=symbol, + reason_code=outcome.reason_code, + phase=outcome.phase, + stage_root=symbol_root, + ) + try: + results[symbol] = _validate_symbol_result( + partial, + expected_symbol=symbol, + symbol_root=symbol_root, + session=session, + ) + except BaseException as error: + system_errors.append(error) + elif isinstance(outcome, asyncio.CancelledError): + data_reasons.append("CAPTURE_CANCELED") + results[symbol] = _data_failure_result( + symbol=symbol, + reason_code="CAPTURE_CANCELED", + phase="DUAL_CAPTURE", + stage_root=symbol_root, + ) + elif isinstance(outcome, BaseException): + system_errors.append(outcome) + + if outer_canceled: + data_reasons.append("CAPTURE_CANCELED") + if system_errors: + primary = system_errors[0] + evidence_root = _retain_system_failure( + stage=stage, + output_root=root, + session_id=session_id, + session=session, + error=primary, + ) + raise M8L2CaptureSystemError( + f"live-L2 capture ended in a nonterminal system failure: {type(primary).__name__}: {primary}", + evidence_root=evidence_root, + ) from primary + if capture_finished_ns < session.end_ns and any( + result.status == "COMPLETE" for result in results.values() + ): + early_completion_error = M8L2CaptureSystemError( + "single-symbol capture reported success before the frozen scheduled end" + ) + evidence_root = _retain_system_failure( + stage=stage, + output_root=root, + session_id=session_id, + session=session, + error=early_completion_error, + ) + raise M8L2CaptureSystemError( + str(early_completion_error), evidence_root=evidence_root + ) from early_completion_error + + phase_ledger.append( + { + "phase": "DUAL_CAPTURE", + "status": "FAILED" if data_reasons else "COMPLETE", + "symbols_completed": sorted(results), + } + ) + try: + _revalidate_runtime_authority( + config=config, + protocol=protocol, + expected_source=source, + expected_runtime=runtime, + source_identity_was_injected=source_identity_was_injected, + ) + _verify_campaign_authority( + root, + root_identity=root_identity, + config=config, + source=source, + runtime=runtime, + expected_sha256=campaign.sha256, + ) + gates, gate_reasons, overlap_ns = _evaluate_gates(results, config=config) + except BaseException as error: + evidence_root = _retain_system_failure( + stage=stage, + output_root=root, + session_id=session_id, + session=session, + error=error, + ) + raise M8L2CaptureSystemError( + "live-L2 authority/gate evaluation ended in a nonterminal system failure", + evidence_root=evidence_root, + ) from error + all_reasons = sorted(set((*data_reasons, *gate_reasons))) + status: SessionStatus = "COMPLETE" if not all_reasons else "INSUFFICIENT_DATA" + phase_ledger.extend( + [ + { + "phase": "SESSION_GATES", + "status": "COMPLETE" if status == "COMPLETE" else "FAILED", + }, + {"phase": "TERMINALIZATION", "status": "READY"}, + ] + ) + return _publish_or_retain_system_failure( + stage=stage, + target=target, + output_root=root, + config=config, + protocol=protocol, + session=session, + session_id=session_id, + source=source, + runtime=runtime, + source_identity_was_injected=source_identity_was_injected, + campaign=campaign, + status=status, + reason_codes=all_reasons, + phase_ledger=phase_ledger, + gates=gates, + results=results, + barrier_released_ns=barrier_ns, + overlap_ns=overlap_ns, + capture_finished_ns=capture_finished_ns, + root_identity=root_identity, + sessions_identity=sessions_identity, + ) + + +def _safe_checksum_relative(value: str) -> str: + candidate = PurePosixPath(value) + if ( + not value + or candidate.is_absolute() + or ".." in candidate.parts + or value != candidate.as_posix() + or "\n" in value + or "\r" in value + ): + raise M8L2VerificationError(f"unsafe checksum path: {value!r}") + return value + + +def _parse_checksums(path: Path) -> dict[str, str]: + try: + lines = path.read_text(encoding="ascii").splitlines() + except (OSError, UnicodeError) as error: + raise M8L2VerificationError(f"cannot read checksum authority: {path}") from error + result: dict[str, str] = {} + for line in lines: + if len(line) < 67 or line[64:66] != " ": + raise M8L2VerificationError("checksum authority has a malformed line") + digest = line[:64] + relative = _safe_checksum_relative(line[66:]) + if not _is_lower_sha256(digest): + raise M8L2VerificationError("checksum authority contains an invalid digest") + if relative in result: + raise M8L2VerificationError(f"checksum authority repeats {relative}") + result[relative] = digest + if not result: + raise M8L2VerificationError("checksum authority must protect at least one file") + return result + + +def _manifest_object(value: object, label: str) -> Mapping[str, Any]: + if not isinstance(value, Mapping) or not all(type(key) is str for key in value): + raise M8L2VerificationError(f"{label} must be a JSON object") + return cast(Mapping[str, Any], value) + + +def _verification_json(path: Path, label: str) -> object: + try: + return _strict_json(path, label=label) + except M8L2CaptureSystemError as error: + raise M8L2VerificationError(str(error)) from error + + +def _symbol_result_from_manifest( + value: object, + *, + symbol: str, + root: Path, + session: M8L2Session, +) -> SymbolCaptureResult: + payload = _manifest_object(value, f"symbols.{symbol}") + + def integer(name: str) -> int: + raw = payload.get(name) + if type(raw) is not int or raw < 0: + raise M8L2VerificationError(f"symbols.{symbol}.{name} is invalid") + return raw + + intervals_raw = payload.get("valid_observed_intervals") + if not isinstance(intervals_raw, list): + raise M8L2VerificationError(f"symbols.{symbol} intervals must be an array") + intervals: list[ObservedInterval] = [] + for index, raw in enumerate(intervals_raw): + entry = _manifest_object(raw, f"symbols.{symbol}.intervals[{index}]") + continuity_id = entry.get("continuity_id") + start = entry.get("start_received_ns") + end = entry.get("end_received_ns_exclusive") + if type(continuity_id) is not str or type(start) is not int or type(end) is not int: + raise M8L2VerificationError("session manifest has a malformed OBSERVED interval") + try: + interval = ObservedInterval(continuity_id, start, end) + except ValueError as error: + raise M8L2VerificationError( + "session manifest has an invalid OBSERVED interval" + ) from error + if dict(entry) != interval.to_dict(): + raise M8L2VerificationError("session OBSERVED interval derived fields are inconsistent") + intervals.append(interval) + + artifacts_raw = payload.get("artifacts") + if not isinstance(artifacts_raw, list): + raise M8L2VerificationError(f"symbols.{symbol}.artifacts must be an array") + artifacts: list[CapturedArtifact] = [] + for index, raw in enumerate(artifacts_raw): + entry = _manifest_object(raw, f"symbols.{symbol}.artifacts[{index}]") + if set(entry) != {"path", "kind", "sha256", "bytes"}: + raise M8L2VerificationError("session symbol artifact entry is not exact") + relative_value = entry.get("path") + kind = entry.get("kind") + digest = entry.get("sha256") + size = entry.get("bytes") + if ( + type(relative_value) is not str + or type(kind) is not str + or type(digest) is not str + or not _is_lower_sha256(digest) + or type(size) is not int + or size < 0 + ): + raise M8L2VerificationError("session symbol artifact entry is malformed") + relative = _safe_checksum_relative(relative_value) + parts = PurePosixPath(relative).parts + if len(parts) < 3 or parts[:2] != ("symbols", symbol): + raise M8L2VerificationError("session symbol artifact escapes its symbol coordinate") + path = root.joinpath(*parts) + if path.stat().st_size != size: + raise M8L2VerificationError("session symbol artifact size differs from its claim") + artifacts.append(CapturedArtifact(path=path, kind=kind, sha256=digest)) + + status = payload.get("status") + reconstruction = payload.get("reconstruction_status") + if status not in {"COMPLETE", "FAILED"} or reconstruction not in { + "LIVE", + "GAPPED", + "INVALID", + "NOT_STARTED", + }: + raise M8L2VerificationError("session symbol status is invalid") + capture_id = payload.get("capture_id") + completion_reason = payload.get("completion_reason") + first = payload.get("first_raw_received_ns") + last = payload.get("last_raw_received_ns") + failure_reason = payload.get("failure_reason_code") + failure_phase = payload.get("failure_phase") + if ( + type(capture_id) is not str + or type(completion_reason) is not str + or (first is not None and type(first) is not int) + or (last is not None and type(last) is not int) + or (failure_reason is not None and type(failure_reason) is not str) + or (failure_phase is not None and type(failure_phase) is not str) + ): + raise M8L2VerificationError("session symbol scalar claims are invalid") + result = SymbolCaptureResult( + symbol=symbol, + capture_id=capture_id, + status=cast(CaptureStatus, status), + completion_reason=completion_reason, + reconstruction_status=cast(ReconstructionStatus, reconstruction), + messages=integer("messages"), + normalized_rows=integer("normalized_rows"), + reconstructed_rows=integer("reconstructed_rows"), + excluded_rows=integer("excluded_rows"), + continuity_epochs=integer("continuity_epochs"), + snapshot_anchors=integer("snapshot_anchors"), + sequence_gaps=integer("sequence_gaps"), + quality_errors=integer("quality_errors"), + quality_warnings=integer("quality_warnings"), + max_raw_frame_bytes_observed=integer("max_raw_frame_bytes_observed"), + max_arrow_batch_bytes_observed=integer("max_arrow_batch_bytes_observed"), + first_raw_received_ns=first, + last_raw_received_ns=last, + valid_observed_intervals=tuple(intervals), + artifacts=tuple(artifacts), + failure_reason_code=failure_reason, + failure_phase=failure_phase, + ) + try: + validated = _validate_symbol_result( + result, + expected_symbol=symbol, + symbol_root=root / "symbols" / symbol, + session=session, + ) + except M8L2CaptureError as error: + raise M8L2VerificationError(str(error)) from error + if dict(payload) != _symbol_payload(validated, stage_root=root): + raise M8L2VerificationError("session symbol payload is not its canonical claim projection") + return validated + + +def verify_m8_l2_session_bundle( + bundle_dir: str | Path, + *, + expected_config: M8L2StudyConfig | None = None, +) -> M8L2SessionBundle: + """Verify marker bytes, exact physical inventory, checksums, and frozen authority.""" + + requested_root = Path(bundle_dir) + try: + _reject_existing_symlink_components(requested_root, label="session bundle path") + except M8L2CaptureSystemError as error: + raise M8L2VerificationError(str(error)) from error + root = requested_root.absolute() + try: + if not stat.S_ISDIR(root.lstat().st_mode): + raise M8L2VerificationError(f"session bundle is not a regular directory: {root}") + files, _ = _walk_regular_evidence(root) + except (OSError, M8L2CaptureSystemError) as error: + raise M8L2VerificationError(f"invalid session bundle filesystem: {error}") from error + if root.parent.name != "sessions": + raise M8L2VerificationError("session bundle parent is not the canonical sessions directory") + manifest_path = root / "session_manifest.json" + checksum_path = root / _CHECKSUM_NAME + regular_paths = {_relative(path, root): path for path in files} + if "session_manifest.json" not in regular_paths or _CHECKSUM_NAME not in regular_paths: + raise M8L2VerificationError("session bundle lacks its manifest or checksum authority") + checksums = _parse_checksums(checksum_path) + marker_candidates = [ + root / name for name in (_COMPLETE_MARKER, _INSUFFICIENT_MARKER) if name in regular_paths + ] + if len(marker_candidates) != 1: + raise M8L2VerificationError("session bundle must have exactly one terminal marker") + marker_path = marker_candidates[0] + expected_marker_bytes = ( + _COMPLETE_BYTES if marker_path.name == _COMPLETE_MARKER else _INSUFFICIENT_BYTES + ) + if marker_path.read_bytes() != expected_marker_bytes: + raise M8L2VerificationError("session terminal marker bytes differ from the contract") + + actual = set(regular_paths) + expected = set(checksums) | {_CHECKSUM_NAME, marker_path.name} + if actual != expected: + raise M8L2VerificationError( + "session physical inventory differs from its checksum authority " + f"(missing={sorted(expected - actual)}, extra={sorted(actual - expected)})" + ) + for relative, digest in checksums.items(): + path = root / relative + if sha256_file(path) != digest: + raise M8L2VerificationError(f"checksum mismatch for {relative}") + + payload = _manifest_object( + _verification_json(manifest_path, "session manifest"), "session manifest" + ) + if set(payload) != { + "schema_version", + "artifact_kind", + "generated_at_utc", + "status", + "session_id", + "study_name", + "protocol_version", + "evidence_tier", + "live_trading", + "session", + "authority", + "symbols", + "cross_symbol_observed_overlap_seconds", + "gates", + "reason_codes", + "phase_ledger", + "artifact_inventory", + "terminal_marker", + "policy", + }: + raise M8L2VerificationError("session manifest keys differ from the exact schema") + if payload.get("schema_version") != _SESSION_SCHEMA_VERSION: + raise M8L2VerificationError("unsupported live-L2 session manifest schema") + if payload.get("artifact_kind") != "m8_prospective_live_l2_session": + raise M8L2VerificationError("session artifact kind is invalid") + status = payload.get("status") + if status not in {"COMPLETE", "INSUFFICIENT_DATA"}: + raise M8L2VerificationError("session manifest has an unsupported status") + expected_marker = _COMPLETE_MARKER if status == "COMPLETE" else _INSUFFICIENT_MARKER + if marker_path.name != expected_marker: + raise M8L2VerificationError("terminal marker disagrees with session status") + session_id = payload.get("session_id") + if type(session_id) is not str or not _is_lower_sha256(session_id): + raise M8L2VerificationError("session manifest has an invalid session_id") + authority = _manifest_object(payload.get("authority"), "session authority") + if set(authority) != { + "campaign_authority_sha256", + "config_sha256", + "config_source_sha256", + "protocol_sha256", + "protocol_freeze_commit", + "runtime_commit", + "runtime_source_tree_sha256", + "runtime_dirty", + "runtime_fingerprint", + "runtime_fingerprint_sha256", + }: + raise M8L2VerificationError("session authority keys differ from the exact schema") + config_path = root / "authority" / "m8_l2_capture_study.toml" + protocol_path = root / "authority" / "M8_L2_PROTOCOL.md" + campaign_path = root / "authority" / _CAMPAIGN_AUTHORITY_NAME + try: + bundled_config = load_m8_l2_config(config_path) + except (OSError, ValueError) as error: + raise M8L2VerificationError("bundled live-L2 config is not the frozen authority") from error + if authority.get("config_source_sha256") != M8_L2_CONFIG_SOURCE_SHA256: + raise M8L2VerificationError("session config bytes are not the frozen authority") + if authority.get("config_sha256") != bundled_config.hash: + raise M8L2VerificationError("session config semantic hash differs from bundled bytes") + if authority.get("protocol_sha256") != M8_L2_PROTOCOL_SHA256: + raise M8L2VerificationError("session protocol bytes are not the frozen authority") + if authority.get("protocol_freeze_commit") != M8_L2_FREEZE_COMMIT: + raise M8L2VerificationError("session freeze commit is not the declared authority") + source = CaptureSourceIdentity( + commit=str(authority.get("runtime_commit")), + source_tree_sha256=str(authority.get("runtime_source_tree_sha256")), + dirty=authority.get("runtime_dirty") is not False, + ) + try: + _validate_source_identity(source) + except M8L2CaptureSystemError as error: + raise M8L2VerificationError(f"invalid runtime source identity: {error}") from error + campaign_sha256 = authority.get("campaign_authority_sha256") + if type(campaign_sha256) is not str or not _is_lower_sha256(campaign_sha256): + raise M8L2VerificationError("session campaign authority digest is invalid") + try: + bundled_campaign = _verify_bundled_campaign_authority( + campaign_path, + config=bundled_config, + source=source, + expected_sha256=campaign_sha256, + ) + except M8L2CaptureSystemError as error: + raise M8L2VerificationError(f"invalid bundled campaign authority: {error}") from error + try: + manifest_runtime = _runtime_from_recorded( + authority.get("runtime_fingerprint"), + authority.get("runtime_fingerprint_sha256"), + ) + except M8L2CaptureSystemError as error: + raise M8L2VerificationError(f"invalid session runtime fingerprint: {error}") from error + if manifest_runtime != bundled_campaign.runtime: + raise M8L2VerificationError( + "session runtime fingerprint differs from bundled campaign authority" + ) + campaign_relative = f"authority/{_CAMPAIGN_AUTHORITY_NAME}" + if checksums.get(campaign_relative) != campaign_sha256: + raise M8L2VerificationError( + "session checksum authority does not bind the campaign authority digest" + ) + if sha256_file(config_path) != M8_L2_CONFIG_SOURCE_SHA256: + raise M8L2VerificationError("bundled live-L2 config bytes are corrupt") + if sha256_file(protocol_path) != M8_L2_PROTOCOL_SHA256: + raise M8L2VerificationError("bundled live-L2 protocol bytes are corrupt") + if expected_config is not None: + try: + expected_canonical = load_m8_l2_config(expected_config.path) + except (OSError, ValueError) as error: + raise M8L2VerificationError("caller config is not backed by frozen bytes") from error + if expected_canonical != expected_config: + raise M8L2VerificationError("caller config object differs from its frozen bytes") + if ( + expected_config.source_sha256 != bundled_config.source_sha256 + or expected_config.hash != bundled_config.hash + ): + raise M8L2VerificationError("caller config semantics differ from the session authority") + if ( + payload.get("study_name") != bundled_config.study.name + or payload.get("protocol_version") != bundled_config.study.protocol_version + or payload.get("evidence_tier") != bundled_config.study.evidence_tier + or payload.get("live_trading") is not False + ): + raise M8L2VerificationError("session study claims differ from frozen configuration") + + inventory_raw = payload.get("artifact_inventory") + if not isinstance(inventory_raw, list): + raise M8L2VerificationError("session artifact inventory must be an array") + inventory: dict[str, tuple[str, int]] = {} + for index, item in enumerate(inventory_raw): + entry = _manifest_object(item, f"artifact_inventory[{index}]") + if set(entry) != {"path", "sha256", "bytes"}: + raise M8L2VerificationError("session artifact inventory entry is not exact") + relative = _safe_checksum_relative(str(entry.get("path"))) + digest = str(entry.get("sha256")) + size = entry.get("bytes") + if not _is_lower_sha256(digest) or isinstance(size, bool) or not isinstance(size, int): + raise M8L2VerificationError("session artifact inventory entry is malformed") + if relative in inventory: + raise M8L2VerificationError(f"session artifact inventory repeats {relative}") + inventory[relative] = (digest, size) + if list(inventory) != sorted(inventory): + raise M8L2VerificationError("session artifact inventory is not canonically ordered") + expected_inventory = set(checksums) - {"session_manifest.json"} + if set(inventory) != expected_inventory: + raise M8L2VerificationError("manifest artifact inventory is not exact") + for relative, (digest, size) in inventory.items(): + path = root / relative + if checksums.get(relative) != digest or path.stat().st_size != size: + raise M8L2VerificationError(f"manifest inventory metadata differs for {relative}") + + reasons_raw = payload.get("reason_codes") + if not isinstance(reasons_raw, list) or not all(type(item) is str for item in reasons_raw): + raise M8L2VerificationError("session reason_codes must be a string array") + reasons = tuple(cast(list[str], reasons_raw)) + if list(reasons) != sorted(set(reasons)): + raise M8L2VerificationError("session reason codes are not canonical") + + session_payload = _manifest_object(payload.get("session"), "session coordinates") + if set(session_payload) != { + "date", + "role", + "scheduled_start_ns", + "scheduled_end_ns", + "scheduled_duration_seconds", + "barrier_released_ns", + "barrier_lateness_ns", + "capture_finished_ns", + }: + raise M8L2VerificationError("session coordinate keys differ from the exact schema") + session_date = session_payload.get("date") + role = session_payload.get("role") + if type(session_date) is not str or type(role) is not str: + raise M8L2VerificationError("session date/role coordinates are invalid") + try: + frozen_session = bundled_config.session_for_date(session_date) + except ValueError as error: + raise M8L2VerificationError("session date is not in the frozen calendar") from error + expected_session_coordinates = { + "date": frozen_session.date.isoformat(), + "role": frozen_session.role, + "scheduled_start_ns": frozen_session.start_ns, + "scheduled_end_ns": frozen_session.end_ns, + "scheduled_duration_seconds": (frozen_session.end_ns - frozen_session.start_ns) + / _NANOSECONDS_PER_SECOND, + } + for name, expected_value in expected_session_coordinates.items(): + if session_payload.get(name) != expected_value: + raise M8L2VerificationError(f"session coordinate {name} differs from the freeze") + capture_finished = session_payload.get("capture_finished_ns") + if capture_finished is not None and type(capture_finished) is not int: + raise M8L2VerificationError("session capture_finished_ns is invalid") + + recomputed_session_id = _session_identity( + config=bundled_config, + session=frozen_session, + source=source, + campaign_authority_sha256=campaign_sha256, + ) + if session_id != recomputed_session_id: + raise M8L2VerificationError("session_id does not derive from the frozen authority") + expected_name = f"{frozen_session.date.isoformat()}-{frozen_session.role}-{session_id[:20]}" + if root.name != expected_name: + raise M8L2VerificationError("session bundle basename differs from its authority") + + symbols_raw = _manifest_object(payload.get("symbols"), "session symbols") + if set(symbols_raw) != set(bundled_config.study.symbols) and not ( + not symbols_raw and reasons == ("MISSED_WINDOW",) + ): + raise M8L2VerificationError("session symbols differ from the exact frozen pair") + results: dict[str, SymbolCaptureResult] = {} + for symbol in bundled_config.study.symbols: + if symbol in symbols_raw: + results[symbol] = _symbol_result_from_manifest( + symbols_raw[symbol], symbol=symbol, root=root, session=frozen_session + ) + + gates_raw = payload.get("gates") + if not isinstance(gates_raw, list) or not all(isinstance(item, Mapping) for item in gates_raw): + raise M8L2VerificationError("session gates must be an array of objects") + if reasons == ("MISSED_WINDOW",): + if status != "INSUFFICIENT_DATA" or results or gates_raw: + raise M8L2VerificationError("missed-window terminal evidence is inconsistent") + overlap_ns = 0 + else: + if set(results) != set(bundled_config.study.symbols): + raise M8L2VerificationError("non-missed session lacks the exact frozen symbol pair") + expected_gates, expected_reasons, overlap_ns = _evaluate_gates( + results, config=bundled_config + ) + if len(expected_gates) != 29 or [dict(item) for item in gates_raw] != expected_gates: + raise M8L2VerificationError("session gates are not the exact 29 recomputed gates") + if list(reasons) != expected_reasons: + raise M8L2VerificationError("session reasons differ from recomputed gate failures") + expected_status = "COMPLETE" if not expected_reasons else "INSUFFICIENT_DATA" + if status != expected_status: + raise M8L2VerificationError("session status differs from recomputed gates") + if payload.get("cross_symbol_observed_overlap_seconds") != ( + overlap_ns / _NANOSECONDS_PER_SECOND + ): + raise M8L2VerificationError("cross-symbol overlap differs from recomputed intervals") + if status == "COMPLETE" and ( + type(capture_finished) is not int or capture_finished < frozen_session.end_ns + ): + raise M8L2VerificationError("complete session was finalized before scheduled end") + terminal_marker = _manifest_object(payload.get("terminal_marker"), "terminal marker claim") + if terminal_marker != { + "path": expected_marker, + "bytes": "complete\\n" if status == "COMPLETE" else "terminal\\n", + }: + raise M8L2VerificationError("terminal marker claim differs from exact bytes") + return M8L2SessionBundle( + root=root, + status=cast(SessionStatus, status), + session_id=session_id, + session_date=session_date, + role=role, + manifest_path=manifest_path, + manifest_sha256=checksums["session_manifest.json"], + checksum_path=checksum_path, + marker_path=marker_path, + reason_codes=reasons, + ) + + +__all__ = [ + "CaptureClock", + "CaptureOne", + "CaptureSourceIdentity", + "CapturedArtifact", + "M8L2CaptureError", + "M8L2CaptureSystemError", + "M8L2DataFailure", + "M8L2SessionBundle", + "M8L2VerificationError", + "ObservedInterval", + "SymbolCaptureResult", + "capture_m8_l2_session", + "current_m8_l2_runtime_fingerprint_sha256", + "merge_observed_intervals", + "overlapping_observed_coverage_ns", + "verify_m8_l2_session_bundle", +] diff --git a/Microstructure/src/microstructure/m8_l2_config.py b/Microstructure/src/microstructure/m8_l2_config.py new file mode 100644 index 0000000000000000000000000000000000000000..d066561a5ad161cccb5845e87a125f184d886039 --- /dev/null +++ b/Microstructure/src/microstructure/m8_l2_config.py @@ -0,0 +1,644 @@ +"""Fail-closed parser for the frozen prospective M8 live-L2 study.""" + +from __future__ import annotations + +import hashlib +import json +import math +import tomllib +from collections.abc import Mapping +from dataclasses import dataclass +from datetime import UTC, date, datetime, time +from pathlib import Path +from typing import Any, Literal, cast + +M8L2SessionRole = Literal["train", "validation", "primary_test", "replication_test"] + +M8_L2_FREEZE_COMMIT = "6db6c8cf81b726069d1833672864e0554976b985" +M8_L2_CONFIG_SOURCE_SHA256 = "b1bf3b4e2820e24e4555bfeb9cb0957f9a0bcdef62039f7d92360e0a97d0dd39" +M8_L2_PROTOCOL_SHA256 = "4c77a2099a4cabd049d10e0f8264d3b4c66704d8e87cbaf0c817fd085f4bbd83" + +_TOP_LEVEL_KEYS = frozenset( + {"study", "sessions", "capture", "features", "models", "execution", "claims"} +) +_STUDY_KEYS = frozenset( + { + "name", + "protocol_version", + "evidence_tier", + "seed", + "source", + "symbols", + "stream_interval_ms", + } +) +_SESSION_KEYS = frozenset({"date", "start_utc", "end_utc", "role"}) +_CAPTURE_KEYS = frozenset( + { + "duration_seconds", + "max_messages_per_symbol", + "max_raw_frame_bytes", + "max_arrow_batch_bytes", + "min_overlapping_coverage_seconds", + "min_single_continuity_epoch_seconds", + "require_complete_status", + "require_live_reconstruction", + "max_sequence_gaps", + "max_quality_errors", + "max_quality_warnings", + } +) +_FEATURE_KEYS = frozenset( + { + "depth_levels", + "event_horizons", + "clock_horizons_ms", + "include_spread", + "include_depth", + "include_ofi", + "include_queue_imbalance", + "include_microprice", + "include_cancellation_intensity", + "include_realized_volatility", + "include_reference_fit_regimes", + } +) +_MODEL_KEYS = frozenset( + { + "selection_metric", + "logistic_c_values", + "tree_max_depth_values", + "tree_min_samples_leaf", + "calibration_fraction", + "bootstrap_samples", + } +) +_EXECUTION_KEYS = frozenset( + { + "market_orders_only", + "taker_fee_bps", + "decision_latency_events", + "order_latency_events", + "liquidate_at_end", + "allow_limit_fill_claim", + "allow_capacity_claim", + } +) +_CLAIM_KEYS = frozenset( + { + "allow_p_values", + "allow_significance_claim", + "allow_realized_execution_claim", + "allow_profitability_claim", + } +) + +_FROZEN_SESSIONS: tuple[tuple[str, str, str, M8L2SessionRole], ...] = ( + ("2026-08-10", "14:00:00", "15:00:00", "train"), + ("2026-08-11", "14:00:00", "15:00:00", "validation"), + ("2026-08-12", "14:00:00", "15:00:00", "primary_test"), + ("2026-08-13", "14:00:00", "15:00:00", "replication_test"), +) + + +class M8L2ConfigError(ValueError): + """Raised when the live-L2 configuration differs from its frozen contract.""" + + +@dataclass(frozen=True, slots=True) +class M8L2Study: + name: str + protocol_version: str + evidence_tier: str + seed: int + source: str + symbols: tuple[str, ...] + stream_interval_ms: int + + +@dataclass(frozen=True, slots=True) +class M8L2Session: + date: date + start_utc: time + end_utc: time + role: M8L2SessionRole + + @property + def start(self) -> datetime: + return datetime.combine(self.date, self.start_utc, tzinfo=UTC) + + @property + def end(self) -> datetime: + return datetime.combine(self.date, self.end_utc, tzinfo=UTC) + + @property + def start_ns(self) -> int: + return int(self.start.timestamp()) * 1_000_000_000 + + @property + def end_ns(self) -> int: + return int(self.end.timestamp()) * 1_000_000_000 + + +@dataclass(frozen=True, slots=True) +class M8L2CaptureLimits: + duration_seconds: int + max_messages_per_symbol: int + max_raw_frame_bytes: int + max_arrow_batch_bytes: int + min_overlapping_coverage_seconds: int + min_single_continuity_epoch_seconds: int + require_complete_status: bool + require_live_reconstruction: bool + max_sequence_gaps: int + max_quality_errors: int + max_quality_warnings: int + + +@dataclass(frozen=True, slots=True) +class M8L2Features: + depth_levels: tuple[int, ...] + event_horizons: tuple[int, ...] + clock_horizons_ms: tuple[int, ...] + include_spread: bool + include_depth: bool + include_ofi: bool + include_queue_imbalance: bool + include_microprice: bool + include_cancellation_intensity: bool + include_realized_volatility: bool + include_reference_fit_regimes: bool + + +@dataclass(frozen=True, slots=True) +class M8L2Models: + selection_metric: str + logistic_c_values: tuple[float, ...] + tree_max_depth_values: tuple[int, ...] + tree_min_samples_leaf: int + calibration_fraction: float + bootstrap_samples: int + + +@dataclass(frozen=True, slots=True) +class M8L2Execution: + market_orders_only: bool + taker_fee_bps: float + decision_latency_events: tuple[int, ...] + order_latency_events: tuple[int, ...] + liquidate_at_end: bool + allow_limit_fill_claim: bool + allow_capacity_claim: bool + + +@dataclass(frozen=True, slots=True) +class M8L2Claims: + allow_p_values: bool + allow_significance_claim: bool + allow_realized_execution_claim: bool + allow_profitability_claim: bool + + +@dataclass(frozen=True, slots=True) +class M8L2StudyConfig: + path: Path + source_sha256: str + study: M8L2Study + sessions: tuple[M8L2Session, ...] + capture: M8L2CaptureLimits + features: M8L2Features + models: M8L2Models + execution: M8L2Execution + claims: M8L2Claims + + def _semantic_payload(self) -> dict[str, object]: + return { + "study": { + "name": self.study.name, + "protocol_version": self.study.protocol_version, + "evidence_tier": self.study.evidence_tier, + "seed": self.study.seed, + "source": self.study.source, + "symbols": list(self.study.symbols), + "stream_interval_ms": self.study.stream_interval_ms, + }, + "sessions": [ + { + "date": item.date.isoformat(), + "start_utc": item.start_utc.isoformat(), + "end_utc": item.end_utc.isoformat(), + "role": item.role, + } + for item in self.sessions + ], + "capture": { + name: getattr(self.capture, name) for name in self.capture.__dataclass_fields__ + }, + "features": { + "depth_levels": list(self.features.depth_levels), + "event_horizons": list(self.features.event_horizons), + "clock_horizons_ms": list(self.features.clock_horizons_ms), + **{ + name: getattr(self.features, name) + for name in self.features.__dataclass_fields__ + if name.startswith("include_") + }, + }, + "models": { + "selection_metric": self.models.selection_metric, + "logistic_c_values": list(self.models.logistic_c_values), + "tree_max_depth_values": list(self.models.tree_max_depth_values), + "tree_min_samples_leaf": self.models.tree_min_samples_leaf, + "calibration_fraction": self.models.calibration_fraction, + "bootstrap_samples": self.models.bootstrap_samples, + }, + "execution": { + "market_orders_only": self.execution.market_orders_only, + "taker_fee_bps": self.execution.taker_fee_bps, + "decision_latency_events": list(self.execution.decision_latency_events), + "order_latency_events": list(self.execution.order_latency_events), + "liquidate_at_end": self.execution.liquidate_at_end, + "allow_limit_fill_claim": self.execution.allow_limit_fill_claim, + "allow_capacity_claim": self.execution.allow_capacity_claim, + }, + "claims": { + name: getattr(self.claims, name) for name in self.claims.__dataclass_fields__ + }, + } + + @property + def hash(self) -> str: + encoded = json.dumps( + self._semantic_payload(), sort_keys=True, separators=(",", ":"), allow_nan=False + ).encode() + return hashlib.sha256(encoded).hexdigest() + + def public_dict(self) -> dict[str, object]: + return { + "path": str(self.path), + "config_sha256": self.hash, + "source_sha256": self.source_sha256, + **self._semantic_payload(), + } + + def session_for_date(self, value: str | date) -> M8L2Session: + requested = date.fromisoformat(value) if isinstance(value, str) else value + matches = [item for item in self.sessions if item.date == requested] + if len(matches) != 1: + raise M8L2ConfigError(f"date is not a frozen live-L2 session: {requested.isoformat()}") + return matches[0] + + +def _mapping(value: object, label: str) -> Mapping[str, Any]: + if not isinstance(value, Mapping) or not all(type(key) is str for key in value): + raise M8L2ConfigError(f"{label} must be a TOML table with string keys") + return cast(Mapping[str, Any], value) + + +def _exact_keys(value: Mapping[str, Any], expected: frozenset[str], label: str) -> None: + observed = frozenset(value) + if observed != expected: + raise M8L2ConfigError( + f"{label} keys differ (missing={sorted(expected - observed)}, " + f"unknown={sorted(observed - expected)})" + ) + + +def _list(value: object, label: str) -> list[Any]: + if not isinstance(value, list): + raise M8L2ConfigError(f"{label} must be an array") + return value + + +def _text(value: object, label: str) -> str: + if type(value) is not str: + raise M8L2ConfigError(f"{label} must be a string") + return value + + +def _integer(value: object, label: str) -> int: + if type(value) is not int: + raise M8L2ConfigError(f"{label} must be an integer") + return value + + +def _number(value: object, label: str) -> float: + if type(value) not in {int, float}: + raise M8L2ConfigError(f"{label} must be a finite number") + result = float(cast(int | float, value)) + if not math.isfinite(result): + raise M8L2ConfigError(f"{label} must be a finite number") + return result + + +def _boolean(value: object, label: str) -> bool: + if type(value) is not bool: + raise M8L2ConfigError(f"{label} must be a boolean") + return value + + +def _int_tuple(value: object, label: str) -> tuple[int, ...]: + return tuple( + _integer(item, f"{label}[{index}]") for index, item in enumerate(_list(value, label)) + ) + + +def _number_tuple(value: object, label: str) -> tuple[float, ...]: + return tuple( + _number(item, f"{label}[{index}]") for index, item in enumerate(_list(value, label)) + ) + + +def _text_tuple(value: object, label: str) -> tuple[str, ...]: + return tuple(_text(item, f"{label}[{index}]") for index, item in enumerate(_list(value, label))) + + +def _frozen(observed: object, expected: object, label: str) -> None: + if observed != expected: + raise M8L2ConfigError(f"{label} is frozen at {expected!r}, observed {observed!r}") + + +def _parse_clock(value: object, label: str) -> time: + raw = _text(value, label) + try: + parsed = time.fromisoformat(raw) + except ValueError as error: + raise M8L2ConfigError(f"{label} must use HH:MM:SS") from error + if parsed.tzinfo is not None or parsed.microsecond or parsed.isoformat() != raw: + raise M8L2ConfigError(f"{label} must use canonical UTC HH:MM:SS") + return parsed + + +def _parse_study(raw: object) -> M8L2Study: + table = _mapping(raw, "study") + _exact_keys(table, _STUDY_KEYS, "study") + result = M8L2Study( + name=_text(table["name"], "study.name"), + protocol_version=_text(table["protocol_version"], "study.protocol_version"), + evidence_tier=_text(table["evidence_tier"], "study.evidence_tier"), + seed=_integer(table["seed"], "study.seed"), + source=_text(table["source"], "study.source"), + symbols=tuple(item.upper() for item in _text_tuple(table["symbols"], "study.symbols")), + stream_interval_ms=_integer(table["stream_interval_ms"], "study.stream_interval_ms"), + ) + expected: dict[str, object] = { + "name": "binance-m8-live-l2-study-v2", + "protocol_version": "2.0.0", + "evidence_tier": "FULL_DATA", + "seed": 20260807, + "source": "binance_spot_live_diff_depth_100ms", + "symbols": ("BTCUSDT", "ETHUSDT"), + "stream_interval_ms": 100, + } + for name, value in expected.items(): + _frozen(getattr(result, name), value, f"study.{name}") + return result + + +def _parse_sessions(raw: object) -> tuple[M8L2Session, ...]: + result: list[M8L2Session] = [] + for index, item in enumerate(_list(raw, "sessions")): + table = _mapping(item, f"sessions[{index}]") + _exact_keys(table, _SESSION_KEYS, f"sessions[{index}]") + raw_date = _text(table["date"], f"sessions[{index}].date") + try: + parsed_date = date.fromisoformat(raw_date) + except ValueError as error: + raise M8L2ConfigError(f"sessions[{index}].date must use YYYY-MM-DD") from error + if parsed_date.isoformat() != raw_date: + raise M8L2ConfigError(f"sessions[{index}].date must use canonical YYYY-MM-DD") + role = _text(table["role"], f"sessions[{index}].role") + if role not in {"train", "validation", "primary_test", "replication_test"}: + raise M8L2ConfigError(f"sessions[{index}].role is unsupported") + session = M8L2Session( + date=parsed_date, + start_utc=_parse_clock(table["start_utc"], f"sessions[{index}].start_utc"), + end_utc=_parse_clock(table["end_utc"], f"sessions[{index}].end_utc"), + role=cast(M8L2SessionRole, role), + ) + if session.end <= session.start: + raise M8L2ConfigError(f"sessions[{index}] end must be after start on the same UTC date") + result.append(session) + observed = tuple( + (item.date.isoformat(), item.start_utc.isoformat(), item.end_utc.isoformat(), item.role) + for item in result + ) + _frozen(observed, _FROZEN_SESSIONS, "session calendar/order") + return tuple(result) + + +def _parse_capture(raw: object) -> M8L2CaptureLimits: + table = _mapping(raw, "capture") + _exact_keys(table, _CAPTURE_KEYS, "capture") + result = M8L2CaptureLimits( + duration_seconds=_integer(table["duration_seconds"], "capture.duration_seconds"), + max_messages_per_symbol=_integer( + table["max_messages_per_symbol"], "capture.max_messages_per_symbol" + ), + max_raw_frame_bytes=_integer(table["max_raw_frame_bytes"], "capture.max_raw_frame_bytes"), + max_arrow_batch_bytes=_integer( + table["max_arrow_batch_bytes"], "capture.max_arrow_batch_bytes" + ), + min_overlapping_coverage_seconds=_integer( + table["min_overlapping_coverage_seconds"], + "capture.min_overlapping_coverage_seconds", + ), + min_single_continuity_epoch_seconds=_integer( + table["min_single_continuity_epoch_seconds"], + "capture.min_single_continuity_epoch_seconds", + ), + require_complete_status=_boolean( + table["require_complete_status"], "capture.require_complete_status" + ), + require_live_reconstruction=_boolean( + table["require_live_reconstruction"], "capture.require_live_reconstruction" + ), + max_sequence_gaps=_integer(table["max_sequence_gaps"], "capture.max_sequence_gaps"), + max_quality_errors=_integer(table["max_quality_errors"], "capture.max_quality_errors"), + max_quality_warnings=_integer( + table["max_quality_warnings"], "capture.max_quality_warnings" + ), + ) + expected = M8L2CaptureLimits( + duration_seconds=3600, + max_messages_per_symbol=60000, + max_raw_frame_bytes=1048576, + max_arrow_batch_bytes=16777216, + min_overlapping_coverage_seconds=3300, + min_single_continuity_epoch_seconds=1800, + require_complete_status=True, + require_live_reconstruction=True, + max_sequence_gaps=0, + max_quality_errors=0, + max_quality_warnings=0, + ) + _frozen(result, expected, "capture contract") + return result + + +def _parse_features(raw: object) -> M8L2Features: + table = _mapping(raw, "features") + _exact_keys(table, _FEATURE_KEYS, "features") + result = M8L2Features( + depth_levels=_int_tuple(table["depth_levels"], "features.depth_levels"), + event_horizons=_int_tuple(table["event_horizons"], "features.event_horizons"), + clock_horizons_ms=_int_tuple(table["clock_horizons_ms"], "features.clock_horizons_ms"), + include_spread=_boolean(table["include_spread"], "features.include_spread"), + include_depth=_boolean(table["include_depth"], "features.include_depth"), + include_ofi=_boolean(table["include_ofi"], "features.include_ofi"), + include_queue_imbalance=_boolean( + table["include_queue_imbalance"], "features.include_queue_imbalance" + ), + include_microprice=_boolean(table["include_microprice"], "features.include_microprice"), + include_cancellation_intensity=_boolean( + table["include_cancellation_intensity"], "features.include_cancellation_intensity" + ), + include_realized_volatility=_boolean( + table["include_realized_volatility"], "features.include_realized_volatility" + ), + include_reference_fit_regimes=_boolean( + table["include_reference_fit_regimes"], "features.include_reference_fit_regimes" + ), + ) + expected = M8L2Features( + depth_levels=(1, 5, 10), + event_horizons=(20, 100), + clock_horizons_ms=(1000, 5000), + include_spread=True, + include_depth=True, + include_ofi=True, + include_queue_imbalance=True, + include_microprice=True, + include_cancellation_intensity=True, + include_realized_volatility=True, + include_reference_fit_regimes=True, + ) + _frozen(result, expected, "features contract") + return result + + +def _parse_models(raw: object) -> M8L2Models: + table = _mapping(raw, "models") + _exact_keys(table, _MODEL_KEYS, "models") + result = M8L2Models( + selection_metric=_text(table["selection_metric"], "models.selection_metric"), + logistic_c_values=_number_tuple(table["logistic_c_values"], "models.logistic_c_values"), + tree_max_depth_values=_int_tuple( + table["tree_max_depth_values"], "models.tree_max_depth_values" + ), + tree_min_samples_leaf=_integer( + table["tree_min_samples_leaf"], "models.tree_min_samples_leaf" + ), + calibration_fraction=_number(table["calibration_fraction"], "models.calibration_fraction"), + bootstrap_samples=_integer(table["bootstrap_samples"], "models.bootstrap_samples"), + ) + expected = M8L2Models( + selection_metric="log_loss", + logistic_c_values=(0.1, 1.0, 10.0), + tree_max_depth_values=(2, 4, 6), + tree_min_samples_leaf=40, + calibration_fraction=0.20, + bootstrap_samples=2000, + ) + _frozen(result, expected, "models contract") + return result + + +def _parse_execution(raw: object) -> M8L2Execution: + table = _mapping(raw, "execution") + _exact_keys(table, _EXECUTION_KEYS, "execution") + result = M8L2Execution( + market_orders_only=_boolean(table["market_orders_only"], "execution.market_orders_only"), + taker_fee_bps=_number(table["taker_fee_bps"], "execution.taker_fee_bps"), + decision_latency_events=_int_tuple( + table["decision_latency_events"], "execution.decision_latency_events" + ), + order_latency_events=_int_tuple( + table["order_latency_events"], "execution.order_latency_events" + ), + liquidate_at_end=_boolean(table["liquidate_at_end"], "execution.liquidate_at_end"), + allow_limit_fill_claim=_boolean( + table["allow_limit_fill_claim"], "execution.allow_limit_fill_claim" + ), + allow_capacity_claim=_boolean( + table["allow_capacity_claim"], "execution.allow_capacity_claim" + ), + ) + expected = M8L2Execution( + market_orders_only=True, + taker_fee_bps=4.0, + decision_latency_events=(0, 1, 5), + order_latency_events=(0, 1, 5), + liquidate_at_end=True, + allow_limit_fill_claim=False, + allow_capacity_claim=False, + ) + _frozen(result, expected, "execution contract") + return result + + +def _parse_claims(raw: object) -> M8L2Claims: + table = _mapping(raw, "claims") + _exact_keys(table, _CLAIM_KEYS, "claims") + result = M8L2Claims( + allow_p_values=_boolean(table["allow_p_values"], "claims.allow_p_values"), + allow_significance_claim=_boolean( + table["allow_significance_claim"], "claims.allow_significance_claim" + ), + allow_realized_execution_claim=_boolean( + table["allow_realized_execution_claim"], "claims.allow_realized_execution_claim" + ), + allow_profitability_claim=_boolean( + table["allow_profitability_claim"], "claims.allow_profitability_claim" + ), + ) + _frozen(result, M8L2Claims(False, False, False, False), "claims contract") + return result + + +def load_m8_l2_config(path: str | Path) -> M8L2StudyConfig: + """Load the exact outcome-blind protocol-v1.0.0 live-L2 configuration.""" + + config_path = Path(path).resolve() + source = config_path.read_bytes() + try: + raw = tomllib.loads(source.decode("utf-8")) + except (UnicodeDecodeError, tomllib.TOMLDecodeError) as error: + raise M8L2ConfigError(f"cannot parse M8 live-L2 TOML: {error}") from error + root = _mapping(raw, "configuration") + _exact_keys(root, _TOP_LEVEL_KEYS, "configuration") + result = M8L2StudyConfig( + path=config_path, + source_sha256=hashlib.sha256(source).hexdigest(), + study=_parse_study(root["study"]), + sessions=_parse_sessions(root["sessions"]), + capture=_parse_capture(root["capture"]), + features=_parse_features(root["features"]), + models=_parse_models(root["models"]), + execution=_parse_execution(root["execution"]), + claims=_parse_claims(root["claims"]), + ) + if result.source_sha256 != M8_L2_CONFIG_SOURCE_SHA256: + raise M8L2ConfigError( + "configuration bytes do not match the outcome-blind freeze " + f"{M8_L2_CONFIG_SOURCE_SHA256}" + ) + return result + + +__all__ = [ + "M8_L2_CONFIG_SOURCE_SHA256", + "M8_L2_FREEZE_COMMIT", + "M8_L2_PROTOCOL_SHA256", + "M8L2CaptureLimits", + "M8L2Claims", + "M8L2ConfigError", + "M8L2Execution", + "M8L2Features", + "M8L2Models", + "M8L2Session", + "M8L2SessionRole", + "M8L2Study", + "M8L2StudyConfig", + "load_m8_l2_config", +] diff --git a/Microstructure/src/microstructure/m8_l2_development.py b/Microstructure/src/microstructure/m8_l2_development.py new file mode 100644 index 0000000000000000000000000000000000000000..64d8fcfe7a1d746aa0c09c040ffbd4723ec2eb4b --- /dev/null +++ b/Microstructure/src/microstructure/m8_l2_development.py @@ -0,0 +1,2214 @@ +"""Outcome-blind development authority for the frozen four-session M8 L2 study. + +This module is the only stage allowed to fit L2 regime thresholds, select a +model, or fit final model state. Its public producer accepts exactly the train +and validation session paths. The held-out sessions are represented only by +their predeclared calendar coordinates and cannot be supplied to this API. + +Publication is fail closed. Complete train/validation sessions produce the +eight-child ``LOCKED`` authority. A verified insufficient development session +instead produces a checksummed ``NOT_CREATED`` authority without opening any +economic rows. Both variants reserve without overwrite and write their exact +terminal marker last. Held-out evaluation may restore only ``LOCKED`` state; +it must never call a fit or update API. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import shutil +import stat +from collections.abc import Mapping +from dataclasses import asdict, dataclass +from datetime import UTC, datetime +from pathlib import Path, PurePosixPath +from typing import Any, Literal, Protocol, cast + +import polars as pl +import pyarrow.parquet as pq # type: ignore[import-untyped] + +import microstructure.m8_l2_inputs as _l2_inputs_module +from microstructure.config import ModelConfig +from microstructure.m8_l2_analysis_config import ( + M8L2AnalysisConfig, + M8L2AnalysisEndpoint, + load_m8_l2_analysis_config, +) +from microstructure.m8_l2_capture import ( + M8L2SessionBundle, + current_m8_l2_runtime_fingerprint_sha256, + verify_m8_l2_session_bundle, +) +from microstructure.m8_l2_config import ( + M8_L2_PROTOCOL_SHA256, + M8L2StudyConfig, + load_m8_l2_config, +) +from microstructure.provenance import ( + ImportOriginError, + assert_project_module_origins, + git_source_tree_sha256, + sha256_file, + strict_git_state, +) +from microstructure.research.l2_multidate import ( + L2EndpointSpec, + L2ObservedInterval, + L2RegimeFit, + apply_l2_regimes, + build_l2_endpoint_frames, + fit_l2_regime_thresholds, + l2_model_feature_columns, +) +from microstructure.research.multidate import ( + AnalysisLock, + FinalFittedState, + LockedSelection, + select_multidate_model, +) + +_LOCK_SCHEMA_VERSION = "m8-l2-development-lock-v1" +_NOT_CREATED_SCHEMA_VERSION = "m8-l2-development-not-created-v1" +_CHILD_SCHEMA_VERSION = "m8-l2-development-child-lock-v1" +_REGIME_SCHEMA_VERSION = "m8-l2-regime-thresholds-v1" +_EXECUTION_REFERENCE_SCHEMA_VERSION = "m8-l2-execution-reference-v1" +_INVENTORY_SCHEMA_VERSION = "m8-l2-development-inventory-v1" +_LOCKED_MARKER = "_LOCKED" +_LOCKED_BYTES = b"locked\n" +_NOT_CREATED_MARKER = "_NOT_CREATED" +_NOT_CREATED_BYTES = b"not-created\n" +_CHECKSUMS_NAME = "CHECKSUMS.sha256" +_INVENTORY_NAME = "inventory.json" +_AGGREGATE_NAME = "development_lock.json" +_AGGREGATE_DIGEST_NAME = "development_lock.sha256" +_MAX_JSON_BYTES = 16 * 1024 * 1024 +_MAX_COMPARISON_BYTES = 64 * 1024 * 1024 +_GIB = 1024**3 +# The 16 GiB host envelope is split into disjoint producer workspaces. These +# are admission limits, not telemetry thresholds: metadata/row-count bounds are +# checked before the costly builders and the materialized result is checked +# immediately after every allocation boundary. +_MAX_DEVELOPMENT_RAW_BYTES = 2 * _GIB +_MAX_DEVELOPMENT_CAUSAL_BYTES = 4 * _GIB +_MAX_SELECTION_WORKSPACE_BYTES = 2 * _GIB +_CAUSAL_ENDPOINT_ROW_UPPER_BYTES = 4 * 1024 +_SELECTION_NUMPY_VECTOR_COUNT = 12 +_EXPECTED_DEVELOPMENT = (("2026-08-10", "train"), ("2026-08-11", "validation")) +_EXPECTED_HELDOUT = ( + ("2026-08-12", "primary_test"), + ("2026-08-13", "replication_test"), +) +_EARLIEST_LOCK_TIME = datetime(2026, 8, 11, 15, 0, tzinfo=UTC) +_LOCK_DEADLINE = datetime(2026, 8, 12, 14, 0, tzinfo=UTC) + + +class M8L2DevelopmentError(RuntimeError): + """Raised when development fitting or lock publication must fail closed.""" + + +@dataclass(frozen=True, slots=True) +class ProducerSourceIdentity: + commit: str + source_tree_sha256: str + dirty: bool + + def to_dict(self) -> dict[str, object]: + return asdict(self) + + +@dataclass(frozen=True, slots=True) +class L2DevelopmentChildLock: + symbol: str + endpoint: str + path: Path + sha256: str + selection_lock_sha256: str + fitted_state_sha256: str + + +@dataclass(frozen=True, slots=True) +class L2DevelopmentLockResult: + root: Path + aggregate_path: Path + aggregate_sha256: str + marker_path: Path + created_at_utc: str + children: tuple[L2DevelopmentChildLock, ...] + status: Literal["LOCKED", "NOT_CREATED"] = "LOCKED" + reason_codes: tuple[str, ...] = () + + +# Neutral public name for the LOCKED | NOT_CREATED union. The historical +# alias remains available because the pre-capture CLI already exposes lock- +# named arguments and both variants intentionally share that authority slot. +L2DevelopmentAuthorityResult = L2DevelopmentLockResult + + +class _LoadedSymbolFrames(Protocol): + book_observations: pl.DataFrame + depth_deltas: pl.DataFrame + intervals: tuple[L2ObservedInterval, ...] + + +class _FileAuthority(Protocol): + manifest_sha256: str + checksums_sha256: str + + def to_dict(self) -> dict[str, object]: ... + + +class _ExpectedFileAuthority(Protocol): + @property + def manifest_sha256(self) -> str: ... + + @property + def checksums_sha256(self) -> str: ... + + +class _CampaignIdentity(Protocol): + campaign_authority_sha256: str + runtime_commit: str + runtime_source_tree_sha256: str + runtime_fingerprint_sha256: str + runtime_dirty: bool + + def to_dict(self) -> dict[str, object]: ... + + +class _VerifiedInput(Protocol): + root: Path + session_id: str + session_date: str + role: str + config_sha256: str + config_source_sha256: str + file_authority: _FileAuthority + campaign_identity: _CampaignIdentity + symbols: Mapping[str, object] + access_phase: str + development_lock_sha256: str | None + + def load_symbol_frames(self, symbol: str) -> _LoadedSymbolFrames: ... + + +class L2DevelopmentInputVerifier(Protocol): + def __call__( + self, + bundle_dir: str | Path, + *, + expected_config: M8L2StudyConfig, + expected_date: str, + expected_role: str, + expected_file_authority: object | None = None, + expected_campaign: object | None = None, + ) -> _VerifiedInput: ... + + +def _frame_bytes(frame: pl.DataFrame) -> int: + """Return Polars' owned-buffer estimate as an integer byte count.""" + + return int(frame.estimated_size("b")) + + +def _loaded_bytes(value: _LoadedSymbolFrames) -> int: + # Intervals are tiny fixed dataclasses, but charging one KiB each keeps the + # admission proof conservative even if a malformed authority has many. + return ( + _frame_bytes(value.book_observations) + + _frame_bytes(value.depth_deltas) + + len(value.intervals) * 1024 + ) + + +def _require_memory_budget(observed: int, maximum: int, label: str) -> None: + if observed < 0 or observed > maximum: + raise M8L2DevelopmentError( + f"{label} exceeds the fail-closed memory budget ({observed} > {maximum} bytes)" + ) + + +def _parquet_metadata_bytes(root: Path, artifact: object, label: str) -> tuple[int, int]: + """Read only Parquet metadata, through a no-follow descriptor, before load.""" + + relative = getattr(artifact, "relative_path", None) + claimed_rows = getattr(artifact, "rows", None) + if not isinstance(relative, str) or not isinstance(claimed_rows, int): + raise M8L2DevelopmentError(f"{label} lacks bounded Parquet metadata authority") + safe = _safe_relative(relative) + path = root / safe + flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0) + try: + descriptor = os.open(path, flags) + before = os.fstat(descriptor) + if not stat.S_ISREG(before.st_mode): + raise M8L2DevelopmentError(f"{label} is not a regular Parquet file") + with os.fdopen(descriptor, "rb", closefd=True) as handle: + parquet = pq.ParquetFile(handle) + metadata = parquet.metadata + rows = int(metadata.num_rows) + uncompressed = sum( + int(metadata.row_group(index).total_byte_size) + for index in range(metadata.num_row_groups) + ) + after = os.fstat(handle.fileno()) + if (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns) != ( + after.st_dev, + after.st_ino, + after.st_size, + after.st_mtime_ns, + ): + raise M8L2DevelopmentError(f"{label} changed during memory admission") + except M8L2DevelopmentError: + raise + except (OSError, ValueError, TypeError) as error: + raise M8L2DevelopmentError(f"cannot inspect {label} memory metadata") from error + if rows != claimed_rows or rows < 1 or uncompressed < 1: + raise M8L2DevelopmentError(f"{label} Parquet metadata differs from its authority") + return uncompressed, rows + + +def _preflight_symbol_raw(value: _VerifiedInput, symbol: str) -> tuple[int, int] | None: + """Return (raw bytes, book rows) without opening column payloads. + + Production verifier objects always expose the two verified artifact + descriptors. The ``None`` branch exists only for injected test loaders; + those remain protected by the immediate post-load budget check. + """ + + descriptor = value.symbols.get(symbol) + books = getattr(descriptor, "book_observations", None) + deltas = getattr(descriptor, "depth_deltas", None) + if books is None or deltas is None: + return None + book_bytes, book_rows = _parquet_metadata_bytes( + value.root, books, f"{value.session_date} {symbol} book observations" + ) + delta_bytes, _ = _parquet_metadata_bytes( + value.root, deltas, f"{value.session_date} {symbol} depth deltas" + ) + return book_bytes + delta_bytes, book_rows + + +def _causal_build_upper_bytes(book_rows: int, endpoint_count: int) -> int: + if book_rows < 0 or endpoint_count < 1: + raise M8L2DevelopmentError("invalid row count for causal-memory admission") + return book_rows * endpoint_count * _CAUSAL_ENDPOINT_ROW_UPPER_BYTES + + +def _selection_workspace_upper_bytes( + train: pl.DataFrame, + validation: pl.DataFrame, + *, + feature_count: int, +) -> int: + """Bound selection copies and NumPy arrays before entering the fitter. + + ``select_multidate_model`` materializes a full-width date concat, eligible + filters/splits, and two sets of float64 feature matrices. Four full-width + equivalents plus feature/target/probability vectors is deliberately above + that live set and therefore rejects before NumPy can exceed its 2 GiB slot. + """ + + if feature_count < 1: + raise M8L2DevelopmentError("selection memory admission requires model features") + rows = train.height + validation.height + full_width_copies = 4 * (_frame_bytes(train) + _frame_bytes(validation)) + numpy_bytes = rows * (feature_count * 8 * 2 + _SELECTION_NUMPY_VECTOR_COUNT * 8) + return full_width_copies + numpy_bytes + + +def _utc_now() -> datetime: + return datetime.now(UTC) + + +def _producer_source_identity(project_root: Path) -> ProducerSourceIdentity: + before = strict_git_state(project_root) + source_tree_sha256 = git_source_tree_sha256(project_root) + after = strict_git_state(project_root) + if before != after: + raise M8L2DevelopmentError("Git identity changed during development source snapshot") + return ProducerSourceIdentity( + commit=before.commit, + source_tree_sha256=source_tree_sha256, + dirty=before.dirty, + ) + + +def _load_input_verifier() -> L2DevelopmentInputVerifier: + return cast( + L2DevelopmentInputVerifier, + _l2_inputs_module.verify_m8_l2_development_input, + ) + + +def _assert_development_import_origins(project_root: Path) -> None: + try: + assert_project_module_origins( + project_root, + "microstructure.m8_l2_development", + _l2_inputs_module, + "microstructure.m8_l2_analysis_config", + "microstructure.research.l2_multidate", + "microstructure.research.multidate", + ) + except ImportOriginError as error: + raise M8L2DevelopmentError( + "development producer has a foreign or mixed import origin" + ) from error + + +def _canonical_json_bytes(value: Mapping[str, object]) -> bytes: + try: + return ( + json.dumps( + dict(value), + sort_keys=True, + separators=(",", ":"), + ensure_ascii=True, + allow_nan=False, + ) + + "\n" + ).encode("ascii") + except (TypeError, ValueError) as error: + raise M8L2DevelopmentError("development authority is not canonical finite JSON") from error + + +def _decode_json_bytes(raw: bytes, label: str) -> dict[str, Any]: + def reject_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + raise M8L2DevelopmentError(f"{label} repeats key {key!r}") + result[key] = value + return result + + def reject_constant(value: str) -> object: + raise M8L2DevelopmentError(f"{label} contains forbidden constant {value}") + + try: + decoded = json.loads( + raw, + object_pairs_hook=reject_duplicates, + parse_constant=reject_constant, + ) + except M8L2DevelopmentError: + raise + except (UnicodeDecodeError, json.JSONDecodeError) as error: + raise M8L2DevelopmentError(f"{label} is not valid UTF-8 JSON") from error + if not isinstance(decoded, dict) or not all(type(key) is str for key in decoded): + raise M8L2DevelopmentError(f"{label} must be a JSON object") + return cast(dict[str, Any], decoded) + + +def _safe_relative(value: str) -> str: + candidate = PurePosixPath(value) + if ( + not value + or candidate.is_absolute() + or ".." in candidate.parts + or value != candidate.as_posix() + ): + raise M8L2DevelopmentError(f"unsafe development-lock relative path {value!r}") + return value + + +def _relative(path: Path, root: Path) -> str: + try: + return path.relative_to(root).as_posix() + except ValueError as error: + raise M8L2DevelopmentError("development artifact escapes its lock root") from error + + +def _fsync_directory(path: Path) -> None: + descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + + +def _write_bytes(path: Path, raw: bytes) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL + if hasattr(os, "O_NOFOLLOW"): + flags |= os.O_NOFOLLOW + descriptor = os.open(path, flags, 0o644) + try: + view = memoryview(raw) + while view: + written = os.write(descriptor, view) + if written < 1: + raise OSError("short write while publishing development authority") + view = view[written:] + os.fsync(descriptor) + finally: + os.close(descriptor) + _fsync_directory(path.parent) + + +def _write_json(path: Path, payload: Mapping[str, object]) -> str: + raw = _canonical_json_bytes(payload) + _write_bytes(path, raw) + return hashlib.sha256(raw).hexdigest() + + +def _read_regular(path: Path, *, label: str, maximum: int) -> bytes: + try: + metadata = path.lstat() + except OSError as error: + raise M8L2DevelopmentError(f"cannot stat {label}") from error + if not stat.S_ISREG(metadata.st_mode): + raise M8L2DevelopmentError(f"{label} must be a regular file") + if metadata.st_size > maximum: + raise M8L2DevelopmentError(f"{label} exceeds its bounded verification size") + flags = os.O_RDONLY + if hasattr(os, "O_NOFOLLOW"): + flags |= os.O_NOFOLLOW + descriptor = os.open(path, flags) + try: + opened = os.fstat(descriptor) + if not stat.S_ISREG(opened.st_mode) or (opened.st_dev, opened.st_ino) != ( + metadata.st_dev, + metadata.st_ino, + ): + raise M8L2DevelopmentError(f"{label} changed during verification") + chunks: list[bytes] = [] + remaining = maximum + 1 + while remaining > 0: + chunk = os.read(descriptor, min(1024 * 1024, remaining)) + if not chunk: + break + chunks.append(chunk) + remaining -= len(chunk) + raw = b"".join(chunks) + if len(raw) > maximum: + raise M8L2DevelopmentError(f"{label} exceeds its bounded verification size") + if os.fstat(descriptor).st_size != len(raw): + raise M8L2DevelopmentError(f"{label} changed during verification") + return raw + except OSError as error: + raise M8L2DevelopmentError(f"cannot read {label}") from error + finally: + os.close(descriptor) + + +def _read_json(path: Path, label: str) -> tuple[dict[str, Any], bytes]: + raw = _read_regular(path, label=label, maximum=_MAX_JSON_BYTES) + return _decode_json_bytes(raw, label), raw + + +def _reject_symlink_components(path: Path) -> None: + requested = path.absolute() + current = Path(requested.anchor) + for part in requested.parts[1:]: + current /= part + if not current.exists() and not current.is_symlink(): + continue + if current.is_symlink(): + raise M8L2DevelopmentError(f"development-lock path contains symlink {current}") + + +def _walk_regular(root: Path) -> dict[str, Path]: + result: dict[str, Path] = {} + pending = [root] + while pending: + directory = pending.pop() + try: + entries = sorted(os.scandir(directory), key=lambda item: item.name) + except OSError as error: + raise M8L2DevelopmentError("cannot enumerate development-lock inventory") from error + for entry in entries: + path = Path(entry.path) + relative = _relative(path, root) + if entry.is_symlink(): + raise M8L2DevelopmentError( + f"development-lock inventory contains symlink {relative}" + ) + if entry.is_dir(follow_symlinks=False): + pending.append(path) + elif entry.is_file(follow_symlinks=False): + result[relative] = path + else: + raise M8L2DevelopmentError( + f"development-lock inventory contains non-regular entry {relative}" + ) + return dict(sorted(result.items())) + + +def _validate_source(identity: ProducerSourceIdentity) -> None: + if identity.dirty: + raise M8L2DevelopmentError("L2 development locking requires a clean Git source tree") + if len(identity.commit) != 40 or any( + char not in "0123456789abcdef" for char in identity.commit + ): + raise M8L2DevelopmentError("producer Git commit is not a lowercase 40-character SHA-1") + if len(identity.source_tree_sha256) != 64 or any( + char not in "0123456789abcdef" for char in identity.source_tree_sha256 + ): + raise M8L2DevelopmentError("producer source-tree identity is not a lowercase SHA-256") + + +def _revalidate_configs( + capture_config: M8L2StudyConfig, + analysis_config: M8L2AnalysisConfig, +) -> tuple[M8L2StudyConfig, M8L2AnalysisConfig]: + try: + capture = load_m8_l2_config(capture_config.path) + analysis = load_m8_l2_analysis_config(analysis_config.path) + except (OSError, ValueError) as error: + raise M8L2DevelopmentError( + "frozen L2 configuration authority cannot be reloaded" + ) from error + if capture != capture_config or analysis != analysis_config: + raise M8L2DevelopmentError("in-memory L2 configuration differs from exact frozen bytes") + if ( + analysis.study.capture_config_source_sha256 != capture.source_sha256 + or analysis.study.capture_protocol_sha256 != M8_L2_PROTOCOL_SHA256 + or analysis.study.symbols != capture.study.symbols + or analysis.study.seed != capture.study.seed + ): + raise M8L2DevelopmentError("capture and analysis contracts do not share one frozen study") + coordinates = tuple((item.date.isoformat(), item.role) for item in capture.sessions) + if coordinates != (*_EXPECTED_DEVELOPMENT, *_EXPECTED_HELDOUT): + raise M8L2DevelopmentError("capture calendar differs from the frozen four-session study") + if ( + analysis.study.training_role != "train" + or analysis.study.selection_role != "validation" + or analysis.study.primary_endpoint_role != "primary_test" + or analysis.study.replication_endpoint_role != "replication_test" + ): + raise M8L2DevelopmentError("analysis roles differ from the frozen four-session study") + return capture, analysis + + +def _campaign_dict(value: _CampaignIdentity) -> dict[str, object]: + payload = value.to_dict() + expected = { + "campaign_authority_sha256", + "runtime_commit", + "runtime_source_tree_sha256", + "runtime_fingerprint_sha256", + "runtime_dirty", + } + if set(payload) != expected: + raise M8L2DevelopmentError("development input campaign identity is malformed") + return payload + + +def _campaign_from_session_bundle(bundle: M8L2SessionBundle) -> _CampaignIdentity: + manifest, raw = _read_json(bundle.manifest_path, "development session manifest") + if hashlib.sha256(raw).hexdigest() != bundle.manifest_sha256: + raise M8L2DevelopmentError("development session manifest authority changed") + authority = manifest.get("authority") + if not isinstance(authority, Mapping): + raise M8L2DevelopmentError("development session campaign authority is malformed") + try: + value = _l2_inputs_module.L2CampaignRuntimeIdentity( + campaign_authority_sha256=str(authority["campaign_authority_sha256"]), + runtime_commit=str(authority["runtime_commit"]), + runtime_source_tree_sha256=str(authority["runtime_source_tree_sha256"]), + runtime_fingerprint_sha256=str(authority["runtime_fingerprint_sha256"]), + runtime_dirty=authority.get("runtime_dirty") is not False, + ) + except (KeyError, TypeError, ValueError) as error: + raise M8L2DevelopmentError("development session campaign authority is malformed") from error + return cast(_CampaignIdentity, value) + + +def _session_file_authority(bundle: M8L2SessionBundle) -> dict[str, object]: + return { + "manifest_sha256": bundle.manifest_sha256, + "checksums_sha256": sha256_file(bundle.checksum_path), + } + + +def _verify_expected_session_file_authorities( + bundles: tuple[M8L2SessionBundle, ...], + expected: Mapping[str, _ExpectedFileAuthority] | None, +) -> None: + """Bind control-only session files to caller-held digests without opening Parquet.""" + + if expected is None: + return + expected_dates = {value[0] for value in _EXPECTED_DEVELOPMENT} + if set(expected) != expected_dates: + raise M8L2DevelopmentError( + "expected development session authority set must contain exactly Aug8 and Aug9" + ) + for bundle in bundles: + authority = expected[bundle.session_date] + if ( + bundle.manifest_sha256 != authority.manifest_sha256 + or sha256_file(bundle.checksum_path) != authority.checksums_sha256 + ): + raise M8L2DevelopmentError(f"caller-held {bundle.role} session file authority changed") + + +def _development_session_claim(bundle: M8L2SessionBundle) -> dict[str, object]: + return { + "date": bundle.session_date, + "role": bundle.role, + "status": bundle.status, + "session_id": bundle.session_id, + "file_authority": _session_file_authority(bundle), + "reason_codes": list(bundle.reason_codes), + } + + +def _not_created_reasons( + bundles: tuple[M8L2SessionBundle, M8L2SessionBundle], +) -> tuple[str, ...]: + return tuple( + sorted( + { + f"DEVELOPMENT_SESSION_INSUFFICIENT::{bundle.role}::{reason}" + for bundle in bundles + if bundle.status != "COMPLETE" + for reason in (bundle.reason_codes or ("SESSION_INSUFFICIENT_DATA",)) + } + ) + ) + + +def _file_authority_dict(value: _FileAuthority) -> dict[str, object]: + payload = value.to_dict() + if set(payload) != {"manifest_sha256", "checksums_sha256"}: + raise M8L2DevelopmentError("development input file authority is malformed") + return payload + + +def _verify_input_descriptor( + value: _VerifiedInput, + bundle: M8L2SessionBundle, + *, + capture: M8L2StudyConfig, + expected_date: str, + expected_role: str, +) -> None: + if ( + value.root.absolute() != bundle.root.absolute() + or value.session_id != bundle.session_id + or value.session_date != expected_date + or value.role != expected_role + or value.config_sha256 != capture.hash + or value.config_source_sha256 != capture.source_sha256 + or value.access_phase != "development" + or value.development_lock_sha256 is not None + or tuple(value.symbols) != capture.study.symbols + or value.file_authority.manifest_sha256 != bundle.manifest_sha256 + ): + raise M8L2DevelopmentError("verified development input descriptor changed its authority") + + +def _endpoint_specs(analysis: M8L2AnalysisConfig) -> tuple[L2EndpointSpec, ...]: + result: list[L2EndpointSpec] = [] + windows = set(analysis.features.rolling_windows) + for item in analysis.endpoints: + impact_window = ( + item.horizon_value if item.domain == "event" else item.nominal_event_block_width + ) + if impact_window not in windows: + impact_window = min(windows, key=lambda value: abs(value - impact_window)) + result.append( + L2EndpointSpec( + name=item.name, + domain=item.domain, + horizon_value=item.horizon_value, + horizon_unit=item.unit, + paired_block_events=item.paired_block_width if item.domain == "event" else None, + paired_block_milliseconds=( + item.paired_block_width if item.domain == "clock" else None + ), + impact_ofi_window=impact_window, + ) + ) + return tuple(result) + + +def _model_config(capture: M8L2StudyConfig) -> ModelConfig: + return ModelConfig( + selection_metric=capture.models.selection_metric, + logistic_c_values=capture.models.logistic_c_values, + tree_max_depth_values=capture.models.tree_max_depth_values, + tree_min_samples_leaf=capture.models.tree_min_samples_leaf, + ) + + +def _finite_unique(frame: pl.DataFrame, column: str, label: str) -> float: + if column not in frame.columns: + raise M8L2DevelopmentError(f"execution reference lacks {column}") + values = [float(value) for value in frame.get_column(column).drop_nulls().unique().to_list()] + if len(values) != 1 or not math.isfinite(values[0]) or values[0] <= 0.0: + raise M8L2DevelopmentError(f"{label} must be one consistent positive finite value") + return values[0] + + +def _execution_reference( + symbol: str, + train: pl.DataFrame, + validation: pl.DataFrame, + analysis: M8L2AnalysisConfig, +) -> dict[str, object]: + train_ready = train.filter(pl.col("feature_ready")).drop_nulls( + ["mid_price", "bid_quantity", "ask_quantity", "tick_size", "lot_size"] + ) + validation_ready = validation.filter(pl.col("feature_ready")).drop_nulls( + ["tick_size", "lot_size"] + ) + if train_ready.is_empty() or validation_ready.is_empty(): + raise M8L2DevelopmentError("execution reference requires feature-ready development rows") + tick = _finite_unique(train_ready, "tick_size", "train tick size") + lot = _finite_unique(train_ready, "lot_size", "train lot size") + if ( + _finite_unique(validation_ready, "tick_size", "validation tick size") != tick + or _finite_unique(validation_ready, "lot_size", "validation lot size") != lot + ): + raise M8L2DevelopmentError("tick/lot size changes between development sessions") + midpoint = train_ready.get_column("mid_price").median() + executable_depth = train_ready.select( + pl.min_horizontal("bid_quantity", "ask_quantity").alias("executable_l1_depth") + ) + depth_q05 = executable_depth.get_column("executable_l1_depth").quantile( + 0.05, interpolation="linear" + ) + if not isinstance(midpoint, (int, float)) or not isinstance(depth_q05, (int, float)): + raise M8L2DevelopmentError("execution reference statistics are unavailable") + reference_mid = float(midpoint) + reference_depth = float(depth_q05) + if not math.isfinite(reference_mid) or reference_mid <= 0.0: + raise M8L2DevelopmentError("train median mid price is not positive and finite") + if not math.isfinite(reference_depth) or reference_depth <= 0.0: + raise M8L2DevelopmentError("train q05 executable L1 depth is not positive and finite") + raw_quantity = min( + analysis.execution.order_notional_usd / reference_mid, + analysis.execution.max_l1_participation * reference_depth, + ) + quantity_lots = math.floor(raw_quantity / lot + 1e-12) + reference_quantity = quantity_lots * lot + if quantity_lots < 1 or not math.isfinite(reference_quantity): + raise M8L2DevelopmentError("frozen execution reference rounds below one lot") + return { + "schema_version": _EXECUTION_REFERENCE_SCHEMA_VERSION, + "artifact_kind": "train_only_execution_reference", + "symbol": symbol, + "fit_date": "2026-08-10", + "fit_role": "train", + "reference_price_statistic": analysis.execution.reference_price_statistic, + "reference_depth_statistic": analysis.execution.reference_depth_statistic, + "reference_mid_price": reference_mid, + "reference_l1_depth_q05": reference_depth, + "tick_size": tick, + "lot_size": lot, + "tick_lot_consistency_roles": ["train", "validation"], + "order_notional_usd": analysis.execution.order_notional_usd, + "max_l1_participation": analysis.execution.max_l1_participation, + "unrounded_reference_quantity": raw_quantity, + "reference_quantity_lots": quantity_lots, + "reference_quantity": reference_quantity, + "rounding_policy": "floor_to_whole_lot", + "quantity_policy": analysis.execution.reference_quantity_policy, + "train_feature_ready_rows": train_ready.height, + } + + +def _regime_payload(fitted: L2RegimeFit, analysis: M8L2AnalysisConfig) -> dict[str, object]: + return { + "schema_version": _REGIME_SCHEMA_VERSION, + "artifact_kind": "train_only_l2_regime_thresholds", + "analysis_config_source_sha256": analysis.source_sha256, + **fitted.to_dict(), + } + + +def _endpoint_payload(endpoint: M8L2AnalysisEndpoint) -> dict[str, object]: + return { + "name": endpoint.name, + "domain": endpoint.domain, + "horizon_value": endpoint.horizon_value, + "horizon_unit": endpoint.unit, + "paired_block_width": endpoint.paired_block_width, + "paired_block_unit": endpoint.paired_block_unit, + "nominal_event_block_width": endpoint.nominal_event_block_width, + } + + +def _frame_sha256(frame: pl.DataFrame) -> str: + digest = hashlib.sha256() + schema = [(name, str(dtype)) for name, dtype in frame.schema.items()] + digest.update(json.dumps(schema, separators=(",", ":")).encode()) + row_hashes = frame.hash_rows(seed=0, seed_1=1, seed_2=2, seed_3=3) + for chunk in row_hashes.get_chunks(): + digest.update(chunk.to_numpy().astype(" str: + path.parent.mkdir(parents=True, exist_ok=True) + if path.exists() or path.is_symlink(): + raise M8L2DevelopmentError(f"refusing to overwrite development artifact {path}") + frame.write_parquet(path, compression="zstd", statistics=True) + descriptor = os.open(path, os.O_RDONLY) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + _fsync_directory(path.parent) + return sha256_file(path) + + +def _child_payload( + *, + root: Path, + symbol: str, + endpoint: M8L2AnalysisEndpoint, + selection: LockedSelection, + selection_path: Path, + state_path: Path, + comparison_path: Path, + comparison_file_sha256: str, + regime_path: Path, + regime_sha256: str, + execution_path: Path, + execution_sha256: str, + capture: M8L2StudyConfig, + analysis: M8L2AnalysisConfig, + producer: ProducerSourceIdentity, + train_input: _VerifiedInput, + validation_input: _VerifiedInput, +) -> dict[str, object]: + return { + "schema_version": _CHILD_SCHEMA_VERSION, + "artifact_kind": "m8_l2_symbol_endpoint_development_lock", + "symbol": symbol, + "endpoint": _endpoint_payload(endpoint), + "capture_config_sha256": capture.hash, + "capture_config_source_sha256": capture.source_sha256, + "analysis_config_sha256": analysis.hash, + "analysis_config_source_sha256": analysis.source_sha256, + "producer_source_identity": producer.to_dict(), + "development_inputs": [ + { + "date": train_input.session_date, + "role": train_input.role, + "session_id": train_input.session_id, + "file_authority": _file_authority_dict(train_input.file_authority), + }, + { + "date": validation_input.session_date, + "role": validation_input.role, + "session_id": validation_input.session_id, + "file_authority": _file_authority_dict(validation_input.file_authority), + }, + ], + "campaign_identity": _campaign_dict(train_input.campaign_identity), + "selection_policy": "eight_candidates_fit_train_only_selected_validation_log_loss", + "final_fit_policy": ( + "selected_specification_and_independent_historical_prior_fit_once_on_" + "train_plus_validation_before_aggregate_lock" + ), + "candidate_count": selection.validation_comparison.height, + "selected_model": selection.selected_model, + "selection_lock_path": _relative(selection_path, root), + "selection_lock_sha256": selection.lock.sha256, + "final_fitted_state_path": _relative(state_path, root), + "final_fitted_state_sha256": selection.fitted_state.sha256, + "validation_comparison_path": _relative(comparison_path, root), + "validation_comparison_file_sha256": comparison_file_sha256, + "validation_comparison_frame_sha256": _frame_sha256(selection.validation_comparison), + "validation_comparison_rows": selection.validation_comparison.height, + "regime_thresholds_path": _relative(regime_path, root), + "regime_thresholds_sha256": regime_sha256, + "execution_reference_path": _relative(execution_path, root), + "execution_reference_sha256": execution_sha256, + "development_frame_sha256": selection.development_frame_sha256, + "test_rows_accessed": False, + "heldout_fit_or_update_allowed": False, + } + + +def _write_child( + *, + root: Path, + symbol: str, + endpoint: M8L2AnalysisEndpoint, + selection: LockedSelection, + regime_path: Path, + regime_sha256: str, + execution_path: Path, + execution_sha256: str, + capture: M8L2StudyConfig, + analysis: M8L2AnalysisConfig, + producer: ProducerSourceIdentity, + train_input: _VerifiedInput, + validation_input: _VerifiedInput, +) -> L2DevelopmentChildLock: + base = root / "models" / symbol.lower() / endpoint.name + selection_path = base / "selection_lock.json" + state_path = base / "final_fitted_state.json" + comparison_path = base / "validation_comparison.parquet" + _write_bytes(selection_path, selection.lock.payload_json.encode("ascii") + b"\n") + _write_bytes(state_path, selection.fitted_state.payload_json.encode("ascii") + b"\n") + comparison_file_sha = _write_parquet(comparison_path, selection.validation_comparison) + child_payload = _child_payload( + root=root, + symbol=symbol, + endpoint=endpoint, + selection=selection, + selection_path=selection_path, + state_path=state_path, + comparison_path=comparison_path, + comparison_file_sha256=comparison_file_sha, + regime_path=regime_path, + regime_sha256=regime_sha256, + execution_path=execution_path, + execution_sha256=execution_sha256, + capture=capture, + analysis=analysis, + producer=producer, + train_input=train_input, + validation_input=validation_input, + ) + child_path = base / "child_lock.json" + child_sha = _write_json(child_path, child_payload) + return L2DevelopmentChildLock( + symbol=symbol, + endpoint=endpoint.name, + path=child_path, + sha256=child_sha, + selection_lock_sha256=selection.lock.sha256, + fitted_state_sha256=selection.fitted_state.sha256, + ) + + +def _reserve_destination(path: Path) -> Path: + _reject_symlink_components(path.parent) + path.parent.mkdir(parents=True, exist_ok=True) + _reject_symlink_components(path.parent) + try: + path.mkdir(mode=0o755) + except FileExistsError as error: + raise M8L2DevelopmentError( + f"development-lock destination already exists; overwrite is forbidden: {path}" + ) from error + _fsync_directory(path.parent) + return path + + +def _publish_inventory( + root: Path, + *, + artifact_kind: str = "m8_l2_development_lock_inventory", +) -> None: + files = _walk_regular(root) + if ( + _LOCKED_MARKER in files + or _NOT_CREATED_MARKER in files + or _CHECKSUMS_NAME in files + or _INVENTORY_NAME in files + ): + raise M8L2DevelopmentError("terminal inventory files were published out of order") + inventory_entries = [ + { + "path": relative, + "sha256": sha256_file(path), + "bytes": path.stat().st_size, + } + for relative, path in files.items() + ] + _write_json( + root / _INVENTORY_NAME, + { + "schema_version": _INVENTORY_SCHEMA_VERSION, + "artifact_kind": artifact_kind, + "files": inventory_entries, + }, + ) + checksum_files = _walk_regular(root) + lines = [f"{sha256_file(path)} {relative}\n" for relative, path in checksum_files.items()] + _write_bytes(root / _CHECKSUMS_NAME, "".join(lines).encode("ascii")) + + +def _validate_lock_time(now: datetime) -> str: + if now.tzinfo is None: + raise M8L2DevelopmentError("development lock clock must be timezone-aware") + observed = now.astimezone(UTC) + if observed < _EARLIEST_LOCK_TIME: + raise M8L2DevelopmentError("development lock cannot precede validation session completion") + if observed >= _LOCK_DEADLINE: + raise M8L2DevelopmentError("development lock deadline has passed") + return observed.isoformat().replace("+00:00", "Z") + + +def _validate_runtime_campaign( + producer: ProducerSourceIdentity, + train_input: _VerifiedInput, + validation_input: _VerifiedInput, +) -> None: + train_campaign = _campaign_dict(train_input.campaign_identity) + validation_campaign = _campaign_dict(validation_input.campaign_identity) + if train_campaign != validation_campaign: + raise M8L2DevelopmentError("development sessions have different campaign identities") + expected = { + "runtime_commit": producer.commit, + "runtime_source_tree_sha256": producer.source_tree_sha256, + "runtime_dirty": False, + } + if any(train_campaign.get(name) != value for name, value in expected.items()): + raise M8L2DevelopmentError( + "development producer source differs from the frozen capture campaign" + ) + if ( + train_campaign.get("runtime_fingerprint_sha256") + != current_m8_l2_runtime_fingerprint_sha256() + ): + raise M8L2DevelopmentError( + "development producer runtime differs from the frozen capture campaign" + ) + + +def _validate_not_created_context( + *, + capture: M8L2StudyConfig, + producer: ProducerSourceIdentity, + bundles: tuple[M8L2SessionBundle, M8L2SessionBundle], +) -> _CampaignIdentity: + campaigns = tuple(_campaign_from_session_bundle(bundle) for bundle in bundles) + if _campaign_dict(campaigns[0]) != _campaign_dict(campaigns[1]): + raise M8L2DevelopmentError("development sessions have different campaign identities") + campaign = _campaign_dict(campaigns[0]) + if ( + campaign.get("runtime_commit") != producer.commit + or campaign.get("runtime_source_tree_sha256") != producer.source_tree_sha256 + or campaign.get("runtime_dirty") is not False + ): + raise M8L2DevelopmentError( + "development producer source differs from the frozen capture campaign" + ) + if campaign["runtime_fingerprint_sha256"] != current_m8_l2_runtime_fingerprint_sha256(): + raise M8L2DevelopmentError( + "development producer runtime differs from the frozen capture campaign" + ) + for bundle, coordinate in zip(bundles, _EXPECTED_DEVELOPMENT, strict=True): + if (bundle.session_date, bundle.role) != coordinate: + raise M8L2DevelopmentError("development session has the wrong frozen coordinate") + if bundle.status not in {"COMPLETE", "INSUFFICIENT_DATA"}: + raise M8L2DevelopmentError("development session has an unsupported terminal status") + if not _not_created_reasons(bundles): + raise M8L2DevelopmentError( + "NOT_CREATED development authority requires an insufficient development session" + ) + if capture.sessions[0].date.isoformat() != bundles[0].session_date: + raise M8L2DevelopmentError("development capture calendar changed") + return campaigns[0] + + +def _publish_not_created_development( + *, + capture: M8L2StudyConfig, + analysis: M8L2AnalysisConfig, + bundles: tuple[M8L2SessionBundle, M8L2SessionBundle], + lock_dir: str | Path, + expected_session_file_authorities: Mapping[str, _ExpectedFileAuthority] | None, +) -> L2DevelopmentAuthorityResult: + project_root = capture.path.parent.parent.resolve() + producer = _producer_source_identity(project_root) + _validate_source(producer) + campaign = _validate_not_created_context( + capture=capture, + producer=producer, + bundles=bundles, + ) + _validate_lock_time(_utc_now()) + root = _reserve_destination(Path(lock_dir).absolute()) + marker = root / _NOT_CREATED_MARKER + reasons = _not_created_reasons(bundles) + try: + created_at = _validate_lock_time(_utc_now()) + payload: dict[str, object] = { + "schema_version": _NOT_CREATED_SCHEMA_VERSION, + "artifact_kind": "m8_l2_development_authority_not_created", + "status": "NOT_CREATED", + "study": analysis.study.name, + "created_at_utc": created_at, + "must_precede_utc": _LOCK_DEADLINE.isoformat().replace("+00:00", "Z"), + "capture_config_sha256": capture.hash, + "capture_config_source_sha256": capture.source_sha256, + "capture_protocol_sha256": analysis.study.capture_protocol_sha256, + "analysis_config_sha256": analysis.hash, + "analysis_config_source_sha256": analysis.source_sha256, + "producer_source_identity": producer.to_dict(), + "campaign_identity": _campaign_dict(campaign), + "development_inputs": [_development_session_claim(bundle) for bundle in bundles], + "reason_codes": list(reasons), + "children": [], + "heldout_declarations": [ + {"date": date_value, "role": role} for date_value, role in _EXPECTED_HELDOUT + ], + "heldout_access": { + "paths_received": False, + "file_hashes_received": False, + "row_counts_received": False, + "economic_rows_opened": False, + "model_fit_or_update_after_lock": False, + }, + "claims": { + "cross_symbol_pooling": False, + "p_values": False, + "significance": False, + "capacity": False, + "realized_execution": False, + "profitability": False, + }, + } + aggregate_path = root / _AGGREGATE_NAME + aggregate_sha = _write_json(aggregate_path, payload) + _write_bytes( + root / _AGGREGATE_DIGEST_NAME, + f"{aggregate_sha} {_AGGREGATE_NAME}\n".encode("ascii"), + ) + _publish_inventory( + root, + artifact_kind="m8_l2_development_not_created_inventory", + ) + _fsync_directory(root) + _validate_lock_time(_utc_now()) + final_capture, final_analysis = _revalidate_configs(capture, analysis) + final_producer = _producer_source_identity(project_root) + repeated = tuple( + verify_m8_l2_session_bundle(bundle.root, expected_config=capture) for bundle in bundles + ) + _verify_expected_session_file_authorities(repeated, expected_session_file_authorities) + if ( + final_capture != capture + or final_analysis != analysis + or final_producer != producer + or repeated != bundles + ): + raise M8L2DevelopmentError( + "development config/source/session authority changed before publication" + ) + repeated_campaign = _validate_not_created_context( + capture=capture, + producer=producer, + bundles=repeated, + ) + if _campaign_dict(repeated_campaign) != _campaign_dict(campaign): + raise M8L2DevelopmentError("development campaign changed before publication") + _assert_development_import_origins(project_root) + _validate_lock_time(_utc_now()) + _write_bytes(marker, _NOT_CREATED_BYTES) + _fsync_directory(root) + return L2DevelopmentLockResult( + root=root, + aggregate_path=aggregate_path, + aggregate_sha256=aggregate_sha, + marker_path=marker, + created_at_utc=created_at, + children=(), + status="NOT_CREATED", + reason_codes=reasons, + ) + except Exception: + if not marker.exists(): + shutil.rmtree(root, ignore_errors=True) + _fsync_directory(root.parent) + raise + + +def lock_m8_l2_development( + capture_config: M8L2StudyConfig, + analysis_config: M8L2AnalysisConfig, + train_bundle_path: str | Path, + validation_bundle_path: str | Path, + lock_dir: str | Path, + *, + input_loader: L2DevelopmentInputVerifier | None = None, + expected_session_file_authorities: Mapping[str, _ExpectedFileAuthority] | None = None, +) -> L2DevelopmentAuthorityResult: + """Publish LOCKED state or a typed NOT_CREATED development authority.""" + + project_root = capture_config.path.parent.parent.resolve() + _assert_development_import_origins(project_root) + capture, analysis = _revalidate_configs(capture_config, analysis_config) + train_requested = Path(train_bundle_path) + validation_requested = Path(validation_bundle_path) + if train_requested.absolute() == validation_requested.absolute(): + raise M8L2DevelopmentError("train and validation must be distinct frozen session paths") + try: + train_bundle = verify_m8_l2_session_bundle(train_requested, expected_config=capture) + validation_bundle = verify_m8_l2_session_bundle( + validation_requested, expected_config=capture + ) + except Exception as error: + raise M8L2DevelopmentError("development session bundle verification failed") from error + bundles = (train_bundle, validation_bundle) + _verify_expected_session_file_authorities(bundles, expected_session_file_authorities) + for bundle, (expected_date, expected_role) in zip(bundles, _EXPECTED_DEVELOPMENT, strict=True): + if bundle.session_date != expected_date or bundle.role != expected_role: + raise M8L2DevelopmentError( + f"development input must be COMPLETE {expected_date} {expected_role} " + "or the matching terminal INSUFFICIENT_DATA authority" + ) + if any(bundle.status != "COMPLETE" for bundle in bundles): + return _publish_not_created_development( + capture=capture, + analysis=analysis, + bundles=bundles, + lock_dir=lock_dir, + expected_session_file_authorities=expected_session_file_authorities, + ) + + project_root = capture.path.parent.parent.resolve() + producer = _producer_source_identity(project_root) + _validate_source(producer) + verifier = input_loader if input_loader is not None else _load_input_verifier() + try: + train_input = verifier( + train_bundle.root, + expected_config=capture, + expected_date="2026-08-10", + expected_role="train", + ) + validation_input = verifier( + validation_bundle.root, + expected_config=capture, + expected_date="2026-08-11", + expected_role="validation", + expected_campaign=train_input.campaign_identity, + ) + except Exception as error: + raise M8L2DevelopmentError("development input authority verification failed") from error + _verify_input_descriptor( + train_input, + train_bundle, + capture=capture, + expected_date="2026-08-10", + expected_role="train", + ) + _verify_input_descriptor( + validation_input, + validation_bundle, + capture=capture, + expected_date="2026-08-11", + expected_role="validation", + ) + _validate_runtime_campaign(producer, train_input, validation_input) + # Refuse to begin expensive development fitting outside the declared lock + # window. The deadline is checked again immediately before publishing the + # aggregate authority because fitting all eight candidates can itself cross + # the held-out boundary. + _validate_lock_time(_utc_now()) + + destination = Path(lock_dir).absolute() + root = _reserve_destination(destination) + marker_path = root / _LOCKED_MARKER + try: + endpoint_specs = _endpoint_specs(analysis) + endpoint_config = {item.name: item for item in analysis.endpoints} + declared_test_dates = tuple(value[0] for value in _EXPECTED_HELDOUT) + children: list[L2DevelopmentChildLock] = [] + execution_claims: list[dict[str, object]] = [] + regime_claims: list[dict[str, object]] = [] + for symbol in capture.study.symbols: + train_admission = _preflight_symbol_raw(train_input, symbol) + validation_admission = _preflight_symbol_raw(validation_input, symbol) + if train_admission is not None and validation_admission is not None: + admitted_raw = train_admission[0] + validation_admission[0] + _require_memory_budget( + admitted_raw, + _MAX_DEVELOPMENT_RAW_BYTES, + f"{symbol} train+validation raw Parquet admission", + ) + _require_memory_budget( + _causal_build_upper_bytes( + train_admission[1] + validation_admission[1], len(endpoint_specs) + ), + _MAX_DEVELOPMENT_CAUSAL_BYTES, + f"{symbol} eight-frame causal build admission", + ) + train_loaded = train_input.load_symbol_frames(symbol) + _require_memory_budget( + _loaded_bytes(train_loaded), + _MAX_DEVELOPMENT_RAW_BYTES, + f"{symbol} train raw materialization", + ) + validation_loaded = validation_input.load_symbol_frames(symbol) + _require_memory_budget( + _loaded_bytes(train_loaded) + _loaded_bytes(validation_loaded), + _MAX_DEVELOPMENT_RAW_BYTES, + f"{symbol} train+validation raw materialization", + ) + if train_admission is None or validation_admission is None: + _require_memory_budget( + _causal_build_upper_bytes( + train_loaded.book_observations.height + + validation_loaded.book_observations.height, + len(endpoint_specs), + ), + _MAX_DEVELOPMENT_CAUSAL_BYTES, + f"{symbol} eight-frame causal build admission", + ) + train_frames = build_l2_endpoint_frames( + train_loaded.book_observations, + train_loaded.depth_deltas, + train_loaded.intervals, + study_date="2026-08-10", + study_role="train", + feature_windows=analysis.features.rolling_windows, + volatility_window=analysis.features.volatility_window, + clock_max_state_age_ms=analysis.features.clock_max_state_age_ms, + endpoints=endpoint_specs, + ) + _require_memory_budget( + sum(_frame_bytes(frame) for frame in train_frames.values()), + _MAX_DEVELOPMENT_CAUSAL_BYTES, + f"{symbol} train causal frames", + ) + validation_frames = build_l2_endpoint_frames( + validation_loaded.book_observations, + validation_loaded.depth_deltas, + validation_loaded.intervals, + study_date="2026-08-11", + study_role="validation", + feature_windows=analysis.features.rolling_windows, + volatility_window=analysis.features.volatility_window, + clock_max_state_age_ms=analysis.features.clock_max_state_age_ms, + endpoints=endpoint_specs, + ) + _require_memory_budget( + sum(_frame_bytes(frame) for frame in train_frames.values()) + + sum(_frame_bytes(frame) for frame in validation_frames.values()), + _MAX_DEVELOPMENT_CAUSAL_BYTES, + f"{symbol} eight accumulated causal frames", + ) + first_endpoint = analysis.endpoints[0].name + regime = fit_l2_regime_thresholds( + train_frames[first_endpoint], + lower_quantile=( + analysis.regimes.quantile_numerators[0] / analysis.regimes.quantile_denominator + ), + upper_quantile=( + analysis.regimes.quantile_numerators[1] / analysis.regimes.quantile_denominator + ), + volatility_column=analysis.regimes.feature, + ) + regime_path = root / "references" / symbol.lower() / "regime_thresholds.json" + regime_sha = _write_json(regime_path, _regime_payload(regime, analysis)) + train_reference_frame = apply_l2_regimes(train_frames[first_endpoint], regime) + validation_reference_frame = apply_l2_regimes(validation_frames[first_endpoint], regime) + execution_path = root / "references" / symbol.lower() / "execution_reference.json" + execution_sha = _write_json( + execution_path, + _execution_reference( + symbol, + train_reference_frame, + validation_reference_frame, + analysis, + ), + ) + del train_reference_frame, validation_reference_frame + execution_claims.append( + { + "symbol": symbol, + "path": _relative(execution_path, root), + "sha256": execution_sha, + } + ) + regime_claims.append( + { + "symbol": symbol, + "path": _relative(regime_path, root), + "sha256": regime_sha, + } + ) + for endpoint in analysis.endpoints: + modeled_train = apply_l2_regimes(train_frames[endpoint.name], regime) + modeled_validation = apply_l2_regimes(validation_frames[endpoint.name], regime) + feature_columns = l2_model_feature_columns( + modeled_train, windows=analysis.features.rolling_windows + ) + if feature_columns != analysis.features.model_feature_columns: + raise M8L2DevelopmentError( + "generated L2 feature ladder differs from frozen analysis contract" + ) + if ( + l2_model_feature_columns( + modeled_validation, windows=analysis.features.rolling_windows + ) + != feature_columns + ): + raise M8L2DevelopmentError("validation feature ladder differs from train") + _require_memory_budget( + _selection_workspace_upper_bytes( + modeled_train, + modeled_validation, + feature_count=len(feature_columns), + ), + _MAX_SELECTION_WORKSPACE_BYTES, + f"{symbol} {endpoint.name} selection scratch/NumPy admission", + ) + selection = select_multidate_model( + (modeled_train, modeled_validation), + _model_config(capture), + feature_columns=feature_columns, + declared_test_dates=declared_test_dates, + seed=analysis.study.seed, + calibration_bins=analysis.calibration.bins, + target="future_mid_up", + calibration_fraction=capture.models.calibration_fraction, + bootstrap_draws=analysis.bootstrap.samples, + block_width_events=endpoint.nominal_event_block_width, + ) + if selection.validation_comparison.height != 8: + raise M8L2DevelopmentError( + "frozen L2 model ladder must contain exactly eight candidates" + ) + children.append( + _write_child( + root=root, + symbol=symbol, + endpoint=endpoint_config[endpoint.name], + selection=selection, + regime_path=regime_path, + regime_sha256=regime_sha, + execution_path=execution_path, + execution_sha256=execution_sha, + capture=capture, + analysis=analysis, + producer=producer, + train_input=train_input, + validation_input=validation_input, + ) + ) + # Child publication retains only canonical JSON/Parquet and + # compact digests; no endpoint frame or fitted scratch is + # allowed to leak into the next coordinate. + del selection, modeled_train, modeled_validation + + # The next symbol begins with no raw/causal locals from this one. + del train_loaded, validation_loaded, train_frames, validation_frames, regime + + expected_children = tuple( + (symbol, endpoint.name) + for symbol in capture.study.symbols + for endpoint in analysis.endpoints + ) + if tuple((item.symbol, item.endpoint) for item in children) != expected_children: + raise M8L2DevelopmentError("development child-lock set is incomplete or reordered") + created_at = _validate_lock_time(_utc_now()) + aggregate_payload: dict[str, object] = { + "schema_version": _LOCK_SCHEMA_VERSION, + "artifact_kind": "m8_l2_outcome_blind_development_lock", + "study": analysis.study.name, + "created_at_utc": created_at, + "must_precede_utc": _LOCK_DEADLINE.isoformat().replace("+00:00", "Z"), + "capture_config_sha256": capture.hash, + "capture_config_source_sha256": capture.source_sha256, + "capture_protocol_sha256": analysis.study.capture_protocol_sha256, + "analysis_config_sha256": analysis.hash, + "analysis_config_source_sha256": analysis.source_sha256, + "producer_source_identity": producer.to_dict(), + "campaign_identity": _campaign_dict(train_input.campaign_identity), + "development_inputs": [ + { + "date": train_input.session_date, + "role": train_input.role, + "session_id": train_input.session_id, + "file_authority": _file_authority_dict(train_input.file_authority), + }, + { + "date": validation_input.session_date, + "role": validation_input.role, + "session_id": validation_input.session_id, + "file_authority": _file_authority_dict(validation_input.file_authority), + }, + ], + "children": [ + { + "symbol": item.symbol, + "endpoint": item.endpoint, + "path": _relative(item.path, root), + "sha256": item.sha256, + "selection_lock_sha256": item.selection_lock_sha256, + "final_fitted_state_sha256": item.fitted_state_sha256, + } + for item in children + ], + "regime_thresholds": regime_claims, + "execution_references": execution_claims, + "fit_policy": ( + "regimes_fit_Aug8_only; candidates_fit_Aug8_only_and_select_Aug9_only; " + "selected_and_prior_fit_once_on_Aug8_plus_Aug9_before_lock" + ), + "heldout_declarations": [ + {"date": date_value, "role": role} for date_value, role in _EXPECTED_HELDOUT + ], + "heldout_access": { + "paths_received": False, + "file_hashes_received": False, + "row_counts_received": False, + "economic_rows_opened": False, + "model_fit_or_update_after_lock": False, + }, + "claims": { + "cross_symbol_pooling": False, + "p_values": False, + "significance": False, + "capacity": False, + "realized_execution": False, + "profitability": False, + }, + } + aggregate_path = root / _AGGREGATE_NAME + aggregate_sha = _write_json(aggregate_path, aggregate_payload) + _write_bytes( + root / _AGGREGATE_DIGEST_NAME, + f"{aggregate_sha} {_AGGREGATE_NAME}\n".encode("ascii"), + ) + _publish_inventory(root) + _fsync_directory(root) + # The terminal marker itself is the durable publication boundary. A + # lock that finished hashing just after the deadline must not become an + # authority merely because its expensive work began in time. + _validate_lock_time(_utc_now()) + final_capture, final_analysis = _revalidate_configs(capture, analysis) + final_producer = _producer_source_identity(project_root) + if final_capture != capture or final_analysis != analysis or final_producer != producer: + raise M8L2DevelopmentError( + "development config/source authority changed before lock publication" + ) + if ( + _campaign_dict(train_input.campaign_identity).get("runtime_fingerprint_sha256") + != current_m8_l2_runtime_fingerprint_sha256() + ): + raise M8L2DevelopmentError("development runtime changed before lock publication") + repeated_bundles = tuple( + verify_m8_l2_session_bundle(bundle.root, expected_config=capture) for bundle in bundles + ) + if repeated_bundles != bundles: + raise M8L2DevelopmentError( + "development session authority changed before lock publication" + ) + _verify_expected_session_file_authorities( + repeated_bundles, + expected_session_file_authorities, + ) + _assert_development_import_origins(project_root) + _validate_lock_time(_utc_now()) + _write_bytes(marker_path, _LOCKED_BYTES) + _fsync_directory(root) + return L2DevelopmentLockResult( + root=root, + aggregate_path=aggregate_path, + aggregate_sha256=aggregate_sha, + marker_path=marker_path, + created_at_utc=created_at, + children=tuple(children), + ) + except Exception: + if not marker_path.exists(): + shutil.rmtree(root, ignore_errors=True) + _fsync_directory(root.parent) + raise + + +def _parse_checksums(raw: bytes) -> dict[str, str]: + try: + text = raw.decode("ascii") + except UnicodeDecodeError as error: + raise M8L2DevelopmentError("development checksums are not ASCII") from error + result: dict[str, str] = {} + for line in text.splitlines(keepends=True): + if not line.endswith("\n") or len(line) < 67 or line[64:66] != " ": + raise M8L2DevelopmentError("development checksum line is malformed") + digest, relative = line[:64], line[66:-1] + if len(digest) != 64 or any(char not in "0123456789abcdef" for char in digest): + raise M8L2DevelopmentError("development checksum digest is malformed") + relative = _safe_relative(relative) + if relative in result: + raise M8L2DevelopmentError("development checksum path is duplicated") + result[relative] = digest + if not result or list(result) != sorted(result): + raise M8L2DevelopmentError("development checksum authority is empty or unordered") + return result + + +def _exact_keys(payload: Mapping[str, Any], expected: set[str], label: str) -> None: + if set(payload) != expected: + raise M8L2DevelopmentError(f"{label} keys differ from the exact schema") + + +def _verify_reference_claims( + root: Path, + aggregate: Mapping[str, Any], + analysis: M8L2AnalysisConfig, +) -> None: + execution = aggregate.get("execution_references") + regimes = aggregate.get("regime_thresholds") + if not isinstance(execution, list) or not isinstance(regimes, list): + raise M8L2DevelopmentError("aggregate reference claims are malformed") + for label, claims, schema in ( + ("execution", execution, _EXECUTION_REFERENCE_SCHEMA_VERSION), + ("regime", regimes, _REGIME_SCHEMA_VERSION), + ): + if len(claims) != len(analysis.study.symbols): + raise M8L2DevelopmentError(f"aggregate {label} reference set is incomplete") + for symbol, raw_claim in zip(analysis.study.symbols, claims, strict=True): + if not isinstance(raw_claim, Mapping) or set(raw_claim) != {"symbol", "path", "sha256"}: + raise M8L2DevelopmentError(f"aggregate {label} reference claim is malformed") + if raw_claim["symbol"] != symbol: + raise M8L2DevelopmentError(f"aggregate {label} reference order changed") + relative = _safe_relative(str(raw_claim["path"])) + payload, raw = _read_json(root / relative, f"{label} reference") + if hashlib.sha256(raw).hexdigest() != raw_claim["sha256"]: + raise M8L2DevelopmentError(f"aggregate {label} reference hash changed") + if payload.get("schema_version") != schema or payload.get("symbol") != symbol: + raise M8L2DevelopmentError(f"aggregate {label} reference semantics changed") + if _canonical_json_bytes(cast(Mapping[str, object], payload)) != raw: + raise M8L2DevelopmentError(f"aggregate {label} reference is not canonical JSON") + if label == "execution" and ( + payload.get("reference_price_statistic") + != analysis.execution.reference_price_statistic + or payload.get("reference_depth_statistic") + != analysis.execution.reference_depth_statistic + or payload.get("quantity_policy") != analysis.execution.reference_quantity_policy + ): + raise M8L2DevelopmentError("execution reference differs from analysis contract") + + +def _restore_child( + root: Path, + claim: Mapping[str, Any], + *, + capture: M8L2StudyConfig, + analysis: M8L2AnalysisConfig, + aggregate: Mapping[str, Any], +) -> L2DevelopmentChildLock: + _exact_keys( + claim, + { + "symbol", + "endpoint", + "path", + "sha256", + "selection_lock_sha256", + "final_fitted_state_sha256", + }, + "aggregate child claim", + ) + child_path = root / _safe_relative(str(claim["path"])) + child, child_raw = _read_json(child_path, "development child lock") + if hashlib.sha256(child_raw).hexdigest() != claim["sha256"]: + raise M8L2DevelopmentError("development child-lock SHA-256 changed") + _exact_keys( + child, + { + "schema_version", + "artifact_kind", + "symbol", + "endpoint", + "capture_config_sha256", + "capture_config_source_sha256", + "analysis_config_sha256", + "analysis_config_source_sha256", + "producer_source_identity", + "development_inputs", + "campaign_identity", + "selection_policy", + "final_fit_policy", + "candidate_count", + "selected_model", + "selection_lock_path", + "selection_lock_sha256", + "final_fitted_state_path", + "final_fitted_state_sha256", + "validation_comparison_path", + "validation_comparison_file_sha256", + "validation_comparison_frame_sha256", + "validation_comparison_rows", + "regime_thresholds_path", + "regime_thresholds_sha256", + "execution_reference_path", + "execution_reference_sha256", + "development_frame_sha256", + "test_rows_accessed", + "heldout_fit_or_update_allowed", + }, + "development child lock", + ) + endpoint_by_name = {item.name: item for item in analysis.endpoints} + symbol = str(claim["symbol"]) + endpoint_name = str(claim["endpoint"]) + endpoint = endpoint_by_name.get(endpoint_name) + if endpoint is None: + raise M8L2DevelopmentError("development child names an unknown endpoint") + if ( + child.get("schema_version") != _CHILD_SCHEMA_VERSION + or child.get("artifact_kind") != "m8_l2_symbol_endpoint_development_lock" + or child.get("symbol") != symbol + or child.get("endpoint") != _endpoint_payload(endpoint) + or child.get("capture_config_sha256") != capture.hash + or child.get("capture_config_source_sha256") != capture.source_sha256 + or child.get("analysis_config_sha256") != analysis.hash + or child.get("analysis_config_source_sha256") != analysis.source_sha256 + or child.get("producer_source_identity") != aggregate.get("producer_source_identity") + or child.get("development_inputs") != aggregate.get("development_inputs") + or child.get("campaign_identity") != aggregate.get("campaign_identity") + or child.get("candidate_count") != 8 + or child.get("test_rows_accessed") is not False + or child.get("heldout_fit_or_update_allowed") is not False + ): + raise M8L2DevelopmentError("development child-lock contract changed") + selection_relative = _safe_relative(str(child["selection_lock_path"])) + selection_raw = _read_regular( + root / selection_relative, label="selection lock", maximum=_MAX_JSON_BYTES + ) + if not selection_raw.endswith(b"\n"): + raise M8L2DevelopmentError("selection lock lacks canonical newline") + selection_text = selection_raw[:-1].decode("ascii") + selection = AnalysisLock.restore(selection_text, str(child["selection_lock_sha256"])) + if selection.sha256 != claim["selection_lock_sha256"]: + raise M8L2DevelopmentError("child selection lock differs from aggregate") + if _canonical_json_bytes(cast(Mapping[str, object], selection.payload())) != selection_raw: + raise M8L2DevelopmentError("selection lock is not canonical JSON") + state_relative = _safe_relative(str(child["final_fitted_state_path"])) + state_raw = _read_regular(root / state_relative, label="fitted state", maximum=_MAX_JSON_BYTES) + if not state_raw.endswith(b"\n"): + raise M8L2DevelopmentError("fitted state lacks canonical newline") + state = FinalFittedState.restore( + state_raw[:-1].decode("ascii"), str(child["final_fitted_state_sha256"]) + ) + if state.sha256 != claim["final_fitted_state_sha256"]: + raise M8L2DevelopmentError("child fitted state differs from aggregate") + selection_payload = selection.payload() + if ( + selection_payload.get("final_fitted_state_sha256") != state.sha256 + or selection_payload.get("final_fitted_state") != state.payload() + or selection_payload.get("development_frame_sha256") + != child.get("development_frame_sha256") + or selection_payload.get("selected_candidate", {}).get("name") + != child.get("selected_model") + or selection_payload.get("test_rows_accessed_during_selection") is not False + or selection_payload.get("declared_test_dates") != [value[0] for value in _EXPECTED_HELDOUT] + ): + raise M8L2DevelopmentError("child selection and fitted-state authorities disagree") + comparison_relative = _safe_relative(str(child["validation_comparison_path"])) + comparison_path = root / comparison_relative + comparison_raw = _read_regular( + comparison_path, label="validation comparison", maximum=_MAX_COMPARISON_BYTES + ) + if hashlib.sha256(comparison_raw).hexdigest() != child["validation_comparison_file_sha256"]: + raise M8L2DevelopmentError("validation comparison file hash changed") + try: + comparison = pl.read_parquet(comparison_path) + except Exception as error: + raise M8L2DevelopmentError("validation comparison cannot be restored") from error + if ( + comparison.height != child["validation_comparison_rows"] + or comparison.height != 8 + or _frame_sha256(comparison) != child["validation_comparison_frame_sha256"] + or _frame_sha256(comparison) != selection_payload.get("validation_comparison_sha256") + or comparison.filter(pl.col("selected_on_validation")).height != 1 + ): + raise M8L2DevelopmentError("validation comparison differs from child selection lock") + return L2DevelopmentChildLock( + symbol=symbol, + endpoint=endpoint_name, + path=child_path, + sha256=str(claim["sha256"]), + selection_lock_sha256=selection.sha256, + fitted_state_sha256=state.sha256, + ) + + +def _verify_not_created_aggregate( + *, + capture: M8L2StudyConfig, + analysis: M8L2AnalysisConfig, + train_bundle_path: str | Path, + validation_bundle_path: str | Path, + root: Path, + marker_path: Path, + aggregate_path: Path, + aggregate_sha: str, + aggregate: Mapping[str, Any], +) -> L2DevelopmentAuthorityResult: + _exact_keys( + aggregate, + { + "schema_version", + "artifact_kind", + "status", + "study", + "created_at_utc", + "must_precede_utc", + "capture_config_sha256", + "capture_config_source_sha256", + "capture_protocol_sha256", + "analysis_config_sha256", + "analysis_config_source_sha256", + "producer_source_identity", + "campaign_identity", + "development_inputs", + "reason_codes", + "children", + "heldout_declarations", + "heldout_access", + "claims", + }, + "NOT_CREATED development authority", + ) + if ( + aggregate.get("schema_version") != _NOT_CREATED_SCHEMA_VERSION + or aggregate.get("artifact_kind") != "m8_l2_development_authority_not_created" + or aggregate.get("status") != "NOT_CREATED" + or aggregate.get("study") != analysis.study.name + or aggregate.get("must_precede_utc") != _LOCK_DEADLINE.isoformat().replace("+00:00", "Z") + or aggregate.get("capture_config_sha256") != capture.hash + or aggregate.get("capture_config_source_sha256") != capture.source_sha256 + or aggregate.get("capture_protocol_sha256") != analysis.study.capture_protocol_sha256 + or aggregate.get("analysis_config_sha256") != analysis.hash + or aggregate.get("analysis_config_source_sha256") != analysis.source_sha256 + or aggregate.get("children") != [] + or aggregate.get("heldout_declarations") + != [{"date": value[0], "role": value[1]} for value in _EXPECTED_HELDOUT] + or aggregate.get("heldout_access") + != { + "paths_received": False, + "file_hashes_received": False, + "row_counts_received": False, + "economic_rows_opened": False, + "model_fit_or_update_after_lock": False, + } + or aggregate.get("claims") + != { + "cross_symbol_pooling": False, + "p_values": False, + "significance": False, + "capacity": False, + "realized_execution": False, + "profitability": False, + } + ): + raise M8L2DevelopmentError("NOT_CREATED development contract changed") + created_raw = aggregate.get("created_at_utc") + if type(created_raw) is not str: + raise M8L2DevelopmentError("NOT_CREATED creation time is malformed") + try: + created = datetime.fromisoformat(created_raw.replace("Z", "+00:00")) + except ValueError as error: + raise M8L2DevelopmentError("NOT_CREATED creation time is malformed") from error + if not _EARLIEST_LOCK_TIME <= created < _LOCK_DEADLINE: + raise M8L2DevelopmentError( + "NOT_CREATED creation time is outside the frozen development window" + ) + producer_payload = aggregate.get("producer_source_identity") + if not isinstance(producer_payload, Mapping): + raise M8L2DevelopmentError("NOT_CREATED producer identity is malformed") + producer = _producer_source_identity(capture.path.parent.parent.resolve()) + _validate_source(producer) + if producer.to_dict() != producer_payload: + raise M8L2DevelopmentError( + "current producer source differs from NOT_CREATED development authority" + ) + try: + bundles = ( + verify_m8_l2_session_bundle(train_bundle_path, expected_config=capture), + verify_m8_l2_session_bundle(validation_bundle_path, expected_config=capture), + ) + except Exception as error: + raise M8L2DevelopmentError( + "external NOT_CREATED development sessions no longer verify" + ) from error + for bundle, coordinate in zip(bundles, _EXPECTED_DEVELOPMENT, strict=True): + if (bundle.session_date, bundle.role) != coordinate: + raise M8L2DevelopmentError("external NOT_CREATED development coordinate changed") + claims = aggregate.get("development_inputs") + if claims != [_development_session_claim(bundle) for bundle in bundles]: + raise M8L2DevelopmentError("external NOT_CREATED development session authority changed") + campaigns = tuple(_campaign_from_session_bundle(bundle) for bundle in bundles) + if _campaign_dict(campaigns[0]) != _campaign_dict(campaigns[1]) or _campaign_dict( + campaigns[0] + ) != aggregate.get("campaign_identity"): + raise M8L2DevelopmentError("NOT_CREATED campaign identity changed") + campaign = _campaign_dict(campaigns[0]) + if ( + campaign.get("runtime_commit") != producer.commit + or campaign.get("runtime_source_tree_sha256") != producer.source_tree_sha256 + or campaign.get("runtime_dirty") is not False + ): + raise M8L2DevelopmentError("NOT_CREATED source and campaign identities disagree") + reasons = _not_created_reasons(bundles) + if not reasons or aggregate.get("reason_codes") != list(reasons): + raise M8L2DevelopmentError("NOT_CREATED typed reasons changed") + return L2DevelopmentLockResult( + root=root, + aggregate_path=aggregate_path, + aggregate_sha256=aggregate_sha, + marker_path=marker_path, + created_at_utc=created_raw, + children=(), + status="NOT_CREATED", + reason_codes=reasons, + ) + + +def verify_m8_l2_development_lock( + capture_config: M8L2StudyConfig, + analysis_config: M8L2AnalysisConfig, + train_bundle_path: str | Path, + validation_bundle_path: str | Path, + lock_dir: str | Path, + *, + expected_lock_sha256: str | None = None, +) -> L2DevelopmentAuthorityResult: + """Strictly restore either development authority and its external sessions.""" + + capture, analysis = _revalidate_configs(capture_config, analysis_config) + root = Path(lock_dir).absolute() + _reject_symlink_components(root) + try: + if not stat.S_ISDIR(root.lstat().st_mode): + raise M8L2DevelopmentError("development lock is not a regular directory") + except OSError as error: + raise M8L2DevelopmentError("development lock directory is unavailable") from error + files = _walk_regular(root) + terminal_names = [name for name in (_LOCKED_MARKER, _NOT_CREATED_MARKER) if name in files] + if len(terminal_names) != 1: + raise M8L2DevelopmentError("development authority requires exactly one terminal marker") + terminal_name = terminal_names[0] + marker_path = root / terminal_name + expected_marker = _LOCKED_BYTES if terminal_name == _LOCKED_MARKER else _NOT_CREATED_BYTES + if _read_regular(marker_path, label="development marker", maximum=32) != expected_marker: + raise M8L2DevelopmentError("development authority marker bytes differ") + if _CHECKSUMS_NAME not in files or _INVENTORY_NAME not in files: + raise M8L2DevelopmentError("development lock lacks checksum/inventory authority") + checksums = _parse_checksums( + _read_regular(root / _CHECKSUMS_NAME, label="development checksums", maximum=1_000_000) + ) + if set(files) != set(checksums) | {_CHECKSUMS_NAME, terminal_name}: + raise M8L2DevelopmentError("physical development inventory differs from checksums") + for relative, expected_digest in checksums.items(): + if sha256_file(root / relative) != expected_digest: + raise M8L2DevelopmentError(f"development checksum mismatch for {relative}") + inventory, inventory_raw = _read_json(root / _INVENTORY_NAME, "development inventory") + _exact_keys(inventory, {"schema_version", "artifact_kind", "files"}, "inventory") + expected_inventory_kind = ( + "m8_l2_development_lock_inventory" + if terminal_name == _LOCKED_MARKER + else "m8_l2_development_not_created_inventory" + ) + if ( + inventory.get("schema_version") != _INVENTORY_SCHEMA_VERSION + or inventory.get("artifact_kind") != expected_inventory_kind + or _canonical_json_bytes(cast(Mapping[str, object], inventory)) != inventory_raw + ): + raise M8L2DevelopmentError("development inventory authority changed") + inventory_entries = inventory.get("files") + expected_inventory = [ + { + "path": relative, + "sha256": checksums[relative], + "bytes": (root / relative).stat().st_size, + } + for relative in checksums + if relative != _INVENTORY_NAME + ] + if inventory_entries != expected_inventory: + raise M8L2DevelopmentError("development inventory entries are not exact") + + aggregate_path = root / _AGGREGATE_NAME + aggregate, aggregate_raw = _read_json(aggregate_path, "aggregate development lock") + aggregate_sha = hashlib.sha256(aggregate_raw).hexdigest() + if expected_lock_sha256 is not None and aggregate_sha != expected_lock_sha256: + raise M8L2DevelopmentError("aggregate development lock differs from expected SHA-256") + if checksums.get(_AGGREGATE_NAME) != aggregate_sha: + raise M8L2DevelopmentError("checksums do not bind the aggregate development lock") + digest_raw = _read_regular( + root / _AGGREGATE_DIGEST_NAME, + label="aggregate development digest", + maximum=256, + ) + if digest_raw != f"{aggregate_sha} {_AGGREGATE_NAME}\n".encode("ascii"): + raise M8L2DevelopmentError("aggregate development digest sidecar changed") + if _canonical_json_bytes(cast(Mapping[str, object], aggregate)) != aggregate_raw: + raise M8L2DevelopmentError("aggregate development lock is not canonical JSON") + if terminal_name == _NOT_CREATED_MARKER: + return _verify_not_created_aggregate( + capture=capture, + analysis=analysis, + train_bundle_path=train_bundle_path, + validation_bundle_path=validation_bundle_path, + root=root, + marker_path=marker_path, + aggregate_path=aggregate_path, + aggregate_sha=aggregate_sha, + aggregate=aggregate, + ) + _exact_keys( + aggregate, + { + "schema_version", + "artifact_kind", + "study", + "created_at_utc", + "must_precede_utc", + "capture_config_sha256", + "capture_config_source_sha256", + "capture_protocol_sha256", + "analysis_config_sha256", + "analysis_config_source_sha256", + "producer_source_identity", + "campaign_identity", + "development_inputs", + "children", + "regime_thresholds", + "execution_references", + "fit_policy", + "heldout_declarations", + "heldout_access", + "claims", + }, + "aggregate development lock", + ) + if ( + aggregate.get("schema_version") != _LOCK_SCHEMA_VERSION + or aggregate.get("artifact_kind") != "m8_l2_outcome_blind_development_lock" + or aggregate.get("study") != analysis.study.name + or aggregate.get("must_precede_utc") != _LOCK_DEADLINE.isoformat().replace("+00:00", "Z") + or aggregate.get("capture_config_sha256") != capture.hash + or aggregate.get("capture_config_source_sha256") != capture.source_sha256 + or aggregate.get("capture_protocol_sha256") != analysis.study.capture_protocol_sha256 + or aggregate.get("analysis_config_sha256") != analysis.hash + or aggregate.get("analysis_config_source_sha256") != analysis.source_sha256 + or aggregate.get("heldout_declarations") + != [{"date": value[0], "role": value[1]} for value in _EXPECTED_HELDOUT] + or aggregate.get("heldout_access") + != { + "paths_received": False, + "file_hashes_received": False, + "row_counts_received": False, + "economic_rows_opened": False, + "model_fit_or_update_after_lock": False, + } + ): + raise M8L2DevelopmentError("aggregate development contract changed") + created_raw = aggregate.get("created_at_utc") + if type(created_raw) is not str: + raise M8L2DevelopmentError("aggregate creation time is malformed") + try: + created = datetime.fromisoformat(created_raw.replace("Z", "+00:00")) + except ValueError as error: + raise M8L2DevelopmentError("aggregate creation time is malformed") from error + if not _EARLIEST_LOCK_TIME <= created < _LOCK_DEADLINE: + raise M8L2DevelopmentError("aggregate creation time is outside the frozen lock window") + producer_payload = aggregate.get("producer_source_identity") + if not isinstance(producer_payload, Mapping): + raise M8L2DevelopmentError("aggregate producer identity is malformed") + producer = _producer_source_identity(capture.path.parent.parent.resolve()) + _validate_source(producer) + if producer.to_dict() != producer_payload: + raise M8L2DevelopmentError("current producer source differs from development lock") + + input_claims = aggregate.get("development_inputs") + if not isinstance(input_claims, list) or len(input_claims) != 2: + raise M8L2DevelopmentError("aggregate development-input set is malformed") + verifier = _load_input_verifier() + verified_inputs: list[_VerifiedInput] = [] + expected_campaign: object | None = None + for bundle_path, expected_coordinate, claim in zip( + (train_bundle_path, validation_bundle_path), + _EXPECTED_DEVELOPMENT, + input_claims, + strict=True, + ): + if not isinstance(claim, Mapping) or set(claim) != { + "date", + "role", + "session_id", + "file_authority", + }: + raise M8L2DevelopmentError("aggregate development-input claim is malformed") + try: + from microstructure.m8_l2_inputs import L2SessionFileAuthority + + raw_authority = cast(Mapping[str, Any], claim["file_authority"]) + file_authority = L2SessionFileAuthority( + manifest_sha256=str(raw_authority["manifest_sha256"]), + checksums_sha256=str(raw_authority["checksums_sha256"]), + ) + value = verifier( + bundle_path, + expected_config=capture, + expected_date=expected_coordinate[0], + expected_role=expected_coordinate[1], + expected_file_authority=file_authority, + expected_campaign=expected_campaign, + ) + except Exception as error: + raise M8L2DevelopmentError( + "external development-input authority no longer verifies" + ) from error + if ( + value.session_id != claim["session_id"] + or _file_authority_dict(value.file_authority) != claim["file_authority"] + ): + raise M8L2DevelopmentError("external development-input claim changed") + verified_inputs.append(value) + expected_campaign = value.campaign_identity + if _campaign_dict(verified_inputs[0].campaign_identity) != aggregate.get( + "campaign_identity" + ) or _campaign_dict(verified_inputs[1].campaign_identity) != aggregate.get("campaign_identity"): + raise M8L2DevelopmentError("external campaign identity differs from development lock") + + children_raw = aggregate.get("children") + if not isinstance(children_raw, list): + raise M8L2DevelopmentError("aggregate child-lock set is malformed") + expected_children = tuple( + (symbol, endpoint.name) + for symbol in capture.study.symbols + for endpoint in analysis.endpoints + ) + if len(children_raw) != len(expected_children): + raise M8L2DevelopmentError("aggregate child-lock set is incomplete") + children: list[L2DevelopmentChildLock] = [] + for expected_child, raw_claim in zip(expected_children, children_raw, strict=True): + if ( + not isinstance(raw_claim, Mapping) + or (raw_claim.get("symbol"), raw_claim.get("endpoint")) != expected_child + ): + raise M8L2DevelopmentError("aggregate child-lock order changed") + children.append( + _restore_child( + root, + cast(Mapping[str, Any], raw_claim), + capture=capture, + analysis=analysis, + aggregate=aggregate, + ) + ) + _verify_reference_claims(root, aggregate, analysis) + return L2DevelopmentLockResult( + root=root, + aggregate_path=aggregate_path, + aggregate_sha256=aggregate_sha, + marker_path=marker_path, + created_at_utc=created_raw, + children=tuple(children), + ) + + +__all__ = [ + "L2DevelopmentAuthorityResult", + "L2DevelopmentChildLock", + "L2DevelopmentInputVerifier", + "L2DevelopmentLockResult", + "M8L2DevelopmentError", + "ProducerSourceIdentity", + "lock_m8_l2_development", + "verify_m8_l2_development_lock", +] diff --git a/Microstructure/src/microstructure/m8_l2_inputs.py b/Microstructure/src/microstructure/m8_l2_inputs.py new file mode 100644 index 0000000000000000000000000000000000000000..0cf0081b1f6e7961ed6f3d3f49e01b146bf9abf4 --- /dev/null +++ b/Microstructure/src/microstructure/m8_l2_inputs.py @@ -0,0 +1,1068 @@ +"""Strict, phase-separated inputs for the frozen prospective M8 L2 study. + +The capture verifier remains the authority for a complete session bundle. This +module adds the narrower research-input boundary: it binds an optional external +manifest/checksum digest, exposes only explicitly inventoried symbol artifacts, +and reopens Parquet through a no-follow directory/file-descriptor chain whenever +payload rows are requested. + +Development and held-out entry points are intentionally separate. A held-out +object cannot be constructed without the digest of an already verified +development lock; this module does not inspect or interpret that lock. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import stat +from collections.abc import Mapping +from dataclasses import dataclass, field +from pathlib import Path, PurePosixPath +from types import MappingProxyType +from typing import Any, Literal, cast + +import polars as pl +import pyarrow as pa # type: ignore[import-untyped] +import pyarrow.parquet as pq # type: ignore[import-untyped] + +from microstructure.data.schemas import SCHEMA_VERSION, ensure_schema, get_schema +from microstructure.m8_l2_capture import ( + M8L2SessionBundle, + M8L2VerificationError, + verify_m8_l2_session_bundle, +) +from microstructure.m8_l2_config import M8L2StudyConfig +from microstructure.research.l2_multidate import L2ObservedInterval + +DevelopmentRole = Literal["train", "validation"] +HeldoutRole = Literal["primary_test", "replication_test"] +L2InputAccessPhase = Literal["development", "heldout_after_lock"] + +_CHECKSUM_NAME = "CHECKSUMS.sha256" +_MANIFEST_NAME = "session_manifest.json" +_READ_CHUNK_BYTES = 1 << 20 +_MAX_JSON_BYTES = 8 << 20 +_MAX_CHECKSUM_BYTES = 8 << 20 +_MAX_PARQUET_FILE_BYTES = 2 << 30 +_MAX_PARQUET_UNCOMPRESSED_BYTES = 4 << 30 +_MAX_COMBINED_UNCOMPRESSED_BYTES = 6 << 30 +_MAX_PARQUET_FOOTER_BYTES = 8 << 20 +_VERIFIED_INPUT_TOKEN = object() + + +class M8L2InputError(M8L2VerificationError): + """Raised when a verified capture is not a safe, phase-correct input.""" + + +def _is_sha256(value: str) -> bool: + return len(value) == 64 and all(character in "0123456789abcdef" for character in value) + + +def _require_sha256(value: str, label: str) -> None: + if not _is_sha256(value): + raise M8L2InputError(f"{label} must be a lowercase SHA-256") + + +@dataclass(frozen=True, slots=True) +class L2SessionFileAuthority: + """External/discovered digest authority for the two session control files.""" + + manifest_sha256: str + checksums_sha256: str + + def __post_init__(self) -> None: + _require_sha256(self.manifest_sha256, "session manifest authority") + _require_sha256(self.checksums_sha256, "session checksum-file authority") + + def to_dict(self) -> dict[str, object]: + return { + "manifest_sha256": self.manifest_sha256, + "checksums_sha256": self.checksums_sha256, + } + + +@dataclass(frozen=True, slots=True) +class L2CampaignRuntimeIdentity: + """Campaign identity that must compare equal across all four sessions.""" + + campaign_authority_sha256: str + runtime_commit: str + runtime_source_tree_sha256: str + runtime_fingerprint_sha256: str + runtime_dirty: bool + + def __post_init__(self) -> None: + _require_sha256(self.campaign_authority_sha256, "campaign authority") + if len(self.runtime_commit) != 40 or any( + character not in "0123456789abcdef" for character in self.runtime_commit + ): + raise M8L2InputError("campaign runtime commit must be a lowercase Git SHA-1") + _require_sha256(self.runtime_source_tree_sha256, "campaign runtime source tree") + _require_sha256(self.runtime_fingerprint_sha256, "campaign runtime fingerprint") + if self.runtime_dirty: + raise M8L2InputError("campaign runtime identity must be clean") + + def to_dict(self) -> dict[str, object]: + return { + "campaign_authority_sha256": self.campaign_authority_sha256, + "runtime_commit": self.runtime_commit, + "runtime_source_tree_sha256": self.runtime_source_tree_sha256, + "runtime_fingerprint_sha256": self.runtime_fingerprint_sha256, + "runtime_dirty": self.runtime_dirty, + } + + +@dataclass(frozen=True, slots=True) +class VerifiedL2Artifact: + """One exact session-relative artifact coordinate.""" + + relative_path: str + kind: str + sha256: str + bytes: int + rows: int | None = None + dataset: str | None = None + + def __post_init__(self) -> None: + _safe_relative(self.relative_path) + if not self.kind: + raise M8L2InputError("artifact kind must not be empty") + _require_sha256(self.sha256, "artifact digest") + if self.bytes < 0: + raise M8L2InputError("artifact byte count must be nonnegative") + if self.rows is not None and self.rows < 0: + raise M8L2InputError("artifact row count must be nonnegative") + + def to_dict(self) -> dict[str, object]: + return { + "relative_path": self.relative_path, + "kind": self.kind, + "sha256": self.sha256, + "bytes": self.bytes, + "rows": self.rows, + "dataset": self.dataset, + } + + +@dataclass(frozen=True, slots=True) +class VerifiedL2SymbolInput: + """Exact research-relevant artifacts and claims for one symbol.""" + + symbol: str + capture_id: str + normalized_rows: int + reconstructed_rows: int + excluded_rows: int + valid_observed_intervals: tuple[L2ObservedInterval, ...] + raw_journal: VerifiedL2Artifact + capture_summary: VerifiedL2Artifact + depth_deltas: VerifiedL2Artifact + book_observations: VerifiedL2Artifact + + +@dataclass(frozen=True, slots=True) +class LoadedL2SymbolFrames: + """The only payload opened by the research producer for one symbol/session.""" + + book_observations: pl.DataFrame + depth_deltas: pl.DataFrame + intervals: tuple[L2ObservedInterval, ...] + + +@dataclass(frozen=True, slots=True) +class _RootIdentity: + device: int + inode: int + + +@dataclass(frozen=True, slots=True) +class VerifiedL2SessionInput: + """Verified authority with an explicitly phase-authorized payload loader.""" + + root: Path + session_id: str + session_date: str + role: str + config_sha256: str + config_source_sha256: str + file_authority: L2SessionFileAuthority + campaign_identity: L2CampaignRuntimeIdentity + symbols: Mapping[str, VerifiedL2SymbolInput] + access_phase: L2InputAccessPhase + development_lock_sha256: str | None + _root_identity: _RootIdentity = field(repr=False, compare=False) + _expected_paths: frozenset[str] = field(repr=False, compare=False) + _session_start_ns: int = field(repr=False, compare=False) + _session_end_ns: int = field(repr=False, compare=False) + _verification_token: object = field(repr=False, compare=False) + + def load_symbol_frames(self, symbol: str) -> LoadedL2SymbolFrames: + """Load exactly one requested symbol after revalidating immutable evidence.""" + + if self._verification_token is not _VERIFIED_INPUT_TOKEN: + raise M8L2InputError("L2 payload loading requires a verifier-created input object") + descriptor = self.symbols.get(symbol) + if descriptor is None: + raise M8L2InputError(f"symbol {symbol!r} is not in verified session {self.session_id}") + _assert_inventory( + self.root, + expected_root=self._root_identity, + expected_paths=self._expected_paths, + ) + _verify_artifact_hash( + self.root, + expected_root=self._root_identity, + artifact=descriptor.raw_journal, + ) + _verify_artifact_hash( + self.root, + expected_root=self._root_identity, + artifact=descriptor.capture_summary, + ) + books, books_uncompressed = _load_verified_parquet( + self.root, + expected_root=self._root_identity, + artifact=descriptor.book_observations, + ) + deltas, deltas_uncompressed = _load_verified_parquet( + self.root, + expected_root=self._root_identity, + artifact=descriptor.depth_deltas, + ) + if books_uncompressed + deltas_uncompressed > _MAX_COMBINED_UNCOMPRESSED_BYTES: + raise M8L2InputError("requested symbol Parquet payload exceeds the memory bound") + _validate_loaded_frames( + books, + deltas, + descriptor=descriptor, + session_start_ns=self._session_start_ns, + session_end_ns=self._session_end_ns, + ) + _assert_inventory( + self.root, + expected_root=self._root_identity, + expected_paths=self._expected_paths, + ) + return LoadedL2SymbolFrames( + book_observations=books, + depth_deltas=deltas, + intervals=descriptor.valid_observed_intervals, + ) + + +def _safe_relative(value: str) -> tuple[str, ...]: + if not value or "\\" in value or "\x00" in value: + raise M8L2InputError("artifact path is not a safe POSIX relative path") + pure = PurePosixPath(value) + if pure.is_absolute() or any(part in {"", ".", ".."} for part in pure.parts): + raise M8L2InputError("artifact path is not a safe POSIX relative path") + if pure.as_posix() != value: + raise M8L2InputError("artifact path is not canonical") + return pure.parts + + +def _absolute_without_resolve(value: str | Path) -> Path: + return Path(os.path.abspath(os.fspath(value))) + + +def _directory_flags() -> int: + return ( + os.O_RDONLY + | getattr(os, "O_DIRECTORY", 0) + | getattr(os, "O_NOFOLLOW", 0) + | getattr(os, "O_CLOEXEC", 0) + ) + + +def _open_root(root: Path, expected: _RootIdentity | None = None) -> int: + """Open every absolute-path directory component without following a link.""" + + if not root.is_absolute(): + raise M8L2InputError("session root must be absolute") + descriptor = os.open(root.anchor, _directory_flags()) + try: + for part in root.parts[1:]: + next_descriptor = os.open(part, _directory_flags(), dir_fd=descriptor) + os.close(descriptor) + descriptor = next_descriptor + metadata = os.fstat(descriptor) + if not stat.S_ISDIR(metadata.st_mode): + raise M8L2InputError("session root is not a directory") + observed = _RootIdentity(metadata.st_dev, metadata.st_ino) + if expected is not None and observed != expected: + raise M8L2InputError("session root identity changed after verification") + return descriptor + except (OSError, M8L2InputError): + os.close(descriptor) + raise + + +def _open_relative(root_descriptor: int, relative: str) -> tuple[int, int, str]: + parts = _safe_relative(relative) + directory = os.dup(root_descriptor) + try: + for part in parts[:-1]: + next_directory = os.open(part, _directory_flags(), dir_fd=directory) + os.close(directory) + directory = next_directory + flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0) + descriptor = os.open(parts[-1], flags, dir_fd=directory) + return directory, descriptor, parts[-1] + except OSError: + os.close(directory) + raise + + +def _same_metadata(left: os.stat_result, right: os.stat_result) -> bool: + return ( + left.st_dev, + left.st_ino, + left.st_mode, + left.st_size, + left.st_mtime_ns, + left.st_ctime_ns, + ) == ( + right.st_dev, + right.st_ino, + right.st_mode, + right.st_size, + right.st_mtime_ns, + right.st_ctime_ns, + ) + + +def _assert_still_named( + parent_descriptor: int, + leaf: str, + expected: os.stat_result, + *, + label: str, +) -> None: + current = os.stat(leaf, dir_fd=parent_descriptor, follow_symlinks=False) + if not stat.S_ISREG(current.st_mode) or not _same_metadata(expected, current): + raise M8L2InputError(f"{label} path changed during its descriptor snapshot") + + +def _hash_descriptor(descriptor: int, maximum_bytes: int) -> tuple[str, int]: + os.lseek(descriptor, 0, os.SEEK_SET) + digest = hashlib.sha256() + total = 0 + remaining = maximum_bytes + 1 + while remaining: + chunk = os.read(descriptor, min(_READ_CHUNK_BYTES, remaining)) + if not chunk: + break + total += len(chunk) + digest.update(chunk) + remaining -= len(chunk) + return digest.hexdigest(), total + + +def _read_control_file( + root: Path, + *, + expected_root: _RootIdentity | None, + relative: str, + maximum_bytes: int, +) -> tuple[bytes, _RootIdentity]: + root_descriptor = _open_root(root, expected_root) + try: + root_metadata = os.fstat(root_descriptor) + root_identity = _RootIdentity(root_metadata.st_dev, root_metadata.st_ino) + parent, descriptor, leaf = _open_relative(root_descriptor, relative) + try: + before = os.fstat(descriptor) + if ( + not stat.S_ISREG(before.st_mode) + or before.st_size < 1 + or before.st_size > maximum_bytes + ): + raise M8L2InputError(f"{relative} is not a bounded nonempty regular file") + chunks: list[bytes] = [] + os.lseek(descriptor, 0, os.SEEK_SET) + remaining = maximum_bytes + 1 + while remaining: + chunk = os.read(descriptor, min(_READ_CHUNK_BYTES, remaining)) + if not chunk: + break + chunks.append(chunk) + remaining -= len(chunk) + raw = b"".join(chunks) + after = os.fstat(descriptor) + _assert_still_named(parent, leaf, after, label=relative) + if len(raw) != before.st_size or not _same_metadata(before, after): + raise M8L2InputError(f"{relative} changed during its bounded read") + return raw, root_identity + finally: + os.close(descriptor) + os.close(parent) + except OSError as error: + raise M8L2InputError(f"cannot securely read session control file {relative}") from error + finally: + os.close(root_descriptor) + + +def _secure_inventory(root: Path, expected_root: _RootIdentity) -> frozenset[str]: + root_descriptor = _open_root(root, expected_root) + + def visit(descriptor: int, prefix: tuple[str, ...]) -> list[str]: + result: list[str] = [] + try: + names = sorted(os.listdir(descriptor)) + except OSError as error: + raise M8L2InputError("cannot enumerate explicit session bundle") from error + for name in names: + if not name or "/" in name or "\x00" in name: + raise M8L2InputError("session bundle contains an unsafe directory entry") + try: + metadata = os.stat(name, dir_fd=descriptor, follow_symlinks=False) + except OSError as error: + raise M8L2InputError("session inventory changed during enumeration") from error + relative_parts = (*prefix, name) + if stat.S_ISREG(metadata.st_mode): + result.append(PurePosixPath(*relative_parts).as_posix()) + elif stat.S_ISDIR(metadata.st_mode): + try: + child = os.open(name, _directory_flags(), dir_fd=descriptor) + except OSError as error: + raise M8L2InputError("cannot securely descend session directory") from error + try: + result.extend(visit(child, relative_parts)) + finally: + os.close(child) + else: + raise M8L2InputError("session bundle contains a symlink or special file") + return result + + try: + return frozenset(visit(root_descriptor, ())) + finally: + os.close(root_descriptor) + + +def _assert_inventory( + root: Path, *, expected_root: _RootIdentity, expected_paths: frozenset[str] +) -> None: + observed = _secure_inventory(root, expected_root) + if observed != expected_paths: + raise M8L2InputError( + "session inventory changed after verification " + f"(missing={sorted(expected_paths - observed)}, " + f"extra={sorted(observed - expected_paths)})" + ) + + +def _json_object(raw: bytes, label: str) -> Mapping[str, Any]: + try: + value = json.loads(raw.decode("utf-8")) + except (UnicodeError, json.JSONDecodeError) as error: + raise M8L2InputError(f"cannot parse {label}") from error + if not isinstance(value, Mapping) or not all(type(key) is str for key in value): + raise M8L2InputError(f"{label} must be a JSON object") + return cast(Mapping[str, Any], value) + + +def _parse_checksums(raw: bytes) -> dict[str, str]: + try: + lines = raw.decode("ascii").splitlines(keepends=True) + except UnicodeError as error: + raise M8L2InputError("session checksum authority must be ASCII") from error + result: dict[str, str] = {} + for line in lines: + if len(line) < 68 or not line.endswith("\n") or line[64:66] != " ": + raise M8L2InputError("session checksum authority has a malformed line") + digest = line[:64] + relative = line[66:-1] + _require_sha256(digest, "session checksum entry") + _safe_relative(relative) + if relative in result: + raise M8L2InputError("session checksum authority repeats a path") + result[relative] = digest + if not result or list(result) != sorted(result): + raise M8L2InputError("session checksum authority is empty or not canonically ordered") + return result + + +def _mapping(value: object, label: str) -> Mapping[str, Any]: + if not isinstance(value, Mapping) or not all(type(key) is str for key in value): + raise M8L2InputError(f"{label} must be an object") + return cast(Mapping[str, Any], value) + + +def _integer(value: object, label: str) -> int: + if type(value) is not int or value < 0: + raise M8L2InputError(f"{label} must be a nonnegative integer") + return value + + +def _artifact_entries( + symbol_payload: Mapping[str, Any], symbol: str +) -> dict[str, VerifiedL2Artifact]: + raw = symbol_payload.get("artifacts") + if not isinstance(raw, list): + raise M8L2InputError(f"symbol {symbol} lacks its artifact inventory") + result: dict[str, VerifiedL2Artifact] = {} + for value in raw: + entry = _mapping(value, f"{symbol} artifact") + relative = entry.get("path") + kind = entry.get("kind") + digest = entry.get("sha256") + size = entry.get("bytes") + if ( + type(relative) is not str + or type(kind) is not str + or type(digest) is not str + or type(size) is not int + ): + raise M8L2InputError(f"symbol {symbol} has a malformed artifact") + artifact = VerifiedL2Artifact( + relative_path=relative, + kind=kind, + sha256=digest, + bytes=size, + ) + if relative in result: + raise M8L2InputError(f"symbol {symbol} repeats an artifact coordinate") + result[relative] = artifact + return result + + +def _one_kind( + artifacts: Mapping[str, VerifiedL2Artifact], *, kind: str, symbol: str +) -> VerifiedL2Artifact: + matches = [item for item in artifacts.values() if item.kind == kind] + if len(matches) != 1: + raise M8L2InputError(f"symbol {symbol} must have exactly one {kind} artifact") + return matches[0] + + +def _symbol_relative(symbol: str, value: object) -> str: + if type(value) is not str: + raise M8L2InputError(f"symbol {symbol} summary path must be a string") + parts = _safe_relative(value) + return PurePosixPath("symbols", symbol, *parts).as_posix() + + +def _normalized_artifact( + *, + symbol: str, + dataset: str, + summary: Mapping[str, Any], + artifacts: Mapping[str, VerifiedL2Artifact], +) -> VerifiedL2Artifact: + datasets = _mapping(summary.get("normalized_dataset_manifests"), "normalized manifests") + entry = _mapping(datasets.get(dataset), f"normalized manifest {dataset}") + rows = _integer(entry.get("rows"), f"{dataset} rows") + relative = _symbol_relative(symbol, entry.get("data_path")) + artifact = artifacts.get(relative) + if artifact is None or artifact.kind != "normalized_data": + raise M8L2InputError(f"symbol {symbol} {dataset} data is not exactly inventoried") + if entry.get("data_sha256") != artifact.sha256: + raise M8L2InputError(f"symbol {symbol} {dataset} digest claims disagree") + return VerifiedL2Artifact( + relative_path=artifact.relative_path, + kind=artifact.kind, + sha256=artifact.sha256, + bytes=artifact.bytes, + rows=rows, + dataset=dataset, + ) + + +def _parse_intervals( + symbol_payload: Mapping[str, Any], *, symbol: str, start_ns: int, end_ns: int +) -> tuple[L2ObservedInterval, ...]: + raw = symbol_payload.get("valid_observed_intervals") + if not isinstance(raw, list) or not raw: + raise M8L2InputError(f"symbol {symbol} lacks valid OBSERVED intervals") + intervals: list[L2ObservedInterval] = [] + prior_end = -1 + for value in raw: + entry = _mapping(value, f"symbol {symbol} interval") + continuity = entry.get("continuity_id") + interval_start = entry.get("start_received_ns") + interval_end = entry.get("end_received_ns_exclusive") + if ( + type(continuity) is not str + or type(interval_start) is not int + or type(interval_end) is not int + ): + raise M8L2InputError(f"symbol {symbol} has a malformed OBSERVED interval") + interval = L2ObservedInterval(continuity, interval_start, interval_end) + if interval.start_received_ns < start_ns or interval.end_received_ns_exclusive > end_ns: + raise M8L2InputError(f"symbol {symbol} OBSERVED interval escapes its session") + if interval.start_received_ns < prior_end: + raise M8L2InputError(f"symbol {symbol} OBSERVED intervals overlap") + prior_end = interval.end_received_ns_exclusive + intervals.append(interval) + return tuple(intervals) + + +def _symbol_descriptor( + root: Path, + *, + expected_root: _RootIdentity, + symbol: str, + payload: Mapping[str, Any], + start_ns: int, + end_ns: int, +) -> VerifiedL2SymbolInput: + artifacts = _artifact_entries(payload, symbol) + capture_summary = _one_kind(artifacts, kind="capture_summary", symbol=symbol) + raw_journal = _one_kind(artifacts, kind="raw_journal", symbol=symbol) + summary_raw, _ = _read_control_file( + root, + expected_root=expected_root, + relative=capture_summary.relative_path, + maximum_bytes=_MAX_JSON_BYTES, + ) + if hashlib.sha256(summary_raw).hexdigest() != capture_summary.sha256: + raise M8L2InputError(f"symbol {symbol} capture summary digest changed") + summary = _json_object(summary_raw, f"symbol {symbol} capture summary") + if summary.get("symbol") != symbol or summary.get("capture_id") != payload.get("capture_id"): + raise M8L2InputError(f"symbol {symbol} capture summary identity differs") + depth = _normalized_artifact( + symbol=symbol, + dataset="depth_deltas", + summary=summary, + artifacts=artifacts, + ) + books = _normalized_artifact( + symbol=symbol, + dataset="book_observations", + summary=summary, + artifacts=artifacts, + ) + normalized_rows = _integer(payload.get("normalized_rows"), f"{symbol} normalized_rows") + reconstructed_rows = _integer(payload.get("reconstructed_rows"), f"{symbol} reconstructed_rows") + excluded_rows = _integer(payload.get("excluded_rows"), f"{symbol} excluded_rows") + if ( + depth.rows != normalized_rows + or books.rows != reconstructed_rows + or normalized_rows != reconstructed_rows + excluded_rows + ): + raise M8L2InputError(f"symbol {symbol} normalized row claims do not reconcile") + capture_id = payload.get("capture_id") + if type(capture_id) is not str or not capture_id: + raise M8L2InputError(f"symbol {symbol} capture_id is invalid") + intervals = _parse_intervals(payload, symbol=symbol, start_ns=start_ns, end_ns=end_ns) + return VerifiedL2SymbolInput( + symbol=symbol, + capture_id=capture_id, + normalized_rows=normalized_rows, + reconstructed_rows=reconstructed_rows, + excluded_rows=excluded_rows, + valid_observed_intervals=intervals, + raw_journal=raw_journal, + capture_summary=capture_summary, + depth_deltas=depth, + book_observations=books, + ) + + +def _load_verified_parquet( + root: Path, + *, + expected_root: _RootIdentity, + artifact: VerifiedL2Artifact, +) -> tuple[pl.DataFrame, int]: + if artifact.dataset not in {"book_observations", "depth_deltas"} or artifact.rows is None: + raise M8L2InputError("requested artifact is not a research Parquet input") + if artifact.bytes < 12 or artifact.bytes > _MAX_PARQUET_FILE_BYTES: + raise M8L2InputError(f"{artifact.dataset} Parquet exceeds its physical byte bound") + root_descriptor = _open_root(root, expected_root) + try: + parent, descriptor, leaf = _open_relative(root_descriptor, artifact.relative_path) + try: + before = os.fstat(descriptor) + if not stat.S_ISREG(before.st_mode) or before.st_size != artifact.bytes: + raise M8L2InputError(f"{artifact.dataset} is not its claimed regular file") + if os.pread(descriptor, 4, 0) != b"PAR1": + raise M8L2InputError(f"{artifact.dataset} lacks its Parquet header") + trailer = os.pread(descriptor, 8, before.st_size - 8) + if len(trailer) != 8 or trailer[4:] != b"PAR1": + raise M8L2InputError(f"{artifact.dataset} lacks its Parquet trailer") + footer_bytes = int.from_bytes(trailer[:4], "little") + if footer_bytes > _MAX_PARQUET_FOOTER_BYTES or footer_bytes + 12 > before.st_size: + raise M8L2InputError(f"{artifact.dataset} Parquet footer exceeds its bound") + first_digest, first_bytes = _hash_descriptor(descriptor, artifact.bytes) + if first_digest != artifact.sha256 or first_bytes != artifact.bytes: + raise M8L2InputError(f"{artifact.dataset} Parquet digest/bytes changed") + os.lseek(descriptor, 0, os.SEEK_SET) + with os.fdopen(os.dup(descriptor), "rb") as handle: + parquet = pq.ParquetFile(handle) + if parquet.metadata.num_rows != artifact.rows: + raise M8L2InputError(f"{artifact.dataset} footer row count differs") + expected_schema = get_schema(artifact.dataset) + # Parquet canonicalizes list child names (``item`` -> ``element``) + # on read, so Arrow's normal structural equality is the registry + # contract; frozen schema metadata is checked explicitly below. + if parquet.schema_arrow != expected_schema: + raise M8L2InputError(f"{artifact.dataset} Parquet schema differs") + metadata = parquet.schema_arrow.metadata or {} + if ( + metadata.get(b"schema_name") != artifact.dataset.encode() + or metadata.get(b"schema_version") != SCHEMA_VERSION.encode() + ): + raise M8L2InputError(f"{artifact.dataset} schema metadata differs") + uncompressed = sum( + parquet.metadata.row_group(index).total_byte_size + for index in range(parquet.metadata.num_row_groups) + ) + if uncompressed > _MAX_PARQUET_UNCOMPRESSED_BYTES: + raise M8L2InputError( + f"{artifact.dataset} Parquet uncompressed payload exceeds its bound" + ) + table = parquet.read() + ensure_schema(table, artifact.dataset) + if table.num_rows != artifact.rows: + raise M8L2InputError(f"{artifact.dataset} materialized row count differs") + if table.nbytes > _MAX_PARQUET_UNCOMPRESSED_BYTES: + raise M8L2InputError( + f"{artifact.dataset} materialized payload exceeds its memory bound" + ) + second_digest, second_bytes = _hash_descriptor(descriptor, artifact.bytes) + after = os.fstat(descriptor) + _assert_still_named(parent, leaf, after, label=artifact.relative_path) + if ( + second_digest != artifact.sha256 + or second_bytes != artifact.bytes + or not _same_metadata(before, after) + ): + raise M8L2InputError(f"{artifact.dataset} changed during its descriptor snapshot") + frame = pl.from_arrow(cast(pa.Table, table)) + if not isinstance(frame, pl.DataFrame): # pragma: no cover - Arrow table overload + raise M8L2InputError(f"{artifact.dataset} did not materialize as a frame") + return frame, uncompressed + finally: + os.close(descriptor) + os.close(parent) + except M8L2InputError: + raise + except (OSError, pa.ArrowException, ValueError) as error: + raise M8L2InputError(f"cannot securely load {artifact.dataset} Parquet") from error + finally: + os.close(root_descriptor) + + +def _verify_artifact_hash( + root: Path, + *, + expected_root: _RootIdentity, + artifact: VerifiedL2Artifact, +) -> None: + """Rebind one requested-symbol lineage artifact through a stable descriptor.""" + + root_descriptor = _open_root(root, expected_root) + try: + parent, descriptor, leaf = _open_relative(root_descriptor, artifact.relative_path) + try: + before = os.fstat(descriptor) + if not stat.S_ISREG(before.st_mode) or before.st_size != artifact.bytes: + raise M8L2InputError(f"{artifact.kind} is not its claimed regular file") + digest, total = _hash_descriptor(descriptor, artifact.bytes) + after = os.fstat(descriptor) + _assert_still_named(parent, leaf, after, label=artifact.relative_path) + if ( + digest != artifact.sha256 + or total != artifact.bytes + or not _same_metadata(before, after) + ): + raise M8L2InputError( + f"{artifact.kind} changed during its bounded descriptor snapshot" + ) + finally: + os.close(descriptor) + os.close(parent) + except M8L2InputError: + raise + except OSError as error: + raise M8L2InputError(f"cannot securely verify {artifact.kind}") from error + finally: + os.close(root_descriptor) + + +def _all_true(frame: pl.DataFrame, expression: pl.Expr) -> bool: + value = frame.select(expression.all()).item() + return value is True + + +def _validate_loaded_frames( + books: pl.DataFrame, + deltas: pl.DataFrame, + *, + descriptor: VerifiedL2SymbolInput, + session_start_ns: int, + session_end_ns: int, +) -> None: + if books.height != descriptor.reconstructed_rows or deltas.height != descriptor.normalized_rows: + raise M8L2InputError(f"symbol {descriptor.symbol} materialized rows do not reconcile") + if deltas.height - books.height != descriptor.excluded_rows: + raise M8L2InputError(f"symbol {descriptor.symbol} excluded rows do not reconcile") + for label, frame in (("book_observations", books), ("depth_deltas", deltas)): + if frame.is_empty(): + raise M8L2InputError(f"symbol {descriptor.symbol} {label} is empty") + if ( + frame.get_column("symbol").null_count() + or frame.get_column("continuity_id").null_count() + ): + raise M8L2InputError(f"symbol {descriptor.symbol} {label} lacks live identity") + if frame.get_column("symbol").unique().to_list() != [descriptor.symbol]: + raise M8L2InputError(f"symbol {descriptor.symbol} {label} contains another symbol") + if not _all_true( + frame, + (pl.col("available_ts_ns") >= session_start_ns) + & (pl.col("available_ts_ns") < session_end_ns) + & pl.col("received_ts_ns").is_not_null() + & (pl.col("available_ts_ns") >= pl.col("received_ts_ns")), + ): + raise M8L2InputError(f"symbol {descriptor.symbol} {label} escapes session timing") + if not _all_true( + books, + pl.col("is_valid") + & (pl.col("sequence_start") <= pl.col("sequence_end")) + & (pl.col("best_bid") < pl.col("best_ask")), + ): + raise M8L2InputError(f"symbol {descriptor.symbol} book observations are invalid") + if not _all_true(deltas, pl.col("first_update_id") <= pl.col("last_update_id")): + raise M8L2InputError(f"symbol {descriptor.symbol} depth sequences are invalid") + + delta_keys = deltas.select( + "continuity_id", + pl.col("first_update_id").alias("sequence_start"), + pl.col("last_update_id").alias("sequence_end"), + "available_ts_ns", + ).unique() + reconciled = books.select( + "continuity_id", "sequence_start", "sequence_end", "available_ts_ns" + ).join( + delta_keys, + on=["continuity_id", "sequence_start", "sequence_end", "available_ts_ns"], + how="anti", + ) + if reconciled.height: + raise M8L2InputError( + f"symbol {descriptor.symbol} book rows do not reconcile to normalized deltas" + ) + + for interval in descriptor.valid_observed_intervals: + book_slice = books.filter( + (pl.col("continuity_id") == interval.continuity_id) + & (pl.col("available_ts_ns") >= interval.start_received_ns) + & (pl.col("available_ts_ns") < interval.end_received_ns_exclusive) + ) + delta_slice = deltas.filter( + (pl.col("continuity_id") == interval.continuity_id) + & (pl.col("available_ts_ns") >= interval.start_received_ns) + & (pl.col("available_ts_ns") < interval.end_received_ns_exclusive) + ) + if book_slice.is_empty() or delta_slice.is_empty(): + raise M8L2InputError( + f"symbol {descriptor.symbol} OBSERVED interval lacks reconciled rows" + ) + + +def _verify_input( + bundle_dir: str | Path, + *, + expected_config: M8L2StudyConfig, + expected_date: str, + expected_role: str, + access_phase: L2InputAccessPhase, + development_lock_sha256: str | None, + expected_file_authority: L2SessionFileAuthority | None, + expected_campaign: L2CampaignRuntimeIdentity | None, +) -> VerifiedL2SessionInput: + root = _absolute_without_resolve(bundle_dir) + try: + bundle: M8L2SessionBundle = verify_m8_l2_session_bundle( + root, expected_config=expected_config + ) + except M8L2VerificationError as error: + raise M8L2InputError(f"session capture authority failed verification: {error}") from error + if bundle.status != "COMPLETE" or bundle.reason_codes: + raise M8L2InputError("L2 research inputs require a gate-complete session") + if bundle.root != root: + raise M8L2InputError("capture verifier returned a different session root") + if bundle.session_date != expected_date or bundle.role != expected_role: + raise M8L2InputError("session date/role differs from the requested frozen coordinate") + + manifest_raw, root_identity = _read_control_file( + root, + expected_root=None, + relative=_MANIFEST_NAME, + maximum_bytes=_MAX_JSON_BYTES, + ) + checksums_raw, repeated_root = _read_control_file( + root, + expected_root=root_identity, + relative=_CHECKSUM_NAME, + maximum_bytes=_MAX_CHECKSUM_BYTES, + ) + if repeated_root != root_identity: + raise M8L2InputError("session root changed while binding control authority") + manifest_sha256 = hashlib.sha256(manifest_raw).hexdigest() + checksums_sha256 = hashlib.sha256(checksums_raw).hexdigest() + discovered_authority = L2SessionFileAuthority(manifest_sha256, checksums_sha256) + if manifest_sha256 != bundle.manifest_sha256: + raise M8L2InputError("secure manifest snapshot differs from capture verifier authority") + if expected_file_authority is not None and discovered_authority != expected_file_authority: + raise M8L2InputError("session control files differ from external digest authority") + checksums = _parse_checksums(checksums_raw) + if checksums.get(_MANIFEST_NAME) != manifest_sha256: + raise M8L2InputError("session checksum file does not bind its manifest") + + payload = _json_object(manifest_raw, "session manifest") + if payload.get("status") != "COMPLETE" or payload.get("reason_codes") != []: + raise M8L2InputError("session manifest is not gate-complete") + gates = payload.get("gates") + if ( + not isinstance(gates, list) + or len(gates) != 29 + or any(not isinstance(item, Mapping) or item.get("passed") is not True for item in gates) + ): + raise M8L2InputError("session does not contain the 29 passing frozen gates") + session_payload = _mapping(payload.get("session"), "session coordinates") + if session_payload.get("date") != expected_date or session_payload.get("role") != expected_role: + raise M8L2InputError("manifest session coordinate differs from its requested role") + expected_session = expected_config.session_for_date(expected_date) + if expected_session.role != expected_role: + raise M8L2InputError("requested role differs from the frozen calendar") + start_ns = expected_session.start_ns + end_ns = expected_session.end_ns + if ( + session_payload.get("scheduled_start_ns") != start_ns + or session_payload.get("scheduled_end_ns") != end_ns + ): + raise M8L2InputError("manifest time bounds differ from the frozen calendar") + + authority = _mapping(payload.get("authority"), "session campaign authority") + campaign = L2CampaignRuntimeIdentity( + campaign_authority_sha256=str(authority.get("campaign_authority_sha256")), + runtime_commit=str(authority.get("runtime_commit")), + runtime_source_tree_sha256=str(authority.get("runtime_source_tree_sha256")), + runtime_fingerprint_sha256=str(authority.get("runtime_fingerprint_sha256")), + runtime_dirty=authority.get("runtime_dirty") is not False, + ) + if expected_campaign is not None and campaign != expected_campaign: + raise M8L2InputError("session campaign/runtime identity differs from prior authority") + config_sha256 = authority.get("config_sha256") + config_source_sha256 = authority.get("config_source_sha256") + if ( + config_sha256 != expected_config.hash + or config_source_sha256 != expected_config.source_sha256 + ): + raise M8L2InputError("session configuration identity differs from the caller authority") + + symbols_payload = _mapping(payload.get("symbols"), "session symbols") + if set(symbols_payload) != set(expected_config.study.symbols): + raise M8L2InputError("session does not contain the exact frozen symbol pair") + descriptors = { + symbol: _symbol_descriptor( + root, + expected_root=root_identity, + symbol=symbol, + payload=_mapping(symbols_payload[symbol], f"symbol {symbol}"), + start_ns=start_ns, + end_ns=end_ns, + ) + for symbol in expected_config.study.symbols + } + + expected_marker = "_SUCCESS" + expected_paths = frozenset({*checksums, _CHECKSUM_NAME, expected_marker}) + _assert_inventory(root, expected_root=root_identity, expected_paths=expected_paths) + return VerifiedL2SessionInput( + root=root, + session_id=bundle.session_id, + session_date=expected_date, + role=expected_role, + config_sha256=cast(str, config_sha256), + config_source_sha256=cast(str, config_source_sha256), + file_authority=discovered_authority, + campaign_identity=campaign, + symbols=MappingProxyType(descriptors), + access_phase=access_phase, + development_lock_sha256=development_lock_sha256, + _root_identity=root_identity, + _expected_paths=expected_paths, + _session_start_ns=start_ns, + _session_end_ns=end_ns, + _verification_token=_VERIFIED_INPUT_TOKEN, + ) + + +def verify_m8_l2_development_input( + bundle_dir: str | Path, + *, + expected_config: M8L2StudyConfig, + expected_date: str, + expected_role: DevelopmentRole, + expected_file_authority: L2SessionFileAuthority | None = None, + expected_campaign: L2CampaignRuntimeIdentity | None = None, +) -> VerifiedL2SessionInput: + """Verify/load-authorize only the frozen train or validation session.""" + + development = { + session.date.isoformat(): session.role for session in expected_config.sessions[:2] + } + if expected_role not in {"train", "validation"} or development.get(expected_date) != ( + expected_role + ): + raise M8L2InputError("development input must be the frozen train/validation coordinate") + return _verify_input( + bundle_dir, + expected_config=expected_config, + expected_date=expected_date, + expected_role=expected_role, + access_phase="development", + development_lock_sha256=None, + expected_file_authority=expected_file_authority, + expected_campaign=expected_campaign, + ) + + +def verify_m8_l2_heldout_input( + bundle_dir: str | Path, + *, + expected_config: M8L2StudyConfig, + expected_date: str, + expected_role: HeldoutRole, + development_lock_sha256: str, + expected_file_authority: L2SessionFileAuthority | None = None, + expected_campaign: L2CampaignRuntimeIdentity | None = None, +) -> VerifiedL2SessionInput: + """Verify/load-authorize one held-out session after a lock digest is known.""" + + _require_sha256(development_lock_sha256, "development lock authority") + heldout = {session.date.isoformat(): session.role for session in expected_config.sessions[2:]} + if ( + expected_role not in {"primary_test", "replication_test"} + or heldout.get(expected_date) != expected_role + ): + raise M8L2InputError("held-out input must be the frozen primary/replication coordinate") + return _verify_input( + bundle_dir, + expected_config=expected_config, + expected_date=expected_date, + expected_role=expected_role, + access_phase="heldout_after_lock", + development_lock_sha256=development_lock_sha256, + expected_file_authority=expected_file_authority, + expected_campaign=expected_campaign, + ) + + +__all__ = [ + "L2CampaignRuntimeIdentity", + "L2SessionFileAuthority", + "LoadedL2SymbolFrames", + "M8L2InputError", + "VerifiedL2Artifact", + "VerifiedL2SessionInput", + "VerifiedL2SymbolInput", + "verify_m8_l2_development_input", + "verify_m8_l2_heldout_input", +] diff --git a/Microstructure/src/microstructure/m8_l2_pipeline.py b/Microstructure/src/microstructure/m8_l2_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..c0ca90fe6b2d7d8f5f93c1a0e0225e602370e56e --- /dev/null +++ b/Microstructure/src/microstructure/m8_l2_pipeline.py @@ -0,0 +1,3805 @@ +"""Atomic producer and verifier for the frozen four-session M8 L2 study. + +The development lock is verified before either held-out payload can be opened. +Every session coordinate and both of its control-file digests are supplied by +the caller; this module never discovers a ``latest`` directory. Publication is +terminal-marker based and never overwrites an existing run. +""" + +from __future__ import annotations + +import ctypes +import errno +import hashlib +import json +import math +import os +import shutil +import stat +import sys +import tempfile +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from pathlib import Path, PurePosixPath +from typing import Any, Literal, cast + +import polars as pl +import pyarrow.parquet as pq # type: ignore[import-untyped] + +from microstructure.m8_l2_analysis_config import ( + M8L2AnalysisConfig, + load_m8_l2_analysis_config, +) +from microstructure.m8_l2_capture import ( + M8L2SessionBundle, + current_m8_l2_runtime_fingerprint_sha256, + verify_m8_l2_session_bundle, +) +from microstructure.m8_l2_config import ( + M8_L2_PROTOCOL_SHA256, + M8L2StudyConfig, + load_m8_l2_config, +) +from microstructure.m8_l2_development import ( + L2DevelopmentLockResult, + verify_m8_l2_development_lock, +) +from microstructure.m8_l2_inputs import ( + L2CampaignRuntimeIdentity, + L2SessionFileAuthority, + VerifiedL2SessionInput, + verify_m8_l2_development_input, + verify_m8_l2_heldout_input, +) +from microstructure.provenance import ( + ImportOriginError, + assert_project_module_origins, + git_source_tree_sha256, + runtime_metadata, + sha256_file, + strict_git_state, + utc_now_iso, +) +from microstructure.reporting.l2 import ( + L2ReportData, + canonical_report_data_sha256, + render_l2_executive_memo, + render_l2_model_comparison, + render_l2_technical_report, +) +from microstructure.research.analysis import RegimeThresholds +from microstructure.research.l2_analysis import ( + L2DescriptiveAnalysis, + build_l2_descriptive_analysis, +) +from microstructure.research.l2_evaluation import ( + L2EvaluationResult, + L2ExecutionReference, + L2HeldoutEndpointFrame, + LockedL2EndpointState, + evaluate_locked_l2_endpoints, + run_locked_l2_market_execution, +) +from microstructure.research.l2_multidate import ( + L2EndpointSpec, + L2RegimeFit, + apply_l2_regimes, + build_l2_endpoint_frames, + l2_model_feature_columns, + validate_l2_endpoint_frame, +) +from microstructure.research.multidate import FinalFittedState + +M8L2StudyRunStatus = Literal["COMPLETE", "INSUFFICIENT_DATA"] + +_SCHEMA_VERSION = "m8-l2-study-run-v2" +_REPORT_INPUT_SCHEMA_VERSION = "m8-l2-report-inputs-v1" +_CHECKSUMS_NAME = "CHECKSUMS.sha256" +_SUCCESS_NAME = "_SUCCESS" +_INSUFFICIENT_NAME = "INSUFFICIENT_DATA" +_SUCCESS_BYTES = b"complete\n" +_INSUFFICIENT_BYTES = b"terminal\n" +_EXPECTED_COORDINATES = ( + ("2026-08-10", "train"), + ("2026-08-11", "validation"), + ("2026-08-12", "primary_test"), + ("2026-08-13", "replication_test"), +) +_GIB = 1024**3 +# Fail-closed producer/verifier workspace partition for a 16 GiB host. The +# categories deliberately sum below the host ceiling even at their limits: +# causal 4 + current raw 2 + evaluation 2 + descriptive 2 + execution 2 = +# 12 GiB, leaving 4 GiB for Python/Polars/runtime and publication overhead. +_MAX_FINAL_RAW_BYTES = 2 * _GIB +_MAX_FINAL_CAUSAL_BYTES = 4 * _GIB +_MAX_CAUSAL_COORDINATE_BYTES = 2 * _GIB +_MAX_EVALUATION_WORKSPACE_BYTES = 2 * _GIB +_MAX_DESCRIPTIVE_WORKSPACE_BYTES = 2 * _GIB +_MAX_EXECUTION_WORKSPACE_BYTES = 2 * _GIB +_CAUSAL_ENDPOINT_ROW_UPPER_BYTES = 4 * 1024 +_PREDICTION_ROW_UPPER_BYTES = 1536 +_PYTHON_CELL_UPPER_BYTES = 192 +_PYTHON_ROW_BASE_UPPER_BYTES = 512 +_PYTHON_LEDGER_ROW_UPPER_BYTES = 2048 +_POLARS_LEDGER_ROW_UPPER_BYTES = 1024 + +_L2_VALIDATION_COLUMNS = ( + "study_date", + "study_role", + "endpoint_name", + "endpoint_domain", + "symbol", + "continuity_id", + "observed_interval_id", + "observed_interval_start_ns", + "observed_interval_end_ns_exclusive", + "decision_ts_ns", + "decision_sequence", + "feature_cutoff_ts_ns", + "max_feature_source_ts_ns", + "max_feature_source_sequence", + "feature_continuity_id", + "label_start_ts_ns", + "label_start_sequence", + "right_censored", + "future_mid_return", + "future_mid_up", + "label_information_end_ts_ns", + "label_information_end_sequence", + "label_continuity_id", + "ofi_signed_future_mid_markout_bps", + "sample_id", +) +_DESCRIPTIVE_COLUMNS = ( + "endpoint_horizon_value", + "endpoint_horizon_unit", + "spread_bps", + "depth_total_l1", + "depth_total_l5", + "depth_total_l10", + "queue_imbalance_l1", + "realized_volatility_w100", + "bid_quantity", + "ask_quantity", + "signed_markout_side_source", + "liquidity_regime", + "volatility_regime", +) +_EXECUTION_EVENT_COLUMNS = ( + *_L2_VALIDATION_COLUMNS, + "best_bid", + "best_ask", + "bid_quantity", + "ask_quantity", + "mid_price", + "tick_size", + "lot_size", +) +_EXECUTION_PREDICTION_COLUMNS = ( + "sample_id", + "symbol", + "study_date", + "study_role", + "endpoint_name", + "decision_sequence", + "selected_probability", + "is_oos", + "split", + "child_lock_sha256", + "aggregate_lock_sha256", + "endpoint_impact_ofi_window", +) + + +class M8L2StudyPipelineError(RuntimeError): + """Raised when final-study production or verification must fail closed.""" + + +class M8L2StudyRunVerificationError(M8L2StudyPipelineError): + """Raised when a terminal M8 L2 run differs from its authorities.""" + + +def _frame_bytes(frame: pl.DataFrame) -> int: + return int(frame.estimated_size("b")) + + +def _frames_bytes(frames: Sequence[pl.DataFrame]) -> int: + return sum(_frame_bytes(frame) for frame in frames) + + +def _require_memory_budget(observed: int, maximum: int, label: str) -> None: + if observed < 0 or observed > maximum: + raise M8L2StudyPipelineError( + f"{label} exceeds the fail-closed memory budget ({observed} > {maximum} bytes)" + ) + + +def _require_verification_memory_budget(observed: int, maximum: int, label: str) -> None: + if observed < 0 or observed > maximum: + raise M8L2StudyRunVerificationError( + f"{label} exceeds the bounded verifier memory budget ({observed} > {maximum} bytes)" + ) + + +def _parquet_metadata_bytes(root: Path, artifact: object, label: str) -> tuple[int, int]: + """Inspect Parquet row-group sizes without opening column payloads.""" + + relative = getattr(artifact, "relative_path", None) + claimed_rows = getattr(artifact, "rows", None) + if not isinstance(relative, str) or not isinstance(claimed_rows, int): + raise M8L2StudyPipelineError(f"{label} lacks bounded Parquet metadata authority") + safe = _safe_relative(relative) + path = root / safe + flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0) + try: + descriptor = os.open(path, flags) + before = os.fstat(descriptor) + if not stat.S_ISREG(before.st_mode): + raise M8L2StudyPipelineError(f"{label} is not a regular Parquet file") + with os.fdopen(descriptor, "rb", closefd=True) as handle: + parquet = pq.ParquetFile(handle) + metadata = parquet.metadata + rows = int(metadata.num_rows) + uncompressed = sum( + int(metadata.row_group(index).total_byte_size) + for index in range(metadata.num_row_groups) + ) + after = os.fstat(handle.fileno()) + if (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns) != ( + after.st_dev, + after.st_ino, + after.st_size, + after.st_mtime_ns, + ): + raise M8L2StudyPipelineError(f"{label} changed during memory admission") + except M8L2StudyPipelineError: + raise + except (OSError, ValueError, TypeError) as error: + raise M8L2StudyPipelineError(f"cannot inspect {label} memory metadata") from error + if rows != claimed_rows or rows < 1 or uncompressed < 1: + raise M8L2StudyPipelineError(f"{label} Parquet metadata differs from its authority") + return uncompressed, rows + + +def _preflight_symbol_raw(value: VerifiedL2SessionInput, symbol: str) -> tuple[int, int] | None: + """Return (uncompressed raw bytes, book rows) before payload materialization. + + Verified production inputs always expose artifact descriptors. Injected + test loaders may omit them and are then guarded by the immediate post-load + check in ``_build_one_symbol_frames``. + """ + + descriptor = value.symbols.get(symbol) + books = getattr(descriptor, "book_observations", None) + deltas = getattr(descriptor, "depth_deltas", None) + if books is None or deltas is None: + return None + book_bytes, book_rows = _parquet_metadata_bytes( + value.root, books, f"{value.session_date} {symbol} book observations" + ) + delta_bytes, _ = _parquet_metadata_bytes( + value.root, deltas, f"{value.session_date} {symbol} depth deltas" + ) + return book_bytes + delta_bytes, book_rows + + +def _loaded_bytes(value: Any) -> int: + books = cast(pl.DataFrame, value.book_observations) + deltas = cast(pl.DataFrame, value.depth_deltas) + intervals = cast(Sequence[object], value.intervals) + return _frame_bytes(books) + _frame_bytes(deltas) + len(intervals) * 1024 + + +def _projected_frame_bytes(frame: pl.DataFrame, columns: Sequence[str], label: str) -> int: + selected = tuple(dict.fromkeys(columns)) + missing = sorted(set(selected).difference(frame.columns)) + if missing: + raise M8L2StudyPipelineError(f"{label} projection lacks required columns: {missing}") + return sum(int(frame.get_column(name).estimated_size("b")) for name in selected) + + +def _project_frame(frame: pl.DataFrame, columns: Sequence[str], label: str) -> pl.DataFrame: + _projected_frame_bytes(frame, columns, label) + return frame.select(*tuple(dict.fromkeys(columns))) + + +def _evaluation_workspace_upper_bytes( + heldout: Sequence[L2HeldoutEndpointFrame], *, feature_count: int +) -> int: + if feature_count < 1: + raise M8L2StudyPipelineError("evaluation memory admission requires model features") + rows = sum(item.frame.height for item in heldout) + full_width_sort_and_filter = 2 * _frames_bytes([item.frame for item in heldout]) + child_and_concat = 2 * rows * _PREDICTION_ROW_UPPER_BYTES + numpy_scratch = rows * (feature_count * 8 + 8 * 8) + return full_width_sort_and_filter + child_and_concat + numpy_scratch + + +def _descriptive_projection_columns(feature_columns: Sequence[str]) -> tuple[str, ...]: + return tuple(dict.fromkeys((*_L2_VALIDATION_COLUMNS, *_DESCRIPTIVE_COLUMNS, *feature_columns))) + + +def _descriptive_workspace_upper_bytes( + causal: Sequence[pl.DataFrame], *, columns: Sequence[str] +) -> int: + projected = sum( + _projected_frame_bytes(frame, columns, "descriptive endpoint") for frame in causal + ) + rows = sum(frame.height for frame in causal) + # Projected inputs, combined concat, largest grouped/sorted temporary and + # retained outputs are charged as four full projected equivalents. + return 4 * projected + rows * 512 + + +def _python_projected_rows_upper_bytes(frame: pl.DataFrame, columns: Sequence[str]) -> int: + payload = _projected_frame_bytes(frame, columns, "Python-row input") + return payload + frame.height * ( + _PYTHON_ROW_BASE_UPPER_BYTES + len(tuple(dict.fromkeys(columns))) * _PYTHON_CELL_UPPER_BYTES + ) + + +def _execution_workspace_upper_bytes( + event_frame: pl.DataFrame, + predictions: pl.DataFrame, +) -> int: + signal_rows = predictions.filter( + (pl.col("selected_probability") >= 0.55) | (pl.col("selected_probability") <= 0.45) + ).height + # One possible forced liquidation row is included in every scenario. + ledger_rows_per_scenario = signal_rows + 1 + scenario_count = 9 + projected_inputs = _projected_frame_bytes( + event_frame, _EXECUTION_EVENT_COLUMNS, "execution event" + ) + _projected_frame_bytes(predictions, _EXECUTION_PREDICTION_COLUMNS, "execution prediction") + python_inputs = _python_projected_rows_upper_bytes( + event_frame, _EXECUTION_EVENT_COLUMNS + ) + _python_projected_rows_upper_bytes(predictions, _EXECUTION_PREDICTION_COLUMNS) + # simulate_predictions holds order/fill/position dictionaries and an + # event-aligned equity ledger for only the current scenario. + current_python_ledgers = ( + 4 * ledger_rows_per_scenario + event_frame.height + ) * _PYTHON_LEDGER_ROW_UPPER_BYTES + # run_locked_l2_market_execution retains the three Polars ledgers from all + # nine completed scenarios until its final coordinate concat. + retained_polars_ledgers = ( + 3 * ledger_rows_per_scenario * scenario_count * _POLARS_LEDGER_ROW_UPPER_BYTES + ) + # Caller projection plus the execution layer's ordered event/prediction + # projections can coexist; charge three complete projected input sets. + return 3 * projected_inputs + python_inputs + current_python_ledgers + retained_polars_ledgers + + +def _assert_final_producer_import_origins(project_root: Path) -> None: + try: + assert_project_module_origins( + project_root, + "microstructure.m8_l2_pipeline", + "microstructure.m8_l2_development", + "microstructure.m8_l2_inputs", + "microstructure.research.l2_analysis", + "microstructure.research.l2_evaluation", + "microstructure.research.l2_multidate", + "microstructure.research.multidate", + "microstructure.reporting.l2", + ) + except ImportOriginError as error: + raise M8L2StudyPipelineError( + "final-study producer has a foreign or mixed import origin" + ) from error + + +@dataclass(frozen=True, slots=True) +class L2StudySessionAuthority: + """An explicit session path plus independent control-file digests.""" + + bundle_path: Path + manifest_sha256: str + checksums_sha256: str + + def __post_init__(self) -> None: + object.__setattr__(self, "bundle_path", Path(self.bundle_path).absolute()) + _require_sha256(self.manifest_sha256, "session manifest authority") + _require_sha256(self.checksums_sha256, "session checksums authority") + + @property + def file_authority(self) -> L2SessionFileAuthority: + return L2SessionFileAuthority(self.manifest_sha256, self.checksums_sha256) + + def to_dict(self) -> dict[str, object]: + return { + "bundle_path": str(self.bundle_path), + "manifest_sha256": self.manifest_sha256, + "checksums_sha256": self.checksums_sha256, + } + + +@dataclass(frozen=True, slots=True) +class M8L2StudyRunResult: + """One verified terminal final-study bundle.""" + + root: Path + status: M8L2StudyRunStatus + manifest_path: Path + manifest_sha256: str + checksum_path: Path + checksum_sha256: str + marker_path: Path + reason_codes: tuple[str, ...] + + @property + def technical_report_path(self) -> Path: + return self.root / "reports" / "technical_report.md" + + @property + def executive_memo_path(self) -> Path: + return self.root / "reports" / "executive_memo.md" + + @property + def model_comparison_path(self) -> Path: + return self.root / "reports" / "model_comparison.md" + + +def reproduce_m8_l2_study( + capture_config: M8L2StudyConfig, + analysis_config: M8L2AnalysisConfig, + train_session: L2StudySessionAuthority, + validation_session: L2StudySessionAuthority, + development_lock_dir: str | Path, + expected_development_lock_sha256: str, + primary_session: L2StudySessionAuthority, + replication_session: L2StudySessionAuthority, + run_dir: str | Path, + *, + expected_existing_manifest_sha256: str | None = None, + expected_existing_checksums_sha256: str | None = None, +) -> M8L2StudyRunResult: + """Produce a run, or reuse one only under caller-held output authority.""" + + return _reproduce_m8_l2_study( + capture_config, + analysis_config, + train_session, + validation_session, + development_lock_dir, + expected_development_lock_sha256, + primary_session, + replication_session, + run_dir, + expected_existing_manifest_sha256=expected_existing_manifest_sha256, + expected_existing_checksums_sha256=expected_existing_checksums_sha256, + ) + + +def verify_m8_l2_study_run( + capture_config: M8L2StudyConfig, + analysis_config: M8L2AnalysisConfig, + train_session: L2StudySessionAuthority, + validation_session: L2StudySessionAuthority, + development_lock_dir: str | Path, + expected_development_lock_sha256: str, + primary_session: L2StudySessionAuthority, + replication_session: L2StudySessionAuthority, + run_dir: str | Path, + *, + expected_manifest_sha256: str | None = None, + expected_checksums_sha256: str | None = None, +) -> M8L2StudyRunResult: + """Recursively verify a terminal run and every external authority.""" + + return _verify_m8_l2_study_run( + capture_config, + analysis_config, + train_session, + validation_session, + development_lock_dir, + expected_development_lock_sha256, + primary_session, + replication_session, + run_dir, + expected_manifest_sha256=expected_manifest_sha256, + expected_checksums_sha256=expected_checksums_sha256, + ) + + +def load_m8_l2_report_data( + capture_config: M8L2StudyConfig, + analysis_config: M8L2AnalysisConfig, + train_session: L2StudySessionAuthority, + validation_session: L2StudySessionAuthority, + development_lock_dir: str | Path, + expected_development_lock_sha256: str, + primary_session: L2StudySessionAuthority, + replication_session: L2StudySessionAuthority, + run_dir: str | Path, + *, + expected_manifest_sha256: str | None = None, + expected_checksums_sha256: str | None = None, +) -> L2ReportData: + """Load report inputs only after complete terminal and authority verification.""" + + if expected_manifest_sha256 is None or expected_checksums_sha256 is None: + raise M8L2StudyRunVerificationError( + "report loading requires caller-held manifest and checksum authorities" + ) + + verified = verify_m8_l2_study_run( + capture_config, + analysis_config, + train_session, + validation_session, + development_lock_dir, + expected_development_lock_sha256, + primary_session, + replication_session, + run_dir, + expected_manifest_sha256=expected_manifest_sha256, + expected_checksums_sha256=expected_checksums_sha256, + ) + data = _load_report_data_snapshot(verified.root) + confirmed = verify_m8_l2_study_run( + capture_config, + analysis_config, + train_session, + validation_session, + development_lock_dir, + expected_development_lock_sha256, + primary_session, + replication_session, + run_dir, + expected_manifest_sha256=expected_manifest_sha256, + expected_checksums_sha256=expected_checksums_sha256, + ) + if confirmed != verified: + raise M8L2StudyRunVerificationError( + "final run authority changed while report inputs were loaded" + ) + return data + + +@dataclass(frozen=True, slots=True) +class _SourceIdentity: + commit: str + source_tree_sha256: str + dirty: bool + + def to_dict(self) -> dict[str, object]: + return { + "commit": self.commit, + "source_tree_sha256": self.source_tree_sha256, + "dirty": self.dirty, + } + + +@dataclass(frozen=True, slots=True) +class _SessionSnapshot: + authority: L2StudySessionAuthority + bundle: M8L2SessionBundle + manifest: Mapping[str, Any] + campaign: L2CampaignRuntimeIdentity + + +@dataclass(frozen=True, slots=True) +class _LockMaterial: + result: L2DevelopmentLockResult + aggregate: Mapping[str, Any] + campaign: L2CampaignRuntimeIdentity + source: _SourceIdentity + states: Mapping[tuple[str, str], LockedL2EndpointState] + regimes: Mapping[str, L2RegimeFit] + references: Mapping[str, L2ExecutionReference] + development_frame_sha256: Mapping[tuple[str, str], str] + snapshot_files: tuple[Path, ...] + + +@dataclass(frozen=True, slots=True) +class _ParentIdentity: + device: int + inode: int + + +def _is_sha256(value: str) -> bool: + return len(value) == 64 and all(character in "0123456789abcdef" for character in value) + + +def _require_sha256(value: str, label: str) -> None: + if not _is_sha256(value): + raise M8L2StudyPipelineError(f"{label} must be a lowercase SHA-256") + + +def _canonical_json_bytes(value: Mapping[str, object]) -> bytes: + try: + return ( + json.dumps( + dict(value), + sort_keys=True, + separators=(",", ":"), + ensure_ascii=True, + allow_nan=False, + ) + + "\n" + ).encode("ascii") + except (TypeError, ValueError) as error: + raise M8L2StudyPipelineError("M8 L2 authority is not finite canonical JSON") from error + + +def _decode_json(raw: bytes, label: str) -> dict[str, Any]: + def reject_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + raise M8L2StudyPipelineError(f"{label} repeats key {key!r}") + result[key] = value + return result + + def reject_constant(value: str) -> object: + raise M8L2StudyPipelineError(f"{label} contains forbidden constant {value}") + + try: + value = json.loads( + raw, + object_pairs_hook=reject_duplicates, + parse_constant=reject_constant, + ) + except M8L2StudyPipelineError: + raise + except (UnicodeDecodeError, json.JSONDecodeError) as error: + raise M8L2StudyPipelineError(f"{label} is not valid UTF-8 JSON") from error + if not isinstance(value, dict) or not all(type(key) is str for key in value): + raise M8L2StudyPipelineError(f"{label} must be a JSON object") + return cast(dict[str, Any], value) + + +def _safe_relative(value: str) -> str: + candidate = PurePosixPath(value) + if ( + not value + or "\\" in value + or "\x00" in value + or candidate.is_absolute() + or any(part in {"", ".", ".."} for part in candidate.parts) + or candidate.as_posix() != value + ): + raise M8L2StudyPipelineError(f"unsafe M8 L2 relative path {value!r}") + return value + + +def _join(root: Path, relative: str) -> Path: + return root.joinpath(*PurePosixPath(_safe_relative(relative)).parts) + + +def _reject_symlink_components(path: Path) -> None: + requested = path.absolute() + current = Path(requested.anchor) + for part in requested.parts[1:]: + current /= part + try: + metadata = current.lstat() + except FileNotFoundError: + continue + except OSError as error: + raise M8L2StudyPipelineError(f"cannot inspect path component {current}") from error + if stat.S_ISLNK(metadata.st_mode): + raise M8L2StudyPipelineError(f"M8 L2 path contains symlink component {current}") + + +def _relative(path: Path, root: Path) -> str: + try: + return path.relative_to(root).as_posix() + except ValueError as error: + raise M8L2StudyPipelineError("artifact escapes the M8 L2 run root") from error + + +def _same_stat(left: os.stat_result, right: os.stat_result) -> bool: + return ( + left.st_dev, + left.st_ino, + left.st_mode, + left.st_size, + left.st_mtime_ns, + left.st_ctime_ns, + ) == ( + right.st_dev, + right.st_ino, + right.st_mode, + right.st_size, + right.st_mtime_ns, + right.st_ctime_ns, + ) + + +def _read_regular( + path: Path, + *, + label: str, + maximum_bytes: int = 64 * 1024 * 1024, + expected_sha256: str | None = None, +) -> bytes: + try: + before_path = path.lstat() + except OSError as error: + raise M8L2StudyPipelineError(f"cannot stat {label}") from error + if ( + not stat.S_ISREG(before_path.st_mode) + or before_path.st_size < 0 + or before_path.st_size > maximum_bytes + ): + raise M8L2StudyPipelineError(f"{label} is not a bounded regular file") + flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0) + try: + descriptor = os.open(path, flags) + except OSError as error: + raise M8L2StudyPipelineError(f"cannot open {label} without following links") from error + try: + before = os.fstat(descriptor) + if not stat.S_ISREG(before.st_mode) or not _same_stat(before_path, before): + raise M8L2StudyPipelineError(f"{label} changed before its descriptor snapshot") + chunks: list[bytes] = [] + remaining = maximum_bytes + 1 + while remaining > 0: + chunk = os.read(descriptor, min(1 << 20, remaining)) + if not chunk: + break + chunks.append(chunk) + remaining -= len(chunk) + raw = b"".join(chunks) + after = os.fstat(descriptor) + after_path = path.lstat() + if len(raw) > maximum_bytes or len(raw) != before.st_size: + raise M8L2StudyPipelineError(f"{label} exceeds its bounded snapshot") + if not _same_stat(before, after) or not _same_stat(after, after_path): + raise M8L2StudyPipelineError(f"{label} changed during its descriptor snapshot") + digest = hashlib.sha256(raw).hexdigest() + if expected_sha256 is not None and digest != expected_sha256: + raise M8L2StudyPipelineError(f"{label} differs from its SHA-256 authority") + return raw + finally: + os.close(descriptor) + + +def _read_json( + path: Path, + label: str, + *, + expected_sha256: str | None = None, +) -> tuple[dict[str, Any], bytes]: + raw = _read_regular(path, label=label, expected_sha256=expected_sha256) + return _decode_json(raw, label), raw + + +def _fsync_directory(path: Path) -> None: + descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + + +def _write_bytes(path: Path, raw: bytes) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0) + descriptor = os.open(path, flags, 0o644) + try: + view = memoryview(raw) + while view: + written = os.write(descriptor, view) + if written < 1: + raise OSError("short M8 L2 artifact write") + view = view[written:] + os.fsync(descriptor) + finally: + os.close(descriptor) + _fsync_directory(path.parent) + + +def _write_json(path: Path, payload: Mapping[str, object]) -> str: + raw = _canonical_json_bytes(payload) + _write_bytes(path, raw) + return hashlib.sha256(raw).hexdigest() + + +def _write_parquet(path: Path, frame: pl.DataFrame) -> str: + path.parent.mkdir(parents=True, exist_ok=True) + if path.exists() or path.is_symlink(): + raise M8L2StudyPipelineError(f"refusing to overwrite M8 L2 artifact {path}") + frame.write_parquet(path, compression="zstd", statistics=True) + descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + _fsync_directory(path.parent) + return sha256_file(path) + + +def _copy_exact(source: Path, destination: Path, *, expected_sha256: str | None = None) -> str: + raw = _read_regular( + source, + label=f"authority snapshot {source}", + maximum_bytes=128 * 1024 * 1024, + expected_sha256=expected_sha256, + ) + _write_bytes(destination, raw) + return hashlib.sha256(raw).hexdigest() + + +def _parse_checksums(raw: bytes, label: str) -> dict[str, str]: + try: + lines = raw.decode("ascii").splitlines(keepends=True) + except UnicodeDecodeError as error: + raise M8L2StudyPipelineError(f"{label} must be ASCII") from error + result: dict[str, str] = {} + for line in lines: + if len(line) < 68 or not line.endswith("\n") or line[64:66] != " ": + raise M8L2StudyPipelineError(f"{label} has a malformed line") + digest = line[:64] + relative = _safe_relative(line[66:-1]) + _require_sha256(digest, f"{label} entry") + if relative in result: + raise M8L2StudyPipelineError(f"{label} repeats {relative}") + result[relative] = digest + if not result or list(result) != sorted(result): + raise M8L2StudyPipelineError(f"{label} is empty or not canonically ordered") + return result + + +def _frame_sha256(frame: pl.DataFrame) -> str: + digest = hashlib.sha256() + schema = [(name, str(dtype)) for name, dtype in frame.schema.items()] + digest.update(json.dumps(schema, separators=(",", ":")).encode()) + for chunk in frame.hash_rows(seed=0, seed_1=1, seed_2=2, seed_3=3).get_chunks(): + digest.update(chunk.to_numpy().astype(" tuple[M8L2StudyConfig, M8L2AnalysisConfig]: + try: + capture = load_m8_l2_config(capture_config.path) + analysis = load_m8_l2_analysis_config(analysis_config.path) + except (OSError, ValueError) as error: + raise M8L2StudyPipelineError("frozen M8 L2 configs cannot be reloaded") from error + if capture != capture_config or analysis != analysis_config: + raise M8L2StudyPipelineError("in-memory M8 L2 configs differ from exact frozen bytes") + coordinates = tuple((item.date.isoformat(), item.role) for item in capture.sessions) + if coordinates != _EXPECTED_COORDINATES: + raise M8L2StudyPipelineError("M8 L2 session calendar differs from the freeze") + if ( + analysis.study.capture_config_source_sha256 != capture.source_sha256 + or analysis.study.capture_protocol_sha256 != M8_L2_PROTOCOL_SHA256 + or analysis.study.symbols != capture.study.symbols + or analysis.study.seed != capture.study.seed + ): + raise M8L2StudyPipelineError("capture and analysis configs do not bind one study") + return capture, analysis + + +def _current_source_identity(capture: M8L2StudyConfig) -> _SourceIdentity: + project_root = capture.path.parent.parent.resolve() + before = strict_git_state(project_root) + source_tree_sha256 = git_source_tree_sha256(project_root) + after = strict_git_state(project_root) + if before != after: + raise M8L2StudyPipelineError("Git identity changed during final source snapshot") + result = _SourceIdentity( + commit=before.commit, + source_tree_sha256=source_tree_sha256, + dirty=before.dirty, + ) + if result.dirty: + raise M8L2StudyPipelineError("final M8 L2 production requires a clean Git source tree") + if len(result.commit) != 40 or any(char not in "0123456789abcdef" for char in result.commit): + raise M8L2StudyPipelineError("final M8 L2 producer commit is not a lowercase Git SHA-1") + _require_sha256(result.source_tree_sha256, "final M8 L2 source tree") + return result + + +def _campaign_from_manifest(manifest: Mapping[str, Any]) -> L2CampaignRuntimeIdentity: + authority = manifest.get("authority") + if not isinstance(authority, Mapping): + raise M8L2StudyPipelineError("session manifest lacks campaign authority") + return L2CampaignRuntimeIdentity( + campaign_authority_sha256=str(authority.get("campaign_authority_sha256")), + runtime_commit=str(authority.get("runtime_commit")), + runtime_source_tree_sha256=str(authority.get("runtime_source_tree_sha256")), + runtime_fingerprint_sha256=str(authority.get("runtime_fingerprint_sha256")), + runtime_dirty=authority.get("runtime_dirty") is not False, + ) + + +def _verify_session_authority( + authority: L2StudySessionAuthority, + *, + capture: M8L2StudyConfig, + expected_date: str, + expected_role: str, + expected_campaign: L2CampaignRuntimeIdentity | None, +) -> _SessionSnapshot: + try: + first = verify_m8_l2_session_bundle(authority.bundle_path, expected_config=capture) + except Exception as error: + raise M8L2StudyPipelineError( + f"session {expected_date} {expected_role} failed capture verification" + ) from error + if first.session_date != expected_date or first.role != expected_role: + raise M8L2StudyPipelineError("session authority has the wrong frozen coordinate") + manifest, _ = _read_json( + first.manifest_path, + f"{expected_role} session manifest", + expected_sha256=authority.manifest_sha256, + ) + _read_regular( + first.checksum_path, + label=f"{expected_role} session checksums", + expected_sha256=authority.checksums_sha256, + ) + if first.manifest_sha256 != authority.manifest_sha256: + raise M8L2StudyPipelineError("session capture verifier and manifest authority disagree") + campaign = _campaign_from_manifest(manifest) + if expected_campaign is not None and campaign != expected_campaign: + raise M8L2StudyPipelineError("four-session campaign/source identity changed") + try: + second = verify_m8_l2_session_bundle(authority.bundle_path, expected_config=capture) + except Exception as error: + raise M8L2StudyPipelineError("session changed during authority snapshot") from error + if second != first: + raise M8L2StudyPipelineError("session verifier result changed during authority snapshot") + return _SessionSnapshot(authority, first, manifest, campaign) + + +def _mapping(value: object, label: str) -> Mapping[str, Any]: + if not isinstance(value, Mapping) or not all(type(key) is str for key in value): + raise M8L2StudyPipelineError(f"{label} must be an object") + return cast(Mapping[str, Any], value) + + +def _string(value: object, label: str) -> str: + if type(value) is not str or not value: + raise M8L2StudyPipelineError(f"{label} must be nonempty text") + return value + + +def _finite(value: object, label: str, *, positive: bool = False) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise M8L2StudyPipelineError(f"{label} must be a finite number") + result = float(value) + if not math.isfinite(result) or (positive and result <= 0.0): + raise M8L2StudyPipelineError( + f"{label} must be finite" + (" and positive" if positive else "") + ) + return result + + +def _endpoint_specs(analysis: M8L2AnalysisConfig) -> tuple[L2EndpointSpec, ...]: + windows = set(analysis.features.rolling_windows) + result: list[L2EndpointSpec] = [] + for endpoint in analysis.endpoints: + impact_window = ( + endpoint.horizon_value + if endpoint.domain == "event" + else endpoint.nominal_event_block_width + ) + if impact_window not in windows: + impact_window = min(windows, key=lambda item: abs(item - impact_window)) + result.append( + L2EndpointSpec( + name=endpoint.name, + domain=endpoint.domain, + horizon_value=endpoint.horizon_value, + horizon_unit=endpoint.unit, + paired_block_events=( + endpoint.paired_block_width if endpoint.domain == "event" else None + ), + paired_block_milliseconds=( + endpoint.paired_block_width if endpoint.domain == "clock" else None + ), + impact_ofi_window=impact_window, + ) + ) + return tuple(result) + + +def _campaign_from_aggregate(aggregate: Mapping[str, Any]) -> L2CampaignRuntimeIdentity: + campaign = _mapping(aggregate.get("campaign_identity"), "development campaign identity") + return L2CampaignRuntimeIdentity( + campaign_authority_sha256=_string( + campaign.get("campaign_authority_sha256"), "development campaign SHA-256" + ), + runtime_commit=_string(campaign.get("runtime_commit"), "development runtime commit"), + runtime_source_tree_sha256=_string( + campaign.get("runtime_source_tree_sha256"), "development runtime source tree" + ), + runtime_fingerprint_sha256=_string( + campaign.get("runtime_fingerprint_sha256"), + "development runtime fingerprint", + ), + runtime_dirty=campaign.get("runtime_dirty") is not False, + ) + + +def _assert_current_runtime(campaign: L2CampaignRuntimeIdentity) -> None: + if current_m8_l2_runtime_fingerprint_sha256() != campaign.runtime_fingerprint_sha256: + raise M8L2StudyPipelineError( + "final producer runtime differs from the frozen capture campaign" + ) + + +def _explicit_development_authority( + aggregate: Mapping[str, Any], + train: L2StudySessionAuthority, + validation: L2StudySessionAuthority, +) -> None: + raw_inputs = aggregate.get("development_inputs") + if not isinstance(raw_inputs, list) or len(raw_inputs) != 2: + raise M8L2StudyPipelineError("development lock has no exact two-session input set") + for claim, supplied, coordinate in zip( + raw_inputs, + (train, validation), + _EXPECTED_COORDINATES[:2], + strict=True, + ): + payload = _mapping(claim, "development input claim") + file_authority = _mapping(payload.get("file_authority"), "development input file authority") + expected = { + "date": coordinate[0], + "role": coordinate[1], + "manifest_sha256": supplied.manifest_sha256, + "checksums_sha256": supplied.checksums_sha256, + } + observed = { + "date": payload.get("date"), + "role": payload.get("role"), + "manifest_sha256": file_authority.get("manifest_sha256"), + "checksums_sha256": file_authority.get("checksums_sha256"), + } + if observed != expected: + raise M8L2StudyPipelineError( + "caller development session authority differs from the aggregate lock" + ) + + +def _verify_lock_context( + capture: M8L2StudyConfig, + analysis: M8L2AnalysisConfig, + train: L2StudySessionAuthority, + validation: L2StudySessionAuthority, + lock_dir: str | Path, + expected_lock_sha256: str, +) -> tuple[L2DevelopmentLockResult, Mapping[str, Any], L2CampaignRuntimeIdentity, _SourceIdentity]: + _require_sha256(expected_lock_sha256, "development aggregate lock authority") + try: + result = verify_m8_l2_development_lock( + capture, + analysis, + train.bundle_path, + validation.bundle_path, + lock_dir, + expected_lock_sha256=expected_lock_sha256, + ) + except Exception as error: + raise M8L2StudyPipelineError("development lock failed recursive verification") from error + aggregate, _ = _read_json( + result.aggregate_path, + "aggregate development lock", + expected_sha256=expected_lock_sha256, + ) + _explicit_development_authority(aggregate, train, validation) + campaign = _campaign_from_aggregate(aggregate) + source = _current_source_identity(capture) + producer = _mapping( + aggregate.get("producer_source_identity"), "development producer source identity" + ) + expected_source = source.to_dict() + if dict(producer) != expected_source: + raise M8L2StudyPipelineError("current producer source differs from development lock") + if ( + campaign.runtime_commit != source.commit + or campaign.runtime_source_tree_sha256 != source.source_tree_sha256 + or campaign.runtime_dirty + ): + raise M8L2StudyPipelineError("development lock and campaign source identities disagree") + return result, aggregate, campaign, source + + +def _regime_from_payload(payload: Mapping[str, Any], *, symbol: str) -> L2RegimeFit: + if ( + payload.get("schema_version") != "m8-l2-regime-thresholds-v1" + or payload.get("artifact_kind") != "train_only_l2_regime_thresholds" + or payload.get("symbol") != symbol + or payload.get("study_date") != "2026-08-10" + or payload.get("fit_scope") != "train_session_only" + ): + raise M8L2StudyPipelineError("train-only regime snapshot has invalid semantics") + thresholds = _mapping(payload.get("thresholds"), "regime thresholds") + return L2RegimeFit( + symbol=symbol, + study_date="2026-08-10", + volatility_column=_string(payload.get("volatility_column"), "regime feature"), + lower_quantile=_finite(payload.get("lower_quantile"), "lower regime quantile"), + upper_quantile=_finite(payload.get("upper_quantile"), "upper regime quantile"), + thresholds=RegimeThresholds( + volatility_low=_finite(thresholds.get("volatility_low"), "volatility low"), + volatility_high=_finite(thresholds.get("volatility_high"), "volatility high"), + spread_tight_bps=_finite(thresholds.get("spread_tight_bps"), "tight spread"), + spread_wide_bps=_finite(thresholds.get("spread_wide_bps"), "wide spread"), + depth_low=_finite(thresholds.get("depth_low"), "low depth"), + depth_high=_finite(thresholds.get("depth_high"), "high depth"), + ), + ) + + +def _execution_reference_from_payload( + payload: Mapping[str, Any], + *, + symbol: str, + aggregate_sha256: str, +) -> L2ExecutionReference: + if ( + payload.get("schema_version") != "m8-l2-execution-reference-v1" + or payload.get("artifact_kind") != "train_only_execution_reference" + or payload.get("symbol") != symbol + or payload.get("fit_date") != "2026-08-10" + or payload.get("fit_role") != "train" + or payload.get("reference_price_statistic") != "train_median_mid_price" + or payload.get("reference_depth_statistic") != "train_q05_min_bid_ask_l1_depth" + ): + raise M8L2StudyPipelineError("train-only execution snapshot has invalid semantics") + return L2ExecutionReference.create( + symbol=symbol, + training_date="2026-08-10", + reference_mid_price=_finite( + payload.get("reference_mid_price"), "execution reference midpoint", positive=True + ), + train_l1_depth_q05=_finite( + payload.get("reference_l1_depth_q05"), "execution reference depth", positive=True + ), + lot_size=_finite(payload.get("lot_size"), "execution reference lot", positive=True), + reference_quantity=_finite( + payload.get("reference_quantity"), "execution reference quantity", positive=True + ), + aggregate_lock_sha256=aggregate_sha256, + ) + + +def _load_lock_material( + capture: M8L2StudyConfig, + analysis: M8L2AnalysisConfig, + result: L2DevelopmentLockResult, + aggregate: Mapping[str, Any], + campaign: L2CampaignRuntimeIdentity, + source: _SourceIdentity, +) -> _LockMaterial: + endpoint_specs = {item.name: item for item in _endpoint_specs(analysis)} + states: dict[tuple[str, str], LockedL2EndpointState] = {} + regimes: dict[str, L2RegimeFit] = {} + references: dict[str, L2ExecutionReference] = {} + development_hashes: dict[tuple[str, str], str] = {} + snapshot_files: dict[str, Path] = { + _relative(result.aggregate_path, result.root): result.aggregate_path, + "development_lock.sha256": result.root / "development_lock.sha256", + } + if result.status == "NOT_CREATED": + development_checksums_path = result.root / _CHECKSUMS_NAME + development_checksums = _parse_checksums( + _read_regular( + development_checksums_path, + label="NOT_CREATED development checksum authority", + maximum_bytes=4 << 20, + ), + "NOT_CREATED development checksum authority", + ) + for relative, digest in development_checksums.items(): + path = _join(result.root, relative) + if _stable_file_sha256_for_pipeline(path, relative) != digest: + raise M8L2StudyPipelineError( + f"NOT_CREATED development snapshot changed for {relative}" + ) + snapshot_files[relative] = path + snapshot_files[_CHECKSUMS_NAME] = development_checksums_path + not_created_marker = result.root / "_NOT_CREATED" + if ( + _read_regular( + not_created_marker, + label="NOT_CREATED development terminal marker", + maximum_bytes=32, + ) + != b"not-created\n" + ): + raise M8L2StudyPipelineError("NOT_CREATED development marker differs") + snapshot_files["_NOT_CREATED"] = not_created_marker + return _LockMaterial( + result=result, + aggregate=aggregate, + campaign=campaign, + source=source, + states={}, + regimes={}, + references={}, + development_frame_sha256={}, + snapshot_files=tuple(snapshot_files[key] for key in sorted(snapshot_files)), + ) + child_by_key = {(item.symbol, item.endpoint): item for item in result.children} + expected_keys = tuple( + (symbol, endpoint.name) + for symbol in capture.study.symbols + for endpoint in analysis.endpoints + ) + if tuple(child_by_key) != expected_keys: + raise M8L2StudyPipelineError("development result has an incomplete child order") + for symbol, endpoint_name in expected_keys: + child_claim = child_by_key[(symbol, endpoint_name)] + child, _ = _read_json( + child_claim.path, + f"{symbol} {endpoint_name} child lock", + expected_sha256=child_claim.sha256, + ) + state_relative = _safe_relative( + _string(child.get("final_fitted_state_path"), "fitted-state path") + ) + state_sha = _string(child.get("final_fitted_state_sha256"), "fitted-state SHA-256") + _require_sha256(state_sha, "fitted-state SHA-256") + state_path = _join(result.root, state_relative) + state_raw = _read_regular( + state_path, + label=f"{symbol} {endpoint_name} fitted state", + ) + if not state_raw.endswith(b"\n"): + raise M8L2StudyPipelineError("fitted-state snapshot lacks canonical newline") + try: + fitted_state = FinalFittedState.restore(state_raw[:-1].decode("ascii"), state_sha) + except (UnicodeDecodeError, ValueError) as error: + raise M8L2StudyPipelineError("fitted-state snapshot cannot be restored") from error + + regime_relative = _safe_relative( + _string(child.get("regime_thresholds_path"), "regime path") + ) + regime_sha = _string(child.get("regime_thresholds_sha256"), "regime SHA-256") + _require_sha256(regime_sha, "regime SHA-256") + regime_path = _join(result.root, regime_relative) + if symbol not in regimes: + regime_payload, _ = _read_json( + regime_path, + f"{symbol} regime thresholds", + expected_sha256=regime_sha, + ) + regimes[symbol] = _regime_from_payload(regime_payload, symbol=symbol) + + execution_relative = _safe_relative( + _string(child.get("execution_reference_path"), "execution reference path") + ) + execution_sha = _string( + child.get("execution_reference_sha256"), "execution reference SHA-256" + ) + _require_sha256(execution_sha, "execution reference SHA-256") + execution_path = _join(result.root, execution_relative) + if symbol not in references: + execution_payload, _ = _read_json( + execution_path, + f"{symbol} execution reference", + expected_sha256=execution_sha, + ) + references[symbol] = _execution_reference_from_payload( + execution_payload, + symbol=symbol, + aggregate_sha256=result.aggregate_sha256, + ) + + states[(symbol, endpoint_name)] = LockedL2EndpointState( + symbol=symbol, + endpoint=endpoint_specs[endpoint_name], + child_lock_sha256=child_claim.sha256, + aggregate_lock_sha256=result.aggregate_sha256, + regime_thresholds_sha256=regime_sha, + fitted_state=fitted_state, + ) + development_sha = _string( + child.get("development_frame_sha256"), "development-frame SHA-256" + ) + _require_sha256(development_sha, "development-frame SHA-256") + development_hashes[(symbol, endpoint_name)] = development_sha + selection_relative = _safe_relative( + _string(child.get("selection_lock_path"), "selection-lock path") + ) + for path in ( + child_claim.path, + state_path, + regime_path, + execution_path, + _join(result.root, selection_relative), + ): + snapshot_files[_relative(path, result.root)] = path + development_checksums_path = result.root / _CHECKSUMS_NAME + development_checksums_raw = _read_regular( + development_checksums_path, + label="development-lock checksum authority", + maximum_bytes=4 << 20, + ) + development_checksums = _parse_checksums( + development_checksums_raw, "development-lock checksum authority" + ) + for relative, digest in development_checksums.items(): + path = _join(result.root, relative) + if _stable_file_sha256_for_pipeline(path, relative) != digest: + raise M8L2StudyPipelineError(f"development-lock snapshot source changed for {relative}") + snapshot_files[relative] = path + snapshot_files[_CHECKSUMS_NAME] = development_checksums_path + locked_marker = result.root / "_LOCKED" + if ( + _read_regular(locked_marker, label="development-lock terminal marker", maximum_bytes=32) + != b"locked\n" + ): + raise M8L2StudyPipelineError("development-lock terminal marker differs") + snapshot_files["_LOCKED"] = locked_marker + return _LockMaterial( + result=result, + aggregate=aggregate, + campaign=campaign, + source=source, + states=states, + regimes=regimes, + references=references, + development_frame_sha256=development_hashes, + snapshot_files=tuple(snapshot_files[key] for key in sorted(snapshot_files)), + ) + + +def _stable_file_sha256_for_pipeline(path: Path, label: str) -> str: + try: + before = path.lstat() + except OSError as error: + raise M8L2StudyPipelineError(f"cannot stat {label}") from error + if not stat.S_ISREG(before.st_mode): + raise M8L2StudyPipelineError(f"{label} must be a regular file") + flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0) + descriptor = os.open(path, flags) + try: + opened = os.fstat(descriptor) + if not _same_stat(before, opened): + raise M8L2StudyPipelineError(f"{label} changed before hashing") + digest = hashlib.sha256() + while chunk := os.read(descriptor, 1 << 20): + digest.update(chunk) + after = os.fstat(descriptor) + if not _same_stat(opened, after) or not _same_stat(after, path.lstat()): + raise M8L2StudyPipelineError(f"{label} changed while hashing") + return digest.hexdigest() + finally: + os.close(descriptor) + + +def _verify_all_sessions( + capture: M8L2StudyConfig, + material: _LockMaterial, + authorities: Sequence[L2StudySessionAuthority], +) -> tuple[_SessionSnapshot, ...]: + if len(authorities) != 4: + raise M8L2StudyPipelineError("the final L2 study requires four explicit sessions") + snapshots: list[_SessionSnapshot] = [] + for supplied, (expected_date, expected_role) in zip( + authorities, _EXPECTED_COORDINATES, strict=True + ): + snapshots.append( + _verify_session_authority( + supplied, + capture=capture, + expected_date=expected_date, + expected_role=expected_role, + expected_campaign=material.campaign, + ) + ) + development_incomplete = any(item.bundle.status != "COMPLETE" for item in snapshots[:2]) + if material.result.status == "LOCKED" and development_incomplete: + raise M8L2StudyPipelineError( + "train/validation failure cannot be promoted without a valid development lock" + ) + if material.result.status == "NOT_CREATED" and not development_incomplete: + raise M8L2StudyPipelineError( + "NOT_CREATED development authority requires an insufficient development session" + ) + return tuple(snapshots) + + +def _reverify_material( + capture: M8L2StudyConfig, + analysis: M8L2AnalysisConfig, + train: L2StudySessionAuthority, + validation: L2StudySessionAuthority, + lock_dir: str | Path, + expected_lock_sha256: str, + expected: _LockMaterial, +) -> None: + result, aggregate, campaign, source = _verify_lock_context( + capture, + analysis, + train, + validation, + lock_dir, + expected_lock_sha256, + ) + if ( + result.aggregate_sha256 != expected.result.aggregate_sha256 + or dict(aggregate) != dict(expected.aggregate) + or campaign != expected.campaign + or source != expected.source + or result.children != expected.result.children + or result.status != expected.result.status + or result.reason_codes != expected.result.reason_codes + ): + raise M8L2StudyPipelineError("development lock/source changed during final production") + + +def _development_input( + snapshot: _SessionSnapshot, + *, + capture: M8L2StudyConfig, + campaign: L2CampaignRuntimeIdentity, +) -> VerifiedL2SessionInput: + role = cast(Literal["train", "validation"], snapshot.bundle.role) + return verify_m8_l2_development_input( + snapshot.authority.bundle_path, + expected_config=capture, + expected_date=snapshot.bundle.session_date, + expected_role=role, + expected_file_authority=snapshot.authority.file_authority, + expected_campaign=campaign, + ) + + +def _heldout_input( + snapshot: _SessionSnapshot, + *, + capture: M8L2StudyConfig, + campaign: L2CampaignRuntimeIdentity, + lock_sha256: str, +) -> VerifiedL2SessionInput: + role = cast(Literal["primary_test", "replication_test"], snapshot.bundle.role) + return verify_m8_l2_heldout_input( + snapshot.authority.bundle_path, + expected_config=capture, + expected_date=snapshot.bundle.session_date, + expected_role=role, + development_lock_sha256=lock_sha256, + expected_file_authority=snapshot.authority.file_authority, + expected_campaign=campaign, + ) + + +def _build_one_symbol_frames( + verified: VerifiedL2SessionInput, + *, + symbol: str, + analysis: M8L2AnalysisConfig, + material: _LockMaterial, +) -> Mapping[str, pl.DataFrame]: + admission = _preflight_symbol_raw(verified, symbol) + if admission is not None: + _require_memory_budget( + admission[0], + _MAX_FINAL_RAW_BYTES, + f"{verified.session_date} {symbol} raw Parquet admission", + ) + _require_memory_budget( + admission[1] * len(analysis.endpoints) * _CAUSAL_ENDPOINT_ROW_UPPER_BYTES, + _MAX_CAUSAL_COORDINATE_BYTES, + f"{verified.session_date} {symbol} causal build admission", + ) + loaded = verified.load_symbol_frames(symbol) + _require_memory_budget( + _loaded_bytes(loaded), + _MAX_FINAL_RAW_BYTES, + f"{verified.session_date} {symbol} raw materialization", + ) + if admission is None: + _require_memory_budget( + loaded.book_observations.height + * len(analysis.endpoints) + * _CAUSAL_ENDPOINT_ROW_UPPER_BYTES, + _MAX_CAUSAL_COORDINATE_BYTES, + f"{verified.session_date} {symbol} causal build admission", + ) + built = dict( + build_l2_endpoint_frames( + loaded.book_observations, + loaded.depth_deltas, + loaded.intervals, + study_date=verified.session_date, + study_role=cast(Any, verified.role), + feature_windows=analysis.features.rolling_windows, + volatility_window=analysis.features.volatility_window, + clock_max_state_age_ms=analysis.features.clock_max_state_age_ms, + endpoints=_endpoint_specs(analysis), + ) + ) + _require_memory_budget( + _frames_bytes(list(built.values())), + _MAX_CAUSAL_COORDINATE_BYTES, + f"{verified.session_date} {symbol} causal builder output", + ) + del loaded + result: dict[str, pl.DataFrame] = {} + for endpoint in analysis.endpoints: + source = built.pop(endpoint.name) + frame = apply_l2_regimes(source, material.regimes[symbol]) + _require_memory_budget( + _frames_bytes([*built.values(), *result.values(), source, frame]), + _MAX_CAUSAL_COORDINATE_BYTES, + f"{verified.session_date} {symbol} causal output/scratch", + ) + if ( + l2_model_feature_columns(frame, windows=analysis.features.rolling_windows) + != analysis.features.model_feature_columns + ): + raise M8L2StudyPipelineError("rebuilt causal frame has the wrong model features") + validate_l2_endpoint_frame(frame) + result[endpoint.name] = frame + del source + _require_memory_budget( + _frames_bytes(list(result.values())), + _MAX_CAUSAL_COORDINATE_BYTES, + f"{verified.session_date} {symbol} causal coordinate output", + ) + return result + + +def _build_causal_frames( + capture: M8L2StudyConfig, + analysis: M8L2AnalysisConfig, + snapshots: Sequence[_SessionSnapshot], + material: _LockMaterial, + *, + train: L2StudySessionAuthority, + validation: L2StudySessionAuthority, + lock_dir: str | Path, + lock_sha256: str, +) -> tuple[ + dict[tuple[str, str, str, str], pl.DataFrame], + tuple[L2HeldoutEndpointFrame, ...], +]: + inputs: list[VerifiedL2SessionInput] = [ + _development_input(snapshots[0], capture=capture, campaign=material.campaign), + _development_input(snapshots[1], capture=capture, campaign=material.campaign), + ] + for heldout_snapshot in snapshots[2:]: + _reverify_material( + capture, + analysis, + train, + validation, + lock_dir, + lock_sha256, + material, + ) + inputs.append( + _heldout_input( + heldout_snapshot, + capture=capture, + campaign=material.campaign, + lock_sha256=lock_sha256, + ) + ) + + causal: dict[tuple[str, str, str, str], pl.DataFrame] = {} + heldout: list[L2HeldoutEndpointFrame] = [] + causal_bytes = 0 + for verified in inputs: + for symbol in capture.study.symbols: + # This check is intentionally adjacent to every held-out payload load. + if verified.role in {"primary_test", "replication_test"}: + _reverify_material( + capture, + analysis, + train, + validation, + lock_dir, + lock_sha256, + material, + ) + frames = _build_one_symbol_frames( + verified, + symbol=symbol, + analysis=analysis, + material=material, + ) + for endpoint in analysis.endpoints: + frame = frames[endpoint.name] + key = (verified.session_date, verified.role, symbol, endpoint.name) + causal[key] = frame + causal_bytes += _frame_bytes(frame) + _require_memory_budget( + causal_bytes, + _MAX_FINAL_CAUSAL_BYTES, + "32-frame accumulated causal output", + ) + if verified.role in {"primary_test", "replication_test"}: + heldout.append( + L2HeldoutEndpointFrame( + symbol=symbol, + endpoint_name=endpoint.name, + study_date=verified.session_date, + study_role=cast(Any, verified.role), + frame=frame, + ) + ) + del frames, frame + expected_count = 4 * len(capture.study.symbols) * len(analysis.endpoints) + if len(causal) != expected_count or len(heldout) != expected_count // 2: + raise M8L2StudyPipelineError("rebuilt causal frame set is incomplete") + for symbol in capture.study.symbols: + for endpoint in analysis.endpoints: + train_frame = causal[("2026-08-10", "train", symbol, endpoint.name)] + validation_frame = causal[("2026-08-11", "validation", symbol, endpoint.name)] + _require_memory_budget( + 2 * (_frame_bytes(train_frame) + _frame_bytes(validation_frame)), + _MAX_CAUSAL_COORDINATE_BYTES, + f"{symbol} {endpoint.name} development-hash concat scratch", + ) + development = pl.concat( + [train_frame, validation_frame], + how="vertical", + ) + if ( + _frame_sha256(development) + != material.development_frame_sha256[(symbol, endpoint.name)] + ): + raise M8L2StudyPipelineError( + "rebuilt train/validation causal frame differs from the locked development hash" + ) + del development, train_frame, validation_frame + return causal, tuple(heldout) + + +def _heldout_availability_reasons( + heldout: Sequence[L2HeldoutEndpointFrame], +) -> tuple[str, ...]: + reasons: list[str] = [] + for item in heldout: + eligible = item.frame.filter( + pl.col("feature_ready") + & (~pl.col("right_censored")) + & pl.col("future_mid_up").is_not_null() + ) + if eligible.is_empty(): + reasons.append( + f"NO_ELIGIBLE_LABELS::{item.study_role}::{item.symbol}::{item.endpoint_name}" + ) + return tuple(sorted(reasons)) + + +def _session_gate_rows(snapshots: Sequence[_SessionSnapshot]) -> tuple[Mapping[str, Any], ...]: + rows: list[Mapping[str, Any]] = [] + for item in snapshots: + symbols = item.manifest.get("symbols") + symbol_payload = symbols if isinstance(symbols, Mapping) else {} + rows.append( + { + "study_date": item.bundle.session_date, + "study_role": item.bundle.role, + "status": item.bundle.status, + "BTCUSDT_gate": ( + _mapping(symbol_payload.get("BTCUSDT"), "BTC session claim").get("status") + if "BTCUSDT" in symbol_payload + else "NOT_AVAILABLE" + ), + "ETHUSDT_gate": ( + _mapping(symbol_payload.get("ETHUSDT"), "ETH session claim").get("status") + if "ETHUSDT" in symbol_payload + else "NOT_AVAILABLE" + ), + "overlap_seconds": item.manifest.get("cross_symbol_observed_overlap_seconds", 0.0), + "reason_codes": list(item.bundle.reason_codes), + "manifest_sha256": item.authority.manifest_sha256, + "checksums_sha256": item.authority.checksums_sha256, + } + ) + return tuple(rows) + + +def _not_created_final_reasons( + snapshots: Sequence[_SessionSnapshot], +) -> tuple[str, ...]: + reasons: set[str] = set() + for index, item in enumerate(snapshots): + if item.bundle.status == "COMPLETE": + continue + prefix = "DEVELOPMENT_SESSION_INSUFFICIENT" if index < 2 else "HELDOUT_SESSION_INSUFFICIENT" + reasons.update( + f"{prefix}::{item.bundle.role}::{reason}" + for reason in (item.bundle.reason_codes or ("SESSION_INSUFFICIENT_DATA",)) + ) + return tuple(sorted(reasons)) + + +def _causal_relative(key: tuple[str, str, str, str]) -> str: + study_date, role, symbol, endpoint = key + return f"causal_frames/{study_date}-{role}/{symbol.lower()}/{endpoint}.parquet" + + +_EVALUATION_PATHS = ( + "evaluation/predictions.parquet", + "evaluation/predictive_metrics.parquet", + "evaluation/paired_by_session_regime.parquet", + "evaluation/equal_session_summary.parquet", + "evaluation/signed_markout.parquet", +) +_DESCRIPTIVE_PATHS = ( + "descriptive/intraday_liquidity.parquet", + "descriptive/ofi_return_association.parquet", + "descriptive/signal_half_life.parquet", + "descriptive/liquidity_recovery.parquet", + "descriptive/regime_diagnostics.parquet", + "descriptive/feature_stability.parquet", + "descriptive/cross_instrument_stability.parquet", +) +_REPORT_PATHS = ( + "reports/technical_report.md", + "reports/executive_memo.md", + "reports/model_comparison.md", +) + + +def _execution_relative(item: L2HeldoutEndpointFrame, name: str) -> str: + return ( + f"execution/partitions/{item.study_date}-{item.study_role}/" + f"{item.symbol.lower()}/{item.endpoint_name}/{name}.parquet" + ) + + +def _authority_sources( + capture: M8L2StudyConfig, + analysis: M8L2AnalysisConfig, + snapshots: Sequence[_SessionSnapshot], + material: _LockMaterial, +) -> Mapping[str, tuple[Path, str]]: + project_root = capture.path.parent.parent.resolve() + protocol = project_root / "docs" / "M8_L2_PROTOCOL.md" + result: dict[str, tuple[Path, str]] = { + "authority/m8_l2_capture_study.toml": (capture.path, capture.source_sha256), + "authority/m8_l2_analysis.toml": (analysis.path, analysis.source_sha256), + "authority/M8_L2_PROTOCOL.md": (protocol, M8_L2_PROTOCOL_SHA256), + "authority/campaign_authority.json": ( + snapshots[0].authority.bundle_path / "authority" / "campaign_authority.json", + material.campaign.campaign_authority_sha256, + ), + } + for snapshot in snapshots: + prefix = f"authority/sessions/{snapshot.bundle.session_date}-{snapshot.bundle.role}" + result[f"{prefix}/session_manifest.json"] = ( + snapshot.bundle.manifest_path, + snapshot.authority.manifest_sha256, + ) + result[f"{prefix}/CHECKSUMS.sha256"] = ( + snapshot.bundle.checksum_path, + snapshot.authority.checksums_sha256, + ) + for source in material.snapshot_files: + relative = _relative(source, material.result.root) + result[f"authority/development_lock/{relative}"] = (source, sha256_file(source)) + return dict(sorted(result.items())) + + +def _artifact_kind(relative: str) -> str: + if relative.startswith("authority/"): + return "authority_snapshot" + if relative.startswith("causal_frames/"): + return "causal_endpoint_frame" + if relative.startswith("evaluation/"): + return "locked_evaluation" + if relative.startswith("execution/"): + return "market_scenario" + if relative.startswith("descriptive/"): + return "descriptive_analysis" + if relative.startswith("reports/"): + return "human_report" + if relative == "provenance.json": + return "provenance" + if relative.startswith("report_inputs"): + return "report_authority" + raise M8L2StudyPipelineError(f"cannot classify run artifact {relative}") + + +def _planned_paths( + *, + authority_paths: Sequence[str], + causal: Mapping[tuple[str, str, str, str], pl.DataFrame], + heldout: Sequence[L2HeldoutEndpointFrame], + complete: bool, +) -> tuple[str, ...]: + paths = set(authority_paths) + paths.update(_causal_relative(key) for key in causal) + if complete: + paths.update(_EVALUATION_PATHS) + paths.update(_DESCRIPTIVE_PATHS) + for item in heldout: + paths.update( + _execution_relative(item, name) for name in ("orders", "fills", "positions") + ) + paths.update(("execution/metrics.parquet", "execution/assumptions.parquet")) + paths.update( + { + "provenance.json", + "report_inputs.json", + "report_inputs.sha256", + *_REPORT_PATHS, + } + ) + return tuple(sorted(paths)) + + +def _development_authority_claim(material: _LockMaterial) -> dict[str, object]: + return { + "status": material.result.status, + "authority_sha256": material.result.aggregate_sha256, + "reason_codes": list(material.result.reason_codes), + } + + +def _run_identity( + capture: M8L2StudyConfig, + analysis: M8L2AnalysisConfig, + material: _LockMaterial, + snapshots: Sequence[_SessionSnapshot], +) -> str: + payload = { + "schema_version": _SCHEMA_VERSION, + "capture_config_source_sha256": capture.source_sha256, + "analysis_config_source_sha256": analysis.source_sha256, + "development_lock_sha256": material.result.aggregate_sha256, + "development_authority": _development_authority_claim(material), + "campaign": material.campaign.to_dict(), + "source": material.source.to_dict(), + "sessions": [ + { + "date": item.bundle.session_date, + "role": item.bundle.role, + "manifest_sha256": item.authority.manifest_sha256, + "checksums_sha256": item.authority.checksums_sha256, + } + for item in snapshots + ], + } + encoded = json.dumps(payload, sort_keys=True, separators=(",", ":"), allow_nan=False).encode() + return hashlib.sha256(encoded).hexdigest() + + +def _provenance_payload( + *, + status: M8L2StudyRunStatus, + capture: M8L2StudyConfig, + analysis: M8L2AnalysisConfig, + material: _LockMaterial, + snapshots: Sequence[_SessionSnapshot], + generated_at_utc: str, + run_id: str, +) -> dict[str, object]: + return { + "schema_version": _SCHEMA_VERSION, + "artifact_kind": "m8_l2_final_study_provenance", + "status": status, + "generated_at_utc": generated_at_utc, + "run_id": run_id, + "git": material.source.to_dict(), + "runtime": runtime_metadata(), + "inputs": { + "capture_config_sha256": capture.hash, + "capture_config_source_sha256": capture.source_sha256, + "capture_protocol_sha256": M8_L2_PROTOCOL_SHA256, + "analysis_config_sha256": analysis.hash, + "analysis_config_source_sha256": analysis.source_sha256, + "development_lock_sha256": material.result.aggregate_sha256, + "development_lock_dir": str(material.result.root), + "development_authority": _development_authority_claim(material), + "campaign_identity": material.campaign.to_dict(), + "sessions": [ + { + "date": item.bundle.session_date, + "role": item.bundle.role, + "external_bundle_path": str(item.authority.bundle_path), + "session_id": item.bundle.session_id, + "status": item.bundle.status, + "manifest_sha256": item.authority.manifest_sha256, + "checksums_sha256": item.authority.checksums_sha256, + } + for item in snapshots + ], + }, + "phase_separation": { + "development_lock_verified_before_heldout_payload": ( + material.result.status == "LOCKED" + ), + "development_authority_status": material.result.status, + "heldout_economic_payload_accessed": ( + material.result.status == "LOCKED" + and all(item.bundle.status == "COMPLETE" for item in snapshots[2:]) + ), + "heldout_fit_or_update_allowed": False, + "model_updated_between_test_dates": False, + "directory_discovery_used": False, + }, + "claims": { + "p_values": False, + "significance": False, + "cross_symbol_pooling": False, + "capacity": False, + "realized_execution": False, + "profitability": False, + }, + } + + +def _research_payload(capture: M8L2StudyConfig, analysis: M8L2AnalysisConfig) -> dict[str, object]: + return { + "question": ( + "Do frozen book-state models reduce future-mid direction log loss versus a " + "historical prior on both untouched sessions?" + ), + "period_start_utc": capture.sessions[0].start.isoformat().replace("+00:00", "Z"), + "period_end_utc": capture.sessions[-1].end.isoformat().replace("+00:00", "Z"), + "symbols": list(capture.study.symbols), + "endpoint_names": [item.name for item in analysis.endpoints], + } + + +def _manifest_payload( + *, + status: M8L2StudyRunStatus, + reason_codes: Sequence[str], + capture: M8L2StudyConfig, + analysis: M8L2AnalysisConfig, + material: _LockMaterial, + snapshots: Sequence[_SessionSnapshot], + generated_at_utc: str, + run_id: str, + artifact_paths: Sequence[str], + tabular_claims: Mapping[str, Mapping[str, object]], +) -> dict[str, object]: + research = _research_payload(capture, analysis) + return { + "schema_version": _SCHEMA_VERSION, + "artifact_kind": "m8_prospective_live_l2_final_study", + "status": status, + "reason_codes": list(reason_codes), + "generated_at_utc": generated_at_utc, + "run_id": run_id, + "evidence_tier": "FULL_DATA", + "effective_evidence_tier": ("FULL_DATA" if status == "COMPLETE" else "INSUFFICIENT_DATA"), + "live_trading": False, + "research": research, + "authority": { + "capture_config_sha256": capture.hash, + "capture_config_source_sha256": capture.source_sha256, + "capture_protocol_sha256": M8_L2_PROTOCOL_SHA256, + "analysis_config_sha256": analysis.hash, + "analysis_config_source_sha256": analysis.source_sha256, + "development_lock_sha256": material.result.aggregate_sha256, + "development_authority": _development_authority_claim(material), + "campaign_identity": material.campaign.to_dict(), + "producer_source_identity": material.source.to_dict(), + }, + "sessions": [dict(row) for row in _session_gate_rows(snapshots)], + "artifacts": [ + {"path": relative, "kind": _artifact_kind(relative)} for relative in artifact_paths + ], + "tabular_outputs": [ + {"path": relative, **dict(tabular_claims[relative])} + for relative in sorted(tabular_claims) + ], + "evaluation": { + "status": "COMPLETE" if status == "COMPLETE" else "NOT_RUN", + "selection_roles": ["train", "validation"], + "heldout_roles": ["primary_test", "replication_test"], + "model_refit_after_development_lock": False, + "p_values_computed": False, + "cross_symbol_pooling": False, + }, + "execution": { + "status": "SCENARIO_ONLY" if status == "COMPLETE" else "NOT_RUN", + "market_orders_only": True, + "live_trading": False, + "realized_execution": False, + "capacity_claim_authorized": False, + "profitability_claim_authorized": False, + }, + "claims": { + "p_values": False, + "significance": False, + "cross_symbol_pooling": False, + "capacity": False, + "realized_execution": False, + "profitability": False, + }, + "terminal_marker": { + "path": _SUCCESS_NAME if status == "COMPLETE" else _INSUFFICIENT_NAME, + "bytes": "complete\\n" if status == "COMPLETE" else "terminal\\n", + }, + } + + +def _normalize_nonfinite(frame: pl.DataFrame) -> pl.DataFrame: + float_columns = [name for name, dtype in frame.schema.items() if dtype.is_float()] + if not float_columns: + return frame + return frame.with_columns( + *[ + pl.when(pl.col(name).is_finite().fill_null(False)) + .then(pl.col(name)) + .otherwise(None) + .alias(name) + for name in float_columns + ] + ) + + +def _require_finite_causal(frame: pl.DataFrame, label: str) -> None: + for name, dtype in frame.schema.items(): + if ( + dtype.is_float() + and frame.select((~pl.col(name).is_finite()).fill_null(False).any()).item() + ): + raise M8L2StudyPipelineError(f"{label} contains non-finite {name}") + + +def _tabular_claim(frame: pl.DataFrame) -> dict[str, object]: + return { + "rows": frame.height, + "frame_sha256": _frame_sha256(frame), + "columns": frame.columns, + } + + +def _write_claimed_frame( + stage: Path, + relative: str, + frame: pl.DataFrame, + claims: dict[str, Mapping[str, object]], + *, + causal: bool = False, +) -> None: + output = frame + if causal: + _require_finite_causal(output, relative) + else: + output = _normalize_nonfinite(output) + claims[relative] = _tabular_claim(output) + _write_parquet(_join(stage, relative), output) + + +def _write_complete_tabular_outputs( + stage: Path, + *, + causal: Mapping[tuple[str, str, str, str], pl.DataFrame], + heldout: Sequence[L2HeldoutEndpointFrame], + evaluation: L2EvaluationResult, + descriptive: L2DescriptiveAnalysis, + references: Mapping[str, L2ExecutionReference], +) -> Mapping[str, Mapping[str, object]]: + claims: dict[str, Mapping[str, object]] = {} + for key in sorted(causal): + _write_claimed_frame(stage, _causal_relative(key), causal[key], claims, causal=True) + evaluation_frames = { + _EVALUATION_PATHS[0]: evaluation.predictions, + _EVALUATION_PATHS[1]: evaluation.predictive_metrics, + _EVALUATION_PATHS[2]: evaluation.paired_by_session_regime, + _EVALUATION_PATHS[3]: evaluation.equal_session_summary, + _EVALUATION_PATHS[4]: evaluation.signed_markout, + } + for relative, frame in evaluation_frames.items(): + _write_claimed_frame(stage, relative, frame, claims) + descriptive_frames = { + _DESCRIPTIVE_PATHS[0]: descriptive.intraday_liquidity, + _DESCRIPTIVE_PATHS[1]: descriptive.ofi_return_association, + _DESCRIPTIVE_PATHS[2]: descriptive.signal_half_life, + _DESCRIPTIVE_PATHS[3]: descriptive.liquidity_recovery, + _DESCRIPTIVE_PATHS[4]: descriptive.regime_diagnostics, + _DESCRIPTIVE_PATHS[5]: descriptive.feature_stability, + _DESCRIPTIVE_PATHS[6]: descriptive.cross_instrument_stability, + } + for relative, frame in descriptive_frames.items(): + _write_claimed_frame(stage, relative, frame, claims) + + metric_frames: list[pl.DataFrame] = [] + assumption_frames: list[pl.DataFrame] = [] + for item in sorted( + heldout, + key=lambda value: (value.study_date, value.symbol, value.endpoint_name), + ): + coordinate_predictions = ( + evaluation.predictions.lazy() + .filter( + (pl.col("study_date") == item.study_date) + & (pl.col("symbol") == item.symbol) + & (pl.col("endpoint_name") == item.endpoint_name) + & (pl.col("study_role") == item.study_role) + ) + .select(*_EXECUTION_PREDICTION_COLUMNS) + .collect() + ) + _require_memory_budget( + _execution_workspace_upper_bytes(item.frame, coordinate_predictions), + _MAX_EXECUTION_WORKSPACE_BYTES, + ( + f"{item.study_date} {item.symbol} {item.endpoint_name} " + "execution input/Python-row/ledger admission" + ), + ) + projected_events = _project_frame( + item.frame, + _EXECUTION_EVENT_COLUMNS, + "execution coordinate events", + ) + coordinate_evaluation = L2EvaluationResult( + predictions=coordinate_predictions, + predictive_metrics=pl.DataFrame(), + paired_by_session_regime=pl.DataFrame(), + equal_session_summary=pl.DataFrame(), + signed_markout=pl.DataFrame(), + ) + execution_item = L2HeldoutEndpointFrame( + symbol=item.symbol, + endpoint_name=item.endpoint_name, + study_date=item.study_date, + study_role=item.study_role, + frame=projected_events, + ) + execution = run_locked_l2_market_execution( + coordinate_evaluation, + (execution_item,), + (references[item.symbol],), + ) + execution_outputs = ( + execution.orders, + execution.fills, + execution.positions, + execution.metrics, + execution.assumptions, + ) + _require_memory_budget( + _frames_bytes([coordinate_predictions, projected_events, *execution_outputs]), + _MAX_EXECUTION_WORKSPACE_BYTES, + ( + f"{item.study_date} {item.symbol} {item.endpoint_name} " + "execution projected inputs and retained ledgers" + ), + ) + for name, frame in ( + ("orders", execution.orders), + ("fills", execution.fills), + ("positions", execution.positions), + ): + _write_claimed_frame(stage, _execution_relative(item, name), frame, claims) + metric_frames.append(execution.metrics) + assumption_frames.append(execution.assumptions) + del ( + coordinate_predictions, + projected_events, + coordinate_evaluation, + execution_item, + execution_outputs, + execution, + ) + _require_memory_budget( + _frames_bytes([*metric_frames, *assumption_frames]) * 2, + _MAX_EXECUTION_WORKSPACE_BYTES, + "execution metric/assumption concat admission", + ) + metrics = _normalize_nonfinite(pl.concat(metric_frames, how="diagonal_relaxed")) + assumptions = _normalize_nonfinite(pl.concat(assumption_frames, how="diagonal_relaxed")) + _write_claimed_frame(stage, "execution/metrics.parquet", metrics, claims) + _write_claimed_frame(stage, "execution/assumptions.parquet", assumptions, claims) + return claims + + +def _write_insufficient_causal_outputs( + stage: Path, + causal: Mapping[tuple[str, str, str, str], pl.DataFrame], +) -> Mapping[str, Mapping[str, object]]: + claims: dict[str, Mapping[str, object]] = {} + for key in sorted(causal): + _write_claimed_frame(stage, _causal_relative(key), causal[key], claims, causal=True) + return claims + + +def _json_rows(frame: pl.DataFrame) -> tuple[Mapping[str, Any], ...]: + normalized = _normalize_nonfinite(frame) + rows = tuple(cast(Mapping[str, Any], row) for row in normalized.to_dicts()) + try: + json.dumps(rows, allow_nan=False) + except (TypeError, ValueError) as error: + raise M8L2StudyPipelineError("report metric rows are not strict finite JSON") from error + return rows + + +def _hypothesis_payload( + status: M8L2StudyRunStatus, + reason_codes: Sequence[str], + evaluation: L2EvaluationResult | None, +) -> dict[str, object]: + if status == "INSUFFICIENT_DATA": + return { + "status": "INSUFFICIENT_DATA", + "conclusion": ( + "The frozen study is INSUFFICIENT_DATA and no held-out predictive or " + f"execution conclusion is authorized. Reasons: {', '.join(reason_codes)}." + ), + "directionally_replicated_pairs": 0, + "declared_pairs": 8, + } + assert evaluation is not None + overall = evaluation.equal_session_summary.filter(pl.col("regime") == "ALL") + replicated = overall.filter(pl.col("directionally_replicated")).height + total = overall.height + return { + "status": "DESCRIPTIVE_COMPLETE", + "conclusion": ( + f"Directional improvement replicated on both untouched sessions for {replicated} " + f"of {total} symbol-endpoint pairs. This is descriptive, not a significance, " + "capacity, realized-execution, or profitability claim." + ), + "directionally_replicated_pairs": replicated, + "declared_pairs": total, + } + + +def _report_data( + *, + manifest: Mapping[str, Any], + provenance: Mapping[str, Any], + snapshots: Sequence[_SessionSnapshot], + status: M8L2StudyRunStatus, + reason_codes: Sequence[str], + evaluation: L2EvaluationResult | None, + execution_metrics: pl.DataFrame | None, +) -> L2ReportData: + paired_rows: tuple[Mapping[str, Any], ...] = () + equal_rows: tuple[Mapping[str, Any], ...] = () + predictive_rows: tuple[Mapping[str, Any], ...] = () + if evaluation is not None: + predictive_rows = _json_rows(evaluation.predictive_metrics) + paired_rows = tuple( + {**dict(row), "status": row.get("bootstrap_status")} + for row in _json_rows(evaluation.paired_by_session_regime) + ) + equal_rows = tuple( + {**dict(row), "status": row.get("replication_status")} + for row in _json_rows(evaluation.equal_session_summary) + ) + return L2ReportData( + manifest=manifest, + provenance=provenance, + session_gates=_session_gate_rows(snapshots), + hypothesis=_hypothesis_payload(status, reason_codes, evaluation), + predictive_metrics=predictive_rows, + paired_metrics=paired_rows, + equal_session_metrics=equal_rows, + execution_metrics=(_json_rows(execution_metrics) if execution_metrics is not None else ()), + ) + + +def _report_snapshot_payload(data: L2ReportData) -> dict[str, object]: + return { + "schema_version": _REPORT_INPUT_SCHEMA_VERSION, + "artifact_kind": "m8_l2_verified_report_inputs", + "report_data_sha256": canonical_report_data_sha256(data), + "data": { + "manifest": dict(data.manifest), + "provenance": dict(data.provenance), + "session_gates": [dict(row) for row in data.session_gates], + "hypothesis": dict(data.hypothesis), + "predictive_metrics": [dict(row) for row in data.predictive_metrics], + "paired_metrics": [dict(row) for row in data.paired_metrics], + "equal_session_metrics": [dict(row) for row in data.equal_session_metrics], + "execution_metrics": [dict(row) for row in data.execution_metrics], + }, + } + + +def _write_report_artifacts(stage: Path, data: L2ReportData) -> None: + snapshot = _report_snapshot_payload(data) + snapshot_sha = _write_json(stage / "report_inputs.json", snapshot) + _write_bytes(stage / "report_inputs.sha256", f"{snapshot_sha} report_inputs.json\n".encode()) + _write_bytes( + stage / "reports" / "technical_report.md", + render_l2_technical_report(data).encode("utf-8"), + ) + _write_bytes( + stage / "reports" / "executive_memo.md", + render_l2_executive_memo(data).encode("utf-8"), + ) + _write_bytes( + stage / "reports" / "model_comparison.md", + render_l2_model_comparison(data).encode("utf-8"), + ) + + +def _walk_regular(root: Path) -> dict[str, Path]: + result: dict[str, Path] = {} + pending = [root] + while pending: + directory = pending.pop() + try: + entries = sorted(os.scandir(directory), key=lambda item: item.name) + except OSError as error: + raise M8L2StudyPipelineError("cannot enumerate final-run inventory") from error + for entry in entries: + path = Path(entry.path) + relative = _relative(path, root) + if entry.is_symlink(): + raise M8L2StudyPipelineError(f"final-run inventory contains symlink {relative}") + if entry.is_dir(follow_symlinks=False): + pending.append(path) + elif entry.is_file(follow_symlinks=False): + result[relative] = path + else: + raise M8L2StudyPipelineError( + f"final-run inventory contains non-regular entry {relative}" + ) + return dict(sorted(result.items())) + + +def _write_checksum_manifest(stage: Path, expected_paths: Sequence[str]) -> str: + files = _walk_regular(stage) + expected = set(expected_paths) | {"run_manifest.json"} + if set(files) != expected: + raise M8L2StudyPipelineError( + "preterminal final-run inventory differs from manifest-declared artifacts " + f"(missing={sorted(expected - set(files))}, extra={sorted(set(files) - expected)})" + ) + raw = "".join(f"{sha256_file(path)} {relative}\n" for relative, path in files.items()).encode( + "ascii" + ) + _write_bytes(stage / _CHECKSUMS_NAME, raw) + return hashlib.sha256(raw).hexdigest() + + +def _parent_identity(path: Path) -> _ParentIdentity: + metadata = path.lstat() + if not stat.S_ISDIR(metadata.st_mode): + raise M8L2StudyPipelineError("M8 L2 publication parent is not a directory") + return _ParentIdentity(metadata.st_dev, metadata.st_ino) + + +def _reserve_stage(target: Path) -> tuple[Path, _ParentIdentity]: + target.parent.mkdir(parents=True, exist_ok=True) + _reject_symlink_components(target.parent) + if target.exists() or target.is_symlink(): + raise M8L2StudyPipelineError( + f"M8 L2 run destination already exists and is not reusable: {target}" + ) + identity = _parent_identity(target.parent) + stage = Path(tempfile.mkdtemp(prefix=f".{target.name}.stage-", dir=target.parent)) + if _parent_identity(stage.parent) != identity: + shutil.rmtree(stage, ignore_errors=True) + raise M8L2StudyPipelineError("M8 L2 publication parent changed during stage reservation") + _fsync_directory(target.parent) + return stage, identity + + +def _atomic_rename_no_replace(stage: Path, target: Path) -> None: + """Use the platform's exclusive directory rename; never fall back to replace.""" + + library = ctypes.CDLL(None, use_errno=True) + source = os.fsencode(stage) + destination = os.fsencode(target) + if sys.platform == "darwin" and hasattr(library, "renameatx_np"): + operation = library.renameatx_np + operation.argtypes = [ + ctypes.c_int, + ctypes.c_char_p, + ctypes.c_int, + ctypes.c_char_p, + ctypes.c_uint, + ] + operation.restype = ctypes.c_int + result = operation(-2, source, -2, destination, 0x00000004) # RENAME_EXCL + elif hasattr(library, "renameat2"): + operation = library.renameat2 + operation.argtypes = [ + ctypes.c_int, + ctypes.c_char_p, + ctypes.c_int, + ctypes.c_char_p, + ctypes.c_uint, + ] + operation.restype = ctypes.c_int + result = operation(-100, source, -100, destination, 1) # RENAME_NOREPLACE + else: # pragma: no cover - supported production platforms expose one primitive + raise M8L2StudyPipelineError( + "platform lacks an atomic no-replace directory publication primitive" + ) + if result != 0: + observed_errno = ctypes.get_errno() + if observed_errno in {errno.EEXIST, errno.ENOTEMPTY}: + raise M8L2StudyPipelineError("M8 L2 run destination appeared during atomic publication") + raise M8L2StudyPipelineError(f"atomic M8 L2 publication failed with errno {observed_errno}") + + +def _publish_stage_no_overwrite( + stage: Path, target: Path, expected_parent: _ParentIdentity +) -> None: + _reject_symlink_components(target.parent) + if _parent_identity(target.parent) != expected_parent or stage.parent != target.parent: + raise M8L2StudyPipelineError("M8 L2 publication parent identity changed") + if target.exists() or target.is_symlink(): + raise M8L2StudyPipelineError("M8 L2 run destination appeared during atomic publication") + _atomic_rename_no_replace(stage, target) + if _parent_identity(target.parent) != expected_parent: + raise M8L2StudyPipelineError("M8 L2 publication parent changed after rename") + _fsync_directory(target.parent) + + +def _copy_authorities(stage: Path, sources: Mapping[str, tuple[Path, str]]) -> None: + for relative, (source, expected_sha256) in sources.items(): + observed = _copy_exact( + source, + _join(stage, relative), + expected_sha256=expected_sha256, + ) + if observed != expected_sha256: + raise M8L2StudyPipelineError("authority snapshot copy changed its digest") + + +def _terminal_revalidation( + *, + capture: M8L2StudyConfig, + analysis: M8L2AnalysisConfig, + train: L2StudySessionAuthority, + validation: L2StudySessionAuthority, + primary: L2StudySessionAuthority, + replication: L2StudySessionAuthority, + lock_dir: str | Path, + lock_sha256: str, + material: _LockMaterial, + snapshots: Sequence[_SessionSnapshot], + require_current_runtime: bool = False, +) -> None: + reloaded_capture, reloaded_analysis = _revalidate_configs(capture, analysis) + if reloaded_capture != capture or reloaded_analysis != analysis: + raise M8L2StudyPipelineError("frozen configs changed during final production") + _reverify_material( + capture, + analysis, + train, + validation, + lock_dir, + lock_sha256, + material, + ) + repeated = _verify_all_sessions(capture, material, (train, validation, primary, replication)) + if tuple(repeated) != tuple(snapshots): + raise M8L2StudyPipelineError("session authorities changed during final production") + if require_current_runtime: + _assert_current_runtime(material.campaign) + # This is deliberately last: after marker durability on the second + # producer call, no authority work remains between this loaded-code + # origin proof and the exclusive terminal-directory rename. + _assert_final_producer_import_origins(capture.path.parent.parent.resolve()) + + +def _publish_run( + *, + status: M8L2StudyRunStatus, + reason_codes: Sequence[str], + capture: M8L2StudyConfig, + analysis: M8L2AnalysisConfig, + train: L2StudySessionAuthority, + validation: L2StudySessionAuthority, + primary: L2StudySessionAuthority, + replication: L2StudySessionAuthority, + lock_dir: str | Path, + lock_sha256: str, + material: _LockMaterial, + snapshots: Sequence[_SessionSnapshot], + causal: Mapping[tuple[str, str, str, str], pl.DataFrame], + heldout: Sequence[L2HeldoutEndpointFrame], + evaluation: L2EvaluationResult | None, + descriptive: L2DescriptiveAnalysis | None, + run_dir: str | Path, +) -> M8L2StudyRunResult: + target = Path(run_dir).absolute() + stage, parent_identity = _reserve_stage(target) + marker = stage / (_SUCCESS_NAME if status == "COMPLETE" else _INSUFFICIENT_NAME) + published = False + try: + sources = _authority_sources(capture, analysis, snapshots, material) + _copy_authorities(stage, sources) + if status == "COMPLETE": + if evaluation is None or descriptive is None: + raise M8L2StudyPipelineError("complete final run lacks economic outputs") + tabular_claims = _write_complete_tabular_outputs( + stage, + causal=causal, + heldout=heldout, + evaluation=evaluation, + descriptive=descriptive, + references=material.references, + ) + execution_metrics = pl.read_parquet(stage / "execution" / "metrics.parquet") + else: + tabular_claims = _write_insufficient_causal_outputs(stage, causal) + execution_metrics = None + artifact_paths = _planned_paths( + authority_paths=tuple(sources), + causal=causal, + heldout=heldout, + complete=status == "COMPLETE", + ) + generated_at = utc_now_iso() + run_id = _run_identity(capture, analysis, material, snapshots) + provenance = _provenance_payload( + status=status, + capture=capture, + analysis=analysis, + material=material, + snapshots=snapshots, + generated_at_utc=generated_at, + run_id=run_id, + ) + _write_json(stage / "provenance.json", provenance) + manifest = _manifest_payload( + status=status, + reason_codes=reason_codes, + capture=capture, + analysis=analysis, + material=material, + snapshots=snapshots, + generated_at_utc=generated_at, + run_id=run_id, + artifact_paths=artifact_paths, + tabular_claims=tabular_claims, + ) + _write_json(stage / "run_manifest.json", manifest) + report_data = _report_data( + manifest=manifest, + provenance=provenance, + snapshots=snapshots, + status=status, + reason_codes=reason_codes, + evaluation=evaluation, + execution_metrics=execution_metrics, + ) + _write_report_artifacts(stage, report_data) + _terminal_revalidation( + capture=capture, + analysis=analysis, + train=train, + validation=validation, + primary=primary, + replication=replication, + lock_dir=lock_dir, + lock_sha256=lock_sha256, + material=material, + snapshots=snapshots, + require_current_runtime=True, + ) + _write_checksum_manifest(stage, artifact_paths) + _fsync_directory(stage) + _write_bytes(marker, _SUCCESS_BYTES if status == "COMPLETE" else _INSUFFICIENT_BYTES) + _fsync_directory(stage) + # Checksumming and durable terminal staging can be materially slower + # than the earlier authority check. Revalidate every external input, + # lock, config, and source identity again at the actual publication + # boundary so a transient or sustained drift cannot be renamed into a + # terminal authority. + _terminal_revalidation( + capture=capture, + analysis=analysis, + train=train, + validation=validation, + primary=primary, + replication=replication, + lock_dir=lock_dir, + lock_sha256=lock_sha256, + material=material, + snapshots=snapshots, + require_current_runtime=True, + ) + _publish_stage_no_overwrite(stage, target, parent_identity) + published = True + return _verify_m8_l2_study_run( + capture, + analysis, + train, + validation, + lock_dir, + lock_sha256, + primary, + replication, + target, + expected_manifest_sha256=sha256_file(target / "run_manifest.json"), + expected_checksums_sha256=sha256_file(target / _CHECKSUMS_NAME), + ) + except BaseException: + if not published: + shutil.rmtree(stage, ignore_errors=True) + _fsync_directory(target.parent) + raise + + +def _reproduce_m8_l2_study( + capture_config: M8L2StudyConfig, + analysis_config: M8L2AnalysisConfig, + train_session: L2StudySessionAuthority, + validation_session: L2StudySessionAuthority, + development_lock_dir: str | Path, + expected_development_lock_sha256: str, + primary_session: L2StudySessionAuthority, + replication_session: L2StudySessionAuthority, + run_dir: str | Path, + *, + expected_existing_manifest_sha256: str | None, + expected_existing_checksums_sha256: str | None, +) -> M8L2StudyRunResult: + _assert_final_producer_import_origins(capture_config.path.parent.parent.resolve()) + capture, analysis = _revalidate_configs(capture_config, analysis_config) + target = Path(run_dir).absolute() + lock_result, aggregate, campaign, source = _verify_lock_context( + capture, + analysis, + train_session, + validation_session, + development_lock_dir, + expected_development_lock_sha256, + ) + _assert_current_runtime(campaign) + if (expected_existing_manifest_sha256 is None) != (expected_existing_checksums_sha256 is None): + raise M8L2StudyPipelineError( + "existing-run manifest and checksum authorities must be supplied together" + ) + if target.exists() or target.is_symlink(): + if target.is_symlink() or not target.is_dir(): + raise M8L2StudyPipelineError("existing M8 L2 run target is not a regular directory") + terminal = [ + name for name in (_SUCCESS_NAME, _INSUFFICIENT_NAME) if (target / name).exists() + ] + if len(terminal) != 1: + raise M8L2StudyPipelineError( + "existing M8 L2 target is unterminated or has conflicting terminal markers" + ) + if expected_existing_manifest_sha256 is None or expected_existing_checksums_sha256 is None: + raise M8L2StudyPipelineError( + "existing M8 L2 target requires caller-held manifest and checksum authorities" + ) + return _verify_m8_l2_study_run( + capture, + analysis, + train_session, + validation_session, + development_lock_dir, + expected_development_lock_sha256, + primary_session, + replication_session, + target, + expected_manifest_sha256=expected_existing_manifest_sha256, + expected_checksums_sha256=expected_existing_checksums_sha256, + ) + if expected_existing_manifest_sha256 is not None: + raise M8L2StudyPipelineError( + "existing-run authorities were supplied but the target does not exist" + ) + + material = _load_lock_material(capture, analysis, lock_result, aggregate, campaign, source) + snapshots = _verify_all_sessions( + capture, + material, + (train_session, validation_session, primary_session, replication_session), + ) + if getattr(getattr(material, "result", None), "status", "LOCKED") == "NOT_CREATED": + reasons = _not_created_final_reasons(snapshots) + if not reasons or tuple(material.result.reason_codes) != tuple( + reason for reason in reasons if reason.startswith("DEVELOPMENT_") + ): + raise M8L2StudyPipelineError( + "NOT_CREATED development reasons differ from the four-session authority" + ) + return _publish_run( + status="INSUFFICIENT_DATA", + reason_codes=reasons, + capture=capture, + analysis=analysis, + train=train_session, + validation=validation_session, + primary=primary_session, + replication=replication_session, + lock_dir=development_lock_dir, + lock_sha256=expected_development_lock_sha256, + material=material, + snapshots=snapshots, + causal={}, + heldout=(), + evaluation=None, + descriptive=None, + run_dir=target, + ) + heldout_failures = [item for item in snapshots[2:] if item.bundle.status != "COMPLETE"] + if heldout_failures: + reasons = tuple( + sorted( + { + f"{item.bundle.role}::{reason}" + for item in heldout_failures + for reason in (item.bundle.reason_codes or ("SESSION_INSUFFICIENT_DATA",)) + } + ) + ) + return _publish_run( + status="INSUFFICIENT_DATA", + reason_codes=reasons, + capture=capture, + analysis=analysis, + train=train_session, + validation=validation_session, + primary=primary_session, + replication=replication_session, + lock_dir=development_lock_dir, + lock_sha256=expected_development_lock_sha256, + material=material, + snapshots=snapshots, + causal={}, + heldout=(), + evaluation=None, + descriptive=None, + run_dir=target, + ) + + causal, heldout = _build_causal_frames( + capture, + analysis, + snapshots, + material, + train=train_session, + validation=validation_session, + lock_dir=development_lock_dir, + lock_sha256=expected_development_lock_sha256, + ) + availability_reasons = _heldout_availability_reasons(heldout) + if availability_reasons: + return _publish_run( + status="INSUFFICIENT_DATA", + reason_codes=availability_reasons, + capture=capture, + analysis=analysis, + train=train_session, + validation=validation_session, + primary=primary_session, + replication=replication_session, + lock_dir=development_lock_dir, + lock_sha256=expected_development_lock_sha256, + material=material, + snapshots=snapshots, + causal=causal, + heldout=heldout, + evaluation=None, + descriptive=None, + run_dir=target, + ) + _require_memory_budget( + _evaluation_workspace_upper_bytes( + heldout, + feature_count=len(analysis.features.model_feature_columns), + ), + _MAX_EVALUATION_WORKSPACE_BYTES, + "held-out evaluation child-frame/concat admission", + ) + evaluation = evaluate_locked_l2_endpoints( + tuple(material.states[key] for key in sorted(material.states)), + heldout, + bootstrap_samples=analysis.bootstrap.samples, + seed=analysis.study.seed, + calibration_bins=analysis.calibration.bins, + ) + evaluation_frames = ( + evaluation.predictions, + evaluation.predictive_metrics, + evaluation.paired_by_session_regime, + evaluation.equal_session_summary, + evaluation.signed_markout, + ) + _require_memory_budget( + _frames_bytes(evaluation_frames), + _MAX_EVALUATION_WORKSPACE_BYTES, + "held-out evaluation retained outputs", + ) + + causal_values = tuple(causal[key] for key in sorted(causal)) + descriptive_columns = _descriptive_projection_columns(analysis.features.model_feature_columns) + _require_memory_budget( + _descriptive_workspace_upper_bytes(causal_values, columns=descriptive_columns), + _MAX_DESCRIPTIVE_WORKSPACE_BYTES, + "descriptive projection/concat/output admission", + ) + descriptive_inputs = tuple( + _project_frame(frame, descriptive_columns, "descriptive endpoint") + for frame in causal_values + ) + descriptive = build_l2_descriptive_analysis( + descriptive_inputs, + feature_columns=analysis.features.model_feature_columns, + stability_bins=analysis.calibration.bins, + ) + descriptive_outputs = ( + descriptive.intraday_liquidity, + descriptive.ofi_return_association, + descriptive.signal_half_life, + descriptive.liquidity_recovery, + descriptive.regime_diagnostics, + descriptive.feature_stability, + descriptive.cross_instrument_stability, + ) + _require_memory_budget( + _frames_bytes([*descriptive_inputs, *descriptive_outputs]), + _MAX_DESCRIPTIVE_WORKSPACE_BYTES, + "descriptive projected inputs and retained outputs", + ) + del causal_values, descriptive_inputs, descriptive_outputs, evaluation_frames + return _publish_run( + status="COMPLETE", + reason_codes=(), + capture=capture, + analysis=analysis, + train=train_session, + validation=validation_session, + primary=primary_session, + replication=replication_session, + lock_dir=development_lock_dir, + lock_sha256=expected_development_lock_sha256, + material=material, + snapshots=snapshots, + causal=causal, + heldout=heldout, + evaluation=evaluation, + descriptive=descriptive, + run_dir=target, + ) + + +def _stable_file_sha256(path: Path, label: str) -> str: + try: + before_path = path.lstat() + except OSError as error: + raise M8L2StudyRunVerificationError(f"cannot stat {label}") from error + if not stat.S_ISREG(before_path.st_mode): + raise M8L2StudyRunVerificationError(f"{label} is not a regular file") + flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0) + try: + descriptor = os.open(path, flags) + except OSError as error: + raise M8L2StudyRunVerificationError(f"cannot securely open {label}") from error + try: + before = os.fstat(descriptor) + if not _same_stat(before_path, before): + raise M8L2StudyRunVerificationError(f"{label} changed before hashing") + digest = hashlib.sha256() + while chunk := os.read(descriptor, 1 << 20): + digest.update(chunk) + after = os.fstat(descriptor) + after_path = path.lstat() + if not _same_stat(before, after) or not _same_stat(after, after_path): + raise M8L2StudyRunVerificationError(f"{label} changed while hashing") + return digest.hexdigest() + finally: + os.close(descriptor) + + +def _report_mapping_tuple(value: object, label: str) -> tuple[Mapping[str, Any], ...]: + if not isinstance(value, list): + raise M8L2StudyRunVerificationError(f"{label} must be an array") + return tuple(_mapping(item, f"{label} entry") for item in value) + + +def _load_report_data_snapshot(root: Path) -> L2ReportData: + payload, raw = _read_json(root / "report_inputs.json", "L2 report-input snapshot") + if set(payload) != { + "schema_version", + "artifact_kind", + "report_data_sha256", + "data", + } or ( + payload.get("schema_version") != _REPORT_INPUT_SCHEMA_VERSION + or payload.get("artifact_kind") != "m8_l2_verified_report_inputs" + ): + raise M8L2StudyRunVerificationError("L2 report-input snapshot schema differs") + sidecar = _read_regular( + root / "report_inputs.sha256", + label="L2 report-input digest sidecar", + maximum_bytes=256, + ) + snapshot_sha = hashlib.sha256(raw).hexdigest() + if sidecar != f"{snapshot_sha} report_inputs.json\n".encode("ascii"): + raise M8L2StudyRunVerificationError("L2 report-input digest sidecar differs") + raw_data = _mapping(payload.get("data"), "L2 report inputs") + if set(raw_data) != { + "manifest", + "provenance", + "session_gates", + "hypothesis", + "predictive_metrics", + "paired_metrics", + "equal_session_metrics", + "execution_metrics", + }: + raise M8L2StudyRunVerificationError("L2 report-input data keys differ") + data = L2ReportData( + manifest=_mapping(raw_data.get("manifest"), "report manifest"), + provenance=_mapping(raw_data.get("provenance"), "report provenance"), + session_gates=_report_mapping_tuple(raw_data.get("session_gates"), "session gates"), + hypothesis=_mapping(raw_data.get("hypothesis"), "report hypothesis"), + predictive_metrics=_report_mapping_tuple( + raw_data.get("predictive_metrics"), "predictive metrics" + ), + paired_metrics=_report_mapping_tuple(raw_data.get("paired_metrics"), "paired metrics"), + equal_session_metrics=_report_mapping_tuple( + raw_data.get("equal_session_metrics"), "equal-session metrics" + ), + execution_metrics=_report_mapping_tuple( + raw_data.get("execution_metrics"), "execution metrics" + ), + ) + if payload.get("report_data_sha256") != canonical_report_data_sha256(data): + raise M8L2StudyRunVerificationError("L2 report inputs differ from their canonical digest") + return data + + +def _verify_report_artifacts( + root: Path, + manifest: Mapping[str, Any], + provenance: Mapping[str, Any], +) -> None: + data = _load_report_data_snapshot(root) + if dict(data.manifest) != dict(manifest) or dict(data.provenance) != dict(provenance): + raise M8L2StudyRunVerificationError( + "report-input snapshot differs from run manifest/provenance" + ) + expected = { + "reports/technical_report.md": render_l2_technical_report(data).encode("utf-8"), + "reports/executive_memo.md": render_l2_executive_memo(data).encode("utf-8"), + "reports/model_comparison.md": render_l2_model_comparison(data).encode("utf-8"), + } + for relative, raw in expected.items(): + if ( + _read_regular( + _join(root, relative), label=f"rendered report {relative}", maximum_bytes=32 << 20 + ) + != raw + ): + raise M8L2StudyRunVerificationError( + f"rendered report {relative} differs from verified machine artifacts" + ) + + +def _tabular_claims_from_manifest( + manifest: Mapping[str, Any], +) -> Mapping[str, Mapping[str, Any]]: + raw = manifest.get("tabular_outputs") + if not isinstance(raw, list): + raise M8L2StudyRunVerificationError("run manifest tabular_outputs must be an array") + result: dict[str, Mapping[str, Any]] = {} + for item in raw: + claim = _mapping(item, "tabular output claim") + if set(claim) != {"path", "rows", "frame_sha256", "columns"}: + raise M8L2StudyRunVerificationError("tabular output claim keys differ") + relative = _safe_relative(_string(claim.get("path"), "tabular output path")) + rows = claim.get("rows") + columns = claim.get("columns") + digest = claim.get("frame_sha256") + if ( + isinstance(rows, bool) + or not isinstance(rows, int) + or rows < 0 + or not isinstance(columns, list) + or not all(type(value) is str for value in columns) + or type(digest) is not str + or not _is_sha256(digest) + or relative in result + ): + raise M8L2StudyRunVerificationError("tabular output claim is malformed") + result[relative] = claim + if list(result) != sorted(result): + raise M8L2StudyRunVerificationError("tabular output claims are not canonically ordered") + return result + + +def _read_claimed_parquet( + root: Path, + relative: str, + claim: Mapping[str, Any], +) -> pl.DataFrame: + try: + frame = pl.read_parquet(_join(root, relative)) + except (OSError, pl.exceptions.PolarsError) as error: + raise M8L2StudyRunVerificationError( + f"cannot restore claimed tabular artifact {relative}" + ) from error + if ( + frame.height != claim.get("rows") + or frame.columns != claim.get("columns") + or _frame_sha256(frame) != claim.get("frame_sha256") + ): + raise M8L2StudyRunVerificationError( + f"tabular artifact {relative} differs from its semantic claim" + ) + return frame + + +def _verify_one_causal_output( + frame: pl.DataFrame, + *, + analysis: M8L2AnalysisConfig, + expected_key: tuple[str, str, str, str], +) -> None: + validate_l2_endpoint_frame(frame) + coordinate = frame.select("study_date", "study_role", "symbol", "endpoint_name").unique() + if coordinate.height != 1: + raise M8L2StudyRunVerificationError("causal artifact has multiple coordinates") + row = coordinate.row(0, named=True) + observed_key = ( + str(row["study_date"]), + str(row["study_role"]), + str(row["symbol"]), + str(row["endpoint_name"]), + ) + if observed_key != expected_key: + raise M8L2StudyRunVerificationError("causal artifact path/coordinate differs") + if ( + l2_model_feature_columns(frame, windows=analysis.features.rolling_windows) + != analysis.features.model_feature_columns + ): + raise M8L2StudyRunVerificationError("causal artifact feature contract differs") + _require_finite_causal(frame, _causal_relative(expected_key)) + + +def _verify_partition_frame( + frame: pl.DataFrame, + *, + key: tuple[str, str, str, str], + family: str, + aggregate_lock_sha256: str, +) -> None: + study_date, role, symbol, endpoint = key + required = { + "scenario_id", + "scenario_symbol", + "study_date", + "study_role", + "endpoint_name", + "decision_latency_events", + "order_latency_events", + "child_lock_sha256", + "aggregate_lock_sha256", + } + if not required.issubset(frame.columns): + raise M8L2StudyRunVerificationError(f"execution {family} partition lacks authority columns") + if frame.is_empty(): + return + expected_values: Mapping[str, object] = { + "scenario_symbol": symbol, + "study_date": study_date, + "study_role": role, + "endpoint_name": endpoint, + "aggregate_lock_sha256": aggregate_lock_sha256, + } + for column, expected in expected_values.items(): + if set(frame.get_column(column).unique().to_list()) != {expected}: + raise M8L2StudyRunVerificationError(f"execution {family} partition coordinate differs") + if frame.get_column("scenario_id").n_unique() > 9: + raise M8L2StudyRunVerificationError(f"execution {family} partition has extra scenarios") + if ( + family == "orders" + and "order_type" in frame.columns + and set(frame.get_column("order_type").drop_nulls().unique()).difference({"market"}) + ): + raise M8L2StudyRunVerificationError("execution orders contain a non-market order") + if ( + family == "fills" + and "liquidity" in frame.columns + and set(frame.get_column("liquidity").drop_nulls().unique()).difference({"taker"}) + ): + raise M8L2StudyRunVerificationError("execution fills contain non-taker liquidity") + + +def _verify_tabular_outputs_streaming( + root: Path, + claims: Mapping[str, Mapping[str, Any]], + *, + capture: M8L2StudyConfig, + analysis: M8L2AnalysisConfig, + material: _LockMaterial, + status: M8L2StudyRunStatus, + reasons: Sequence[str], +) -> Mapping[str, pl.DataFrame]: + if getattr(material.result, "status", "LOCKED") == "NOT_CREATED" and claims: + raise M8L2StudyRunVerificationError( + "NOT_CREATED final run must not contain economic tabular outputs" + ) + expected_causal_keys = tuple( + (session.date.isoformat(), session.role, symbol, endpoint.name) + for session in capture.sessions + for symbol in capture.study.symbols + for endpoint in analysis.endpoints + ) + causal_paths = {path for path in claims if path.startswith("causal_frames/")} + expected_causal_paths = {_causal_relative(key) for key in expected_causal_keys} + if status == "COMPLETE" and causal_paths != expected_causal_paths: + raise M8L2StudyRunVerificationError("complete run lacks all 32 causal frames") + if status == "INSUFFICIENT_DATA" and causal_paths and causal_paths != expected_causal_paths: + raise M8L2StudyRunVerificationError("insufficient run has a partial causal-frame set") + if ( + causal_paths + and status == "INSUFFICIENT_DATA" + and not all(reason.startswith("NO_ELIGIBLE_LABELS::") for reason in reasons) + ): + raise M8L2StudyRunVerificationError( + "capture-gate insufficient run must not publish economic frames" + ) + + observed_availability_reasons: list[str] = [] + if causal_paths: + for symbol in capture.study.symbols: + for endpoint in analysis.endpoints: + train_key = ("2026-08-10", "train", symbol, endpoint.name) + validation_key = ("2026-08-11", "validation", symbol, endpoint.name) + train_path = _causal_relative(train_key) + validation_path = _causal_relative(validation_key) + train_frame = _read_claimed_parquet(root, train_path, claims[train_path]) + _require_verification_memory_budget( + _frame_bytes(train_frame), + _MAX_CAUSAL_COORDINATE_BYTES, + "train causal verification coordinate", + ) + _verify_one_causal_output(train_frame, analysis=analysis, expected_key=train_key) + validation_frame = _read_claimed_parquet( + root, validation_path, claims[validation_path] + ) + _require_verification_memory_budget( + _frame_bytes(train_frame) + _frame_bytes(validation_frame), + _MAX_CAUSAL_COORDINATE_BYTES, + "development causal verification pair", + ) + _verify_one_causal_output( + validation_frame, analysis=analysis, expected_key=validation_key + ) + development = pl.concat([train_frame, validation_frame], how="vertical") + _require_verification_memory_budget( + _frame_bytes(train_frame) + + _frame_bytes(validation_frame) + + _frame_bytes(development), + _MAX_CAUSAL_COORDINATE_BYTES, + "development causal verification concat", + ) + if ( + _frame_sha256(development) + != material.development_frame_sha256[(symbol, endpoint.name)] + ): + raise M8L2StudyRunVerificationError( + "published development causal frame differs from child lock" + ) + del train_frame, validation_frame, development + for study_date, role in _EXPECTED_COORDINATES[2:]: + key = (study_date, role, symbol, endpoint.name) + relative = _causal_relative(key) + frame = _read_claimed_parquet(root, relative, claims[relative]) + _require_verification_memory_budget( + _frame_bytes(frame), + _MAX_CAUSAL_COORDINATE_BYTES, + "held-out causal verification coordinate", + ) + _verify_one_causal_output(frame, analysis=analysis, expected_key=key) + eligible = frame.filter( + pl.col("feature_ready") + & (~pl.col("right_censored")) + & pl.col("future_mid_up").is_not_null() + ) + if eligible.is_empty(): + observed_availability_reasons.append( + f"NO_ELIGIBLE_LABELS::{role}::{symbol}::{endpoint.name}" + ) + del frame, eligible + if status == "COMPLETE" and observed_availability_reasons: + raise M8L2StudyRunVerificationError("complete run contains an empty held-out endpoint") + if ( + status == "INSUFFICIENT_DATA" + and causal_paths + and tuple(sorted(observed_availability_reasons)) != tuple(reasons) + ): + raise M8L2StudyRunVerificationError( + "insufficient reasons differ from published causal availability" + ) + + partition_paths = {path for path in claims if path.startswith("execution/partitions/")} + expected_partition_paths: dict[str, tuple[tuple[str, str, str, str], str]] = {} + if status == "COMPLETE": + for study_date, role in _EXPECTED_COORDINATES[2:]: + for symbol in capture.study.symbols: + for endpoint in analysis.endpoints: + key = (study_date, role, symbol, endpoint.name) + for family in ("orders", "fills", "positions"): + relative = ( + f"execution/partitions/{study_date}-{role}/{symbol.lower()}/" + f"{endpoint.name}/{family}.parquet" + ) + expected_partition_paths[relative] = (key, family) + if partition_paths != set(expected_partition_paths): + raise M8L2StudyRunVerificationError("execution partition inventory differs") + for relative in sorted(partition_paths): + frame = _read_claimed_parquet(root, relative, claims[relative]) + _require_verification_memory_budget( + _frame_bytes(frame), + _MAX_EXECUTION_WORKSPACE_BYTES, + "execution partition verification coordinate", + ) + key, family = expected_partition_paths[relative] + _verify_partition_frame( + frame, + key=key, + family=family, + aggregate_lock_sha256=material.result.aggregate_sha256, + ) + del frame + + retained_paths = set(claims) - causal_paths - partition_paths + retained: dict[str, pl.DataFrame] = {} + retained_bytes = {"evaluation": 0, "descriptive": 0, "execution": 0} + for relative in sorted(retained_paths): + frame = _read_claimed_parquet(root, relative, claims[relative]) + category = relative.split("/", 1)[0] + if category not in retained_bytes: + raise M8L2StudyRunVerificationError(f"unclassified retained tabular output {relative}") + retained_bytes[category] += _frame_bytes(frame) + maximum = { + "evaluation": _MAX_EVALUATION_WORKSPACE_BYTES, + "descriptive": _MAX_DESCRIPTIVE_WORKSPACE_BYTES, + "execution": _MAX_EXECUTION_WORKSPACE_BYTES, + }[category] + _require_verification_memory_budget( + retained_bytes[category], maximum, f"retained {category} verification outputs" + ) + retained[relative] = frame + return retained + + +def _all_false(frame: pl.DataFrame, columns: Sequence[str], label: str) -> None: + for column in columns: + if ( + column not in frame.columns + or frame.get_column(column).null_count() + or bool(frame.get_column(column).any()) + ): + raise M8L2StudyRunVerificationError(f"{label} does not keep {column}=false") + + +def _require_nullable_unit_interval_columns( + frame: pl.DataFrame, columns: Sequence[str], label: str +) -> None: + missing = sorted(set(columns).difference(frame.columns)) + if missing: + raise M8L2StudyRunVerificationError(f"{label} lacks ratio columns: {missing}") + for column in columns: + dtype = frame.schema[column] + if not (dtype.is_float() or dtype.is_integer()): + raise M8L2StudyRunVerificationError(f"{label} {column} is not numeric") + values = frame.get_column(column).drop_nulls().to_list() + if any( + not math.isfinite(float(value)) or not 0.0 <= float(value) <= 1.0 for value in values + ): + raise M8L2StudyRunVerificationError( + f"{label} {column} must be null or finite in [0, 1]" + ) + + +def _verify_complete_semantics( + frames: Mapping[str, pl.DataFrame], + *, + capture: M8L2StudyConfig, + analysis: M8L2AnalysisConfig, + material: _LockMaterial, +) -> None: + expected_noncausal = ( + set(_EVALUATION_PATHS) + | set(_DESCRIPTIVE_PATHS) + | { + "execution/metrics.parquet", + "execution/assumptions.parquet", + } + ) + if not expected_noncausal.issubset(frames): + raise M8L2StudyRunVerificationError("complete run lacks declared result tables") + predictions = frames[_EVALUATION_PATHS[0]] + required_prediction_columns = { + "sample_id", + "symbol", + "study_date", + "study_role", + "endpoint_name", + "is_oos", + "split", + "child_lock_sha256", + "aggregate_lock_sha256", + "test_used_for_selection", + "model_updated_between_test_dates", + "p_value_computed", + "significance_claim_authorized", + } + if not required_prediction_columns.issubset(predictions.columns): + raise M8L2StudyRunVerificationError("prediction artifact lacks lock/OOS boundaries") + if ( + predictions.is_empty() + or predictions.get_column("sample_id").n_unique() != predictions.height + or set(predictions.get_column("study_role").unique()) + != {"primary_test", "replication_test"} + or set(predictions.get_column("split").unique()) != {"final_test"} + or not bool(predictions.get_column("is_oos").all()) + or set(predictions.get_column("aggregate_lock_sha256").unique()) + != {material.result.aggregate_sha256} + ): + raise M8L2StudyRunVerificationError("prediction artifact is not exact held-out OOS data") + _all_false( + predictions, + ( + "test_used_for_selection", + "model_updated_between_test_dates", + "p_value_computed", + "significance_claim_authorized", + ), + "prediction artifact", + ) + for relative in (_EVALUATION_PATHS[1], _EVALUATION_PATHS[2], _EVALUATION_PATHS[3]): + frame = frames[relative] + _all_false( + frame, + ("p_value_computed", "significance_claim_authorized"), + relative, + ) + if "cross_symbol_pooling" in frame.columns: + _all_false(frame, ("cross_symbol_pooling",), relative) + metrics = frames["execution/metrics.parquet"] + assumptions = frames["execution/assumptions.parquet"] + expected_scenarios = 2 * len(capture.study.symbols) * len(analysis.endpoints) * 3 * 3 + if metrics.height != expected_scenarios or assumptions.height != expected_scenarios: + raise M8L2StudyRunVerificationError("execution scenario grid is incomplete") + if metrics.get_column("scenario_id").n_unique() != expected_scenarios: + raise M8L2StudyRunVerificationError("execution scenario identities collide") + _require_nullable_unit_interval_columns( + metrics, + ("fill_ratio", "fill_ratio_requested", "partial_fill_order_ratio"), + "execution metrics", + ) + _all_false( + metrics, + ( + "capacity_claim_authorized", + "realized_execution_claim_authorized", + "profitability_claim_authorized", + ), + "execution metrics", + ) + _all_false( + assumptions, + ( + "live_trading", + "capacity_claim_authorized", + "realized_execution_claim_authorized", + "profitability_claim_authorized", + ), + "execution assumptions", + ) + if set(metrics.get_column("order_type").unique()) != {"market"} or not bool( + assumptions.get_column("market_orders_only").all() + ): + raise M8L2StudyRunVerificationError("execution output is not market-only") + + +def _artifact_paths_from_manifest(manifest: Mapping[str, Any]) -> tuple[str, ...]: + raw = manifest.get("artifacts") + if not isinstance(raw, list): + raise M8L2StudyRunVerificationError("run manifest artifacts must be an array") + result: list[str] = [] + for item in raw: + claim = _mapping(item, "run artifact claim") + if set(claim) != {"path", "kind"}: + raise M8L2StudyRunVerificationError("run artifact claim keys differ") + relative = _safe_relative(_string(claim.get("path"), "run artifact path")) + if claim.get("kind") != _artifact_kind(relative): + raise M8L2StudyRunVerificationError("run artifact kind differs from its path") + result.append(relative) + if result != sorted(set(result)): + raise M8L2StudyRunVerificationError("run artifact paths are duplicate or unordered") + return tuple(result) + + +def _reverify_internal_terminal_snapshot( + root: Path, + *, + root_identity: _ParentIdentity, + initial_files: Mapping[str, Path], + terminal_name: str, + terminal_bytes: bytes, + checksums_raw: bytes, + checksums: Mapping[str, str], +) -> None: + """Rebind every internal byte after semantic and external verification. + + The first pass supports semantic parsing. This second stable-descriptor pass + occurs at the return boundary so an artifact changed after its semantic read + cannot inherit the earlier verification result. + """ + + try: + _reject_symlink_components(root) + before = root.lstat() + except (M8L2StudyPipelineError, OSError) as error: + raise M8L2StudyRunVerificationError( + "final M8 L2 run path changed before return-boundary verification" + ) from error + if ( + not stat.S_ISDIR(before.st_mode) + or _ParentIdentity(before.st_dev, before.st_ino) != root_identity + ): + raise M8L2StudyRunVerificationError( + "final M8 L2 run directory identity changed before return" + ) + observed_files = _walk_regular(root) + if set(observed_files) != set(initial_files): + raise M8L2StudyRunVerificationError( + "final-run inventory changed after semantic verification" + ) + if ( + _read_regular( + root / terminal_name, + label="return-boundary terminal marker", + maximum_bytes=32, + ) + != terminal_bytes + ): + raise M8L2StudyRunVerificationError( + "final-run terminal marker changed after semantic verification" + ) + if ( + _read_regular( + root / _CHECKSUMS_NAME, + label="return-boundary checksums", + maximum_bytes=16 << 20, + ) + != checksums_raw + ): + raise M8L2StudyRunVerificationError( + "final-run checksums changed after semantic verification" + ) + for relative, expected_digest in checksums.items(): + if _stable_file_sha256(_join(root, relative), f"return-boundary {relative}") != ( + expected_digest + ): + raise M8L2StudyRunVerificationError( + f"final-run artifact changed after semantic verification: {relative}" + ) + try: + after = root.lstat() + except OSError as error: + raise M8L2StudyRunVerificationError( + "final M8 L2 run path disappeared before verification returned" + ) from error + if ( + not stat.S_ISDIR(after.st_mode) + or _ParentIdentity(after.st_dev, after.st_ino) != root_identity + ): + raise M8L2StudyRunVerificationError( + "final M8 L2 run directory identity changed at verification return" + ) + + +def _verify_m8_l2_study_run( + capture_config: M8L2StudyConfig, + analysis_config: M8L2AnalysisConfig, + train_session: L2StudySessionAuthority, + validation_session: L2StudySessionAuthority, + development_lock_dir: str | Path, + expected_development_lock_sha256: str, + primary_session: L2StudySessionAuthority, + replication_session: L2StudySessionAuthority, + run_dir: str | Path, + *, + expected_manifest_sha256: str | None = None, + expected_checksums_sha256: str | None = None, +) -> M8L2StudyRunResult: + capture, analysis = _revalidate_configs(capture_config, analysis_config) + if expected_manifest_sha256 is not None: + _require_sha256(expected_manifest_sha256, "expected final-run manifest") + if expected_checksums_sha256 is not None: + _require_sha256(expected_checksums_sha256, "expected final-run checksums") + lock_result, aggregate, campaign, source = _verify_lock_context( + capture, + analysis, + train_session, + validation_session, + development_lock_dir, + expected_development_lock_sha256, + ) + material = _load_lock_material(capture, analysis, lock_result, aggregate, campaign, source) + snapshots = _verify_all_sessions( + capture, + material, + (train_session, validation_session, primary_session, replication_session), + ) + for snapshot in snapshots[2:]: + if material.result.status == "LOCKED" and snapshot.bundle.status == "COMPLETE": + _reverify_material( + capture, + analysis, + train_session, + validation_session, + development_lock_dir, + expected_development_lock_sha256, + material, + ) + _heldout_input( + snapshot, + capture=capture, + campaign=material.campaign, + lock_sha256=expected_development_lock_sha256, + ) + + root = Path(run_dir).absolute() + try: + _reject_symlink_components(root) + except M8L2StudyPipelineError as error: + raise M8L2StudyRunVerificationError( + "final M8 L2 run path contains an unsafe component" + ) from error + try: + metadata = root.lstat() + except OSError as error: + raise M8L2StudyRunVerificationError("final M8 L2 run directory is unavailable") from error + if not stat.S_ISDIR(metadata.st_mode): + raise M8L2StudyRunVerificationError("final M8 L2 run must be a regular directory") + root_identity = _ParentIdentity(metadata.st_dev, metadata.st_ino) + files = _walk_regular(root) + terminal_names = [name for name in (_SUCCESS_NAME, _INSUFFICIENT_NAME) if name in files] + if len(terminal_names) != 1: + raise M8L2StudyRunVerificationError("final M8 L2 run requires exactly one terminal marker") + terminal_name = terminal_names[0] + marker_path = root / terminal_name + expected_marker_bytes = ( + _SUCCESS_BYTES if terminal_name == _SUCCESS_NAME else _INSUFFICIENT_BYTES + ) + if ( + _read_regular(marker_path, label="final M8 L2 terminal marker", maximum_bytes=32) + != expected_marker_bytes + ): + raise M8L2StudyRunVerificationError("final M8 L2 terminal marker bytes differ") + if _CHECKSUMS_NAME not in files or "run_manifest.json" not in files: + raise M8L2StudyRunVerificationError("final M8 L2 run lacks control authorities") + checksums_raw = _read_regular( + root / _CHECKSUMS_NAME, + label="final M8 L2 checksums", + maximum_bytes=16 << 20, + ) + checksums_sha = hashlib.sha256(checksums_raw).hexdigest() + if expected_checksums_sha256 is not None and checksums_sha != expected_checksums_sha256: + raise M8L2StudyRunVerificationError("final-run checksums differ from caller authority") + checksums = _parse_checksums(checksums_raw, "final M8 L2 checksums") + expected_inventory = set(checksums) | {_CHECKSUMS_NAME, terminal_name} + if set(files) != expected_inventory: + raise M8L2StudyRunVerificationError( + "final-run physical inventory differs from checksums " + f"(missing={sorted(expected_inventory - set(files))}, " + f"extra={sorted(set(files) - expected_inventory)})" + ) + for relative, expected_digest in checksums.items(): + if _stable_file_sha256(_join(root, relative), relative) != expected_digest: + raise M8L2StudyRunVerificationError(f"final-run checksum mismatch for {relative}") + + manifest, manifest_raw = _read_json(root / "run_manifest.json", "final-run manifest") + manifest_sha = hashlib.sha256(manifest_raw).hexdigest() + if expected_manifest_sha256 is not None and manifest_sha != expected_manifest_sha256: + raise M8L2StudyRunVerificationError("final-run manifest differs from caller authority") + if checksums.get("run_manifest.json") != manifest_sha: + raise M8L2StudyRunVerificationError("final-run checksums do not bind the manifest") + expected_manifest_keys = { + "schema_version", + "artifact_kind", + "status", + "reason_codes", + "generated_at_utc", + "run_id", + "evidence_tier", + "effective_evidence_tier", + "live_trading", + "research", + "authority", + "sessions", + "artifacts", + "tabular_outputs", + "evaluation", + "execution", + "claims", + "terminal_marker", + } + if set(manifest) != expected_manifest_keys: + raise M8L2StudyRunVerificationError("final-run manifest keys differ") + status_raw = manifest.get("status") + if status_raw not in {"COMPLETE", "INSUFFICIENT_DATA"}: + raise M8L2StudyRunVerificationError("final-run status is unsupported") + status = cast(M8L2StudyRunStatus, status_raw) + expected_terminal = _SUCCESS_NAME if status == "COMPLETE" else _INSUFFICIENT_NAME + expected_terminal_claim = { + "path": expected_terminal, + "bytes": "complete\\n" if status == "COMPLETE" else "terminal\\n", + } + if ( + terminal_name != expected_terminal + or manifest.get("terminal_marker") != expected_terminal_claim + ): + raise M8L2StudyRunVerificationError("final-run status and terminal marker disagree") + raw_reasons = manifest.get("reason_codes") + if not isinstance(raw_reasons, list) or not all(type(item) is str for item in raw_reasons): + raise M8L2StudyRunVerificationError("final-run reason codes must be strings") + reasons = tuple(cast(list[str], raw_reasons)) + if list(reasons) != sorted(set(reasons)) or (status == "COMPLETE") == bool(reasons): + raise M8L2StudyRunVerificationError("final-run reason/status boundary is inconsistent") + if ( + manifest.get("schema_version") != _SCHEMA_VERSION + or manifest.get("artifact_kind") != "m8_prospective_live_l2_final_study" + or manifest.get("evidence_tier") != "FULL_DATA" + or manifest.get("effective_evidence_tier") + != ("FULL_DATA" if status == "COMPLETE" else "INSUFFICIENT_DATA") + or manifest.get("live_trading") is not False + ): + raise M8L2StudyRunVerificationError("final-run evidence boundary differs") + + run_id = _run_identity(capture, analysis, material, snapshots) + if manifest.get("run_id") != run_id: + raise M8L2StudyRunVerificationError("final-run deterministic identity differs") + authority = _mapping(manifest.get("authority"), "final-run authority") + expected_authority = { + "capture_config_sha256": capture.hash, + "capture_config_source_sha256": capture.source_sha256, + "capture_protocol_sha256": M8_L2_PROTOCOL_SHA256, + "analysis_config_sha256": analysis.hash, + "analysis_config_source_sha256": analysis.source_sha256, + "development_lock_sha256": material.result.aggregate_sha256, + "development_authority": _development_authority_claim(material), + "campaign_identity": material.campaign.to_dict(), + "producer_source_identity": material.source.to_dict(), + } + if dict(authority) != expected_authority: + raise M8L2StudyRunVerificationError("final-run authority differs from external evidence") + if manifest.get("sessions") != [dict(row) for row in _session_gate_rows(snapshots)]: + raise M8L2StudyRunVerificationError("final-run session claims differ from external bundles") + if status == "COMPLETE" and any(item.bundle.status != "COMPLETE" for item in snapshots): + raise M8L2StudyRunVerificationError("complete run contains an insufficient session") + if status == "INSUFFICIENT_DATA": + if material.result.status == "NOT_CREATED": + if reasons != _not_created_final_reasons(snapshots): + raise M8L2StudyRunVerificationError( + "NOT_CREATED final reasons differ from all session authorities" + ) + else: + session_reasons = { + f"{item.bundle.role}::{reason}" + for item in snapshots[2:] + if item.bundle.status != "COMPLETE" + for reason in (item.bundle.reason_codes or ("SESSION_INSUFFICIENT_DATA",)) + } + if session_reasons: + if set(reasons) != session_reasons: + raise M8L2StudyRunVerificationError( + "insufficient reasons differ from held-out capture gates" + ) + elif not all(reason.startswith("NO_ELIGIBLE_LABELS::") for reason in reasons): + raise M8L2StudyRunVerificationError( + "insufficient final run lacks a typed data-availability boundary" + ) + + provenance, provenance_raw = _read_json(root / "provenance.json", "final-run provenance") + if _canonical_json_bytes(cast(Mapping[str, object], provenance)) != provenance_raw: + raise M8L2StudyRunVerificationError("final-run provenance is not canonical JSON") + generated_at = _string(manifest.get("generated_at_utc"), "manifest generation time") + expected_provenance = _provenance_payload( + status=status, + capture=capture, + analysis=analysis, + material=material, + snapshots=snapshots, + generated_at_utc=generated_at, + run_id=run_id, + ) + if provenance != expected_provenance: + raise M8L2StudyRunVerificationError("final-run provenance differs from exact authorities") + + artifact_paths = _artifact_paths_from_manifest(manifest) + if set(artifact_paths) != set(checksums) - {"run_manifest.json"}: + raise M8L2StudyRunVerificationError( + "manifest-declared artifacts differ from checksum inventory" + ) + authority_sources = _authority_sources(capture, analysis, snapshots, material) + if set(authority_sources) != {path for path in artifact_paths if path.startswith("authority/")}: + raise M8L2StudyRunVerificationError("self-contained authority snapshot set differs") + for relative, (external, expected_digest) in authority_sources.items(): + if ( + _stable_file_sha256(external, f"external {relative}") != expected_digest + or _stable_file_sha256(_join(root, relative), relative) != expected_digest + ): + raise M8L2StudyRunVerificationError( + f"self-contained authority snapshot changed for {relative}" + ) + + tabular_claims = _tabular_claims_from_manifest(manifest) + expected_parquets = { + path + for path in artifact_paths + if path.endswith(".parquet") and not path.startswith("authority/") + } + if set(tabular_claims) != expected_parquets: + raise M8L2StudyRunVerificationError( + "tabular semantic claims differ from declared Parquet artifacts" + ) + frames = _verify_tabular_outputs_streaming( + root, + tabular_claims, + capture=capture, + analysis=analysis, + material=material, + status=status, + reasons=reasons, + ) + if status == "COMPLETE": + _verify_complete_semantics( + frames, + capture=capture, + analysis=analysis, + material=material, + ) + elif any( + path.startswith(("evaluation/", "execution/", "descriptive/")) for path in tabular_claims + ): + raise M8L2StudyRunVerificationError( + "insufficient final run improperly contains promoted economic results" + ) + _verify_report_artifacts(root, manifest, provenance) + report_data = _load_report_data_snapshot(root) + if tuple(dict(row) for row in report_data.session_gates) != tuple( + dict(row) for row in _session_gate_rows(snapshots) + ): + raise M8L2StudyRunVerificationError("report session gates differ from external evidence") + _terminal_revalidation( + capture=capture, + analysis=analysis, + train=train_session, + validation=validation_session, + primary=primary_session, + replication=replication_session, + lock_dir=development_lock_dir, + lock_sha256=expected_development_lock_sha256, + material=material, + snapshots=snapshots, + ) + _reverify_internal_terminal_snapshot( + root, + root_identity=root_identity, + initial_files=files, + terminal_name=terminal_name, + terminal_bytes=expected_marker_bytes, + checksums_raw=checksums_raw, + checksums=checksums, + ) + return M8L2StudyRunResult( + root=root, + status=status, + manifest_path=root / "run_manifest.json", + manifest_sha256=manifest_sha, + checksum_path=root / _CHECKSUMS_NAME, + checksum_sha256=checksums_sha, + marker_path=marker_path, + reason_codes=reasons, + ) + + +__all__ = [ + "L2StudySessionAuthority", + "M8L2StudyPipelineError", + "M8L2StudyRunResult", + "M8L2StudyRunStatus", + "M8L2StudyRunVerificationError", + "load_m8_l2_report_data", + "reproduce_m8_l2_study", + "verify_m8_l2_study_run", +] diff --git a/Microstructure/src/microstructure/m8_manifest.py b/Microstructure/src/microstructure/m8_manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..6205fc6ffb757d7859c0b4f4418bfa9091e8edaf --- /dev/null +++ b/Microstructure/src/microstructure/m8_manifest.py @@ -0,0 +1,2045 @@ +"""Immutable input-manifest contract for the frozen M8 trade study. + +The verifier intentionally inspects only JSON metadata, exact file hashes, and +Parquet footers/schemas. It never materializes normalized trade rows. Economic +row-level validation belongs to the acquisition/quality stage whose immutable +reports and findings are bound here. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import re +import struct +import tempfile +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from datetime import UTC, datetime +from datetime import date as Date +from decimal import Decimal, InvalidOperation +from pathlib import Path +from types import MappingProxyType +from typing import Any, cast +from urllib.parse import parse_qsl, urlparse +from zipfile import BadZipFile, ZipFile + +import pyarrow as pa # type: ignore[import-untyped] +import pyarrow.parquet as pq # type: ignore[import-untyped] + +from microstructure.data.schemas import SCHEMA_VERSION, get_schema +from microstructure.m8_config import M8PeriodRole, M8StudyConfig +from microstructure.provenance import sha256_file + +M8_INPUT_MANIFEST_VERSION = "1.2.0" +_STORAGE_MANIFEST_VERSION = "1.0.0" +_DIGEST = re.compile(r"[0-9a-f]{64}") +_UTC_TIMESTAMP = re.compile( + r"(?P\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})" + r"(?:\.(?P\d{1,9}))?(?:Z|\+00:00)" +) +_MAX_JSON_BYTES = 8 * 1024 * 1024 +_MAX_SYMBOL_METADATA_BYTES = 1 * 1024 * 1024 +_MAX_ARCHIVE_CHECKSUM_BYTES = 4_096 +_MAX_ZIP_DIRECTORY_BYTES = 256 * 1_024 +_MAX_ZIP_TAIL_BYTES = 22 + 65_535 +_NS_PER_DAY = 86_400 * 1_000_000_000 +_EPOCH = datetime(1970, 1, 1, tzinfo=UTC) +_ZIP_CENTRAL_SIGNATURE = b"PK\x01\x02" +_ZIP_CENTRAL_STRUCT = struct.Struct("<4s6H3L5H2L") +_ZIP_EOCD_SIGNATURE = b"PK\x05\x06" +_ZIP_EOCD_STRUCT = struct.Struct("<4s4H2LH") +_ZIP64_EXTRA_FIELD_ID = 0x0001 +_ZIP16_SENTINEL = 0xFFFF +_ZIP32_SENTINEL = 0xFFFFFFFF + +_TOP_KEYS = frozenset( + { + "manifest_version", + "artifact_kind", + "config", + "study", + "symbol_metadata", + "total_symbol_metadata_bytes", + "total_raw_zip_bytes", + "entries", + } +) +_CONFIG_KEYS = frozenset({"semantic_sha256", "source_sha256", "protocol_version"}) +_STUDY_KEYS = frozenset({"name", "evidence_tier", "source", "symbols", "periods"}) +_STUDY_PERIOD_KEYS = frozenset({"date", "role"}) +_SYMBOL_METADATA_KEYS = frozenset( + { + "symbol", + "status", + "tick_size", + "lot_size", + "observed_ts_ns", + "raw_path", + "raw_sha256", + "raw_bytes", + "source_uri", + "source_manifest_path", + "source_manifest_sha256", + "source_manifest_bytes", + } +) +_ARCHIVE_CHECKSUM_KEYS = frozenset( + { + "path", + "sha256", + "bytes", + "source_uri", + "source_manifest_path", + "source_manifest_sha256", + "source_manifest_bytes", + } +) +_ENTRY_KEYS = frozenset( + { + "symbol", + "date", + "role", + "complete", + "requested_range_ns", + "rows", + "trade_id_range", + "observed_range_ns", + "scales", + "raw", + "normalized", + "quality", + } +) +_RANGE_KEYS = frozenset({"start", "end_exclusive"}) +_OBSERVED_KEYS = frozenset({"start", "end_inclusive"}) +_TRADE_ID_KEYS = frozenset({"first", "last", "contiguous_count"}) +_SCALE_KEYS = frozenset({"tick_size", "lot_size"}) +_CHECKSUM_KEYS = frozenset({"algorithm", "value"}) +_RAW_KEYS = frozenset( + { + "zip_path", + "zip_sha256", + "zip_bytes", + "uncompressed_bytes", + "source_uri", + "source_manifest_path", + "source_manifest_sha256", + "source_manifest_bytes", + "checksum", + } +) +_NORMALIZED_KEYS = frozenset( + { + "dataset_manifest_path", + "dataset_manifest_sha256", + "dataset_manifest_bytes", + "rows", + "parts", + } +) +_PART_KEYS = frozenset( + { + "data_path", + "data_sha256", + "data_bytes", + "sidecar_path", + "sidecar_sha256", + "sidecar_bytes", + "rows", + "write_ordinal", + "observed_range_ns", + } +) +_QUALITY_KEYS = frozenset( + { + "report_path", + "report_sha256", + "report_bytes", + "findings_path", + "findings_sha256", + "findings_bytes", + "errors", + "warnings", + } +) +_RAW_SIDECAR_KEYS = frozenset( + { + "manifest_version", + "artifact_kind", + "source", + "source_uri", + "downloaded_at_utc", + "requested_range_ns", + "checksum", + "upstream_checksum_sha256", + "bytes", + "path", + "response_headers", + } +) +_DATASET_KEYS = frozenset( + { + "manifest_version", + "dataset", + "schema_version", + "source", + "source_uri", + "downloaded_at_utc", + "requested_range_ns", + "artifacts", + "rows", + } +) +_DATASET_PART_KEYS = frozenset( + { + "data_path", + "manifest_path", + "data_sha256", + "manifest_sha256", + "rows", + "write_ordinal", + "observed_range_ns", + } +) +_PART_SIDECAR_KEYS = frozenset( + { + "manifest_version", + "artifact_kind", + "dataset", + "schema_name", + "schema_version", + "venue", + "symbol", + "partition_date", + "write_ordinal", + "source", + "source_uri", + "downloaded_at_utc", + "requested_range_ns", + "observed_range_ns", + "source_checksum_sha256", + "checksum", + "rows", + "bytes", + "path", + "transformations", + } +) + + +class M8ManifestError(RuntimeError): + """Raised when M8 input evidence is missing, unsafe, or inconsistent.""" + + +@dataclass(frozen=True, slots=True) +class M8NormalizedPart: + data_path: Path + data_sha256: str + data_bytes: int + sidecar_path: Path + sidecar_sha256: str + sidecar_bytes: int + rows: int + write_ordinal: int + observed_start_ns: int + observed_end_inclusive_ns: int + + +@dataclass(frozen=True, slots=True) +class M8SymbolMetadata: + symbol: str + status: str + tick_size: Decimal + lot_size: Decimal + observed_ts_ns: int + raw_path: Path + raw_sha256: str + raw_bytes: int + source_uri: str + source_manifest_path: Path + source_manifest_sha256: str + source_manifest_bytes: int + + +@dataclass(frozen=True, slots=True) +class M8ArchiveEntry: + symbol: str + date: Date + role: M8PeriodRole + complete: bool + rows: int + first_trade_id: int + last_trade_id: int + observed_start_ns: int + observed_end_inclusive_ns: int + tick_size: Decimal + lot_size: Decimal + raw_zip_path: Path + raw_zip_sha256: str + raw_zip_bytes: int + raw_uncompressed_bytes: int + raw_source_uri: str + raw_source_manifest_path: Path + raw_source_manifest_sha256: str + raw_source_manifest_bytes: int + raw_checksum_path: Path + raw_checksum_sha256: str + raw_checksum_bytes: int + raw_checksum_source_uri: str + raw_checksum_source_manifest_path: Path + raw_checksum_source_manifest_sha256: str + raw_checksum_source_manifest_bytes: int + normalized_dataset_manifest_path: Path + normalized_dataset_manifest_sha256: str + normalized_dataset_manifest_bytes: int + normalized_parts: tuple[M8NormalizedPart, ...] + quality_report_path: Path + quality_report_sha256: str + quality_report_bytes: int + quality_findings_path: Path + quality_findings_sha256: str + quality_findings_bytes: int + quality_errors: int + quality_warnings: int + + +@dataclass(frozen=True, slots=True) +class M8InputManifest: + root: Path + path: Path + sha256: str + config_sha256: str + config_source_sha256: str + protocol_version: str + symbol_metadata: tuple[M8SymbolMetadata, ...] + entries: tuple[M8ArchiveEntry, ...] + + def metadata_for(self, symbol: str) -> M8SymbolMetadata: + for metadata in self.symbol_metadata: + if metadata.symbol == symbol: + return metadata + raise KeyError(f"no verified M8 symbol metadata for {symbol}") + + @property + def ordered_part_paths(self) -> Mapping[tuple[str, str], tuple[Path, ...]]: + """Return verified Parquet paths keyed in frozen period/symbol order.""" + + paths = { + (entry.symbol, entry.date.isoformat()): tuple( + part.data_path for part in entry.normalized_parts + ) + for entry in self.entries + } + return MappingProxyType(paths) + + def part_paths_for(self, symbol: str, date: Date | str) -> tuple[Path, ...]: + date_text = date.isoformat() if isinstance(date, Date) else date + try: + return self.ordered_part_paths[(symbol, date_text)] + except KeyError as exc: + raise KeyError(f"no verified M8 parts for {symbol}/{date_text}") from exc + + +def _day_bounds_ns(day: Date) -> tuple[int, int]: + start = datetime(day.year, day.month, day.day, tzinfo=UTC) + delta = start - _EPOCH + start_ns = (delta.days * 86_400 + delta.seconds) * 1_000_000_000 + return start_ns, start_ns + _NS_PER_DAY + + +def _object(value: object, label: str) -> Mapping[str, Any]: + if not isinstance(value, Mapping): + raise M8ManifestError(f"{label} must be a JSON object") + if not all(isinstance(key, str) for key in value): + raise M8ManifestError(f"{label} contains a non-string key") + return cast(Mapping[str, Any], value) + + +def _array(value: object, label: str) -> list[Any]: + if not isinstance(value, list): + raise M8ManifestError(f"{label} must be a JSON array") + return value + + +def _text(value: object, label: str) -> str: + if type(value) is not str: + raise M8ManifestError(f"{label} must be a string") + return value + + +def _integer(value: object, label: str, *, minimum: int | None = None) -> int: + if type(value) is not int: + raise M8ManifestError(f"{label} must be an integer") + result = value + if minimum is not None and result < minimum: + raise M8ManifestError(f"{label} must be at least {minimum}") + return result + + +def _boolean(value: object, label: str) -> bool: + if type(value) is not bool: + raise M8ManifestError(f"{label} must be a boolean") + return value + + +def _digest(value: object, label: str) -> str: + digest = _text(value, label) + if _DIGEST.fullmatch(digest) is None: + raise M8ManifestError(f"{label} must be a lowercase SHA-256 digest") + return digest + + +def _decimal(value: object, label: str) -> Decimal: + raw = _text(value, label) + try: + result = Decimal(raw) + except InvalidOperation as exc: + raise M8ManifestError(f"{label} must be a decimal string") from exc + if not result.is_finite() or result <= 0: + raise M8ManifestError(f"{label} must be finite and positive") + return result + + +def _exact_keys(value: Mapping[str, Any], expected: frozenset[str], label: str) -> None: + observed = frozenset(value) + missing = sorted(expected - observed) + extra = sorted(observed - expected) + if missing or extra: + details: list[str] = [] + if missing: + details.append("missing=" + ",".join(missing)) + if extra: + details.append("extra=" + ",".join(extra)) + raise M8ManifestError(f"{label} keys are invalid ({'; '.join(details)})") + + +def _parse_date(value: object, label: str) -> Date: + raw = _text(value, label) + try: + parsed = Date.fromisoformat(raw) + except ValueError as exc: + raise M8ManifestError(f"{label} must be an ISO UTC date") from exc + if parsed.isoformat() != raw: + raise M8ManifestError(f"{label} must use canonical YYYY-MM-DD form") + return parsed + + +def _parse_role(value: object, label: str) -> M8PeriodRole: + raw = _text(value, label) + allowed = {"train", "validation", "primary_test", "replication_test"} + if raw not in allowed: + raise M8ManifestError(f"{label} has an unsupported role: {raw!r}") + return cast(M8PeriodRole, raw) + + +def _utc_ns_from_iso(value: object, label: str) -> int: + raw = _text(value, label) + matched = _UTC_TIMESTAMP.fullmatch(raw) + if matched is None: + raise M8ManifestError( + f"{label} must be an ISO-8601 UTC timestamp with at most nanosecond precision" + ) + try: + second = datetime.strptime(matched.group("second"), "%Y-%m-%dT%H:%M:%S").replace(tzinfo=UTC) + except ValueError as exc: + raise M8ManifestError(f"{label} is not a valid UTC timestamp") from exc + fraction = (matched.group("fraction") or "").ljust(9, "0") + delta = second - _EPOCH + return (delta.days * 86_400 + delta.seconds) * 1_000_000_000 + int(fraction or "0") + + +def _read_json_object(path: Path, label: str) -> Mapping[str, Any]: + try: + size = path.stat().st_size + except OSError as exc: + raise M8ManifestError(f"cannot stat {label} at {path}: {exc}") from exc + if size > _MAX_JSON_BYTES: + raise M8ManifestError(f"{label} exceeds the {_MAX_JSON_BYTES}-byte JSON limit") + + def reject_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + raise M8ManifestError(f"{label} contains duplicate JSON key {key!r}") + result[key] = value + return result + + try: + with path.open(encoding="utf-8") as handle: + parsed = json.load(handle, object_pairs_hook=reject_duplicates) + except M8ManifestError: + raise + except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc: + raise M8ManifestError(f"cannot parse {label} at {path}: {exc}") from exc + return _object(parsed, label) + + +def _resolve_contained_file(root: Path, value: str | Path, label: str) -> Path: + declared = Path(value) + candidate = declared if declared.is_absolute() else root / declared + resolved_root = root.resolve() + resolved = candidate.resolve() + if not resolved.is_relative_to(resolved_root): + raise M8ManifestError(f"{label} escapes the M8 input root: {declared}") + if not resolved.is_file(): + raise M8ManifestError(f"missing {label}: {resolved}") + return resolved + + +def _declared_file(root: Path, value: object, label: str) -> Path: + raw = _text(value, label) + if Path(raw).is_absolute(): + raise M8ManifestError(f"{label} must be relative to the M8 input root") + return _resolve_contained_file(root, raw, label) + + +def _relative_file(root: Path, value: Path, label: str) -> str: + resolved = _resolve_contained_file(root, value, label) + return resolved.relative_to(root.resolve()).as_posix() + + +def _verify_file(path: Path, sha256: str, byte_count: int, label: str) -> None: + if path.stat().st_size != byte_count: + raise M8ManifestError(f"{label} byte count does not match") + observed = sha256_file(path) + if observed != sha256: + raise M8ManifestError(f"{label} SHA-256 mismatch: expected {sha256}, observed {observed}") + + +def _range(value: object, label: str) -> tuple[int, int]: + raw = _object(value, label) + _exact_keys(raw, _RANGE_KEYS, label) + start = _integer(raw["start"], f"{label}.start") + end = _integer(raw["end_exclusive"], f"{label}.end_exclusive") + if end <= start: + raise M8ManifestError(f"{label} must be non-empty") + return start, end + + +def _observed_range(value: object, label: str) -> tuple[int, int]: + raw = _object(value, label) + _exact_keys(raw, _OBSERVED_KEYS, label) + start = _integer(raw["start"], f"{label}.start") + end = _integer(raw["end_inclusive"], f"{label}.end_inclusive") + if end < start: + raise M8ManifestError(f"{label} ends before it starts") + return start, end + + +def _verify_day_range(observed: tuple[int, int], day_range: tuple[int, int], label: str) -> None: + if observed[0] < day_range[0] or observed[1] >= day_range[1]: + raise M8ManifestError(f"{label} falls outside its declared UTC day") + + +def _expected_entry_order(config: M8StudyConfig) -> tuple[tuple[str, Date, M8PeriodRole], ...]: + return tuple( + (symbol, period.date, period.role) + for period in config.periods + for symbol in config.study.symbols + ) + + +def _ordered_symbol_metadata( + config: M8StudyConfig, values: Sequence[M8SymbolMetadata] +) -> tuple[M8SymbolMetadata, ...]: + expected_symbols = config.study.symbols + observed: dict[str, M8SymbolMetadata] = {} + for metadata in values: + if metadata.symbol in observed: + raise M8ManifestError(f"duplicate M8 symbol metadata for {metadata.symbol}") + if metadata.symbol not in expected_symbols: + raise M8ManifestError(f"extra M8 symbol metadata for {metadata.symbol}") + observed[metadata.symbol] = metadata + missing = [symbol for symbol in expected_symbols if symbol not in observed] + if missing: + raise M8ManifestError("missing M8 symbol metadata: " + ", ".join(missing)) + if len(observed) != 2: + raise M8ManifestError("the frozen M8 study requires exactly two symbol metadata entries") + return tuple(observed[symbol] for symbol in expected_symbols) + + +def _ordered_entries( + config: M8StudyConfig, entries: Sequence[M8ArchiveEntry] +) -> tuple[M8ArchiveEntry, ...]: + expected = _expected_entry_order(config) + expected_keys = {(symbol, day): role for symbol, day, role in expected} + observed: dict[tuple[str, Date], M8ArchiveEntry] = {} + for entry in entries: + key = (entry.symbol, entry.date) + if key in observed: + raise M8ManifestError( + f"duplicate M8 archive entry for {entry.symbol}/{entry.date.isoformat()}" + ) + expected_role = expected_keys.get(key) + if expected_role is None: + raise M8ManifestError( + f"extra M8 archive entry for {entry.symbol}/{entry.date.isoformat()}" + ) + if entry.role != expected_role: + raise M8ManifestError( + f"role mismatch for {entry.symbol}/{entry.date.isoformat()}: " + f"expected {expected_role}, observed {entry.role}" + ) + observed[key] = entry + missing = [ + f"{symbol}/{day.isoformat()}" + for symbol, day, _role in expected + if (symbol, day) not in observed + ] + if missing: + raise M8ManifestError("missing M8 archive entries: " + ", ".join(missing)) + if len(observed) != 8: + raise M8ManifestError("the frozen M8 study requires exactly eight symbol/date entries") + return tuple(observed[(symbol, day)] for symbol, day, _role in expected) + + +def _symbol_metadata_payload(root: Path, metadata: M8SymbolMetadata) -> dict[str, object]: + return { + "symbol": metadata.symbol, + "status": metadata.status, + "tick_size": format(metadata.tick_size, "f"), + "lot_size": format(metadata.lot_size, "f"), + "observed_ts_ns": metadata.observed_ts_ns, + "raw_path": _relative_file(root, metadata.raw_path, "exchangeInfo raw body"), + "raw_sha256": metadata.raw_sha256, + "raw_bytes": metadata.raw_bytes, + "source_uri": metadata.source_uri, + "source_manifest_path": _relative_file( + root, + metadata.source_manifest_path, + "exchangeInfo source sidecar", + ), + "source_manifest_sha256": metadata.source_manifest_sha256, + "source_manifest_bytes": metadata.source_manifest_bytes, + } + + +def _part_payload(root: Path, part: M8NormalizedPart) -> dict[str, object]: + return { + "data_path": _relative_file(root, part.data_path, "normalized Parquet part"), + "data_sha256": part.data_sha256, + "data_bytes": part.data_bytes, + "sidecar_path": _relative_file(root, part.sidecar_path, "normalized part sidecar"), + "sidecar_sha256": part.sidecar_sha256, + "sidecar_bytes": part.sidecar_bytes, + "rows": part.rows, + "write_ordinal": part.write_ordinal, + "observed_range_ns": { + "start": part.observed_start_ns, + "end_inclusive": part.observed_end_inclusive_ns, + }, + } + + +def _entry_payload(root: Path, entry: M8ArchiveEntry) -> dict[str, object]: + day_start, day_end = _day_bounds_ns(entry.date) + parts = sorted(entry.normalized_parts, key=lambda item: item.write_ordinal) + return { + "symbol": entry.symbol, + "date": entry.date.isoformat(), + "role": entry.role, + "complete": entry.complete, + "requested_range_ns": {"start": day_start, "end_exclusive": day_end}, + "rows": entry.rows, + "trade_id_range": { + "first": entry.first_trade_id, + "last": entry.last_trade_id, + "contiguous_count": entry.rows, + }, + "observed_range_ns": { + "start": entry.observed_start_ns, + "end_inclusive": entry.observed_end_inclusive_ns, + }, + "scales": { + "tick_size": format(entry.tick_size, "f"), + "lot_size": format(entry.lot_size, "f"), + }, + "raw": { + "zip_path": _relative_file(root, entry.raw_zip_path, "raw ZIP"), + "zip_sha256": entry.raw_zip_sha256, + "zip_bytes": entry.raw_zip_bytes, + "uncompressed_bytes": entry.raw_uncompressed_bytes, + "source_uri": entry.raw_source_uri, + "source_manifest_path": _relative_file( + root, entry.raw_source_manifest_path, "raw source sidecar" + ), + "source_manifest_sha256": entry.raw_source_manifest_sha256, + "source_manifest_bytes": entry.raw_source_manifest_bytes, + "checksum": { + "path": _relative_file( + root, + entry.raw_checksum_path, + "official archive CHECKSUM", + ), + "sha256": entry.raw_checksum_sha256, + "bytes": entry.raw_checksum_bytes, + "source_uri": entry.raw_checksum_source_uri, + "source_manifest_path": _relative_file( + root, + entry.raw_checksum_source_manifest_path, + "official archive CHECKSUM source sidecar", + ), + "source_manifest_sha256": entry.raw_checksum_source_manifest_sha256, + "source_manifest_bytes": entry.raw_checksum_source_manifest_bytes, + }, + }, + "normalized": { + "dataset_manifest_path": _relative_file( + root, + entry.normalized_dataset_manifest_path, + "normalized dataset manifest", + ), + "dataset_manifest_sha256": entry.normalized_dataset_manifest_sha256, + "dataset_manifest_bytes": entry.normalized_dataset_manifest_bytes, + "rows": entry.rows, + "parts": [_part_payload(root, part) for part in parts], + }, + "quality": { + "report_path": _relative_file(root, entry.quality_report_path, "quality report"), + "report_sha256": entry.quality_report_sha256, + "report_bytes": entry.quality_report_bytes, + "findings_path": _relative_file(root, entry.quality_findings_path, "quality findings"), + "findings_sha256": entry.quality_findings_sha256, + "findings_bytes": entry.quality_findings_bytes, + "errors": entry.quality_errors, + "warnings": entry.quality_warnings, + }, + } + + +def _manifest_payload( + config: M8StudyConfig, + root: Path, + entries: Sequence[M8ArchiveEntry], + symbol_metadata: Sequence[M8SymbolMetadata], +) -> dict[str, object]: + ordered = _ordered_entries(config, entries) + ordered_metadata = _ordered_symbol_metadata(config, symbol_metadata) + entry_payloads = [_entry_payload(root, entry) for entry in ordered] + return { + "manifest_version": M8_INPUT_MANIFEST_VERSION, + "artifact_kind": "m8_multidate_trade_input", + "config": { + "semantic_sha256": config.hash, + "source_sha256": config.source_sha256, + "protocol_version": config.study.protocol_version, + }, + "study": { + "name": config.study.name, + "evidence_tier": config.study.evidence_tier, + "source": config.study.source, + "symbols": list(config.study.symbols), + "periods": [ + {"date": period.date.isoformat(), "role": period.role} for period in config.periods + ], + }, + "symbol_metadata": [ + _symbol_metadata_payload(root, metadata) for metadata in ordered_metadata + ], + "total_symbol_metadata_bytes": sum(metadata.raw_bytes for metadata in ordered_metadata), + "total_raw_zip_bytes": sum(entry.raw_zip_bytes for entry in ordered), + "entries": entry_payloads, + } + + +def _verify_exchange_info_uri(source_uri: str, symbol: str, label: str) -> None: + try: + parsed = urlparse(source_uri) + port = parsed.port + except ValueError as exc: + raise M8ManifestError(f"{label} has an invalid network location") from exc + try: + query = parse_qsl( + parsed.query, + keep_blank_values=True, + strict_parsing=True, + max_num_fields=2, + ) + except ValueError as exc: + raise M8ManifestError(f"{label} has an invalid query") from exc + if ( + parsed.scheme != "https" + or parsed.netloc != "data-api.binance.vision" + or parsed.hostname != "data-api.binance.vision" + or port is not None + or parsed.username is not None + or parsed.password is not None + or parsed.path != "/api/v3/exchangeInfo" + or parsed.params + or parsed.fragment + or query != [("symbol", symbol)] + or any(ord(character) < 0x20 or ord(character) == 0x7F for character in source_uri) + ): + raise M8ManifestError( + f"{label} is not the exact official exchangeInfo request for {symbol}" + ) + + +def _verify_null_requested_range(value: object, label: str) -> None: + requested = _object(value, label) + _exact_keys(requested, _RANGE_KEYS, label) + if requested["start"] is not None or requested["end_exclusive"] is not None: + raise M8ManifestError(f"{label} must have null API range bounds") + + +def _verify_exchange_info_payload( + raw_path: Path, + *, + symbol: str, + status: str, + tick_size: Decimal, + lot_size: Decimal, + label: str, +) -> None: + payload = _read_json_object(raw_path, f"{label} raw body") + symbols = _array(payload.get("symbols"), f"{label} raw body symbols") + if len(symbols) != 1: + raise M8ManifestError(f"{label} raw body must contain exactly the requested symbol") + item = _object(symbols[0], f"{label} raw body symbol") + if _text(item.get("symbol"), f"{label} raw body symbol name") != symbol: + raise M8ManifestError(f"{label} raw body returned a different symbol") + if _text(item.get("status"), f"{label} raw body status") != status: + raise M8ManifestError(f"{label} raw body status does not match") + + filters: dict[str, Mapping[str, Any]] = {} + for index, raw_filter in enumerate(_array(item.get("filters"), f"{label} raw body filters")): + filter_value = _object(raw_filter, f"{label} raw body filters[{index}]") + filter_type = _text( + filter_value.get("filterType"), + f"{label} raw body filters[{index}].filterType", + ) + if filter_type in filters: + raise M8ManifestError(f"{label} raw body has duplicate {filter_type} filters") + filters[filter_type] = filter_value + try: + price_filter = filters["PRICE_FILTER"] + lot_filter = filters["LOT_SIZE"] + except KeyError as exc: + raise M8ManifestError( + f"{label} raw body lacks PRICE_FILTER or LOT_SIZE provenance" + ) from exc + source_tick = _decimal(price_filter.get("tickSize"), f"{label} raw PRICE_FILTER.tickSize") + source_lot = _decimal(lot_filter.get("stepSize"), f"{label} raw LOT_SIZE.stepSize") + if source_tick != tick_size or source_lot != lot_size: + raise M8ManifestError(f"{label} declared scales do not match its raw exchangeInfo body") + + +def _verify_symbol_metadata( + root: Path, + value: object, + expected_symbol: str, + index: int, +) -> M8SymbolMetadata: + label = f"symbol_metadata[{index}]" + metadata = _object(value, label) + _exact_keys(metadata, _SYMBOL_METADATA_KEYS, label) + symbol = _text(metadata["symbol"], f"{label}.symbol") + if symbol != expected_symbol: + raise M8ManifestError(f"{label} is out of frozen symbol order") + status = _text(metadata["status"], f"{label}.status") + if status != "TRADING": + raise M8ManifestError(f"{label} must prove that {symbol} was TRADING") + tick_size = _decimal(metadata["tick_size"], f"{label}.tick_size") + lot_size = _decimal(metadata["lot_size"], f"{label}.lot_size") + observed_ts_ns = _integer(metadata["observed_ts_ns"], f"{label}.observed_ts_ns", minimum=1) + + raw_path = _declared_file(root, metadata["raw_path"], f"{label} raw body") + raw_sha = _digest(metadata["raw_sha256"], f"{label} raw SHA") + raw_bytes = _integer(metadata["raw_bytes"], f"{label} raw bytes", minimum=1) + if raw_bytes > _MAX_SYMBOL_METADATA_BYTES: + raise M8ManifestError( + f"{label} raw body exceeds the {_MAX_SYMBOL_METADATA_BYTES}-byte metadata limit" + ) + _verify_file(raw_path, raw_sha, raw_bytes, f"{label} raw body") + + source_uri = _text(metadata["source_uri"], f"{label}.source_uri") + _verify_exchange_info_uri(source_uri, symbol, f"{label}.source_uri") + source_manifest_path = _declared_file( + root, + metadata["source_manifest_path"], + f"{label} source sidecar", + ) + source_manifest_sha = _digest(metadata["source_manifest_sha256"], f"{label} source sidecar SHA") + source_manifest_bytes = _integer( + metadata["source_manifest_bytes"], + f"{label} source sidecar bytes", + minimum=1, + ) + _verify_file( + source_manifest_path, + source_manifest_sha, + source_manifest_bytes, + f"{label} source sidecar", + ) + if raw_path == source_manifest_path: + raise M8ManifestError(f"{label} raw body and source sidecar must be distinct files") + + sidecar = _read_json_object(source_manifest_path, f"{label} source sidecar") + _exact_keys(sidecar, _RAW_SIDECAR_KEYS, f"{label} source sidecar") + expected_claims: dict[str, object] = { + "manifest_version": _STORAGE_MANIFEST_VERSION, + "artifact_kind": "raw_source", + "source": "binance_spot_public_api", + "source_uri": source_uri, + "bytes": raw_bytes, + "path": raw_path.name, + } + for key, expected in expected_claims.items(): + if sidecar[key] != expected: + raise M8ManifestError(f"{label} source sidecar {key} claim does not match") + _verify_null_requested_range( + sidecar["requested_range_ns"], f"{label} source sidecar requested range" + ) + checksum = _object(sidecar["checksum"], f"{label} source sidecar checksum") + _exact_keys(checksum, _CHECKSUM_KEYS, f"{label} source sidecar checksum") + if ( + checksum["algorithm"] != "sha256" + or _digest(checksum["value"], f"{label} source sidecar checksum value") != raw_sha + ): + raise M8ManifestError(f"{label} source sidecar checksum does not match") + if sidecar["upstream_checksum_sha256"] is not None: + raise M8ManifestError(f"{label} API source sidecar must not claim an upstream checksum") + downloaded_ts_ns = _utc_ns_from_iso( + sidecar["downloaded_at_utc"], f"{label} source sidecar download timestamp" + ) + if downloaded_ts_ns != observed_ts_ns: + raise M8ManifestError(f"{label} observed timestamp does not match its source sidecar") + response_headers = _object( + sidecar["response_headers"], f"{label} source sidecar response headers" + ) + if not all(type(header_value) is str for header_value in response_headers.values()): + raise M8ManifestError(f"{label} source sidecar response headers must be strings") + + _verify_exchange_info_payload( + raw_path, + symbol=symbol, + status=status, + tick_size=tick_size, + lot_size=lot_size, + label=label, + ) + return M8SymbolMetadata( + symbol=symbol, + status=status, + tick_size=tick_size, + lot_size=lot_size, + observed_ts_ns=observed_ts_ns, + raw_path=raw_path, + raw_sha256=raw_sha, + raw_bytes=raw_bytes, + source_uri=source_uri, + source_manifest_path=source_manifest_path, + source_manifest_sha256=source_manifest_sha, + source_manifest_bytes=source_manifest_bytes, + ) + + +def _verify_official_daily_uri( + source_uri: str, + *, + symbol: str, + expected_name: str, + label: str, +) -> None: + try: + parsed_uri = urlparse(source_uri) + port = parsed_uri.port + except ValueError as exc: + raise M8ManifestError(f"{label} has an invalid network location") from exc + expected_uri_path = f"/data/spot/daily/aggTrades/{symbol}/{expected_name}" + expected_uri = f"https://data.binance.vision{expected_uri_path}" + if ( + source_uri != expected_uri + or parsed_uri.scheme != "https" + or parsed_uri.netloc != "data.binance.vision" + or parsed_uri.hostname != "data.binance.vision" + or port is not None + or parsed_uri.username is not None + or parsed_uri.password is not None + or parsed_uri.path != expected_uri_path + or parsed_uri.params + or parsed_uri.query + or parsed_uri.fragment + ): + raise M8ManifestError(f"{label} is not the exact official daily archive URI") + + +def _verify_official_checksum( + *, + entry_label: str, + root: Path, + value: object, + symbol: str, + day: Date, + day_range: tuple[int, int], + zip_path: Path, + zip_sha256: str, + archive_source_uri: str, + archive_sidecar_path: Path, +) -> tuple[Path, str, int, str, Path, str, int]: + label = f"{entry_label} official CHECKSUM" + checksum = _object(value, label) + _exact_keys(checksum, _ARCHIVE_CHECKSUM_KEYS, label) + archive_name = f"{symbol}-aggTrades-{day.isoformat()}.zip" + checksum_name = f"{archive_name}.CHECKSUM" + + checksum_path = _declared_file(root, checksum["path"], f"{label} raw body") + if checksum_path.name != checksum_name: + raise M8ManifestError(f"{label} filename does not match the official archive basename") + checksum_sha = _digest(checksum["sha256"], f"{label} raw SHA") + checksum_bytes = _integer(checksum["bytes"], f"{label} raw bytes", minimum=1) + if checksum_bytes > _MAX_ARCHIVE_CHECKSUM_BYTES: + raise M8ManifestError( + f"{label} exceeds the {_MAX_ARCHIVE_CHECKSUM_BYTES}-byte checksum limit" + ) + _verify_file(checksum_path, checksum_sha, checksum_bytes, f"{label} raw body") + try: + checksum_body = checksum_path.read_bytes() + except OSError as exc: + raise M8ManifestError(f"cannot read {label} raw body: {exc}") from exc + expected_line = f"{zip_sha256} {archive_name}".encode("ascii") + if checksum_body not in { + expected_line, + expected_line + b"\n", + expected_line + b"\r\n", + }: + raise M8ManifestError(f"{label} body must be exactly one ZIP SHA-256/basename line") + + source_uri = _text(checksum["source_uri"], f"{label}.source_uri") + if source_uri != f"{archive_source_uri}.CHECKSUM": + raise M8ManifestError(f"{label} URI is not bound to its ZIP URI") + _verify_official_daily_uri( + source_uri, + symbol=symbol, + expected_name=checksum_name, + label=f"{label}.source_uri", + ) + sidecar_path = _declared_file( + root, + checksum["source_manifest_path"], + f"{label} source sidecar", + ) + sidecar_sha = _digest(checksum["source_manifest_sha256"], f"{label} source sidecar SHA") + sidecar_bytes = _integer( + checksum["source_manifest_bytes"], + f"{label} source sidecar bytes", + minimum=1, + ) + _verify_file(sidecar_path, sidecar_sha, sidecar_bytes, f"{label} source sidecar") + if checksum_path in {zip_path, archive_sidecar_path, sidecar_path} or sidecar_path in { + zip_path, + archive_sidecar_path, + }: + raise M8ManifestError(f"{label} evidence paths must be distinct") + + sidecar = _read_json_object(sidecar_path, f"{label} source sidecar") + _exact_keys(sidecar, _RAW_SIDECAR_KEYS, f"{label} source sidecar") + expected_claims: dict[str, object] = { + "manifest_version": _STORAGE_MANIFEST_VERSION, + "artifact_kind": "raw_source", + "source": "binance_spot_daily_aggtrades_archive_checksum", + "source_uri": source_uri, + "bytes": checksum_bytes, + "path": checksum_name, + } + for key, expected in expected_claims.items(): + if sidecar[key] != expected: + raise M8ManifestError(f"{label} source sidecar {key} claim does not match") + if _range(sidecar["requested_range_ns"], f"{label} requested range") != day_range: + raise M8ManifestError(f"{label} source sidecar does not claim the full UTC day") + sidecar_checksum = _object(sidecar["checksum"], f"{label} source sidecar checksum") + _exact_keys(sidecar_checksum, _CHECKSUM_KEYS, f"{label} source sidecar checksum") + if ( + sidecar_checksum["algorithm"] != "sha256" + or _digest(sidecar_checksum["value"], f"{label} source sidecar checksum value") + != checksum_sha + ): + raise M8ManifestError(f"{label} source sidecar checksum claim does not match") + if sidecar["upstream_checksum_sha256"] is not None: + raise M8ManifestError(f"{label} source sidecar must not claim an upstream checksum") + if _utc_ns_from_iso(sidecar["downloaded_at_utc"], f"{label} download timestamp") < 1: + raise M8ManifestError(f"{label} download timestamp must be after the Unix epoch") + response_headers = _object(sidecar["response_headers"], f"{label} response headers") + if not all(type(header_value) is str for header_value in response_headers.values()): + raise M8ManifestError(f"{label} response headers must be strings") + return ( + checksum_path, + checksum_sha, + checksum_bytes, + source_uri, + sidecar_path, + sidecar_sha, + sidecar_bytes, + ) + + +def _verify_raw_source_sidecar( + *, + config: M8StudyConfig, + entry_label: str, + day_range: tuple[int, int], + symbol: str, + day: Date, + zip_path: Path, + zip_sha256: str, + zip_bytes: int, + source_uri: str, + sidecar_path: Path, +) -> None: + expected_name = f"{symbol}-aggTrades-{day.isoformat()}.zip" + if zip_path.name != expected_name: + raise M8ManifestError(f"{entry_label} raw ZIP filename is not the frozen daily archive") + _verify_official_daily_uri( + source_uri, + symbol=symbol, + expected_name=expected_name, + label=f"{entry_label} source URI", + ) + + sidecar = _read_json_object(sidecar_path, f"{entry_label} raw source sidecar") + _exact_keys(sidecar, _RAW_SIDECAR_KEYS, f"{entry_label} raw source sidecar") + if sidecar["manifest_version"] != _STORAGE_MANIFEST_VERSION: + raise M8ManifestError(f"{entry_label} raw source sidecar version is unsupported") + if sidecar["artifact_kind"] != "raw_source": + raise M8ManifestError(f"{entry_label} raw source sidecar kind is invalid") + if sidecar["source"] != config.study.source or sidecar["source_uri"] != source_uri: + raise M8ManifestError(f"{entry_label} raw source sidecar lineage does not match") + if _range(sidecar["requested_range_ns"], f"{entry_label} raw requested range") != day_range: + raise M8ManifestError(f"{entry_label} raw source sidecar is not a complete UTC day") + checksum = _object(sidecar["checksum"], f"{entry_label} raw checksum") + _exact_keys(checksum, _CHECKSUM_KEYS, f"{entry_label} raw checksum") + if ( + checksum.get("algorithm") != "sha256" + or _digest(checksum.get("value"), f"{entry_label} raw checksum value") != zip_sha256 + ): + raise M8ManifestError(f"{entry_label} raw source checksum claim does not match") + if ( + _digest( + sidecar["upstream_checksum_sha256"], + f"{entry_label} upstream checksum", + ) + != zip_sha256 + ): + raise M8ManifestError(f"{entry_label} official upstream checksum does not match") + if _integer(sidecar["bytes"], f"{entry_label} raw sidecar bytes", minimum=1) != zip_bytes: + raise M8ManifestError(f"{entry_label} raw source byte claim does not match") + sidecar_filename = _text(sidecar["path"], f"{entry_label} raw sidecar path") + if Path(sidecar_filename).name != sidecar_filename or sidecar_filename != expected_name: + raise M8ManifestError(f"{entry_label} raw source sidecar path does not match") + if _utc_ns_from_iso(sidecar["downloaded_at_utc"], f"{entry_label} download timestamp") < 1: + raise M8ManifestError(f"{entry_label} download timestamp must be after the Unix epoch") + response_headers = _object(sidecar["response_headers"], f"{entry_label} response headers") + if not all(type(header_value) is str for header_value in response_headers.values()): + raise M8ManifestError(f"{entry_label} response headers must be strings") + + +def _verify_zip_archive( + *, + config: M8StudyConfig, + entry_label: str, + symbol: str, + day: Date, + zip_path: Path, + uncompressed_bytes: int, +) -> None: + expected_member = f"{symbol}-aggTrades-{day.isoformat()}.csv" + try: + _preflight_zip_central_directory( + zip_path, + entry_label=entry_label, + expected_member=expected_member, + expected_uncompressed_bytes=uncompressed_bytes, + max_uncompressed_bytes=config.study.max_archive_uncompressed_bytes, + ) + with ZipFile(zip_path) as archive: + members = archive.infolist() + if len(members) != 1: + raise M8ManifestError(f"{entry_label} archive must contain exactly one CSV member") + member = members[0] + member_path = Path(member.filename) + if ( + member.is_dir() + or member.filename != expected_member + or member_path.is_absolute() + or ".." in member_path.parts + ): + raise M8ManifestError(f"{entry_label} archive member is not the frozen daily CSV") + if member.flag_bits & 0x1: + raise M8ManifestError(f"{entry_label} archive member must not be encrypted") + if member.file_size != uncompressed_bytes: + raise M8ManifestError( + f"{entry_label} expanded-byte claim does not match ZIP metadata" + ) + if member.file_size > config.study.max_archive_uncompressed_bytes: + raise M8ManifestError( + f"{entry_label} archive exceeds the frozen expanded-byte ceiling" + ) + except M8ManifestError: + raise + except (BadZipFile, OSError, ValueError) as exc: + raise M8ManifestError( + f"{entry_label} raw archive is not a valid bounded ZIP: {exc}" + ) from exc + + +def _zip_extra_field_ids(extra: bytes, *, entry_label: str) -> tuple[int, ...]: + """Parse bounded central-directory extra fields without opening a ZIP member.""" + + field_ids: list[int] = [] + offset = 0 + while offset < len(extra): + if len(extra) - offset < 4: + raise M8ManifestError( + f"{entry_label} archive central-directory extra field is truncated" + ) + field_id, field_bytes = struct.unpack_from(" len(extra) - offset: + raise M8ManifestError( + f"{entry_label} archive central-directory extra field exceeds its bounds" + ) + field_ids.append(field_id) + offset += field_bytes + return tuple(field_ids) + + +def _preflight_zip_central_directory( + path: Path, + *, + entry_label: str, + expected_member: str, + expected_uncompressed_bytes: int, + max_uncompressed_bytes: int, +) -> None: + """Bound and authenticate the one-entry ZIP directory before ``ZipFile`` parses it. + + Only the EOCD record and the declared central-directory bytes are read. In + particular, this preflight never seeks to or decompresses the CSV member. + ZIP64 is deliberately unsupported because the frozen daily-archive limits + fit in the classic ZIP fields and accepting ZIP64 would add an unnecessary + parser surface before the economic-data boundary. + """ + + try: + size = path.stat().st_size + if size < _ZIP_EOCD_STRUCT.size: + raise M8ManifestError(f"{entry_label} archive is too small to contain a ZIP EOCD") + tail_bytes = min(size, _MAX_ZIP_TAIL_BYTES) + with path.open("rb") as source: + source.seek(size - tail_bytes) + tail = source.read(tail_bytes) + relative_eocd = tail.rfind(_ZIP_EOCD_SIGNATURE) + if relative_eocd < 0 or len(tail) - relative_eocd < _ZIP_EOCD_STRUCT.size: + raise M8ManifestError(f"{entry_label} archive ZIP EOCD is missing or truncated") + ( + _signature, + disk_number, + central_disk, + entries_on_disk, + entries_total, + central_bytes, + central_offset, + comment_bytes, + ) = _ZIP_EOCD_STRUCT.unpack_from(tail, relative_eocd) + eocd_offset = size - tail_bytes + relative_eocd + if eocd_offset + _ZIP_EOCD_STRUCT.size + comment_bytes != size: + raise M8ManifestError( + f"{entry_label} archive ZIP EOCD has trailing or malformed bounds" + ) + if ( + disk_number == _ZIP16_SENTINEL + or central_disk == _ZIP16_SENTINEL + or entries_on_disk == _ZIP16_SENTINEL + or entries_total == _ZIP16_SENTINEL + or central_bytes == _ZIP32_SENTINEL + or central_offset == _ZIP32_SENTINEL + ): + raise M8ManifestError(f"{entry_label} archive ZIP64 is not permitted") + if disk_number != 0 or central_disk != 0: + raise M8ManifestError(f"{entry_label} archive must be a single-disk ZIP") + if entries_on_disk != 1 or entries_total != 1: + raise M8ManifestError( + f"{entry_label} archive must contain exactly one central-directory member" + ) + if central_bytes < _ZIP_CENTRAL_STRUCT.size: + raise M8ManifestError( + f"{entry_label} archive central directory is smaller than one entry" + ) + if central_bytes > _MAX_ZIP_DIRECTORY_BYTES: + raise M8ManifestError( + f"{entry_label} archive central directory exceeds its metadata byte ceiling" + ) + if central_offset + central_bytes != eocd_offset: + raise M8ManifestError(f"{entry_label} archive central-directory bounds are malformed") + + with path.open("rb") as source: + source.seek(central_offset) + directory = source.read(central_bytes) + if len(directory) != central_bytes: + raise M8ManifestError(f"{entry_label} archive central directory is truncated") + ( + signature, + _version_made, + _version_needed, + flags, + compression, + _modified_time, + _modified_date, + _crc32, + compressed_bytes, + uncompressed_bytes, + filename_bytes, + extra_bytes, + member_comment_bytes, + member_disk, + _internal_attributes, + _external_attributes, + local_header_offset, + ) = _ZIP_CENTRAL_STRUCT.unpack_from(directory) + if signature != _ZIP_CENTRAL_SIGNATURE: + raise M8ManifestError(f"{entry_label} archive central-directory signature is invalid") + if ( + compressed_bytes == _ZIP32_SENTINEL + or uncompressed_bytes == _ZIP32_SENTINEL + or local_header_offset == _ZIP32_SENTINEL + or member_disk == _ZIP16_SENTINEL + ): + raise M8ManifestError(f"{entry_label} archive ZIP64 entry is not permitted") + if member_disk != 0: + raise M8ManifestError(f"{entry_label} archive member starts on another disk") + declared_entry_bytes = ( + _ZIP_CENTRAL_STRUCT.size + filename_bytes + extra_bytes + member_comment_bytes + ) + if declared_entry_bytes != central_bytes: + raise M8ManifestError( + f"{entry_label} archive central directory does not contain exactly one entry" + ) + filename_start = _ZIP_CENTRAL_STRUCT.size + filename_end = filename_start + filename_bytes + extra_end = filename_end + extra_bytes + filename = directory[filename_start:filename_end] + extra = directory[filename_end:extra_end] + try: + decoded_filename = filename.decode("ascii") + except UnicodeDecodeError as exc: + raise M8ManifestError( + f"{entry_label} archive central member name is not ASCII" + ) from exc + if decoded_filename != expected_member: + raise M8ManifestError( + f"{entry_label} archive central member is not the frozen daily CSV" + ) + if _ZIP64_EXTRA_FIELD_ID in _zip_extra_field_ids(extra, entry_label=entry_label): + raise M8ManifestError(f"{entry_label} archive ZIP64 extra field is not permitted") + if flags & 0x1: + raise M8ManifestError(f"{entry_label} archive member must not be encrypted") + if compression not in {0, 8}: + raise M8ManifestError(f"{entry_label} archive member uses unsupported compression") + if local_header_offset >= central_offset: + raise M8ManifestError( + f"{entry_label} archive local-header offset is outside the payload region" + ) + if uncompressed_bytes != expected_uncompressed_bytes: + raise M8ManifestError( + f"{entry_label} expanded-byte claim does not match ZIP central metadata" + ) + if uncompressed_bytes < 1 or uncompressed_bytes > max_uncompressed_bytes: + raise M8ManifestError(f"{entry_label} archive exceeds the frozen expanded-byte ceiling") + except M8ManifestError: + raise + except (OSError, struct.error, ValueError) as exc: + raise M8ManifestError( + f"{entry_label} raw archive has invalid bounded ZIP metadata: {exc}" + ) from exc + + +def _verify_quality( + *, + entry_label: str, + rows: int, + quality: Mapping[str, Any], + root: Path, +) -> tuple[Path, str, int, Path, str, int, int, int]: + _exact_keys(quality, _QUALITY_KEYS, f"{entry_label}.quality") + report_sha = _digest(quality["report_sha256"], f"{entry_label} quality report SHA") + report_bytes = _integer( + quality["report_bytes"], f"{entry_label} quality report bytes", minimum=1 + ) + report_path = _declared_file(root, quality["report_path"], f"{entry_label} quality report") + _verify_file(report_path, report_sha, report_bytes, f"{entry_label} quality report") + findings_sha = _digest(quality["findings_sha256"], f"{entry_label} quality findings SHA") + findings_bytes = _integer( + quality["findings_bytes"], f"{entry_label} quality findings bytes", minimum=0 + ) + findings_path = _declared_file( + root, quality["findings_path"], f"{entry_label} quality findings" + ) + _verify_file(findings_path, findings_sha, findings_bytes, f"{entry_label} quality findings") + errors = _integer(quality["errors"], f"{entry_label} quality errors", minimum=0) + warnings = _integer(quality["warnings"], f"{entry_label} quality warnings", minimum=0) + if errors != 0 or warnings != 0: + raise M8ManifestError(f"{entry_label} has quality findings and is not complete evidence") + if findings_bytes != 0: + raise M8ManifestError(f"{entry_label} zero-finding JSONL must be empty") + + report = _read_json_object(report_path, f"{entry_label} quality report") + if report.get("dataset") != "trades": + raise M8ManifestError(f"{entry_label} quality report dataset is not trades") + if _integer(report.get("rows_checked"), f"{entry_label} rows checked", minimum=1) != rows: + raise M8ManifestError(f"{entry_label} quality report row count does not match") + summary = _object(report.get("summary"), f"{entry_label} quality summary") + if _integer(summary.get("errors"), f"{entry_label} report errors", minimum=0) != errors: + raise M8ManifestError(f"{entry_label} quality error count does not match") + if _integer(summary.get("warnings"), f"{entry_label} report warnings", minimum=0) != warnings: + raise M8ManifestError(f"{entry_label} quality warning count does not match") + retained = _array(report.get("findings"), f"{entry_label} retained findings") + if retained: + raise M8ManifestError(f"{entry_label} zero-finding quality report retained findings") + if report.get("mutation_policy") != "observations were not changed or repaired": + raise M8ManifestError(f"{entry_label} quality report mutation policy is invalid") + return ( + report_path, + report_sha, + report_bytes, + findings_path, + findings_sha, + findings_bytes, + errors, + warnings, + ) + + +def _verify_part( + *, + config: M8StudyConfig, + entry_label: str, + part_index: int, + part_value: object, + dataset_artifact_value: object, + root: Path, + dataset_root: Path, + symbol: str, + day: Date, + day_range: tuple[int, int], + source_uri: str, + raw_sha256: str, +) -> M8NormalizedPart: + label = f"{entry_label} normalized part {part_index}" + part = _object(part_value, label) + _exact_keys(part, _PART_KEYS, label) + dataset_artifact = _object(dataset_artifact_value, f"{label} dataset descriptor") + _exact_keys(dataset_artifact, _DATASET_PART_KEYS, f"{label} dataset descriptor") + + ordinal = _integer(part["write_ordinal"], f"{label}.write_ordinal", minimum=0) + if ( + ordinal != part_index + or _integer( + dataset_artifact["write_ordinal"], + f"{label} dataset write ordinal", + minimum=0, + ) + != ordinal + ): + raise M8ManifestError(f"{label} write ordinals are not contiguous and ordered") + rows = _integer(part["rows"], f"{label}.rows", minimum=1) + if _integer(dataset_artifact["rows"], f"{label} dataset rows", minimum=1) != rows: + raise M8ManifestError(f"{label} dataset row count does not match") + + data_sha = _digest(part["data_sha256"], f"{label} data SHA") + sidecar_sha = _digest(part["sidecar_sha256"], f"{label} sidecar SHA") + if _digest(dataset_artifact["data_sha256"], f"{label} dataset data SHA") != data_sha: + raise M8ManifestError(f"{label} dataset data checksum does not match") + if _digest(dataset_artifact["manifest_sha256"], f"{label} dataset sidecar SHA") != sidecar_sha: + raise M8ManifestError(f"{label} dataset sidecar checksum does not match") + + data_bytes = _integer(part["data_bytes"], f"{label} data bytes", minimum=1) + sidecar_bytes = _integer(part["sidecar_bytes"], f"{label} sidecar bytes", minimum=1) + data_path = _declared_file(root, part["data_path"], f"{label} data") + sidecar_path = _declared_file(root, part["sidecar_path"], f"{label} sidecar") + nested_data_path = _declared_file( + dataset_root, + dataset_artifact["data_path"], + f"{label} dataset data path", + ) + nested_sidecar_path = _declared_file( + dataset_root, + dataset_artifact["manifest_path"], + f"{label} dataset sidecar path", + ) + if data_path != nested_data_path or sidecar_path != nested_sidecar_path: + raise M8ManifestError(f"{label} explicit paths do not match the dataset manifest") + _verify_file(data_path, data_sha, data_bytes, f"{label} data") + _verify_file(sidecar_path, sidecar_sha, sidecar_bytes, f"{label} sidecar") + + observed = _observed_range(part["observed_range_ns"], f"{label} observed range") + dataset_observed = _observed_range( + dataset_artifact["observed_range_ns"], f"{label} dataset observed range" + ) + if observed != dataset_observed: + raise M8ManifestError(f"{label} observed ranges do not match") + _verify_day_range(observed, day_range, f"{label} observed range") + + sidecar = _read_json_object(sidecar_path, f"{label} sidecar") + _exact_keys(sidecar, _PART_SIDECAR_KEYS, f"{label} sidecar") + expected_claims: dict[str, object] = { + "manifest_version": _STORAGE_MANIFEST_VERSION, + "artifact_kind": "normalized_parquet", + "dataset": "trades", + "schema_name": "trades", + "schema_version": SCHEMA_VERSION, + "venue": "binance_spot", + "symbol": symbol, + "partition_date": day.isoformat(), + "write_ordinal": ordinal, + "source": config.study.source, + "source_uri": source_uri, + "source_checksum_sha256": raw_sha256, + "rows": rows, + "bytes": data_bytes, + } + for key, expected in expected_claims.items(): + if sidecar[key] != expected: + raise M8ManifestError(f"{label} sidecar {key} claim does not match") + if _range(sidecar["requested_range_ns"], f"{label} sidecar requested range") != day_range: + raise M8ManifestError(f"{label} sidecar requested range does not match") + if _observed_range(sidecar["observed_range_ns"], f"{label} sidecar observed") != observed: + raise M8ManifestError(f"{label} sidecar observed range does not match") + checksum = _object(sidecar["checksum"], f"{label} sidecar checksum") + if ( + checksum.get("algorithm") != "sha256" + or _digest(checksum.get("value"), f"{label} sidecar checksum value") != data_sha + ): + raise M8ManifestError(f"{label} sidecar data checksum does not match") + expected_nested_data = _text(dataset_artifact["data_path"], f"{label} nested data path") + if sidecar["path"] != expected_nested_data: + raise M8ManifestError(f"{label} sidecar path claim does not match") + + try: + parquet = pq.ParquetFile(data_path) + if parquet.metadata.num_rows != rows: + raise M8ManifestError(f"{label} Parquet footer row count does not match") + if not parquet.schema_arrow.equals(get_schema("trades"), check_metadata=True): + raise M8ManifestError(f"{label} Parquet schema is not normalized trades") + except M8ManifestError: + raise + except (OSError, pa.ArrowException, ValueError) as exc: + raise M8ManifestError(f"cannot inspect {label} Parquet footer: {exc}") from exc + + return M8NormalizedPart( + data_path=data_path, + data_sha256=data_sha, + data_bytes=data_bytes, + sidecar_path=sidecar_path, + sidecar_sha256=sidecar_sha, + sidecar_bytes=sidecar_bytes, + rows=rows, + write_ordinal=ordinal, + observed_start_ns=observed[0], + observed_end_inclusive_ns=observed[1], + ) + + +def _verify_normalized( + *, + config: M8StudyConfig, + entry_label: str, + normalized: Mapping[str, Any], + root: Path, + symbol: str, + day: Date, + day_range: tuple[int, int], + entry_rows: int, + entry_observed: tuple[int, int], + source_uri: str, + raw_sha256: str, +) -> tuple[Path, str, int, tuple[M8NormalizedPart, ...]]: + _exact_keys(normalized, _NORMALIZED_KEYS, f"{entry_label}.normalized") + dataset_sha = _digest( + normalized["dataset_manifest_sha256"], f"{entry_label} dataset manifest SHA" + ) + dataset_bytes = _integer( + normalized["dataset_manifest_bytes"], + f"{entry_label} dataset manifest bytes", + minimum=1, + ) + dataset_path = _declared_file( + root, + normalized["dataset_manifest_path"], + f"{entry_label} normalized dataset manifest", + ) + _verify_file( + dataset_path, + dataset_sha, + dataset_bytes, + f"{entry_label} normalized dataset manifest", + ) + if dataset_path.parent.name != "_manifests": + raise M8ManifestError(f"{entry_label} dataset manifest is not under _manifests") + dataset_root = dataset_path.parent.parent.resolve() + if not dataset_root.is_relative_to(root.resolve()): + raise M8ManifestError(f"{entry_label} dataset root escapes the M8 input root") + + declared_rows = _integer(normalized["rows"], f"{entry_label} normalized rows", minimum=1) + if declared_rows != entry_rows: + raise M8ManifestError(f"{entry_label} normalized row count does not match") + top_parts = _array(normalized["parts"], f"{entry_label} normalized parts") + if not top_parts: + raise M8ManifestError(f"{entry_label} must declare at least one normalized part") + + dataset = _read_json_object(dataset_path, f"{entry_label} dataset manifest") + _exact_keys(dataset, _DATASET_KEYS, f"{entry_label} dataset manifest") + expected_claims: dict[str, object] = { + "manifest_version": _STORAGE_MANIFEST_VERSION, + "dataset": "trades", + "schema_version": SCHEMA_VERSION, + "source": config.study.source, + "source_uri": source_uri, + "rows": entry_rows, + } + for key, expected in expected_claims.items(): + if dataset[key] != expected: + raise M8ManifestError(f"{entry_label} dataset manifest {key} claim does not match") + if _range(dataset["requested_range_ns"], f"{entry_label} dataset requested range") != day_range: + raise M8ManifestError(f"{entry_label} dataset requested range does not match") + dataset_parts = _array(dataset["artifacts"], f"{entry_label} dataset artifacts") + if len(dataset_parts) != len(top_parts): + raise M8ManifestError(f"{entry_label} dataset part count does not match") + + parts = tuple( + _verify_part( + config=config, + entry_label=entry_label, + part_index=index, + part_value=top_part, + dataset_artifact_value=dataset_part, + root=root, + dataset_root=dataset_root, + symbol=symbol, + day=day, + day_range=day_range, + source_uri=source_uri, + raw_sha256=raw_sha256, + ) + for index, (top_part, dataset_part) in enumerate(zip(top_parts, dataset_parts, strict=True)) + ) + if len({part.data_path for part in parts}) != len(parts): + raise M8ManifestError(f"{entry_label} contains duplicate normalized part paths") + if len({part.sidecar_path for part in parts}) != len(parts): + raise M8ManifestError(f"{entry_label} contains duplicate normalized sidecar paths") + if sum(part.rows for part in parts) != entry_rows: + raise M8ManifestError(f"{entry_label} normalized part rows do not sum to entry rows") + aggregate_observed = ( + min(part.observed_start_ns for part in parts), + max(part.observed_end_inclusive_ns for part in parts), + ) + if aggregate_observed != entry_observed: + raise M8ManifestError(f"{entry_label} normalized part bounds do not match entry bounds") + return dataset_path, dataset_sha, dataset_bytes, parts + + +def _verify_entry( + config: M8StudyConfig, + root: Path, + value: object, + expected: tuple[str, Date, M8PeriodRole], + symbol_metadata: M8SymbolMetadata, + index: int, +) -> M8ArchiveEntry: + label = f"entries[{index}]" + entry = _object(value, label) + _exact_keys(entry, _ENTRY_KEYS, label) + symbol = _text(entry["symbol"], f"{label}.symbol") + day = _parse_date(entry["date"], f"{label}.date") + role = _parse_role(entry["role"], f"{label}.role") + if (symbol, day, role) != expected: + raise M8ManifestError( + f"{label} is out of frozen order or has an unexpected symbol/date/role" + ) + if not _boolean(entry["complete"], f"{label}.complete"): + raise M8ManifestError(f"{label} is not a complete full-day archive") + day_range = _day_bounds_ns(day) + if _range(entry["requested_range_ns"], f"{label}.requested_range_ns") != day_range: + raise M8ManifestError(f"{label} does not claim the exact full UTC day") + + rows = _integer(entry["rows"], f"{label}.rows", minimum=1) + trade_ids = _object(entry["trade_id_range"], f"{label}.trade_id_range") + _exact_keys(trade_ids, _TRADE_ID_KEYS, f"{label}.trade_id_range") + first_trade_id = _integer(trade_ids["first"], f"{label}.first_trade_id", minimum=0) + last_trade_id = _integer(trade_ids["last"], f"{label}.last_trade_id", minimum=0) + contiguous_count = _integer( + trade_ids["contiguous_count"], f"{label}.contiguous_count", minimum=1 + ) + if contiguous_count != rows or last_trade_id - first_trade_id + 1 != rows: + raise M8ManifestError(f"{label} aggregate-trade IDs are not a contiguous row count") + + observed = _observed_range(entry["observed_range_ns"], f"{label}.observed_range_ns") + _verify_day_range(observed, day_range, f"{label} observed event bounds") + scales = _object(entry["scales"], f"{label}.scales") + _exact_keys(scales, _SCALE_KEYS, f"{label}.scales") + tick_size = _decimal(scales["tick_size"], f"{label}.tick_size") + lot_size = _decimal(scales["lot_size"], f"{label}.lot_size") + if ( + symbol_metadata.symbol != symbol + or tick_size != symbol_metadata.tick_size + or lot_size != symbol_metadata.lot_size + ): + raise M8ManifestError( + f"{label} scales do not match verified exchangeInfo metadata for {symbol}" + ) + + raw = _object(entry["raw"], f"{label}.raw") + _exact_keys(raw, _RAW_KEYS, f"{label}.raw") + raw_zip_path = _declared_file(root, raw["zip_path"], f"{label} raw ZIP") + raw_zip_sha = _digest(raw["zip_sha256"], f"{label} raw ZIP SHA") + raw_zip_bytes = _integer(raw["zip_bytes"], f"{label} raw ZIP bytes", minimum=1) + raw_uncompressed_bytes = _integer( + raw["uncompressed_bytes"], f"{label} raw expanded bytes", minimum=1 + ) + if raw_zip_bytes > config.study.max_archive_compressed_bytes: + raise M8ManifestError(f"{label} raw ZIP exceeds the frozen compressed-byte ceiling") + if raw_uncompressed_bytes > config.study.max_archive_uncompressed_bytes: + raise M8ManifestError(f"{label} archive exceeds the frozen expanded-byte ceiling") + _verify_file(raw_zip_path, raw_zip_sha, raw_zip_bytes, f"{label} raw ZIP") + _verify_zip_archive( + config=config, + entry_label=label, + symbol=symbol, + day=day, + zip_path=raw_zip_path, + uncompressed_bytes=raw_uncompressed_bytes, + ) + source_uri = _text(raw["source_uri"], f"{label}.source_uri") + raw_sidecar_path = _declared_file( + root, raw["source_manifest_path"], f"{label} raw source sidecar" + ) + raw_sidecar_sha = _digest(raw["source_manifest_sha256"], f"{label} raw source sidecar SHA") + raw_sidecar_bytes = _integer( + raw["source_manifest_bytes"], f"{label} raw source sidecar bytes", minimum=1 + ) + _verify_file( + raw_sidecar_path, + raw_sidecar_sha, + raw_sidecar_bytes, + f"{label} raw source sidecar", + ) + _verify_raw_source_sidecar( + config=config, + entry_label=label, + day_range=day_range, + symbol=symbol, + day=day, + zip_path=raw_zip_path, + zip_sha256=raw_zip_sha, + zip_bytes=raw_zip_bytes, + source_uri=source_uri, + sidecar_path=raw_sidecar_path, + ) + ( + raw_checksum_path, + raw_checksum_sha, + raw_checksum_bytes, + raw_checksum_source_uri, + raw_checksum_sidecar_path, + raw_checksum_sidecar_sha, + raw_checksum_sidecar_bytes, + ) = _verify_official_checksum( + entry_label=label, + root=root, + value=raw["checksum"], + symbol=symbol, + day=day, + day_range=day_range, + zip_path=raw_zip_path, + zip_sha256=raw_zip_sha, + archive_source_uri=source_uri, + archive_sidecar_path=raw_sidecar_path, + ) + + normalized = _object(entry["normalized"], f"{label}.normalized") + dataset_path, dataset_sha, dataset_bytes, parts = _verify_normalized( + config=config, + entry_label=label, + normalized=normalized, + root=root, + symbol=symbol, + day=day, + day_range=day_range, + entry_rows=rows, + entry_observed=observed, + source_uri=source_uri, + raw_sha256=raw_zip_sha, + ) + quality = _object(entry["quality"], f"{label}.quality") + ( + quality_report_path, + quality_report_sha, + quality_report_bytes, + quality_findings_path, + quality_findings_sha, + quality_findings_bytes, + quality_errors, + quality_warnings, + ) = _verify_quality(entry_label=label, rows=rows, quality=quality, root=root) + + return M8ArchiveEntry( + symbol=symbol, + date=day, + role=role, + complete=True, + rows=rows, + first_trade_id=first_trade_id, + last_trade_id=last_trade_id, + observed_start_ns=observed[0], + observed_end_inclusive_ns=observed[1], + tick_size=tick_size, + lot_size=lot_size, + raw_zip_path=raw_zip_path, + raw_zip_sha256=raw_zip_sha, + raw_zip_bytes=raw_zip_bytes, + raw_uncompressed_bytes=raw_uncompressed_bytes, + raw_source_uri=source_uri, + raw_source_manifest_path=raw_sidecar_path, + raw_source_manifest_sha256=raw_sidecar_sha, + raw_source_manifest_bytes=raw_sidecar_bytes, + raw_checksum_path=raw_checksum_path, + raw_checksum_sha256=raw_checksum_sha, + raw_checksum_bytes=raw_checksum_bytes, + raw_checksum_source_uri=raw_checksum_source_uri, + raw_checksum_source_manifest_path=raw_checksum_sidecar_path, + raw_checksum_source_manifest_sha256=raw_checksum_sidecar_sha, + raw_checksum_source_manifest_bytes=raw_checksum_sidecar_bytes, + normalized_dataset_manifest_path=dataset_path, + normalized_dataset_manifest_sha256=dataset_sha, + normalized_dataset_manifest_bytes=dataset_bytes, + normalized_parts=parts, + quality_report_path=quality_report_path, + quality_report_sha256=quality_report_sha, + quality_report_bytes=quality_report_bytes, + quality_findings_path=quality_findings_path, + quality_findings_sha256=quality_findings_sha, + quality_findings_bytes=quality_findings_bytes, + quality_errors=quality_errors, + quality_warnings=quality_warnings, + ) + + +def _verify_payload( + config: M8StudyConfig, root: Path, payload: Mapping[str, Any] +) -> tuple[tuple[M8SymbolMetadata, ...], tuple[M8ArchiveEntry, ...]]: + _exact_keys(payload, _TOP_KEYS, "M8 input manifest") + if payload["manifest_version"] != M8_INPUT_MANIFEST_VERSION: + raise M8ManifestError("unsupported M8 input manifest version") + if payload["artifact_kind"] != "m8_multidate_trade_input": + raise M8ManifestError("unexpected M8 input manifest artifact kind") + + config_claim = _object(payload["config"], "M8 input manifest config") + _exact_keys(config_claim, _CONFIG_KEYS, "M8 input manifest config") + expected_config = { + "semantic_sha256": config.hash, + "source_sha256": config.source_sha256, + "protocol_version": config.study.protocol_version, + } + if dict(config_claim) != expected_config: + raise M8ManifestError("M8 input manifest is bound to a different frozen configuration") + + study = _object(payload["study"], "M8 input manifest study") + _exact_keys(study, _STUDY_KEYS, "M8 input manifest study") + expected_periods = [ + {"date": period.date.isoformat(), "role": period.role} for period in config.periods + ] + observed_periods = _array(study["periods"], "M8 input manifest study periods") + for index, raw_period in enumerate(observed_periods): + period = _object(raw_period, f"M8 input manifest study periods[{index}]") + _exact_keys(period, _STUDY_PERIOD_KEYS, f"M8 input manifest study periods[{index}]") + expected_study: dict[str, object] = { + "name": config.study.name, + "evidence_tier": config.study.evidence_tier, + "source": config.study.source, + "symbols": list(config.study.symbols), + "periods": expected_periods, + } + if dict(study) != expected_study: + raise M8ManifestError("M8 input manifest study scope differs from the frozen protocol") + + raw_symbol_metadata = _array(payload["symbol_metadata"], "M8 input manifest symbol metadata") + if len(raw_symbol_metadata) != len(config.study.symbols) or len(raw_symbol_metadata) != 2: + raise M8ManifestError("M8 input manifest must contain exactly two symbol metadata entries") + symbol_metadata = tuple( + _verify_symbol_metadata(root, value, expected_symbol, index) + for index, (value, expected_symbol) in enumerate( + zip(raw_symbol_metadata, config.study.symbols, strict=True) + ) + ) + if len({metadata.symbol for metadata in symbol_metadata}) != len(symbol_metadata): + raise M8ManifestError("M8 input manifest contains duplicate symbol metadata") + if len({metadata.raw_path for metadata in symbol_metadata}) != len(symbol_metadata): + raise M8ManifestError("M8 input manifest reuses an exchangeInfo raw body") + if len({metadata.source_manifest_path for metadata in symbol_metadata}) != len(symbol_metadata): + raise M8ManifestError("M8 input manifest reuses an exchangeInfo source sidecar") + total_symbol_metadata_bytes = _integer( + payload["total_symbol_metadata_bytes"], + "M8 total symbol metadata bytes", + minimum=1, + ) + observed_metadata_total = sum(metadata.raw_bytes for metadata in symbol_metadata) + if total_symbol_metadata_bytes != observed_metadata_total: + raise M8ManifestError("M8 total symbol metadata byte claim does not match") + if total_symbol_metadata_bytes > len(symbol_metadata) * _MAX_SYMBOL_METADATA_BYTES: + raise M8ManifestError("M8 symbol metadata exceeds its bounded total byte ceiling") + metadata_by_symbol = {metadata.symbol: metadata for metadata in symbol_metadata} + + raw_entries = _array(payload["entries"], "M8 input manifest entries") + expected_order = _expected_entry_order(config) + if len(raw_entries) != len(expected_order) or len(raw_entries) != 8: + raise M8ManifestError("M8 input manifest must contain exactly eight entries") + entries = tuple( + _verify_entry( + config, + root, + value, + expected, + metadata_by_symbol[expected[0]], + index, + ) + for index, (value, expected) in enumerate(zip(raw_entries, expected_order, strict=True)) + ) + if len({(entry.symbol, entry.date) for entry in entries}) != len(entries): + raise M8ManifestError("M8 input manifest contains duplicate symbol/date entries") + total_raw_zip_bytes = _integer( + payload["total_raw_zip_bytes"], "M8 total raw ZIP bytes", minimum=1 + ) + observed_total = sum(entry.raw_zip_bytes for entry in entries) + if total_raw_zip_bytes != observed_total: + raise M8ManifestError("M8 total raw ZIP byte claim does not match its entries") + if total_raw_zip_bytes > config.study.max_total_download_bytes: + raise M8ManifestError("M8 raw archives exceed the frozen total-download ceiling") + return symbol_metadata, entries + + +def _encoded_manifest(payload: Mapping[str, Any]) -> bytes: + return ( + json.dumps(payload, indent=2, sort_keys=True, allow_nan=False, ensure_ascii=False) + "\n" + ).encode("utf-8") + + +def write_m8_input_manifest( + config: M8StudyConfig, + root: str | Path, + entries: Sequence[M8ArchiveEntry], + symbol_metadata: Sequence[M8SymbolMetadata], + *, + output_dir: str | Path | None = None, +) -> M8InputManifest: + """Validate and atomically publish one deterministic content-addressed manifest.""" + + input_root = Path(root).resolve() + if not input_root.is_dir(): + raise M8ManifestError(f"M8 input root does not exist: {input_root}") + payload = _manifest_payload(config, input_root, entries, symbol_metadata) + _verify_payload(config, input_root, payload) + encoded = _encoded_manifest(payload) + digest = hashlib.sha256(encoded).hexdigest() + directory = ( + (input_root / "_manifests").resolve() + if output_dir is None + else ( + Path(output_dir) if Path(output_dir).is_absolute() else input_root / output_dir + ).resolve() + ) + if not directory.is_relative_to(input_root): + raise M8ManifestError("M8 manifest output directory escapes the input root") + directory.mkdir(parents=True, exist_ok=True) + destination = directory / f"m8-input.manifest-{digest[:20]}.json" + if destination.exists(): + if destination.read_bytes() != encoded: + raise M8ManifestError(f"immutable M8 manifest collision at {destination}") + else: + descriptor, temporary_name = tempfile.mkstemp( + dir=directory, + prefix=f".{destination.name}.", + suffix=".tmp", + ) + temporary = Path(temporary_name) + try: + with os.fdopen(descriptor, "wb") as handle: + handle.write(encoded) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, destination) + except BaseException: + temporary.unlink(missing_ok=True) + raise + return read_m8_input_manifest( + config, + input_root, + destination, + manifest_sha256=digest, + ) + + +def read_m8_input_manifest( + config: M8StudyConfig, + root: str | Path, + manifest_path: str | Path, + *, + manifest_sha256: str, +) -> M8InputManifest: + """Read and fully verify a manifest and every declared evidence artifact.""" + + input_root = Path(root).resolve() + if not input_root.is_dir(): + raise M8ManifestError(f"M8 input root does not exist: {input_root}") + expected_sha = _digest(manifest_sha256, "M8 input manifest SHA") + path = _resolve_contained_file(input_root, Path(manifest_path), "M8 input manifest") + observed_sha = sha256_file(path) + if observed_sha != expected_sha: + raise M8ManifestError( + f"M8 input manifest SHA-256 mismatch: expected {expected_sha}, observed {observed_sha}" + ) + expected_name = f"m8-input.manifest-{expected_sha[:20]}.json" + if path.name != expected_name: + raise M8ManifestError("M8 input manifest filename is not content-addressed") + payload = _read_json_object(path, "M8 input manifest") + symbol_metadata, entries = _verify_payload(config, input_root, payload) + return M8InputManifest( + root=input_root, + path=path, + sha256=expected_sha, + config_sha256=config.hash, + config_source_sha256=config.source_sha256, + protocol_version=config.study.protocol_version, + symbol_metadata=symbol_metadata, + entries=entries, + ) + + +def verify_m8_input_manifest( + config: M8StudyConfig, + root: str | Path, + manifest_path: str | Path, + *, + manifest_sha256: str, +) -> M8InputManifest: + """Alias with an explicit verification name for CLI/pipeline call sites.""" + + return read_m8_input_manifest( + config, + root, + manifest_path, + manifest_sha256=manifest_sha256, + ) + + +__all__ = [ + "M8_INPUT_MANIFEST_VERSION", + "M8ArchiveEntry", + "M8InputManifest", + "M8ManifestError", + "M8NormalizedPart", + "M8SymbolMetadata", + "read_m8_input_manifest", + "verify_m8_input_manifest", + "write_m8_input_manifest", +] diff --git a/Microstructure/src/microstructure/m8_normalization.py b/Microstructure/src/microstructure/m8_normalization.py new file mode 100644 index 0000000000000000000000000000000000000000..27ab0c4164801998687eb5471db0c27e5a312d04 --- /dev/null +++ b/Microstructure/src/microstructure/m8_normalization.py @@ -0,0 +1,375 @@ +"""Single-archive, streaming normalization for the locked M8 producer. + +This module intentionally has no all-calendar entry point. A caller receives +one already authenticated :class:`AcquiredDailyArchive` and decides when the +CSV member may be opened. In particular, the M8 producer supplies a +``before_member_open`` guard for held-out dates so the durable analysis lock is +revalidated at the lowest economic-data boundary. +""" + +from __future__ import annotations + +from collections.abc import Callable, Iterator, Mapping +from dataclasses import dataclass +from datetime import UTC, datetime +from pathlib import Path +from typing import Any, Literal, cast + +import pyarrow as pa # type: ignore[import-untyped] + +from microstructure.data.binance_archive import ( + AcquiredDailyArchive, + BinanceArchivePayloadError, +) +from microstructure.data.quality import IncrementalQualityValidator +from microstructure.data.storage import DatasetWriteResult, write_partitioned_parquet +from microstructure.m8_config import M8Period, M8StudyConfig +from microstructure.m8_manifest import M8ArchiveEntry, M8NormalizedPart, M8SymbolMetadata +from microstructure.provenance import read_json, sha256_file + +_DEFAULT_BATCH_ROWS = 65_536 + + +class M8NormalizationError(RuntimeError): + """A system or caller-contract failure while normalizing one archive.""" + + +M8NormalizationFailureKind = Literal[ + "PAYLOAD_OR_CONTINUITY", + "QUALITY_GATE", + "POSTWRITE_CONSISTENCY", +] +M8NormalizationEvidenceCompletion = Literal[ + "PARTIAL_STREAM", + "COMPLETE_DATASET_AND_QUALITY", +] + + +class M8InsufficientDataError(M8NormalizationError): + """A deterministic archive/data-quality failure in a declared date.""" + + def __init__( + self, + symbol: str, + study_date: str, + reason: str, + *, + failure_kind: M8NormalizationFailureKind | None = None, + evidence_completion: M8NormalizationEvidenceCompletion | None = None, + completed_evidence: M8ArchiveEntry | None = None, + ) -> None: + super().__init__(f"{symbol}/{study_date}: {reason}") + self.symbol = symbol + self.study_date = study_date + self.reason = reason + self.failure_kind = failure_kind + self.evidence_completion = evidence_completion + self.completed_evidence = completed_evidence + + +@dataclass(frozen=True, slots=True) +class M8NormalizedArchive: + """One complete archive entry plus its bounded normalization output.""" + + entry: M8ArchiveEntry + output_root: Path + + +def _object(value: object, label: str) -> Mapping[str, Any]: + if not isinstance(value, Mapping): + raise M8NormalizationError(f"{label} must be a JSON object") + return cast(Mapping[str, Any], value) + + +def _downloaded_at(acquired: AcquiredDailyArchive) -> str: + try: + sidecar = _object( + read_json(acquired.archive_artifact.manifest_path), + "archive source sidecar", + ) + except M8NormalizationError: + raise + except (OSError, UnicodeDecodeError, ValueError) as exc: + raise M8NormalizationError(f"cannot parse archive source sidecar: {exc}") from exc + value = sidecar.get("downloaded_at_utc") + if type(value) is not str or not value: + raise M8NormalizationError("archive source sidecar lacks downloaded_at_utc") + return value + + +def _parts(storage: DatasetWriteResult) -> tuple[M8NormalizedPart, ...]: + return tuple( + M8NormalizedPart( + data_path=item.data_path.resolve(), + data_sha256=item.data_sha256, + data_bytes=item.data_path.stat().st_size, + sidecar_path=item.manifest_path.resolve(), + sidecar_sha256=item.manifest_sha256, + sidecar_bytes=item.manifest_path.stat().st_size, + rows=item.rows, + write_ordinal=item.write_ordinal, + observed_start_ns=item.observed_start_ns, + observed_end_inclusive_ns=item.observed_end_inclusive_ns, + ) + for item in storage.artifacts + ) + + +def _validate_contract( + config: M8StudyConfig, + period: M8Period, + metadata: M8SymbolMetadata, + acquired: AcquiredDailyArchive, + root: Path, +) -> None: + request = acquired.request + if request.symbol != metadata.symbol or request.date != period.date: + raise M8NormalizationError("acquired archive identity disagrees with requested period") + if request.tick_size != metadata.tick_size or request.lot_size != metadata.lot_size: + raise M8NormalizationError("acquired archive scales disagree with frozen metadata") + if metadata.status != "TRADING" or metadata.symbol not in config.study.symbols: + raise M8NormalizationError("symbol metadata does not prove a frozen TRADING symbol") + evidence = ( + acquired.archive_artifact.path.resolve(), + acquired.archive_artifact.manifest_path.resolve(), + acquired.checksum_artifact.path.resolve(), + acquired.checksum_artifact.manifest_path.resolve(), + ) + if len(set(evidence)) != len(evidence) or any( + not path.is_relative_to(root) or not path.is_file() for path in evidence + ): + raise M8NormalizationError("stage-local raw evidence is missing, reused, or escapes root") + if acquired.upstream_sha256 != acquired.archive_artifact.sha256: + raise M8NormalizationError("official checksum does not authenticate the stage-local ZIP") + for artifact in (acquired.archive_artifact, acquired.checksum_artifact): + if artifact.path.stat().st_size != artifact.bytes: + raise M8NormalizationError("stage-local raw artifact byte count changed") + if sha256_file(artifact.path) != artifact.sha256: + raise M8NormalizationError("stage-local raw artifact checksum changed") + if sha256_file(artifact.manifest_path) != artifact.manifest_sha256: + raise M8NormalizationError("stage-local raw sidecar checksum changed") + + +def _validate_frozen_period(config: M8StudyConfig, period: M8Period) -> None: + """Reject a date/role reinterpretation before any economic member can open.""" + + if period not in config.periods: + raise M8NormalizationError("M8 period date/role is not an exact frozen configuration entry") + + +def normalize_m8_archive( + config: M8StudyConfig, + period: M8Period, + metadata: M8SymbolMetadata, + acquired: AcquiredDailyArchive, + input_root: str | Path, + *, + output_root: str | Path | None = None, + before_member_open: Callable[[], None] | None = None, + batch_rows: int = _DEFAULT_BATCH_ROWS, +) -> M8NormalizedArchive: + """Stream one authenticated archive through DQ and partitioned Parquet. + + ``input_root`` is the immutable raw-evidence authority used for containment + checks. ``output_root`` may isolate normalized and DQ artifacts elsewhere; + omitting it preserves the legacy co-located layout. The function never + retains a full daily trade table. Archive parsing, incremental quality + validation, and Parquet writing are bounded by ``batch_rows``. Any + deterministic payload/continuity/DQ failure is exposed as + :class:`M8InsufficientDataError` so the producer can publish a terminal + failed-result bundle without selecting a replacement date. + """ + + if isinstance(batch_rows, bool) or not isinstance(batch_rows, int) or batch_rows < 1: + raise ValueError("batch_rows must be a positive integer") + raw_root = Path(input_root).resolve() + if not raw_root.is_dir(): + raise M8NormalizationError(f"stage-local M8 input root is missing: {raw_root}") + derived_root = raw_root if output_root is None else Path(output_root).resolve() + if derived_root.exists() and not derived_root.is_dir(): + raise M8NormalizationError( + f"stage-local M8 normalization output root is not a directory: {derived_root}" + ) + _validate_frozen_period(config, period) + if period.role in {"primary_test", "replication_test"} and before_member_open is None: + raise M8NormalizationError( + "held-out M8 archives require a lock-revalidation callback before member open" + ) + _validate_contract(config, period, metadata, acquired, raw_root) + symbol = metadata.symbol + study_date = period.date.isoformat() + base = derived_root / "normalized" / symbol / study_date + if base.exists(): + raise M8NormalizationError( + f"refusing to overwrite prior normalized evidence for {symbol}/{study_date}" + ) + quality_root = derived_root / "quality" / symbol / study_date + if quality_root.exists(): + raise M8NormalizationError( + f"refusing to overwrite prior quality evidence for {symbol}/{study_date}" + ) + quality_root.mkdir(parents=True, exist_ok=False) + findings_path = quality_root / "findings.jsonl" + report_path = quality_root / "report.json" + day_start = datetime(period.date.year, period.date.month, period.date.day, tzinfo=UTC) + day_start_ns = int(day_start.timestamp()) * 1_000_000_000 + day_end_ns = day_start_ns + 86_400 * 1_000_000_000 + stream = acquired.iter_normalized_batches( + batch_rows=batch_rows, + before_member_open=before_member_open, + ) + try: + with IncrementalQualityValidator( + "trades", + findings_jsonl_path=findings_path, + ) as validator: + + def validated_batches() -> Iterator[pa.RecordBatch]: + for batch in stream: + if batch.num_rows < 1 or batch.num_rows > batch_rows: + raise M8NormalizationError( + "archive stream violated its configured row bound" + ) + validator.update(batch) + yield batch + + storage = write_partitioned_parquet( + validated_batches(), + root=base, + dataset="trades", + schema_name="trades", + source=config.study.source, + source_uri=acquired.archive_artifact.source_uri, + downloaded_at_utc=_downloaded_at(acquired), + source_checksum_sha256=acquired.archive_artifact.sha256, + requested_start_ns=day_start_ns, + requested_end_ns=day_end_ns, + max_input_batch_rows=batch_rows, + max_rows_per_file=250_000, + ) + report = validator.finish() + summary = stream.summary + report.write_json(report_path) + except BinanceArchivePayloadError as exc: + stream.close() + raise M8InsufficientDataError( + symbol, + study_date, + str(exc), + failure_kind="PAYLOAD_OR_CONTINUITY", + evidence_completion="PARTIAL_STREAM", + ) from exc + except BaseException: + stream.close() + raise + + if summary.symbol != symbol or summary.date != study_date: + raise M8InsufficientDataError( + symbol, + study_date, + "archive summary identity disagrees", + failure_kind="POSTWRITE_CONSISTENCY", + evidence_completion="COMPLETE_DATASET_AND_QUALITY", + ) + if summary.source_archive_sha256 != acquired.archive_artifact.sha256: + raise M8InsufficientDataError( + symbol, + study_date, + "archive summary checksum disagrees", + failure_kind="POSTWRITE_CONSISTENCY", + evidence_completion="COMPLETE_DATASET_AND_QUALITY", + ) + if summary.expanded_bytes != acquired.declared_uncompressed_bytes: + raise M8InsufficientDataError( + symbol, + study_date, + "expanded byte count disagrees", + failure_kind="POSTWRITE_CONSISTENCY", + evidence_completion="COMPLETE_DATASET_AND_QUALITY", + ) + if storage.rows != summary.rows or report.rows_checked != summary.rows: + raise M8InsufficientDataError( + symbol, + study_date, + "stream/storage/DQ row counts disagree", + failure_kind="POSTWRITE_CONSISTENCY", + evidence_completion="COMPLETE_DATASET_AND_QUALITY", + ) + if summary.last_trade_id - summary.first_trade_id + 1 != summary.rows: + raise M8InsufficientDataError( + symbol, + study_date, + "aggregate trade IDs are noncontiguous", + failure_kind="POSTWRITE_CONSISTENCY", + evidence_completion="COMPLETE_DATASET_AND_QUALITY", + ) + normalized_parts = _parts(storage) + if not normalized_parts or sum(part.rows for part in normalized_parts) != summary.rows: + raise M8InsufficientDataError( + symbol, + study_date, + "normalized part accounting failed", + failure_kind="POSTWRITE_CONSISTENCY", + evidence_completion="COMPLETE_DATASET_AND_QUALITY", + ) + entry = M8ArchiveEntry( + symbol=symbol, + date=period.date, + role=period.role, + complete=True, + rows=summary.rows, + first_trade_id=summary.first_trade_id, + last_trade_id=summary.last_trade_id, + observed_start_ns=summary.first_event_ts_ns, + observed_end_inclusive_ns=summary.last_event_ts_ns, + tick_size=metadata.tick_size, + lot_size=metadata.lot_size, + raw_zip_path=acquired.archive_artifact.path.resolve(), + raw_zip_sha256=acquired.archive_artifact.sha256, + raw_zip_bytes=acquired.archive_artifact.bytes, + raw_uncompressed_bytes=summary.expanded_bytes, + raw_source_uri=acquired.archive_artifact.source_uri, + raw_source_manifest_path=acquired.archive_artifact.manifest_path.resolve(), + raw_source_manifest_sha256=acquired.archive_artifact.manifest_sha256, + raw_source_manifest_bytes=acquired.archive_artifact.manifest_path.stat().st_size, + raw_checksum_path=acquired.checksum_artifact.path.resolve(), + raw_checksum_sha256=acquired.checksum_artifact.sha256, + raw_checksum_bytes=acquired.checksum_artifact.bytes, + raw_checksum_source_uri=acquired.checksum_artifact.source_uri, + raw_checksum_source_manifest_path=acquired.checksum_artifact.manifest_path.resolve(), + raw_checksum_source_manifest_sha256=acquired.checksum_artifact.manifest_sha256, + raw_checksum_source_manifest_bytes=acquired.checksum_artifact.manifest_path.stat().st_size, + normalized_dataset_manifest_path=storage.manifest_path.resolve(), + normalized_dataset_manifest_sha256=storage.manifest_sha256, + normalized_dataset_manifest_bytes=storage.manifest_path.stat().st_size, + normalized_parts=normalized_parts, + quality_report_path=report_path.resolve(), + quality_report_sha256=sha256_file(report_path), + quality_report_bytes=report_path.stat().st_size, + quality_findings_path=findings_path.resolve(), + quality_findings_sha256=sha256_file(findings_path), + quality_findings_bytes=findings_path.stat().st_size, + quality_errors=report.error_count, + quality_warnings=report.warning_count, + ) + if report.error_count or (report.warning_count and not config.quality.allow_quality_warnings): + raise M8InsufficientDataError( + symbol, + study_date, + f"quality gate reported {report.error_count} errors and " + f"{report.warning_count} warnings", + failure_kind="QUALITY_GATE", + evidence_completion="COMPLETE_DATASET_AND_QUALITY", + completed_evidence=entry, + ) + return M8NormalizedArchive(entry=entry, output_root=derived_root) + + +__all__ = [ + "M8InsufficientDataError", + "M8NormalizationError", + "M8NormalizationEvidenceCompletion", + "M8NormalizationFailureKind", + "M8NormalizedArchive", + "normalize_m8_archive", +] diff --git a/Microstructure/src/microstructure/m8_pipeline.py b/Microstructure/src/microstructure/m8_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..c259985d72b1ee18787595d0f853743919c94894 --- /dev/null +++ b/Microstructure/src/microstructure/m8_pipeline.py @@ -0,0 +1,6166 @@ +"""Atomic producer for the frozen M8 multi-date trade-only study. + +The orchestration in this module is deliberately stricter than the exploratory +public-sample producer. It verifies one explicitly named, content-addressed +input manifest before reading normalized rows, builds every development date +for both instruments, persists a canonical selection lock, and only then opens +the primary and replication test dates. The resulting ``FULL_DATA`` label is +scoped to the eight complete trade archives; execution, fills, P&L, capacity, +and statistical-significance claims remain unavailable. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import re +import shutil +import stat +import tempfile +from collections.abc import Mapping, Sequence +from dataclasses import asdict, dataclass +from datetime import UTC, date, datetime +from pathlib import Path +from typing import Any, Literal, cast + +import numpy as np +import polars as pl +from numpy.typing import NDArray + +from microstructure.config import FeatureConfig, ModelConfig +from microstructure.m8_acquisition import ( + M8AcquisitionError, + M8AcquisitionManifest, + M8RawSymbolMetadata, + copy_m8_acquisition_into, + read_m8_acquisition_manifest, +) +from microstructure.m8_config import M8PeriodRole, M8StudyConfig +from microstructure.m8_manifest import ( + M8ArchiveEntry, + M8InputManifest, + M8ManifestError, + M8SymbolMetadata, + verify_m8_input_manifest, + write_m8_input_manifest, +) +from microstructure.m8_normalization import ( + M8InsufficientDataError, + M8NormalizationEvidenceCompletion, + M8NormalizationFailureKind, + normalize_m8_archive, +) +from microstructure.provenance import ( + git_source_tree_sha256, + git_state, + runtime_metadata, + sha256_file, + utc_now_iso, + write_json, +) +from microstructure.reporting import ( + load_run_bundle, + render_executive_memo, + render_model_comparison_report, + render_technical_report, + verify_checksums, + write_checksum_manifest, +) +from microstructure.research.analysis import DescriptiveAnalysisError, feature_stability_summary +from microstructure.research.features import ResearchDataError, TemporalLeakageError +from microstructure.research.models import ModelEvaluationError, classification_metrics +from microstructure.research.multidate import ( + AnalysisLock, + FinalFittedState, + LockedMultiDateTestResult, + LockedSelection, + MultiDateEvaluationError, + evaluate_locked_multidate_tests, + select_multidate_model, +) +from microstructure.research.trade_only import ( + build_trade_only_research_frame, + validate_trade_only_temporal_contract, +) + +M8_PIPELINE_SCHEMA_VERSION = "1.0.0" +M8_EVIDENCE_TIER = "FULL_DATA" +M8_EVIDENCE_SCOPE = "trade_only_complete_predeclared_daily_archives" +M8_EXECUTION_EXCLUSION_REASON = ( + "NOT_RUN: aggregate-trade archives contain no contemporaneous bid/ask, depth, " + "cancellation, queue, or local receipt-time state. Execution, fills, fees-to-alpha " + "conversion, P&L, capacity, and profitability are outside this trade-only study." +) +M8_NO_SIGNIFICANCE_CAVEAT = ( + "The seeded paired block intervals are descriptive dependence diagnostics. No p-values " + "are computed, H0 is not rejected, and no statistical-significance claim is authorized." +) +M8_NO_POOLING_CAVEAT = ( + "BTCUSDT and ETHUSDT are evaluated and reported separately; no cross-instrument pooling " + "or persistent-alpha conclusion is authorized." +) + +_DIGEST = re.compile(r"^[0-9a-f]{64}$") +_ANALYSIS_LOCK_SCHEMA_VERSION = "m8-analysis-lock-v2" +_MAX_LOCK_JSON_BYTES = 8 * 1024 * 1024 +_MAX_LOCK_DIGEST_BYTES = 512 +_MAX_FAILURE_INVENTORY_BYTES = 16 * 1024 * 1024 +_MAX_FAILURE_INVENTORY_ENTRIES = 50_000 +_MAX_FAILURE_FINDING_LINE_BYTES = 1024 * 1024 +_LOCK_READ_CHUNK_BYTES = 64 * 1024 +_DEVELOPMENT_ROLES = frozenset({"train", "validation"}) +_TEST_ROLES = frozenset({"primary_test", "replication_test"}) +_TRADE_COLUMNS = ( + "symbol", + "continuity_id", + "trade_id", + "event_ts_ns", + "received_ts_ns", + "available_ts_ns", + "availability_basis", + "price", + "quantity", + "aggressor_side", +) + + +class M8PipelineError(RuntimeError): + """Raised when an M8 run cannot be produced without violating its protocol.""" + + +M8RunStatus = Literal["COMPLETE", "INSUFFICIENT_DATA"] + +_M8FailureReasonCode = Literal[ + "RAW_ARCHIVE_INTEGRITY", + "ARCHIVE_PAYLOAD_OR_CONTINUITY", + "ARCHIVE_QUALITY_GATE", + "ARCHIVE_POSTWRITE_CONSISTENCY", + "RESEARCH_FRAME_INSUFFICIENT", + "MODEL_SELECTION_INSUFFICIENT", + "FINAL_NORMALIZED_MANIFEST_INCOMPLETE", + "LOCKED_EVALUATION_INSUFFICIENT", +] +_M8FailureStage = Literal[ + "development_acquisition", + "development_normalization", + "development_research", + "model_selection", + "held_out_acquisition", + "held_out_normalization", + "final_manifest", + "held_out_research", + "locked_evaluation", +] +_M8FailedRole = Literal[ + "train", + "validation", + "primary_test", + "replication_test", + "study", + "all_test_dates", +] + +_NORMALIZATION_REASON_CODES = frozenset( + { + "ARCHIVE_PAYLOAD_OR_CONTINUITY", + "ARCHIVE_QUALITY_GATE", + "ARCHIVE_POSTWRITE_CONSISTENCY", + } +) +_FAILURE_STAGE_CONTRACT: Mapping[str, tuple[bool, frozenset[str], frozenset[str]]] = { + "development_acquisition": ( + False, + frozenset({"RAW_ARCHIVE_INTEGRITY"}), + _DEVELOPMENT_ROLES, + ), + "development_normalization": ( + False, + _NORMALIZATION_REASON_CODES, + _DEVELOPMENT_ROLES, + ), + "development_research": ( + False, + frozenset({"RESEARCH_FRAME_INSUFFICIENT"}), + _DEVELOPMENT_ROLES, + ), + "model_selection": ( + False, + frozenset({"MODEL_SELECTION_INSUFFICIENT"}), + frozenset({"validation"}), + ), + "held_out_acquisition": ( + True, + frozenset({"RAW_ARCHIVE_INTEGRITY"}), + _TEST_ROLES, + ), + "held_out_normalization": (True, _NORMALIZATION_REASON_CODES, _TEST_ROLES), + "final_manifest": ( + True, + frozenset({"FINAL_NORMALIZED_MANIFEST_INCOMPLETE"}), + frozenset({"study"}), + ), + "held_out_research": ( + True, + frozenset({"RESEARCH_FRAME_INSUFFICIENT"}), + _TEST_ROLES, + ), + "locked_evaluation": ( + True, + frozenset({"LOCKED_EVALUATION_INSUFFICIENT"}), + frozenset({"all_test_dates"}), + ), +} + + +@dataclass(frozen=True, slots=True) +class M8RunResult: + """Verified terminal result of one immutable M8 production attempt.""" + + path: Path + status: M8RunStatus + raw_manifest_sha256: str + normalized_manifest_sha256: str | None + + def __fspath__(self) -> str: + return str(self.path) + + +@dataclass(frozen=True, slots=True) +class _TypedInsufficientFailure: + """Stable machine-readable classification plus diagnostic failure text.""" + + symbol: str + study_date: str + reason: str + reason_code: _M8FailureReasonCode + failure_stage: _M8FailureStage + failed_role: _M8FailedRole + normalization_failure_kind: M8NormalizationFailureKind | None = None + normalization_evidence_completion: M8NormalizationEvidenceCompletion | None = None + normalization_completed_evidence: M8ArchiveEntry | None = None + + +@dataclass(frozen=True, slots=True) +class _FailureEvidenceItem: + """One canonical, checksum-bound entry in a failed run's evidence inventory.""" + + path: str + sha256: str + bytes: int + + +def _typed_failure( + error: M8InsufficientDataError, + *, + reason_code: _M8FailureReasonCode | None = None, + failure_stage: _M8FailureStage, + failed_role: _M8FailedRole, +) -> _TypedInsufficientFailure: + """Attach an explicit protocol classification without parsing diagnostic text.""" + + normalization_stage = failure_stage in { + "development_normalization", + "held_out_normalization", + } + normalization_kind = error.failure_kind + evidence_completion = error.evidence_completion + completed_evidence = error.completed_evidence + if normalization_stage: + mapping: Mapping[M8NormalizationFailureKind, _M8FailureReasonCode] = { + "PAYLOAD_OR_CONTINUITY": "ARCHIVE_PAYLOAD_OR_CONTINUITY", + "QUALITY_GATE": "ARCHIVE_QUALITY_GATE", + "POSTWRITE_CONSISTENCY": "ARCHIVE_POSTWRITE_CONSISTENCY", + } + if normalization_kind is None or evidence_completion is None: + raise M8PipelineError("normalization failure lacks its typed evidence state") + derived_reason = mapping[normalization_kind] + if reason_code is not None and reason_code != derived_reason: + raise M8PipelineError("normalization failure reason code was not derived from its type") + reason_code = derived_reason + if normalization_kind == "PAYLOAD_OR_CONTINUITY" and ( + evidence_completion != "PARTIAL_STREAM" or completed_evidence is not None + ): + raise M8PipelineError("payload failure has an invalid evidence-completion state") + if normalization_kind == "QUALITY_GATE" and ( + evidence_completion != "COMPLETE_DATASET_AND_QUALITY" or completed_evidence is None + ): + raise M8PipelineError("quality-gate failure lacks complete normalization evidence") + if normalization_kind == "POSTWRITE_CONSISTENCY" and ( + evidence_completion != "COMPLETE_DATASET_AND_QUALITY" or completed_evidence is not None + ): + raise M8PipelineError("postwrite failure has an invalid evidence-completion state") + elif ( + reason_code is None + or normalization_kind is not None + or evidence_completion is not None + or completed_evidence is not None + ): + raise M8PipelineError("non-normalization failure has invalid typed evidence metadata") + + return _TypedInsufficientFailure( + symbol=error.symbol, + study_date=error.study_date, + reason=error.reason, + reason_code=reason_code, + failure_stage=failure_stage, + failed_role=failed_role, + normalization_failure_kind=normalization_kind, + normalization_evidence_completion=evidence_completion, + normalization_completed_evidence=completed_evidence, + ) + + +@dataclass(frozen=True, slots=True) +class _SourceIdentity: + commit: str + dirty: bool + source_tree_sha256: str + + def public_dict(self) -> dict[str, object]: + return { + "commit": self.commit, + "dirty": self.dirty, + "source_tree_sha256": self.source_tree_sha256, + } + + +@dataclass(frozen=True, slots=True) +class _DateArtifacts: + symbol: str + study_date: str + role: M8PeriodRole + research_path: Path + evaluation_path: Path + summary: Mapping[str, object] + + +@dataclass(frozen=True, slots=True) +class _SelectionArtifacts: + symbol: str + selection: LockedSelection + lock_path: Path + fitted_state_path: Path + comparison_path: Path + + +@dataclass(frozen=True, slots=True) +class _EvaluationArtifacts: + symbol: str + selected_model: str + predictions_path: Path + paired_date_path: Path + stability_path: Path + plan_path: Path + predictive_rows: tuple[Mapping[str, object], ...] + paired_date_rows: tuple[Mapping[str, object], ...] + aggregate_row: Mapping[str, object] + + +@dataclass(frozen=True, slots=True) +class _BoundedFileSnapshot: + """One regular-file byte snapshot read and hashed through a single descriptor.""" + + content: bytes + sha256: str + + +@dataclass(frozen=True, slots=True) +class _BoundedJsonSnapshot: + """Strict canonical JSON decoded from one hash-bound file snapshot.""" + + content: bytes + text: str + payload: Mapping[str, Any] + sha256: str + + +def _json_safe(value: Any) -> Any: + if isinstance(value, np.generic): + return _json_safe(value.item()) + if isinstance(value, float) and not math.isfinite(value): + return None + if isinstance(value, Path): + return str(value) + if isinstance(value, Mapping): + return {str(key): _json_safe(item) for key, item in value.items()} + if isinstance(value, (list, tuple)): + return [_json_safe(item) for item in value] + return value + + +def _write_json(path: Path, payload: Mapping[str, Any] | list[Any]) -> None: + clean = _json_safe(payload) + if not isinstance(clean, (dict, list)): + raise TypeError("JSON artifact payload must be an object or list") + write_json(path, clean) + + +def _canonical_json_bytes(payload: Mapping[str, Any]) -> bytes: + return json.dumps( + _json_safe(payload), + sort_keys=True, + separators=(",", ":"), + allow_nan=False, + ensure_ascii=False, + ).encode("utf-8") + + +def _stable_sha256(payload: Mapping[str, Any]) -> str: + return hashlib.sha256(_canonical_json_bytes(payload)).hexdigest() + + +def _fsync_directory(path: Path) -> None: + """Durably commit directory-entry changes on POSIX filesystems.""" + + descriptor = os.open(path, os.O_RDONLY) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + + +def _fsync_tree(root: Path) -> None: + """Flush every regular artifact and directory without following symbolic links.""" + + resolved_root = root.resolve() + if root.is_symlink() or not resolved_root.is_dir(): + raise M8PipelineError("M8 staging tree is not a real directory") + nofollow = getattr(os, "O_NOFOLLOW", 0) + for directory_name, directory_names, file_names in os.walk( + resolved_root, + topdown=False, + followlinks=False, + ): + directory = Path(directory_name) + for child_name in directory_names: + child = directory / child_name + if child.is_symlink(): + raise M8PipelineError(f"M8 staging tree contains a symlink: {child}") + for file_name in file_names: + path = directory / file_name + if path.is_symlink(): + raise M8PipelineError(f"M8 staging tree contains a symlink: {path}") + if not stat.S_ISREG(path.lstat().st_mode): + raise M8PipelineError(f"M8 staging artifact is not a regular file: {path}") + descriptor = os.open(path, os.O_RDONLY | nofollow) + try: + if not stat.S_ISREG(os.fstat(descriptor).st_mode): + raise M8PipelineError(f"M8 staging artifact is not a regular file: {path}") + os.fsync(descriptor) + finally: + os.close(descriptor) + _fsync_directory(directory) + + +def _create_terminal_marker(path: Path, content: str) -> None: + """Create, flush, and durably link a terminal marker exactly once.""" + + descriptor = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644) + with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as handle: + handle.write(content.rstrip("\n") + "\n") + handle.flush() + os.fsync(handle.fileno()) + _fsync_directory(path.parent) + + +def _atomic_write_bytes(path: Path, content: bytes) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary_name = tempfile.mkstemp( + dir=path.parent, + prefix=f".{path.name}.", + suffix=".tmp", + ) + temporary = Path(temporary_name) + try: + with os.fdopen(descriptor, "wb") as handle: + handle.write(content) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, path) + _fsync_directory(path.parent) + except BaseException: + temporary.unlink(missing_ok=True) + raise + + +def _atomic_write_text(path: Path, content: str, *, trailing_newline: bool = True) -> None: + encoded = (content.rstrip("\n") + "\n" if trailing_newline else content).encode("utf-8") + _atomic_write_bytes(path, encoded) + + +def _require_digest(value: str, label: str) -> str: + if value != value.lower() or _DIGEST.fullmatch(value) is None: + raise M8PipelineError(f"{label} must be an exact lowercase SHA-256 digest") + return value + + +def _read_bounded_regular_snapshot( + path: Path, + *, + label: str, + max_bytes: int, + expected_sha256: str | None = None, +) -> _BoundedFileSnapshot: + """Read, bound, and hash one non-symlink regular file through the same FD.""" + + if isinstance(max_bytes, bool) or not isinstance(max_bytes, int) or max_bytes < 1: + raise ValueError("bounded snapshot size must be a positive integer") + expected = ( + None if expected_sha256 is None else _require_digest(expected_sha256, f"{label} SHA-256") + ) + nofollow = getattr(os, "O_NOFOLLOW", None) + if nofollow is None: + raise M8PipelineError(f"{label} cannot be opened without O_NOFOLLOW support") + flags = os.O_RDONLY | nofollow | getattr(os, "O_CLOEXEC", 0) + try: + descriptor = os.open(path, flags) + except OSError as exc: + raise M8PipelineError(f"cannot open {label} as a non-symlink regular file") from exc + try: + before = os.fstat(descriptor) + if not stat.S_ISREG(before.st_mode): + raise M8PipelineError(f"{label} is not a regular file") + if before.st_size < 0 or before.st_size > max_bytes: + raise M8PipelineError(f"{label} exceeds its {max_bytes}-byte hard limit") + chunks: list[bytes] = [] + observed_bytes = 0 + while True: + chunk = os.read( + descriptor, + min(_LOCK_READ_CHUNK_BYTES, max_bytes + 1 - observed_bytes), + ) + if not chunk: + break + chunks.append(chunk) + observed_bytes += len(chunk) + if observed_bytes > max_bytes: + raise M8PipelineError(f"{label} exceeds its {max_bytes}-byte hard limit") + after = os.fstat(descriptor) + identity_before = ( + before.st_dev, + before.st_ino, + before.st_mode, + before.st_size, + before.st_mtime_ns, + before.st_ctime_ns, + ) + identity_after = ( + after.st_dev, + after.st_ino, + after.st_mode, + after.st_size, + after.st_mtime_ns, + after.st_ctime_ns, + ) + if identity_after != identity_before or observed_bytes != before.st_size: + raise M8PipelineError(f"{label} changed while its bounded snapshot was read") + try: + linked = os.stat(path, follow_symlinks=False) + except OSError as exc: + raise M8PipelineError(f"{label} path changed while its snapshot was read") from exc + if ( + not stat.S_ISREG(linked.st_mode) + or linked.st_dev != before.st_dev + or linked.st_ino != before.st_ino + ): + raise M8PipelineError(f"{label} path changed identity while its snapshot was read") + content = b"".join(chunks) + observed_sha256 = hashlib.sha256(content).hexdigest() + if expected is not None and observed_sha256 != expected: + raise M8PipelineError(f"{label} bytes do not match the expected SHA-256") + return _BoundedFileSnapshot(content=content, sha256=observed_sha256) + finally: + os.close(descriptor) + + +def _strict_canonical_json_snapshot( + snapshot: _BoundedFileSnapshot, + *, + label: str, + ensure_ascii: bool, +) -> _BoundedJsonSnapshot: + """Decode canonical JSON while rejecting duplicate keys and non-finite constants.""" + + try: + text = snapshot.content.decode("utf-8") + except UnicodeDecodeError as exc: + raise M8PipelineError(f"{label} is not valid UTF-8") from exc + + def reject_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + raise M8PipelineError(f"{label} repeats JSON key {key!r}") + result[key] = value + return result + + def reject_constant(value: str) -> object: + raise M8PipelineError(f"{label} contains forbidden JSON constant {value}") + + try: + decoded = json.loads( + text, + object_pairs_hook=reject_duplicates, + parse_constant=reject_constant, + ) + except M8PipelineError: + raise + except (RecursionError, TypeError, ValueError) as exc: + raise M8PipelineError(f"{label} is not valid JSON") from exc + if not isinstance(decoded, Mapping): + raise M8PipelineError(f"{label} must be a JSON object") + payload = cast(Mapping[str, Any], decoded) + try: + canonical = json.dumps( + payload, + sort_keys=True, + separators=(",", ":"), + allow_nan=False, + ensure_ascii=ensure_ascii, + ).encode("utf-8") + except (RecursionError, TypeError, ValueError) as exc: + raise M8PipelineError(f"{label} cannot be represented as canonical JSON") from exc + if snapshot.content != canonical: + raise M8PipelineError(f"{label} bytes are not canonical JSON") + return _BoundedJsonSnapshot( + content=snapshot.content, + text=text, + payload=payload, + sha256=snapshot.sha256, + ) + + +def _read_bounded_json_snapshot( + path: Path, + *, + label: str, + expected_sha256: str, + ensure_ascii: bool, +) -> _BoundedJsonSnapshot: + return _strict_canonical_json_snapshot( + _read_bounded_regular_snapshot( + path, + label=label, + max_bytes=_MAX_LOCK_JSON_BYTES, + expected_sha256=expected_sha256, + ), + label=label, + ensure_ascii=ensure_ascii, + ) + + +def _read_exact_bounded_text(path: Path, *, label: str, expected_text: str) -> None: + snapshot = _read_bounded_regular_snapshot( + path, + label=label, + max_bytes=_MAX_LOCK_DIGEST_BYTES, + ) + try: + observed = snapshot.content.decode("utf-8") + except UnicodeDecodeError as exc: + raise M8PipelineError(f"{label} is not valid UTF-8") from exc + if observed != expected_text: + raise M8PipelineError(f"{label} bytes are invalid") + + +def _restore_analysis_lock_file( + path: Path, + expected_sha256: str, + label: str, +) -> AnalysisLock: + digest = _require_digest(expected_sha256, f"{label} SHA-256") + snapshot = _read_bounded_json_snapshot( + path, + label=label, + expected_sha256=digest, + ensure_ascii=True, + ) + try: + lock = AnalysisLock.restore(snapshot.text, digest) + if lock.payload() != snapshot.payload: + raise M8PipelineError(f"{label} decoded inconsistently") + except (MultiDateEvaluationError, ValueError) as exc: + raise M8PipelineError(f"{label} is invalid") from exc + return lock + + +def _relative(path: Path, root: Path) -> str: + try: + return path.resolve().relative_to(root.resolve()).as_posix() + except ValueError as exc: + raise M8PipelineError(f"run artifact escapes the staging directory: {path}") from exc + + +def _published_file(root: Path, value: object, label: str) -> Path: + """Resolve one canonical bundle-relative regular file without following aliases.""" + + if type(value) is not str: + raise M8PipelineError(f"{label} must be a bundle-relative path") + declared = Path(value) + if ( + declared.is_absolute() + or "\\" in value + or value != declared.as_posix() + or not declared.parts + or any(part in {"", ".", ".."} for part in declared.parts) + ): + raise M8PipelineError(f"{label} is not a canonical bundle-relative path") + current = root.resolve() + for component in declared.parts: + current /= component + if current.is_symlink(): + raise M8PipelineError(f"{label} traverses a symbolic link") + resolved = current.resolve() + if not resolved.is_relative_to(root.resolve()) or not resolved.is_file(): + raise M8PipelineError(f"{label} is missing or escapes the completed bundle") + return resolved + + +def _read_json_object(path: Path, label: str) -> Mapping[str, Any]: + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError, ValueError) as exc: + raise M8PipelineError(f"cannot read {label} as JSON") from exc + if not isinstance(payload, Mapping): + raise M8PipelineError(f"{label} must be a JSON object") + return cast(Mapping[str, Any], payload) + + +def _decode_failure_inventory(snapshot: _BoundedFileSnapshot) -> list[Any]: + """Decode the stable JSON-list representation used by failed evidence inventories.""" + + label = "INSUFFICIENT_DATA failure evidence inventory" + try: + text = snapshot.content.decode("utf-8") + except UnicodeDecodeError as exc: + raise M8PipelineError(f"{label} is not valid UTF-8") from exc + + def reject_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + raise M8PipelineError(f"{label} repeats JSON key {key!r}") + result[key] = value + return result + + def reject_constant(value: str) -> object: + raise M8PipelineError(f"{label} contains forbidden JSON constant {value}") + + try: + decoded = json.loads( + text, + object_pairs_hook=reject_duplicates, + parse_constant=reject_constant, + ) + except M8PipelineError: + raise + except (RecursionError, TypeError, ValueError) as exc: + raise M8PipelineError(f"{label} is not valid JSON") from exc + if not isinstance(decoded, list): + raise M8PipelineError(f"{label} must be a JSON array") + try: + stable = (json.dumps(decoded, indent=2, sort_keys=True, allow_nan=False) + "\n").encode( + "utf-8" + ) + except (RecursionError, TypeError, ValueError) as exc: + raise M8PipelineError(f"{label} is not stable JSON") from exc + if snapshot.content != stable: + raise M8PipelineError(f"{label} is not stable canonical JSON") + return decoded + + +def _decode_stable_pretty_json_object( + snapshot: _BoundedFileSnapshot, + *, + label: str, +) -> Mapping[str, Any]: + """Decode the pretty canonical JSON used by terminal and storage records.""" + + try: + text = snapshot.content.decode("utf-8") + except UnicodeDecodeError as exc: + raise M8PipelineError(f"{label} is not valid UTF-8") from exc + + def reject_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + raise M8PipelineError(f"{label} repeats JSON key {key!r}") + result[key] = value + return result + + def reject_constant(value: str) -> object: + raise M8PipelineError(f"{label} contains forbidden JSON constant {value}") + + try: + decoded = json.loads( + text, + object_pairs_hook=reject_duplicates, + parse_constant=reject_constant, + ) + except M8PipelineError: + raise + except (RecursionError, TypeError, ValueError) as exc: + raise M8PipelineError(f"{label} is not valid JSON") from exc + if not isinstance(decoded, Mapping): + raise M8PipelineError(f"{label} must be a JSON object") + try: + stable = (json.dumps(decoded, indent=2, sort_keys=True, allow_nan=False) + "\n").encode( + "utf-8" + ) + except (RecursionError, TypeError, ValueError) as exc: + raise M8PipelineError(f"{label} is not stable JSON") from exc + if snapshot.content != stable: + raise M8PipelineError(f"{label} is not stable canonical JSON") + return cast(Mapping[str, Any], decoded) + + +def _verify_inventory_file( + root: Path, + item: _FailureEvidenceItem, +) -> None: + """Hash one inventoried file through a stable non-following descriptor.""" + + label = f"failure evidence inventory artifact {item.path}" + path = _published_file(root, item.path, label) + nofollow = getattr(os, "O_NOFOLLOW", None) + if nofollow is None: + raise M8PipelineError(f"{label} cannot be opened without O_NOFOLLOW support") + try: + descriptor = os.open(path, os.O_RDONLY | nofollow | getattr(os, "O_CLOEXEC", 0)) + except OSError as exc: + raise M8PipelineError(f"cannot open {label} as a regular file") from exc + try: + before = os.fstat(descriptor) + if not stat.S_ISREG(before.st_mode): + raise M8PipelineError(f"{label} is not a regular file") + if before.st_size != item.bytes: + raise M8PipelineError(f"{label} byte count disagrees with its inventory claim") + digest = hashlib.sha256() + observed_bytes = 0 + while chunk := os.read(descriptor, _LOCK_READ_CHUNK_BYTES): + digest.update(chunk) + observed_bytes += len(chunk) + after = os.fstat(descriptor) + identity_before = ( + before.st_dev, + before.st_ino, + before.st_mode, + before.st_size, + before.st_mtime_ns, + before.st_ctime_ns, + ) + identity_after = ( + after.st_dev, + after.st_ino, + after.st_mode, + after.st_size, + after.st_mtime_ns, + after.st_ctime_ns, + ) + if identity_after != identity_before or observed_bytes != item.bytes: + raise M8PipelineError(f"{label} changed while it was verified") + try: + linked = os.stat(path, follow_symlinks=False) + except OSError as exc: + raise M8PipelineError(f"{label} path changed while it was verified") from exc + if ( + not stat.S_ISREG(linked.st_mode) + or linked.st_dev != before.st_dev + or linked.st_ino != before.st_ino + ): + raise M8PipelineError(f"{label} path changed identity while it was verified") + if digest.hexdigest() != item.sha256: + raise M8PipelineError(f"{label} SHA-256 disagrees with its inventory claim") + finally: + os.close(descriptor) + + +def _verify_failure_evidence_inventory( + target: Path, +) -> dict[str, _FailureEvidenceItem]: + """Verify a failed bundle's pre-terminal inventory against its exact physical tree.""" + + inventory_relative = "data/failure_evidence_inventory.json" + inventory_path = _published_file( + target, + inventory_relative, + "INSUFFICIENT_DATA failure evidence inventory", + ) + snapshot = _read_bounded_regular_snapshot( + inventory_path, + label="INSUFFICIENT_DATA failure evidence inventory", + max_bytes=_MAX_FAILURE_INVENTORY_BYTES, + ) + raw_entries = _decode_failure_inventory(snapshot) + if not raw_entries or len(raw_entries) > _MAX_FAILURE_INVENTORY_ENTRIES: + raise M8PipelineError( + "INSUFFICIENT_DATA failure evidence inventory has an invalid entry count" + ) + + entries: list[_FailureEvidenceItem] = [] + for index, raw_entry in enumerate(raw_entries): + label = f"failure evidence inventory[{index}]" + if not isinstance(raw_entry, Mapping) or set(raw_entry) != {"path", "sha256", "bytes"}: + raise M8PipelineError(f"{label} has an invalid schema") + path_value = raw_entry.get("path") + if type(path_value) is not str: + raise M8PipelineError(f"{label}.path must be a canonical bundle-relative path") + declared = Path(path_value) + if ( + declared.is_absolute() + or "\\" in path_value + or path_value != declared.as_posix() + or not declared.parts + or any(part in {"", ".", ".."} for part in declared.parts) + ): + raise M8PipelineError(f"{label}.path is not a canonical bundle-relative path") + sha_value = raw_entry.get("sha256") + if type(sha_value) is not str: + raise M8PipelineError(f"{label}.sha256 must be one lowercase SHA-256") + digest = _require_digest(sha_value, f"{label}.sha256") + byte_value = raw_entry.get("bytes") + if isinstance(byte_value, bool) or not isinstance(byte_value, int) or byte_value < 0: + raise M8PipelineError(f"{label}.bytes must be a non-negative integer") + entries.append(_FailureEvidenceItem(path=path_value, sha256=digest, bytes=byte_value)) + + paths = [item.path for item in entries] + if paths != sorted(paths) or len(paths) != len(set(paths)): + raise M8PipelineError( + "INSUFFICIENT_DATA failure evidence inventory paths are duplicate or unordered" + ) + + actual_files: set[str] = set() + try: + for path in target.rglob("*"): + mode = path.lstat().st_mode + if stat.S_ISLNK(mode): + raise M8PipelineError( + "INSUFFICIENT_DATA bundle contains a symbolic link outside its inventory" + ) + if stat.S_ISDIR(mode): + continue + if not stat.S_ISREG(mode): + raise M8PipelineError( + "INSUFFICIENT_DATA bundle contains a non-regular inventory artifact" + ) + actual_files.add(path.relative_to(target).as_posix()) + except OSError as exc: + raise M8PipelineError("cannot enumerate INSUFFICIENT_DATA evidence inventory") from exc + + terminal_exclusions = { + inventory_relative, + "checksums.sha256", + "INSUFFICIENT_DATA", + } + if not terminal_exclusions.issubset(actual_files): + raise M8PipelineError( + "INSUFFICIENT_DATA evidence inventory is missing a terminal publication artifact" + ) + inventoried_paths = set(paths) + observed_scope = actual_files - terminal_exclusions + missing = sorted(observed_scope - inventoried_paths) + extra = sorted(inventoried_paths - observed_scope) + if missing or extra: + raise M8PipelineError( + "INSUFFICIENT_DATA failure evidence inventory differs from the physical bundle: " + f"missing={missing}, extra={extra}" + ) + + by_path = {item.path: item for item in entries} + for item in entries: + _verify_inventory_file(target, item) + return by_path + + +def _canonical_inventory_child(value: object, label: str) -> str: + if type(value) is not str: + raise M8PipelineError(f"{label} must be a canonical relative path") + declared = Path(value) + if ( + declared.is_absolute() + or "\\" in value + or value != declared.as_posix() + or not declared.parts + or any(part in {"", ".", ".."} for part in declared.parts) + ): + raise M8PipelineError(f"{label} is not a canonical relative path") + return value + + +def _expected_completed_normalizations( + config: M8StudyConfig, + failure: Mapping[str, Any], +) -> list[tuple[str, str, str]]: + declared: list[tuple[str, str, str]] = [ + (symbol, period.date.isoformat(), period.role) + for period in config.periods + for symbol in config.study.symbols + ] + stage = failure.get("failure_stage") + if stage == "model_selection": + return [item for item in declared if item[2] in _DEVELOPMENT_ROLES] + if stage in {"final_manifest", "held_out_research", "locked_evaluation"}: + return declared + failed = ( + failure.get("failed_symbol"), + failure.get("failed_date"), + failure.get("failed_role"), + ) + try: + failed_index = declared.index(cast(tuple[str, str, str], failed)) + except ValueError as exc: + raise M8PipelineError( + "INSUFFICIENT_DATA completed normalization progress has no declared failure boundary" + ) from exc + if stage == "development_research": + return declared[: failed_index + 1] + if stage in { + "development_acquisition", + "development_normalization", + "held_out_acquisition", + "held_out_normalization", + }: + return declared[:failed_index] + raise M8PipelineError( + "INSUFFICIENT_DATA completed normalization progress has an unsupported failure stage" + ) + + +def _require_inventory_claim( + inventory: Mapping[str, _FailureEvidenceItem], + path: str, + label: str, + *, + sha256: str | None = None, + expected_bytes: int | None = None, +) -> _FailureEvidenceItem: + item = inventory.get(path) + if item is None: + raise M8PipelineError(f"{label} is absent from the failure evidence inventory") + if sha256 is not None and item.sha256 != sha256: + raise M8PipelineError(f"{label} SHA-256 differs from the failure evidence inventory") + if expected_bytes is not None and item.bytes != expected_bytes: + raise M8PipelineError(f"{label} byte count differs from the failure evidence inventory") + return item + + +def _read_inventory_bounded_snapshot( + *, + target: Path, + inventory: Mapping[str, _FailureEvidenceItem], + relative_path: str, + label: str, + max_bytes: int, + expected_sha256: str | None = None, +) -> _BoundedFileSnapshot: + """Read exactly the bytes already claimed by a verified failure inventory.""" + + item = _require_inventory_claim( + inventory, + relative_path, + label, + sha256=expected_sha256, + ) + if item.bytes < 1 or item.bytes > max_bytes: + raise M8PipelineError(f"{label} exceeds its {max_bytes}-byte hard limit") + snapshot = _read_bounded_regular_snapshot( + _published_file(target, relative_path, label), + label=label, + max_bytes=max_bytes, + expected_sha256=item.sha256, + ) + if len(snapshot.content) != item.bytes: + raise M8PipelineError(f"{label} byte count differs from the failure inventory") + return snapshot + + +def _read_inventory_bounded_json_snapshot( + *, + target: Path, + inventory: Mapping[str, _FailureEvidenceItem], + relative_path: str, + label: str, + expected_sha256: str, + ensure_ascii: bool, +) -> _BoundedJsonSnapshot: + """Decode canonical JSON from the same FD-bound bytes named by inventory.""" + + return _strict_canonical_json_snapshot( + _read_inventory_bounded_snapshot( + target=target, + inventory=inventory, + relative_path=relative_path, + label=label, + max_bytes=_MAX_LOCK_JSON_BYTES, + expected_sha256=expected_sha256, + ), + label=label, + ensure_ascii=ensure_ascii, + ) + + +def _read_inventory_exact_bounded_text( + *, + target: Path, + inventory: Mapping[str, _FailureEvidenceItem], + relative_path: str, + label: str, + expected_text: str, +) -> None: + snapshot = _read_inventory_bounded_snapshot( + target=target, + inventory=inventory, + relative_path=relative_path, + label=label, + max_bytes=_MAX_LOCK_DIGEST_BYTES, + ) + try: + observed = snapshot.content.decode("utf-8") + except UnicodeDecodeError as exc: + raise M8PipelineError(f"{label} is not valid UTF-8") from exc + if observed != expected_text: + raise M8PipelineError(f"{label} bytes are invalid") + + +def _read_inventory_json_object( + *, + target: Path, + inventory: Mapping[str, _FailureEvidenceItem], + relative_path: str, + label: str, + max_bytes: int = _MAX_LOCK_JSON_BYTES, +) -> Mapping[str, Any]: + """Read one semantic JSON record from the same bounded bytes bound by inventory.""" + + item = _require_inventory_claim(inventory, relative_path, label) + if item.bytes < 1 or item.bytes > max_bytes: + raise M8PipelineError(f"{label} exceeds its JSON byte limit") + snapshot = _read_bounded_regular_snapshot( + _published_file(target, relative_path, label), + label=label, + max_bytes=max_bytes, + expected_sha256=item.sha256, + ) + if len(snapshot.content) != item.bytes: + raise M8PipelineError(f"{label} byte count differs from the failure inventory") + return _decode_stable_pretty_json_object(snapshot, label=label) + + +def _verify_quality_findings_jsonl( + *, + target: Path, + item: _FailureEvidenceItem, + expected_errors: int, + expected_warnings: int, + label: str, +) -> None: + """Stream and count one inventory-bound findings file without retaining it.""" + + path = _published_file(target, item.path, label) + nofollow = getattr(os, "O_NOFOLLOW", None) + if nofollow is None: + raise M8PipelineError(f"{label} cannot be opened without O_NOFOLLOW support") + try: + descriptor = os.open(path, os.O_RDONLY | nofollow | getattr(os, "O_CLOEXEC", 0)) + except OSError as exc: + raise M8PipelineError(f"cannot open {label} as a regular file") from exc + digest = hashlib.sha256() + observed_bytes = 0 + buffered = b"" + errors = 0 + warnings = 0 + + def parse_line(line: bytes) -> str: + if not line or len(line) > _MAX_FAILURE_FINDING_LINE_BYTES: + raise M8PipelineError(f"{label} contains an empty or oversized JSON line") + + def reject_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + raise M8PipelineError(f"{label} repeats JSON key {key!r}") + result[key] = value + return result + + def reject_constant(value: str) -> object: + raise M8PipelineError(f"{label} contains forbidden JSON constant {value}") + + try: + decoded = json.loads( + line.decode("utf-8"), + object_pairs_hook=reject_duplicates, + parse_constant=reject_constant, + ) + except M8PipelineError: + raise + except (RecursionError, TypeError, UnicodeDecodeError, ValueError) as exc: + raise M8PipelineError(f"{label} contains invalid JSONL") from exc + if not isinstance(decoded, Mapping): + raise M8PipelineError(f"{label} JSONL entries must be objects") + try: + canonical = json.dumps( + decoded, + ensure_ascii=False, + separators=(",", ":"), + sort_keys=True, + allow_nan=False, + ).encode("utf-8") + except (RecursionError, TypeError, ValueError) as exc: + raise M8PipelineError(f"{label} contains unstable JSONL") from exc + if line != canonical: + raise M8PipelineError(f"{label} is not stable canonical JSONL") + severity = decoded.get("severity") + if severity not in {"ERROR", "WARNING"}: + raise M8PipelineError(f"{label} contains an invalid finding severity") + return cast(str, severity) + + try: + before = os.fstat(descriptor) + if not stat.S_ISREG(before.st_mode) or before.st_size != item.bytes: + raise M8PipelineError(f"{label} byte count differs from its inventory") + while chunk := os.read(descriptor, _LOCK_READ_CHUNK_BYTES): + observed_bytes += len(chunk) + digest.update(chunk) + buffered += chunk + while b"\n" in buffered: + line, buffered = buffered.split(b"\n", 1) + severity = parse_line(line) + if severity == "ERROR": + errors += 1 + else: + warnings += 1 + if len(buffered) > _MAX_FAILURE_FINDING_LINE_BYTES: + raise M8PipelineError(f"{label} contains an oversized JSON line") + if buffered: + raise M8PipelineError(f"{label} must end every JSONL entry with a newline") + after = os.fstat(descriptor) + before_identity = ( + before.st_dev, + before.st_ino, + before.st_mode, + before.st_size, + before.st_mtime_ns, + before.st_ctime_ns, + ) + after_identity = ( + after.st_dev, + after.st_ino, + after.st_mode, + after.st_size, + after.st_mtime_ns, + after.st_ctime_ns, + ) + if before_identity != after_identity or observed_bytes != item.bytes: + raise M8PipelineError(f"{label} changed while it was verified") + linked = os.stat(path, follow_symlinks=False) + if ( + not stat.S_ISREG(linked.st_mode) + or linked.st_dev != before.st_dev + or linked.st_ino != before.st_ino + or digest.hexdigest() != item.sha256 + ): + raise M8PipelineError(f"{label} changed identity or SHA-256 while verified") + except OSError as exc: + raise M8PipelineError(f"cannot verify {label}") from exc + finally: + os.close(descriptor) + if errors != expected_errors or warnings != expected_warnings: + raise M8PipelineError(f"{label} severity counts differ from the quality report") + + +def _verify_failed_normalization_evidence( + *, + target: Path, + config: M8StudyConfig, + raw_manifest: M8AcquisitionManifest, + failure: Mapping[str, Any], + inventory: Mapping[str, _FailureEvidenceItem], +) -> None: + """Verify the stage-derived failed symbol/date evidence contract.""" + + reason_code = failure.get("reason_code") + raw_evidence = failure.get("failed_normalization_evidence") + reason_contract: Mapping[str, tuple[str, str]] = { + "ARCHIVE_PAYLOAD_OR_CONTINUITY": ("PAYLOAD_OR_CONTINUITY", "PARTIAL_STREAM"), + "ARCHIVE_QUALITY_GATE": ("QUALITY_GATE", "COMPLETE_DATASET_AND_QUALITY"), + "ARCHIVE_POSTWRITE_CONSISTENCY": ( + "POSTWRITE_CONSISTENCY", + "COMPLETE_DATASET_AND_QUALITY", + ), + } + expected_typed = reason_contract.get(cast(str, reason_code)) + if expected_typed is None: + if raw_evidence is not None: + raise M8PipelineError("non-normalization failure claims normalization evidence") + return + if not isinstance(raw_evidence, Mapping): + raise M8PipelineError("normalization failure lacks its typed evidence authority") + expected_keys = { + "schema_version", + "failure_kind", + "evidence_completion", + "normalized_prefix", + "quality_prefix", + "artifacts", + "complete_normalization", + } + if set(raw_evidence) != expected_keys: + raise M8PipelineError("failed normalization evidence schema is invalid") + symbol = failure.get("failed_symbol") + study_date = failure.get("failed_date") + role = failure.get("failed_role") + if type(symbol) is not str or type(study_date) is not str or type(role) is not str: + raise M8PipelineError("failed normalization identity is malformed") + normalized_prefix = f"data/normalized_input/normalized/{symbol}/{study_date}" + quality_prefix = f"data/normalized_input/quality/{symbol}/{study_date}" + kind, completion = expected_typed + if ( + raw_evidence.get("schema_version") != "m8-failed-normalization-evidence-v1" + or raw_evidence.get("failure_kind") != kind + or raw_evidence.get("evidence_completion") != completion + or raw_evidence.get("normalized_prefix") != normalized_prefix + or raw_evidence.get("quality_prefix") != quality_prefix + ): + raise M8PipelineError("failed normalization evidence has inconsistent typed claims") + + raw_artifacts = raw_evidence.get("artifacts") + if not isinstance(raw_artifacts, list): + raise M8PipelineError("failed normalization scoped artifacts must be a JSON array") + scoped_claims: list[_FailureEvidenceItem] = [] + for index, value in enumerate(raw_artifacts): + label = f"failed normalization artifacts[{index}]" + if not isinstance(value, Mapping) or set(value) != {"path", "sha256", "bytes"}: + raise M8PipelineError(f"{label} schema is invalid") + path = value.get("path") + sha = value.get("sha256") + byte_count = value.get("bytes") + if type(path) is not str or not ( + path.startswith(f"{normalized_prefix}/") or path.startswith(f"{quality_prefix}/") + ): + raise M8PipelineError(f"{label} is outside the frozen failed evidence roots") + if type(sha) is not str: + raise M8PipelineError(f"{label} lacks its SHA-256") + digest = _require_digest(sha, f"{label} SHA-256") + if isinstance(byte_count, bool) or not isinstance(byte_count, int) or byte_count < 0: + raise M8PipelineError(f"{label} has an invalid byte count") + scoped_claims.append(_FailureEvidenceItem(path, digest, byte_count)) + claim_paths = [item.path for item in scoped_claims] + if claim_paths != sorted(claim_paths) or len(claim_paths) != len(set(claim_paths)): + raise M8PipelineError("failed normalization artifact paths are duplicate or unordered") + observed_scope = { + path: item + for path, item in inventory.items() + if path.startswith(f"{normalized_prefix}/") or path.startswith(f"{quality_prefix}/") + } + if set(claim_paths) != set(observed_scope) or any( + observed_scope[item.path] != item for item in scoped_claims + ): + raise M8PipelineError("failed normalization evidence differs from its inventoried tree") + + dataset_paths = [ + path + for path in observed_scope + if Path(path).parent.as_posix() == f"{normalized_prefix}/_manifests" + and re.fullmatch(r"trades\.manifest-[0-9a-f]{20}\.json", Path(path).name) + ] + report_path = f"{quality_prefix}/report.json" + findings_path = f"{quality_prefix}/findings.jsonl" + complete_claim = raw_evidence.get("complete_normalization") + if completion == "PARTIAL_STREAM": + if dataset_paths or report_path in observed_scope or findings_path in observed_scope: + raise M8PipelineError("partial payload failure contains final normalization evidence") + if complete_claim is not None: + raise M8PipelineError("partial payload failure claims a complete normalization") + allowed_part = re.compile( + rf"^{re.escape(normalized_prefix)}/trades/schema-1\.0\.0/" + rf"venue-binance_spot/symbol-{re.escape(symbol)}/date-{re.escape(study_date)}/" + r"part-[0-9a-f]{20}(?:\.parquet|\.manifest-[0-9a-f]{20}\.json)$" + ) + if any(allowed_part.fullmatch(path) is None for path in observed_scope): + raise M8PipelineError("partial payload failure contains a noncanonical artifact") + return + + if ( + len(dataset_paths) != 1 + or report_path not in observed_scope + or findings_path not in observed_scope + ): + raise M8PipelineError("complete failed normalization lacks dataset and quality evidence") + if kind == "POSTWRITE_CONSISTENCY": + if complete_claim is not None: + raise M8PipelineError("postwrite failure claims an accepted normalization entry") + _read_inventory_json_object( + target=target, + inventory=inventory, + relative_path=dataset_paths[0], + label="postwrite failed dataset manifest", + ) + _read_inventory_json_object( + target=target, + inventory=inventory, + relative_path=report_path, + label="postwrite failed quality report", + ) + return + + if not isinstance(complete_claim, Mapping): + raise M8PipelineError("quality-gate failure lacks its complete normalization claim") + _verify_normalization_claims( + target=target, + config=config, + raw_manifest=raw_manifest, + inventory=inventory, + raw_completed=[complete_claim], + expected_order=[(symbol, study_date, role)], + require_quality_gate_failure=True, + ) + + +def _verify_normalization_claims( + *, + target: Path, + config: M8StudyConfig, + raw_manifest: M8AcquisitionManifest, + inventory: Mapping[str, _FailureEvidenceItem], + raw_completed: Sequence[Any], + expected_order: Sequence[tuple[str, str, str]], + require_quality_gate_failure: bool, +) -> None: + """Bind normalization claims to raw authority, parts, and exact DQ evidence.""" + + observed_order: list[tuple[str, str, str]] = [] + raw_by_key = { + (entry.symbol, entry.date.isoformat(), str(entry.role)): entry + for entry in raw_manifest.archives + } + expected_keys = { + "symbol", + "date", + "role", + "rows", + "raw_zip_sha256", + "normalized_dataset_manifest_sha256", + "quality_errors", + "quality_warnings", + } + for index, raw_claim in enumerate(raw_completed): + label = f"completed normalizations[{index}]" + if not isinstance(raw_claim, Mapping) or set(raw_claim) != expected_keys: + raise M8PipelineError(f"{label} has an invalid schema") + symbol = raw_claim.get("symbol") + study_date = raw_claim.get("date") + role = raw_claim.get("role") + if type(symbol) is not str or type(study_date) is not str or type(role) is not str: + raise M8PipelineError(f"{label} has a malformed symbol/date/role identity") + identity = (symbol, study_date, role) + observed_order.append(identity) + raw_entry = raw_by_key.get(identity) + if raw_entry is None: + raise M8PipelineError(f"{label} is outside the frozen raw acquisition calendar") + + rows = raw_claim.get("rows") + errors = raw_claim.get("quality_errors") + warnings = raw_claim.get("quality_warnings") + if ( + isinstance(rows, bool) + or not isinstance(rows, int) + or rows < 1 + or isinstance(errors, bool) + or not isinstance(errors, int) + or errors < 0 + or isinstance(warnings, bool) + or not isinstance(warnings, int) + or warnings < 0 + ): + raise M8PipelineError(f"{label} has invalid row or quality counts") + raw_sha_value = raw_claim.get("raw_zip_sha256") + normalized_sha_value = raw_claim.get("normalized_dataset_manifest_sha256") + if type(raw_sha_value) is not str or type(normalized_sha_value) is not str: + raise M8PipelineError(f"{label} lacks required SHA-256 claims") + raw_sha = _require_digest(raw_sha_value, f"{label} raw ZIP SHA-256") + normalized_sha = _require_digest( + normalized_sha_value, + f"{label} normalized manifest SHA-256", + ) + if raw_sha != raw_entry.archive_sha256: + raise M8PipelineError(f"{label} raw ZIP SHA-256 differs from acquisition authority") + + archive_root = f"data/normalized_input/normalized/{symbol}/{study_date}" + dataset_directory = f"{archive_root}/_manifests" + dataset_matches = [ + item + for path, item in inventory.items() + if Path(path).parent.as_posix() == dataset_directory + and re.fullmatch(r"trades\.manifest-[0-9a-f]{20}\.json", Path(path).name) + and item.sha256 == normalized_sha + ] + if len(dataset_matches) != 1: + raise M8PipelineError( + f"{label} normalized dataset manifest is absent or ambiguous in the inventory" + ) + dataset_item = dataset_matches[0] + dataset_relative = dataset_item.path + if dataset_item.bytes > _MAX_LOCK_JSON_BYTES: + raise M8PipelineError(f"{label} normalized dataset manifest exceeds its JSON limit") + dataset = _read_inventory_json_object( + target=target, + inventory=inventory, + relative_path=dataset_relative, + label=f"{label} normalized dataset manifest", + ) + if ( + dataset.get("dataset") != "trades" + or dataset.get("source") != config.study.source + or dataset.get("source_uri") != raw_entry.archive_source_uri + or dataset.get("rows") != rows + ): + raise M8PipelineError(f"{label} normalized dataset manifest claims differ") + artifacts = dataset.get("artifacts") + if not isinstance(artifacts, list) or not artifacts: + raise M8PipelineError(f"{label} normalized dataset manifest has no artifacts") + part_rows = 0 + part_paths: set[str] = set() + for part_index, raw_part in enumerate(artifacts): + part_label = f"{label} normalized part {part_index}" + if not isinstance(raw_part, Mapping): + raise M8PipelineError(f"{part_label} is not a JSON object") + ordinal = raw_part.get("write_ordinal") + part_row_count = raw_part.get("rows") + if ( + isinstance(ordinal, bool) + or not isinstance(ordinal, int) + or ordinal != part_index + or isinstance(part_row_count, bool) + or not isinstance(part_row_count, int) + or part_row_count < 1 + ): + raise M8PipelineError(f"{part_label} has invalid row or ordinal claims") + part_rows += part_row_count + for path_key, sha_key, kind in ( + ("data_path", "data_sha256", "data"), + ("manifest_path", "manifest_sha256", "sidecar"), + ): + child = _canonical_inventory_child( + raw_part.get(path_key), + f"{part_label} {kind} path", + ) + sha_value = raw_part.get(sha_key) + if type(sha_value) is not str: + raise M8PipelineError(f"{part_label} {kind} lacks its SHA-256") + part_sha = _require_digest(sha_value, f"{part_label} {kind} SHA-256") + part_relative = f"{archive_root}/{child}" + if part_relative in part_paths: + raise M8PipelineError(f"{label} normalized dataset reuses an artifact path") + part_paths.add(part_relative) + _require_inventory_claim( + inventory, + part_relative, + f"{part_label} {kind}", + sha256=part_sha, + ) + if part_rows != rows: + raise M8PipelineError(f"{label} normalized part rows do not sum to its row claim") + + quality_root = f"data/normalized_input/quality/{symbol}/{study_date}" + report_relative = f"{quality_root}/report.json" + findings_relative = f"{quality_root}/findings.jsonl" + report_item = _require_inventory_claim( + inventory, + report_relative, + f"{label} quality report", + ) + findings_item = _require_inventory_claim( + inventory, + findings_relative, + f"{label} quality findings", + ) + if report_item.bytes > _MAX_LOCK_JSON_BYTES: + raise M8PipelineError(f"{label} quality report exceeds its JSON limit") + report = _read_inventory_json_object( + target=target, + inventory=inventory, + relative_path=report_relative, + label=f"{label} quality report", + ) + summary = report.get("summary") + if ( + report.get("dataset") != "trades" + or report.get("rows_checked") != rows + or not isinstance(summary, Mapping) + or summary.get("errors") != errors + or summary.get("warnings") != warnings + ): + raise M8PipelineError(f"{label} quality report claims differ") + gate_failed = errors > 0 or (warnings > 0 and not config.quality.allow_quality_warnings) + if gate_failed is not require_quality_gate_failure: + raise M8PipelineError(f"{label} quality counts disagree with its completion state") + _verify_quality_findings_jsonl( + target=target, + item=findings_item, + expected_errors=errors, + expected_warnings=warnings, + label=f"{label} quality findings JSONL", + ) + if require_quality_gate_failure: + expected_scope = { + dataset_relative, + report_relative, + findings_relative, + *part_paths, + } + observed_scope = { + path + for path in inventory + if path.startswith(f"{archive_root}/") or path.startswith(f"{quality_root}/") + } + if observed_scope != expected_scope: + raise M8PipelineError( + f"{label} complete failed evidence omits or adds scoped artifacts" + ) + + if observed_order != expected_order: + raise M8PipelineError( + "INSUFFICIENT_DATA completed normalizations differ from frozen failure progress" + ) + + +def _verify_completed_normalization_evidence( + *, + target: Path, + config: M8StudyConfig, + raw_manifest: M8AcquisitionManifest, + failure: Mapping[str, Any], + inventory: Mapping[str, _FailureEvidenceItem], +) -> None: + """Bind every successfully completed normalization before the failure boundary.""" + + raw_completed = failure.get("completed_normalizations") + if not isinstance(raw_completed, list): + raise M8PipelineError("INSUFFICIENT_DATA completed normalizations must be a JSON array") + _verify_normalization_claims( + target=target, + config=config, + raw_manifest=raw_manifest, + inventory=inventory, + raw_completed=raw_completed, + expected_order=_expected_completed_normalizations(config, failure), + require_quality_gate_failure=False, + ) + + +def _bind_inventory_artifact( + *, + target: Path, + inventory: Mapping[str, _FailureEvidenceItem], + path: Path, + sha256: str, + byte_count: int, + label: str, +) -> str: + """Bind one semantic path/SHA/size claim to an inventoried same-FD read.""" + + try: + relative = path.relative_to(target.resolve()).as_posix() + except ValueError as exc: + raise M8PipelineError(f"{label} escapes the failed bundle") from exc + relative = _canonical_inventory_child(relative, f"{label} path") + item = _require_inventory_claim( + inventory, + relative, + label, + sha256=_require_digest(sha256, f"{label} SHA-256"), + expected_bytes=byte_count, + ) + _verify_inventory_file(target, item) + return relative + + +def _bind_raw_acquisition_inventory( + *, + target: Path, + inventory: Mapping[str, _FailureEvidenceItem], + manifest: M8AcquisitionManifest, + manifest_relative: str, +) -> None: + """Exact-bind a bundled raw manifest and every retained raw artifact.""" + + manifest_item = _require_inventory_claim( + inventory, + manifest_relative, + "INSUFFICIENT_DATA bundled raw acquisition manifest", + sha256=manifest.sha256, + ) + if manifest_item.bytes < 1 or manifest_item.bytes > _MAX_LOCK_JSON_BYTES: + raise M8PipelineError("bundled raw acquisition manifest exceeds its JSON byte limit") + raw_root = manifest.root + try: + raw_prefix = raw_root.relative_to(target.resolve()).as_posix() + except ValueError as exc: + raise M8PipelineError("bundled raw acquisition root escapes the failed bundle") from exc + expected_scope = {manifest_relative} + for index, artifact in enumerate(manifest.retained_artifacts): + child = _canonical_inventory_child( + artifact.path, + f"bundled raw retained artifact[{index}] path", + ) + relative = f"{raw_prefix}/{child}" + expected_scope.add(relative) + item = _require_inventory_claim( + inventory, + relative, + f"bundled raw retained artifact[{index}]", + sha256=_require_digest( + artifact.sha256, + f"bundled raw retained artifact[{index}] SHA-256", + ), + expected_bytes=artifact.bytes, + ) + _verify_inventory_file(target, item) + observed_scope = { + path for path in inventory if path == raw_prefix or path.startswith(f"{raw_prefix}/") + } + if observed_scope != expected_scope: + raise M8PipelineError( + "bundled raw acquisition paths differ from the failure evidence inventory" + ) + + +def _bind_final_input_manifest_inventory( + *, + target: Path, + inventory: Mapping[str, _FailureEvidenceItem], + manifest: M8InputManifest, +) -> None: + """Exact-bind the optional final manifest and every artifact it names.""" + + try: + manifest_relative = manifest.path.relative_to(target.resolve()).as_posix() + except ValueError as exc: + raise M8PipelineError("final normalized manifest escapes the failed bundle") from exc + manifest_relative = _canonical_inventory_child( + manifest_relative, + "INSUFFICIENT_DATA final normalized manifest path", + ) + _read_inventory_bounded_snapshot( + target=target, + inventory=inventory, + relative_path=manifest_relative, + label="INSUFFICIENT_DATA final normalized manifest", + max_bytes=_MAX_LOCK_JSON_BYTES, + expected_sha256=manifest.sha256, + ) + for metadata in manifest.symbol_metadata: + _bind_inventory_artifact( + target=target, + inventory=inventory, + path=metadata.raw_path, + sha256=metadata.raw_sha256, + byte_count=metadata.raw_bytes, + label=f"final manifest {metadata.symbol} metadata body", + ) + _bind_inventory_artifact( + target=target, + inventory=inventory, + path=metadata.source_manifest_path, + sha256=metadata.source_manifest_sha256, + byte_count=metadata.source_manifest_bytes, + label=f"final manifest {metadata.symbol} metadata source manifest", + ) + for entry in manifest.entries: + label = f"final manifest {entry.symbol}/{entry.date.isoformat()}" + artifact_claims = ( + (entry.raw_zip_path, entry.raw_zip_sha256, entry.raw_zip_bytes, "raw ZIP"), + ( + entry.raw_source_manifest_path, + entry.raw_source_manifest_sha256, + entry.raw_source_manifest_bytes, + "raw source manifest", + ), + ( + entry.raw_checksum_path, + entry.raw_checksum_sha256, + entry.raw_checksum_bytes, + "official checksum", + ), + ( + entry.raw_checksum_source_manifest_path, + entry.raw_checksum_source_manifest_sha256, + entry.raw_checksum_source_manifest_bytes, + "checksum source manifest", + ), + ( + entry.normalized_dataset_manifest_path, + entry.normalized_dataset_manifest_sha256, + entry.normalized_dataset_manifest_bytes, + "normalized dataset manifest", + ), + ( + entry.quality_report_path, + entry.quality_report_sha256, + entry.quality_report_bytes, + "quality report", + ), + ( + entry.quality_findings_path, + entry.quality_findings_sha256, + entry.quality_findings_bytes, + "quality findings", + ), + ) + for path, digest, byte_count, kind in artifact_claims: + _bind_inventory_artifact( + target=target, + inventory=inventory, + path=path, + sha256=digest, + byte_count=byte_count, + label=f"{label} {kind}", + ) + for part in entry.normalized_parts: + _bind_inventory_artifact( + target=target, + inventory=inventory, + path=part.data_path, + sha256=part.data_sha256, + byte_count=part.data_bytes, + label=f"{label} normalized part {part.write_ordinal}", + ) + _bind_inventory_artifact( + target=target, + inventory=inventory, + path=part.sidecar_path, + sha256=part.sidecar_sha256, + byte_count=part.sidecar_bytes, + label=f"{label} normalized part {part.write_ordinal} sidecar", + ) + + +def _restore_fitted_state_file( + path: Path, + expected_sha256: str, + label: str, +) -> FinalFittedState: + digest = _require_digest(expected_sha256, f"{label} SHA-256") + snapshot = _read_bounded_json_snapshot( + path, + label=label, + expected_sha256=digest, + ensure_ascii=True, + ) + try: + state = FinalFittedState.restore(snapshot.text, digest) + if state.payload() != snapshot.payload: + raise M8PipelineError(f"{label} decoded inconsistently") + except (MultiDateEvaluationError, ValueError) as exc: + raise M8PipelineError(f"{label} is invalid") from exc + return state + + +def _restore_inventory_analysis_lock_file( + *, + target: Path, + inventory: Mapping[str, _FailureEvidenceItem], + relative_path: str, + expected_sha256: str, + label: str, +) -> AnalysisLock: + """Restore a failed-run lock only from its inventory-bound same-FD snapshot.""" + + digest = _require_digest(expected_sha256, f"{label} SHA-256") + snapshot = _read_inventory_bounded_json_snapshot( + target=target, + inventory=inventory, + relative_path=relative_path, + label=label, + expected_sha256=digest, + ensure_ascii=True, + ) + try: + lock = AnalysisLock.restore(snapshot.text, digest) + if lock.payload() != snapshot.payload: + raise M8PipelineError(f"{label} decoded inconsistently") + except (MultiDateEvaluationError, ValueError) as exc: + raise M8PipelineError(f"{label} is invalid") from exc + return lock + + +def _restore_inventory_fitted_state_file( + *, + target: Path, + inventory: Mapping[str, _FailureEvidenceItem], + relative_path: str, + expected_sha256: str, + label: str, +) -> FinalFittedState: + """Restore a failed-run fitted state from inventory-bound same-FD bytes.""" + + digest = _require_digest(expected_sha256, f"{label} SHA-256") + snapshot = _read_inventory_bounded_json_snapshot( + target=target, + inventory=inventory, + relative_path=relative_path, + label=label, + expected_sha256=digest, + ensure_ascii=True, + ) + try: + state = FinalFittedState.restore(snapshot.text, digest) + if state.payload() != snapshot.payload: + raise M8PipelineError(f"{label} decoded inconsistently") + except (MultiDateEvaluationError, ValueError) as exc: + raise M8PipelineError(f"{label} is invalid") from exc + return state + + +def _caused_by_system_fault(error: BaseException) -> bool: + """Distinguish an acquisition integrity rejection from wrapped local I/O faults.""" + + observed: BaseException | None = error + seen: set[int] = set() + while observed is not None and id(observed) not in seen: + seen.add(id(observed)) + if observed is not error and isinstance(observed, OSError): + return True + observed = observed.__cause__ or observed.__context__ + return False + + +def _utc_from_ns(timestamp_ns: int) -> str: + seconds, nanoseconds = divmod(timestamp_ns, 1_000_000_000) + instant = datetime.fromtimestamp(seconds, tz=UTC) + return f"{instant:%Y-%m-%dT%H:%M:%S}.{nanoseconds:09d}Z" + + +def _day_bounds_ns(day: date) -> tuple[int, int]: + start = datetime(day.year, day.month, day.day, tzinfo=UTC) + start_ns = int(start.timestamp()) * 1_000_000_000 + return start_ns, start_ns + 86_400 * 1_000_000_000 + + +def _project_root(config: M8StudyConfig) -> Path: + source = config.path.resolve() + if not source.is_file(): + raise M8PipelineError(f"M8 machine specification is missing: {source}") + root = source.parent.parent.resolve() + if not (root / "pyproject.toml").is_file(): + raise M8PipelineError( + "M8 configuration must live below the research project root containing pyproject.toml" + ) + return root + + +def _verify_config_source(config: M8StudyConfig) -> None: + observed = sha256_file(config.path) + if observed != config.source_sha256: + raise M8PipelineError( + "M8 machine specification bytes changed after the configuration was loaded" + ) + + +def _capture_source_identity(project_root: Path) -> _SourceIdentity: + state = git_state(project_root) + return _SourceIdentity( + commit=state.commit, + dirty=state.dirty, + source_tree_sha256=git_source_tree_sha256(project_root), + ) + + +def _protocol_source(project_root: Path) -> Path: + path = project_root / "docs" / "M8_MULTIDATE_TRADE_PROTOCOL.md" + if not path.is_file(): + raise M8PipelineError(f"frozen M8 protocol is missing: {path}") + return path + + +def _atomic_copy_exact( + source: Path, + destination: Path, + *, + expected_sha256: str, + expected_bytes: int | None = None, +) -> None: + expected = _require_digest(expected_sha256, f"SHA-256 for {source}") + try: + before_size = source.stat().st_size + except OSError as exc: + raise M8PipelineError(f"cannot stat immutable input artifact: {source}") from exc + if expected_bytes is not None and before_size != expected_bytes: + raise M8PipelineError(f"immutable input artifact byte count changed: {source}") + + destination.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary_name = tempfile.mkstemp( + dir=destination.parent, + prefix=f".{destination.name}.", + suffix=".tmp", + ) + temporary = Path(temporary_name) + digest = hashlib.sha256() + copied = 0 + try: + with source.open("rb") as input_handle, os.fdopen(descriptor, "wb") as output_handle: + while chunk := input_handle.read(1024 * 1024): + output_handle.write(chunk) + digest.update(chunk) + copied += len(chunk) + output_handle.flush() + os.fsync(output_handle.fileno()) + if digest.hexdigest() != expected: + raise M8PipelineError(f"immutable input artifact changed while copying: {source}") + if expected_bytes is not None and copied != expected_bytes: + raise M8PipelineError(f"immutable input artifact changed size while copying: {source}") + os.replace(temporary, destination) + except BaseException: + temporary.unlink(missing_ok=True) + raise + if sha256_file(destination) != expected: + raise M8PipelineError(f"frozen evidence copy failed checksum verification: {destination}") + + +def _load_final_input_manifest( + config: M8StudyConfig, + manifest_path: Path, + manifest_sha256: str, +) -> M8InputManifest: + expected = _require_digest(manifest_sha256, "M8 input manifest SHA-256") + explicit = manifest_path.resolve() + if explicit.parent.name != "_manifests": + raise M8PipelineError( + "M8 input manifest must use the canonical /_manifests/ location" + ) + expected_name = f"m8-input.manifest-{expected[:20]}.json" + if explicit.name != expected_name: + raise M8PipelineError("M8 input manifest filename is not content-addressed by the SHA") + if not explicit.is_file(): + raise M8PipelineError(f"M8 input manifest does not exist: {explicit}") + if sha256_file(explicit) != expected: + raise M8PipelineError("M8 input manifest bytes do not match the supplied SHA-256") + input_root = explicit.parent.parent.resolve() + try: + manifest = verify_m8_input_manifest( + config, + input_root, + explicit, + manifest_sha256=expected, + ) + except M8ManifestError as exc: + raise M8PipelineError(f"M8 input manifest verification failed: {exc}") from exc + if manifest.path != explicit or manifest.sha256 != expected: + raise M8PipelineError("M8 input verifier returned a different manifest authority") + _validate_manifest_scope(config, manifest) + return manifest + + +def _load_raw_manifest( + config: M8StudyConfig, + manifest_path: Path, + manifest_sha256: str, +) -> M8AcquisitionManifest: + expected = _require_digest(manifest_sha256, "M8 raw acquisition manifest SHA-256") + explicit = manifest_path.resolve() + if explicit.name != f"m8-acquisition.manifest-{expected[:20]}.json": + raise M8PipelineError( + "M8 raw acquisition manifest filename is not content-addressed by the SHA" + ) + if not explicit.is_file() or sha256_file(explicit) != expected: + raise M8PipelineError("M8 raw acquisition manifest bytes do not match the supplied SHA") + try: + manifest = read_m8_acquisition_manifest( + explicit, + expected_sha256=expected, + config=config, + ) + except Exception as exc: + raise M8PipelineError(f"M8 raw acquisition manifest verification failed: {exc}") from exc + if manifest.path.resolve() != explicit or manifest.sha256 != expected: + raise M8PipelineError("M8 raw verifier returned a different manifest authority") + if ( + manifest.config_sha256 != config.hash + or manifest.config_source_sha256 != config.source_sha256 + or manifest.protocol_version != config.study.protocol_version + ): + raise M8PipelineError("M8 raw acquisition is bound to another protocol/configuration") + return manifest + + +def _validate_manifest_scope(config: M8StudyConfig, manifest: M8InputManifest) -> None: + if ( + manifest.config_sha256 != config.hash + or manifest.config_source_sha256 != config.source_sha256 + or manifest.protocol_version != config.study.protocol_version + ): + raise M8PipelineError("M8 input is bound to a different configuration or protocol") + if tuple(metadata.symbol for metadata in manifest.symbol_metadata) != config.study.symbols: + raise M8PipelineError("M8 input does not contain the exact frozen symbol metadata") + metadata_by_symbol = {metadata.symbol: metadata for metadata in manifest.symbol_metadata} + if len(metadata_by_symbol) != len(config.study.symbols) or any( + metadata.status != "TRADING" for metadata in manifest.symbol_metadata + ): + raise M8PipelineError("M8 symbol metadata must prove both instruments were TRADING") + expected = tuple( + (symbol, period.date, period.role) + for period in config.periods + for symbol in config.study.symbols + ) + observed = tuple((entry.symbol, entry.date, entry.role) for entry in manifest.entries) + if observed != expected or len(observed) != 8: + raise M8PipelineError("M8 input does not contain the exact frozen eight-entry calendar") + if any( + not entry.complete + or entry.quality_errors != 0 + or entry.quality_warnings != 0 + or entry.rows < 1 + for entry in manifest.entries + ): + raise M8PipelineError( + "M8 FULL_DATA requires every declared archive complete and free of errors/warnings" + ) + if any( + entry.tick_size != metadata_by_symbol[entry.symbol].tick_size + or entry.lot_size != metadata_by_symbol[entry.symbol].lot_size + for entry in manifest.entries + ): + raise M8PipelineError("M8 archive scales disagree with verified exchange metadata") + if ( + sum(entry.raw_zip_bytes for entry in manifest.entries) + > config.study.max_total_download_bytes + ): + raise M8PipelineError("M8 raw archives exceed the frozen total-download ceiling") + + +def _entry_lookup(manifest: M8InputManifest) -> dict[tuple[str, str], M8ArchiveEntry]: + return {(entry.symbol, entry.date.isoformat()): entry for entry in manifest.entries} + + +def _normalized_metadata(metadata: M8RawSymbolMetadata) -> M8SymbolMetadata: + """Project a verified raw metadata descriptor into the final input schema.""" + + return M8SymbolMetadata( + symbol=metadata.symbol, + status=metadata.status, + tick_size=metadata.tick_size, + lot_size=metadata.lot_size, + observed_ts_ns=metadata.observed_ts_ns, + raw_path=metadata.raw_path.resolve(), + raw_sha256=metadata.raw_sha256, + raw_bytes=metadata.raw_bytes, + source_uri=metadata.source_uri, + source_manifest_path=metadata.source_manifest_path.resolve(), + source_manifest_sha256=metadata.source_manifest_sha256, + source_manifest_bytes=metadata.source_manifest_bytes, + ) + + +def _freeze_protocol_and_config( + config: M8StudyConfig, + project_root: Path, + stage: Path, +) -> dict[str, object]: + _verify_config_source(config) + protocol = _protocol_source(project_root) + protocol_sha = sha256_file(protocol) + config_destination = stage / "protocol" / "m8_multidate_trade_study.toml" + protocol_destination = stage / "protocol" / "M8_MULTIDATE_TRADE_PROTOCOL.md" + _atomic_copy_exact( + config.path, + config_destination, + expected_sha256=config.source_sha256, + expected_bytes=config.path.stat().st_size, + ) + _atomic_copy_exact( + protocol, + protocol_destination, + expected_sha256=protocol_sha, + expected_bytes=protocol.stat().st_size, + ) + return { + "machine_spec_path": _relative(config_destination, stage), + "machine_spec_source_sha256": config.source_sha256, + "config_semantic_sha256": config.hash, + "protocol_path": _relative(protocol_destination, stage), + "protocol_sha256": protocol_sha, + "protocol_version": config.study.protocol_version, + } + + +def _snapshot_input_evidence( + manifest: M8InputManifest, + stage: Path, +) -> tuple[dict[str, object], tuple[str, ...]]: + """Index stage-local input evidence without creating another raw copy.""" + + manifest_copy = stage / "data" / "m8_input_manifest.json" + _atomic_copy_exact( + manifest.path, + manifest_copy, + expected_sha256=manifest.sha256, + expected_bytes=manifest.path.stat().st_size, + ) + hashes: set[str] = {manifest.sha256} + metadata_rows: list[dict[str, object]] = [] + for metadata in manifest.symbol_metadata: + hashes.update((metadata.raw_sha256, metadata.source_manifest_sha256)) + metadata_rows.append( + { + "symbol": metadata.symbol, + "status": metadata.status, + "tick_size": format(metadata.tick_size, "f"), + "lot_size": format(metadata.lot_size, "f"), + "observed_ts_ns": metadata.observed_ts_ns, + "observed_utc": _utc_from_ns(metadata.observed_ts_ns), + "source_uri": metadata.source_uri, + "bundle_raw_path": _relative(metadata.raw_path, stage), + "raw_sha256": metadata.raw_sha256, + "raw_bytes": metadata.raw_bytes, + "bundle_source_manifest_path": _relative(metadata.source_manifest_path, stage), + "source_manifest_sha256": metadata.source_manifest_sha256, + "source_manifest_bytes": metadata.source_manifest_bytes, + } + ) + entries: list[dict[str, object]] = [] + for entry in manifest.entries: + part_copies: list[dict[str, object]] = [] + for part in entry.normalized_parts: + hashes.update((part.sidecar_sha256, part.data_sha256)) + part_copies.append( + { + "write_ordinal": part.write_ordinal, + "rows": part.rows, + "bundle_data_path": _relative(part.data_path, stage), + "data_sha256": part.data_sha256, + "data_bytes": part.data_bytes, + "sidecar_path": _relative(part.sidecar_path, stage), + "sidecar_sha256": part.sidecar_sha256, + } + ) + hashes.update( + ( + entry.raw_zip_sha256, + entry.raw_source_manifest_sha256, + entry.raw_checksum_sha256, + entry.raw_checksum_source_manifest_sha256, + entry.normalized_dataset_manifest_sha256, + entry.quality_report_sha256, + entry.quality_findings_sha256, + ) + ) + entries.append( + { + "symbol": entry.symbol, + "date": entry.date.isoformat(), + "role": entry.role, + "complete": entry.complete, + "rows": entry.rows, + "trade_id_range": { + "first": entry.first_trade_id, + "last": entry.last_trade_id, + "contiguous": True, + }, + "observed_range_ns": { + "start": entry.observed_start_ns, + "end_inclusive": entry.observed_end_inclusive_ns, + }, + "raw_archive": { + "bundle_path": _relative(entry.raw_zip_path, stage), + "sha256": entry.raw_zip_sha256, + "bytes": entry.raw_zip_bytes, + "uncompressed_bytes": entry.raw_uncompressed_bytes, + "source_uri": entry.raw_source_uri, + "official_checksum": { + "bundle_path": _relative(entry.raw_checksum_path, stage), + "sha256": entry.raw_checksum_sha256, + "bytes": entry.raw_checksum_bytes, + "source_uri": entry.raw_checksum_source_uri, + "bundle_source_manifest_path": _relative( + entry.raw_checksum_source_manifest_path, + stage, + ), + "source_manifest_sha256": (entry.raw_checksum_source_manifest_sha256), + "source_manifest_bytes": entry.raw_checksum_source_manifest_bytes, + }, + "source_manifest_path": _relative(entry.raw_source_manifest_path, stage), + "source_manifest_sha256": entry.raw_source_manifest_sha256, + }, + "normalized_dataset_manifest": { + "path": _relative(entry.normalized_dataset_manifest_path, stage), + "sha256": entry.normalized_dataset_manifest_sha256, + "bytes": entry.normalized_dataset_manifest_bytes, + }, + "normalized_parts": part_copies, + "quality": { + "report_path": _relative(entry.quality_report_path, stage), + "report_sha256": entry.quality_report_sha256, + "findings_path": _relative(entry.quality_findings_path, stage), + "findings_sha256": entry.quality_findings_sha256, + "errors": 0, + "warnings": 0, + }, + } + ) + snapshot = { + "schema_version": M8_PIPELINE_SCHEMA_VERSION, + "artifact_kind": "m8_verified_input_snapshot", + "manifest_authority": { + "policy": "explicit path plus caller-supplied lowercase SHA-256; no discovery", + "bundle_path": _relative(manifest.path, stage), + "sha256": manifest.sha256, + "frozen_copy_path": _relative(manifest_copy, stage), + }, + "input_root": _relative(manifest.root, stage), + "config_sha256": manifest.config_sha256, + "config_source_sha256": manifest.config_source_sha256, + "protocol_version": manifest.protocol_version, + "evidence_tier": M8_EVIDENCE_TIER, + "evidence_scope": M8_EVIDENCE_SCOPE, + "symbol_metadata": metadata_rows, + "entries": entries, + "self_contained_bundle_input": True, + "raw_archives_copied_into_run": True, + "snapshot_created_additional_raw_evidence_copies": False, + "normalized_rows_are_stage_local": True, + "note": ( + "Accepted raw archives, official checksums, source sidecars, and metadata are " + "self-contained below data/input; normalized parts and DQ evidence are isolated " + "below data/normalized_input. This snapshot only indexes those authoritative " + "stage-local bytes and creates no further raw copy." + ), + } + _write_json(stage / "data" / "manifest_snapshot.json", snapshot) + return snapshot, tuple(sorted(hashes)) + + +def _feature_config(config: M8StudyConfig) -> FeatureConfig: + return FeatureConfig( + trade_windows=config.features.trade_windows, + volatility_window=config.features.volatility_window, + intensity_window=config.features.intensity_window, + label_horizon_events=config.study.label_horizon_events, + large_trade_quantile=config.features.large_trade_quantile, + ) + + +def _model_config(config: M8StudyConfig) -> ModelConfig: + return ModelConfig( + selection_metric=config.study.selection_metric, + logistic_c_values=config.models.logistic_c_values, + tree_max_depth_values=config.models.tree_max_depth_values, + tree_min_samples_leaf=config.models.tree_min_samples_leaf, + ) + + +def _trade_feature_columns(config: M8StudyConfig) -> tuple[str, ...]: + columns: list[str] = ["log_trade_return_1"] + for window in config.features.trade_windows: + columns.extend( + ( + f"signed_trade_volume_w{window}", + f"trade_volume_w{window}", + f"trade_imbalance_w{window}", + ) + ) + columns.extend( + ( + f"trade_count_w{config.features.intensity_window}", + f"trade_intensity_w{config.features.intensity_window}", + f"realized_volatility_w{config.features.volatility_window}", + ) + ) + return tuple(dict.fromkeys(columns)) + + +def _read_normalized_date(entry: M8ArchiveEntry) -> pl.DataFrame: + """Read one already-verified date; callers enforce the analysis-lock phase.""" + + paths = tuple(part.data_path for part in entry.normalized_parts) + if not paths: + raise M8PipelineError(f"no normalized Parquet parts for {entry.symbol}/{entry.date}") + try: + frame = pl.read_parquet(list(paths), columns=list(_TRADE_COLUMNS), rechunk=False) + except Exception as exc: + raise M8PipelineError( + f"cannot read normalized M8 date {entry.symbol}/{entry.date}: {exc}" + ) from exc + for part in entry.normalized_parts: + if part.data_path.stat().st_size != part.data_bytes: + raise M8PipelineError( + f"normalized part changed size during research read: {part.data_path}" + ) + if sha256_file(part.data_path) != part.data_sha256: + raise M8PipelineError(f"normalized part changed during research read: {part.data_path}") + _validate_normalized_date(frame, entry) + return frame + + +def _validate_normalized_date(frame: pl.DataFrame, entry: M8ArchiveEntry) -> None: + label = f"{entry.symbol}/{entry.date.isoformat()}" + if frame.height != entry.rows: + raise M8PipelineError(f"normalized row count disagrees with manifest for {label}") + if frame.get_column("symbol").null_count() or set(frame.get_column("symbol").unique()) != { + entry.symbol + }: + raise M8PipelineError(f"normalized symbol scope is invalid for {label}") + expected_continuity = f"binance_spot:{entry.symbol}:{entry.date.isoformat()}" + continuity = frame.get_column("continuity_id") + if continuity.null_count() or set(continuity.unique()) != {expected_continuity}: + raise M8PipelineError(f"normalized continuity does not reset at the UTC date for {label}") + if not frame.get_column("trade_id").is_sorted(): + raise M8PipelineError(f"normalized trade IDs are not physically ordered for {label}") + if frame.filter((pl.col("trade_id").diff() != 1).fill_null(False)).height: + raise M8PipelineError(f"normalized trade IDs contain a gap for {label}") + first_id = int(cast(int, frame.get_column("trade_id").min())) + last_id = int(cast(int, frame.get_column("trade_id").max())) + if (first_id, last_id) != (entry.first_trade_id, entry.last_trade_id): + raise M8PipelineError(f"normalized trade-ID bounds disagree with manifest for {label}") + if not frame.get_column("available_ts_ns").is_sorted(): + raise M8PipelineError(f"normalized availability clock reverses for {label}") + if frame.filter(pl.col("available_ts_ns") < pl.col("event_ts_ns")).height: + raise M8PipelineError(f"normalized availability precedes event time for {label}") + if set(frame.get_column("availability_basis").unique()) != {"exchange_event_time_proxy"}: + raise M8PipelineError( + f"historical M8 rows have an unsupported availability basis for {label}" + ) + if frame.get_column("received_ts_ns").null_count() != frame.height: + raise M8PipelineError(f"historical M8 rows cannot claim local receipt time for {label}") + observed = ( + int(cast(int, frame.get_column("event_ts_ns").min())), + int(cast(int, frame.get_column("event_ts_ns").max())), + ) + if observed != (entry.observed_start_ns, entry.observed_end_inclusive_ns): + raise M8PipelineError(f"normalized event-time bounds disagree with manifest for {label}") + day_start, day_end = _day_bounds_ns(entry.date) + if observed[0] < day_start or observed[1] >= day_end: + raise M8PipelineError(f"normalized rows escape their UTC date for {label}") + + +def _evaluation_columns(config: M8StudyConfig) -> tuple[str, ...]: + return ( + "study_date", + "study_role", + "symbol", + "decision_ts_ns", + "decision_sequence", + "decision_trade_id", + "continuity_id", + "feature_continuity_id", + "label_continuity_id", + "max_feature_source_ts_ns", + "max_feature_source_trade_id", + "label_start_ts_ns", + "label_start_trade_id", + "label_information_end_ts_ns", + "label_information_end_trade_id", + "feature_ready", + "right_censored", + config.study.target, + *_trade_feature_columns(config), + ) + + +def _date_summary( + entry: M8ArchiveEntry, + research: pl.DataFrame, + temporal_audit: Mapping[str, object], + target: str, +) -> dict[str, object]: + eligible = research.filter(pl.col("feature_ready") & (~pl.col("right_censored"))) + positive = eligible.filter(pl.col(target) == 1).height + negative = eligible.filter(pl.col(target) == 0).height + return { + "symbol": entry.symbol, + "date": entry.date.isoformat(), + "role": entry.role, + "source_rows": entry.rows, + "research_rows": research.height, + "feature_ready_rows": research.filter(pl.col("feature_ready")).height, + "right_censored_rows": research.filter(pl.col("right_censored")).height, + "feature_warmup_excluded_rows": research.filter(~pl.col("feature_ready")).height, + "eligible_labeled_rows": eligible.height, + "eligible_positive_rows": positive, + "eligible_negative_rows": negative, + "eligible_positive_rate": positive / eligible.height if eligible.height else None, + "observed_start_ts_ns": entry.observed_start_ns, + "observed_end_inclusive_ts_ns": entry.observed_end_inclusive_ns, + "observed_start_utc": _utc_from_ns(entry.observed_start_ns), + "observed_end_inclusive_utc": _utc_from_ns(entry.observed_end_inclusive_ns), + "first_trade_id": entry.first_trade_id, + "last_trade_id": entry.last_trade_id, + "continuity_id": f"binance_spot:{entry.symbol}:{entry.date.isoformat()}", + "quality_errors": entry.quality_errors, + "quality_warnings": entry.quality_warnings, + "temporal_audit": dict(temporal_audit), + "source_values_repaired": False, + } + + +def _build_date_artifacts( + entry: M8ArchiveEntry, + config: M8StudyConfig, + stage: Path, +) -> _DateArtifacts: + trades = _read_normalized_date(entry) + research = build_trade_only_research_frame(trades, _feature_config(config)).with_columns( + pl.lit(entry.date.isoformat()).alias("study_date"), + pl.lit(entry.role).alias("study_role"), + pl.col("label_horizon_trades").alias("label_horizon_events"), + ) + temporal = validate_trade_only_temporal_contract(research) + missing = sorted(set(_evaluation_columns(config)).difference(research.columns)) + if missing: + raise ResearchDataError(f"M8 research frame is missing frozen model columns: {missing}") + evaluation = research.select(_evaluation_columns(config)) + base = stage / "research" / entry.symbol.lower() / entry.date.isoformat() + research_path = base / "research_frame.parquet" + evaluation_path = base / "evaluation_frame.parquet" + research_path.parent.mkdir(parents=True, exist_ok=True) + research.write_parquet(research_path, compression="zstd", statistics=True) + evaluation.write_parquet(evaluation_path, compression="zstd", statistics=True) + summary = _date_summary(entry, research, asdict(temporal), config.study.target) + _write_json(base / "summary.json", summary) + return _DateArtifacts( + symbol=entry.symbol, + study_date=entry.date.isoformat(), + role=entry.role, + research_path=research_path, + evaluation_path=evaluation_path, + summary=summary, + ) + + +def _load_evaluation(path: Path) -> pl.DataFrame: + try: + return pl.read_parquet(path) + except Exception as exc: + raise M8PipelineError(f"cannot reload frozen per-date evaluation frame: {path}") from exc + + +def _select_symbol( + symbol: str, + symbol_index: int, + development: Sequence[_DateArtifacts], + config: M8StudyConfig, + stage: Path, +) -> _SelectionArtifacts: + frames = tuple(_load_evaluation(item.evaluation_path) for item in development) + test_dates = tuple( + period.date.isoformat() for period in config.periods if period.role in _TEST_ROLES + ) + selection = select_multidate_model( + frames, + _model_config(config), + feature_columns=_trade_feature_columns(config), + declared_test_dates=test_dates, + seed=config.study.seed + symbol_index * 100_000, + calibration_bins=config.study.feature_stability_bins, + target=config.study.target, + calibration_fraction=config.study.calibration_fraction, + ) + model_root = stage / "models" / symbol.lower() + comparison_path = model_root / "validation_candidate_comparison.parquet" + comparison = selection.validation_comparison.with_columns( + pl.lit(symbol).alias("symbol"), + pl.lit(symbol).alias("instrument"), + pl.lit(config.study.label_horizon_events).alias("horizon_events"), + pl.lit("validation").alias("split"), + pl.lit(selection.lock.sha256).alias("selection_lock_sha256"), + pl.lit(selection.fitted_state.sha256).alias("final_fitted_state_sha256"), + pl.lit(False).alias("significance_claim_authorized"), + ) + comparison_path.parent.mkdir(parents=True, exist_ok=True) + comparison.write_parquet(comparison_path, compression="zstd", statistics=True) + fitted_state_path = model_root / "final_fitted_state.json" + _atomic_write_text( + fitted_state_path, + selection.fitted_state.payload_json, + trailing_newline=False, + ) + restored_state = _restore_fitted_state_file( + fitted_state_path, + selection.fitted_state.sha256, + f"persisted {symbol} final fitted state", + ) + if restored_state != selection.fitted_state: + raise M8PipelineError(f"persisted final fitted state changed for {symbol}") + lock_path = stage / "analysis" / "locks" / f"{symbol.lower()}.selection_lock.json" + _atomic_write_text(lock_path, selection.lock.payload_json, trailing_newline=False) + _restore_analysis_lock_file( + lock_path, + selection.lock.sha256, + f"persisted {symbol} selection lock", + ) + _fsync_directory(fitted_state_path.parent) + _fsync_directory(lock_path.parent) + return _SelectionArtifacts( + symbol=symbol, + selection=selection, + lock_path=lock_path, + fitted_state_path=fitted_state_path, + comparison_path=comparison_path, + ) + + +def _commit_development_manifest( + entries: Sequence[M8ArchiveEntry], + date_artifacts: Mapping[tuple[str, str], _DateArtifacts], + config: M8StudyConfig, + stage: Path, +) -> tuple[Path, str]: + expected = tuple( + (symbol, period.date.isoformat(), period.role) + for period in config.periods + if period.role in _DEVELOPMENT_ROLES + for symbol in config.study.symbols + ) + lookup = {(entry.symbol, entry.date.isoformat()): entry for entry in entries} + if tuple((entry.symbol, entry.date.isoformat(), entry.role) for entry in entries) != expected: + raise M8PipelineError("development normalization did not produce the exact frozen order") + payload: dict[str, Any] = { + "schema_version": "m8-development-evidence-v1", + "artifact_kind": "immutable_development_normalized_manifest", + "config_sha256": config.hash, + "config_source_sha256": config.source_sha256, + "protocol_version": config.study.protocol_version, + "test_member_opened": False, + "entries": [], + } + rows: list[dict[str, object]] = [] + for symbol, study_date, role in expected: + entry = lookup[(symbol, study_date)] + artifacts = date_artifacts[(symbol, study_date)] + rows.append( + { + "symbol": symbol, + "date": study_date, + "role": role, + "rows": entry.rows, + "raw_zip_sha256": entry.raw_zip_sha256, + "official_checksum_sha256": entry.raw_checksum_sha256, + "raw_source_manifest_sha256": entry.raw_source_manifest_sha256, + "official_checksum_source_manifest_sha256": ( + entry.raw_checksum_source_manifest_sha256 + ), + "normalized_dataset_manifest_sha256": (entry.normalized_dataset_manifest_sha256), + "normalized_parts": [ + { + "write_ordinal": part.write_ordinal, + "rows": part.rows, + "data_sha256": part.data_sha256, + "sidecar_sha256": part.sidecar_sha256, + } + for part in entry.normalized_parts + ], + "quality_report_sha256": entry.quality_report_sha256, + "quality_findings_sha256": entry.quality_findings_sha256, + "quality_errors": entry.quality_errors, + "quality_warnings": entry.quality_warnings, + "research_frame_path": _relative(artifacts.research_path, stage), + "research_frame_sha256": sha256_file(artifacts.research_path), + "evaluation_frame_path": _relative(artifacts.evaluation_path, stage), + "evaluation_frame_sha256": sha256_file(artifacts.evaluation_path), + } + ) + payload["entries"] = rows + encoded = _canonical_json_bytes(payload) + digest = hashlib.sha256(encoded).hexdigest() + path = ( + stage + / "data" + / "normalized_input" + / "_manifests" + / f"m8-development.manifest-{digest[:20]}.json" + ) + _atomic_write_bytes(path, encoded) + if sha256_file(path) != digest: + raise M8PipelineError("development normalized manifest was not durably persisted") + return path, digest + + +def _commit_aggregate_lock( + selections: Sequence[_SelectionArtifacts], + config: M8StudyConfig, + raw_manifest: M8AcquisitionManifest, + development_manifest_path: Path, + development_manifest_sha256: str, + protocol_sha256: str, + source_identity: _SourceIdentity, + stage: Path, +) -> tuple[Path, str]: + ordered = tuple(selections) + if tuple(item.symbol for item in ordered) != config.study.symbols: + raise M8PipelineError("selection locks are not in the frozen symbol order") + for item in ordered: + _restore_lock(item) + _fsync_directory(item.fitted_state_path.parent) + _fsync_directory(item.lock_path.parent) + payload = { + "schema_version": _ANALYSIS_LOCK_SCHEMA_VERSION, + "study": config.study.name, + "protocol_version": config.study.protocol_version, + "protocol_sha256": protocol_sha256, + "config_sha256": config.hash, + "config_source_sha256": config.source_sha256, + "source_identity": source_identity.public_dict(), + "raw_acquisition_manifest_sha256": raw_manifest.sha256, + "raw_evidence_content_identity_sha256": raw_manifest.content_identity_sha256, + "development_manifest_path": _relative(development_manifest_path, stage), + "development_manifest_sha256": development_manifest_sha256, + "development_dates": [ + period.date.isoformat() + for period in config.periods + if period.role in _DEVELOPMENT_ROLES + ], + "declared_test_dates": [ + period.date.isoformat() for period in config.periods if period.role in _TEST_ROLES + ], + "test_data_opened_before_lock": False, + "test_economic_rows_materialized_before_lock": False, + "test_raw_hashes_and_bounded_zip_metadata_verified_before_lock": True, + "selection_metric": config.study.selection_metric, + "target": config.study.target, + "symbols": [ + { + "symbol": item.symbol, + "selected_model": item.selection.selected_model, + "selection_lock_path": _relative(item.lock_path, stage), + "selection_lock_sha256": item.selection.lock.sha256, + "final_fitted_state_path": _relative(item.fitted_state_path, stage), + "final_fitted_state_sha256": item.selection.fitted_state.sha256, + "development_frame_sha256": item.selection.development_frame_sha256, + "validation_comparison_path": _relative(item.comparison_path, stage), + "validation_comparison_rows": item.selection.validation_comparison.height, + } + for item in ordered + ], + "final_fit_policy": ( + "fit selected specification and independent historical prior once on development " + "train+validation before this lock; held-out evaluation restores verified numeric " + "state and performs prediction without fit or update" + ), + "claim_permissions": { + "p_values": False, + "significance": False, + "cross_instrument_pooling": False, + "execution": False, + "profitability": False, + }, + } + encoded = _canonical_json_bytes(payload) + digest = hashlib.sha256(encoded).hexdigest() + lock_path = stage / "analysis" / "analysis_lock.json" + _atomic_write_bytes(lock_path, encoded) + _atomic_write_text( + stage / "analysis" / "analysis_lock.sha256", + f"{digest} analysis_lock.json", + ) + if sha256_file(lock_path) != digest: + raise M8PipelineError("aggregate M8 analysis lock was not durably persisted") + return lock_path, digest + + +def _assert_lock_durable( + lock_path: Path, + lock_sha256: str, + selections: Sequence[_SelectionArtifacts], +) -> Mapping[str, Any]: + aggregate_snapshot = _read_bounded_json_snapshot( + lock_path, + label="M8 aggregate lock", + expected_sha256=lock_sha256, + ensure_ascii=False, + ) + aggregate = aggregate_snapshot.payload + digest_path = lock_path.with_name("analysis_lock.sha256") + expected_line = f"{lock_sha256} analysis_lock.json\n" + _read_exact_bounded_text( + digest_path, + label="M8 aggregate lock digest sidecar", + expected_text=expected_line, + ) + try: + development_relative = aggregate["development_manifest_path"] + development_sha = aggregate["development_manifest_sha256"] + aggregate_symbols = aggregate["symbols"] + except (KeyError, TypeError) as exc: + raise M8PipelineError("M8 aggregate lock payload is invalid before testing") from exc + if type(development_relative) is not str or type(development_sha) is not str: + raise M8PipelineError("M8 aggregate lock development binding is invalid") + stage = lock_path.parent.parent.resolve() + development_path = _published_file( + stage, + development_relative, + "M8 development evidence", + ) + _read_bounded_json_snapshot( + development_path, + label="M8 development evidence", + expected_sha256=development_sha, + ensure_ascii=False, + ) + if not isinstance(aggregate_symbols, list) or len(aggregate_symbols) != len(selections): + raise M8PipelineError("M8 aggregate lock has an invalid symbol-state set") + for raw_symbol, item in zip(aggregate_symbols, selections, strict=True): + if not isinstance(raw_symbol, Mapping) or any( + raw_symbol.get(key) != value + for key, value in { + "symbol": item.symbol, + "selection_lock_path": _relative(item.lock_path, stage), + "selection_lock_sha256": item.selection.lock.sha256, + "final_fitted_state_path": _relative(item.fitted_state_path, stage), + "final_fitted_state_sha256": item.selection.fitted_state.sha256, + "development_frame_sha256": item.selection.development_frame_sha256, + }.items() + ): + raise M8PipelineError( + f"M8 aggregate lock state claims changed before testing for {item.symbol}" + ) + _restore_lock(item) + return aggregate + + +def _verify_completed_lock_chain( + *, + target: Path, + config: M8StudyConfig, + raw_manifest: M8AcquisitionManifest, + source_identity: _SourceIdentity, + protocol_sha256: str, + run_manifest: Mapping[str, Any], + provenance: Mapping[str, Any], +) -> dict[str, str]: + """Rebuild the complete published lock authority from bundle bytes.""" + + provenance_path = provenance.get("selection_lock_path") + provenance_sha = provenance.get("selection_lock_sha256") + if type(provenance_sha) is not str: + raise M8PipelineError("completed provenance lacks the aggregate lock SHA-256") + aggregate_sha = _require_digest(provenance_sha, "completed aggregate lock SHA-256") + + research = run_manifest.get("research") + if not isinstance(research, Mapping): + raise M8PipelineError("completed run manifest lacks its research lock authority") + run_lock = research.get("analysis_lock") + if not isinstance(run_lock, Mapping): + raise M8PipelineError("completed run manifest lacks its aggregate lock claim") + if run_lock.get("committed_before_test_rows_opened") is not True: + raise M8PipelineError("completed run does not claim a pre-test durable lock") + if run_lock.get("path") != provenance_path or run_lock.get("sha256") != aggregate_sha: + raise M8PipelineError("run manifest and provenance aggregate-lock claims differ") + + aggregate_path = _published_file(target, provenance_path, "completed aggregate lock") + aggregate_snapshot = _read_bounded_json_snapshot( + aggregate_path, + label="completed aggregate lock", + expected_sha256=aggregate_sha, + ensure_ascii=False, + ) + aggregate = aggregate_snapshot.payload + digest_path = aggregate_path.with_name("analysis_lock.sha256") + _read_exact_bounded_text( + digest_path, + label="completed aggregate lock digest sidecar", + expected_text=f"{aggregate_sha} analysis_lock.json\n", + ) + expected_claims: dict[str, object] = { + "schema_version": _ANALYSIS_LOCK_SCHEMA_VERSION, + "study": config.study.name, + "protocol_version": config.study.protocol_version, + "protocol_sha256": protocol_sha256, + "config_sha256": config.hash, + "config_source_sha256": config.source_sha256, + "source_identity": source_identity.public_dict(), + "raw_acquisition_manifest_sha256": raw_manifest.sha256, + "raw_evidence_content_identity_sha256": raw_manifest.content_identity_sha256, + "development_dates": [ + period.date.isoformat() + for period in config.periods + if period.role in _DEVELOPMENT_ROLES + ], + "declared_test_dates": [ + period.date.isoformat() for period in config.periods if period.role in _TEST_ROLES + ], + "test_data_opened_before_lock": False, + "test_economic_rows_materialized_before_lock": False, + "selection_metric": config.study.selection_metric, + "target": config.study.target, + } + if any(aggregate.get(key) != value for key, value in expected_claims.items()): + raise M8PipelineError("completed aggregate lock is bound to different authorities") + + development_sha_value = aggregate.get("development_manifest_sha256") + if type(development_sha_value) is not str: + raise M8PipelineError("completed aggregate lock lacks a development-manifest SHA") + development_sha = _require_digest( + development_sha_value, + "completed development manifest SHA-256", + ) + development_path = _published_file( + target, + aggregate.get("development_manifest_path"), + "completed development manifest", + ) + development = _read_bounded_json_snapshot( + development_path, + label="completed development manifest", + expected_sha256=development_sha, + ensure_ascii=False, + ).payload + if ( + development.get("schema_version") != "m8-development-evidence-v1" + or development.get("artifact_kind") != "immutable_development_normalized_manifest" + or development.get("config_sha256") != config.hash + or development.get("config_source_sha256") != config.source_sha256 + or development.get("protocol_version") != config.study.protocol_version + or development.get("test_member_opened") is not False + ): + raise M8PipelineError("completed development manifest has different authority claims") + development_entries = development.get("entries") + expected_development = [ + (symbol, period.date.isoformat(), period.role) + for period in config.periods + if period.role in _DEVELOPMENT_ROLES + for symbol in config.study.symbols + ] + if ( + not isinstance(development_entries, Sequence) + or isinstance(development_entries, (str, bytes)) + or len(development_entries) != len(expected_development) + ): + raise M8PipelineError("completed development manifest has an invalid entry set") + observed_development: list[tuple[object, object, object]] = [] + for entry in development_entries: + if not isinstance(entry, Mapping): + raise M8PipelineError("completed development manifest entry is not an object") + observed_development.append((entry.get("symbol"), entry.get("date"), entry.get("role"))) + if observed_development != expected_development: + raise M8PipelineError("completed development manifest is outside the frozen order") + + raw_symbols = aggregate.get("symbols") + if ( + not isinstance(raw_symbols, Sequence) + or isinstance(raw_symbols, (str, bytes)) + or len(raw_symbols) != len(config.study.symbols) + ): + raise M8PipelineError("completed aggregate lock has an invalid symbol-lock set") + instruments = research.get("instruments") + if not isinstance(instruments, Mapping): + raise M8PipelineError("completed run manifest lacks per-symbol lock claims") + child_paths: list[Path] = [] + state_paths: list[Path] = [] + fitted_state_claims: list[dict[str, str]] = [] + primary_start_ns = _day_bounds_ns( + next(period.date for period in config.periods if period.role == "primary_test") + )[0] + for raw_symbol, expected_symbol in zip(raw_symbols, config.study.symbols, strict=True): + if not isinstance(raw_symbol, Mapping) or raw_symbol.get("symbol") != expected_symbol: + raise M8PipelineError("completed child locks are outside the frozen symbol order") + child_sha_value = raw_symbol.get("selection_lock_sha256") + if type(child_sha_value) is not str: + raise M8PipelineError(f"completed {expected_symbol} lock lacks its SHA-256") + child_sha = _require_digest( + child_sha_value, + f"completed {expected_symbol} selection lock SHA-256", + ) + child_path = _published_file( + target, + raw_symbol.get("selection_lock_path"), + f"completed {expected_symbol} selection lock", + ) + child_paths.append(child_path) + child = _restore_analysis_lock_file( + child_path, + child_sha, + f"completed {expected_symbol} selection lock", + ).payload() + state_sha_value = raw_symbol.get("final_fitted_state_sha256") + if type(state_sha_value) is not str: + raise M8PipelineError(f"completed {expected_symbol} state lacks its SHA-256") + state_sha = _require_digest( + state_sha_value, + f"completed {expected_symbol} final fitted-state SHA-256", + ) + state_path = _published_file( + target, + raw_symbol.get("final_fitted_state_path"), + f"completed {expected_symbol} final fitted state", + ) + state_paths.append(state_path) + state = _restore_fitted_state_file( + state_path, + state_sha, + f"completed {expected_symbol} final fitted state", + ) + state_payload = state.payload() + selected = child.get("selected_candidate") + instrument = instruments.get(expected_symbol) + if ( + not isinstance(selected, Mapping) + or not isinstance(instrument, Mapping) + or selected.get("name") != raw_symbol.get("selected_model") + or instrument.get("selected_model") != raw_symbol.get("selected_model") + or instrument.get("selection_lock_sha256") != child_sha + or instrument.get("final_fitted_state_path") + != raw_symbol.get("final_fitted_state_path") + or instrument.get("final_fitted_state_sha256") != state_sha + or child.get("development_frame_sha256") != raw_symbol.get("development_frame_sha256") + or child.get("final_fitted_state_sha256") != state_sha + or child.get("final_fitted_state") != state_payload + or state_payload.get("development_frame_sha256") + != raw_symbol.get("development_frame_sha256") + or state_payload.get("feature_columns") != list(_trade_feature_columns(config)) + or state_payload.get("target") != config.study.target + or type(state_payload.get("fit_cutoff_ts_ns")) is not int + or cast(int, state_payload["fit_cutoff_ts_ns"]) >= primary_start_ns + or child.get("selection_metric") != config.study.selection_metric + or child.get("target") != config.study.target + or child.get("train_dates") + != [period.date.isoformat() for period in config.periods if period.role == "train"] + or child.get("validation_date") + != next( + period.date.isoformat() for period in config.periods if period.role == "validation" + ) + or child.get("declared_test_dates") != expected_claims["declared_test_dates"] + or child.get("test_rows_accessed_during_selection") is not False + ): + raise M8PipelineError( + f"completed {expected_symbol} selection lock claims are inconsistent" + ) + fitted_state_claims.append( + { + "symbol": expected_symbol, + "path": cast(str, raw_symbol["final_fitted_state_path"]), + "sha256": state_sha, + } + ) + if len(set(child_paths)) != len(child_paths): + raise M8PipelineError("completed aggregate lock reuses a child selection lock") + if len(set(state_paths)) != len(state_paths): + raise M8PipelineError("completed aggregate lock reuses a final fitted-state artifact") + if ( + provenance.get("final_fitted_states") != fitted_state_claims + or research.get("final_fitted_states") != fitted_state_claims + ): + raise M8PipelineError("completed final fitted-state claims differ across authorities") + + artifacts = run_manifest.get("artifacts") + if not isinstance(artifacts, Mapping): + raise M8PipelineError("completed run manifest lacks its artifact index") + research_manifest_path = _published_file( + target, + artifacts.get("research_manifest"), + "completed research manifest", + ) + research_manifest = _read_json_object(research_manifest_path, "completed research manifest") + if ( + research_manifest.get("selection_lock_path") != provenance_path + or research_manifest.get("selection_lock_sha256") != aggregate_sha + or research_manifest.get("final_fitted_states") != fitted_state_claims + ): + raise M8PipelineError("completed research manifest names a different aggregate lock") + return {claim["symbol"]: claim["sha256"] for claim in fitted_state_claims} + + +def _verify_insufficient_failure_taxonomy( + failure: Mapping[str, Any], + config: M8StudyConfig, +) -> bool: + """Validate the stable failure code/stage/role contract without parsing reason text.""" + + if failure.get("schema_version") != "m8-insufficient-data-v1": + raise M8PipelineError("INSUFFICIENT_DATA failure schema is invalid") + reason_value = failure.get("reason") + reason_code_value = failure.get("reason_code") + stage_value = failure.get("failure_stage") + role_value = failure.get("failed_role") + if type(reason_value) is not str or not reason_value.strip(): + raise M8PipelineError("INSUFFICIENT_DATA diagnostic reason is invalid") + if ( + type(stage_value) is not str + or type(reason_code_value) is not str + or type(role_value) is not str + ): + raise M8PipelineError("INSUFFICIENT_DATA typed failure fields are malformed") + stage = stage_value + reason_code = reason_code_value + role = role_value + contract: tuple[bool, frozenset[str], frozenset[str]] | None = _FAILURE_STAGE_CONTRACT.get( + stage + ) + if contract is None: + raise M8PipelineError("INSUFFICIENT_DATA failure stage is not recognized") + expected_after_lock, expected_reason_codes, allowed_roles = contract + if reason_code not in expected_reason_codes or role not in allowed_roles: + raise M8PipelineError("INSUFFICIENT_DATA reason code/stage/role are inconsistent") + if failure.get("failed_after_analysis_lock") is not expected_after_lock: + raise M8PipelineError("INSUFFICIENT_DATA failure stage disagrees with lock state") + + symbol = failure.get("failed_symbol") + study_date = failure.get("failed_date") + if role in _DEVELOPMENT_ROLES or role in _TEST_ROLES: + if symbol not in config.study.symbols or not any( + period.date.isoformat() == study_date and period.role == role + for period in config.periods + ): + raise M8PipelineError("INSUFFICIENT_DATA failed symbol/date/role is undeclared") + elif stage == "final_manifest": + if symbol != "STUDY" or study_date != "all_dates" or role != "study": + raise M8PipelineError("INSUFFICIENT_DATA final-manifest identity is invalid") + elif stage == "locked_evaluation": + if ( + symbol not in config.study.symbols + or study_date != "locked_evaluation" + or role != "all_test_dates" + ): + raise M8PipelineError("INSUFFICIENT_DATA locked-evaluation identity is invalid") + else: + raise M8PipelineError("INSUFFICIENT_DATA failure identity is invalid") + return bool(expected_after_lock) + + +def _verify_insufficient_lock_chain( + *, + target: Path, + inventory: Mapping[str, _FailureEvidenceItem], + config: M8StudyConfig, + raw_manifest: M8AcquisitionManifest, + bundled_raw_sha256: str, + source_identity: _SourceIdentity, + protocol_sha256: str, + failure: Mapping[str, Any], + provenance: Mapping[str, Any], + run_manifest: Mapping[str, Any], +) -> None: + """Rebuild a failed bundle's lock authority, or prove it failed before locking.""" + + failed_after_lock = _verify_insufficient_failure_taxonomy(failure, config) + expected_authorities: Mapping[str, object] = { + "config_sha256": config.hash, + "config_source_sha256": config.source_sha256, + "protocol_version": config.study.protocol_version, + "protocol_sha256": protocol_sha256, + "raw_acquisition_manifest_sha256": raw_manifest.sha256, + "bundled_raw_acquisition_manifest_sha256": bundled_raw_sha256, + "raw_evidence_content_identity_sha256": raw_manifest.content_identity_sha256, + } + for key, expected in expected_authorities.items(): + if failure.get(key) != expected or provenance.get(key) != expected: + raise M8PipelineError(f"INSUFFICIENT_DATA failure/provenance have a different {key}") + if ( + failure.get("source_identity") != source_identity.public_dict() + or provenance.get("git") != source_identity.public_dict() + ): + raise M8PipelineError("INSUFFICIENT_DATA failure/provenance source claims differ") + if failure.get("generated_at_utc") != provenance.get("generated_at_utc"): + raise M8PipelineError("INSUFFICIENT_DATA failure/provenance timestamps differ") + if ( + run_manifest.get("status") != "INSUFFICIENT_DATA" + or run_manifest.get("evidence_scope") != M8_EVIDENCE_SCOPE + ): + raise M8PipelineError("INSUFFICIENT_DATA run manifest has inconsistent status") + artifacts = run_manifest.get("artifacts") + research = run_manifest.get("research") + data_claims = run_manifest.get("data") + if ( + not isinstance(artifacts, Mapping) + or not isinstance(research, Mapping) + or not isinstance(data_claims, Mapping) + ): + raise M8PipelineError("INSUFFICIENT_DATA run manifest lacks lock authority sections") + evidence_claim = failure.get("failed_normalization_evidence") + evidence_completion = ( + evidence_claim.get("evidence_completion") if isinstance(evidence_claim, Mapping) else None + ) + if ( + provenance.get("failure_reason_code") != failure.get("reason_code") + or data_claims.get("failure_reason_code") != failure.get("reason_code") + or provenance.get("failed_normalization_evidence_completion") != evidence_completion + or data_claims.get("failed_normalization_evidence_completion") != evidence_completion + ): + raise M8PipelineError("INSUFFICIENT_DATA typed failure claims differ across records") + if artifacts.get("failure") != "failure.json" or artifacts.get( + "raw_acquisition_manifest" + ) != provenance.get("bundled_raw_acquisition_manifest_path"): + raise M8PipelineError("INSUFFICIENT_DATA run artifact claims differ from provenance") + + selection_symbols = failure.get("selection_completed_symbols") + selection_locks = failure.get("selection_locks") + if ( + not isinstance(selection_symbols, Sequence) + or isinstance(selection_symbols, (str, bytes)) + or not isinstance(selection_locks, Sequence) + or isinstance(selection_locks, (str, bytes)) + or any(type(symbol) is not str for symbol in selection_symbols) + ): + raise M8PipelineError("INSUFFICIENT_DATA selection progress is malformed") + selection_symbols_list = list(selection_symbols) + raw_fitted_state_claims = failure.get("final_fitted_states") + if ( + not isinstance(raw_fitted_state_claims, Sequence) + or isinstance(raw_fitted_state_claims, (str, bytes)) + or provenance.get("final_fitted_states") != raw_fitted_state_claims + or research.get("final_fitted_states") != raw_fitted_state_claims + ): + raise M8PipelineError("INSUFFICIENT_DATA final fitted-state claims are malformed") + fitted_state_claims = list(raw_fitted_state_claims) + if len(fitted_state_claims) != len(selection_symbols_list) or any( + not isinstance(claim, Mapping) or claim.get("symbol") != expected_symbol + for claim, expected_symbol in zip( + fitted_state_claims, + selection_symbols_list, + strict=True, + ) + ): + raise M8PipelineError("INSUFFICIENT_DATA fitted states are outside the frozen order") + primary_start_ns = _day_bounds_ns( + next(period.date for period in config.periods if period.role == "primary_test") + )[0] + expected_selection_started = failed_after_lock or failure.get("failure_stage") == ( + "model_selection" + ) + if ( + failure.get("selection_started") is not expected_selection_started + or failure.get("aggregate_lock_committed") is not failed_after_lock + or failure.get("selection_completed_symbol_count") != len(selection_symbols_list) + or selection_symbols_list != list(config.study.symbols[: len(selection_symbols_list)]) + or len(selection_locks) != len(selection_symbols_list) + or research.get("selection_started") is not expected_selection_started + or research.get("aggregate_lock_committed") is not failed_after_lock + or research.get("selection_completed_symbols") != selection_symbols_list + or research.get("selection_completed_symbol_count") != len(selection_symbols_list) + ): + raise M8PipelineError("INSUFFICIENT_DATA selection progress claims are inconsistent") + if failed_after_lock and selection_symbols_list != list(config.study.symbols): + raise M8PipelineError("post-lock INSUFFICIENT_DATA lacks both completed selections") + if not expected_selection_started and selection_symbols_list: + raise M8PipelineError("pre-selection INSUFFICIENT_DATA claims completed selections") + if failure.get("failure_stage") == "model_selection" and ( + len(selection_symbols_list) >= len(config.study.symbols) + or failure.get("failed_symbol") != config.study.symbols[len(selection_symbols_list)] + ): + raise M8PipelineError("selection failure progress disagrees with the failed symbol") + + evaluation_symbols = failure.get("endpoint_evaluation_completed_symbols") + if ( + not isinstance(evaluation_symbols, Sequence) + or isinstance(evaluation_symbols, (str, bytes)) + or any(type(symbol) is not str for symbol in evaluation_symbols) + ): + raise M8PipelineError("INSUFFICIENT_DATA endpoint progress is malformed") + evaluation_symbols_list = list(evaluation_symbols) + expected_evaluation_started = failure.get("failure_stage") == "locked_evaluation" + endpoint_claims: Mapping[str, object] = { + "endpoint_evaluation_performed": expected_evaluation_started, + "endpoint_evaluation_started": expected_evaluation_started, + "endpoint_evaluation_completed": False, + "endpoint_artifacts_published": False, + "endpoint_evaluation_completed_symbols": evaluation_symbols_list, + "endpoint_evaluation_completed_symbol_count": len(evaluation_symbols_list), + } + if ( + evaluation_symbols_list != list(config.study.symbols[: len(evaluation_symbols_list)]) + or (not expected_evaluation_started and evaluation_symbols_list) + or len(evaluation_symbols_list) >= len(config.study.symbols) + or any(failure.get(key) != value for key, value in endpoint_claims.items()) + or any(research.get(key) != value for key, value in endpoint_claims.items()) + ): + raise M8PipelineError("INSUFFICIENT_DATA endpoint progress claims are inconsistent") + if ( + expected_evaluation_started + and failure.get("failed_symbol") != config.study.symbols[len(evaluation_symbols_list)] + ): + raise M8PipelineError("locked-evaluation progress disagrees with the failed symbol") + + if not failed_after_lock: + if ( + failure.get("analysis_lock") is not None + or failure.get("analysis_lock_path") is not None + or failure.get("analysis_lock_sha256") is not None + or provenance.get("selection_lock_path") is not None + or provenance.get("selection_lock_sha256") is not None + or research.get("analysis_lock") is not None + or "analysis_lock" in artifacts + ): + raise M8PipelineError("pre-lock INSUFFICIENT_DATA result contains a lock claim") + if failure.get("held_out_member_opened") is not False: + raise M8PipelineError("pre-lock INSUFFICIENT_DATA lacks the held-out-open denial") + if (target / "analysis" / "analysis_lock.json").exists() or ( + target / "analysis" / "analysis_lock.sha256" + ).exists(): + raise M8PipelineError("pre-lock INSUFFICIENT_DATA contains an aggregate lock") + partial_paths: list[Path] = [] + partial_state_paths: list[Path] = [] + for lock_claim, state_claim, expected_symbol in zip( + selection_locks, + fitted_state_claims, + selection_symbols_list, + strict=True, + ): + if ( + not isinstance(lock_claim, Mapping) + or not isinstance(state_claim, Mapping) + or lock_claim.get("symbol") != expected_symbol + ): + raise M8PipelineError("partial selection locks are outside the frozen order") + lock_sha_value = lock_claim.get("sha256") + if type(lock_sha_value) is not str: + raise M8PipelineError(f"partial {expected_symbol} lock lacks its SHA-256") + lock_sha = _require_digest( + lock_sha_value, + f"partial {expected_symbol} selection lock SHA-256", + ) + lock_relative = _canonical_inventory_child( + lock_claim.get("path"), + f"partial {expected_symbol} selection lock", + ) + lock_path = _published_file( + target, + lock_relative, + f"partial {expected_symbol} selection lock", + ) + partial_paths.append(lock_path) + child = _restore_inventory_analysis_lock_file( + target=target, + inventory=inventory, + relative_path=lock_relative, + expected_sha256=lock_sha, + label=f"partial {expected_symbol} selection lock", + ).payload() + state_sha_value = state_claim.get("sha256") + if type(state_sha_value) is not str: + raise M8PipelineError(f"partial {expected_symbol} state lacks its SHA-256") + state_sha = _require_digest( + state_sha_value, + f"partial {expected_symbol} fitted-state SHA-256", + ) + if ( + lock_claim.get("final_fitted_state_path") != state_claim.get("path") + or lock_claim.get("final_fitted_state_sha256") != state_sha + ): + raise M8PipelineError(f"partial {expected_symbol} lock and state claims differ") + state_relative = _canonical_inventory_child( + state_claim.get("path"), + f"partial {expected_symbol} final fitted state", + ) + state_path = _published_file( + target, + state_relative, + f"partial {expected_symbol} final fitted state", + ) + partial_state_paths.append(state_path) + state = _restore_inventory_fitted_state_file( + target=target, + inventory=inventory, + relative_path=state_relative, + expected_sha256=state_sha, + label=f"partial {expected_symbol} final fitted state", + ) + state_payload = state.payload() + if ( + child.get("selection_metric") != config.study.selection_metric + or child.get("target") != config.study.target + or child.get("final_fitted_state_sha256") != state_sha + or child.get("final_fitted_state") != state_payload + or state_payload.get("development_frame_sha256") + != child.get("development_frame_sha256") + or state_payload.get("feature_columns") != list(_trade_feature_columns(config)) + or state_payload.get("target") != config.study.target + or type(state_payload.get("fit_cutoff_ts_ns")) is not int + or cast(int, state_payload["fit_cutoff_ts_ns"]) >= primary_start_ns + or child.get("train_dates") + != [period.date.isoformat() for period in config.periods if period.role == "train"] + or child.get("validation_date") + != next( + period.date.isoformat() + for period in config.periods + if period.role == "validation" + ) + or child.get("declared_test_dates") + != [ + period.date.isoformat() + for period in config.periods + if period.role in _TEST_ROLES + ] + or child.get("test_rows_accessed_during_selection") is not False + ): + raise M8PipelineError( + f"partial {expected_symbol} selection lock claims are inconsistent" + ) + if len(set(partial_paths)) != len(partial_paths): + raise M8PipelineError("pre-lock failure reuses a partial child selection lock") + if len(set(partial_state_paths)) != len(partial_state_paths): + raise M8PipelineError("pre-lock failure reuses a partial fitted-state artifact") + return + + failure_path = failure.get("analysis_lock_path") + failure_sha_value = failure.get("analysis_lock_sha256") + provenance_path = provenance.get("selection_lock_path") + provenance_sha_value = provenance.get("selection_lock_sha256") + if type(failure_sha_value) is not str or type(provenance_sha_value) is not str: + raise M8PipelineError("post-lock INSUFFICIENT_DATA lacks aggregate lock digests") + failure_sha = _require_digest(failure_sha_value, "failed aggregate lock SHA-256") + provenance_sha = _require_digest(provenance_sha_value, "provenance aggregate lock SHA-256") + if failure_path != provenance_path or failure_sha != provenance_sha: + raise M8PipelineError("failure and provenance aggregate-lock claims differ") + if artifacts.get("analysis_lock") != failure_path: + raise M8PipelineError("failure and run manifest aggregate-lock paths differ") + run_lock = research.get("analysis_lock") + if ( + not isinstance(run_lock, Mapping) + or run_lock.get("path") != failure_path + or run_lock.get("sha256") != failure_sha + or run_lock.get("committed_before_test_rows_opened") is not True + ): + raise M8PipelineError("failure run manifest has a different aggregate lock claim") + + aggregate_relative = _canonical_inventory_child(failure_path, "failed aggregate lock") + aggregate_snapshot = _read_inventory_bounded_json_snapshot( + target=target, + inventory=inventory, + relative_path=aggregate_relative, + label="failed aggregate lock", + expected_sha256=failure_sha, + ensure_ascii=False, + ) + aggregate = aggregate_snapshot.payload + digest_relative = Path(aggregate_relative).with_name("analysis_lock.sha256").as_posix() + _read_inventory_exact_bounded_text( + target=target, + inventory=inventory, + relative_path=digest_relative, + label="failed aggregate lock digest sidecar", + expected_text=f"{failure_sha} analysis_lock.json\n", + ) + expected_lock_claims: Mapping[str, object] = { + "schema_version": _ANALYSIS_LOCK_SCHEMA_VERSION, + "study": config.study.name, + "protocol_version": config.study.protocol_version, + "protocol_sha256": protocol_sha256, + "config_sha256": config.hash, + "config_source_sha256": config.source_sha256, + "source_identity": source_identity.public_dict(), + "raw_acquisition_manifest_sha256": raw_manifest.sha256, + "raw_evidence_content_identity_sha256": raw_manifest.content_identity_sha256, + "development_dates": [ + period.date.isoformat() + for period in config.periods + if period.role in _DEVELOPMENT_ROLES + ], + "declared_test_dates": [ + period.date.isoformat() for period in config.periods if period.role in _TEST_ROLES + ], + "test_data_opened_before_lock": False, + "test_economic_rows_materialized_before_lock": False, + "test_raw_hashes_and_bounded_zip_metadata_verified_before_lock": True, + "selection_metric": config.study.selection_metric, + "target": config.study.target, + } + if any(aggregate.get(key) != value for key, value in expected_lock_claims.items()): + raise M8PipelineError("failed aggregate lock is bound to different authorities") + + development_sha_value = aggregate.get("development_manifest_sha256") + if type(development_sha_value) is not str: + raise M8PipelineError("failed aggregate lock lacks a development-manifest SHA") + development_sha = _require_digest( + development_sha_value, + "failed development manifest SHA-256", + ) + development_relative = _canonical_inventory_child( + aggregate.get("development_manifest_path"), + "failed development manifest", + ) + development = _read_inventory_bounded_json_snapshot( + target=target, + inventory=inventory, + relative_path=development_relative, + label="failed development manifest", + expected_sha256=development_sha, + ensure_ascii=False, + ).payload + if ( + development.get("schema_version") != "m8-development-evidence-v1" + or development.get("artifact_kind") != "immutable_development_normalized_manifest" + or development.get("config_sha256") != config.hash + or development.get("config_source_sha256") != config.source_sha256 + or development.get("protocol_version") != config.study.protocol_version + or development.get("test_member_opened") is not False + ): + raise M8PipelineError("failed development manifest has different authority claims") + development_entries = development.get("entries") + expected_development = [ + (symbol, period.date.isoformat(), period.role) + for period in config.periods + if period.role in _DEVELOPMENT_ROLES + for symbol in config.study.symbols + ] + if ( + not isinstance(development_entries, Sequence) + or isinstance(development_entries, (str, bytes)) + or len(development_entries) != len(expected_development) + ): + raise M8PipelineError("failed development manifest has an invalid entry set") + observed_development: list[tuple[object, object, object]] = [] + for entry in development_entries: + if not isinstance(entry, Mapping): + raise M8PipelineError("failed development manifest entry is not an object") + observed_development.append((entry.get("symbol"), entry.get("date"), entry.get("role"))) + if observed_development != expected_development: + raise M8PipelineError("failed development manifest is outside the frozen order") + + raw_symbols = aggregate.get("symbols") + failure_locks = selection_locks + if ( + not isinstance(raw_symbols, Sequence) + or isinstance(raw_symbols, (str, bytes)) + or not isinstance(failure_locks, Sequence) + or isinstance(failure_locks, (str, bytes)) + or len(raw_symbols) != len(config.study.symbols) + or len(failure_locks) != len(config.study.symbols) + ): + raise M8PipelineError("failed result has an invalid child-lock set") + child_paths: list[Path] = [] + state_paths: list[Path] = [] + for raw_symbol, failure_lock, state_claim, expected_symbol in zip( + raw_symbols, + failure_locks, + fitted_state_claims, + config.study.symbols, + strict=True, + ): + if ( + not isinstance(raw_symbol, Mapping) + or not isinstance(failure_lock, Mapping) + or not isinstance(state_claim, Mapping) + or raw_symbol.get("symbol") != expected_symbol + or failure_lock.get("symbol") != expected_symbol + ): + raise M8PipelineError("failed child locks are outside the frozen symbol order") + child_path_value = raw_symbol.get("selection_lock_path") + child_sha_value = raw_symbol.get("selection_lock_sha256") + if type(child_sha_value) is not str: + raise M8PipelineError(f"failed {expected_symbol} lock lacks its SHA-256") + child_sha = _require_digest( + child_sha_value, + f"failed {expected_symbol} selection lock SHA-256", + ) + if failure_lock.get("path") != child_path_value or failure_lock.get("sha256") != child_sha: + raise M8PipelineError( + f"failure and aggregate {expected_symbol} child-lock claims differ" + ) + child_relative = _canonical_inventory_child( + child_path_value, + f"failed {expected_symbol} selection lock", + ) + child_path = _published_file( + target, + child_relative, + f"failed {expected_symbol} selection lock", + ) + child_paths.append(child_path) + child = _restore_inventory_analysis_lock_file( + target=target, + inventory=inventory, + relative_path=child_relative, + expected_sha256=child_sha, + label=f"failed {expected_symbol} selection lock", + ).payload() + state_sha_value = raw_symbol.get("final_fitted_state_sha256") + if type(state_sha_value) is not str: + raise M8PipelineError(f"failed {expected_symbol} state lacks its SHA-256") + state_sha = _require_digest( + state_sha_value, + f"failed {expected_symbol} final fitted-state SHA-256", + ) + if ( + raw_symbol.get("final_fitted_state_path") != state_claim.get("path") + or state_claim.get("sha256") != state_sha + or failure_lock.get("final_fitted_state_path") != state_claim.get("path") + or failure_lock.get("final_fitted_state_sha256") != state_sha + ): + raise M8PipelineError(f"failed {expected_symbol} final fitted-state claims differ") + state_relative = _canonical_inventory_child( + state_claim.get("path"), + f"failed {expected_symbol} final fitted state", + ) + state_path = _published_file( + target, + state_relative, + f"failed {expected_symbol} final fitted state", + ) + state_paths.append(state_path) + state = _restore_inventory_fitted_state_file( + target=target, + inventory=inventory, + relative_path=state_relative, + expected_sha256=state_sha, + label=f"failed {expected_symbol} final fitted state", + ) + state_payload = state.payload() + selected = child.get("selected_candidate") + if ( + not isinstance(selected, Mapping) + or selected.get("name") != raw_symbol.get("selected_model") + or child.get("development_frame_sha256") != raw_symbol.get("development_frame_sha256") + or child.get("final_fitted_state_sha256") != state_sha + or child.get("final_fitted_state") != state_payload + or state_payload.get("development_frame_sha256") + != raw_symbol.get("development_frame_sha256") + or state_payload.get("feature_columns") != list(_trade_feature_columns(config)) + or state_payload.get("target") != config.study.target + or type(state_payload.get("fit_cutoff_ts_ns")) is not int + or cast(int, state_payload["fit_cutoff_ts_ns"]) >= primary_start_ns + or child.get("selection_metric") != config.study.selection_metric + or child.get("target") != config.study.target + or child.get("train_dates") + != [period.date.isoformat() for period in config.periods if period.role == "train"] + or child.get("validation_date") + != next( + period.date.isoformat() for period in config.periods if period.role == "validation" + ) + or child.get("declared_test_dates") != expected_lock_claims["declared_test_dates"] + or child.get("test_rows_accessed_during_selection") is not False + ): + raise M8PipelineError( + f"failed {expected_symbol} selection lock claims are inconsistent" + ) + if len(set(child_paths)) != len(child_paths): + raise M8PipelineError("failed aggregate lock reuses a child selection lock") + if len(set(state_paths)) != len(state_paths): + raise M8PipelineError("failed aggregate lock reuses a fitted-state artifact") + + +def _restore_lock(selection: _SelectionArtifacts) -> AnalysisLock: + lock = _restore_analysis_lock_file( + selection.lock_path, + selection.selection.lock.sha256, + f"persisted {selection.symbol} selection lock", + ) + lock_payload = lock.payload() + state = _restore_fitted_state_file( + selection.fitted_state_path, + selection.selection.fitted_state.sha256, + f"persisted {selection.symbol} final fitted state", + ) + if ( + state != selection.selection.fitted_state + or lock_payload.get("final_fitted_state_sha256") != state.sha256 + or lock_payload.get("final_fitted_state") != state.payload() + ): + raise M8PipelineError( + f"persisted lock and final fitted state disagree for {selection.symbol}" + ) + return lock + + +def _array_sha256(values: NDArray[np.int64]) -> str: + normalized = np.asarray(values, dtype=" dict[str, object]: + plan = result.plan + return { + "contract": ( + "date-local features/labels; train predicts validation; locked selected/prior fit " + "once on train+validation; primary and replication tests receive no update" + ), + "folds": [ + { + "fold_id": fold.fold_id, + "train_rows": int(fold.train_indices.size), + "validation_rows": int(fold.validation_indices.size), + "train_indices_sha256": _array_sha256(fold.train_indices), + "validation_indices_sha256": _array_sha256(fold.validation_indices), + "train_start_ts_ns": fold.train_start_ts_ns, + "train_end_ts_ns": fold.train_end_ts_ns, + "validation_start_ts_ns": fold.validation_start_ts_ns, + "validation_end_ts_ns": fold.validation_end_ts_ns, + "purged_rows": fold.purged_rows, + "embargoed_time_buckets": fold.embargoed_time_buckets, + } + for fold in plan.folds + ], + "final_train_rows": int(plan.final_train_indices.size), + "test_rows": int(plan.test_indices.size), + "final_train_indices_sha256": _array_sha256(plan.final_train_indices), + "test_indices_sha256": _array_sha256(plan.test_indices), + "test_start_ts_ns": plan.test_start_ts_ns, + "test_end_ts_ns": plan.test_end_ts_ns, + "decision_time_count": plan.decision_time_count, + "test_used_for_selection": False, + "model_updated_between_test_dates": False, + } + + +def _predictive_metric_rows( + result: LockedMultiDateTestResult, + config: M8StudyConfig, +) -> tuple[Mapping[str, object], ...]: + predictions = result.predictions + rows: list[Mapping[str, object]] = [] + dates = sorted(str(value) for value in predictions.get_column("study_date").unique()) + for study_date in dates: + current = predictions.filter(pl.col("study_date") == study_date) + y_true = current.get_column("y_true").to_numpy().astype(np.int64, copy=False) + period_start = int(cast(int, current.get_column("decision_ts_ns").min())) + period_end = int(cast(int, current.get_column("decision_ts_ns").max())) + study_role = str(current.get_column("study_role")[0]) + symbol = str(current.get_column("symbol")[0]) + specifications = ( + ( + "selected", + result.selected_model, + "selected_probability", + str(current.get_column("selected_fit_status")[0]), + int(current.get_column("selected_fit_cutoff_ts_ns")[0]), + "validation_log_loss", + ), + ( + "historical_prior", + "historical_prior", + "prior_probability", + str(current.get_column("prior_fit_status")[0]), + int(current.get_column("prior_fit_cutoff_ts_ns")[0]), + "predeclared_baseline", + ), + ) + for role, model, probability_column, fit_status, cutoff, selected_on in specifications: + probability = ( + current.get_column(probability_column).to_numpy().astype(np.float64, copy=False) + ) + metrics = classification_metrics( + y_true, + probability, + calibration_bins=config.study.feature_stability_bins, + ) + rows.append( + { + "symbol": symbol, + "instrument": symbol, + "study_date": study_date, + "study_role": study_role, + "test_phase": str(current.get_column("test_phase")[0]), + "model_role": role, + "model": model, + "locked_selected_model": result.selected_model, + "horizon_events": config.study.label_horizon_events, + "split": "final_test", + "n_obs": current.height, + "period_start_ts_ns": period_start, + "period_end_ts_ns": period_end, + "period_start_utc": _utc_from_ns(period_start), + "period_end_utc": _utc_from_ns(period_end), + "fit_status": fit_status, + "fit_cutoff_ts_ns": cutoff, + "selected_on": selected_on, + "selection_lock_sha256": result.lock_sha256, + "test_used_for_selection": False, + "model_updated_between_test_dates": False, + "significance_claim_authorized": False, + **metrics, + } + ) + return tuple(rows) + + +def _endpoint_status(result: LockedMultiDateTestResult) -> str: + per_date = result.paired_log_loss.per_date.sort("study_date") + if result.paired_log_loss.aggregate.status != "ok" or per_date.height < 2: + return "insufficient_data" + favorable = [bool(value) for value in per_date.get_column("point_favorable").to_list()] + if all(favorable): + return "supported" + if any(favorable): + return "mixed" + return "failed" + + +def _loss_direction(value: float) -> str: + if not math.isfinite(value): + return "insufficient_data" + if value < 0.0: + return "favorable" + if value > 0.0: + return "unfavorable" + return "tied" + + +def _three_period_direction_summary( + selection: _SelectionArtifacts, + paired_dates: pl.DataFrame, +) -> dict[str, object]: + """Publish the frozen validation→primary→replication direction diagnostic.""" + + comparison = selection.selection.validation_comparison + selected = comparison.filter(pl.col("selected_on_validation")) + prior = comparison.filter(pl.col("requested_model") == "historical_prior") + primary = paired_dates.filter(pl.col("study_role") == "primary_test") + replication = paired_dates.filter(pl.col("study_role") == "replication_test") + if selected.height != 1 or prior.height != 1 or primary.height != 1 or replication.height != 1: + return { + "validation_primary_replication_status": "insufficient_data", + "direction_consistent_across_validation_primary_replication": False, + "favorable_across_validation_primary_replication": False, + } + + validation_selected = float(selected.get_column("log_loss")[0]) + validation_prior = float(prior.get_column("log_loss")[0]) + validation_delta = validation_selected - validation_prior + primary_delta = float(primary.get_column("point_delta")[0]) + replication_delta = float(replication.get_column("point_delta")[0]) + values = (validation_delta, primary_delta, replication_delta) + directions = tuple(_loss_direction(value) for value in values) + sufficient = all(direction != "insufficient_data" for direction in directions) + consistent = sufficient and len(set(directions)) == 1 + favorable = sufficient and all(direction == "favorable" for direction in directions) + if not sufficient: + status = "insufficient_data" + elif favorable: + status = "supported" + elif consistent and directions[0] in {"unfavorable", "tied"}: + status = "failed" + else: + status = "mixed" + return { + "validation_date": selection.selection.validation_date, + "validation_selected_log_loss": validation_selected, + "validation_prior_log_loss": validation_prior, + "validation_point_delta": validation_delta, + "validation_direction": directions[0], + "primary_date": str(primary.get_column("study_date")[0]), + "primary_point_delta": primary_delta, + "primary_direction": directions[1], + "replication_date": str(replication.get_column("study_date")[0]), + "replication_point_delta": replication_delta, + "replication_direction": directions[2], + "direction_consistent_across_validation_primary_replication": consistent, + "favorable_across_validation_primary_replication": favorable, + "validation_primary_replication_status": status, + } + + +def _training_only_stability( + development_frames: Sequence[pl.DataFrame], + test_frames: Sequence[pl.DataFrame], + *, + feature_columns: Sequence[str], + bins: int, + lock_sha256: str, +) -> pl.DataFrame: + train_candidates = [ + frame + for frame in development_frames + if set(str(value) for value in frame.get_column("study_role").unique()) == {"train"} + ] + if len(train_candidates) != 1: + raise ResearchDataError("feature stability requires exactly one frozen training date") + reference = train_candidates[0].filter(pl.col("feature_ready") & (~pl.col("right_censored"))) + if reference.is_empty(): + raise ResearchDataError("feature stability training reference is empty") + outputs: list[pl.DataFrame] = [] + for frame in test_frames: + comparison = frame.filter(pl.col("feature_ready") & (~pl.col("right_censored"))) + if comparison.is_empty(): + raise ResearchDataError("feature stability test comparison is empty") + study_date = str(comparison.get_column("study_date")[0]) + role = str(comparison.get_column("study_role")[0]) + outputs.append( + feature_stability_summary( + reference, + comparison, + feature_columns=feature_columns, + group_columns=("symbol",), + bins=bins, + ).with_columns( + pl.lit(str(reference.get_column("study_date")[0])).alias("reference_study_date"), + pl.lit("train_only").alias("reference_role"), + pl.lit(study_date).alias("comparison_study_date"), + pl.lit(role).alias("comparison_study_role"), + pl.lit("primary" if role == "primary_test" else "replication").alias("test_phase"), + pl.lit(True).alias("reference_bins_fit_without_test"), + pl.lit(lock_sha256).alias("selection_lock_sha256"), + ) + ) + return pl.concat(outputs, how="vertical").sort("comparison_study_date", "symbol", "feature") + + +def _evaluate_symbol( + symbol: str, + selection: _SelectionArtifacts, + development: Sequence[_DateArtifacts], + tests: Sequence[_DateArtifacts], + config: M8StudyConfig, + stage: Path, +) -> _EvaluationArtifacts: + development_frames = tuple(_load_evaluation(item.evaluation_path) for item in development) + test_frames = tuple(_load_evaluation(item.evaluation_path) for item in tests) + restored = _restore_lock(selection) + result = evaluate_locked_multidate_tests(development_frames, test_frames, restored) + if result.lock_sha256 != selection.selection.lock.sha256: + raise M8PipelineError(f"locked evaluation returned a different lock for {symbol}") + if result.predictions.filter(pl.col("model_updated_between_test_dates")).height: + raise M8PipelineError(f"locked M8 model updated during test dates for {symbol}") + expected_dates = tuple( + period.date.isoformat() for period in config.periods if period.role in _TEST_ROLES + ) + observed_dates = tuple( + sorted(str(value) for value in result.predictions["study_date"].unique()) + ) + if observed_dates != expected_dates: + raise M8PipelineError(f"locked predictions omit or add a test date for {symbol}") + + model_root = stage / "models" / symbol.lower() + predictions = result.predictions.with_columns( + pl.lit(symbol).alias("instrument"), + pl.lit(config.study.label_horizon_events).alias("horizon_events"), + pl.lit("selected_and_historical_prior_only").alias("prediction_scope"), + pl.lit(False).alias("execution_claim_authorized"), + pl.lit(False).alias("profitability_claim_authorized"), + ) + predictions_path = model_root / "selected_and_prior_test_predictions.parquet" + predictions_path.parent.mkdir(parents=True, exist_ok=True) + predictions.write_parquet(predictions_path, compression="zstd", statistics=True) + for item in tests: + date_path = model_root / item.study_date / "selected_and_prior_predictions.parquet" + date_path.parent.mkdir(parents=True, exist_ok=True) + predictions.filter(pl.col("study_date") == item.study_date).write_parquet( + date_path, + compression="zstd", + statistics=True, + ) + + status = _endpoint_status(result) + paired = result.paired_log_loss.per_date.with_columns( + pl.lit(symbol).alias("symbol"), + pl.lit(symbol).alias("instrument"), + pl.lit(result.selected_model).alias("selected_model"), + pl.lit("historical_prior").alias("baseline"), + pl.lit(status).alias("instrument_status"), + pl.lit(result.lock_sha256).alias("selection_lock_sha256"), + pl.lit(False).alias("p_value_computed"), + pl.lit(False).alias("significance_claim_authorized"), + ) + paired_date_path = stage / "metrics" / symbol.lower() / "paired_log_loss_by_date.parquet" + paired_date_path.parent.mkdir(parents=True, exist_ok=True) + paired.write_parquet(paired_date_path, compression="zstd", statistics=True) + + aggregate = result.paired_log_loss.aggregate + direction_summary = _three_period_direction_summary(selection, paired) + aggregate_row: dict[str, object] = { + "symbol": symbol, + "instrument": symbol, + "selected_model": result.selected_model, + "baseline": "historical_prior", + "metric": "log_loss", + "delta_definition": "selected_model_minus_historical_prior", + "date_weighting": "equal", + "point_delta": aggregate.point_estimate, + "ci_low": aggregate.lower, + "ci_high": aggregate.upper, + "n_obs": int(cast(int, paired.get_column("n_obs").sum())), + "n_dates": paired.height, + "n_blocks": aggregate.n_blocks, + "samples": aggregate.n_bootstrap, + "seed": aggregate.seed, + "bootstrap_status": aggregate.status, + "block_width_events": config.study.bootstrap_block_events, + "status": status, + "replication_status": result.paired_log_loss.replication_status, + "directionally_replicated": status == "supported", + "selection_lock_sha256": result.lock_sha256, + "p_value": None, + "p_value_computed": False, + "h0_rejected": False, + "significance_claim_authorized": False, + "cross_instrument_pooling": False, + "execution_claim_authorized": False, + "profitability_claim_authorized": False, + **direction_summary, + } + + stability = _training_only_stability( + development_frames, + test_frames, + feature_columns=_trade_feature_columns(config), + bins=config.study.feature_stability_bins, + lock_sha256=result.lock_sha256, + ) + stability_path = stage / "analysis" / symbol.lower() / "feature_stability.parquet" + stability_path.parent.mkdir(parents=True, exist_ok=True) + stability.write_parquet(stability_path, compression="zstd", statistics=True) + plan_path = stage / "research" / symbol.lower() / "walk_forward_plan.json" + _write_json(plan_path, _plan_payload(result)) + return _EvaluationArtifacts( + symbol=symbol, + selected_model=result.selected_model, + predictions_path=predictions_path, + paired_date_path=paired_date_path, + stability_path=stability_path, + plan_path=plan_path, + predictive_rows=_predictive_metric_rows(result, config), + paired_date_rows=tuple(cast(Mapping[str, object], row) for row in paired.to_dicts()), + aggregate_row=aggregate_row, + ) + + +def _combine_parquet(paths: Sequence[Path], destination: Path) -> None: + if not paths: + raise M8PipelineError(f"cannot create empty combined Parquet artifact: {destination}") + destination.parent.mkdir(parents=True, exist_ok=True) + lazy = pl.concat([pl.scan_parquet(path) for path in paths], how="vertical_relaxed") + lazy.sink_parquet(destination, compression="zstd", statistics=True, maintain_order=True) + + +def _publish_evaluation_artifacts( + evaluations: Sequence[_EvaluationArtifacts], + evaluation_stage: Path, + stage: Path, +) -> tuple[_EvaluationArtifacts, ...]: + """Publish endpoint files only after every symbol evaluates successfully.""" + + published: list[_EvaluationArtifacts] = [] + + def publish(path: Path) -> Path: + try: + relative = path.resolve().relative_to(evaluation_stage.resolve()) + except ValueError as exc: + raise M8PipelineError("evaluation artifact escaped its isolated staging root") from exc + destination = stage / relative + if destination.exists(): + raise M8PipelineError(f"endpoint publication would overwrite: {destination}") + _atomic_copy_exact( + path, + destination, + expected_sha256=sha256_file(path), + expected_bytes=path.stat().st_size, + ) + return destination + + for item in evaluations: + published.append( + _EvaluationArtifacts( + symbol=item.symbol, + selected_model=item.selected_model, + predictions_path=publish(item.predictions_path), + paired_date_path=publish(item.paired_date_path), + stability_path=publish(item.stability_path), + plan_path=publish(item.plan_path), + predictive_rows=item.predictive_rows, + paired_date_rows=item.paired_date_rows, + aggregate_row=item.aggregate_row, + ) + ) + shutil.rmtree(evaluation_stage) + return tuple(published) + + +def _write_reports(stage: Path) -> None: + bundle = load_run_bundle(stage, require_complete=False, verify_integrity=False) + report_root = stage / "reports" + _atomic_write_text(report_root / "technical_report.md", render_technical_report(bundle)) + _atomic_write_text(report_root / "executive_memo.md", render_executive_memo(bundle)) + _atomic_write_text( + report_root / "model_comparison.md", + render_model_comparison_report(bundle), + ) + + +def _final_fitted_state_claims( + selections: Sequence[_SelectionArtifacts], + stage: Path, +) -> list[dict[str, str]]: + return [ + { + "symbol": item.symbol, + "path": _relative(item.fitted_state_path, stage), + "sha256": item.selection.fitted_state.sha256, + } + for item in selections + ] + + +def _final_fitted_state_sha256_by_symbol( + selections: Sequence[_SelectionArtifacts], +) -> dict[str, str]: + return {item.symbol: item.selection.fitted_state.sha256 for item in selections} + + +def _run_key( + config: M8StudyConfig, + raw_manifest: M8AcquisitionManifest, + normalized_manifest: M8InputManifest, + protocol: Mapping[str, object], + source: _SourceIdentity, + final_fitted_state_sha256_by_symbol: Mapping[str, str], +) -> tuple[str, dict[str, object]]: + inputs: dict[str, object] = { + "pipeline_schema_version": M8_PIPELINE_SCHEMA_VERSION, + "study": config.study.name, + "protocol_version": config.study.protocol_version, + "config_sha256": config.hash, + "config_source_sha256": config.source_sha256, + "raw_acquisition_manifest_sha256": raw_manifest.sha256, + "raw_evidence_content_identity_sha256": raw_manifest.content_identity_sha256, + "normalized_input_manifest_sha256": normalized_manifest.sha256, + "protocol_sha256": protocol["protocol_sha256"], + "final_fitted_state_sha256_by_symbol": dict(final_fitted_state_sha256_by_symbol), + "git": source.public_dict(), + "seed": config.study.seed, + "evidence_scope": M8_EVIDENCE_SCOPE, + } + return _stable_sha256(inputs), inputs + + +def _quality_payload( + manifest: M8InputManifest, + date_artifacts: Sequence[_DateArtifacts], + *, + generated_at_utc: str, +) -> dict[str, object]: + summaries = [dict(item.summary) for item in date_artifacts] + return { + "generated_at_utc": generated_at_utc, + "dataset": "m8_complete_binance_daily_aggregate_trades", + "rows_checked": sum(entry.rows for entry in manifest.entries), + "summary": {"errors": 0, "warnings": 0}, + "all_eight_archives_complete": True, + "raw_acquisition_manifest_and_hashes_verified_before_economic_reads": True, + "final_normalized_manifest_verified_before_endpoint_evaluation": True, + "date_local_continuity_resets_verified": True, + "aggregate_trade_ids_contiguous_within_each_symbol_date": True, + "availability_clock_nondecreasing": True, + "availability_basis": "exchange_event_time_proxy_plus_trade_id_tie_break", + "local_receipt_time_available": False, + "per_symbol_date": summaries, + "source_values_repaired": False, + "mutation_policy": "questionable observations are never silently repaired", + } + + +def _normalization_evidence_claim(entry: M8ArchiveEntry) -> dict[str, object]: + """Serialize one complete normalization without treating it as accepted study input.""" + + return { + "symbol": entry.symbol, + "date": entry.date.isoformat(), + "role": entry.role, + "rows": entry.rows, + "raw_zip_sha256": entry.raw_zip_sha256, + "normalized_dataset_manifest_sha256": entry.normalized_dataset_manifest_sha256, + "quality_errors": entry.quality_errors, + "quality_warnings": entry.quality_warnings, + } + + +def _failed_normalization_evidence_payload( + stage: Path, + failure: _TypedInsufficientFailure, +) -> dict[str, object] | None: + """Bind the exact failed symbol/date subtree with a typed completion state.""" + + kind = failure.normalization_failure_kind + completion = failure.normalization_evidence_completion + complete_entry = failure.normalization_completed_evidence + if kind is None or completion is None: + if complete_entry is not None: + raise M8PipelineError("non-normalization failure retained a normalization entry") + return None + + normalized_prefix = f"data/normalized_input/normalized/{failure.symbol}/{failure.study_date}" + quality_prefix = f"data/normalized_input/quality/{failure.symbol}/{failure.study_date}" + scoped_roots = (stage / normalized_prefix, stage / quality_prefix) + files: list[Path] = [] + for root in scoped_roots: + if root.is_symlink(): + raise M8PipelineError("failed normalization evidence root is a symbolic link") + if not root.exists(): + continue + if not root.is_dir(): + raise M8PipelineError("failed normalization evidence root is not a directory") + for path in root.rglob("*"): + mode = path.lstat().st_mode + if stat.S_ISLNK(mode) or (not stat.S_ISDIR(mode) and not stat.S_ISREG(mode)): + raise M8PipelineError("failed normalization evidence is not a regular tree") + if stat.S_ISREG(mode): + files.append(path) + artifacts = [ + { + "path": path.relative_to(stage).as_posix(), + "sha256": sha256_file(path), + "bytes": path.stat().st_size, + } + for path in sorted(files) + ] + scoped_paths = {cast(str, item["path"]) for item in artifacts} + dataset_manifests = { + path + for path in scoped_paths + if Path(path).parent.as_posix() == f"{normalized_prefix}/_manifests" + and re.fullmatch(r"trades\.manifest-[0-9a-f]{20}\.json", Path(path).name) + } + report_path = f"{quality_prefix}/report.json" + findings_path = f"{quality_prefix}/findings.jsonl" + if completion == "PARTIAL_STREAM": + if kind != "PAYLOAD_OR_CONTINUITY" or complete_entry is not None: + raise M8PipelineError("partial failed normalization has an invalid typed state") + if dataset_manifests or report_path in scoped_paths or findings_path in scoped_paths: + raise M8PipelineError("partial failed normalization contains final evidence") + normalization_claim: dict[str, object] | None = None + else: + if kind not in {"QUALITY_GATE", "POSTWRITE_CONSISTENCY"}: + raise M8PipelineError("complete failed normalization has an invalid typed state") + if len(dataset_manifests) != 1 or not {report_path, findings_path}.issubset(scoped_paths): + raise M8PipelineError("complete failed normalization lacks final evidence") + if kind == "QUALITY_GATE": + if complete_entry is None: + raise M8PipelineError("quality-gate failure lacks its structured evidence") + normalization_claim = _normalization_evidence_claim(complete_entry) + else: + if complete_entry is not None: + raise M8PipelineError("postwrite failure unexpectedly claims accepted evidence") + normalization_claim = None + + return { + "schema_version": "m8-failed-normalization-evidence-v1", + "failure_kind": kind, + "evidence_completion": completion, + "normalized_prefix": normalized_prefix, + "quality_prefix": quality_prefix, + "artifacts": artifacts, + "complete_normalization": normalization_claim, + } + + +def _assert_test_open_authority( + *, + config: M8StudyConfig, + project_root: Path, + source_identity: _SourceIdentity, + protocol_sha256: str, + authority_manifest: M8AcquisitionManifest, + stage_manifest: M8AcquisitionManifest, + aggregate_lock_path: Path, + aggregate_lock_sha256: str, + selections: Sequence[_SelectionArtifacts], +) -> None: + """Revalidate all immutable authorities at the actual member-open boundary.""" + + aggregate = _assert_lock_durable( + aggregate_lock_path, + aggregate_lock_sha256, + selections, + ) + expected_lock_claims: dict[str, object] = { + "protocol_version": config.study.protocol_version, + "protocol_sha256": protocol_sha256, + "config_sha256": config.hash, + "config_source_sha256": config.source_sha256, + "raw_acquisition_manifest_sha256": authority_manifest.sha256, + "raw_evidence_content_identity_sha256": authority_manifest.content_identity_sha256, + "source_identity": source_identity.public_dict(), + "test_data_opened_before_lock": False, + "test_economic_rows_materialized_before_lock": False, + } + if any(aggregate.get(key) != value for key, value in expected_lock_claims.items()): + raise M8PipelineError("aggregate lock authority claims changed before held-out open") + _verify_config_source(config) + if sha256_file(_protocol_source(project_root)) != protocol_sha256: + raise M8PipelineError("frozen M8 protocol changed before held-out member open") + current_source = _capture_source_identity(project_root) + if ( + current_source != source_identity + or current_source.dirty + or re.fullmatch(r"[0-9a-f]{40}|[0-9a-f]{64}", current_source.commit) is None + ): + raise M8PipelineError("Git/source-tree identity changed before held-out member open") + observed_authority = _load_raw_manifest( + config, + authority_manifest.path, + authority_manifest.sha256, + ) + try: + observed_stage = read_m8_acquisition_manifest( + stage_manifest.path, + expected_sha256=stage_manifest.sha256, + config=config, + ) + except Exception as exc: + raise M8PipelineError( + f"bundled raw acquisition evidence changed before held-out member open: {exc}" + ) from exc + if ( + observed_authority.total_accepted_zip_bytes != observed_stage.total_accepted_zip_bytes + or observed_authority.total_raw_evidence_bytes != observed_stage.total_raw_evidence_bytes + or observed_authority.content_identity_sha256 != observed_stage.content_identity_sha256 + or observed_stage.copied_from_manifest_sha256 != authority_manifest.sha256 + or observed_authority.protocol_document_sha256 != protocol_sha256 + or observed_stage.protocol_document_sha256 != protocol_sha256 + ): + raise M8PipelineError( + "bundled raw evidence differs from the explicit acquisition authority" + ) + + +def _publish_insufficient_data( + *, + config: M8StudyConfig, + stage: Path, + project_root: Path, + source_identity: _SourceIdentity, + protocol: Mapping[str, object], + authority_manifest: M8AcquisitionManifest, + stage_manifest: M8AcquisitionManifest, + selections: Sequence[_SelectionArtifacts], + aggregate_lock_path: Path, + aggregate_lock_sha256: str, + completed_entries: Sequence[M8ArchiveEntry], + failure: _TypedInsufficientFailure, + generated_at_utc: str, + final_manifest: M8InputManifest | None = None, + endpoint_evaluation_started: bool = False, + completed_evaluation_symbols: Sequence[str] = (), +) -> None: + """Finalize a terminal, immutable failed-result bundle after lock exposure.""" + + _assert_lock_durable(aggregate_lock_path, aggregate_lock_sha256, selections) + final_fitted_state_claims = _final_fitted_state_claims(selections, stage) + _verify_config_source(config) + if sha256_file(_protocol_source(project_root)) != protocol["protocol_sha256"]: + raise M8PipelineError("protocol changed while preserving insufficient-data evidence") + if _capture_source_identity(project_root) != source_identity: + raise M8PipelineError("source identity changed while preserving insufficient-data evidence") + forbidden = ( + stage / "models" / "predictions.parquet", + stage / "metrics" / "predictive_metrics.json", + stage / "metrics" / "hypothesis_evaluation.json", + stage / "metrics" / "paired_log_loss_by_date.parquet", + stage / "metrics" / "equal_date_hypothesis.parquet", + ) + if any(path.exists() for path in forbidden): + raise M8PipelineError("endpoint artifacts exist in an insufficient-data attempt") + if any(path.is_file() for path in stage.rglob("*prediction*")): + raise M8PipelineError("prediction artifacts exist in an insufficient-data attempt") + declared_order = [ + (symbol, period.date.isoformat(), period.role) + for period in config.periods + for symbol in config.study.symbols + ] + completed = [ + { + "symbol": entry.symbol, + "date": entry.date.isoformat(), + "role": entry.role, + "rows": entry.rows, + "raw_zip_sha256": entry.raw_zip_sha256, + "normalized_dataset_manifest_sha256": (entry.normalized_dataset_manifest_sha256), + "quality_errors": entry.quality_errors, + "quality_warnings": entry.quality_warnings, + } + for entry in completed_entries + ] + failed_key = next( + ( + item + for item in declared_order + if item[0] == failure.symbol and item[1] == failure.study_date + ), + None, + ) + failed_index = ( + declared_order.index(failed_key) if failed_key is not None else len(declared_order) + ) + stopped_before = [ + {"symbol": symbol, "date": study_date, "role": role} + for symbol, study_date, role in declared_order[failed_index + 1 :] + ] + failed_normalization_evidence = _failed_normalization_evidence_payload(stage, failure) + failure_payload = { + "schema_version": "m8-insufficient-data-v1", + "status": "INSUFFICIENT_DATA", + "terminal": True, + "generated_at_utc": generated_at_utc, + "reason": failure.reason, + "reason_code": failure.reason_code, + "failure_stage": failure.failure_stage, + "failed_symbol": failure.symbol, + "failed_date": failure.study_date, + "failed_role": failure.failed_role, + "failed_normalization_evidence": failed_normalization_evidence, + "failed_after_analysis_lock": True, + "replacement_date_selected": False, + "reselection_performed": False, + "endpoint_evaluation_performed": endpoint_evaluation_started, + "endpoint_evaluation_started": endpoint_evaluation_started, + "endpoint_evaluation_completed": False, + "endpoint_artifacts_published": False, + "endpoint_evaluation_completed_symbols": list(completed_evaluation_symbols), + "endpoint_evaluation_completed_symbol_count": len(completed_evaluation_symbols), + "predictions_published": False, + "config_sha256": config.hash, + "config_source_sha256": config.source_sha256, + "protocol_version": config.study.protocol_version, + "protocol_sha256": protocol["protocol_sha256"], + "raw_acquisition_manifest_sha256": authority_manifest.sha256, + "bundled_raw_acquisition_manifest_sha256": stage_manifest.sha256, + "raw_evidence_content_identity_sha256": (authority_manifest.content_identity_sha256), + "source_identity": source_identity.public_dict(), + "analysis_lock_path": _relative(aggregate_lock_path, stage), + "analysis_lock_sha256": aggregate_lock_sha256, + "aggregate_lock_committed": True, + "selection_started": True, + "selection_completed_symbols": [selection.symbol for selection in selections], + "selection_completed_symbol_count": len(selections), + "selection_locks": [ + { + "symbol": selection.symbol, + "path": _relative(selection.lock_path, stage), + "sha256": selection.selection.lock.sha256, + "final_fitted_state_path": _relative( + selection.fitted_state_path, + stage, + ), + "final_fitted_state_sha256": selection.selection.fitted_state.sha256, + } + for selection in selections + ], + "final_fitted_states": final_fitted_state_claims, + "completed_normalizations": completed, + "stopped_before": stopped_before, + "final_all_date_normalized_manifest": ( + None + if final_manifest is None + else { + "path": _relative(final_manifest.path, stage), + "sha256": final_manifest.sha256, + } + ), + } + _write_json(stage / "failure.json", failure_payload) + resolved = config.public_dict() + resolved.update( + { + "effective_evidence_tier": "INSUFFICIENT_DATA", + "evidence_scope": M8_EVIDENCE_SCOPE, + "protocol": dict(protocol), + "raw_acquisition_manifest_sha256": authority_manifest.sha256, + "execution_status": "NOT_RUN", + } + ) + _write_json(stage / "resolved_config.json", resolved) + provenance = { + "generated_at_utc": generated_at_utc, + "status": "INSUFFICIENT_DATA", + "failure_reason_code": failure.reason_code, + "failed_normalization_evidence_completion": (failure.normalization_evidence_completion), + "config_sha256": config.hash, + "config_source_sha256": config.source_sha256, + "raw_acquisition_manifest_path": str(authority_manifest.path.resolve()), + "raw_acquisition_manifest_sha256": authority_manifest.sha256, + "bundled_raw_acquisition_manifest_path": _relative(stage_manifest.path, stage), + "bundled_raw_acquisition_manifest_sha256": stage_manifest.sha256, + "raw_evidence_content_identity_sha256": authority_manifest.content_identity_sha256, + "raw_evidence_byte_budget": { + "external_total": authority_manifest.total_raw_evidence_bytes, + "bundle_copy_total": stage_manifest.total_raw_evidence_bytes, + "combined_total": ( + authority_manifest.total_raw_evidence_bytes + + stage_manifest.total_raw_evidence_bytes + ), + "ceiling": config.study.max_total_download_bytes, + }, + "protocol_sha256": protocol["protocol_sha256"], + "protocol_version": config.study.protocol_version, + "selection_lock_path": _relative(aggregate_lock_path, stage), + "selection_lock_sha256": aggregate_lock_sha256, + "final_fitted_states": final_fitted_state_claims, + "git": source_identity.public_dict(), + "runtime": runtime_metadata(), + "pipeline_schema_version": M8_PIPELINE_SCHEMA_VERSION, + } + _write_json(stage / "provenance.json", provenance) + run_manifest = { + "schema_version": M8_PIPELINE_SCHEMA_VERSION, + "run_id": config.study.name, + "status": "INSUFFICIENT_DATA", + "evidence_tier": "INSUFFICIENT_DATA", + "evidence_scope": M8_EVIDENCE_SCOPE, + "data": { + "mode": "binance_spot_daily_aggtrades_trade_only", + "symbols": list(config.study.symbols), + "all_requested_ranges_complete": False, + "completed_normalizations": completed, + "failure_reason_code": failure.reason_code, + "failed_normalization_evidence_completion": (failure.normalization_evidence_completion), + "failed_symbol": failure.symbol, + "failed_date": failure.study_date, + "stopped_before": stopped_before, + }, + "artifacts": { + "failure": "failure.json", + "analysis_lock": _relative(aggregate_lock_path, stage), + "raw_acquisition_manifest": _relative(stage_manifest.path, stage), + "resolved_config": "resolved_config.json", + }, + "research": { + "scope": "trade_only", + "analysis_lock": { + "path": _relative(aggregate_lock_path, stage), + "sha256": aggregate_lock_sha256, + "committed_before_test_rows_opened": True, + }, + "aggregate_lock_committed": True, + "selection_started": True, + "selection_completed_symbols": [selection.symbol for selection in selections], + "selection_completed_symbol_count": len(selections), + "final_fitted_states": final_fitted_state_claims, + "endpoint_status": "insufficient_data", + "endpoint_evaluation_performed": endpoint_evaluation_started, + "endpoint_evaluation_started": endpoint_evaluation_started, + "endpoint_evaluation_completed": False, + "endpoint_artifacts_published": False, + "endpoint_evaluation_completed_symbols": list(completed_evaluation_symbols), + "endpoint_evaluation_completed_symbol_count": len(completed_evaluation_symbols), + "reselection_performed": False, + "replacement_date_selected": False, + "instruments": { + symbol: { + "status": "insufficient_data", + "validation_primary_replication_status": "insufficient_data", + } + for symbol in config.study.symbols + }, + }, + "execution_assumptions": { + "status": "NOT_RUN", + "reason": M8_EXECUTION_EXCLUSION_REASON, + "pnl_calculated": False, + "fills_calculated": False, + "capacity_calculated": False, + "profitability_claim_authorized": False, + }, + } + _write_json(stage / "run_manifest.json", run_manifest) + _atomic_write_text( + stage / "reports" / "insufficient_data.md", + ( + "# M8 study result: INSUFFICIENT_DATA\n\n" + f"The predeclared {failure.symbol}/{failure.study_date} archive failed the frozen " + f"data contract after the analysis lock: {failure.reason}\n\n" + "No replacement date or reselection occurred. No prediction or endpoint artifact " + "was published; any staged evaluation work was discarded. No execution, P&L, or " + "significance result was published.\n" + ), + ) + inventory = [ + { + "path": path.relative_to(stage).as_posix(), + "sha256": sha256_file(path), + "bytes": path.stat().st_size, + } + for path in sorted(stage.rglob("*")) + if path.is_file() + ] + _write_json(stage / "data" / "failure_evidence_inventory.json", inventory) + _fsync_tree(stage) + write_checksum_manifest(stage) + _create_terminal_marker(stage / "INSUFFICIENT_DATA", "terminal") + + +def _publish_prelock_insufficient_data( + *, + config: M8StudyConfig, + stage: Path, + project_root: Path, + source_identity: _SourceIdentity, + protocol: Mapping[str, object], + authority_manifest: M8AcquisitionManifest, + stage_manifest: M8AcquisitionManifest, + completed_entries: Sequence[M8ArchiveEntry], + failure: _TypedInsufficientFailure, + generated_at_utc: str, + partial_selections: Sequence[_SelectionArtifacts] = (), +) -> None: + """Preserve a deterministic declared-data failure before model locking.""" + + _verify_config_source(config) + if sha256_file(_protocol_source(project_root)) != protocol["protocol_sha256"]: + raise M8PipelineError("protocol changed while preserving pre-lock failure evidence") + if _capture_source_identity(project_root) != source_identity: + raise M8PipelineError("source changed while preserving pre-lock failure evidence") + declared = [ + (symbol, period.date.isoformat(), period.role) + for period in config.periods + for symbol in config.study.symbols + ] + failed_key = next( + (item for item in declared if item[0] == failure.symbol and item[1] == failure.study_date), + None, + ) + failed_index = declared.index(failed_key) if failed_key is not None else -1 + completed = [ + { + "symbol": entry.symbol, + "date": entry.date.isoformat(), + "role": entry.role, + "rows": entry.rows, + "raw_zip_sha256": entry.raw_zip_sha256, + "normalized_dataset_manifest_sha256": entry.normalized_dataset_manifest_sha256, + "quality_errors": entry.quality_errors, + "quality_warnings": entry.quality_warnings, + } + for entry in completed_entries + ] + selection_started = failure.failure_stage == "model_selection" + completed_selection_symbols = [item.symbol for item in partial_selections] + if ( + completed_selection_symbols and not selection_started + ) or completed_selection_symbols != list( + config.study.symbols[: len(completed_selection_symbols)] + ): + raise M8PipelineError("pre-lock partial selections are outside the frozen order") + final_fitted_state_claims = _final_fitted_state_claims(partial_selections, stage) + stopped_before = [ + {"symbol": symbol, "date": study_date, "role": role} + for symbol, study_date, role in declared[failed_index + 1 :] + ] + failed_normalization_evidence = _failed_normalization_evidence_payload(stage, failure) + failure_payload = { + "schema_version": "m8-insufficient-data-v1", + "status": "INSUFFICIENT_DATA", + "terminal": True, + "generated_at_utc": generated_at_utc, + "reason": failure.reason, + "reason_code": failure.reason_code, + "failure_stage": failure.failure_stage, + "failed_symbol": failure.symbol, + "failed_date": failure.study_date, + "failed_role": failure.failed_role, + "failed_normalization_evidence": failed_normalization_evidence, + "failed_after_analysis_lock": False, + "held_out_member_opened": False, + "analysis_lock": None, + "analysis_lock_path": None, + "analysis_lock_sha256": None, + "aggregate_lock_committed": False, + "selection_started": selection_started, + "selection_completed_symbols": completed_selection_symbols, + "selection_completed_symbol_count": len(completed_selection_symbols), + "selection_locks": [ + { + "symbol": selection.symbol, + "path": _relative(selection.lock_path, stage), + "sha256": selection.selection.lock.sha256, + "final_fitted_state_path": _relative( + selection.fitted_state_path, + stage, + ), + "final_fitted_state_sha256": selection.selection.fitted_state.sha256, + } + for selection in partial_selections + ], + "final_fitted_states": final_fitted_state_claims, + "replacement_date_selected": False, + "reselection_performed": False, + "endpoint_evaluation_performed": False, + "endpoint_evaluation_started": False, + "endpoint_evaluation_completed": False, + "endpoint_artifacts_published": False, + "endpoint_evaluation_completed_symbols": [], + "endpoint_evaluation_completed_symbol_count": 0, + "predictions_published": False, + "config_sha256": config.hash, + "config_source_sha256": config.source_sha256, + "protocol_version": config.study.protocol_version, + "protocol_sha256": protocol["protocol_sha256"], + "raw_acquisition_manifest_sha256": authority_manifest.sha256, + "bundled_raw_acquisition_manifest_sha256": stage_manifest.sha256, + "raw_evidence_content_identity_sha256": (authority_manifest.content_identity_sha256), + "source_identity": source_identity.public_dict(), + "completed_normalizations": completed, + "stopped_before": stopped_before, + "final_all_date_normalized_manifest": None, + } + _write_json(stage / "failure.json", failure_payload) + resolved = config.public_dict() + resolved.update( + { + "effective_evidence_tier": "INSUFFICIENT_DATA", + "evidence_scope": M8_EVIDENCE_SCOPE, + "protocol": dict(protocol), + "raw_acquisition_manifest_sha256": authority_manifest.sha256, + "execution_status": "NOT_RUN", + } + ) + _write_json(stage / "resolved_config.json", resolved) + _write_json( + stage / "provenance.json", + { + "generated_at_utc": generated_at_utc, + "status": "INSUFFICIENT_DATA", + "failure_reason_code": failure.reason_code, + "failed_normalization_evidence_completion": (failure.normalization_evidence_completion), + "config_sha256": config.hash, + "config_source_sha256": config.source_sha256, + "raw_acquisition_manifest_path": str(authority_manifest.path.resolve()), + "raw_acquisition_manifest_sha256": authority_manifest.sha256, + "bundled_raw_acquisition_manifest_path": _relative(stage_manifest.path, stage), + "bundled_raw_acquisition_manifest_sha256": stage_manifest.sha256, + "raw_evidence_content_identity_sha256": (authority_manifest.content_identity_sha256), + "raw_evidence_byte_budget": { + "external_total": authority_manifest.total_raw_evidence_bytes, + "bundle_copy_total": stage_manifest.total_raw_evidence_bytes, + "combined_total": ( + authority_manifest.total_raw_evidence_bytes + + stage_manifest.total_raw_evidence_bytes + ), + "ceiling": config.study.max_total_download_bytes, + }, + "protocol_sha256": protocol["protocol_sha256"], + "protocol_version": config.study.protocol_version, + "selection_lock_path": None, + "selection_lock_sha256": None, + "final_fitted_states": final_fitted_state_claims, + "git": source_identity.public_dict(), + "runtime": runtime_metadata(), + "pipeline_schema_version": M8_PIPELINE_SCHEMA_VERSION, + }, + ) + _write_json( + stage / "run_manifest.json", + { + "schema_version": M8_PIPELINE_SCHEMA_VERSION, + "run_id": config.study.name, + "status": "INSUFFICIENT_DATA", + "evidence_tier": "INSUFFICIENT_DATA", + "evidence_scope": M8_EVIDENCE_SCOPE, + "data": { + "all_requested_ranges_complete": False, + "completed_normalizations": completed, + "failure_reason_code": failure.reason_code, + "failed_normalization_evidence_completion": ( + failure.normalization_evidence_completion + ), + "failed_symbol": failure.symbol, + "failed_date": failure.study_date, + "stopped_before": stopped_before, + }, + "artifacts": { + "failure": "failure.json", + "raw_acquisition_manifest": _relative(stage_manifest.path, stage), + "resolved_config": "resolved_config.json", + }, + "research": { + "scope": "trade_only", + "analysis_lock": None, + "aggregate_lock_committed": False, + "selection_started": selection_started, + "selection_completed_symbols": completed_selection_symbols, + "selection_completed_symbol_count": len(completed_selection_symbols), + "final_fitted_states": final_fitted_state_claims, + "endpoint_status": "insufficient_data", + "endpoint_evaluation_performed": False, + "endpoint_evaluation_started": False, + "endpoint_evaluation_completed": False, + "endpoint_artifacts_published": False, + "endpoint_evaluation_completed_symbols": [], + "endpoint_evaluation_completed_symbol_count": 0, + }, + "execution_assumptions": { + "status": "NOT_RUN", + "reason": M8_EXECUTION_EXCLUSION_REASON, + "pnl_calculated": False, + "fills_calculated": False, + "capacity_calculated": False, + "profitability_claim_authorized": False, + }, + }, + ) + _atomic_write_text( + stage / "reports" / "insufficient_data.md", + ( + "# M8 study result: INSUFFICIENT_DATA\n\n" + f"The predeclared {failure.symbol}/{failure.study_date} input failed before the " + f"analysis lock: {failure.reason}\n\n" + + ( + "Candidate selection began and completed for " + f"{', '.join(completed_selection_symbols) or 'no symbol'}, but no aggregate " + "lock was committed. " + if selection_started + else "No candidate selection or aggregate lock was created. " + ) + + ( + "No held-out member, replacement date, prediction, endpoint publication, " + "execution, P&L, or significance result was produced.\n" + ) + ), + ) + inventory = [ + { + "path": path.relative_to(stage).as_posix(), + "sha256": sha256_file(path), + "bytes": path.stat().st_size, + } + for path in sorted(stage.rglob("*")) + if path.is_file() + ] + _write_json(stage / "data" / "failure_evidence_inventory.json", inventory) + _fsync_tree(stage) + write_checksum_manifest(stage) + _create_terminal_marker(stage / "INSUFFICIENT_DATA", "terminal") + + +def _produce_m8( + config: M8StudyConfig, + authority_manifest: M8AcquisitionManifest, + stage: Path, + project_root: Path, + source_identity: _SourceIdentity, +) -> tuple[M8RunStatus, str | None]: + if stage.exists() and any(stage.iterdir()): + raise M8PipelineError("M8 staging directory must be empty") + stage.mkdir(parents=True, exist_ok=True) + protocol = _freeze_protocol_and_config(config, project_root, stage) + if authority_manifest.protocol_document_sha256 != protocol["protocol_sha256"]: + raise M8PipelineError("raw acquisition manifest is bound to another protocol document") + evidence_root = stage / "data" + raw_input_root = evidence_root / "input" + normalized_input_root = evidence_root / "normalized_input" + planned_copy_bytes = authority_manifest.total_raw_evidence_bytes + combined_raw_evidence_bytes = authority_manifest.total_raw_evidence_bytes + planned_copy_bytes + if combined_raw_evidence_bytes > config.study.max_total_download_bytes: + raise M8PipelineError( + "external raw evidence plus the distinct bundle copy exceeds the frozen total-byte " + "ceiling" + ) + try: + raw_manifest = copy_m8_acquisition_into(authority_manifest, raw_input_root) + except Exception as exc: + raise M8PipelineError(f"cannot freeze raw acquisition evidence into run: {exc}") from exc + if ( + raw_manifest.copied_from_manifest_sha256 != authority_manifest.sha256 + or raw_manifest.content_identity_sha256 != authority_manifest.content_identity_sha256 + or raw_manifest.total_raw_evidence_bytes != authority_manifest.total_raw_evidence_bytes + ): + raise M8PipelineError("bundled raw evidence is not an exact semantic copy of authority") + generated_at = utc_now_iso() + metadata = tuple( + _normalized_metadata(raw_manifest.metadata_for(symbol)) for symbol in config.study.symbols + ) + metadata_by_symbol = {item.symbol: item for item in metadata} + entries: list[M8ArchiveEntry] = [] + + date_artifacts: dict[tuple[str, str], _DateArtifacts] = {} + # Phase 1: stream-normalize and research only the two development dates for + # both instruments. No held-out CSV member is opened in this loop. + for period in config.periods: + if period.role not in _DEVELOPMENT_ROLES: + continue + for symbol in config.study.symbols: + descriptor = raw_manifest.archive_descriptor_for(symbol, period.date) + try: + acquired = descriptor.reconstruct() + except M8AcquisitionError as exc: + if _caused_by_system_fault(exc): + raise + failure = _typed_failure( + M8InsufficientDataError(symbol, period.date.isoformat(), str(exc)), + reason_code="RAW_ARCHIVE_INTEGRITY", + failure_stage="development_acquisition", + failed_role=period.role, + ) + _publish_prelock_insufficient_data( + config=config, + stage=stage, + project_root=project_root, + source_identity=source_identity, + protocol=protocol, + authority_manifest=authority_manifest, + stage_manifest=raw_manifest, + completed_entries=entries, + failure=failure, + generated_at_utc=generated_at, + ) + return "INSUFFICIENT_DATA", None + try: + normalized = normalize_m8_archive( + config, + period, + metadata_by_symbol[symbol], + acquired, + raw_input_root, + output_root=normalized_input_root, + ) + except M8InsufficientDataError as exc: + _publish_prelock_insufficient_data( + config=config, + stage=stage, + project_root=project_root, + source_identity=source_identity, + protocol=protocol, + authority_manifest=authority_manifest, + stage_manifest=raw_manifest, + completed_entries=entries, + failure=_typed_failure( + exc, + failure_stage="development_normalization", + failed_role=period.role, + ), + generated_at_utc=generated_at, + ) + return "INSUFFICIENT_DATA", None + entry = normalized.entry + entries.append(entry) + try: + date_artifacts[(symbol, period.date.isoformat())] = _build_date_artifacts( + entry, config, stage + ) + except (ResearchDataError, TemporalLeakageError) as exc: + failure = _typed_failure( + M8InsufficientDataError(symbol, period.date.isoformat(), str(exc)), + reason_code="RESEARCH_FRAME_INSUFFICIENT", + failure_stage="development_research", + failed_role=period.role, + ) + _publish_prelock_insufficient_data( + config=config, + stage=stage, + project_root=project_root, + source_identity=source_identity, + protocol=protocol, + authority_manifest=authority_manifest, + stage_manifest=raw_manifest, + completed_entries=entries, + failure=failure, + generated_at_utc=generated_at, + ) + return "INSUFFICIENT_DATA", None + + development_manifest_path, development_manifest_sha = _commit_development_manifest( + entries, + date_artifacts, + config, + stage, + ) + selections: list[_SelectionArtifacts] = [] + for symbol_index, symbol in enumerate(config.study.symbols): + development = tuple( + date_artifacts[(symbol, period.date.isoformat())] + for period in config.periods + if period.role in _DEVELOPMENT_ROLES + ) + try: + selections.append(_select_symbol(symbol, symbol_index, development, config, stage)) + except (MultiDateEvaluationError, ModelEvaluationError) as exc: + validation_date = next( + period.date.isoformat() for period in config.periods if period.role == "validation" + ) + failure = _typed_failure( + M8InsufficientDataError(symbol, validation_date, str(exc)), + reason_code="MODEL_SELECTION_INSUFFICIENT", + failure_stage="model_selection", + failed_role="validation", + ) + _publish_prelock_insufficient_data( + config=config, + stage=stage, + project_root=project_root, + source_identity=source_identity, + protocol=protocol, + authority_manifest=authority_manifest, + stage_manifest=raw_manifest, + completed_entries=entries, + failure=failure, + generated_at_utc=generated_at, + partial_selections=selections, + ) + return "INSUFFICIENT_DATA", None + final_fitted_state_claims = _final_fitted_state_claims(selections, stage) + selection_by_symbol = {item.symbol: item for item in selections} + aggregate_lock_path, aggregate_lock_sha = _commit_aggregate_lock( + selections, + config, + authority_manifest, + development_manifest_path, + development_manifest_sha, + protocol["protocol_sha256"], + source_identity, + stage, + ) + _assert_lock_durable(aggregate_lock_path, aggregate_lock_sha, selections) + + # Phase 2: stream-normalize every held-out date. The callback executes + # inside the ZIP reader immediately before each CSV member open. + for period in config.periods: + if period.role not in _TEST_ROLES: + continue + for symbol in config.study.symbols: + descriptor = raw_manifest.archive_descriptor_for(symbol, period.date) + + def before_member_open() -> None: + _assert_test_open_authority( + config=config, + project_root=project_root, + source_identity=source_identity, + protocol_sha256=cast(str, protocol["protocol_sha256"]), + authority_manifest=authority_manifest, + stage_manifest=raw_manifest, + aggregate_lock_path=aggregate_lock_path, + aggregate_lock_sha256=aggregate_lock_sha, + selections=selections, + ) + + try: + acquired = descriptor.reconstruct() + except M8AcquisitionError as exc: + if _caused_by_system_fault(exc): + raise + failure = _typed_failure( + M8InsufficientDataError(symbol, period.date.isoformat(), str(exc)), + reason_code="RAW_ARCHIVE_INTEGRITY", + failure_stage="held_out_acquisition", + failed_role=period.role, + ) + _publish_insufficient_data( + config=config, + stage=stage, + project_root=project_root, + source_identity=source_identity, + protocol=protocol, + authority_manifest=authority_manifest, + stage_manifest=raw_manifest, + selections=selections, + aggregate_lock_path=aggregate_lock_path, + aggregate_lock_sha256=aggregate_lock_sha, + completed_entries=entries, + failure=failure, + generated_at_utc=generated_at, + ) + return "INSUFFICIENT_DATA", None + try: + normalized = normalize_m8_archive( + config, + period, + metadata_by_symbol[symbol], + acquired, + raw_input_root, + output_root=normalized_input_root, + before_member_open=before_member_open, + ) + except M8InsufficientDataError as exc: + _publish_insufficient_data( + config=config, + stage=stage, + project_root=project_root, + source_identity=source_identity, + protocol=protocol, + authority_manifest=authority_manifest, + stage_manifest=raw_manifest, + selections=selections, + aggregate_lock_path=aggregate_lock_path, + aggregate_lock_sha256=aggregate_lock_sha, + completed_entries=entries, + failure=_typed_failure( + exc, + failure_stage="held_out_normalization", + failed_role=period.role, + ), + generated_at_utc=generated_at, + ) + return "INSUFFICIENT_DATA", None + entries.append(normalized.entry) + + # No endpoint artifact is constructed until all eight normalizations pass + # and the strict legacy all-date manifest has been persisted and reloaded. + try: + manifest = write_m8_input_manifest(config, evidence_root, entries, metadata) + manifest = verify_m8_input_manifest( + config, + evidence_root, + manifest.path, + manifest_sha256=manifest.sha256, + ) + except M8ManifestError as exc: + failure = _typed_failure( + M8InsufficientDataError("STUDY", "all_dates", str(exc)), + reason_code="FINAL_NORMALIZED_MANIFEST_INCOMPLETE", + failure_stage="final_manifest", + failed_role="study", + ) + _publish_insufficient_data( + config=config, + stage=stage, + project_root=project_root, + source_identity=source_identity, + protocol=protocol, + authority_manifest=authority_manifest, + stage_manifest=raw_manifest, + selections=selections, + aggregate_lock_path=aggregate_lock_path, + aggregate_lock_sha256=aggregate_lock_sha, + completed_entries=entries, + failure=failure, + generated_at_utc=generated_at, + ) + return "INSUFFICIENT_DATA", None + input_snapshot, input_hashes = _snapshot_input_evidence(manifest, stage) + lookup = _entry_lookup(manifest) + for period in config.periods: + if period.role not in _TEST_ROLES: + continue + for symbol in config.study.symbols: + entry = lookup[(symbol, period.date.isoformat())] + try: + date_artifacts[(symbol, period.date.isoformat())] = _build_date_artifacts( + entry, config, stage + ) + except (ResearchDataError, TemporalLeakageError) as exc: + failure = _typed_failure( + M8InsufficientDataError(symbol, period.date.isoformat(), str(exc)), + reason_code="RESEARCH_FRAME_INSUFFICIENT", + failure_stage="held_out_research", + failed_role=period.role, + ) + _publish_insufficient_data( + config=config, + stage=stage, + project_root=project_root, + source_identity=source_identity, + protocol=protocol, + authority_manifest=authority_manifest, + stage_manifest=raw_manifest, + selections=selections, + aggregate_lock_path=aggregate_lock_path, + aggregate_lock_sha256=aggregate_lock_sha, + completed_entries=entries, + failure=failure, + generated_at_utc=generated_at, + final_manifest=manifest, + ) + return "INSUFFICIENT_DATA", manifest.sha256 + + _assert_lock_durable(aggregate_lock_path, aggregate_lock_sha, selections) + evaluation_stage = stage / ".endpoint-staging" + evaluation_stage.mkdir(parents=True, exist_ok=False) + staged_evaluations: list[_EvaluationArtifacts] = [] + for selection in selections: + symbol = selection.symbol + development = tuple( + date_artifacts[(symbol, period.date.isoformat())] + for period in config.periods + if period.role in _DEVELOPMENT_ROLES + ) + tests = tuple( + date_artifacts[(symbol, period.date.isoformat())] + for period in config.periods + if period.role in _TEST_ROLES + ) + try: + staged_evaluations.append( + _evaluate_symbol( + symbol, + selection, + development, + tests, + config, + evaluation_stage, + ) + ) + except ( + MultiDateEvaluationError, + ModelEvaluationError, + ResearchDataError, + TemporalLeakageError, + DescriptiveAnalysisError, + ) as exc: + shutil.rmtree(evaluation_stage) + failure = _typed_failure( + M8InsufficientDataError(symbol, "locked_evaluation", str(exc)), + reason_code="LOCKED_EVALUATION_INSUFFICIENT", + failure_stage="locked_evaluation", + failed_role="all_test_dates", + ) + _publish_insufficient_data( + config=config, + stage=stage, + project_root=project_root, + source_identity=source_identity, + protocol=protocol, + authority_manifest=authority_manifest, + stage_manifest=raw_manifest, + selections=selections, + aggregate_lock_path=aggregate_lock_path, + aggregate_lock_sha256=aggregate_lock_sha, + completed_entries=entries, + failure=failure, + generated_at_utc=generated_at, + final_manifest=manifest, + endpoint_evaluation_started=True, + completed_evaluation_symbols=tuple(item.symbol for item in staged_evaluations), + ) + return "INSUFFICIENT_DATA", manifest.sha256 + evaluations = _publish_evaluation_artifacts(staged_evaluations, evaluation_stage, stage) + + ordered_dates = tuple( + date_artifacts[(symbol, period.date.isoformat())] + for period in config.periods + for symbol in config.study.symbols + ) + _combine_parquet( + [item.predictions_path for item in evaluations], + stage / "models" / "predictions.parquet", + ) + _combine_parquet( + [item.comparison_path for item in selections], + stage / "models" / "validation_candidate_comparison.parquet", + ) + _combine_parquet( + [item.paired_date_path for item in evaluations], + stage / "metrics" / "paired_log_loss_by_date.parquet", + ) + _combine_parquet( + [item.stability_path for item in evaluations], + stage / "analysis" / "feature_stability.parquet", + ) + aggregate_frame = pl.DataFrame( + [dict(item.aggregate_row) for item in evaluations], infer_schema_length=None + ) + aggregate_frame.write_parquet( + stage / "metrics" / "equal_date_hypothesis.parquet", + compression="zstd", + statistics=True, + ) + predictive_rows = [dict(row) for item in evaluations for row in item.predictive_rows] + _write_json(stage / "metrics" / "predictive_metrics.json", predictive_rows) + _write_json(stage / "metrics" / "execution_metrics.json", []) + _write_json(stage / "metrics" / "execution_sensitivity.json", []) + _write_json( + stage / "metrics" / "execution_exclusion.json", + { + "status": "NOT_RUN", + "reason": M8_EXECUTION_EXCLUSION_REASON, + "execution_metrics_rows": 0, + "execution_sensitivity_rows": 0, + "fills_calculated": False, + "pnl_calculated": False, + "capacity_calculated": False, + "execution_claim_authorized": False, + "profitability_claim_authorized": False, + }, + ) + hypothesis_payload = { + "schema_version": M8_PIPELINE_SCHEMA_VERSION, + "generated_at_utc": generated_at, + "evidence_tier": M8_EVIDENCE_TIER, + "evidence_scope": M8_EVIDENCE_SCOPE, + "hypotheses": { + "H0": ( + "The validation-selected model does not reduce untouched-date log loss " + "relative to the historical-prior classifier." + ), + "H1": ( + "The validation-selected model reduces log loss on both primary and " + "replication dates." + ), + }, + "selection_metric": "log_loss", + "delta_definition": "selected_model_minus_historical_prior", + "date_weighting": "equal", + "bootstrap": { + "method": "paired contiguous-block percentile bootstrap from block sufficient statistics", + "samples": config.study.bootstrap_samples, + "block_width_events": config.study.bootstrap_block_events, + "ci_level": 0.95, + }, + "per_symbol": [dict(item.aggregate_row) for item in evaluations], + "per_date": [dict(row) for item in evaluations for row in item.paired_date_rows], + "per_date_artifact": "metrics/paired_log_loss_by_date.parquet", + "cross_instrument_conclusion": { + "status": "not_inferred", + "pooling_performed": False, + "persistent_alpha_claim_authorized": False, + "text": M8_NO_POOLING_CAVEAT, + }, + "p_values_computed": False, + "h0_rejected": False, + "significance_claim_authorized": False, + "execution_claim_authorized": False, + "profitability_claim_authorized": False, + "caveat": M8_NO_SIGNIFICANCE_CAVEAT, + } + _write_json(stage / "metrics" / "hypothesis_evaluation.json", hypothesis_payload) + _write_json( + stage / "analysis" / "instrument_status.json", + [ + { + "symbol": item.symbol, + "selected_model": item.selected_model, + "status": item.aggregate_row["status"], + "replication_status": item.aggregate_row["replication_status"], + "validation_primary_replication_status": item.aggregate_row[ + "validation_primary_replication_status" + ], + "direction_consistent_across_validation_primary_replication": ( + item.aggregate_row["direction_consistent_across_validation_primary_replication"] + ), + "selection_lock_sha256": item.aggregate_row["selection_lock_sha256"], + "final_fitted_state_path": _relative( + selection_by_symbol[item.symbol].fitted_state_path, + stage, + ), + "final_fitted_state_sha256": selection_by_symbol[ + item.symbol + ].selection.fitted_state.sha256, + } + for item in evaluations + ], + ) + + research_manifest = { + "schema_version": M8_PIPELINE_SCHEMA_VERSION, + "artifact_kind": "m8_per_date_research_frames", + "temporal_contract": ( + "exchange event time is the availability proxy; aggregate-trade ID breaks ties; " + "features and labels reset at every symbol/date continuity ID" + ), + "target": config.study.target, + "label_horizon_events": config.study.label_horizon_events, + "feature_columns": list(_trade_feature_columns(config)), + "selection_lock_path": _relative(aggregate_lock_path, stage), + "selection_lock_sha256": aggregate_lock_sha, + "final_fitted_states": final_fitted_state_claims, + "test_data_opened_before_lock": False, + "test_economic_rows_materialized_before_lock": False, + "test_raw_hashes_and_bounded_zip_metadata_verified_before_lock": True, + "test_normalization_completed_after_lock": True, + "final_all_date_manifest_committed_before_endpoint_evaluation": True, + "entries": [ + { + "symbol": item.symbol, + "date": item.study_date, + "role": item.role, + "research_frame": _relative(item.research_path, stage), + "research_frame_sha256": sha256_file(item.research_path), + "evaluation_frame": _relative(item.evaluation_path, stage), + "evaluation_frame_sha256": sha256_file(item.evaluation_path), + "summary": _relative(item.research_path.parent / "summary.json", stage), + } + for item in ordered_dates + ], + "symbol_evaluations": { + item.symbol: { + "selected_model": item.selected_model, + "predictions": _relative(item.predictions_path, stage), + "paired_date_metrics": _relative(item.paired_date_path, stage), + "feature_stability": _relative(item.stability_path, stage), + "walk_forward_plan": _relative(item.plan_path, stage), + "final_fitted_state_path": _relative( + selection_by_symbol[item.symbol].fitted_state_path, + stage, + ), + "final_fitted_state_sha256": selection_by_symbol[ + item.symbol + ].selection.fitted_state.sha256, + "test_used_for_selection": False, + "model_updated_between_test_dates": False, + } + for item in evaluations + }, + } + _write_json(stage / "research" / "manifest.json", research_manifest) + quality = _quality_payload(manifest, ordered_dates, generated_at_utc=generated_at) + _write_json(stage / "quality" / "summary.json", quality) + dashboard_path = stage / "dashboard" / "market_state.parquet" + dashboard_path.parent.mkdir(parents=True, exist_ok=True) + pl.DataFrame( + [ + {key: value for key, value in item.summary.items() if key != "temporal_audit"} + for item in ordered_dates + ], + infer_schema_length=None, + ).write_parquet(stage / "quality" / "per_date_summary.parquet") + pl.DataFrame( + [ + { + "symbol": item.symbol, + "date": item.study_date, + "role": item.role, + "eligible_labeled_rows": item.summary["eligible_labeled_rows"], + "positive_rate": item.summary["eligible_positive_rate"], + "scope": "trade_only_no_book_state", + "evidence_tier": M8_EVIDENCE_TIER, + } + for item in ordered_dates + ], + infer_schema_length=None, + ).write_parquet(dashboard_path) + + resolved = config.public_dict() + resolved.update( + { + "effective_evidence_tier": M8_EVIDENCE_TIER, + "evidence_scope": M8_EVIDENCE_SCOPE, + "full_data_boundary": ( + "complete requested trade archives only; not complete market observability" + ), + "protocol": protocol, + "input_manifest_sha256": manifest.sha256, + "raw_acquisition_manifest_sha256": authority_manifest.sha256, + "execution_status": "NOT_RUN", + "claim_permissions": { + "p_values": False, + "significance": False, + "cross_instrument_pooling": False, + "execution": False, + "profitability": False, + }, + } + ) + _write_json(stage / "resolved_config.json", resolved) + + run_key, run_key_inputs = _run_key( + config, + authority_manifest, + manifest, + protocol, + source_identity, + _final_fitted_state_sha256_by_symbol(selections), + ) + provenance = { + "generated_at_utc": generated_at, + "evidence_tier": M8_EVIDENCE_TIER, + "evidence_scope": M8_EVIDENCE_SCOPE, + "config_sha256": config.hash, + "config_source_sha256": config.source_sha256, + "input_manifest_sha256": [manifest.sha256], + "input_data_and_evidence_sha256": sorted( + {*input_hashes, authority_manifest.sha256, raw_manifest.sha256} + ), + "m8_input_manifest_path": _relative(manifest.path, stage), + "m8_input_manifest_sha256": manifest.sha256, + "raw_acquisition_manifest_path": str(authority_manifest.path.resolve()), + "raw_acquisition_manifest_sha256": authority_manifest.sha256, + "bundled_raw_acquisition_manifest_path": _relative(raw_manifest.path, stage), + "bundled_raw_acquisition_manifest_sha256": raw_manifest.sha256, + "raw_evidence_content_identity_sha256": authority_manifest.content_identity_sha256, + "raw_evidence_byte_budget": { + "external_total": authority_manifest.total_raw_evidence_bytes, + "bundle_copy_total": raw_manifest.total_raw_evidence_bytes, + "combined_total": ( + authority_manifest.total_raw_evidence_bytes + raw_manifest.total_raw_evidence_bytes + ), + "ceiling": config.study.max_total_download_bytes, + }, + "manifest_authority": ( + "explicit raw-acquisition path and caller-supplied lowercase SHA-256; no discovery" + ), + "protocol_path": protocol["protocol_path"], + "protocol_sha256": protocol["protocol_sha256"], + "protocol_version": config.study.protocol_version, + "selection_lock_path": _relative(aggregate_lock_path, stage), + "selection_lock_sha256": aggregate_lock_sha, + "final_fitted_states": final_fitted_state_claims, + "git": source_identity.public_dict(), + "runtime": runtime_metadata(), + "seed": config.study.seed, + "run_key": run_key, + "run_key_inputs": run_key_inputs, + "pipeline_schema_version": M8_PIPELINE_SCHEMA_VERSION, + "data_availability_clock": "exchange_event_time_proxy_plus_aggregate_trade_id", + "local_receipt_time_available": False, + "execution_simulated": False, + "pnl_calculated": False, + } + _write_json(stage / "provenance.json", provenance) + + rows = sum(entry.rows for entry in manifest.entries) + observed_start = min(entry.observed_start_ns for entry in manifest.entries) + observed_end = max(entry.observed_end_inclusive_ns for entry in manifest.entries) + symbol_coverage = [] + for symbol in config.study.symbols: + entries = [entry for entry in manifest.entries if entry.symbol == symbol] + symbol_coverage.append( + { + "symbol": symbol, + "rows": sum(entry.rows for entry in entries), + "complete": True, + "complete_range": True, + "observed_start_utc": _utc_from_ns( + min(entry.observed_start_ns for entry in entries) + ), + "observed_end_inclusive_utc": _utc_from_ns( + max(entry.observed_end_inclusive_ns for entry in entries) + ), + "requested_dates": [entry.date.isoformat() for entry in entries], + } + ) + artifacts = { + "resolved_config": "resolved_config.json", + "protocol": cast(str, protocol["protocol_path"]), + "machine_spec": cast(str, protocol["machine_spec_path"]), + "raw_acquisition_manifest": _relative(raw_manifest.path, stage), + "input_manifest_snapshot": "data/m8_input_manifest.json", + "data_manifest_snapshot": "data/manifest_snapshot.json", + "quality_summary": "quality/summary.json", + "quality_by_date": "quality/per_date_summary.parquet", + "research_manifest": "research/manifest.json", + "analysis_lock": "analysis/analysis_lock.json", + "predictions": "models/predictions.parquet", + "model_comparison_data": "models/validation_candidate_comparison.parquet", + "predictive_metrics": "metrics/predictive_metrics.json", + "hypothesis_evaluation": "metrics/hypothesis_evaluation.json", + "paired_date_metrics": "metrics/paired_log_loss_by_date.parquet", + "equal_date_metrics": "metrics/equal_date_hypothesis.parquet", + "feature_stability": "analysis/feature_stability.parquet", + "instrument_status": "analysis/instrument_status.json", + "execution_metrics": "metrics/execution_metrics.json", + "execution_sensitivity": "metrics/execution_sensitivity.json", + "execution_exclusion": "metrics/execution_exclusion.json", + "market_state": "dashboard/market_state.parquet", + "technical_report": "reports/technical_report.md", + "executive_memo": "reports/executive_memo.md", + "model_comparison": "reports/model_comparison.md", + } + run_manifest = { + "schema_version": M8_PIPELINE_SCHEMA_VERSION, + "run_id": config.study.name, + "run_key": run_key, + "status": "complete", + "evidence_tier": M8_EVIDENCE_TIER, + "evidence_scope": M8_EVIDENCE_SCOPE, + "data": { + "mode": "binance_spot_daily_aggtrades_trade_only", + "source": config.study.source, + "symbols": list(config.study.symbols), + "rows": rows, + "all_requested_ranges_complete": True, + "requested_dates": [period.date.isoformat() for period in config.periods], + "observed_start_utc": _utc_from_ns(observed_start), + "observed_end_utc": _utc_from_ns(observed_end), + "observed_start_ts_ns": observed_start, + "observed_end_ts_ns": observed_end, + "availability_basis": "exchange_event_time_proxy_plus_aggregate_trade_id", + "local_receipt_time_available": False, + "symbol_coverage": symbol_coverage, + "date_coverage": [ + { + "symbol": entry.symbol, + "date": entry.date.isoformat(), + "role": entry.role, + "rows": entry.rows, + "complete": entry.complete, + "quality_errors": entry.quality_errors, + "quality_warnings": entry.quality_warnings, + "observed_start_utc": _utc_from_ns(entry.observed_start_ns), + "observed_end_inclusive_utc": _utc_from_ns(entry.observed_end_inclusive_ns), + } + for entry in manifest.entries + ], + "full_data_boundary": ( + "all bytes in all predeclared daily trade archives; no book or receipt-time data" + ), + }, + "artifacts": artifacts, + "research": { + "question": ( + "whether frozen aggregate-trade order-flow features improve next-20-trade " + "direction log loss over a historical prior on both untouched dates" + ), + "scope": "trade_only", + "target": config.study.target, + "label_horizon_trades": config.study.label_horizon_events, + "evaluation_contract": ( + "per-symbol train/validation selection, disk-persisted lock, primary and " + "replication evaluation with one fixed train+validation fit" + ), + "selection_contract": "validation log loss only; test rows never select or update", + "final_fitted_states": final_fitted_state_claims, + "analysis_lock": { + "path": _relative(aggregate_lock_path, stage), + "sha256": aggregate_lock_sha, + "committed_before_test_rows_opened": True, + }, + "hypothesis_evaluation": { + "artifact": "metrics/hypothesis_evaluation.json", + "per_date_artifact": "metrics/paired_log_loss_by_date.parquet", + "equal_date_artifact": "metrics/equal_date_hypothesis.parquet", + "baseline": "historical_prior", + "metric": "log_loss", + "delta_definition": "selected_model_minus_historical_prior", + "date_weighting": "equal", + "per_symbol_only": True, + "cross_instrument_pooling": False, + "p_values_computed": False, + "h0_rejected": False, + "significance_claim_authorized": False, + "persistent_alpha_claim_authorized": False, + }, + "instruments": { + item.symbol: { + "selected_model": item.selected_model, + "status": item.aggregate_row["status"], + "replication_status": item.aggregate_row["replication_status"], + "validation_primary_replication_status": item.aggregate_row[ + "validation_primary_replication_status" + ], + "direction_consistent_across_validation_primary_replication": ( + item.aggregate_row[ + "direction_consistent_across_validation_primary_replication" + ] + ), + "selection_lock_sha256": item.aggregate_row["selection_lock_sha256"], + "final_fitted_state_path": _relative( + selection_by_symbol[item.symbol].fitted_state_path, + stage, + ), + "final_fitted_state_sha256": selection_by_symbol[ + item.symbol + ].selection.fitted_state.sha256, + "model_updated_between_test_dates": False, + } + for item in evaluations + }, + }, + "execution_assumptions": { + "status": "NOT_RUN", + "reason": M8_EXECUTION_EXCLUSION_REASON, + "pnl_calculated": False, + "fills_calculated": False, + "capacity_calculated": False, + "profitability_claim_authorized": False, + }, + "warnings": [ + ( + "FULL_DATA is narrowly scoped to complete predeclared trade archives and does " + "not mean full market observability or deployable evidence." + ), + "Exchange event time is an availability proxy; no local receipt clock is available.", + M8_EXECUTION_EXCLUSION_REASON, + M8_NO_SIGNIFICANCE_CAVEAT, + M8_NO_POOLING_CAVEAT, + ], + } + _write_json(stage / "run_manifest.json", run_manifest) + _write_reports(stage) + + # Revalidate every external hash after all economic computation and prove + # that neither the frozen config nor the exact source tree changed mid-run. + _verify_config_source(config) + if sha256_file(_protocol_source(project_root)) != protocol["protocol_sha256"]: + raise M8PipelineError("frozen M8 protocol changed during production") + second_manifest = _load_final_input_manifest(config, manifest.path, manifest.sha256) + if second_manifest.sha256 != manifest.sha256: + raise M8PipelineError("M8 input identity changed during production") + second_raw = _load_raw_manifest( + config, + authority_manifest.path, + authority_manifest.sha256, + ) + if second_raw.sha256 != authority_manifest.sha256: + raise M8PipelineError("M8 raw acquisition identity changed during production") + read_m8_acquisition_manifest( + raw_manifest.path, + expected_sha256=raw_manifest.sha256, + config=config, + ) + if _capture_source_identity(project_root) != source_identity: + raise M8PipelineError("Git/source-tree identity changed during M8 production") + _assert_lock_durable(aggregate_lock_path, aggregate_lock_sha, selections) + if ( + input_snapshot["manifest_authority"] + != json.loads((stage / "data" / "manifest_snapshot.json").read_text(encoding="utf-8"))[ + "manifest_authority" + ] + ): + raise M8PipelineError("frozen input snapshot changed during production") + + _fsync_tree(stage) + write_checksum_manifest(stage) + _create_terminal_marker(stage / "_SUCCESS", "complete") + load_run_bundle(stage) + return "COMPLETE", manifest.sha256 + + +def _reuse_completed( + target: Path, + config: M8StudyConfig, + raw_manifest: M8AcquisitionManifest, + project_root: Path, + source_identity: _SourceIdentity, +) -> M8RunResult: + if (target / "INSUFFICIENT_DATA").exists(): + raise M8PipelineError("completed M8 target has conflicting terminal markers") + try: + success_bytes = (target / "_SUCCESS").read_bytes() + except OSError as exc: + raise M8PipelineError("completed M8 terminal marker is unavailable") from exc + if success_bytes != b"complete\n": + raise M8PipelineError("completed M8 terminal marker bytes are invalid") + try: + bundle = load_run_bundle(target) + except Exception as exc: + raise M8PipelineError(f"completed M8 target failed integrity verification: {exc}") from exc + if bundle.run_id != config.study.name: + raise M8PipelineError("completed M8 target has a different run ID") + expected_pairs = { + "config_sha256": config.hash, + "config_source_sha256": config.source_sha256, + "raw_acquisition_manifest_sha256": raw_manifest.sha256, + "raw_evidence_content_identity_sha256": raw_manifest.content_identity_sha256, + "protocol_version": config.study.protocol_version, + "pipeline_schema_version": M8_PIPELINE_SCHEMA_VERSION, + "evidence_scope": M8_EVIDENCE_SCOPE, + } + for key, expected in expected_pairs.items(): + if bundle.provenance.get(key) != expected: + raise M8PipelineError(f"completed M8 target has a different {key}") + bundled_raw_path_value = bundle.provenance.get("bundled_raw_acquisition_manifest_path") + bundled_raw_sha = bundle.provenance.get("bundled_raw_acquisition_manifest_sha256") + if type(bundled_raw_path_value) is not str or type(bundled_raw_sha) is not str: + raise M8PipelineError("completed M8 target lacks bundled raw-manifest identity") + bundled_raw_path = (target / bundled_raw_path_value).resolve() + if not bundled_raw_path.is_relative_to(target): + raise M8PipelineError("completed bundled raw-manifest path escapes target") + try: + bundled_raw = read_m8_acquisition_manifest( + bundled_raw_path, + expected_sha256=bundled_raw_sha, + config=config, + ) + except Exception as exc: + raise M8PipelineError(f"completed bundled raw evidence is invalid: {exc}") from exc + if ( + bundled_raw.copied_from_manifest_sha256 != raw_manifest.sha256 + or bundled_raw.content_identity_sha256 != raw_manifest.content_identity_sha256 + ): + raise M8PipelineError("completed bundled raw evidence differs from acquisition authority") + normalized_sha = bundle.provenance.get("m8_input_manifest_sha256") + normalized_path_value = bundle.provenance.get("m8_input_manifest_path") + if type(normalized_sha) is not str or type(normalized_path_value) is not str: + raise M8PipelineError("completed M8 target lacks normalized-manifest identity") + normalized_path = (target / normalized_path_value).resolve() + if not normalized_path.is_relative_to(target): + raise M8PipelineError("completed M8 normalized-manifest path escapes the bundle") + normalized_manifest = _load_final_input_manifest( + config, + normalized_path, + normalized_sha, + ) + bundled_git = bundle.provenance.get("git") + if not isinstance(bundled_git, Mapping) or dict(bundled_git) != source_identity.public_dict(): + raise M8PipelineError("completed M8 target has a different Git/source-tree identity") + protocol_sha = sha256_file(_protocol_source(project_root)) + if bundle.provenance.get("protocol_sha256") != protocol_sha: + raise M8PipelineError("completed M8 target has a different frozen protocol") + final_fitted_state_sha256_by_symbol = _verify_completed_lock_chain( + target=target, + config=config, + raw_manifest=raw_manifest, + source_identity=source_identity, + protocol_sha256=protocol_sha, + run_manifest=bundle.manifest, + provenance=bundle.provenance, + ) + expected_run_key, expected_run_key_inputs = _run_key( + config, + raw_manifest, + normalized_manifest, + {"protocol_sha256": protocol_sha}, + source_identity, + final_fitted_state_sha256_by_symbol, + ) + if ( + bundle.manifest.get("run_key") != expected_run_key + or bundle.provenance.get("run_key") != expected_run_key + or bundle.provenance.get("run_key_inputs") != expected_run_key_inputs + ): + raise M8PipelineError("completed M8 target has a different deterministic run identity") + execution = bundle.manifest.get("execution_assumptions") + if not isinstance(execution, Mapping) or execution.get("status") != "NOT_RUN": + raise M8PipelineError("completed M8 target improperly claims execution evidence") + if bundle.manifest.get("evidence_scope") != M8_EVIDENCE_SCOPE: + raise M8PipelineError("completed FULL_DATA target is not explicitly trade-only") + return M8RunResult( + path=target, + status="COMPLETE", + raw_manifest_sha256=raw_manifest.sha256, + normalized_manifest_sha256=normalized_manifest.sha256, + ) + + +def _reuse_insufficient( + target: Path, + config: M8StudyConfig, + raw_manifest: M8AcquisitionManifest, + project_root: Path, + source_identity: _SourceIdentity, +) -> M8RunResult: + if (target / "_SUCCESS").exists(): + raise M8PipelineError("INSUFFICIENT_DATA target has conflicting terminal markers") + try: + marker_bytes = _read_bounded_regular_snapshot( + _published_file(target, "INSUFFICIENT_DATA", "INSUFFICIENT_DATA terminal marker"), + label="INSUFFICIENT_DATA terminal marker", + max_bytes=32, + ).content + except M8PipelineError as exc: + raise M8PipelineError("INSUFFICIENT_DATA terminal marker is unavailable") from exc + if marker_bytes != b"terminal\n": + raise M8PipelineError("INSUFFICIENT_DATA terminal marker bytes are invalid") + try: + verify_checksums(target) + except Exception as exc: + raise M8PipelineError( + f"INSUFFICIENT_DATA target failed integrity verification: {exc}" + ) from exc + failure_inventory = _verify_failure_evidence_inventory(target) + failure = _read_inventory_json_object( + target=target, + inventory=failure_inventory, + relative_path="failure.json", + label="INSUFFICIENT_DATA failure record", + ) + provenance = _read_inventory_json_object( + target=target, + inventory=failure_inventory, + relative_path="provenance.json", + label="INSUFFICIENT_DATA provenance record", + ) + run_manifest = _read_inventory_json_object( + target=target, + inventory=failure_inventory, + relative_path="run_manifest.json", + label="INSUFFICIENT_DATA run manifest", + ) + if failure.get("status") != "INSUFFICIENT_DATA" or failure.get("terminal") is not True: + raise M8PipelineError("INSUFFICIENT_DATA target lacks a terminal failure record") + expected = { + "config_sha256": config.hash, + "config_source_sha256": config.source_sha256, + "raw_acquisition_manifest_sha256": raw_manifest.sha256, + "raw_evidence_content_identity_sha256": raw_manifest.content_identity_sha256, + "protocol_version": config.study.protocol_version, + "pipeline_schema_version": M8_PIPELINE_SCHEMA_VERSION, + } + for key, value in expected.items(): + if provenance.get(key) != value: + raise M8PipelineError(f"INSUFFICIENT_DATA target has a different {key}") + if provenance.get("git") != source_identity.public_dict(): + raise M8PipelineError("INSUFFICIENT_DATA target has a different source identity") + if provenance.get("protocol_sha256") != sha256_file(_protocol_source(project_root)): + raise M8PipelineError("INSUFFICIENT_DATA target has a different protocol") + bundled_raw_path_value = provenance.get("bundled_raw_acquisition_manifest_path") + bundled_raw_sha = provenance.get("bundled_raw_acquisition_manifest_sha256") + if type(bundled_raw_path_value) is not str or type(bundled_raw_sha) is not str: + raise M8PipelineError("INSUFFICIENT_DATA target lacks bundled raw-manifest identity") + bundled_raw_relative = _canonical_inventory_child( + bundled_raw_path_value, + "INSUFFICIENT_DATA bundled raw acquisition manifest", + ) + bundled_raw_digest = _require_digest( + bundled_raw_sha, + "INSUFFICIENT_DATA bundled raw acquisition manifest SHA-256", + ) + _read_inventory_bounded_snapshot( + target=target, + inventory=failure_inventory, + relative_path=bundled_raw_relative, + label="INSUFFICIENT_DATA bundled raw acquisition manifest", + max_bytes=_MAX_LOCK_JSON_BYTES, + expected_sha256=bundled_raw_digest, + ) + bundled_raw_path = _published_file( + target, + bundled_raw_relative, + "INSUFFICIENT_DATA bundled raw acquisition manifest", + ) + try: + bundled_raw = read_m8_acquisition_manifest( + bundled_raw_path, + expected_sha256=bundled_raw_digest, + config=config, + ) + except Exception as exc: + raise M8PipelineError(f"INSUFFICIENT_DATA bundled raw evidence is invalid: {exc}") from exc + if ( + bundled_raw.copied_from_manifest_sha256 != raw_manifest.sha256 + or bundled_raw.content_identity_sha256 != raw_manifest.content_identity_sha256 + ): + raise M8PipelineError( + "INSUFFICIENT_DATA bundled raw evidence differs from acquisition authority" + ) + _bind_raw_acquisition_inventory( + target=target, + inventory=failure_inventory, + manifest=bundled_raw, + manifest_relative=bundled_raw_relative, + ) + _verify_insufficient_lock_chain( + target=target, + inventory=failure_inventory, + config=config, + raw_manifest=raw_manifest, + bundled_raw_sha256=bundled_raw.sha256, + source_identity=source_identity, + protocol_sha256=sha256_file(_protocol_source(project_root)), + failure=failure, + provenance=provenance, + run_manifest=run_manifest, + ) + _verify_failed_normalization_evidence( + target=target, + config=config, + raw_manifest=raw_manifest, + failure=failure, + inventory=failure_inventory, + ) + _verify_completed_normalization_evidence( + target=target, + config=config, + raw_manifest=raw_manifest, + failure=failure, + inventory=failure_inventory, + ) + forbidden = ( + target / "models" / "predictions.parquet", + target / "metrics" / "predictive_metrics.json", + target / "metrics" / "hypothesis_evaluation.json", + target / "metrics" / "paired_log_loss_by_date.parquet", + target / "metrics" / "equal_date_hypothesis.parquet", + target / "_SUCCESS", + ) + if any(path.exists() for path in forbidden): + raise M8PipelineError("INSUFFICIENT_DATA target improperly contains endpoint output") + if any(path.is_file() for path in target.rglob("*prediction*")): + raise M8PipelineError("INSUFFICIENT_DATA target improperly contains predictions") + normalized_manifest_sha256: str | None = None + final_manifest_claim = failure.get("final_all_date_normalized_manifest") + if final_manifest_claim is not None: + if not isinstance(final_manifest_claim, Mapping): + raise M8PipelineError("INSUFFICIENT_DATA final-manifest claim is malformed") + final_path_value = final_manifest_claim.get("path") + final_sha = final_manifest_claim.get("sha256") + if type(final_path_value) is not str or type(final_sha) is not str: + raise M8PipelineError("INSUFFICIENT_DATA final-manifest identity is malformed") + final_relative = _canonical_inventory_child( + final_path_value, + "INSUFFICIENT_DATA final normalized manifest", + ) + final_digest = _require_digest( + final_sha, + "INSUFFICIENT_DATA final normalized manifest SHA-256", + ) + _read_inventory_bounded_snapshot( + target=target, + inventory=failure_inventory, + relative_path=final_relative, + label="INSUFFICIENT_DATA final normalized manifest", + max_bytes=_MAX_LOCK_JSON_BYTES, + expected_sha256=final_digest, + ) + final_manifest = _load_final_input_manifest( + config, + _published_file( + target, + final_relative, + "INSUFFICIENT_DATA final normalized manifest", + ), + final_digest, + ) + _bind_final_input_manifest_inventory( + target=target, + inventory=failure_inventory, + manifest=final_manifest, + ) + normalized_manifest_sha256 = final_manifest.sha256 + if _verify_failure_evidence_inventory(target) != failure_inventory: + raise M8PipelineError("INSUFFICIENT_DATA evidence identity changed during verification") + return M8RunResult( + path=target, + status="INSUFFICIENT_DATA", + raw_manifest_sha256=raw_manifest.sha256, + normalized_manifest_sha256=normalized_manifest_sha256, + ) + + +def _self_verify_produced_terminal( + *, + target: Path, + expected_status: M8RunStatus, + expected_normalized_manifest_sha256: str | None, + config: M8StudyConfig, + raw_manifest: M8AcquisitionManifest, + project_root: Path, + source_identity: _SourceIdentity, +) -> M8RunResult: + """Apply the external reuse contract to a just-produced terminal tree.""" + + if expected_status == "COMPLETE": + observed = _reuse_completed( + target, + config, + raw_manifest, + project_root, + source_identity, + ) + else: + observed = _reuse_insufficient( + target, + config, + raw_manifest, + project_root, + source_identity, + ) + if ( + observed.status != expected_status + or observed.raw_manifest_sha256 != raw_manifest.sha256 + or observed.normalized_manifest_sha256 != expected_normalized_manifest_sha256 + ): + raise M8PipelineError("M8 producer terminal result disagrees with its reuse verifier") + return observed + + +def verify_m8_result( + path: str | Path, + config: M8StudyConfig, + *, + raw_manifest_path: str | Path, + raw_manifest_sha256: str, +) -> M8RunResult: + """Verify one immutable complete or insufficient-data M8 result.""" + + project_root = _project_root(config) + _verify_config_source(config) + raw_manifest = _load_raw_manifest( + config, + Path(raw_manifest_path), + raw_manifest_sha256, + ) + source_identity = _capture_source_identity(project_root) + if ( + source_identity.dirty + or re.fullmatch(r"[0-9a-f]{40}|[0-9a-f]{64}", source_identity.commit) is None + ): + raise M8PipelineError("M8 result verification requires the exact clean committed source") + target = Path(path).resolve() + if not target.is_dir(): + raise M8PipelineError(f"M8 result directory does not exist: {target}") + success_marker = (target / "_SUCCESS").is_file() + insufficient_marker = (target / "INSUFFICIENT_DATA").is_file() + if success_marker and insufficient_marker: + raise M8PipelineError("M8 result has conflicting terminal markers") + if success_marker: + return _reuse_completed(target, config, raw_manifest, project_root, source_identity) + if insufficient_marker: + return _reuse_insufficient(target, config, raw_manifest, project_root, source_identity) + raise M8PipelineError("M8 result has no recognized terminal marker") + + +def reproduce_m8( + config: M8StudyConfig, + run_dir: Path, + *, + raw_manifest_path: Path, + raw_manifest_sha256: str, +) -> M8RunResult: + """Produce or verify one immutable M8 trade-only run bundle. + + The input authority is always the caller's exact manifest path and lowercase + SHA-256. No directory scan, newest-file rule, implicit fallback, repair, or + overwrite is permitted. A new run is built in a sibling directory and + atomically renamed only after checksums and ``_SUCCESS`` are complete. + """ + + project_root = _project_root(config) + _verify_config_source(config) + raw_manifest = _load_raw_manifest( + config, + Path(raw_manifest_path), + raw_manifest_sha256, + ) + source_identity = _capture_source_identity(project_root) + if not re.fullmatch(r"[0-9a-f]{40}|[0-9a-f]{64}", source_identity.commit): + raise M8PipelineError( + "M8 production requires a real committed Git revision before opening any economic rows" + ) + if source_identity.dirty: + raise M8PipelineError( + "M8 production and reuse require a clean Git working tree; commit the exact " + "source state before opening any economic rows" + ) + target = Path(run_dir).resolve() + if target.exists(): + if (target / "_SUCCESS").is_file() and (target / "INSUFFICIENT_DATA").is_file(): + raise M8PipelineError("M8 run target has conflicting terminal markers") + if target.is_dir() and (target / "_SUCCESS").is_file(): + return _reuse_completed( + target, + config, + raw_manifest, + project_root, + source_identity, + ) + if target.is_dir() and (target / "INSUFFICIENT_DATA").is_file(): + return _reuse_insufficient( + target, + config, + raw_manifest, + project_root, + source_identity, + ) + raise M8PipelineError( + f"M8 run target already exists but is incomplete or not a directory: {target}" + ) + + target.parent.mkdir(parents=True, exist_ok=True) + stage = Path(tempfile.mkdtemp(prefix=f".{target.name}.staging-", dir=target.parent)).resolve() + try: + status, normalized_manifest_sha256 = _produce_m8( + config, + raw_manifest, + stage, + project_root, + source_identity, + ) + _self_verify_produced_terminal( + target=stage, + expected_status=status, + expected_normalized_manifest_sha256=normalized_manifest_sha256, + config=config, + raw_manifest=raw_manifest, + project_root=project_root, + source_identity=source_identity, + ) + if target.exists(): + raise M8PipelineError(f"M8 run target appeared during production: {target}") + stage.rename(target) + _fsync_directory(target.parent) + return _self_verify_produced_terminal( + target=target, + expected_status=status, + expected_normalized_manifest_sha256=normalized_manifest_sha256, + config=config, + raw_manifest=raw_manifest, + project_root=project_root, + source_identity=source_identity, + ) + except M8PipelineError: + if stage.exists(): + shutil.rmtree(stage) + raise + except Exception as exc: + if stage.exists(): + shutil.rmtree(stage) + raise M8PipelineError(f"M8 production failed closed: {exc}") from exc + + +__all__ = [ + "M8_EVIDENCE_SCOPE", + "M8_EVIDENCE_TIER", + "M8_EXECUTION_EXCLUSION_REASON", + "M8_PIPELINE_SCHEMA_VERSION", + "M8PipelineError", + "M8RunResult", + "M8RunStatus", + "reproduce_m8", + "verify_m8_result", +] diff --git a/Microstructure/src/microstructure/pipeline.py b/Microstructure/src/microstructure/pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..f7c92e6413101314635f9d4d506bf68e31f8f886 --- /dev/null +++ b/Microstructure/src/microstructure/pipeline.py @@ -0,0 +1,1235 @@ +"""Atomic, reproducible end-to-end producer for the synthetic research slice. + +This module orchestrates existing data, research, model, execution, and reporting +APIs. It does not contain an exchange connection or an order-entry path. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import shutil +import tempfile +from collections import defaultdict +from collections.abc import Mapping, Sequence +from dataclasses import asdict +from datetime import UTC, datetime +from pathlib import Path +from typing import Any, cast + +import numpy as np +import polars as pl +from numpy.typing import NDArray + +from microstructure.config import ProjectConfig, datetime_to_ns +from microstructure.data.quality import ValidationReport, validate_table +from microstructure.data.storage import DatasetWriteResult, write_partitioned_parquet +from microstructure.data.synthetic import generate_synthetic_market, iter_table_batches +from microstructure.execution import run_execution_sensitivity, simulate_predictions +from microstructure.provenance import ( + git_source_tree_sha256, + git_state, + provenance_header, + sha256_file, + write_json, +) +from microstructure.reporting import ( + load_run_bundle, + render_executive_memo, + render_model_comparison, + render_technical_report, + write_checksum_manifest, +) +from microstructure.research.analysis import ( + LiquidityShockThresholds, + RegimeThresholds, + assign_market_regimes, + cross_instrument_stability_summary, + estimate_signal_half_life, + feature_stability_summary, + intraday_liquidity_summary, + large_trade_price_impact_summary, + liquidity_recovery_summary, + ofi_future_return_association, + regime_outcome_summary, +) +from microstructure.research.features import ( + add_future_event_labels, + build_research_frame, + validate_temporal_contract, +) +from microstructure.research.labels import add_event_time_price_impact_labels +from microstructure.research.models import ( + block_bootstrap_metric, + classification_metrics, + evaluate_model_ladder, +) +from microstructure.research.splits import WalkForwardPlan, expanding_walk_forward_splits + +PIPELINE_SCHEMA_VERSION = "1.0.0" +_SYNTHETIC_EVIDENCE = "SYNTHETIC_SMOKE" + + +class PipelineError(RuntimeError): + """Raised when a run cannot be produced without violating its contracts.""" + + +def _utc_from_ns(timestamp_ns: int) -> str: + return ( + datetime.fromtimestamp(timestamp_ns / 1_000_000_000, tz=UTC) + .isoformat() + .replace("+00:00", "Z") + ) + + +def _json_safe(value: Any) -> Any: + if isinstance(value, np.generic): + return _json_safe(value.item()) + if isinstance(value, float) and not math.isfinite(value): + return None + if isinstance(value, Path): + return str(value) + if isinstance(value, Mapping): + return {str(key): _json_safe(item) for key, item in value.items()} + if isinstance(value, (list, tuple)): + return [_json_safe(item) for item in value] + return value + + +def _stable_sha256(payload: Mapping[str, Any]) -> str: + encoded = json.dumps(payload, sort_keys=True, separators=(",", ":"), allow_nan=False) + return hashlib.sha256(encoded.encode("utf-8")).hexdigest() + + +def _write_json(path: Path, payload: Mapping[str, Any] | list[Any]) -> None: + clean = _json_safe(payload) + if not isinstance(clean, (dict, list)): + raise TypeError("JSON artifact payload must be an object or list") + write_json(path, clean) + + +def _atomic_write_text(path: Path, content: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary_name = tempfile.mkstemp( + dir=path.parent, + prefix=f".{path.name}.", + suffix=".tmp", + text=True, + ) + try: + with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as handle: + handle.write(content.rstrip() + "\n") + os.replace(temporary_name, path) + except BaseException: + Path(temporary_name).unlink(missing_ok=True) + raise + + +def _mapping_columns_as_json(frame: pl.DataFrame) -> pl.DataFrame: + """Make metric-map columns portable to Parquet without inventing map entries.""" + rows = frame.to_dicts() + mapping_columns = { + key for row in rows for key, value in row.items() if isinstance(value, Mapping) + } + if not mapping_columns: + return frame + serialized: list[dict[str, Any]] = [] + for row in rows: + output: dict[str, Any] = {} + for key, value in row.items(): + if key in mapping_columns: + output[f"{key}_json"] = json.dumps( + _json_safe(value), sort_keys=True, separators=(",", ":") + ) + else: + output[key] = value + serialized.append(output) + return pl.DataFrame(serialized) + + +def _relative(path: Path, root: Path) -> str: + return path.resolve().relative_to(root.resolve()).as_posix() + + +def _dataset_snapshot(result: DatasetWriteResult, run_root: Path) -> dict[str, Any]: + return { + "dataset": result.dataset, + "schema_version": result.schema_version, + "rows": result.rows, + "manifest_path": _relative(result.manifest_path, run_root), + "manifest_sha256": result.manifest_sha256, + "partitions": [ + { + "venue": artifact.venue, + "symbol": artifact.symbol, + "partition_date": artifact.partition_date, + "rows": artifact.rows, + "data_path": _relative(artifact.data_path, run_root), + "data_sha256": artifact.data_sha256, + "manifest_path": _relative(artifact.manifest_path, run_root), + "manifest_sha256": artifact.manifest_sha256, + } + for artifact in result.artifacts + ], + } + + +def _input_identity_hashes(results: Sequence[DatasetWriteResult]) -> list[str]: + """Hash timestamp-free manifest identities and their immutable data parts.""" + identities: list[str] = [] + for result in results: + partitions = sorted( + ( + { + "venue": artifact.venue, + "symbol": artifact.symbol, + "partition_date": artifact.partition_date, + "rows": artifact.rows, + "data_sha256": artifact.data_sha256, + } + for artifact in result.artifacts + ), + key=lambda item: ( + str(item["venue"]), + str(item["symbol"]), + str(item["partition_date"]), + str(item["data_sha256"]), + ), + ) + identities.append( + _stable_sha256( + { + "artifact_kind": "normalized_dataset_manifest_identity", + "dataset": result.dataset, + "schema_version": result.schema_version, + "rows": result.rows, + "partitions": partitions, + } + ) + ) + identities.extend(artifact.data_sha256 for artifact in result.artifacts) + return sorted(identities) + + +def _run_identity( + *, + config_sha256: str, + input_identity_sha256: Sequence[str], + git: Mapping[str, Any], + seed: int, +) -> tuple[str, dict[str, Any]]: + inputs = { + "config_sha256": config_sha256, + "input_manifest_identity_or_data_sha256": sorted(input_identity_sha256), + "git": { + "commit": str(git.get("commit", "UNKNOWN")), + "dirty": bool(git.get("dirty", False)), + "source_tree_sha256": str(git.get("source_tree_sha256", "UNKNOWN")), + }, + "seed": seed, + } + return _stable_sha256(inputs), inputs + + +def _quality_payload( + reports: Sequence[ValidationReport], *, generated_at_utc: str +) -> dict[str, Any]: + findings = [asdict(finding) for report in reports for finding in report.findings] + errors = sum(report.error_count for report in reports) + warnings = sum(report.warning_count for report in reports) + return { + "generated_at_utc": generated_at_utc, + "dataset": "synthetic_normalized_market", + "rows_checked": sum(report.rows_checked for report in reports), + "summary": {"errors": errors, "warnings": warnings}, + "reports": [ + { + "dataset": report.dataset, + "rows_checked": report.rows_checked, + "errors": report.error_count, + "warnings": report.warning_count, + } + for report in reports + ], + "findings": findings, + "mutation_policy": "observations were not changed or repaired", + } + + +def _serialize_plan(plan: WalkForwardPlan) -> dict[str, Any]: + return { + "contract": ( + "global decision-time buckets; feature_ready and uncensored rows only; " + "training labels end strictly before evaluation; configured embargo applied" + ), + "index_basis": ( + "zero-based row positions in research/evaluation_frame.parquet; this exact " + "feature-ready frame is passed to splitting and model evaluation" + ), + "decision_time_count": plan.decision_time_count, + "folds": [ + { + "fold_id": fold.fold_id, + "train_indices": [int(value) for value in fold.train_indices.tolist()], + "validation_indices": [int(value) for value in fold.validation_indices.tolist()], + "train_start_ts_ns": fold.train_start_ts_ns, + "train_end_ts_ns": fold.train_end_ts_ns, + "validation_start_ts_ns": fold.validation_start_ts_ns, + "validation_end_ts_ns": fold.validation_end_ts_ns, + "purged_rows": fold.purged_rows, + "embargoed_time_buckets": fold.embargoed_time_buckets, + } + for fold in plan.folds + ], + "final_train_indices": [int(value) for value in plan.final_train_indices.tolist()], + "test_indices": [int(value) for value in plan.test_indices.tolist()], + "test_start_ts_ns": plan.test_start_ts_ns, + "test_end_ts_ns": plan.test_end_ts_ns, + } + + +def _bootstrap_comparison( + comparison: pl.DataFrame, + predictions: pl.DataFrame, + *, + metric: str, + n_bootstrap: int, + seed: int, + horizon_events: int, +) -> tuple[list[dict[str, Any]], pl.DataFrame]: + block_width = max(2, 2 * horizon_events) + blocked = ( + predictions.with_columns( + (pl.col("decision_ts_ns").rank(method="dense").cast(pl.Int64) - 1).alias( + "_bootstrap_time_rank" + ) + ) + .with_columns( + (pl.col("_bootstrap_time_rank") // block_width).cast(pl.String).alias("bootstrap_block") + ) + .drop("_bootstrap_time_rank") + ) + rows: list[dict[str, Any]] = [] + for row in comparison.to_dicts(): + serialized = dict(row) + if row["split"] == "test": + selected = blocked.filter( + (pl.col("split") == "test") & (pl.col("model") == str(row["model"])) + ) + interval = block_bootstrap_metric( + selected, + metric=metric, + block_column="bootstrap_block", + n_bootstrap=n_bootstrap, + seed=seed, + ) + serialized[f"{metric}_ci_low"] = interval.lower + serialized[f"{metric}_ci_high"] = interval.upper + serialized["bootstrap_status"] = interval.status + serialized["bootstrap_blocks"] = interval.n_blocks + serialized["bootstrap_samples"] = interval.n_bootstrap + serialized["bootstrap_block_width_events"] = block_width + serialized["bootstrap_block_policy"] = ( + "pooled_dense_decision_time_clusters_2x_label_horizon" + ) + serialized["bootstrap_limitation"] = ( + "fixed clusters approximate serial and contemporaneous dependence; " + "they do not establish asymptotic coverage" + ) + rows.append(serialized) + return rows, blocked + + +def _execution_events( + research_frame: pl.DataFrame, trades: pl.DataFrame +) -> tuple[pl.DataFrame, dict[str, Any]]: + """Build an availability-time replay frame without joining future trades. + + The current simulator accepts one qualifying trade per market-state event. + For the synthetic fixture there is exactly one trade in each book interval. + If a future input has more, this adapter selects the latest eligible trade and + records the conservative omission count rather than double-counting volume. + """ + trade_groups: dict[tuple[str, str], list[dict[str, Any]]] = defaultdict(list) + for trade in trades.sort(["symbol", "continuity_id", "available_ts_ns", "trade_id"]).to_dicts(): + key = (str(trade["symbol"]), str(trade["continuity_id"])) + trade_groups[key].append(trade) + + pointers: dict[tuple[str, str], int] = defaultdict(int) + prior_decision: dict[tuple[str, str], int] = {} + omitted_trades = 0 + output: list[dict[str, Any]] = [] + ordered = research_frame.sort(["symbol", "continuity_id", "decision_sequence"]) + for research_row in ordered.to_dicts(): + symbol = str(research_row["symbol"]) + continuity = str(research_row["continuity_id"]) + key = (symbol, continuity) + decision_ts = int(research_row["decision_ts_ns"]) + lower_bound = prior_decision.get(key, -1) + candidates = trade_groups.get(key, []) + pointer = pointers[key] + eligible: list[dict[str, Any]] = [] + while ( + pointer < len(candidates) and int(candidates[pointer]["available_ts_ns"]) <= decision_ts + ): + if int(candidates[pointer]["available_ts_ns"]) > lower_bound: + eligible.append(candidates[pointer]) + pointer += 1 + pointers[key] = pointer + prior_decision[key] = decision_ts + omitted_trades += max(0, len(eligible) - 1) + selected_trade: dict[str, Any] | None = eligible[-1] if eligible else None + trade_side = 0 + trade_quantity = 0.0 + trade_price = float(research_row["mid_price"]) + if selected_trade is not None: + trade_side = 1 if str(selected_trade["aggressor_side"]).lower() == "buy" else -1 + trade_quantity = float(selected_trade["quantity"]) + trade_price = float(selected_trade["price"]) + + output.append( + { + "symbol": symbol, + "continuity_id": continuity, + "sample_id": int(research_row["decision_sequence"]), + "decision_sequence": int(research_row["decision_sequence"]), + # The execution clock is availability/decision time, not exchange event time. + "event_ts_ns": decision_ts, + "decision_ts_ns": decision_ts, + "market_event_ts_ns": int(research_row["market_event_ts_ns"]), + "best_bid": float(research_row["best_bid"]), + "best_ask": float(research_row["best_ask"]), + "mid_price": float(research_row["mid_price"]), + "bid_quantity": float(research_row["bid_quantity"]), + "ask_quantity": float(research_row["ask_quantity"]), + "depth_bid_1": float(research_row["depth_bid_1"]), + "depth_ask_1": float(research_row["depth_ask_1"]), + "tick_size": float(research_row["tick_size"]), + "lot_size": float(research_row["lot_size"]), + "trade_side": trade_side, + "trade_quantity": trade_quantity, + "trade_price": trade_price, + } + ) + return pl.DataFrame(output), { + "clock": "decision_ts_ns derived from available_ts_ns", + "join_rule": ( + "latest trade with previous_decision_ts < trade.available_ts_ns <= decision_ts_ns " + "within symbol and continuity_id" + ), + "multiple_trades_policy": "latest eligible trade retained; earlier interval trades omitted", + "omitted_eligible_trades": omitted_trades, + "trade_only_queue_limitation": True, + } + + +def _indexed_plan_rows(evaluation: pl.DataFrame, indices: NDArray[np.int64]) -> pl.DataFrame: + return evaluation.with_row_index("_evaluation_index").filter( + pl.col("_evaluation_index").is_in(indices.tolist()) + ) + + +def _symbol_quantiles( + frame: pl.DataFrame, + column: str, + quantiles: Sequence[float], + *, + positive_only: bool = False, +) -> dict[str, tuple[float, ...]]: + result: dict[str, tuple[float, ...]] = {} + for partition in frame.partition_by("symbol", maintain_order=True): + symbol = str(partition.get_column("symbol")[0]) + values = partition.get_column(column).drop_nulls().to_numpy().astype(np.float64) + values = values[np.isfinite(values)] + if positive_only: + values = values[values > 0] + if not values.size: + raise PipelineError(f"training partition {symbol} has no finite values for {column}") + result[symbol] = tuple(float(np.quantile(values, value)) for value in quantiles) + return result + + +def _regime_model_performance( + predictions: pl.DataFrame, + regimes: pl.DataFrame, + *, + calibration_bins: int, +) -> pl.DataFrame: + regime_keys = regimes.select( + pl.col("_evaluation_index").alias("row_id"), + "symbol", + "volatility_regime", + "liquidity_regime", + "joint_market_regime", + ) + joined = predictions.join( + regime_keys, + on=["row_id", "symbol"], + how="inner", + validate="m:1", + ) + group_columns = ( + "model", + "family", + "split", + "fold_id", + "symbol", + "volatility_regime", + "liquidity_regime", + "joint_market_regime", + ) + rows: list[dict[str, Any]] = [] + for partition in joined.partition_by(list(group_columns), maintain_order=True): + y_true = partition.get_column("y_true").to_numpy().astype(np.int64) + probability = partition.get_column("probability").to_numpy().astype(np.float64) + start = int(cast(int, partition.get_column("decision_ts_ns").min())) + end = int(cast(int, partition.get_column("decision_ts_ns").max())) + row = {column: partition.get_column(column)[0] for column in group_columns} + row.update( + { + "n_obs": partition.height, + "period_start_utc": _utc_from_ns(start), + "period_end_utc": _utc_from_ns(end), + **classification_metrics( + y_true, + probability, + calibration_bins=calibration_bins, + ), + "threshold_source": "caller_supplied_final_training_period", + "analysis_kind": "regime_model_performance_descriptive", + "descriptive_only": True, + } + ) + rows.append(row) + return pl.DataFrame(rows).sort(list(group_columns)) + + +def _write_descriptive_analysis( + *, + research: pl.DataFrame, + evaluation: pl.DataFrame, + plan: WalkForwardPlan, + execution_events: pl.DataFrame, + model_predictions: pl.DataFrame, + feature_columns: Sequence[str], + config: ProjectConfig, + stage: Path, + generated_at_utc: str, +) -> tuple[dict[str, str], dict[str, Any]]: + """Persist predeclared descriptive diagnostics with train-only thresholds.""" + indexed = evaluation.with_row_index("_evaluation_index") + train = _indexed_plan_rows(evaluation, plan.final_train_indices) + test = _indexed_plan_rows(evaluation, plan.test_indices) + configured_horizon = config.features.label_horizon_events + horizons = sorted({1, max(1, configured_horizon // 2), configured_horizon}) + keys = ["symbol", "continuity_id", "decision_sequence"] + labeled = indexed + return_columns: dict[int, str] = {} + for horizon in horizons: + return_column = f"future_mid_return_h{horizon}" + variant = ( + add_future_event_labels(research, horizon) + .filter(pl.col("feature_ready")) + .select(*keys, pl.col("future_mid_return").alias(return_column)) + ) + labeled = labeled.join(variant, on=keys, how="left", validate="1:1") + return_columns[horizon] = return_column + labeled = labeled.sort("_evaluation_index") + if labeled.height != evaluation.height: + raise PipelineError("descriptive labels do not align one-to-one with evaluation rows") + + intraday = intraday_liquidity_summary(labeled, bucket_minutes=60) + association = ofi_future_return_association( + labeled, + horizon_return_columns=return_columns, + ofi_column="ofi_l1", + ) + half_life = estimate_signal_half_life(association) + cross_instrument = cross_instrument_stability_summary( + association, + value_column="ols_slope_return_per_ofi_unit", + ) + + volatility_column = f"realized_volatility_w{config.features.volatility_window}" + volatility_quantiles = _symbol_quantiles(train, volatility_column, (1 / 3, 2 / 3)) + spread_quantiles = _symbol_quantiles(train, "spread_bps", (1 / 3, 2 / 3)) + depth_quantiles = _symbol_quantiles(train, "depth_total_l1", (1 / 3, 2 / 3)) + regime_thresholds = { + symbol: RegimeThresholds( + volatility_low=volatility_quantiles[symbol][0], + volatility_high=volatility_quantiles[symbol][1], + spread_tight_bps=spread_quantiles[symbol][0], + spread_wide_bps=spread_quantiles[symbol][1], + depth_low=depth_quantiles[symbol][0], + depth_high=depth_quantiles[symbol][1], + ) + for symbol in volatility_quantiles + } + regimes = assign_market_regimes( + labeled, + train_thresholds=regime_thresholds, + volatility_column=volatility_column, + ) + held_out_regimes = regimes.filter(pl.col("_evaluation_index").is_in(plan.test_indices.tolist())) + regime_outcomes = regime_outcome_summary( + held_out_regimes, + outcome_columns=("future_mid_return", "future_mid_up"), + ) + regime_model_performance = _regime_model_performance( + model_predictions.filter(pl.col("split") == "test"), + held_out_regimes, + calibration_bins=config.evaluation.calibration_bins, + ) + + recovery_spread = _symbol_quantiles(train, "spread_bps", (0.5, 0.9)) + recovery_depth = _symbol_quantiles(train, "depth_total_l1", (0.1, 0.5)) + recovery_thresholds = { + symbol: LiquidityShockThresholds( + spread_shock_bps=recovery_spread[symbol][1], + depth_shock_max=recovery_depth[symbol][0], + spread_recovery_bps=recovery_spread[symbol][0], + depth_recovery_min=recovery_depth[symbol][1], + max_recovery_events=max(2, configured_horizon), + ) + for symbol in recovery_spread + } + recovery = liquidity_recovery_summary( + labeled, + train_thresholds=recovery_thresholds, + ) + stability = feature_stability_summary( + train, + test, + feature_columns=feature_columns, + ) + + impact_input = ( + labeled.join( + execution_events.select(*keys, "trade_side", "trade_quantity"), + on=keys, + how="left", + validate="1:1", + ) + .filter((pl.col("trade_quantity") > 0) & (pl.col("trade_side") != 0)) + .with_columns(pl.col(f"future_mid_return_h{configured_horizon}").alias("future_mid_return")) + ) + event_impact = add_event_time_price_impact_labels( + impact_input, + side_column="trade_side", + ) + impact_train = event_impact.filter( + pl.col("_evaluation_index").is_in(plan.final_train_indices.tolist()) + ) + quantity_thresholds = { + symbol: values[0] + for symbol, values in _symbol_quantiles( + impact_train, + "trade_quantity", + (config.features.large_trade_quantile,), + positive_only=True, + ).items() + } + large_trade_impact = large_trade_price_impact_summary( + event_impact, + impact_columns={configured_horizon: "event_time_signed_price_impact_bps"}, + train_quantity_thresholds=quantity_thresholds, + quantity_column="trade_quantity", + ) + + frames = { + "intraday_liquidity": intraday, + "ofi_future_return": association, + "signal_decay_curve": half_life.curve, + "signal_half_life": half_life.summary, + "event_time_impact_labels": event_impact, + "large_trade_price_impact": large_trade_impact, + "liquidity_recovery": recovery, + "market_regimes": regimes, + "regime_outcomes": regime_outcomes, + "regime_model_performance": regime_model_performance, + "cross_instrument_stability": cross_instrument, + "feature_stability": stability, + } + analysis_root = stage / "analysis" + analysis_root.mkdir(parents=True, exist_ok=True) + artifacts: dict[str, str] = {} + for name, frame in frames.items(): + relative = f"analysis/{name}.parquet" + frame.write_parquet(stage / relative) + artifacts[f"analysis_{name}"] = relative + manifest = { + "generated_at_utc": generated_at_utc, + "evidence_tier": _SYNTHETIC_EVIDENCE, + "descriptive_only": True, + "economic_claim_authorized": False, + "threshold_source": "final_training_period_only", + "training_rows": train.height, + "test_rows": test.height, + "event_horizons": horizons, + "artifacts": { + name: {"path": artifacts[f"analysis_{name}"], "rows": frame.height} + for name, frame in frames.items() + }, + "limitations": [ + "Synthetic diagnostics validate computation only.", + "Trade-side impact uses the latest strictly observable interval trade.", + "Regime and shock thresholds are derived only from the final training rows.", + "Regime outcome and model-performance summaries are restricted to the held-out test.", + ], + } + _write_json(analysis_root / "manifest.json", manifest) + artifacts["analysis_manifest"] = "analysis/manifest.json" + return artifacts, manifest + + +def _assert_execution_alignment(events: pl.DataFrame, predictions: pl.DataFrame) -> None: + if predictions.is_empty(): + raise PipelineError("selected model produced no held-out test predictions") + event_keys = { + (str(row["symbol"]), int(row["decision_sequence"])): ( + str(row["continuity_id"]), + int(row["decision_ts_ns"]), + ) + for row in events.select( + "symbol", "decision_sequence", "continuity_id", "decision_ts_ns" + ).to_dicts() + } + for row in predictions.to_dicts(): + key = (str(row["symbol"]), int(row["decision_sequence"])) + expected = event_keys.get(key) + observed = (str(row["continuity_id"]), int(row["decision_ts_ns"])) + if expected is None or expected != observed: + raise PipelineError( + "selected prediction does not match its causal execution event and continuity" + ) + if row.get("split") != "test" or row.get("is_oos") is not True: + raise PipelineError("execution requires validation-selected held-out test predictions") + + +def _execution_metric_row( + metrics: Mapping[str, Any], + *, + model: str, + family: str, + order_label: str, + horizon_events: int, + period_start_utc: str, + period_end_utc: str, + n_obs: int, +) -> dict[str, Any]: + turnover = float(metrics.get("turnover_notional", 0.0)) + fees = float(metrics.get("total_fees", 0.0)) + return { + "model": model if order_label == "market" else f"{model} [limit execution]", + "predictive_model": model, + "family": family, + "instrument": "POOLED", + "instrument_scope": "POOLED", + "horizon_events": horizon_events, + "split": "test", + "n_obs": n_obs, + "period_start_utc": period_start_utc, + "period_end_utc": period_end_utc, + "order_type": order_label, + "gross_bps": metrics.get("gross_edge_bps"), + "fees_bps": fees / turnover * 10_000.0 if turnover else None, + "net_bps": metrics.get("net_edge_bps"), + "fill_rate": metrics.get("fill_ratio"), + "turnover": metrics.get("turnover_notional"), + "max_drawdown": metrics.get("maximum_drawdown"), + "max_drawdown_bps_of_turnover": metrics.get("maximum_drawdown_bps_of_turnover"), + "mean_adverse_selection_bps": metrics.get("mean_adverse_selection_bps"), + "maximum_absolute_inventory_by_symbol": metrics.get("maximum_absolute_inventory_by_symbol"), + "selected_on": "validation", + "evidence_tier": _SYNTHETIC_EVIDENCE, + } + + +def _produce_synthetic(config: ProjectConfig, stage: Path) -> None: + if config.data.mode != "synthetic": + raise PipelineError("synthetic producer requires data.mode='synthetic'") + if config.data.events_per_symbol is None: + raise PipelineError("synthetic configuration requires events_per_symbol") + + generated = provenance_header( + project_root=config.project_root, + config_hash=config.hash, + evidence_tier=_SYNTHETIC_EVIDENCE, + input_manifests=[], + ) + generated_at = cast(str, generated["generated_at_utc"]) + start_ns = datetime_to_ns(config.data.start) + synthetic = generate_synthetic_market( + symbols=config.data.symbols, + events_per_symbol=config.data.events_per_symbol, + start_ts_ns=start_ns, + seed=config.run.seed, + ) + + normalized_root = stage / "data" / "normalized" + requested_end_ns = datetime_to_ns(config.data.end) if config.data.end else None + trades_written = write_partitioned_parquet( + iter_table_batches(synthetic.trades), + root=normalized_root, + dataset="trades", + schema_name="trades", + source=config.data.source, + source_uri="synthetic://local/deterministic-v1", + downloaded_at_utc=generated_at, + requested_start_ns=start_ns, + requested_end_ns=requested_end_ns, + ) + books_written = write_partitioned_parquet( + iter_table_batches(synthetic.book_observations), + root=normalized_root, + dataset="book_observations", + schema_name="book_observations", + source=config.data.source, + source_uri="synthetic://local/deterministic-v1", + downloaded_at_utc=generated_at, + requested_start_ns=start_ns, + requested_end_ns=requested_end_ns, + ) + + quality_reports = ( + validate_table( + synthetic.trades, + "trades", + max_spread_bps=config.quality.max_spread_bps, + max_silence_ns=config.quality.max_silence_ms * 1_000_000, + ), + validate_table( + synthetic.book_observations, + "book_observations", + max_spread_bps=config.quality.max_spread_bps, + max_silence_ns=config.quality.max_silence_ms * 1_000_000, + ), + ) + quality = _quality_payload(quality_reports, generated_at_utc=generated_at) + _write_json(stage / "quality" / "summary.json", quality) + if config.quality.fail_on_error and any(report.has_errors for report in quality_reports): + raise PipelineError("synthetic normalized data failed configured quality gates") + + trades = cast(pl.DataFrame, pl.from_arrow(synthetic.trades)) + books = cast(pl.DataFrame, pl.from_arrow(synthetic.book_observations)) + research = build_research_frame(books, trades, config.features) + temporal_audit = validate_temporal_contract(research) + research_path = stage / "research" / "research_frame.parquet" + research_path.parent.mkdir(parents=True, exist_ok=True) + research.write_parquet(research_path) + + evaluation = research.filter(pl.col("feature_ready")) + if evaluation.is_empty(): + raise PipelineError("causal feature construction produced no feature-ready rows") + evaluation_path = stage / "research" / "evaluation_frame.parquet" + evaluation.write_parquet(evaluation_path) + + plan = expanding_walk_forward_splits(evaluation, config.evaluation) + _write_json(stage / "research" / "folds.json", _serialize_plan(plan)) + ladder = evaluate_model_ladder( + evaluation, + plan, + config.models, + seed=config.run.seed, + calibration_bins=config.evaluation.calibration_bins, + ) + predictive_rows, predictions = _bootstrap_comparison( + ladder.comparison, + ladder.predictions, + metric=ladder.selection_metric, + n_bootstrap=config.evaluation.bootstrap_samples, + seed=config.run.seed + 10_000, + horizon_events=config.features.label_horizon_events, + ) + _write_json(stage / "metrics" / "predictive_metrics.json", predictive_rows) + predictions_path = stage / "models" / "predictions.parquet" + predictions_path.parent.mkdir(parents=True, exist_ok=True) + predictions.write_parquet(predictions_path) + selected_predictions = predictions.filter( + (pl.col("split") == "test") & (pl.col("model") == ladder.selected_model) + ) + selected_path = stage / "models" / "selected_test_predictions.parquet" + selected_predictions.write_parquet(selected_path) + + execution_events, adapter_assumptions = _execution_events(research, trades) + analysis_artifacts, analysis_manifest = _write_descriptive_analysis( + research=research, + evaluation=evaluation, + plan=plan, + execution_events=execution_events, + model_predictions=predictions, + feature_columns=ladder.feature_columns, + config=config, + stage=stage, + generated_at_utc=generated_at, + ) + _assert_execution_alignment(execution_events, selected_predictions) + execution_events_path = stage / "execution" / "events.parquet" + execution_events_path.parent.mkdir(parents=True, exist_ok=True) + execution_events.write_parquet(execution_events_path) + market_result = simulate_predictions( + execution_events, + selected_predictions, + config.execution, + order_type="market", + seed=config.run.seed, + markout_events=config.features.label_horizon_events, + ) + limit_result = simulate_predictions( + execution_events, + selected_predictions, + config.execution, + order_type="limit", + seed=config.run.seed, + markout_events=config.features.label_horizon_events, + ) + sensitivity = run_execution_sensitivity( + execution_events, + selected_predictions, + config.execution, + seed=config.run.seed, + markout_events=config.features.label_horizon_events, + ) + sensitivity_parquet = _mapping_columns_as_json(sensitivity) + for name, frame in ( + ("market_orders", market_result.orders), + ("market_fills", market_result.fills), + ("market_positions", market_result.positions), + ("limit_orders", limit_result.orders), + ("limit_fills", limit_result.fills), + ("limit_positions", limit_result.positions), + ("capacity_sensitivity", sensitivity_parquet), + ): + frame.write_parquet(stage / "execution" / f"{name}.parquet") + + selected_comparison = ladder.comparison.filter( + (pl.col("split") == "test") & (pl.col("model") == ladder.selected_model) + ) + if selected_comparison.height != 1: + raise PipelineError("selected model must have exactly one final-test comparison row") + selected_metric = selected_comparison.to_dicts()[0] + family = str(selected_metric["family"]) + period_start = str(selected_metric["period_start_utc"]) + period_end = str(selected_metric["period_end_utc"]) + execution_rows = [ + _execution_metric_row( + market_result.metrics, + model=ladder.selected_model, + family=family, + order_label="market", + horizon_events=config.features.label_horizon_events, + period_start_utc=period_start, + period_end_utc=period_end, + n_obs=selected_predictions.height, + ), + _execution_metric_row( + limit_result.metrics, + model=ladder.selected_model, + family=family, + order_label="limit", + horizon_events=config.features.label_horizon_events, + period_start_utc=period_start, + period_end_utc=period_end, + n_obs=selected_predictions.height, + ), + ] + _write_json(stage / "metrics" / "execution_metrics.json", execution_rows) + _write_json(stage / "metrics" / "execution_sensitivity.json", sensitivity.to_dicts()) + + market_columns = [ + "symbol", + "decision_ts_ns", + "mid_price", + "spread_bps", + "depth_total_l1", + "queue_imbalance_l1", + "ofi_l1", + "feature_ready", + ] + volatility_columns = [ + name for name in research.columns if name.startswith("realized_volatility_w") + ] + market_state = research.select( + *market_columns, + *volatility_columns, + pl.lit(_SYNTHETIC_EVIDENCE).alias("evidence_tier"), + ).sort(["decision_ts_ns", "symbol"]) + market_state_path = stage / "dashboard" / "market_state.parquet" + market_state_path.parent.mkdir(parents=True, exist_ok=True) + market_state.write_parquet(market_state_path) + + available_values = [ + int(cast(int, synthetic.trades.column("available_ts_ns").to_pylist()[0])), + int(cast(int, synthetic.book_observations.column("available_ts_ns").to_pylist()[0])), + ] + observed_start_ns = min(available_values) + observed_end_ns = max( + int(cast(int, synthetic.trades.column("available_ts_ns").to_pylist()[-1])), + int(cast(int, synthetic.book_observations.column("available_ts_ns").to_pylist()[-1])), + ) + data_snapshot = { + "schema_version": PIPELINE_SCHEMA_VERSION, + "source": config.data.source, + "source_uri": "synthetic://local/deterministic-v1", + "evidence_tier": _SYNTHETIC_EVIDENCE, + "requested_period_utc": { + "start": config.data.start.isoformat().replace("+00:00", "Z"), + "end": config.data.end.isoformat().replace("+00:00", "Z") if config.data.end else None, + }, + "observed_period_utc": { + "start": _utc_from_ns(observed_start_ns), + "end": _utc_from_ns(observed_end_ns), + }, + "datasets": [ + _dataset_snapshot(trades_written, stage), + _dataset_snapshot(books_written, stage), + ], + } + _write_json(stage / "data" / "manifest_snapshot.json", data_snapshot) + + input_hashes = sorted([trades_written.manifest_sha256, books_written.manifest_sha256]) + input_identity_hashes = _input_identity_hashes((trades_written, books_written)) + git_metadata = cast(Mapping[str, Any], generated["git"]) + run_key, run_key_inputs = _run_identity( + config_sha256=config.hash, + input_identity_sha256=input_identity_hashes, + git=git_metadata, + seed=config.run.seed, + ) + generated["input_manifest_sha256"] = input_hashes + generated.update( + { + "run_key": run_key, + "run_key_inputs": run_key_inputs, + "pipeline_schema_version": PIPELINE_SCHEMA_VERSION, + "seed": config.run.seed, + "requested_evidence_tier": config.run.evidence_tier, + "effective_evidence_tier": _SYNTHETIC_EVIDENCE, + "observed_start_utc": _utc_from_ns(observed_start_ns), + "observed_end_utc": _utc_from_ns(observed_end_ns), + } + ) + _write_json(stage / "provenance.json", generated) + resolved_config = config.public_dict() + resolved_config["effective_evidence_tier"] = _SYNTHETIC_EVIDENCE + _write_json(stage / "resolved_config.json", resolved_config) + + run_manifest = { + "schema_version": PIPELINE_SCHEMA_VERSION, + "run_id": config.run.name, + "run_key": run_key, + "status": "complete", + "evidence_tier": _SYNTHETIC_EVIDENCE, + "data": { + "mode": "synthetic", + "source": config.data.source, + "symbols": list(config.data.symbols), + "observed_start_utc": _utc_from_ns(observed_start_ns), + "observed_end_utc": _utc_from_ns(observed_end_ns), + "observed_start_ts_ns": observed_start_ns, + "observed_end_ts_ns": observed_end_ns, + }, + "artifacts": { + "resolved_config": "resolved_config.json", + "data_manifest_snapshot": "data/manifest_snapshot.json", + "quality_summary": "quality/summary.json", + "research_frame": "research/research_frame.parquet", + "evaluation_frame": "research/evaluation_frame.parquet", + "folds": "research/folds.json", + "predictions": "models/predictions.parquet", + "selected_test_predictions": "models/selected_test_predictions.parquet", + "predictive_metrics": "metrics/predictive_metrics.json", + "execution_metrics": "metrics/execution_metrics.json", + "execution_sensitivity": "metrics/execution_sensitivity.json", + "market_state": "dashboard/market_state.parquet", + "technical_report": "reports/technical_report.md", + "executive_memo": "reports/executive_memo.md", + "model_comparison": "reports/model_comparison.md", + **analysis_artifacts, + }, + "research": { + **asdict(temporal_audit), + "feature_ready_rows": evaluation.height, + "evaluation_rows": evaluation.height, + "evaluation_frame": "research/evaluation_frame.parquet", + "fold_index_basis": "zero-based rows of the persisted evaluation frame", + "selected_model": ladder.selected_model, + "selection_metric": ladder.selection_metric, + "feature_columns": list(ladder.feature_columns), + "model_candidates": sorted( + str(value) for value in ladder.comparison.get_column("model").unique() + ), + "descriptive_analysis": { + "manifest": analysis_artifacts["analysis_manifest"], + "descriptive_only": analysis_manifest["descriptive_only"], + "threshold_source": analysis_manifest["threshold_source"], + "event_horizons": analysis_manifest["event_horizons"], + }, + "test_start_utc": _utc_from_ns(plan.test_start_ts_ns), + "test_end_utc": _utc_from_ns(plan.test_end_ts_ns), + }, + "execution_assumptions": { + "market": market_result.assumptions, + "limit": limit_result.assumptions, + "event_adapter": adapter_assumptions, + }, + "warnings": [ + "Synthetic output validates software behavior only and is not market evidence.", + "Execution is exogenous simulation; no live order path exists.", + ( + f"Requested evidence tier {config.run.evidence_tier} was overridden by " + "SYNTHETIC_SMOKE because the source is synthetic." + if config.run.evidence_tier != _SYNTHETIC_EVIDENCE + else "Synthetic evidence tier was preserved." + ), + ], + } + _write_json(stage / "run_manifest.json", run_manifest) + + provisional = load_run_bundle(stage, require_complete=False, verify_integrity=False) + _atomic_write_text( + stage / "reports" / "technical_report.md", + render_technical_report(provisional), + ) + _atomic_write_text( + stage / "reports" / "executive_memo.md", + render_executive_memo(provisional), + ) + _atomic_write_text( + stage / "reports" / "model_comparison.md", + render_model_comparison(provisional), + ) + + write_checksum_manifest(stage) + success_descriptor = os.open(stage / "_SUCCESS", os.O_CREAT | os.O_EXCL | os.O_WRONLY) + with os.fdopen(success_descriptor, "w", encoding="utf-8") as success: + success.write("complete\n") + load_run_bundle(stage) + + +def _produce( + config: ProjectConfig, + stage: Path, + *, + ingestion_manifest_path: str | Path | None, + ingestion_manifest_sha256: str | None, +) -> None: + if config.data.mode == "synthetic": + _produce_synthetic(config, stage) + return + if config.data.mode != "binance_rest": + raise PipelineError( + f"no research-run producer is registered for data mode {config.data.mode!r}" + ) + if ingestion_manifest_path is None or ingestion_manifest_sha256 is None: + raise PipelineError( + "public reproduction requires an explicit ingestion manifest path and SHA-256" + ) + from microstructure.public_pipeline import produce_public_trade_run + + produce_public_trade_run( + config, + stage, + ingestion_manifest_path=ingestion_manifest_path, + ingestion_manifest_sha256=ingestion_manifest_sha256, + ) + + +def reproduce( + config: ProjectConfig, + run_dir: Path, + *, + ingestion_manifest_path: str | Path | None = None, + ingestion_manifest_sha256: str | None = None, +) -> Path: + """Produce or verify one immutable research run bundle. + + A verified completed target is reused without changing a byte. An existing + incomplete target is never repaired or overwritten. New output is built in a + sibling staging directory, verified, and atomically renamed into place. + Public-data runs require an explicit content-hashed ingestion-manifest anchor; + synthetic runs reject one so their input contract cannot be confused. + """ + anchored = ingestion_manifest_path is not None or ingestion_manifest_sha256 is not None + normalized_ingestion_sha256 = ( + ingestion_manifest_sha256.lower() if ingestion_manifest_sha256 is not None else None + ) + if (ingestion_manifest_path is None) != (ingestion_manifest_sha256 is None): + raise PipelineError("ingestion manifest path and SHA-256 must be supplied together") + if config.data.mode == "synthetic" and anchored: + raise PipelineError("synthetic reproduction does not accept a public input manifest") + if config.data.mode == "binance_rest" and not anchored: + raise PipelineError( + "public reproduction requires an explicit ingestion manifest path and SHA-256" + ) + if config.data.mode == "binance_rest": + if ingestion_manifest_path is None or ingestion_manifest_sha256 is None: + raise PipelineError("public ingestion anchor is incomplete") + public_manifest_path = Path(ingestion_manifest_path).resolve() + if not public_manifest_path.is_file(): + raise PipelineError(f"public ingestion manifest does not exist: {public_manifest_path}") + observed_manifest_sha = sha256_file(public_manifest_path) + if observed_manifest_sha != normalized_ingestion_sha256: + raise PipelineError("public ingestion manifest bytes do not match the supplied SHA-256") + + target = run_dir.resolve() + if target.exists(): + if target.is_dir() and (target / "_SUCCESS").is_file(): + bundle = load_run_bundle(target) + if bundle.provenance.get("config_sha256") != config.hash: + raise PipelineError( + "completed run target was produced from a different configuration" + ) + if bundle.run_id != config.run.name: + raise PipelineError( + "completed run target has a different run ID than the configuration" + ) + current_state = git_state(config.project_root) + current_git = { + "commit": current_state.commit, + "dirty": current_state.dirty, + "source_tree_sha256": git_source_tree_sha256(config.project_root), + } + bundled_git = bundle.provenance.get("git") + if not isinstance(bundled_git, Mapping) or any( + bundled_git.get(key) != value for key, value in current_git.items() + ): + raise PipelineError( + "completed run target was produced from a different Git/source-tree state" + ) + if ( + config.data.mode == "binance_rest" + and bundle.provenance.get("ingestion_manifest_sha256") + != normalized_ingestion_sha256 + ): + raise PipelineError( + "completed run target was produced from a different ingestion manifest" + ) + return target + raise PipelineError( + f"run target already exists but is not a verified completed bundle: {target}" + ) + + target.parent.mkdir(parents=True, exist_ok=True) + stage = Path(tempfile.mkdtemp(prefix=f".{target.name}.staging-", dir=target.parent)).resolve() + try: + _produce( + config, + stage, + ingestion_manifest_path=ingestion_manifest_path, + ingestion_manifest_sha256=normalized_ingestion_sha256, + ) + if target.exists(): + raise PipelineError(f"run target appeared during production: {target}") + stage.rename(target) + load_run_bundle(target) + return target + except BaseException: + if stage.exists(): + shutil.rmtree(stage) + raise + + +__all__ = ["PipelineError", "reproduce"] diff --git a/Microstructure/src/microstructure/provenance.py b/Microstructure/src/microstructure/provenance.py new file mode 100644 index 0000000000000000000000000000000000000000..febfc915dc82b50568901101f23a4acfd95e5e2e --- /dev/null +++ b/Microstructure/src/microstructure/provenance.py @@ -0,0 +1,339 @@ +"""Checksums, Git state, and JSON artifact helpers.""" + +from __future__ import annotations + +import hashlib +import json +import os +import platform +import stat +import subprocess +import sys +import tempfile +from collections.abc import Mapping +from dataclasses import asdict, dataclass +from datetime import UTC, datetime +from pathlib import Path +from types import ModuleType +from typing import Any + + +@dataclass(frozen=True, slots=True) +class GitState: + commit: str + dirty: bool + + +class ImportOriginError(RuntimeError): + """Raised when loaded project code does not belong to one source root.""" + + +def _canonical_absolute_path(value: str | Path, label: str) -> Path: + path = Path(value) + if not path.is_absolute() or path != Path(os.path.abspath(path)): + raise ImportOriginError(f"{label} must be a canonical absolute path") + return path + + +def _reject_symlink_path(path: Path, label: str) -> None: + """Reject a missing path or any symlink component without following it.""" + + current = Path(path.anchor) + for component in path.parts[1:]: + current /= component + try: + metadata = current.lstat() + except OSError as error: + raise ImportOriginError(f"cannot inspect {label}: {current}") from error + if stat.S_ISLNK(metadata.st_mode): + raise ImportOriginError(f"{label} contains symlink component: {current}") + + +def _loaded_module(value: str | ModuleType) -> tuple[str, ModuleType]: + if isinstance(value, str): + name = value + module = sys.modules.get(name) + if not isinstance(module, ModuleType): + raise ImportOriginError(f"required project module is not loaded: {name}") + elif isinstance(value, ModuleType): + module = value + name = module.__name__ + if not name or sys.modules.get(name) is not module: + raise ImportOriginError( + "loaded project module object is not its canonical sys.modules entry" + ) + else: + raise TypeError("project module authorities must be module names or module objects") + if name != "microstructure" and not name.startswith("microstructure."): + raise ImportOriginError(f"module is outside the microstructure namespace: {name}") + return name, module + + +def assert_project_module_origins( + project_root: str | Path, + *modules: str | ModuleType, +) -> None: + """Prove that loaded project modules come from one unsymlinked checkout. + + The check is intentionally about the code that Python actually loaded, not + merely the checkout whose bytes were hashed for provenance. Every module + and its loaded parent packages must have a canonical ``__file__`` matching + its name below ``/src/microstructure``. Package search paths + must contain exactly that one directory, closing mixed/editable namespace + cases where a clean checkout is hashed while code executes elsewhere. + """ + + root = _canonical_absolute_path(project_root, "project root") + source_root = root / "src" / "microstructure" + _reject_symlink_path(source_root, "project source root") + try: + source_metadata = source_root.lstat() + except OSError as error: # pragma: no cover - covered by path walk above + raise ImportOriginError("project source root is unavailable") from error + if not stat.S_ISDIR(source_metadata.st_mode): + raise ImportOriginError("project source root is not a regular directory") + try: + resolved_source_root = source_root.resolve(strict=True) + except OSError as error: # pragma: no cover - covered by path walk above + raise ImportOriginError("project source root cannot be resolved") from error + + requested: dict[str, ModuleType] = {} + for value in ("microstructure", "microstructure.provenance", *modules): + name, module = _loaded_module(value) + previous = requested.setdefault(name, module) + if previous is not module: + raise ImportOriginError(f"mixed loaded module objects for {name}") + components = name.split(".") + for length in range(1, len(components)): + parent_name = ".".join(components[:length]) + parent, parent_module = _loaded_module(parent_name) + previous_parent = requested.setdefault(parent, parent_module) + if previous_parent is not parent_module: + raise ImportOriginError(f"mixed loaded module objects for {parent}") + + for name, module in sorted(requested.items()): + raw_file = getattr(module, "__file__", None) + if type(raw_file) is not str or not raw_file: + raise ImportOriginError(f"loaded project module lacks __file__ authority: {name}") + observed = _canonical_absolute_path(raw_file, f"loaded module {name}") + _reject_symlink_path(observed, f"loaded module {name}") + try: + metadata = observed.lstat() + resolved = observed.resolve(strict=True) + except OSError as error: + raise ImportOriginError(f"loaded project module is unavailable: {name}") from error + if not stat.S_ISREG(metadata.st_mode): + raise ImportOriginError(f"loaded project module is not a regular source file: {name}") + try: + resolved.relative_to(resolved_source_root) + except ValueError as error: + raise ImportOriginError( + f"loaded project module comes from a foreign source root: {name}" + ) from error + + relative_parts = name.split(".")[1:] + package_path = getattr(module, "__path__", None) + if package_path is None: + expected = source_root.joinpath(*relative_parts).with_suffix(".py") + else: + expected_directory = source_root.joinpath(*relative_parts) + try: + search_paths = tuple(package_path) + except TypeError as error: + raise ImportOriginError( + f"loaded package search path is malformed: {name}" + ) from error + if len(search_paths) != 1 or type(search_paths[0]) is not str: + raise ImportOriginError(f"loaded package has a mixed namespace path: {name}") + search_path = _canonical_absolute_path( + search_paths[0], f"loaded package search path {name}" + ) + _reject_symlink_path(search_path, f"loaded package search path {name}") + try: + resolved_search_path = search_path.resolve(strict=True) + except OSError as error: + raise ImportOriginError(f"loaded package path is unavailable: {name}") from error + if resolved_search_path != expected_directory: + raise ImportOriginError(f"loaded package has a foreign namespace path: {name}") + expected = expected_directory / "__init__.py" + if resolved != expected: + raise ImportOriginError( + f"loaded project module path does not match its module name: {name}" + ) + + +def sha256_file(path: str | Path, chunk_size: int = 1024 * 1024) -> str: + """Hash a file without loading it into memory.""" + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + while chunk := handle.read(chunk_size): + digest.update(chunk) + return digest.hexdigest() + + +def utc_now_iso() -> str: + return datetime.now(UTC).isoformat().replace("+00:00", "Z") + + +def git_state(project_root: str | Path) -> GitState: + """Return the repository commit and dirty state, including unborn repos.""" + root = Path(project_root) + revision = subprocess.run( + ["git", "rev-parse", "HEAD"], + cwd=root, + check=False, + capture_output=True, + text=True, + ) + commit = revision.stdout.strip() if revision.returncode == 0 else "UNBORN" + status = subprocess.run( + ["git", "status", "--porcelain"], + cwd=root, + check=False, + capture_output=True, + text=True, + ) + return GitState(commit=commit, dirty=bool(status.stdout.strip())) + + +def strict_git_state(project_root: str | Path) -> GitState: + """Return Git identity only when both revision and status commands succeed. + + Generic sample workflows intentionally retain ``git_state``'s historical + non-repository fallback. Prospective producers use this stricter boundary + so a failed ``git status`` can never masquerade as a clean worktree. + """ + + root = Path(project_root) + environment = {**os.environ, "GIT_OPTIONAL_LOCKS": "0"} + revision = subprocess.run( + ["git", "rev-parse", "HEAD"], + cwd=root, + check=False, + capture_output=True, + text=True, + env=environment, + ) + status = subprocess.run( + ["git", "status", "--porcelain"], + cwd=root, + check=False, + capture_output=True, + text=True, + env=environment, + ) + if revision.returncode != 0 or status.returncode != 0: + raise RuntimeError("unable to determine strict Git working-tree identity") + return GitState(commit=revision.stdout.strip(), dirty=bool(status.stdout.strip())) + + +def git_source_tree_sha256(project_root: str | Path) -> str: + """Hash exact tracked and non-ignored untracked working-tree bytes. + + The Git revision plus a dirty boolean cannot distinguish two different + patches on the same commit. This digest is path-stable, excludes ignored + raw/run artifacts, and streams file content so provenance remains exact + without loading the source tree into memory. + """ + requested_root = Path(project_root).resolve() + repository = subprocess.run( + ["git", "rev-parse", "--show-toplevel"], + cwd=requested_root, + check=False, + capture_output=True, + text=True, + ) + if repository.returncode != 0: + return hashlib.sha256(b"NOT_A_GIT_WORKTREE").hexdigest() + repository_root = Path(repository.stdout.strip()).resolve() + listing = subprocess.run( + ["git", "ls-files", "-z", "--cached", "--others", "--exclude-standard"], + cwd=repository_root, + check=False, + capture_output=True, + ) + if listing.returncode != 0: + raise RuntimeError("unable to enumerate Git source-tree files") + + digest = hashlib.sha256() + relative_paths = sorted(item for item in listing.stdout.split(b"\0") if item) + for encoded_relative in relative_paths: + relative = Path(os.fsdecode(encoded_relative)) + path = repository_root / relative + digest.update(len(encoded_relative).to_bytes(8, "big")) + digest.update(encoded_relative) + if path.exists() or path.is_symlink(): + digest.update((path.lstat().st_mode & 0o7777).to_bytes(4, "big")) + if path.is_symlink(): + target = os.readlink(path).encode("utf-8", errors="surrogateescape") + digest.update(b"SYMLINK\0") + digest.update(len(target).to_bytes(8, "big")) + digest.update(target) + elif path.is_file(): + digest.update(b"FILE\0") + digest.update(sha256_file(path).encode()) + elif path.exists(): + digest.update(b"OTHER\0") + else: + digest.update(b"MISSING\0") + return digest.hexdigest() + + +def runtime_metadata() -> dict[str, str]: + return { + "python": sys.version.split()[0], + "platform": platform.platform(), + "machine": platform.machine(), + } + + +def write_json(path: str | Path, payload: Mapping[str, Any] | list[Any]) -> None: + """Atomically write stable, human-readable JSON.""" + destination = Path(path) + destination.parent.mkdir(parents=True, exist_ok=True) + handle, temporary_name = tempfile.mkstemp( + dir=destination.parent, + prefix=f".{destination.name}.", + suffix=".tmp", + text=True, + ) + try: + with os.fdopen(handle, "w", encoding="utf-8") as stream: + json.dump(payload, stream, indent=2, sort_keys=True, allow_nan=False) + stream.write("\n") + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary_name, destination) + directory_descriptor = os.open(destination.parent, os.O_RDONLY) + try: + os.fsync(directory_descriptor) + finally: + os.close(directory_descriptor) + except BaseException: + Path(temporary_name).unlink(missing_ok=True) + raise + + +def read_json(path: str | Path) -> Any: + with Path(path).open(encoding="utf-8") as handle: + return json.load(handle) + + +def provenance_header( + *, + project_root: str | Path, + config_hash: str, + evidence_tier: str, + input_manifests: list[str], +) -> dict[str, Any]: + state = git_state(project_root) + git = asdict(state) + git["source_tree_sha256"] = git_source_tree_sha256(project_root) + return { + "generated_at_utc": utc_now_iso(), + "evidence_tier": evidence_tier, + "config_sha256": config_hash, + "input_manifest_sha256": sorted(input_manifests), + "git": git, + "runtime": runtime_metadata(), + } diff --git a/Microstructure/src/microstructure/public_data.py b/Microstructure/src/microstructure/public_data.py new file mode 100644 index 0000000000000000000000000000000000000000..aeb21e0b421cb9e9ba69a1f99f1440a5694d2c3d --- /dev/null +++ b/Microstructure/src/microstructure/public_data.py @@ -0,0 +1,2299 @@ +"""Bounded, manifest-anchored loading of normalized public trade data. + +The reader deliberately starts from an immutable ingestion manifest rather than +discovering Parquet files in a directory. It verifies the caller's ingestion +manifest digest, the referenced normalized-data manifest digest, every declared +part and sidecar digest, and the coverage/evidence claims before returning data. +""" + +from __future__ import annotations + +import re +import sqlite3 +import tempfile +from collections.abc import Generator, Iterator, Mapping +from dataclasses import dataclass +from datetime import UTC, datetime +from decimal import Decimal, InvalidOperation +from pathlib import Path +from types import MappingProxyType +from typing import Any, Literal, cast +from urllib.parse import parse_qsl, urlsplit + +import duckdb +import polars as pl +import pyarrow as pa # type: ignore[import-untyped] +import pyarrow.parquet as pq # type: ignore[import-untyped] + +from microstructure.config import ProjectConfig, datetime_to_ns +from microstructure.data.quality import IncrementalQualityValidator, ValidationReport +from microstructure.data.schemas import SCHEMA_VERSION, ensure_schema, get_schema +from microstructure.data.storage import MANIFEST_VERSION +from microstructure.provenance import read_json, sha256_file + +PublicEvidenceTier = Literal["PUBLIC_SAMPLE_PARTIAL", "FULL_DATA"] +_SHA256 = re.compile(r"^[0-9a-f]{64}$") +_NS_PER_SECOND = 1_000_000_000 +# Matches the downloader's public-response ceiling. The reader checks this +# before JSON parsing so a recomputed manifest cannot turn one "page" into an +# unbounded-memory payload by inserting giant unused strings. +_MAX_RAW_ARTIFACT_BYTES = 8 * 1024 * 1024 +_MAX_JSON_STRING_BYTES = 64 * 1024 +_JSON_BASE_BYTES = 256 * 1024 +_JSON_BYTES_PER_STRUCTURE_TOKEN = 32 * 1024 +_PARQUET_BASE_BYTES = 1024 * 1024 +_PARQUET_BYTES_PER_TRADE_ROW = 4096 +_MAX_PARQUET_PART_ENCODED_BYTES = 64 * 1024 * 1024 +_MAX_PARQUET_PART_DECODED_BYTES = 128 * 1024 * 1024 + +__all__ = [ + "ObservedUtcCoverage", + "PublicDataError", + "PublicEvidenceTier", + "PublicTradeDataset", + "PublicTrades", + "SymbolObservedCoverage", + "VerifiedPublicTradeBatchStream", + "read_public_trades", + "verify_public_trade_dataset", +] + + +class PublicDataError(RuntimeError): + """Raised when a public normalized input cannot be verified safely.""" + + +@dataclass(frozen=True, slots=True) +class ObservedUtcCoverage: + """Exact inclusive event-time coverage for a bounded set of rows.""" + + start_ns: int + end_inclusive_ns: int + start_utc: str + end_inclusive_utc: str + + +@dataclass(frozen=True, slots=True) +class SymbolObservedCoverage: + """Actual rows and event-time coverage for one manifested symbol.""" + + symbol: str + rows: int + complete_range: bool + tick_size: Decimal + lot_size: Decimal + observed: ObservedUtcCoverage + + +@dataclass(frozen=True, slots=True) +class PublicTrades: + """Verified public trades in Arrow and Polars representations.""" + + arrow_trades: pa.Table + polars_trades: pl.DataFrame + observed: ObservedUtcCoverage + symbols: tuple[SymbolObservedCoverage, ...] + evidence_tier: PublicEvidenceTier + all_requested_ranges_complete: bool + ingestion_manifest_path: Path + ingestion_manifest_sha256: str + dataset_manifest_path: Path + dataset_manifest_sha256: str + part_paths: tuple[Path, ...] + raw_artifact_paths: tuple[Path, ...] + raw_manifest_paths: tuple[Path, ...] + raw_artifact_sha256s: tuple[str, ...] + validation: ValidationReport + row_bound: int + canonical_order: tuple[str, ...] + + @property + def rows(self) -> int: + return cast(int, self.arrow_trades.num_rows) + + @property + def input_manifest_sha256s(self) -> tuple[str, ...]: + return tuple(sorted({self.ingestion_manifest_sha256, self.dataset_manifest_sha256})) + + +@dataclass(frozen=True, slots=True) +class _ParquetPartDescriptor: + """Verified metadata needed to stream one normalized Parquet part.""" + + data_path: Path + data_sha256: str + sidecar_path: Path + rows: int + write_ordinal: int + venue: str + symbol: str + partition_date: str + observed_start_ns: int + observed_end_inclusive_ns: int + + +@dataclass(frozen=True, slots=True) +class _RawPageDescriptor: + """A bounded raw page descriptor; raw records are deliberately not retained.""" + + path: Path + sha256: str + symbol: str + from_id: int | None + rows: int + first_id: int | None + last_id: int | None + + +@dataclass(frozen=True, slots=True) +class _VerifiedStreamSummary: + validation: ValidationReport + observed: ObservedUtcCoverage + symbols: tuple[SymbolObservedCoverage, ...] + + +class VerifiedPublicTradeBatchStream(Iterator[pa.RecordBatch]): + """One fresh, bounded validation operation over a public trade data set. + + The final validation and observed-coverage summary become available only + after the iterator is exhausted. Closing early releases DuckDB, SQLite, + and temporary spill resources without claiming that the data were fully + validated. One upstream Parquet pass is audited in immutable physical/write + order and fed directly into DuckDB's bounded external sort; the resulting + research batches are deterministic without rereading the source parts. + """ + + def __init__( + self, + generator: Generator[pa.RecordBatch, None, _VerifiedStreamSummary], + *, + fail_on_error: bool, + ) -> None: + self._generator = generator + self._fail_on_error = fail_on_error + self._summary: _VerifiedStreamSummary | None = None + self._closed = False + + def __iter__(self) -> VerifiedPublicTradeBatchStream: + return self + + def __next__(self) -> pa.RecordBatch: + if self._closed: + raise StopIteration + try: + return next(self._generator) + except StopIteration as stop: + self._closed = True + self._summary = cast(_VerifiedStreamSummary, stop.value) + if self._fail_on_error and self._summary.validation.has_errors: + raise PublicDataError( + "public normalized trades failed quality validation with " + f"{self._summary.validation.error_count} error findings" + ) from None + raise + except BaseException: + self._closed = True + raise + + @property + def summary(self) -> _VerifiedStreamSummary: + if self._summary is None: + raise RuntimeError("verified public batch stream has not been fully consumed") + return self._summary + + @property + def validation(self) -> ValidationReport: + return self.summary.validation + + def close(self) -> None: + if not self._closed: + self._generator.close() + self._closed = True + + +class _PhysicalAuditBatchSource(Iterator[pa.RecordBatch]): + """Adapt an audited generator to Arrow's one-input-pass reader API.""" + + def __init__( + self, + generator: Generator[pa.RecordBatch, None, _VerifiedStreamSummary], + ) -> None: + self._generator = generator + self._summary: _VerifiedStreamSummary | None = None + self._closed = False + + def __iter__(self) -> _PhysicalAuditBatchSource: + return self + + def __next__(self) -> pa.RecordBatch: + if self._closed: + raise StopIteration + try: + return next(self._generator) + except StopIteration as stop: + self._closed = True + self._summary = cast(_VerifiedStreamSummary, stop.value) + raise + except BaseException: + self._closed = True + raise + + @property + def summary(self) -> _VerifiedStreamSummary: + if self._summary is None: + raise RuntimeError("physical public-data audit has not been fully consumed") + return self._summary + + def close(self) -> None: + if not self._closed: + self._generator.close() + self._closed = True + + +@dataclass(frozen=True, slots=True) +class PublicTradeDataset: + """Manifest-verified descriptors for a potentially large public data set. + + Construction reads and hashes manifests, sidecars, Parquet footers, and + bounded raw API pages, but never materializes normalized Parquet rows. + Every call to :meth:`iter_verified_batches` creates an independent bounded + operation whose Arrow batch size and DuckDB sort memory are explicit. + """ + + rows: int + observed: ObservedUtcCoverage + symbols: tuple[SymbolObservedCoverage, ...] + evidence_tier: PublicEvidenceTier + all_requested_ranges_complete: bool + ingestion_manifest_path: Path + ingestion_manifest_sha256: str + dataset_manifest_path: Path + dataset_manifest_sha256: str + part_paths: tuple[Path, ...] + raw_artifact_paths: tuple[Path, ...] + raw_manifest_paths: tuple[Path, ...] + raw_artifact_sha256s: tuple[str, ...] + row_bound: int + canonical_order: tuple[str, ...] + _config: ProjectConfig + _requested_range: tuple[int, int] + _symbol_claims: Mapping[str, _SymbolClaim] + _parts: tuple[_ParquetPartDescriptor, ...] + _raw_pages_by_digest: Mapping[str, _RawPageDescriptor] + _ordered_raw_pages: Mapping[str, tuple[_RawPageDescriptor, ...]] + + @property + def input_manifest_sha256s(self) -> tuple[str, ...]: + return tuple(sorted({self.ingestion_manifest_sha256, self.dataset_manifest_sha256})) + + def iter_verified_batches( + self, + *, + batch_rows: int = 65_536, + memory_limit: str = "256MB", + temp_directory: str | Path | None = None, + ) -> VerifiedPublicTradeBatchStream: + """Return a fresh bounded stream in deterministic canonical order.""" + if isinstance(batch_rows, bool) or not isinstance(batch_rows, int) or batch_rows < 1: + raise ValueError("batch_rows must be a positive integer") + if not isinstance(memory_limit, str) or not memory_limit.strip(): + raise ValueError("memory_limit must be a non-empty DuckDB memory size") + return VerifiedPublicTradeBatchStream( + _stream_verified_batches( + self, + batch_rows=batch_rows, + memory_limit=memory_limit, + temp_directory=temp_directory, + ), + fail_on_error=self._config.quality.fail_on_error, + ) + + def validate( + self, + *, + batch_rows: int = 65_536, + memory_limit: str = "256MB", + temp_directory: str | Path | None = None, + ) -> ValidationReport: + """Validate all rows incrementally without retaining normalized data.""" + stream = self.iter_verified_batches( + batch_rows=batch_rows, + memory_limit=memory_limit, + temp_directory=temp_directory, + ) + try: + for _ in stream: + pass + return stream.validation + finally: + stream.close() + + +@dataclass(frozen=True, slots=True) +class _SymbolClaim: + rows: int + complete_range: bool + tick_size: Decimal + lot_size: Decimal + terminal: _TerminalClaim | None + + +@dataclass(frozen=True, slots=True) +class _TerminalClaim: + raw_page_count: int + stop_reason: str + last_raw_page_sha256: str + last_path: str + last_manifest_path: str + last_request_uri: str + last_row_count: int + + +@dataclass(frozen=True, slots=True) +class _VerifiedRawArtifacts: + paths: tuple[Path, ...] + manifest_paths: tuple[Path, ...] + sha256s: frozenset[str] + pages_by_digest: Mapping[str, _RawPageDescriptor] + ordered_pages: Mapping[str, tuple[_RawPageDescriptor, ...]] + + +@dataclass(frozen=True, slots=True) +class _RawAggregateTrade: + aggregate_id: int + first_trade_id: int + last_trade_id: int + event_ts_ns: int + price: Decimal + quantity: Decimal + buyer_is_maker: bool + + +@dataclass(frozen=True, slots=True) +class _AggregatePage: + path: Path + manifest_path: Path + sha256: str + request_uri: str + downloaded_at_ns: int + from_id: int | None + rows: int + first_id: int | None + last_id: int | None + first_event_ts_ns: int | None + last_event_ts_ns: int | None + + +def _object(value: object, label: str) -> Mapping[str, Any]: + if not isinstance(value, Mapping) or not all(isinstance(key, str) for key in value): + raise PublicDataError(f"{label} must be a JSON object with string keys") + return cast(Mapping[str, Any], value) + + +def _array(value: object, label: str) -> list[Any]: + if not isinstance(value, list): + raise PublicDataError(f"{label} must be a JSON array") + return value + + +def _text(value: object, label: str) -> str: + if not isinstance(value, str) or not value: + raise PublicDataError(f"{label} must be a non-empty string") + return value + + +def _integer(value: object, label: str, *, minimum: int | None = None) -> int: + if isinstance(value, bool) or not isinstance(value, int): + raise PublicDataError(f"{label} must be an integer") + if minimum is not None and value < minimum: + raise PublicDataError(f"{label} must be at least {minimum}") + return value + + +def _boolean(value: object, label: str) -> bool: + if not isinstance(value, bool): + raise PublicDataError(f"{label} must be a boolean") + return value + + +def _digest(value: object, label: str) -> str: + digest = _text(value, label).lower() + if _SHA256.fullmatch(digest) is None: + raise PublicDataError(f"{label} must be a SHA-256 hex digest") + return digest + + +def _positive_decimal(value: object, label: str) -> Decimal: + if not isinstance(value, str) or not value: + raise PublicDataError(f"{label} must be a non-empty decimal string") + try: + result = Decimal(value) + except InvalidOperation as exc: + raise PublicDataError(f"{label} is not a valid decimal") from exc + if not result.is_finite() or result <= 0: + raise PublicDataError(f"{label} must be positive and finite") + return result + + +def _positive_decimal_number(value: object, label: str) -> Decimal: + if isinstance(value, bool) or not isinstance(value, (Decimal, float, int, str)): + raise PublicDataError(f"{label} must be a decimal number") + try: + result = Decimal(str(value)) + except InvalidOperation as exc: + raise PublicDataError(f"{label} is not a valid decimal") from exc + if not result.is_finite() or result <= 0: + raise PublicDataError(f"{label} must be positive and finite") + return result + + +def _scaled_integer(value: Decimal, quantum: Decimal, label: str) -> int: + scaled = value / quantum + integral = scaled.to_integral_value() + if scaled != integral: + raise PublicDataError(f"{label} is not aligned to exchangeInfo scale") + return int(integral) + + +def _unsigned_integer_text(value: str, label: str, *, minimum: int = 0) -> int: + if not value.isascii() or not value.isdecimal(): + raise PublicDataError(f"{label} must be an unsigned decimal integer") + result = int(value) + if result < minimum: + raise PublicDataError(f"{label} must be at least {minimum}") + return result + + +def _load_json_value(path: Path, label: str) -> object: + _preflight_json_structure(path, label) + try: + return cast(object, read_json(path)) + except (OSError, UnicodeError, ValueError) as exc: + raise PublicDataError(f"cannot read {label} at {path}: {exc}") from exc + + +def _preflight_json_structure(path: Path, label: str) -> None: + """Bound JSON token width and bytes relative to its structural cardinality. + + Manifests legitimately grow with O(parts/pages), so a fixed whole-file cap + would defeat full-history use. This streaming preflight instead permits + bytes proportional to JSON structure while rejecting giant padding strings + before ``read_json`` allocates them. + """ + total_bytes = 0 + structure_tokens = 0 + current_string_bytes = 0 + in_string = False + escaped = False + try: + with path.open("rb") as handle: + while chunk := handle.read(64 * 1024): + total_bytes += len(chunk) + for byte in chunk: + if in_string: + current_string_bytes += 1 + if current_string_bytes > _MAX_JSON_STRING_BYTES: + raise PublicDataError( + f"{label} has a JSON string above bounded token size " + f"{_MAX_JSON_STRING_BYTES} bytes" + ) + if escaped: + escaped = False + elif byte == 0x5C: # backslash + escaped = True + elif byte == 0x22: # quote + in_string = False + elif byte == 0x22: + in_string = True + current_string_bytes = 0 + elif byte in {0x7B, 0x7D, 0x5B, 0x5D, 0x2C}: # {}[], + structure_tokens += 1 + except PublicDataError: + raise + except OSError as exc: + raise PublicDataError(f"cannot preflight {label} at {path}: {exc}") from exc + allowed_bytes = _JSON_BASE_BYTES + (structure_tokens * _JSON_BYTES_PER_STRUCTURE_TOKEN) + if total_bytes > allowed_bytes: + raise PublicDataError( + f"{label} has {total_bytes} bytes above its structural JSON bound {allowed_bytes}" + ) + + +def _request_query( + source_uri: str, + *, + base_url: str, + endpoint: str, + label: str, +) -> dict[str, str]: + """Parse a raw request URI only when it is rooted at the configured API.""" + try: + configured = urlsplit(base_url) + requested = urlsplit(source_uri) + configured_port = configured.port + requested_port = requested.port + except ValueError as exc: + raise PublicDataError(f"{label} is not a valid URL: {exc}") from exc + if ( + configured.scheme.lower() not in {"http", "https"} + or configured.hostname is None + or configured.username is not None + or configured.password is not None + or configured.query + or configured.fragment + ): + raise PublicDataError("configured data.base_url is not a plain HTTP(S) base URL") + if ( + requested.scheme.lower() != configured.scheme.lower() + or requested.hostname is None + or requested.hostname.lower() != configured.hostname.lower() + or requested_port != configured_port + or requested.username is not None + or requested.password is not None + ): + raise PublicDataError(f"{label} is not bound to configured data.base_url") + base_path = configured.path.rstrip("/") + expected_path = f"{base_path}{endpoint}" + if requested.path != expected_path: + raise PublicDataError(f"{label} does not use exact endpoint {expected_path!r}") + if requested.fragment: + raise PublicDataError(f"{label} must not contain a fragment") + try: + pairs = parse_qsl(requested.query, keep_blank_values=True, strict_parsing=True) + except ValueError as exc: + raise PublicDataError(f"{label} has a malformed query string") from exc + query: dict[str, str] = {} + for key, value in pairs: + if not key or not value: + raise PublicDataError(f"{label} query keys and values must not be empty") + if key in query: + raise PublicDataError(f"{label} has duplicate query parameter {key!r}") + query[key] = value + return query + + +def _validate_exchange_info_payload( + path: Path, + *, + symbol: str, + claim: _SymbolClaim, + label: str, +) -> None: + payload = _object(_load_json_value(path, f"{label} payload"), f"{label} payload") + symbols = _array(payload.get("symbols"), f"{label} payload.symbols") + if len(symbols) != 1: + raise PublicDataError(f"{label} must contain exactly one exchangeInfo symbol") + item = _object(symbols[0], f"{label} payload.symbols[0]") + payload_symbol = _text(item.get("symbol"), f"{label} payload.symbol") + if payload_symbol != symbol: + raise PublicDataError(f"{label} payload symbol does not match its request URI") + status = _text(item.get("status"), f"{label} payload.status") + if status != "TRADING": + raise PublicDataError(f"{label} payload status is not TRADING") + _text(item.get("baseAsset"), f"{label} payload.baseAsset") + _text(item.get("quoteAsset"), f"{label} payload.quoteAsset") + + filters = _array(item.get("filters"), f"{label} payload.filters") + selected: dict[str, Mapping[str, Any]] = {} + for filter_index, raw_filter in enumerate(filters): + filter_item = _object(raw_filter, f"{label} payload.filters[{filter_index}]") + filter_type = _text( + filter_item.get("filterType"), + f"{label} payload.filters[{filter_index}].filterType", + ) + if filter_type in {"PRICE_FILTER", "LOT_SIZE"}: + if filter_type in selected: + raise PublicDataError(f"{label} payload has duplicate {filter_type}") + selected[filter_type] = filter_item + if set(selected) != {"PRICE_FILTER", "LOT_SIZE"}: + raise PublicDataError(f"{label} payload lacks PRICE_FILTER or LOT_SIZE") + tick_size = _positive_decimal( + selected["PRICE_FILTER"].get("tickSize"), + f"{label} payload.PRICE_FILTER.tickSize", + ) + lot_size = _positive_decimal( + selected["LOT_SIZE"].get("stepSize"), + f"{label} payload.LOT_SIZE.stepSize", + ) + if tick_size != claim.tick_size or lot_size != claim.lot_size: + raise PublicDataError(f"{label} payload scales do not match ingestion claim for {symbol}") + + +def _aggregate_records( + path: Path, + label: str, + *, + request_limit: int, + requested_range: tuple[int, int], +) -> dict[int, _RawAggregateTrade]: + # ``requested_range`` is retained in the signature to bind the cache to + # the verified request. Binance may legitimately return a terminal + # sentinel row at/after endTime; normalized rows, not untouched raw pages, + # are required to fall inside the requested half-open interval. + del requested_range + payload = _array(_load_json_value(path, f"{label} payload"), f"{label} payload") + if len(payload) > request_limit: + raise PublicDataError( + f"{label} contains {len(payload)} rows, above configured page limit {request_limit}" + ) + records: dict[int, _RawAggregateTrade] = {} + previous_event_ts_ns: int | None = None + for record_index, raw_record in enumerate(payload): + record = _object(raw_record, f"{label} payload[{record_index}]") + aggregate_id = _integer( + record.get("a"), + f"{label} payload[{record_index}].a", + minimum=0, + ) + if records and aggregate_id <= next(reversed(records)): + raise PublicDataError(f"{label} aggregate-trade IDs are not strictly increasing") + first_trade_id = _integer( + record.get("f"), + f"{label} payload[{record_index}].f", + minimum=0, + ) + last_trade_id = _integer( + record.get("l"), + f"{label} payload[{record_index}].l", + minimum=first_trade_id, + ) + event_time_ms = _integer( + record.get("T"), + f"{label} payload[{record_index}].T", + minimum=0, + ) + event_ts_ns = event_time_ms * 1_000_000 + if previous_event_ts_ns is not None and event_ts_ns < previous_event_ts_ns: + raise PublicDataError(f"{label} aggregate-trade event times are not nondecreasing") + previous_event_ts_ns = event_ts_ns + price = _positive_decimal(record.get("p"), f"{label} payload[{record_index}].p") + quantity = _positive_decimal(record.get("q"), f"{label} payload[{record_index}].q") + buyer_is_maker = _boolean( + record.get("m"), + f"{label} payload[{record_index}].m", + ) + records[aggregate_id] = _RawAggregateTrade( + aggregate_id=aggregate_id, + first_trade_id=first_trade_id, + last_trade_id=last_trade_id, + event_ts_ns=event_ts_ns, + price=price, + quantity=quantity, + buyer_is_maker=buyer_is_maker, + ) + return records + + +class _RawPageCache: + """Load at most one bounded aggregate-trade page at a time.""" + + def __init__( + self, + pages_by_digest: Mapping[str, _RawPageDescriptor], + *, + request_limit: int, + requested_range: tuple[int, int], + ) -> None: + self._pages_by_digest = pages_by_digest + self._request_limit = request_limit + self._requested_range = requested_range + self._digest: str | None = None + self._records: Mapping[int, _RawAggregateTrade] = MappingProxyType({}) + + def record( + self, + digest: str, + *, + symbol: str, + trade_id: int, + label: str, + ) -> _RawAggregateTrade: + descriptor = self._pages_by_digest.get(digest) + if descriptor is None: + raise PublicDataError(f"{label} references an undeclared or empty raw artifact") + if descriptor.symbol != symbol: + raise PublicDataError( + f"{label} references a raw page for {descriptor.symbol}, not {symbol}" + ) + if self._digest != digest: + # Re-hash at use time so verification and consumption are not split + # by an unnoticed local-file replacement. + _verify_file(descriptor.path, descriptor.sha256, f"raw aggregate page for {symbol}") + records = _aggregate_records( + descriptor.path, + f"raw aggregate page for {symbol}", + request_limit=self._request_limit, + requested_range=self._requested_range, + ) + _verify_file(descriptor.path, descriptor.sha256, f"raw aggregate page for {symbol}") + ids = tuple(records) + if ( + len(records) != descriptor.rows + or (ids[0] if ids else None) != descriptor.first_id + or (ids[-1] if ids else None) != descriptor.last_id + ): + raise PublicDataError(f"raw aggregate page metadata changed for {symbol}") + self._digest = digest + self._records = records + raw_record = self._records.get(trade_id) + if raw_record is None: + raise PublicDataError( + f"{label} trade_id is absent from its exact raw aggregate-trade page" + ) + return raw_record + + +class _ExpectedLineageIndex: + """Disk-backed inverse lineage for every downloader-selected raw trade.""" + + def __init__(self, dataset: PublicTradeDataset) -> None: + self._connection = sqlite3.connect("") + self._connection.execute("PRAGMA cache_size = -2048") + self._connection.execute("PRAGMA temp_store = FILE") + self._connection.execute("PRAGMA journal_mode = OFF") + self._connection.execute("PRAGMA synchronous = OFF") + self._connection.execute( + """ + CREATE TABLE expected_lineage ( + symbol TEXT NOT NULL, + source_sha256 TEXT NOT NULL, + trade_id INTEGER NOT NULL, + seen_count INTEGER NOT NULL DEFAULT 0, + PRIMARY KEY (symbol, source_sha256, trade_id) + ) WITHOUT ROWID + """ + ) + try: + self._populate(dataset) + except BaseException: + self._connection.close() + raise + + def _populate(self, dataset: PublicTradeDataset) -> None: + row_cap = cast(int, dataset._config.data.max_events_per_symbol) + for symbol in dataset._config.data.symbols: + expected_count = 0 + for page in dataset._ordered_raw_pages[symbol]: + if expected_count >= row_cap: + break + _verify_file(page.path, page.sha256, f"raw aggregate page for {symbol}") + records = _aggregate_records( + page.path, + f"raw aggregate page for {symbol}", + request_limit=dataset._config.data.request_limit, + requested_range=dataset._requested_range, + ) + _verify_file(page.path, page.sha256, f"raw aggregate page for {symbol}") + ids = tuple(records) + if ( + len(records) != page.rows + or (ids[0] if ids else None) != page.first_id + or (ids[-1] if ids else None) != page.last_id + ): + raise PublicDataError(f"raw aggregate page metadata changed for {symbol}") + selected: list[tuple[str, str, int]] = [] + for record in records.values(): + if not ( + dataset._requested_range[0] + <= record.event_ts_ns + < dataset._requested_range[1] + ): + continue + if expected_count >= row_cap: + break + selected.append((symbol, page.sha256, record.aggregate_id)) + expected_count += 1 + try: + self._connection.executemany( + """ + INSERT INTO expected_lineage (symbol, source_sha256, trade_id) + VALUES (?, ?, ?) + """, + selected, + ) + except sqlite3.IntegrityError as exc: + raise PublicDataError( + f"raw aggregate pages contain duplicate selected lineage for {symbol}" + ) from exc + claimed = dataset._symbol_claims[symbol].rows + if expected_count != claimed: + raise PublicDataError( + f"raw selected rows for {symbol} ({expected_count}) do not match " + f"normalized coverage claim ({claimed})" + ) + self._connection.commit() + + def mark_seen(self, *, symbol: str, source_sha256: str, trade_id: int) -> None: + cursor = self._connection.execute( + """ + UPDATE expected_lineage + SET seen_count = seen_count + 1 + WHERE symbol = ? AND source_sha256 = ? AND trade_id = ? + """, + (symbol, source_sha256, trade_id), + ) + if cursor.rowcount != 1: + raise PublicDataError( + "normalized trade is outside the exact downloader-selected raw sequence" + ) + + def mismatch_counts(self) -> tuple[int, int]: + missing, repeated = self._connection.execute( + """ + SELECT + SUM(CASE WHEN seen_count = 0 THEN 1 ELSE 0 END), + SUM(CASE WHEN seen_count > 1 THEN 1 ELSE 0 END) + FROM expected_lineage + """ + ).fetchone() + return int(missing or 0), int(repeated or 0) + + def commit(self) -> None: + self._connection.commit() + + def close(self) -> None: + self._connection.close() + + +def _validate_normalized_trade_row( + raw_row: object, + *, + row_index: int, + symbol_claims: Mapping[str, _SymbolClaim], + raw_cache: _RawPageCache, +) -> None: + label = f"normalized trade row {row_index}" + row = _object(raw_row, label) + symbol = _text(row.get("symbol"), f"{label}.symbol") + claim = symbol_claims.get(symbol) + if claim is None: + raise PublicDataError(f"{label} has an unmanifested symbol {symbol}") + source_id = _digest(row.get("source_artifact_id"), f"{label}.source_artifact_id") + trade_id = _integer(row.get("trade_id"), f"{label}.trade_id", minimum=0) + raw_record = raw_cache.record( + source_id, + symbol=symbol, + trade_id=trade_id, + label=label, + ) + + price = _positive_decimal_number(row.get("price"), f"{label}.price") + quantity = _positive_decimal_number(row.get("quantity"), f"{label}.quantity") + expected_price_ticks = _scaled_integer(raw_record.price, claim.tick_size, f"{label}.price") + expected_quantity_lots = _scaled_integer( + raw_record.quantity, + claim.lot_size, + f"{label}.quantity", + ) + expected_aggressor = "sell" if raw_record.buyer_is_maker else "buy" + mismatches = { + "venue": row.get("venue") != "binance_spot", + "event_ts_ns": row.get("event_ts_ns") != raw_record.event_ts_ns, + "received_ts_ns": row.get("received_ts_ns") is not None, + "available_ts_ns": row.get("available_ts_ns") != raw_record.event_ts_ns, + "availability_basis": row.get("availability_basis") != "exchange_event_time_proxy", + "capture_seq": row.get("capture_seq") is not None, + "continuity_id": row.get("continuity_id") is not None, + "first_trade_id": row.get("first_trade_id") != raw_record.first_trade_id, + "last_trade_id": row.get("last_trade_id") != raw_record.last_trade_id, + "price_ticks": row.get("price_ticks") != expected_price_ticks, + "quantity_lots": row.get("quantity_lots") != expected_quantity_lots, + "price": price != raw_record.price, + "quantity": quantity != raw_record.quantity, + "quote_quantity": row.get("quote_quantity") + != float(raw_record.price) * float(raw_record.quantity), + "aggressor_side": row.get("aggressor_side") != expected_aggressor, + "buyer_is_maker": row.get("buyer_is_maker") != raw_record.buyer_is_maker, + } + mismatched_fields = sorted(field for field, mismatched in mismatches.items() if mismatched) + if mismatched_fields: + raise PublicDataError( + f"{label} does not match its exact raw aggregate-trade record: " + + ", ".join(mismatched_fields) + ) + + +def _load_object(path: Path, label: str) -> Mapping[str, Any]: + _preflight_json_structure(path, label) + try: + return _object(read_json(path), label) + except PublicDataError: + raise + except (OSError, ValueError) as exc: + raise PublicDataError(f"cannot read {label} at {path}: {exc}") from exc + + +def _verify_file(path: Path, expected_sha256: str, label: str) -> None: + if not path.is_file(): + raise PublicDataError(f"missing {label}: {path}") + try: + observed = sha256_file(path) + except OSError as exc: + raise PublicDataError(f"cannot hash {label} at {path}: {exc}") from exc + if observed != expected_sha256: + raise PublicDataError( + f"{label} SHA-256 mismatch: expected {expected_sha256}, got {observed}" + ) + + +def _declared_file(root: Path, value: object, label: str) -> Path: + declared = Path(_text(value, label)) + if declared.is_absolute(): + raise PublicDataError(f"{label} must be relative to its manifest root") + resolved_root = root.resolve() + candidate = (resolved_root / declared).resolve() + if not candidate.is_relative_to(resolved_root): + raise PublicDataError(f"{label} escapes its manifest root: {declared}") + if not candidate.is_file(): + raise PublicDataError(f"missing {label}: {candidate}") + return candidate + + +def _utc_iso_from_ns(timestamp_ns: int) -> str: + seconds, nanoseconds = divmod(timestamp_ns, _NS_PER_SECOND) + instant = datetime.fromtimestamp(seconds, tz=UTC) + return f"{instant:%Y-%m-%dT%H:%M:%S}.{nanoseconds:09d}Z" + + +def _utc_ns_from_iso(value: object, label: str) -> int: + raw = _text(value, label) + try: + parsed = datetime.fromisoformat(raw.replace("Z", "+00:00")) + except ValueError as exc: + raise PublicDataError(f"{label} is not a valid ISO-8601 timestamp") from exc + if parsed.tzinfo is None: + raise PublicDataError(f"{label} must include a UTC offset") + utc = parsed.astimezone(UTC) + epoch = datetime(1970, 1, 1, tzinfo=UTC) + delta = utc - epoch + return ( + delta.days * 86_400 * _NS_PER_SECOND + + delta.seconds * _NS_PER_SECOND + + delta.microseconds * 1_000 + ) + + +def _coverage(start_ns: int, end_inclusive_ns: int) -> ObservedUtcCoverage: + if end_inclusive_ns < start_ns: + raise PublicDataError("observed coverage ends before it starts") + return ObservedUtcCoverage( + start_ns=start_ns, + end_inclusive_ns=end_inclusive_ns, + start_utc=_utc_iso_from_ns(start_ns), + end_inclusive_utc=_utc_iso_from_ns(end_inclusive_ns), + ) + + +def _requested_range(manifest: Mapping[str, Any], label: str) -> tuple[int, int]: + requested = _object(manifest.get("requested_range_ns"), f"{label}.requested_range_ns") + start_ns = _integer(requested.get("start"), f"{label}.requested_range_ns.start") + end_ns = _integer(requested.get("end_exclusive"), f"{label}.requested_range_ns.end_exclusive") + if end_ns <= start_ns: + raise PublicDataError(f"{label} requested range must be non-empty") + return start_ns, end_ns + + +def _terminal_claim( + item: Mapping[str, Any], + *, + label: str, + rows: int, + complete_range: bool, + requested_range: tuple[int, int], +) -> _TerminalClaim | None: + top_fields = ("raw_page_count", "stop_reason", "last_raw_page_sha256") + presence = [item.get(field) is not None for field in top_fields] + summary_value = item.get("stream_summary") + if not any(presence) and summary_value is None: + return None + if not all(presence) or summary_value is None: + raise PublicDataError(f"{label} has an incomplete terminal stream claim") + raw_page_count = _integer(item.get("raw_page_count"), f"{label}.raw_page_count", minimum=1) + stop_reason = _text(item.get("stop_reason"), f"{label}.stop_reason") + if stop_reason not in {"event_cap", "range_end", "short_page", "empty_page"}: + raise PublicDataError(f"{label}.stop_reason is unsupported") + last_sha = _digest(item.get("last_raw_page_sha256"), f"{label}.last_raw_page_sha256") + summary = _object(summary_value, f"{label}.stream_summary") + if ( + _integer( + summary.get("requested_start_ns"), + f"{label}.stream_summary.requested_start_ns", + ) + != requested_range[0] + or _integer( + summary.get("requested_end_ns"), + f"{label}.stream_summary.requested_end_ns", + ) + != requested_range[1] + or _integer( + summary.get("rows_yielded"), + f"{label}.stream_summary.rows_yielded", + minimum=1, + ) + != rows + or _integer( + summary.get("raw_page_count"), + f"{label}.stream_summary.raw_page_count", + minimum=1, + ) + != raw_page_count + or _text(summary.get("stop_reason"), f"{label}.stream_summary.stop_reason") != stop_reason + or _boolean( + summary.get("complete_range"), + f"{label}.stream_summary.complete_range", + ) + != complete_range + ): + raise PublicDataError(f"{label}.stream_summary disagrees with its symbol claim") + expected_complete = stop_reason != "event_cap" and rows > 0 + if complete_range != expected_complete: + raise PublicDataError(f"{label} completeness disagrees with terminal stop reason") + last = _object(summary.get("last_raw_page"), f"{label}.stream_summary.last_raw_page") + last_page_sha = _digest(last.get("sha256"), f"{label}.stream_summary.last_raw_page.sha256") + if last_page_sha != last_sha: + raise PublicDataError(f"{label} last raw page SHA-256 claims disagree") + return _TerminalClaim( + raw_page_count=raw_page_count, + stop_reason=stop_reason, + last_raw_page_sha256=last_sha, + last_path=_text(last.get("path"), f"{label}.stream_summary.last_raw_page.path"), + last_manifest_path=_text( + last.get("manifest_path"), + f"{label}.stream_summary.last_raw_page.manifest_path", + ), + last_request_uri=_text( + last.get("request_uri"), + f"{label}.stream_summary.last_raw_page.request_uri", + ), + last_row_count=_integer( + last.get("row_count"), + f"{label}.stream_summary.last_raw_page.row_count", + minimum=0, + ), + ) + + +def _validate_ingestion_manifest( + manifest: Mapping[str, Any], + config: ProjectConfig, +) -> tuple[ + PublicEvidenceTier, + bool, + tuple[int, int], + dict[str, _SymbolClaim], + Mapping[str, Any], +]: + if manifest.get("manifest_version") != MANIFEST_VERSION: + raise PublicDataError("unsupported ingestion manifest version") + if manifest.get("artifact_kind") != "ingestion_run": + raise PublicDataError("manifest is not an ingestion_run artifact") + if manifest.get("mode") != "binance_rest": + raise PublicDataError("public trade reader requires a binance_rest ingestion manifest") + if ( + manifest.get("schema_version") != SCHEMA_VERSION + or manifest.get("schema_version") != config.data.schema_version + ): + raise PublicDataError("ingestion manifest has an unsupported schema version") + if _text(manifest.get("source"), "ingestion.source") != config.data.source: + raise PublicDataError("ingestion source does not match configured source") + + effective = _text(manifest.get("evidence_tier"), "ingestion.evidence_tier") + requested = _text(manifest.get("requested_evidence_tier"), "ingestion.requested_evidence_tier") + if effective not in {"PUBLIC_SAMPLE_PARTIAL", "FULL_DATA"}: + raise PublicDataError(f"unsupported public evidence tier: {effective!r}") + if requested not in {"PUBLIC_SAMPLE_PARTIAL", "FULL_DATA"}: + raise PublicDataError(f"unsupported requested public evidence tier: {requested!r}") + if requested != config.run.evidence_tier: + raise PublicDataError("requested evidence tier does not match configuration") + + all_complete = _boolean( + manifest.get("all_requested_ranges_complete"), + "ingestion.all_requested_ranges_complete", + ) + row_cap = _integer( + manifest.get("row_cap_per_symbol"), "ingestion.row_cap_per_symbol", minimum=1 + ) + if row_cap != config.data.max_events_per_symbol: + raise PublicDataError("ingestion row cap does not match configuration") + requested_range = _requested_range(manifest, "ingestion") + if config.data.end is None: + raise PublicDataError("public input configuration requires a bounded end time") + configured_range = (datetime_to_ns(config.data.start), datetime_to_ns(config.data.end)) + if requested_range != configured_range: + raise PublicDataError("ingestion requested range does not match configuration") + raw_symbols = _array(manifest.get("symbols"), "ingestion.symbols") + if not raw_symbols: + raise PublicDataError("ingestion.symbols must not be empty") + symbols: dict[str, _SymbolClaim] = {} + for index, raw_symbol in enumerate(raw_symbols): + item = _object(raw_symbol, f"ingestion.symbols[{index}]") + symbol = _text(item.get("symbol"), f"ingestion.symbols[{index}].symbol") + if symbol in symbols: + raise PublicDataError(f"duplicate symbol coverage entry: {symbol}") + rows = _integer(item.get("rows"), f"ingestion.symbols[{index}].rows", minimum=1) + if rows > row_cap: + raise PublicDataError(f"manifested rows for {symbol} exceed row_cap_per_symbol") + complete = _boolean( + item.get("complete_range"), f"ingestion.symbols[{index}].complete_range" + ) + symbols[symbol] = _SymbolClaim( + rows=rows, + complete_range=complete, + tick_size=_positive_decimal( + item.get("tick_size"), f"ingestion.symbols[{index}].tick_size" + ), + lot_size=_positive_decimal( + item.get("lot_size"), f"ingestion.symbols[{index}].lot_size" + ), + terminal=_terminal_claim( + item, + label=f"ingestion.symbols[{index}]", + rows=rows, + complete_range=complete, + requested_range=requested_range, + ), + ) + + if set(symbols) != set(config.data.symbols): + raise PublicDataError("ingestion symbols do not match configured symbols") + + derived_complete = all(claim.complete_range for claim in symbols.values()) + if all_complete != derived_complete: + raise PublicDataError("all_requested_ranges_complete disagrees with per-symbol coverage") + expected_effective = requested if all_complete else "PUBLIC_SAMPLE_PARTIAL" + if effective == "FULL_DATA" and expected_effective != "FULL_DATA": + raise PublicDataError("partial or lower-tier coverage cannot be promoted to FULL_DATA") + if effective != expected_effective: + raise PublicDataError( + "effective evidence tier does not match requested tier and manifested coverage" + ) + legacy_complete = sorted( + symbol + for symbol, claim in symbols.items() + if claim.complete_range and claim.terminal is None + ) + if legacy_complete: + raise PublicDataError( + "complete public coverage lacks terminal stream evidence for symbols: " + + ", ".join(legacy_complete) + ) + + datasets = _array(manifest.get("normalized_datasets"), "ingestion.normalized_datasets") + if len(datasets) != 1: + raise PublicDataError("public trade ingestion must declare exactly one normalized dataset") + dataset = _object(datasets[0], "ingestion.normalized_datasets[0]") + if dataset.get("schema_name") != "trades": + raise PublicDataError("public ingestion normalized dataset must use the trades schema") + + return ( + cast(PublicEvidenceTier, effective), + all_complete, + requested_range, + symbols, + dataset, + ) + + +def _validate_dataset_manifest( + manifest: Mapping[str, Any], + *, + ingestion_source: object, + requested_range: tuple[int, int], +) -> tuple[int, list[Any], str]: + if manifest.get("manifest_version") != MANIFEST_VERSION: + raise PublicDataError("unsupported normalized dataset manifest version") + if manifest.get("dataset") != "trades": + raise PublicDataError("referenced normalized manifest is not the trades dataset") + if manifest.get("schema_version") != SCHEMA_VERSION: + raise PublicDataError("normalized dataset manifest has an unsupported schema version") + source = _text(manifest.get("source"), "normalized dataset.source") + if source != ingestion_source: + raise PublicDataError("ingestion and normalized dataset sources do not match") + source_uri = _text(manifest.get("source_uri"), "normalized dataset.source_uri") + if _requested_range(manifest, "normalized dataset") != requested_range: + raise PublicDataError("ingestion and normalized dataset requested ranges do not match") + rows = _integer(manifest.get("rows"), "normalized dataset.rows", minimum=1) + artifacts = _array(manifest.get("artifacts"), "normalized dataset.artifacts") + if not artifacts: + raise PublicDataError("normalized dataset manifest declares no Parquet parts") + return rows, artifacts, source_uri + + +def _verify_raw_artifacts( + ingestion: Mapping[str, Any], + *, + bundle_root: Path, + requested_range: tuple[int, int], + config: ProjectConfig, + symbol_claims: Mapping[str, _SymbolClaim], +) -> _VerifiedRawArtifacts: + entries = _array(ingestion.get("raw_artifacts"), "ingestion.raw_artifacts") + if not entries: + raise PublicDataError("public ingestion manifest declares no raw artifacts") + raw_root = (bundle_root / "raw").resolve() + paths: list[Path] = [] + manifest_paths: list[Path] = [] + digests: set[str] = set() + pages_by_digest: dict[str, _RawPageDescriptor] = {} + ordered_page_descriptors: dict[str, tuple[_RawPageDescriptor, ...]] = {} + aggregate_pages: dict[str, list[_AggregatePage]] = {symbol: [] for symbol in symbol_claims} + exchange_info_symbols: set[str] = set() + seen_paths: dict[Path, bool] = {} + seen_manifest_paths: set[Path] = set() + + try: + base_path = urlsplit(config.data.base_url).path.rstrip("/") + except ValueError as exc: + raise PublicDataError(f"configured data.base_url is not valid: {exc}") from exc + aggregate_endpoint = "/api/v3/aggTrades" + exchange_info_endpoint = "/api/v3/exchangeInfo" + + for index, raw_entry in enumerate(entries): + label = f"ingestion.raw_artifacts[{index}]" + entry = _object(raw_entry, label) + path = _declared_file(bundle_root, entry.get("path"), f"{label}.path") + manifest_path = _declared_file( + bundle_root, entry.get("manifest_path"), f"{label}.manifest_path" + ) + if not path.is_relative_to(raw_root) or not manifest_path.is_relative_to(raw_root): + raise PublicDataError(f"{label} is outside the ingestion bundle's raw root") + if manifest_path in seen_manifest_paths: + raise PublicDataError(f"duplicate declared raw sidecar at index {index}") + seen_manifest_paths.add(manifest_path) + + digest = _digest(entry.get("sha256"), f"{label}.sha256") + manifest_digest = _digest(entry.get("manifest_sha256"), f"{label}.manifest_sha256") + _verify_file(path, digest, f"raw artifact {index}") + _verify_file(manifest_path, manifest_digest, f"raw artifact sidecar {index}") + if path.stat().st_size > _MAX_RAW_ARTIFACT_BYTES: + raise PublicDataError( + f"raw artifact {index} exceeds bounded JSON size {_MAX_RAW_ARTIFACT_BYTES} bytes" + ) + sidecar = _load_object(manifest_path, f"raw artifact sidecar {index}") + if sidecar.get("manifest_version") != MANIFEST_VERSION: + raise PublicDataError(f"raw artifact sidecar {index} has an unsupported version") + if sidecar.get("artifact_kind") != "raw_source": + raise PublicDataError(f"raw artifact sidecar {index} has an unexpected kind") + if sidecar.get("source") != "binance_spot_public_api": + raise PublicDataError(f"raw artifact sidecar {index} is not a Binance public source") + source_uri = _text(sidecar.get("source_uri"), f"raw artifact sidecar {index}.source_uri") + downloaded_at_ns = _utc_ns_from_iso( + sidecar.get("downloaded_at_utc"), + f"raw artifact sidecar {index}.downloaded_at_utc", + ) + if sidecar.get("path") != path.name or manifest_path.parent != path.parent: + raise PublicDataError(f"raw artifact sidecar {index} path does not match") + if ( + _integer(sidecar.get("bytes"), f"raw artifact sidecar {index}.bytes", minimum=1) + != path.stat().st_size + ): + raise PublicDataError(f"raw artifact sidecar {index} byte count does not match") + checksum = _object(sidecar.get("checksum"), f"raw artifact sidecar {index}.checksum") + if ( + checksum.get("algorithm") != "sha256" + or _digest(checksum.get("value"), f"raw artifact sidecar {index}.checksum.value") + != digest + ): + raise PublicDataError(f"raw artifact sidecar {index} checksum does not match") + + raw_requested = _object( + sidecar.get("requested_range_ns"), + f"raw artifact sidecar {index}.requested_range_ns", + ) + raw_start = raw_requested.get("start") + raw_end = raw_requested.get("end_exclusive") + + requested_path = urlsplit(source_uri).path + raw_label = f"raw artifact sidecar {index}.source_uri" + is_empty_aggregate = False + if requested_path == f"{base_path}{aggregate_endpoint}": + query = _request_query( + source_uri, + base_url=config.data.base_url, + endpoint=aggregate_endpoint, + label=raw_label, + ) + initial_keys = {"symbol", "startTime", "endTime", "limit"} + continuation_keys = {"symbol", "fromId", "limit"} + if set(query) == initial_keys: + expected_start_ms = requested_range[0] // 1_000_000 + expected_end_ms = (requested_range[1] - 1) // 1_000_000 + if ( + _unsigned_integer_text(query["startTime"], f"{raw_label}.startTime") + != expected_start_ms + or _unsigned_integer_text(query["endTime"], f"{raw_label}.endTime") + != expected_end_ms + ): + raise PublicDataError( + f"{raw_label} time query does not match the requested range" + ) + from_id: int | None = None + elif set(query) == continuation_keys: + from_id = _unsigned_integer_text(query["fromId"], f"{raw_label}.fromId") + else: + raise PublicDataError( + f"{raw_label} must use exactly the initial-time or fromId query parameters" + ) + symbol = query["symbol"] + if symbol not in symbol_claims: + raise PublicDataError(f"{raw_label} symbol is not a configured symbol") + limit = _unsigned_integer_text(query["limit"], f"{raw_label}.limit", minimum=1) + if limit != config.data.request_limit: + raise PublicDataError(f"{raw_label} limit does not match configuration") + if ( + raw_start is None + or raw_end is None + or ( + _integer(raw_start, f"raw artifact sidecar {index}.requested_range_ns.start"), + _integer( + raw_end, + f"raw artifact sidecar {index}.requested_range_ns.end_exclusive", + ), + ) + != requested_range + ): + raise PublicDataError( + f"raw artifact sidecar {index} requested range does not match" + ) + aggregate_records = _aggregate_records( + path, + f"raw aggregate-trade artifact {index}", + request_limit=config.data.request_limit, + requested_range=requested_range, + ) + aggregate_ids = tuple(aggregate_records) + if from_id is not None and aggregate_ids and aggregate_ids[0] != from_id: + raise PublicDataError( + f"raw aggregate-trade artifact {index} does not begin at requested fromId" + ) + is_empty_aggregate = not aggregate_records + if aggregate_records: + descriptor = _RawPageDescriptor( + path=path, + sha256=digest, + symbol=symbol, + from_id=from_id, + rows=len(aggregate_records), + first_id=aggregate_ids[0], + last_id=aggregate_ids[-1], + ) + existing = pages_by_digest.get(digest) + if existing is not None and ( + existing.symbol != descriptor.symbol + or existing.from_id != descriptor.from_id + or existing.first_id != descriptor.first_id + or existing.last_id != descriptor.last_id + ): + raise PublicDataError( + f"raw aggregate-trade digest has ambiguous nonempty semantics at index {index}" + ) + if existing is None: + pages_by_digest[digest] = descriptor + aggregate_pages[symbol].append( + _AggregatePage( + path=path, + manifest_path=manifest_path, + sha256=digest, + request_uri=source_uri, + downloaded_at_ns=downloaded_at_ns, + from_id=from_id, + rows=len(aggregate_records), + first_id=aggregate_ids[0] if aggregate_ids else None, + last_id=aggregate_ids[-1] if aggregate_ids else None, + first_event_ts_ns=( + aggregate_records[aggregate_ids[0]].event_ts_ns if aggregate_ids else None + ), + last_event_ts_ns=( + aggregate_records[aggregate_ids[-1]].event_ts_ns if aggregate_ids else None + ), + ) + ) + elif requested_path == f"{base_path}{exchange_info_endpoint}": + query = _request_query( + source_uri, + base_url=config.data.base_url, + endpoint=exchange_info_endpoint, + label=raw_label, + ) + if set(query) != {"symbol"}: + raise PublicDataError(f"{raw_label} must contain exactly the symbol parameter") + symbol = query["symbol"] + claim = symbol_claims.get(symbol) + if claim is None: + raise PublicDataError(f"{raw_label} symbol is not a configured symbol") + if raw_start is not None or raw_end is not None: + raise PublicDataError( + f"raw artifact sidecar {index} exchangeInfo range must be null" + ) + _validate_exchange_info_payload( + path, + symbol=symbol, + claim=claim, + label=f"raw exchangeInfo artifact {index}", + ) + exchange_info_symbols.add(symbol) + else: + raise PublicDataError(f"{raw_label} does not use an allowed Binance public endpoint") + + if path in seen_paths and not (seen_paths[path] and is_empty_aggregate): + raise PublicDataError( + f"duplicate raw data path has nonempty or non-aggregate semantics at index {index}" + ) + seen_paths[path] = is_empty_aggregate + + paths.append(path) + manifest_paths.append(manifest_path) + digests.add(digest) + + if exchange_info_symbols != set(symbol_claims): + missing = sorted(set(symbol_claims).difference(exchange_info_symbols)) + raise PublicDataError( + "public ingestion lacks exchangeInfo raw artifacts for configured symbols: " + + ", ".join(missing) + ) + for symbol, pages in aggregate_pages.items(): + initial_pages = [page for page in pages if page.from_id is None] + if len(initial_pages) != 1: + raise PublicDataError( + f"public ingestion must declare exactly one initial-time aggTrades page for {symbol}" + ) + previous_last_id = initial_pages[0].last_id + previous_last_event_ts_ns = initial_pages[0].last_event_ts_ns + continuation_pages = sorted( + (page for page in pages if page.from_id is not None), + key=lambda page: cast(int, page.from_id), + ) + seen_from_ids: set[int] = set() + terminal_empty_seen = initial_pages[0].rows == 0 + for page in continuation_pages: + from_id = cast(int, page.from_id) + if from_id in seen_from_ids: + raise PublicDataError(f"raw aggregate-trade pagination repeats fromId for {symbol}") + seen_from_ids.add(from_id) + if terminal_empty_seen: + raise PublicDataError( + f"raw aggregate-trade pagination continues after an empty page for {symbol}" + ) + if previous_last_id is None or from_id != previous_last_id + 1: + raise PublicDataError( + f"raw aggregate-trade pagination is not contiguous for {symbol}" + ) + if ( + previous_last_event_ts_ns is not None + and page.first_event_ts_ns is not None + and page.first_event_ts_ns < previous_last_event_ts_ns + ): + raise PublicDataError( + f"raw aggregate-trade event time reverses across pages for {symbol}" + ) + if page.rows == 0: + terminal_empty_seen = True + else: + previous_last_id = page.last_id + previous_last_event_ts_ns = page.last_event_ts_ns + + ordered_pages = [initial_pages[0], *continuation_pages] + ordered_page_descriptors[symbol] = tuple( + _RawPageDescriptor( + path=page.path, + sha256=page.sha256, + symbol=symbol, + from_id=page.from_id, + rows=page.rows, + first_id=page.first_id, + last_id=page.last_id, + ) + for page in ordered_pages + ) + terminal_page = ordered_pages[-1] + symbol_claim = symbol_claims[symbol] + if symbol_claim.rows >= cast(int, config.data.max_events_per_symbol): + derived_stop_reason = "event_cap" + elif terminal_page.rows == 0: + derived_stop_reason = "empty_page" + elif ( + terminal_page.last_event_ts_ns is not None + and terminal_page.last_event_ts_ns >= requested_range[1] + ): + derived_stop_reason = "range_end" + elif terminal_page.rows < config.data.request_limit: + derived_stop_reason = "short_page" + else: + raise PublicDataError( + f"raw aggregate-trade chain ends without a terminal condition for {symbol}" + ) + derived_complete = derived_stop_reason != "event_cap" and symbol_claim.rows > 0 + if symbol_claim.complete_range != derived_complete: + raise PublicDataError( + f"manifested completeness disagrees with raw terminal page for {symbol}" + ) + if derived_complete and terminal_page.downloaded_at_ns < requested_range[1]: + raise PublicDataError( + f"complete range for {symbol} ends after its terminal page was downloaded" + ) + terminal_claim = symbol_claim.terminal + if terminal_claim is not None and ( + terminal_claim.raw_page_count != len(ordered_pages) + or terminal_claim.stop_reason != derived_stop_reason + or terminal_claim.last_raw_page_sha256 != terminal_page.sha256 + or terminal_claim.last_row_count != terminal_page.rows + or terminal_claim.last_request_uri != terminal_page.request_uri + or _declared_file( + bundle_root, + terminal_claim.last_path, + f"terminal raw page path for {symbol}", + ) + != terminal_page.path + or _declared_file( + bundle_root, + terminal_claim.last_manifest_path, + f"terminal raw page manifest path for {symbol}", + ) + != terminal_page.manifest_path + ): + raise PublicDataError( + f"terminal stream claim does not match declared raw pages for {symbol}" + ) + + return _VerifiedRawArtifacts( + paths=tuple(sorted(set(paths))), + manifest_paths=tuple(sorted(manifest_paths)), + sha256s=frozenset(digests), + pages_by_digest=MappingProxyType(pages_by_digest), + ordered_pages=MappingProxyType(ordered_page_descriptors), + ) + + +def _verify_part_descriptor( + raw_artifact: object, + *, + index: int, + write_ordinal: int, + normalized_root: Path, + dataset_source: str, + dataset_source_uri: str, + requested_range: tuple[int, int], +) -> _ParquetPartDescriptor: + label = f"normalized dataset.artifacts[{index}]" + artifact = _object(raw_artifact, label) + declared_rows = _integer(artifact.get("rows"), f"{label}.rows", minimum=1) + data_sha = _digest(artifact.get("data_sha256"), f"{label}.data_sha256") + sidecar_sha = _digest(artifact.get("manifest_sha256"), f"{label}.manifest_sha256") + data_path = _declared_file(normalized_root, artifact.get("data_path"), f"{label}.data_path") + sidecar_path = _declared_file( + normalized_root, artifact.get("manifest_path"), f"{label}.manifest_path" + ) + _verify_file(data_path, data_sha, f"Parquet part {index}") + _verify_file(sidecar_path, sidecar_sha, f"Parquet sidecar {index}") + + sidecar = _load_object(sidecar_path, f"Parquet sidecar {index}") + if sidecar.get("manifest_version") != MANIFEST_VERSION: + raise PublicDataError(f"Parquet sidecar {index} has an unsupported manifest version") + if sidecar.get("artifact_kind") != "normalized_parquet": + raise PublicDataError(f"Parquet sidecar {index} has an unexpected artifact kind") + if sidecar.get("dataset") != "trades" or sidecar.get("schema_name") != "trades": + raise PublicDataError(f"Parquet sidecar {index} declares an unexpected schema") + if sidecar.get("schema_version") != SCHEMA_VERSION: + raise PublicDataError(f"Parquet sidecar {index} has an unsupported schema version") + if sidecar.get("source") != dataset_source: + raise PublicDataError(f"Parquet sidecar {index} source does not match its dataset") + if sidecar.get("source_uri") != dataset_source_uri: + raise PublicDataError(f"Parquet sidecar {index} source URI does not match its dataset") + if _requested_range(sidecar, f"Parquet sidecar {index}") != requested_range: + raise PublicDataError(f"Parquet sidecar {index} requested range does not match") + if _integer(sidecar.get("rows"), f"Parquet sidecar {index}.rows", minimum=1) != declared_rows: + raise PublicDataError(f"Parquet sidecar {index} row count does not match") + checksum = _object(sidecar.get("checksum"), f"Parquet sidecar {index}.checksum") + if ( + checksum.get("algorithm") != "sha256" + or _digest(checksum.get("value"), f"Parquet sidecar {index}.checksum.value") != data_sha + ): + raise PublicDataError(f"Parquet sidecar {index} checksum does not match") + if sidecar.get("path") != artifact.get("data_path"): + raise PublicDataError(f"Parquet sidecar {index} data path does not match") + sidecar_ordinal = sidecar.get("write_ordinal") + if ( + sidecar_ordinal is not None + and _integer(sidecar_ordinal, f"Parquet sidecar {index}.write_ordinal", minimum=0) + != write_ordinal + ): + raise PublicDataError(f"Parquet sidecar {index} write ordinal does not match") + if ( + _integer(sidecar.get("bytes"), f"Parquet sidecar {index}.bytes", minimum=1) + != data_path.stat().st_size + ): + raise PublicDataError(f"Parquet sidecar {index} byte count does not match") + proportional_parquet_bound = _PARQUET_BASE_BYTES + ( + declared_rows * _PARQUET_BYTES_PER_TRADE_ROW + ) + encoded_parquet_bound = min( + proportional_parquet_bound, + _MAX_PARQUET_PART_ENCODED_BYTES, + ) + if data_path.stat().st_size > encoded_parquet_bound: + raise PublicDataError( + f"Parquet part {index} exceeds bounded encoded bytes for its row count" + ) + + expected_schema = get_schema("trades") + try: + parquet = pq.ParquetFile(data_path) + if parquet.metadata.num_rows != declared_rows: + raise PublicDataError(f"Parquet part {index} metadata row count does not match") + uncompressed_bytes = sum( + parquet.metadata.row_group(row_group).total_byte_size + for row_group in range(parquet.metadata.num_row_groups) + ) + decoded_parquet_bound = min( + proportional_parquet_bound, + _MAX_PARQUET_PART_DECODED_BYTES, + ) + if uncompressed_bytes > decoded_parquet_bound: + raise PublicDataError( + f"Parquet part {index} exceeds bounded decoded bytes for its row count" + ) + if not parquet.schema_arrow.equals(expected_schema, check_metadata=True): + raise PublicDataError(f"Parquet part {index} has an unexpected trades schema") + except PublicDataError: + raise + except (OSError, pa.ArrowException, ValueError) as exc: + raise PublicDataError(f"cannot inspect Parquet part {index} metadata: {exc}") from exc + + observed = _object(sidecar.get("observed_range_ns"), f"Parquet sidecar {index}.observed") + observed_start = _integer(observed.get("start"), f"Parquet sidecar {index}.observed.start") + observed_end = _integer( + observed.get("end_inclusive"), + f"Parquet sidecar {index}.observed.end_inclusive", + ) + if ( + observed_end < observed_start + or observed_start < requested_range[0] + or observed_end >= requested_range[1] + ): + raise PublicDataError(f"Parquet sidecar {index} observed range is invalid") + artifact_observed_value = artifact.get("observed_range_ns") + if artifact_observed_value is not None: + artifact_observed = _object( + artifact_observed_value, + f"normalized dataset.artifacts[{index}].observed_range_ns", + ) + if ( + _integer( + artifact_observed.get("start"), + f"normalized dataset.artifacts[{index}].observed_range_ns.start", + ) + != observed_start + or _integer( + artifact_observed.get("end_inclusive"), + f"normalized dataset.artifacts[{index}].observed_range_ns.end_inclusive", + ) + != observed_end + ): + raise PublicDataError( + f"normalized dataset artifact {index} observed range does not match sidecar" + ) + sidecar_symbol = _text(sidecar.get("symbol"), f"Parquet sidecar {index}.symbol") + sidecar_venue = _text(sidecar.get("venue"), f"Parquet sidecar {index}.venue") + partition_date = _text(sidecar.get("partition_date"), f"Parquet sidecar {index}.partition_date") + try: + parsed_date = datetime.strptime(partition_date, "%Y-%m-%d").date() + except ValueError as exc: + raise PublicDataError(f"Parquet sidecar {index} partition date is invalid") from exc + observed_dates = { + datetime.fromtimestamp(timestamp // _NS_PER_SECOND, tz=UTC).date() + for timestamp in (observed_start, observed_end) + } + if observed_dates != {parsed_date}: + raise PublicDataError(f"Parquet sidecar {index} observed range crosses its partition date") + return _ParquetPartDescriptor( + data_path=data_path, + data_sha256=data_sha, + sidecar_path=sidecar_path, + rows=declared_rows, + write_ordinal=write_ordinal, + venue=sidecar_venue, + symbol=sidecar_symbol, + partition_date=partition_date, + observed_start_ns=observed_start, + observed_end_inclusive_ns=observed_end, + ) + + +def verify_public_trade_dataset( + config: ProjectConfig, + ingestion_manifest_path: str | Path, + *, + ingestion_manifest_sha256: str, +) -> PublicTradeDataset: + """Verify a public-trade bundle without materializing normalized rows. + + ``ingestion_manifest_sha256`` is required so the path itself cannot silently + select a different ingestion run. This pass verifies every manifest, + sidecar, file digest, Parquet footer/schema, raw-page pagination claim, and + coverage claim. It retains only O(parts + raw pages + symbols) descriptors. + Normalized Parquet row data are read only by ``iter_verified_batches``. + """ + if config.data.mode != "binance_rest": + raise PublicDataError("public trade reader requires data.mode='binance_rest'") + configured_cap = config.data.max_events_per_symbol + if configured_cap is None or configured_cap < 1: + raise PublicDataError("public trade reader requires a configured positive row cap") + max_rows = configured_cap * len(config.data.symbols) + expected_ingestion_sha = _digest(ingestion_manifest_sha256, "ingestion_manifest_sha256") + manifest_path = Path(ingestion_manifest_path).resolve() + if manifest_path.parent.name != "_ingestion_manifests": + raise PublicDataError( + "ingestion manifest must remain under its bundle _ingestion_manifests directory" + ) + _verify_file(manifest_path, expected_ingestion_sha, "ingestion manifest") + ingestion = _load_object(manifest_path, "ingestion manifest") + evidence_tier, all_complete, requested_range, symbol_claims, dataset_entry = ( + _validate_ingestion_manifest(ingestion, config) + ) + + bundle_root = manifest_path.parent.parent.resolve() + verified_raw = _verify_raw_artifacts( + ingestion, + bundle_root=bundle_root, + requested_range=requested_range, + config=config, + symbol_claims=symbol_claims, + ) + dataset_manifest_path = _declared_file( + bundle_root, + dataset_entry.get("manifest_path"), + "ingestion.normalized_datasets[0].manifest_path", + ) + dataset_manifest_sha = _digest( + dataset_entry.get("manifest_sha256"), + "ingestion.normalized_datasets[0].manifest_sha256", + ) + _verify_file(dataset_manifest_path, dataset_manifest_sha, "normalized dataset manifest") + if dataset_manifest_path.parent.name != "_manifests": + raise PublicDataError("normalized dataset manifest is outside its _manifests directory") + normalized_root = dataset_manifest_path.parent.parent.resolve() + if normalized_root != (bundle_root / "normalized").resolve(): + raise PublicDataError( + "normalized dataset is not under the ingestion bundle's normalized root" + ) + + dataset_manifest = _load_object(dataset_manifest_path, "normalized dataset manifest") + dataset_rows, raw_artifacts, dataset_source_uri = _validate_dataset_manifest( + dataset_manifest, + ingestion_source=ingestion.get("source"), + requested_range=requested_range, + ) + ingestion_rows = _integer( + dataset_entry.get("rows"), "ingestion.normalized_datasets[0].rows", minimum=1 + ) + if dataset_rows > max_rows: + raise PublicDataError( + f"manifested trades contain {dataset_rows} rows, above required bound {max_rows}" + ) + if dataset_rows != ingestion_rows or dataset_rows != sum( + claim.rows for claim in symbol_claims.values() + ): + raise PublicDataError("ingestion, symbol, and normalized dataset row counts do not match") + + parts: list[_ParquetPartDescriptor] = [] + declared_part_rows = 0 + seen_data_paths: set[Path] = set() + seen_sidecar_paths: set[Path] = set() + declared_symbol_rows: dict[str, int] = {symbol: 0 for symbol in symbol_claims} + declared_symbol_starts: dict[str, int] = {} + declared_symbol_ends: dict[str, int] = {} + ordinal_presence: list[bool] = [] + declared_ordinals: set[int] = set() + for index, raw_artifact in enumerate(raw_artifacts): + artifact = _object(raw_artifact, f"normalized dataset.artifacts[{index}]") + ordinal_value = artifact.get("write_ordinal") + ordinal_presence.append(ordinal_value is not None) + write_ordinal = ( + _integer( + ordinal_value, + f"normalized dataset.artifacts[{index}].write_ordinal", + minimum=0, + ) + if ordinal_value is not None + else index + ) + if write_ordinal in declared_ordinals: + raise PublicDataError(f"duplicate Parquet write ordinal: {write_ordinal}") + declared_ordinals.add(write_ordinal) + next_rows = _integer( + artifact.get("rows"), f"normalized dataset.artifacts[{index}].rows", minimum=1 + ) + if declared_part_rows + next_rows > max_rows: + raise PublicDataError(f"declared Parquet parts exceed required row bound {max_rows}") + part = _verify_part_descriptor( + artifact, + index=index, + write_ordinal=write_ordinal, + normalized_root=normalized_root, + dataset_source=_text(dataset_manifest.get("source"), "normalized dataset.source"), + dataset_source_uri=dataset_source_uri, + requested_range=requested_range, + ) + if part.data_path in seen_data_paths: + raise PublicDataError(f"duplicate declared Parquet part: {part.data_path}") + if part.sidecar_path in seen_sidecar_paths: + raise PublicDataError(f"duplicate declared Parquet sidecar: {part.sidecar_path}") + seen_data_paths.add(part.data_path) + seen_sidecar_paths.add(part.sidecar_path) + if part.venue != "binance_spot": + raise PublicDataError(f"Parquet part {index} venue is not binance_spot") + if part.symbol not in symbol_claims: + raise PublicDataError(f"Parquet part {index} symbol is not manifested") + declared_part_rows += part.rows + declared_symbol_rows[part.symbol] += part.rows + declared_symbol_starts[part.symbol] = min( + declared_symbol_starts.get(part.symbol, part.observed_start_ns), + part.observed_start_ns, + ) + declared_symbol_ends[part.symbol] = max( + declared_symbol_ends.get(part.symbol, part.observed_end_inclusive_ns), + part.observed_end_inclusive_ns, + ) + parts.append(part) + + if declared_part_rows != dataset_rows: + raise PublicDataError("declared Parquet part rows do not match dataset rows") + if any(ordinal_presence) and not all(ordinal_presence): + raise PublicDataError("normalized dataset mixes present and missing write ordinals") + if all(ordinal_presence) and declared_ordinals != set(range(len(parts))): + raise PublicDataError("normalized dataset write ordinals must be contiguous from zero") + canonical_order = ("venue", "symbol", "available_ts_ns", "event_ts_ns", "trade_id") + symbol_coverage: list[SymbolObservedCoverage] = [] + for symbol in sorted(symbol_claims): + claim = symbol_claims[symbol] + if declared_symbol_rows[symbol] != claim.rows: + raise PublicDataError(f"declared Parquet rows for {symbol} do not match coverage claim") + if symbol not in declared_symbol_starts: + raise PublicDataError(f"declared Parquet parts contain no rows for {symbol}") + symbol_coverage.append( + SymbolObservedCoverage( + symbol=symbol, + rows=claim.rows, + complete_range=claim.complete_range, + tick_size=claim.tick_size, + lot_size=claim.lot_size, + observed=_coverage( + declared_symbol_starts[symbol], + declared_symbol_ends[symbol], + ), + ) + ) + return PublicTradeDataset( + rows=dataset_rows, + observed=_coverage( + min(part.observed_start_ns for part in parts), + max(part.observed_end_inclusive_ns for part in parts), + ), + symbols=tuple(symbol_coverage), + evidence_tier=evidence_tier, + all_requested_ranges_complete=all_complete, + ingestion_manifest_path=manifest_path, + ingestion_manifest_sha256=expected_ingestion_sha, + dataset_manifest_path=dataset_manifest_path, + dataset_manifest_sha256=dataset_manifest_sha, + part_paths=tuple(part.data_path for part in parts), + raw_artifact_paths=verified_raw.paths, + raw_manifest_paths=verified_raw.manifest_paths, + raw_artifact_sha256s=tuple(sorted(verified_raw.sha256s)), + row_bound=max_rows, + canonical_order=canonical_order, + _config=config, + _requested_range=requested_range, + _symbol_claims=MappingProxyType(dict(symbol_claims)), + _parts=tuple(parts), + _raw_pages_by_digest=verified_raw.pages_by_digest, + _ordered_raw_pages=verified_raw.ordered_pages, + ) + + +def _normalized_batch( + raw_batch: pa.RecordBatch, + *, + label: str, +) -> pa.RecordBatch: + expected = get_schema("trades") + try: + arrays: list[pa.Array] = [] + for name in expected.names: + field_index = raw_batch.schema.get_field_index(name) + if field_index < 0: + raise PublicDataError(f"{label} is missing column {name!r}") + arrays.append(raw_batch.column(field_index)) + normalized = pa.RecordBatch.from_arrays(arrays, schema=expected) + ensure_schema(normalized, "trades") + return normalized + except PublicDataError: + raise + except (pa.ArrowException, ValueError) as exc: + raise PublicDataError(f"{label} has an unexpected trades schema: {exc}") from exc + + +def _iter_audited_physical_batches( + dataset: PublicTradeDataset, + *, + batch_rows: int, +) -> Generator[pa.RecordBatch, None, _VerifiedStreamSummary]: + """Yield each source batch once after immutable physical-order auditing.""" + validator = IncrementalQualityValidator( + "trades", + max_spread_bps=dataset._config.quality.max_spread_bps, + max_silence_ns=dataset._config.quality.max_silence_ms * 1_000_000, + row_chunk_size=batch_rows, + ) + validator_finished = False + lineage_index: _ExpectedLineageIndex | None = None + raw_cache = _RawPageCache( + dataset._raw_pages_by_digest, + request_limit=dataset._config.data.request_limit, + requested_range=dataset._requested_range, + ) + actual_symbol_rows: dict[str, int] = {symbol: 0 for symbol in dataset._symbol_claims} + actual_symbol_starts: dict[str, int] = {} + actual_symbol_ends: dict[str, int] = {} + total_rows = 0 + audited_schema = get_schema("trades").append( + pa.field("__physical_ordinal", pa.int64(), nullable=False) + ) + try: + lineage_index = _ExpectedLineageIndex(dataset) + for part in sorted(dataset._parts, key=lambda item: item.write_ordinal): + _verify_file(part.data_path, part.data_sha256, "normalized Parquet part") + part_rows = 0 + part_start: int | None = None + part_end: int | None = None + try: + parquet = pq.ParquetFile(part.data_path) + physical_batches = parquet.iter_batches(batch_size=batch_rows) + for raw_batch in physical_batches: + if raw_batch.num_rows < 1: + continue + if raw_batch.num_rows > batch_rows: + raise PublicDataError( + f"Parquet emitted {raw_batch.num_rows} rows above batch bound " + f"{batch_rows}" + ) + normalized = _normalized_batch( + raw_batch, + label=f"Parquet part {part.data_path}", + ) + rows = cast(list[dict[str, Any]], normalized.to_pylist()) + for local_index, row in enumerate(rows): + row_index = total_rows + local_index + symbol = str(row["symbol"]) + venue = str(row["venue"]) + timestamp = int(row["event_ts_ns"]) + if symbol != part.symbol or venue != part.venue: + raise PublicDataError( + f"normalized row {row_index} does not match its Parquet " + "sidecar partition" + ) + actual_date = ( + datetime.fromtimestamp(timestamp // _NS_PER_SECOND, tz=UTC) + .date() + .isoformat() + ) + if actual_date != part.partition_date: + raise PublicDataError( + f"normalized row {row_index} does not match its partition date" + ) + if ( + not dataset._requested_range[0] + <= timestamp + < dataset._requested_range[1] + ): + raise PublicDataError( + f"normalized row {row_index} is outside the requested range" + ) + claim = dataset._symbol_claims.get(symbol) + if claim is None: + raise PublicDataError( + f"normalized row {row_index} has an unmanifested symbol {symbol}" + ) + try: + tick_size = Decimal(str(row["tick_size"])) + lot_size = Decimal(str(row["lot_size"])) + except InvalidOperation as exc: + raise PublicDataError( + f"normalized row {row_index} has invalid scales for {symbol}" + ) from exc + if tick_size != claim.tick_size or lot_size != claim.lot_size: + raise PublicDataError( + f"normalized row {row_index} scales do not match manifest for " + f"{symbol}" + ) + _validate_normalized_trade_row( + row, + row_index=row_index, + symbol_claims=dataset._symbol_claims, + raw_cache=raw_cache, + ) + lineage_index.mark_seen( + symbol=symbol, + source_sha256=str(row["source_artifact_id"]), + trade_id=int(row["trade_id"]), + ) + actual_symbol_rows[symbol] += 1 + actual_symbol_starts[symbol] = min( + actual_symbol_starts.get(symbol, timestamp), timestamp + ) + actual_symbol_ends[symbol] = max( + actual_symbol_ends.get(symbol, timestamp), timestamp + ) + part_start = timestamp if part_start is None else min(part_start, timestamp) + part_end = timestamp if part_end is None else max(part_end, timestamp) + del rows + validator.update(normalized) + lineage_index.commit() + batch_count = normalized.num_rows + physical_start = total_rows + total_rows += batch_count + part_rows += batch_count + yield pa.RecordBatch.from_arrays( + [ + *normalized.columns, + pa.array( + range(physical_start, physical_start + batch_count), + type=pa.int64(), + ), + ], + schema=audited_schema, + ) + except PublicDataError: + raise + except (OSError, pa.ArrowException, ValueError) as exc: + raise PublicDataError( + f"cannot stream normalized Parquet part {part.data_path}: {exc}" + ) from exc + if part_rows != part.rows: + raise PublicDataError( + f"materialized rows for Parquet part {part.data_path} do not match sidecar" + ) + if part_start != part.observed_start_ns or part_end != part.observed_end_inclusive_ns: + raise PublicDataError( + f"materialized coverage for Parquet part {part.data_path} does not match " + "sidecar" + ) + _verify_file(part.data_path, part.data_sha256, "normalized Parquet part") + + validation = validator.finish() + validator_finished = True + if total_rows != dataset.rows: + raise PublicDataError("streamed trades do not match manifested dataset rows") + symbol_coverage: list[SymbolObservedCoverage] = [] + for symbol in sorted(dataset._symbol_claims): + claim = dataset._symbol_claims[symbol] + if actual_symbol_rows[symbol] != claim.rows: + raise PublicDataError(f"materialized rows for {symbol} do not match coverage claim") + if symbol not in actual_symbol_starts: + raise PublicDataError(f"materialized trades contain no rows for {symbol}") + symbol_coverage.append( + SymbolObservedCoverage( + symbol=symbol, + rows=claim.rows, + complete_range=claim.complete_range, + tick_size=claim.tick_size, + lot_size=claim.lot_size, + observed=_coverage(actual_symbol_starts[symbol], actual_symbol_ends[symbol]), + ) + ) + observed = _coverage(min(actual_symbol_starts.values()), max(actual_symbol_ends.values())) + if observed != dataset.observed or tuple(symbol_coverage) != dataset.symbols: + raise PublicDataError("materialized coverage does not match verified manifest metadata") + missing_lineage, repeated_lineage = lineage_index.mismatch_counts() + if (missing_lineage or repeated_lineage) and not ( + dataset._config.quality.fail_on_error and validation.has_errors + ): + raise PublicDataError( + "normalized rows do not exactly cover downloader-selected raw trades: " + f"missing={missing_lineage}, repeated={repeated_lineage}" + ) + return _VerifiedStreamSummary( + validation=validation, + observed=observed, + symbols=tuple(symbol_coverage), + ) + finally: + if not validator_finished: + validator.close() + if lineage_index is not None: + lineage_index.close() + + +def _stream_verified_batches( + dataset: PublicTradeDataset, + *, + batch_rows: int, + memory_limit: str, + temp_directory: str | Path | None, +) -> Generator[pa.RecordBatch, None, _VerifiedStreamSummary]: + """Audit source order, then externally sort a fresh bounded research pass.""" + owned_temp: tempfile.TemporaryDirectory[str] | None = None + if temp_directory is None: + owned_temp = tempfile.TemporaryDirectory(prefix="microstructure-public-sort-") + sort_temp = Path(owned_temp.name).resolve() + else: + sort_temp = Path(temp_directory).resolve() + if not sort_temp.is_dir(): + raise PublicDataError(f"DuckDB temporary directory does not exist: {sort_temp}") + + connection: duckdb.DuckDBPyConnection | None = None + reader: pa.RecordBatchReader | None = None + source_reader: pa.RecordBatchReader | None = None + physical_source: _PhysicalAuditBatchSource | None = None + field_names = get_schema("trades").names + previous_order_key: tuple[str, str, int, int, int, str, int] | None = None + emitted_rows = 0 + quoted_fields = ", ".join(f'"{name}"' for name in field_names) + order_fields = ", ".join(f'"{name}" ASC' for name in dataset.canonical_order) + query = ( + f"SELECT {quoted_fields}, __physical_ordinal " + "FROM verified_source " + f"ORDER BY {order_fields}, source_artifact_id ASC, __physical_ordinal ASC" + ) + try: + connection = duckdb.connect(database=":memory:") + connection.execute("SET memory_limit = ?", [memory_limit]) + connection.execute("SET temp_directory = ?", [str(sort_temp)]) + connection.execute("SET threads = 1") + connection.execute("SET preserve_insertion_order = false") + + audited_schema = get_schema("trades").append( + pa.field("__physical_ordinal", pa.int64(), nullable=False) + ) + physical_source = _PhysicalAuditBatchSource( + _iter_audited_physical_batches(dataset, batch_rows=batch_rows) + ) + source_reader = pa.RecordBatchReader.from_batches(audited_schema, physical_source) + connection.register("verified_source", source_reader) + reader = connection.execute(query).to_arrow_reader(batch_size=batch_rows) + summary: _VerifiedStreamSummary | None = None + for raw_batch in reader: + if summary is None: + summary = physical_source.summary + if dataset._config.quality.fail_on_error and summary.validation.has_errors: + raise PublicDataError( + "public normalized trades failed quality validation with " + f"{summary.validation.error_count} error findings" + ) + if raw_batch.num_rows < 1: + continue + if raw_batch.num_rows > batch_rows: + raise PublicDataError( + f"DuckDB emitted {raw_batch.num_rows} rows above batch bound {batch_rows}" + ) + normalized = _normalized_batch(raw_batch, label="DuckDB canonical output") + physical_ordinals = cast( + list[int], + raw_batch.column( + raw_batch.schema.get_field_index("__physical_ordinal") + ).to_pylist(), + ) + rows = cast(list[dict[str, Any]], normalized.to_pylist()) + for row, physical_ordinal in zip(rows, physical_ordinals, strict=True): + order_key = ( + str(row["venue"]), + str(row["symbol"]), + int(row["available_ts_ns"]), + int(row["event_ts_ns"]), + int(row["trade_id"]), + str(row["source_artifact_id"]), + int(physical_ordinal), + ) + if previous_order_key is not None and order_key < previous_order_key: + raise PublicDataError("DuckDB output violated canonical trade order") + previous_order_key = order_key + del rows, physical_ordinals + emitted_rows += normalized.num_rows + yield normalized + if emitted_rows != dataset.rows: + raise PublicDataError("canonical stream rows do not match manifested dataset rows") + if summary is None: + summary = physical_source.summary + return summary + except duckdb.Error as exc: + raise PublicDataError(f"cannot externally sort public trades: {exc}") from exc + finally: + if reader is not None: + reader.close() + if source_reader is not None: + source_reader.close() + if physical_source is not None: + physical_source.close() + if connection is not None: + connection.close() + if owned_temp is not None: + owned_temp.cleanup() + + +def read_public_trades( + config: ProjectConfig, + ingestion_manifest_path: str | Path, + *, + ingestion_manifest_sha256: str, + materialization_max_rows: int = 100_000, +) -> PublicTrades: + """Compatibility materializer built on the bounded verified stream. + + ``materialization_max_rows`` is a separate finite safety guard. It is + checked against already-verified manifest metadata before DuckDB or PyArrow + reads any normalized row, regardless of the configured ingestion cap. + """ + dataset = verify_public_trade_dataset( + config, + ingestion_manifest_path, + ingestion_manifest_sha256=ingestion_manifest_sha256, + ) + if ( + isinstance(materialization_max_rows, bool) + or not isinstance(materialization_max_rows, int) + or materialization_max_rows < 1 + ): + raise ValueError("materialization_max_rows must be a positive integer") + if dataset.rows > materialization_max_rows: + raise PublicDataError( + f"verified public data has {dataset.rows} rows, above materialization guard " + f"{materialization_max_rows}" + ) + + stream = dataset.iter_verified_batches( + batch_rows=min(65_536, materialization_max_rows), + memory_limit="256MB", + ) + batches: list[pa.RecordBatch] = [] + try: + for batch in stream: + batches.append(batch) + summary = stream.summary + finally: + stream.close() + try: + trades = pa.Table.from_batches(batches, schema=get_schema("trades")) + ensure_schema(trades, "trades") + except (pa.ArrowException, ValueError) as exc: + raise PublicDataError(f"cannot materialize verified public trades: {exc}") from exc + if trades.num_rows != dataset.rows: + raise PublicDataError("materialized trades do not match manifested dataset rows") + return PublicTrades( + arrow_trades=trades, + polars_trades=cast(pl.DataFrame, pl.from_arrow(trades)), + observed=summary.observed, + symbols=summary.symbols, + evidence_tier=dataset.evidence_tier, + all_requested_ranges_complete=dataset.all_requested_ranges_complete, + ingestion_manifest_path=dataset.ingestion_manifest_path, + ingestion_manifest_sha256=dataset.ingestion_manifest_sha256, + dataset_manifest_path=dataset.dataset_manifest_path, + dataset_manifest_sha256=dataset.dataset_manifest_sha256, + part_paths=dataset.part_paths, + raw_artifact_paths=dataset.raw_artifact_paths, + raw_manifest_paths=dataset.raw_manifest_paths, + raw_artifact_sha256s=dataset.raw_artifact_sha256s, + validation=summary.validation, + row_bound=dataset.row_bound, + canonical_order=dataset.canonical_order, + ) diff --git a/Microstructure/src/microstructure/public_pipeline.py b/Microstructure/src/microstructure/public_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..e1ad4c2e49a765fea52b951cf6f2a2eb10712ccd --- /dev/null +++ b/Microstructure/src/microstructure/public_pipeline.py @@ -0,0 +1,1466 @@ +"""Frozen public aggregate-trade research-run producer. + +This producer is deliberately narrower than the synthetic vertical slice. It +loads one explicitly manifested, bounded public trade ingestion; proves trade-ID +and availability-clock continuity before deriving research epochs; evaluates +each instrument independently; and publishes predictive diagnostics only. It +never invokes the execution simulator or calculates P&L. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import tempfile +from collections.abc import Mapping, Sequence +from dataclasses import asdict, dataclass +from datetime import UTC, datetime +from pathlib import Path +from typing import Any, cast + +import numpy as np +import polars as pl + +from microstructure.config import ProjectConfig +from microstructure.provenance import ( + provenance_header, + read_json, + sha256_file, + write_json, +) +from microstructure.public_data import PublicTrades, read_public_trades +from microstructure.reporting import ( + load_run_bundle, + render_executive_memo, + render_model_comparison, + render_technical_report, + write_checksum_manifest, +) +from microstructure.research.analysis import ( + feature_stability_summary, + ofi_future_return_association, +) +from microstructure.research.models import ( + block_bootstrap_metric, + evaluate_model_ladder, + paired_block_bootstrap_difference, +) +from microstructure.research.splits import WalkForwardPlan, expanding_walk_forward_splits +from microstructure.research.trade_only import ( + build_trade_only_research_frame, + validate_trade_only_temporal_contract, +) + +PUBLIC_PIPELINE_SCHEMA_VERSION = "1.0.0" +PUBLIC_EVIDENCE_TIER = "PUBLIC_SAMPLE_PARTIAL" +EXECUTION_EXCLUSION_REASON = ( + "Not run: aggregate-trade history has no contemporaneous quotes, depth, queue state, " + "or local receipt clock, so execution, fees-to-alpha conversion, P&L, fills, and capacity " + "would be unsupported claims." +) +HYPOTHESIS_BASELINE = "historical_prior" +HYPOTHESIS_BLOCK_POLICY = "fixed_contiguous_2x_label_horizon" +HYPOTHESIS_CAVEAT = ( + "Exploratory paired percentile interval on a bounded retrospective sample; it is a " + "dependence diagnostic, not a p-value, confirmatory significance test, or basis for " + "rejecting H0." +) +CROSS_INSTRUMENT_CONCLUSION = ( + "No pooled or cross-instrument conclusion is inferred: BTCUSDT and ETHUSDT are separate " + "sample-specific diagnostics. They cannot support a persistent-alpha claim, regardless " + "of their point-estimate directions." +) + +__all__ = [ + "EXECUTION_EXCLUSION_REASON", + "PUBLIC_EVIDENCE_TIER", + "PUBLIC_PIPELINE_SCHEMA_VERSION", + "PublicPipelineError", + "produce_public_trade_run", +] + + +class PublicPipelineError(RuntimeError): + """Raised when the frozen public run cannot be produced honestly.""" + + +@dataclass(frozen=True, slots=True) +class _SymbolResult: + symbol: str + research: pl.DataFrame + evaluation: pl.DataFrame + plan: WalkForwardPlan + predictions: pl.DataFrame + comparison: pl.DataFrame + selected_predictions: pl.DataFrame + selected_model: str + feature_columns: tuple[str, ...] + temporal_audit: Mapping[str, Any] + hypothesis_evaluation: Mapping[str, Any] + + +def _json_safe(value: Any) -> Any: + if isinstance(value, np.generic): + return _json_safe(value.item()) + if isinstance(value, float) and not math.isfinite(value): + return None + if isinstance(value, Path): + return str(value) + if isinstance(value, Mapping): + return {str(key): _json_safe(item) for key, item in value.items()} + if isinstance(value, (list, tuple)): + return [_json_safe(item) for item in value] + return value + + +def _write_json(path: Path, payload: Mapping[str, Any] | list[Any]) -> None: + clean = _json_safe(payload) + if not isinstance(clean, (dict, list)): + raise TypeError("JSON artifact payload must be an object or list") + write_json(path, clean) + + +def _atomic_write_text(path: Path, content: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary_name = tempfile.mkstemp( + dir=path.parent, + prefix=f".{path.name}.", + suffix=".tmp", + text=True, + ) + try: + with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as handle: + handle.write(content.rstrip() + "\n") + os.replace(temporary_name, path) + except BaseException: + Path(temporary_name).unlink(missing_ok=True) + raise + + +def _freeze_protocol(config: ProjectConfig, stage: Path) -> tuple[str, str]: + source = config.project_root / "docs" / "PUBLIC_TRADE_PROTOCOL.md" + if not source.is_file(): + raise PublicPipelineError(f"frozen public trade protocol is missing: {source}") + before = sha256_file(source) + try: + content = source.read_bytes() + except OSError as exc: + raise PublicPipelineError(f"cannot read frozen public trade protocol: {source}") from exc + after = sha256_file(source) + if before != after or hashlib.sha256(content).hexdigest() != before: + raise PublicPipelineError("public trade protocol changed while it was being frozen") + + relative = "protocol/PUBLIC_TRADE_PROTOCOL.md" + destination = stage / relative + destination.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary_name = tempfile.mkstemp( + dir=destination.parent, + prefix=f".{destination.name}.", + suffix=".tmp", + ) + try: + with os.fdopen(descriptor, "wb") as handle: + handle.write(content) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary_name, destination) + except BaseException: + Path(temporary_name).unlink(missing_ok=True) + raise + if sha256_file(destination) != before: + raise PublicPipelineError("frozen protocol copy does not match its source SHA-256") + return relative, before + + +def _utc_from_ns(timestamp_ns: int) -> str: + seconds, nanoseconds = divmod(timestamp_ns, 1_000_000_000) + instant = datetime.fromtimestamp(seconds, tz=UTC) + return f"{instant:%Y-%m-%dT%H:%M:%S}.{nanoseconds:09d}Z" + + +def _stable_sha256(payload: Mapping[str, Any]) -> str: + encoded = json.dumps(payload, sort_keys=True, separators=(",", ":"), allow_nan=False) + return hashlib.sha256(encoded.encode("utf-8")).hexdigest() + + +def _mapping(value: object) -> Mapping[str, Any] | None: + if not isinstance(value, Mapping) or not all(isinstance(key, str) for key in value): + return None + return cast(Mapping[str, Any], value) + + +def _project_path(path: Path, project_root: Path) -> str: + resolved = path.resolve() + try: + return resolved.relative_to(project_root.resolve()).as_posix() + except ValueError: + return str(resolved) + + +def _verified_manifest_object(path: Path, expected_sha256: str) -> Mapping[str, Any]: + before = sha256_file(path) + if before != expected_sha256: + raise PublicPipelineError(f"input manifest changed after verified loading: {path}") + payload = _mapping(read_json(path)) + after = sha256_file(path) + if after != expected_sha256 or after != before: + raise PublicPipelineError(f"input manifest changed while capturing lineage: {path}") + if payload is None: + raise PublicPipelineError(f"verified input manifest is not a JSON object: {path}") + return payload + + +def _input_lineage(public: PublicTrades, config: ProjectConfig) -> dict[str, Any]: + ingestion = _verified_manifest_object( + public.ingestion_manifest_path, public.ingestion_manifest_sha256 + ) + dataset = _verified_manifest_object( + public.dataset_manifest_path, public.dataset_manifest_sha256 + ) + + manifest_hashes = set(public.input_manifest_sha256s) + data_hashes = set(public.raw_artifact_sha256s) + raw_entries = ingestion.get("raw_artifacts") + if not isinstance(raw_entries, list): + raise PublicPipelineError("verified ingestion manifest has no raw artifact array") + for entry_value in raw_entries: + entry = _mapping(entry_value) + if entry is None: + raise PublicPipelineError("verified raw artifact entry is not an object") + raw_sha = entry.get("sha256") + raw_manifest_sha = entry.get("manifest_sha256") + if isinstance(raw_sha, str): + data_hashes.add(raw_sha) + raw_path = public.ingestion_manifest_path.parent.parent / str(entry.get("path")) + if sha256_file(raw_path) != raw_sha: + raise PublicPipelineError(f"raw input changed while capturing lineage: {raw_path}") + if isinstance(raw_manifest_sha, str): + manifest_hashes.add(raw_manifest_sha) + raw_manifest_path = public.ingestion_manifest_path.parent.parent / str( + entry.get("manifest_path") + ) + if sha256_file(raw_manifest_path) != raw_manifest_sha: + raise PublicPipelineError( + f"raw manifest changed while capturing lineage: {raw_manifest_path}" + ) + + part_entries = dataset.get("artifacts") + if not isinstance(part_entries, list): + raise PublicPipelineError("verified dataset manifest has no artifact array") + for entry_value in part_entries: + entry = _mapping(entry_value) + if entry is None: + raise PublicPipelineError("verified normalized artifact entry is not an object") + data_sha = entry.get("data_sha256") + part_manifest_sha = entry.get("manifest_sha256") + if isinstance(data_sha, str): + data_hashes.add(data_sha) + data_path = public.dataset_manifest_path.parent.parent / str(entry.get("data_path")) + if sha256_file(data_path) != data_sha: + raise PublicPipelineError( + f"normalized part changed while capturing lineage: {data_path}" + ) + if isinstance(part_manifest_sha, str): + manifest_hashes.add(part_manifest_sha) + part_manifest_path = public.dataset_manifest_path.parent.parent / str( + entry.get("manifest_path") + ) + if sha256_file(part_manifest_path) != part_manifest_sha: + raise PublicPipelineError( + "normalized part manifest changed while capturing lineage: " + f"{part_manifest_path}" + ) + + return { + "ingestion_manifest": { + "absolute_path": str(public.ingestion_manifest_path.resolve()), + "project_relative_or_absolute_path": _project_path( + public.ingestion_manifest_path, config.project_root + ), + "sha256": public.ingestion_manifest_sha256, + }, + "normalized_dataset_manifest": { + "absolute_path": str(public.dataset_manifest_path.resolve()), + "project_relative_or_absolute_path": _project_path( + public.dataset_manifest_path, config.project_root + ), + "sha256": public.dataset_manifest_sha256, + }, + "normalized_parts": [ + _project_path(path, config.project_root) for path in public.part_paths + ], + "raw_artifacts": [ + _project_path(path, config.project_root) for path in public.raw_artifact_paths + ], + "raw_manifests": [ + _project_path(path, config.project_root) for path in public.raw_manifest_paths + ], + "manifest_sha256": sorted(manifest_hashes), + "data_sha256": sorted(data_hashes), + } + + +def _derive_verified_continuity( + public: PublicTrades, config: ProjectConfig +) -> tuple[pl.DataFrame, list[dict[str, Any]]]: + if public.rows > public.row_bound: + raise PublicPipelineError("materialized public rows exceed the verified configured bound") + raw = public.polars_trades + expected_symbols = set(config.data.symbols) + if set(str(value) for value in raw.get_column("symbol").unique()) != expected_symbols: + raise PublicPipelineError("materialized public symbols do not match the configuration") + if raw.get_column("continuity_id").null_count() != raw.height: + raise PublicPipelineError( + "archive normalized rows must retain null source continuity before derivation" + ) + + derived_frames: list[pl.DataFrame] = [] + audits: list[dict[str, Any]] = [] + for symbol in config.data.symbols: + source = raw.filter(pl.col("symbol") == symbol).sort("trade_id") + if source.is_empty(): + raise PublicPipelineError(f"verified public input has no rows for {symbol}") + ids = source.get_column("trade_id").to_numpy().astype(np.int64) + available = source.get_column("available_ts_ns").to_numpy().astype(np.int64) + event = source.get_column("event_ts_ns").to_numpy().astype(np.int64) + if np.any(np.diff(ids) != 1): + raise PublicPipelineError(f"aggregate trade IDs are not contiguous by one for {symbol}") + if np.any(np.diff(available) < 0): + raise PublicPipelineError( + f"availability clock reverses in aggregate-trade-ID order for {symbol}" + ) + if np.any(available < event): + raise PublicPipelineError(f"availability precedes event time for {symbol}") + bases = set(str(value) for value in source.get_column("availability_basis").unique()) + if bases != {"exchange_event_time_proxy"}: + raise PublicPipelineError( + f"historical public trades require the exchange-event-time proxy for {symbol}" + ) + if source.get_column("received_ts_ns").null_count() != source.height: + raise PublicPipelineError( + f"historical public trades cannot claim local receipt time for {symbol}" + ) + + continuity_id = ( + f"public-aggtrade:{public.ingestion_manifest_sha256[:16]}:{symbol}:" + f"{int(ids[0])}-{int(ids[-1])}" + ) + derived_frames.append(source.with_columns(pl.lit(continuity_id).alias("continuity_id"))) + audits.append( + { + "symbol": symbol, + "rows": source.height, + "first_trade_id": int(ids[0]), + "last_trade_id": int(ids[-1]), + "trade_id_step": 1, + "trade_ids_contiguous": True, + "availability_clock_nondecreasing": True, + "tied_availability_rows": int(np.count_nonzero(np.diff(available) == 0)), + "availability_basis": "exchange_event_time_proxy", + "local_receipt_time_available": False, + "derived_continuity_id": continuity_id, + "derivation_timing": "assigned only after ID and clock verification", + "source_rows_mutated": False, + } + ) + return pl.concat(derived_frames).sort(["symbol", "trade_id"]), audits + + +def _trade_feature_columns(config: ProjectConfig, frame: pl.DataFrame) -> tuple[str, ...]: + columns: list[str] = ["log_trade_return_1"] + for window in config.features.trade_windows: + columns.extend( + [ + f"signed_trade_volume_w{window}", + f"trade_volume_w{window}", + f"trade_imbalance_w{window}", + ] + ) + intensity = config.features.intensity_window + columns.extend([f"trade_count_w{intensity}", f"trade_intensity_w{intensity}"]) + columns.append(f"realized_volatility_w{config.features.volatility_window}") + selected = tuple(dict.fromkeys(columns)) + missing = sorted(set(selected).difference(frame.columns)) + if missing: + raise PublicPipelineError(f"declared trade-only model features are missing: {missing}") + return selected + + +def _serialize_plan(plan: WalkForwardPlan) -> dict[str, Any]: + return { + "contract": ( + "single-symbol decision-time buckets; expanding training; feature-ready and " + "uncensored evaluation; labels ending at or beyond evaluation are purged; " + "configured embargo applied" + ), + "index_basis": "zero-based row positions in this symbol's evaluation_frame.parquet", + "decision_time_count": plan.decision_time_count, + "folds": [ + { + "fold_id": fold.fold_id, + "train_indices": [int(value) for value in fold.train_indices.tolist()], + "validation_indices": [int(value) for value in fold.validation_indices.tolist()], + "train_start_ts_ns": fold.train_start_ts_ns, + "train_end_ts_ns": fold.train_end_ts_ns, + "validation_start_ts_ns": fold.validation_start_ts_ns, + "validation_end_ts_ns": fold.validation_end_ts_ns, + "purged_rows": fold.purged_rows, + "embargoed_time_buckets": fold.embargoed_time_buckets, + } + for fold in plan.folds + ], + "final_train_indices": [int(value) for value in plan.final_train_indices.tolist()], + "test_indices": [int(value) for value in plan.test_indices.tolist()], + "test_start_ts_ns": plan.test_start_ts_ns, + "test_end_ts_ns": plan.test_end_ts_ns, + "test_used_for_selection": False, + } + + +def _add_fixed_blocks(predictions: pl.DataFrame, *, block_width: int) -> pl.DataFrame: + group = ["split", "fold_id"] + return ( + predictions.with_columns( + pl.col("decision_sequence").min().over(group).alias("_block_origin_trade_id") + ) + .with_columns( + ((pl.col("decision_sequence") - pl.col("_block_origin_trade_id")) // block_width) + .cast(pl.Int64) + .alias("_block_index") + ) + .with_columns( + pl.concat_str( + [ + "symbol", + "split", + pl.col("fold_id").cast(pl.String), + pl.col("_block_index").cast(pl.String), + ], + separator=":", + ).alias("bootstrap_block"), + (pl.col("_block_origin_trade_id") + pl.col("_block_index") * block_width).alias( + "bootstrap_block_start_trade_id" + ), + ) + .with_columns( + (pl.col("bootstrap_block_start_trade_id") + block_width - 1).alias( + "bootstrap_block_end_trade_id" + ), + pl.lit(block_width, dtype=pl.Int64).alias("bootstrap_block_width_trades"), + pl.lit("fixed_contiguous_2x_label_horizon").alias("bootstrap_block_policy"), + ) + .drop("_block_origin_trade_id", "_block_index") + ) + + +def _bootstrap_comparison( + comparison: pl.DataFrame, + predictions: pl.DataFrame, + *, + symbol: str, + selected_model: str, + metric: str, + n_bootstrap: int, + seed: int, + horizon: int, +) -> pl.DataFrame: + rows: list[dict[str, Any]] = [] + block_width = 2 * horizon + for index, source_row in enumerate( + comparison.sort(["split", "fold_id", "requested_model"]).to_dicts() + ): + row = dict(source_row) + requested_model = str(row.get("requested_model", row["model"])) + row["selected_on_validation"] = requested_model == selected_model + row["selected_on"] = "validation" if requested_model == selected_model else None + row["selection_contract"] = "validation folds only; final test opened after selection" + row["test_used_for_selection"] = False + row["evidence_tier"] = PUBLIC_EVIDENCE_TIER + row["execution_evaluated"] = False + row[f"{metric}_ci_low"] = None + row[f"{metric}_ci_high"] = None + row["bootstrap_status"] = None + row["bootstrap_blocks"] = None + row["bootstrap_samples"] = None + row["bootstrap_seed"] = None + row["bootstrap_block_width_trades"] = None + row["bootstrap_block_policy"] = None + row["bootstrap_limitation"] = None + if row["split"] == "test": + evaluated = predictions.filter( + (pl.col("split") == "test") + & (pl.col("model") == str(row["model"])) + & (pl.col("requested_model") == requested_model) + ) + interval_seed = seed + index + interval = block_bootstrap_metric( + evaluated, + metric=metric, + block_column="bootstrap_block", + n_bootstrap=n_bootstrap, + seed=interval_seed, + ) + row[f"{metric}_ci_low"] = interval.lower + row[f"{metric}_ci_high"] = interval.upper + row["bootstrap_status"] = interval.status + row["bootstrap_blocks"] = interval.n_blocks + row["bootstrap_samples"] = interval.n_bootstrap + row["bootstrap_seed"] = interval_seed + row["bootstrap_block_width_trades"] = block_width + row["bootstrap_block_policy"] = "fixed_contiguous_2x_label_horizon" + row["bootstrap_limitation"] = ( + "percentile dependence diagnostic on fixed trade blocks; not a p-value or " + "confirmatory coverage guarantee" + ) + rows.append(row) + return pl.DataFrame(rows, infer_schema_length=None).with_columns( + pl.lit(symbol).alias("symbol"), + pl.lit(symbol).alias("instrument"), + pl.lit(symbol).alias("instrument_scope"), + ) + + +def _metric_delta_direction(metric: str) -> tuple[str, int]: + if metric in {"log_loss", "brier_score", "expected_calibration_error"}: + return "negative_selected_minus_prior_is_favorable", -1 + if metric in {"accuracy", "balanced_accuracy", "roc_auc", "pr_auc"}: + return "positive_selected_minus_prior_is_favorable", 1 + raise PublicPipelineError(f"unsupported paired hypothesis metric: {metric}") + + +def _paired_hypothesis_evaluation( + predictions: pl.DataFrame, + *, + symbol: str, + selected_model: str, + metric: str, + n_bootstrap: int, + seed: int, + horizon: int, +) -> dict[str, Any]: + selected = predictions.filter( + (pl.col("split") == "test") & (pl.col("requested_model") == selected_model) + ) + baseline = predictions.filter( + (pl.col("split") == "test") & (pl.col("requested_model") == HYPOTHESIS_BASELINE) + ) + if selected.is_empty(): + raise PublicPipelineError( + f"validation-selected test predictions are missing for paired test: {symbol}" + ) + if baseline.is_empty(): + raise PublicPipelineError(f"historical-prior test predictions are missing for {symbol}") + + identity_columns = [ + "row_id", + "y_true", + "bootstrap_block", + "bootstrap_block_start_trade_id", + "bootstrap_block_end_trade_id", + "bootstrap_block_width_trades", + "bootstrap_block_policy", + ] + for name, frame in (("selected", selected), ("historical_prior", baseline)): + missing = sorted(set(identity_columns).difference(frame.columns)) + if missing: + raise PublicPipelineError( + f"{name} predictions lack paired-bootstrap identity columns: {missing}" + ) + if frame.get_column("row_id").n_unique() != frame.height: + raise PublicPipelineError(f"{name} predictions contain duplicate row IDs for {symbol}") + + selected_identity = selected.select(identity_columns).sort("row_id") + baseline_identity = baseline.select(identity_columns).sort("row_id") + if not selected_identity.equals(baseline_identity): + raise PublicPipelineError( + f"selected and historical-prior predictions do not share identical rows/blocks for {symbol}" + ) + + block_width = 2 * horizon + policies = selected.get_column("bootstrap_block_policy").unique().to_list() + widths = selected.get_column("bootstrap_block_width_trades").unique().to_list() + if policies != [HYPOTHESIS_BLOCK_POLICY] or widths != [block_width]: + raise PublicPipelineError( + f"paired hypothesis blocks do not implement the frozen 2x-horizon policy for {symbol}" + ) + + interval = paired_block_bootstrap_difference( + selected, + baseline, + metric=metric, + block_column="bootstrap_block", + n_bootstrap=n_bootstrap, + seed=seed, + ) + favorable_direction, favorable_sign = _metric_delta_direction(metric) + signed_point = favorable_sign * interval.point_estimate + if not math.isfinite(signed_point): + point_assessment = "unavailable" + point_favorable: bool | None = None + elif signed_point > 0: + point_assessment = "favorable_point_only" + point_favorable = True + elif signed_point < 0: + point_assessment = "unfavorable_point" + point_favorable = False + else: + point_assessment = "point_tie" + point_favorable = False + + if interval.lower is None or interval.upper is None: + interval_relation = "unavailable" + elif interval.lower <= 0.0 <= interval.upper: + interval_relation = "includes_zero" + elif favorable_sign * interval.lower > 0.0 and favorable_sign * interval.upper > 0.0: + interval_relation = "entirely_favorable" + else: + interval_relation = "entirely_unfavorable" + + return { + "symbol": symbol, + "selected_model": selected_model, + "baseline": HYPOTHESIS_BASELINE, + "metric": metric, + "delta_definition": "selected_model_minus_historical_prior", + "point_delta": interval.point_estimate, + "ci_level": 0.95, + "ci_low": interval.lower, + "ci_high": interval.upper, + "n_obs": selected.height, + "n_blocks": interval.n_blocks, + "samples": interval.n_bootstrap, + "seed": interval.seed, + "status": interval.status, + "block_column": "bootstrap_block", + "block_policy": HYPOTHESIS_BLOCK_POLICY, + "block_width_trades": block_width, + "paired_row_ids_identical": True, + "paired_blocks_identical": True, + "favorable_direction": favorable_direction, + "point_favorable": point_favorable, + "point_assessment": point_assessment, + "interval_relation_to_zero": interval_relation, + "exploratory": True, + "significance_claim_authorized": False, + "h0_rejection_authorized": False, + "caveat": HYPOTHESIS_CAVEAT, + "cross_instrument_conclusion": CROSS_INSTRUMENT_CONCLUSION, + } + + +def _attach_paired_hypothesis_to_comparison( + comparison: pl.DataFrame, + hypothesis: Mapping[str, Any], +) -> pl.DataFrame: + selected_model = str(hypothesis["selected_model"]) + rows: list[dict[str, Any]] = [] + attached = 0 + for source in comparison.to_dicts(): + row = dict(source) + selected_test = row["split"] == "test" and row.get("requested_model") == selected_model + paired_fields = { + "paired_baseline": None, + "paired_metric": None, + "paired_metric_delta": None, + "paired_metric_delta_ci_low": None, + "paired_metric_delta_ci_high": None, + "paired_n_obs": None, + "paired_bootstrap_blocks": None, + "paired_bootstrap_samples": None, + "paired_bootstrap_seed": None, + "paired_bootstrap_status": None, + "paired_bootstrap_block_policy": None, + "paired_favorable_direction": None, + "paired_point_favorable": None, + "paired_exploratory": None, + "paired_significance_claim_authorized": None, + } + if selected_test: + attached += 1 + paired_fields.update( + { + "paired_baseline": hypothesis["baseline"], + "paired_metric": hypothesis["metric"], + "paired_metric_delta": hypothesis["point_delta"], + "paired_metric_delta_ci_low": hypothesis["ci_low"], + "paired_metric_delta_ci_high": hypothesis["ci_high"], + "paired_n_obs": hypothesis["n_obs"], + "paired_bootstrap_blocks": hypothesis["n_blocks"], + "paired_bootstrap_samples": hypothesis["samples"], + "paired_bootstrap_seed": hypothesis["seed"], + "paired_bootstrap_status": hypothesis["status"], + "paired_bootstrap_block_policy": hypothesis["block_policy"], + "paired_favorable_direction": hypothesis["favorable_direction"], + "paired_point_favorable": hypothesis["point_favorable"], + "paired_exploratory": hypothesis["exploratory"], + "paired_significance_claim_authorized": hypothesis[ + "significance_claim_authorized" + ], + } + ) + row.update(paired_fields) + rows.append(row) + if attached != 1: + raise PublicPipelineError( + "paired hypothesis metadata must attach to exactly one selected test comparison row" + ) + return pl.DataFrame(rows, infer_schema_length=None) + + +def _rows_by_plan( + evaluation: pl.DataFrame, indices: np.ndarray[Any, np.dtype[np.int64]] +) -> pl.DataFrame: + indexed = evaluation.with_row_index("_research_row_id") + return indexed.filter(pl.col("_research_row_id").is_in(indices)).drop("_research_row_id") + + +def _evaluate_symbol( + trades: pl.DataFrame, + *, + config: ProjectConfig, + symbol_index: int, +) -> _SymbolResult: + symbol = str(trades.get_column("symbol")[0]) + research = build_trade_only_research_frame(trades, config.features).with_columns( + pl.col("label_horizon_trades").alias("label_horizon_events") + ) + temporal = validate_trade_only_temporal_contract(research) + evaluation = research.filter(pl.col("feature_ready")) + if evaluation.is_empty(): + raise PublicPipelineError(f"trade-only feature construction produced no rows for {symbol}") + features = _trade_feature_columns(config, evaluation) + plan = expanding_walk_forward_splits(evaluation, config.evaluation) + ladder = evaluate_model_ladder( + evaluation, + plan, + config.models, + seed=config.run.seed + symbol_index * 100_000, + calibration_bins=config.evaluation.calibration_bins, + target="future_trade_up", + features=features, + ) + block_width = 2 * config.features.label_horizon_events + predictions = _add_fixed_blocks(ladder.predictions, block_width=block_width) + comparison = _bootstrap_comparison( + ladder.comparison, + predictions, + symbol=symbol, + selected_model=ladder.selected_model, + metric=ladder.selection_metric, + n_bootstrap=config.evaluation.bootstrap_samples, + seed=config.run.seed + symbol_index * 100_000 + 10_000, + horizon=config.features.label_horizon_events, + ) + selected = predictions.filter( + (pl.col("split") == "test") & (pl.col("requested_model") == ladder.selected_model) + ) + if selected.is_empty() or selected.get_column("requested_model").n_unique() != 1: + raise PublicPipelineError(f"validation-selected test predictions are missing for {symbol}") + hypothesis = _paired_hypothesis_evaluation( + predictions, + symbol=symbol, + selected_model=ladder.selected_model, + metric=ladder.selection_metric, + n_bootstrap=config.evaluation.bootstrap_samples, + seed=config.run.seed + symbol_index * 100_000 + 20_000, + horizon=config.features.label_horizon_events, + ) + comparison = _attach_paired_hypothesis_to_comparison(comparison, hypothesis) + return _SymbolResult( + symbol=symbol, + research=research, + evaluation=evaluation, + plan=plan, + predictions=predictions, + comparison=comparison, + selected_predictions=selected, + selected_model=ladder.selected_model, + feature_columns=features, + temporal_audit=asdict(temporal), + hypothesis_evaluation=hypothesis, + ) + + +def _trade_summary( + trades: pl.DataFrame, continuity_audits: Sequence[Mapping[str, Any]] +) -> pl.DataFrame: + continuity = { + str(row["symbol"]): str(row["derived_continuity_id"]) for row in continuity_audits + } + rows: list[dict[str, Any]] = [] + for frame in trades.partition_by("symbol", maintain_order=True): + symbol = str(frame.get_column("symbol")[0]) + buy = frame.filter(pl.col("aggressor_side") == "buy") + sell = frame.filter(pl.col("aggressor_side") == "sell") + rows.append( + { + "symbol": symbol, + "rows": frame.height, + "first_trade_id": int(cast(int, frame.get_column("trade_id").min())), + "last_trade_id": int(cast(int, frame.get_column("trade_id").max())), + "observed_start_utc": _utc_from_ns( + int(cast(int, frame.get_column("event_ts_ns").min())) + ), + "observed_end_utc": _utc_from_ns( + int(cast(int, frame.get_column("event_ts_ns").max())) + ), + "total_quantity": float(cast(float, frame.get_column("quantity").sum())), + "total_quote_quantity": float( + cast(float, frame.get_column("quote_quantity").sum()) + ), + "buy_rows": buy.height, + "sell_rows": sell.height, + "buy_quantity": float(cast(float, buy.get_column("quantity").sum())), + "sell_quantity": float(cast(float, sell.get_column("quantity").sum())), + "derived_continuity_id": continuity[symbol], + "availability_basis": "exchange_event_time_proxy", + "analysis_kind": "public_trade_sample_summary_descriptive", + "descriptive_only": True, + } + ) + return pl.DataFrame(rows).sort("symbol") + + +def _write_analyses( + *, + trades: pl.DataFrame, + symbol_results: Sequence[_SymbolResult], + continuity_audits: Sequence[Mapping[str, Any]], + config: ProjectConfig, + stage: Path, + generated_at_utc: str, +) -> dict[str, str]: + summary = _trade_summary(trades, continuity_audits) + stability_frames: list[pl.DataFrame] = [] + flow_frames: list[pl.DataFrame] = [] + flow_feature = f"trade_imbalance_w{max(config.features.trade_windows)}" + for result in symbol_results: + train = _rows_by_plan(result.evaluation, result.plan.final_train_indices) + test = _rows_by_plan(result.evaluation, result.plan.test_indices) + stability_frames.append( + feature_stability_summary( + train, + test, + feature_columns=result.feature_columns, + group_columns=("symbol",), + ).with_columns( + pl.lit("final_training_period").alias("reference_period"), + pl.lit("untouched_final_test").alias("comparison_period"), + pl.lit(PUBLIC_EVIDENCE_TIER).alias("evidence_tier"), + ) + ) + labeled = result.evaluation.filter(~pl.col("right_censored")) + flow_frames.append( + ofi_future_return_association( + labeled, + horizon_return_columns={ + config.features.label_horizon_events: "future_trade_return" + }, + ofi_column=flow_feature, + min_observations=3, + ).with_columns( + pl.lit("all_feature_ready_labeled_rows").alias("analysis_scope"), + pl.lit(PUBLIC_EVIDENCE_TIER).alias("evidence_tier"), + ) + ) + stability = pl.concat(stability_frames) + flow_return = pl.concat(flow_frames) + artifacts = { + "trade_summary": "analysis/trade_summary.parquet", + "feature_stability": "analysis/feature_stability.parquet", + "flow_return_analysis": "analysis/flow_return_analysis.parquet", + } + for name, frame in ( + ("trade_summary", summary), + ("feature_stability", stability), + ("flow_return_analysis", flow_return), + ): + path = stage / artifacts[name] + path.parent.mkdir(parents=True, exist_ok=True) + frame.write_parquet(path) + _write_json( + stage / "analysis" / "manifest.json", + { + "generated_at_utc": generated_at_utc, + "evidence_tier": PUBLIC_EVIDENCE_TIER, + "descriptive_only": True, + "economic_claim_authorized": False, + "execution_claim_authorized": False, + "artifacts": { + "trade_summary": {"path": artifacts["trade_summary"], "rows": summary.height}, + "feature_stability": { + "path": artifacts["feature_stability"], + "rows": stability.height, + "reference": "final training period", + "comparison": "untouched final test", + }, + "flow_return_analysis": { + "path": artifacts["flow_return_analysis"], + "rows": flow_return.height, + "scope": "all feature-ready labeled rows", + }, + }, + "limitations": [ + "Retrospective bounded sample; no confirmatory significance claim.", + "Exchange event time is an availability proxy, not local receipt evidence.", + "Trade-only observations cannot support book or execution analysis.", + ], + }, + ) + return {**artifacts, "analysis_manifest": "analysis/manifest.json"} + + +def _quality_payload( + public: PublicTrades, + continuity_audits: Sequence[Mapping[str, Any]], + *, + generated_at_utc: str, +) -> dict[str, Any]: + return { + "generated_at_utc": generated_at_utc, + "dataset": "manifested_public_aggregate_trades", + "rows_checked": public.validation.rows_checked, + "summary": { + "errors": public.validation.error_count, + "warnings": public.validation.warning_count, + }, + "normalized_schema_validation": { + "dataset": public.validation.dataset, + "rows_checked": public.validation.rows_checked, + "errors": public.validation.error_count, + "warnings": public.validation.warning_count, + "findings": [asdict(finding) for finding in public.validation.findings], + }, + "aggregate_trade_continuity": list(continuity_audits), + "row_bound": public.row_bound, + "row_bound_respected": public.rows <= public.row_bound, + "canonical_source_order": list(public.canonical_order), + "mutation_policy": ( + "verified normalized observations were not repaired or overwritten; continuity " + "exists only in persisted derived research frames" + ), + } + + +def _hypothesis_number(value: object) -> str: + if value is None: + return "N/A" + if isinstance(value, (int, float)) and not isinstance(value, bool): + number = float(value) + return f"{number:.6f}" if math.isfinite(number) else "N/A" + return str(value) + + +def _render_hypothesis_report_section(stage: Path) -> str: + artifact = stage / "metrics" / "hypothesis_evaluation.json" + payload = _mapping(read_json(artifact)) + if payload is None: + raise PublicPipelineError("serialized hypothesis evaluation must be a JSON object") + rows = payload.get("per_symbol") + if not isinstance(rows, list) or not rows: + raise PublicPipelineError("serialized hypothesis evaluation has no per-symbol rows") + + lines = [ + "## Paired H0/H1 diagnostic", + "", + ( + "The frozen comparison is validation-selected test predictions versus the " + "historical-prior baseline on identical `row_id` and fixed 2x-horizon blocks. " + "For Δ log-loss (selected minus historical prior), a negative value favors the " + "selected model." + ), + "", + ( + "| Symbol | Selected model | Baseline | Metric | Point Δ | Paired 95% interval | " + "Observations | Blocks | Samples | Seed | Status |" + ), + "| --- | --- | --- | --- | ---: | --- | ---: | ---: | ---: | ---: | --- |", + ] + for value in rows: + row = _mapping(value) + if row is None: + raise PublicPipelineError("serialized per-symbol hypothesis row is not an object") + interval = ( + f"[{_hypothesis_number(row.get('ci_low'))}, {_hypothesis_number(row.get('ci_high'))}]" + ) + cells = ( + row.get("symbol"), + row.get("selected_model"), + row.get("baseline"), + row.get("metric"), + _hypothesis_number(row.get("point_delta")), + interval, + row.get("n_obs"), + row.get("n_blocks"), + row.get("samples"), + row.get("seed"), + row.get("status"), + ) + lines.append( + "| " + + " | ".join(str(cell).replace("|", "\\|").replace("\n", " ") for cell in cells) + + " |" + ) + lines.extend( + [ + "", + ( + "These paired percentile intervals are dependence diagnostics, not p-values " + "or confirmatory significance intervals; H0 is not rejected by this " + "exploratory design." + ), + "", + ( + "No cross-instrument estimate was pooled. Mixed directions, if present, " + "cannot support persistent alpha; even matching directions would remain " + "bounded, sample-specific diagnostics." + ), + ] + ) + return "\n".join(lines) + + +def _report_set(stage: Path) -> None: + bundle = load_run_bundle(stage, require_complete=False, verify_integrity=False) + hypothesis_section = _render_hypothesis_report_section(stage) + _atomic_write_text( + stage / "reports" / "technical_report.md", + render_technical_report(bundle), + ) + _atomic_write_text( + stage / "reports" / "executive_memo.md", + render_executive_memo(bundle), + ) + _atomic_write_text( + stage / "reports" / "model_comparison.md", + render_model_comparison(bundle) + + "\nExecution status: `NOT_RUN`. Reason: " + + EXECUTION_EXCLUSION_REASON + + "\n\n" + + hypothesis_section + + "\n", + ) + + +def produce_public_trade_run( + config: ProjectConfig, + stage: Path, + *, + ingestion_manifest_path: str | Path, + ingestion_manifest_sha256: str, +) -> None: + """Populate an empty atomic stage with one verified public trade-only run. + + The caller owns staging-directory creation, cleanup on failure, and final + rename. This function writes ``_SUCCESS`` only after every artifact, report, + and checksum is durable in the supplied stage. + """ + + destination = stage.resolve() + if destination.exists() and any(destination.iterdir()): + raise PublicPipelineError("public run stage must be empty") + destination.mkdir(parents=True, exist_ok=True) + + if config.data.mode != "binance_rest": + raise PublicPipelineError("public trade producer requires data.mode='binance_rest'") + explicit_manifest_path = Path(ingestion_manifest_path).resolve() + public = read_public_trades( + config, + explicit_manifest_path, + ingestion_manifest_sha256=ingestion_manifest_sha256, + ) + if public.evidence_tier == "FULL_DATA" and not public.all_requested_ranges_complete: + raise PublicPipelineError("reader evidence tier contradicts manifested completeness") + derived_trades, continuity_audits = _derive_verified_continuity(public, config) + if public.validation.has_errors: + raise PublicPipelineError("verified public normalized input has quality errors") + + generated = provenance_header( + project_root=config.project_root, + config_hash=config.hash, + evidence_tier=PUBLIC_EVIDENCE_TIER, + input_manifests=[], + ) + generated_at = cast(str, generated["generated_at_utc"]) + lineage = _input_lineage(public, config) + manifest_hashes = cast(list[str], lineage["manifest_sha256"]) + data_hashes = cast(list[str], lineage["data_sha256"]) + protocol_path, protocol_sha256 = _freeze_protocol(config, destination) + + symbol_results: list[_SymbolResult] = [] + for symbol_index, symbol in enumerate(config.data.symbols): + symbol_results.append( + _evaluate_symbol( + derived_trades.filter(pl.col("symbol") == symbol), + config=config, + symbol_index=symbol_index, + ) + ) + + research_root = destination / "research" + model_root = destination / "models" + combined_research: list[pl.DataFrame] = [] + combined_evaluation: list[pl.DataFrame] = [] + combined_predictions: list[pl.DataFrame] = [] + combined_comparison: list[pl.DataFrame] = [] + combined_selected: list[pl.DataFrame] = [] + symbol_manifest: dict[str, Any] = {} + for result in symbol_results: + slug = result.symbol.lower() + symbol_research = research_root / slug + symbol_models = model_root / slug + symbol_research.mkdir(parents=True, exist_ok=True) + symbol_models.mkdir(parents=True, exist_ok=True) + result.research.write_parquet(symbol_research / "research_frame.parquet") + result.evaluation.write_parquet(symbol_research / "evaluation_frame.parquet") + _write_json(symbol_research / "folds.json", _serialize_plan(result.plan)) + result.predictions.write_parquet(symbol_models / "predictions.parquet") + result.comparison.write_parquet(symbol_models / "comparison.parquet") + result.selected_predictions.write_parquet( + symbol_models / "selected_test_predictions.parquet" + ) + combined_research.append(result.research) + combined_evaluation.append(result.evaluation) + combined_predictions.append(result.predictions) + combined_comparison.append(result.comparison) + combined_selected.append(result.selected_predictions) + symbol_manifest[result.symbol] = { + "research_frame": f"research/{slug}/research_frame.parquet", + "evaluation_frame": f"research/{slug}/evaluation_frame.parquet", + "folds": f"research/{slug}/folds.json", + "predictions": f"models/{slug}/predictions.parquet", + "comparison": f"models/{slug}/comparison.parquet", + "selected_test_predictions": f"models/{slug}/selected_test_predictions.parquet", + "selected_model": result.selected_model, + "selection_metric": config.models.selection_metric, + "selection_source": "validation folds only", + "test_used_for_selection": False, + "feature_columns": list(result.feature_columns), + "temporal_audit": dict(result.temporal_audit), + "paired_hypothesis_evaluation": dict(result.hypothesis_evaluation), + "test_start_utc": _utc_from_ns(result.plan.test_start_ts_ns), + "test_end_utc": _utc_from_ns(result.plan.test_end_ts_ns), + } + + research = pl.concat(combined_research) + evaluation = pl.concat(combined_evaluation) + predictions = pl.concat(combined_predictions) + comparison = pl.concat(combined_comparison) + selected_predictions = pl.concat(combined_selected) + research.write_parquet(research_root / "research_frame.parquet") + evaluation.write_parquet(research_root / "evaluation_frame.parquet") + predictions.write_parquet(model_root / "predictions.parquet") + comparison.write_parquet(model_root / "comparison.parquet") + selected_predictions.write_parquet(model_root / "selected_test_predictions.parquet") + + metrics_root = destination / "metrics" + _write_json(metrics_root / "predictive_metrics.json", comparison.to_dicts()) + hypothesis_rows = [dict(result.hypothesis_evaluation) for result in symbol_results] + hypothesis_payload = { + "schema_version": PUBLIC_PIPELINE_SCHEMA_VERSION, + "generated_at_utc": generated_at, + "evidence_tier": PUBLIC_EVIDENCE_TIER, + "hypotheses": { + "H0": ( + "The validation-selected model does not improve held-out selection-metric " + "performance over the historical-prior classifier." + ), + "H1_exploratory": ( + "Causal aggregate-trade features improve held-out selection-metric " + "performance relative to the historical prior." + ), + }, + "comparison_contract": ( + "per-symbol validation-selected final-test predictions minus historical-prior " + "predictions on identical row_id and fixed dependency block" + ), + "selection_metric": config.models.selection_metric, + "delta_definition": "selected_model_minus_historical_prior", + "bootstrap": { + "method": "paired fixed-block percentile bootstrap", + "ci_level": 0.95, + "samples": config.evaluation.bootstrap_samples, + "seed_policy": "run_seed + symbol_index*100000 + 20000", + "block_policy": HYPOTHESIS_BLOCK_POLICY, + "block_width_trades": 2 * config.features.label_horizon_events, + }, + "per_symbol": hypothesis_rows, + "cross_instrument_conclusion": { + "status": "not_inferred", + "pooling_performed": False, + "persistent_alpha_claim_authorized": False, + "text": CROSS_INSTRUMENT_CONCLUSION, + }, + "exploratory": True, + "significance_claim_authorized": False, + "caveat": HYPOTHESIS_CAVEAT, + } + _write_json(metrics_root / "hypothesis_evaluation.json", hypothesis_payload) + _write_json(metrics_root / "execution_metrics.json", []) + _write_json(metrics_root / "execution_sensitivity.json", []) + _write_json( + metrics_root / "execution_exclusion.json", + { + "status": "NOT_RUN", + "reason": EXECUTION_EXCLUSION_REASON, + "execution_metrics_rows": 0, + "execution_sensitivity_rows": 0, + "pnl_calculated": False, + "profitability_claim_authorized": False, + }, + ) + + analysis_artifacts = _write_analyses( + trades=derived_trades, + symbol_results=symbol_results, + continuity_audits=continuity_audits, + config=config, + stage=destination, + generated_at_utc=generated_at, + ) + quality = _quality_payload(public, continuity_audits, generated_at_utc=generated_at) + _write_json(destination / "quality" / "summary.json", quality) + + market_state = evaluation.select( + "symbol", + "decision_ts_ns", + "decision_trade_id", + "price", + "quantity", + "aggressor_side", + f"trade_imbalance_w{max(config.features.trade_windows)}", + f"realized_volatility_w{config.features.volatility_window}", + pl.lit(PUBLIC_EVIDENCE_TIER).alias("evidence_tier"), + pl.lit("trade_only_no_book_state").alias("market_state_scope"), + ).sort(["decision_ts_ns", "symbol", "decision_trade_id"]) + dashboard_path = destination / "dashboard" / "market_state.parquet" + dashboard_path.parent.mkdir(parents=True, exist_ok=True) + market_state.write_parquet(dashboard_path) + + data_snapshot = { + "schema_version": PUBLIC_PIPELINE_SCHEMA_VERSION, + "mode": "binance_rest_trade_only", + "source": config.data.source, + "evidence_tier": PUBLIC_EVIDENCE_TIER, + "reader_effective_evidence_tier": public.evidence_tier, + "configured_requested_evidence_tier": config.run.evidence_tier, + "producer_evidence_policy": ( + "always PUBLIC_SAMPLE_PARTIAL for this retrospective exploratory protocol" + ), + "requested_period_utc": { + "start": config.data.start.isoformat().replace("+00:00", "Z"), + "end": config.data.end.isoformat().replace("+00:00", "Z") if config.data.end else None, + }, + "observed_period_utc": { + "start": public.observed.start_utc, + "end_inclusive": public.observed.end_inclusive_utc, + }, + "rows": public.rows, + "row_bound": public.row_bound, + "all_requested_ranges_complete": public.all_requested_ranges_complete, + "canonical_order": list(public.canonical_order), + "manifest_authority": { + "policy": "explicit path and caller-supplied SHA-256; no directory discovery", + "absolute_path": str(public.ingestion_manifest_path.resolve()), + "project_relative_or_absolute_path": _project_path( + public.ingestion_manifest_path, config.project_root + ), + "sha256": public.ingestion_manifest_sha256, + }, + "lineage": lineage, + "symbols": [ + { + "symbol": item.symbol, + "rows": item.rows, + "complete_range": item.complete_range, + "tick_size": str(item.tick_size), + "lot_size": str(item.lot_size), + "observed_start_utc": item.observed.start_utc, + "observed_end_inclusive_utc": item.observed.end_inclusive_utc, + } + for item in public.symbols + ], + "transformation": ( + "source normalized rows unchanged; one derived continuity epoch per symbol was " + "assigned only after contiguous aggregate-ID and nonreversing-clock checks" + ), + } + _write_json(destination / "data" / "manifest_snapshot.json", data_snapshot) + + resolved_config = config.public_dict() + resolved_config["effective_evidence_tier"] = PUBLIC_EVIDENCE_TIER + resolved_config["reader_effective_evidence_tier"] = public.evidence_tier + resolved_config["evidence_policy"] = ( + "retrospective public trade protocol cannot be promoted above PUBLIC_SAMPLE_PARTIAL" + ) + resolved_config["protocol"] = { + "path": protocol_path, + "sha256": protocol_sha256, + } + _write_json(destination / "resolved_config.json", resolved_config) + + git_metadata = cast(Mapping[str, Any], generated["git"]) + run_key_inputs = { + "config_sha256": config.hash, + "input_manifest_sha256": manifest_hashes, + "input_data_sha256": data_hashes, + "protocol_sha256": protocol_sha256, + "git": { + "commit": str(git_metadata.get("commit", "UNKNOWN")), + "dirty": bool(git_metadata.get("dirty", False)), + "source_tree_sha256": str(git_metadata.get("source_tree_sha256", "UNKNOWN")), + }, + "seed": config.run.seed, + "protocol": "public_aggregate_trade_exploratory_v1", + } + run_key = _stable_sha256(run_key_inputs) + generated.update( + { + "evidence_tier": PUBLIC_EVIDENCE_TIER, + "requested_evidence_tier": config.run.evidence_tier, + "effective_evidence_tier": PUBLIC_EVIDENCE_TIER, + "reader_effective_evidence_tier": public.evidence_tier, + "input_manifest_sha256": manifest_hashes, + "input_data_sha256": data_hashes, + "ingestion_manifest_path": _project_path( + public.ingestion_manifest_path, config.project_root + ), + "ingestion_manifest_absolute_path": str(public.ingestion_manifest_path.resolve()), + "ingestion_manifest_sha256": public.ingestion_manifest_sha256, + "ingestion_manifest_authority": ( + "explicit path and caller-supplied SHA-256; no directory discovery" + ), + "protocol_path": protocol_path, + "protocol_sha256": protocol_sha256, + "run_key": run_key, + "run_key_inputs": run_key_inputs, + "pipeline_schema_version": PUBLIC_PIPELINE_SCHEMA_VERSION, + "seed": config.run.seed, + "observed_start_utc": public.observed.start_utc, + "observed_end_utc": public.observed.end_inclusive_utc, + "data_availability_clock": "exchange_event_time_proxy", + "local_receipt_time_available": False, + "execution_simulated": False, + } + ) + _write_json(destination / "provenance.json", generated) + + artifacts = { + "resolved_config": "resolved_config.json", + "protocol": protocol_path, + "data_manifest_snapshot": "data/manifest_snapshot.json", + "quality_summary": "quality/summary.json", + "research_frame": "research/research_frame.parquet", + "evaluation_frame": "research/evaluation_frame.parquet", + "predictions": "models/predictions.parquet", + "selected_test_predictions": "models/selected_test_predictions.parquet", + "model_comparison_data": "models/comparison.parquet", + "predictive_metrics": "metrics/predictive_metrics.json", + "hypothesis_evaluation": "metrics/hypothesis_evaluation.json", + "execution_metrics": "metrics/execution_metrics.json", + "execution_sensitivity": "metrics/execution_sensitivity.json", + "execution_exclusion": "metrics/execution_exclusion.json", + "market_state": "dashboard/market_state.parquet", + "technical_report": "reports/technical_report.md", + "executive_memo": "reports/executive_memo.md", + "model_comparison": "reports/model_comparison.md", + **analysis_artifacts, + } + run_manifest = { + "schema_version": PUBLIC_PIPELINE_SCHEMA_VERSION, + "run_id": config.run.name, + "run_key": run_key, + "status": "complete", + "evidence_tier": PUBLIC_EVIDENCE_TIER, + "data": { + "mode": "binance_rest_trade_only", + "source": config.data.source, + "symbols": list(config.data.symbols), + "rows": public.rows, + "row_bound": public.row_bound, + "all_requested_ranges_complete": public.all_requested_ranges_complete, + "reader_effective_evidence_tier": public.evidence_tier, + "configured_requested_evidence_tier": config.run.evidence_tier, + "observed_start_utc": public.observed.start_utc, + "observed_end_utc": public.observed.end_inclusive_utc, + "observed_start_ts_ns": public.observed.start_ns, + "observed_end_ts_ns": public.observed.end_inclusive_ns, + "availability_basis": "exchange_event_time_proxy", + "local_receipt_time_available": False, + "symbol_coverage": [ + { + "symbol": item.symbol, + "rows": item.rows, + "complete_range": item.complete_range, + "observed_start_utc": item.observed.start_utc, + "observed_end_inclusive_utc": item.observed.end_inclusive_utc, + } + for item in public.symbols + ], + }, + "artifacts": artifacts, + "research": { + "question": ( + "whether recent observable aggregate-trade direction and size contain " + "out-of-time information about future trade-price direction" + ), + "target": "future_trade_up", + "label_horizon_trades": config.features.label_horizon_events, + "evaluation_contract": "separate per-symbol expanding purged walk-forward", + "selection_contract": "validation folds only; final test never used for selection", + "bootstrap_contract": { + "samples": config.evaluation.bootstrap_samples, + "seeded": True, + "block_width_trades": 2 * config.features.label_horizon_events, + "block_policy": "fixed_contiguous_2x_label_horizon", + "status": "dependence diagnostic, not confirmatory significance", + }, + "hypothesis_evaluation": { + "artifact": "metrics/hypothesis_evaluation.json", + "hypotheses": ["H0", "H1_exploratory"], + "baseline": HYPOTHESIS_BASELINE, + "metric": config.models.selection_metric, + "delta_definition": "selected_model_minus_historical_prior", + "paired_on": ["row_id", "bootstrap_block"], + "per_symbol_only": True, + "cross_instrument_pooling": False, + "persistent_alpha_claim_authorized": False, + "exploratory": True, + "significance_claim_authorized": False, + "caveat": HYPOTHESIS_CAVEAT, + "cross_instrument_conclusion": CROSS_INSTRUMENT_CONCLUSION, + }, + "symbols": symbol_manifest, + "descriptive_analysis": { + "manifest": analysis_artifacts["analysis_manifest"], + "descriptive_only": True, + "economic_claim_authorized": False, + }, + }, + "execution_assumptions": { + "status": "NOT_RUN", + "reason": EXECUTION_EXCLUSION_REASON, + "pnl_calculated": False, + "fills_calculated": False, + "capacity_calculated": False, + "profitability_claim_authorized": False, + }, + "warnings": [ + "PUBLIC_SAMPLE_PARTIAL: results are bounded, retrospective, and sample-specific.", + "Exchange event time is an availability proxy and not local receipt evidence.", + EXECUTION_EXCLUSION_REASON, + "Bootstrap intervals are dependence diagnostics and not significance claims.", + CROSS_INSTRUMENT_CONCLUSION, + ], + } + _write_json(destination / "run_manifest.json", run_manifest) + _report_set(destination) + if _input_lineage(public, config) != lineage: + raise PublicPipelineError("external input lineage changed while producing the run") + write_checksum_manifest(destination) + descriptor = os.open(destination / "_SUCCESS", os.O_CREAT | os.O_EXCL | os.O_WRONLY) + with os.fdopen(descriptor, "w", encoding="utf-8") as success: + success.write("complete\n") + load_run_bundle(destination) diff --git a/Microstructure/src/microstructure/py.typed b/Microstructure/src/microstructure/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Microstructure/src/microstructure/py.typed @@ -0,0 +1 @@ + diff --git a/Microstructure/src/microstructure/reporting/__init__.py b/Microstructure/src/microstructure/reporting/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..10ad01f0afd963dd72619155e787535d5ee520a0 --- /dev/null +++ b/Microstructure/src/microstructure/reporting/__init__.py @@ -0,0 +1,56 @@ +"""Frozen-bundle reporting and verification interfaces.""" + +from microstructure.reporting.bundle import ( + ChecksumMismatchError, + IncompleteRunError, + RunBundle, + RunBundleError, + RunBundleValidationError, + evidence_watermark, + load_run_bundle, + verify_checksums, + write_checksum_manifest, +) +from microstructure.reporting.l2 import ( + L2ReportData, + L2ReportError, + canonical_report_data_sha256, + render_l2_executive_memo, + render_l2_model_comparison, + render_l2_technical_report, + write_l2_report_set, +) +from microstructure.reporting.render import ( + ReportPaths, + render_executive_memo, + render_model_comparison_report, + render_technical_report, + write_report_set, +) +from microstructure.reporting.tables import comparison_rows, render_model_comparison + +__all__ = [ + "ChecksumMismatchError", + "IncompleteRunError", + "L2ReportData", + "L2ReportError", + "ReportPaths", + "RunBundle", + "RunBundleError", + "RunBundleValidationError", + "canonical_report_data_sha256", + "comparison_rows", + "evidence_watermark", + "load_run_bundle", + "render_executive_memo", + "render_l2_executive_memo", + "render_l2_model_comparison", + "render_l2_technical_report", + "render_model_comparison", + "render_model_comparison_report", + "render_technical_report", + "verify_checksums", + "write_checksum_manifest", + "write_l2_report_set", + "write_report_set", +] diff --git a/Microstructure/src/microstructure/reporting/bundle.py b/Microstructure/src/microstructure/reporting/bundle.py new file mode 100644 index 0000000000000000000000000000000000000000..65056ee6d2ae8bd37cdc7b44dd610566d533c56d --- /dev/null +++ b/Microstructure/src/microstructure/reporting/bundle.py @@ -0,0 +1,499 @@ +"""Read and verify immutable research run bundles. + +Reporting is deliberately downstream of research computation. A completed run +bundle contains frozen JSON/CSV/Parquet artifacts, a checksum manifest, and an +``_SUCCESS`` marker written only after every other file. The dashboard and +report renderer use this module rather than importing modeling code. +""" + +from __future__ import annotations + +import csv +import hmac +import json +import os +import re +import tempfile +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from datetime import UTC, datetime +from pathlib import Path, PurePosixPath +from typing import Any, cast + +from microstructure.provenance import sha256_file + +EvidenceTier = str + +EVIDENCE_TIERS = frozenset({"SYNTHETIC_SMOKE", "PUBLIC_SAMPLE_PARTIAL", "FULL_DATA"}) +SYNTHETIC_WATERMARK = ( + "SYNTHETIC SMOKE — SOFTWARE VALIDATION ONLY; NOT EMPIRICAL OR INVESTMENT EVIDENCE" +) +PUBLIC_SAMPLE_WATERMARK = ( + "PUBLIC SAMPLE / PARTIAL EVIDENCE — RESULTS ARE SAMPLE-SPECIFIC AND RESEARCH-ONLY" +) +FULL_DATA_WATERMARK = "FULL-DATA RESEARCH RUN — SIMULATED RESULTS ARE NOT LIVE-TRADING PERFORMANCE" + +_HEX_64 = re.compile(r"^[0-9a-f]{64}$") +_GIT_REVISION = re.compile(r"^[0-9a-f]{40}(?:[0-9a-f]{24})?$") +_CHECKSUM_LINE = re.compile(r"^([0-9a-f]{64}) ([^\n]+)$") +_CHECKSUM_EXCLUSIONS = frozenset({"checksums.sha256", "_SUCCESS", "INSUFFICIENT_DATA"}) + + +class RunBundleError(ValueError): + """Base error for an unusable research run bundle.""" + + +class IncompleteRunError(RunBundleError): + """Raised when the producer has not finalized a run bundle.""" + + +class RunBundleValidationError(RunBundleError): + """Raised when provenance or artifact structure is internally inconsistent.""" + + +class ChecksumMismatchError(RunBundleError): + """Raised when frozen bundle bytes no longer match their manifest.""" + + +def evidence_watermark(evidence_tier: str) -> str: + """Return the mandatory, user-visible evidence label for a run.""" + labels = { + "SYNTHETIC_SMOKE": SYNTHETIC_WATERMARK, + "PUBLIC_SAMPLE_PARTIAL": PUBLIC_SAMPLE_WATERMARK, + "FULL_DATA": FULL_DATA_WATERMARK, + } + try: + return labels[evidence_tier] + except KeyError as error: + raise RunBundleValidationError(f"unsupported evidence tier {evidence_tier!r}") from error + + +@dataclass(frozen=True, slots=True) +class RunBundle: + """Validated, read-only view of a completed run directory.""" + + root: Path + manifest: Mapping[str, Any] + provenance: Mapping[str, Any] + quality: Mapping[str, Any] + hypothesis_evaluation: Mapping[str, Any] + predictive_metrics: tuple[Mapping[str, Any], ...] + execution_metrics: tuple[Mapping[str, Any], ...] + execution_sensitivity: tuple[Mapping[str, Any], ...] + market_state: tuple[Mapping[str, Any], ...] + + @property + def run_id(self) -> str: + return cast(str, self.manifest["run_id"]) + + @property + def evidence_tier(self) -> str: + return cast(str, self.manifest["evidence_tier"]) + + @property + def watermark(self) -> str: + return evidence_watermark(self.evidence_tier) + + @property + def data(self) -> Mapping[str, Any]: + return cast(Mapping[str, Any], self.manifest["data"]) + + @property + def symbols(self) -> tuple[str, ...]: + return tuple(str(value) for value in cast(Sequence[Any], self.data["symbols"])) + + @property + def observed_start_utc(self) -> str: + return cast(str, self.data["observed_start_utc"]) + + @property + def observed_end_utc(self) -> str: + return cast(str, self.data["observed_end_utc"]) + + +def _read_json(path: Path) -> Any: + try: + with path.open(encoding="utf-8") as handle: + return json.load(handle) + except (OSError, json.JSONDecodeError) as error: + raise RunBundleValidationError( + f"cannot read valid JSON from {path.name}: {error}" + ) from error + + +def _read_json_object(path: Path) -> dict[str, Any]: + payload = _read_json(path) + if not isinstance(payload, dict): + raise RunBundleValidationError(f"{path.name} must contain a JSON object") + return cast(dict[str, Any], payload) + + +def _utc(value: Any, field: str) -> datetime: + if not isinstance(value, str): + raise RunBundleValidationError(f"{field} must be a UTC timestamp string") + try: + parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) + except ValueError as error: + raise RunBundleValidationError(f"{field} is not an ISO-8601 timestamp") from error + if parsed.tzinfo is None or parsed.utcoffset() != UTC.utcoffset(parsed): + raise RunBundleValidationError(f"{field} must be explicitly UTC") + return parsed + + +def _require_sha256(value: Any, field: str) -> str: + if not isinstance(value, str) or _HEX_64.fullmatch(value) is None: + raise RunBundleValidationError(f"{field} must be a lowercase SHA-256 digest") + return value + + +def _validate_manifest(manifest: Mapping[str, Any], provenance: Mapping[str, Any]) -> None: + run_id = manifest.get("run_id") + if not isinstance(run_id, str) or not run_id.strip(): + raise RunBundleValidationError("run_manifest.json requires a non-empty run_id") + if manifest.get("status") != "complete": + raise IncompleteRunError("run_manifest.json status must be 'complete'") + + tier = manifest.get("evidence_tier") + if not isinstance(tier, str) or tier not in EVIDENCE_TIERS: + raise RunBundleValidationError(f"unsupported evidence tier {tier!r}") + if provenance.get("evidence_tier") != tier: + raise RunBundleValidationError("run manifest and provenance evidence tiers do not match") + + data = manifest.get("data") + if not isinstance(data, Mapping): + raise RunBundleValidationError("run_manifest.json requires a data object") + mode = data.get("mode") + source = data.get("source") + if not isinstance(mode, str) or not isinstance(source, str): + raise RunBundleValidationError("data.mode and data.source must be strings") + synthetic_source = "synthetic" in mode.lower() or "synthetic" in source.lower() + if tier == "SYNTHETIC_SMOKE" and not synthetic_source: + raise RunBundleValidationError( + "SYNTHETIC_SMOKE requires a clearly identified synthetic data source" + ) + if tier != "SYNTHETIC_SMOKE" and synthetic_source: + raise RunBundleValidationError( + "synthetic data cannot be promoted to public-sample or full-data evidence" + ) + if tier == "FULL_DATA" and data.get("all_requested_ranges_complete") is not True: + raise RunBundleValidationError( + "FULL_DATA requires manifested complete coverage for every requested range" + ) + + symbols = data.get("symbols") + if ( + not isinstance(symbols, Sequence) + or isinstance(symbols, str) + or not symbols + or not all(isinstance(symbol, str) and symbol for symbol in symbols) + ): + raise RunBundleValidationError("data.symbols must be a non-empty string list") + observed_start = _utc(data.get("observed_start_utc"), "data.observed_start_utc") + observed_end = _utc(data.get("observed_end_utc"), "data.observed_end_utc") + if observed_end < observed_start: + raise RunBundleValidationError("observed data period ends before it starts") + + _utc(provenance.get("generated_at_utc"), "provenance.generated_at_utc") + _require_sha256(provenance.get("config_sha256"), "provenance.config_sha256") + input_hashes = provenance.get("input_manifest_sha256") + if not isinstance(input_hashes, list): + raise RunBundleValidationError("provenance.input_manifest_sha256 must be a list") + if tier != "SYNTHETIC_SMOKE" and not input_hashes: + raise RunBundleValidationError( + "public-sample and full-data runs require at least one input manifest SHA-256" + ) + for index, digest in enumerate(input_hashes): + _require_sha256(digest, f"provenance.input_manifest_sha256[{index}]") + + manifest_run_key = manifest.get("run_key") + provenance_run_key = provenance.get("run_key") + if manifest_run_key is not None or provenance_run_key is not None: + manifest_digest = _require_sha256(manifest_run_key, "run_manifest.run_key") + provenance_digest = _require_sha256(provenance_run_key, "provenance.run_key") + if not hmac.compare_digest(manifest_digest, provenance_digest): + raise RunBundleValidationError("run manifest and provenance run keys do not match") + + git = provenance.get("git") + if not isinstance(git, Mapping): + raise RunBundleValidationError("provenance.git must be an object") + commit = git.get("commit") + if commit != "UNBORN" and ( + not isinstance(commit, str) or _GIT_REVISION.fullmatch(commit) is None + ): + raise RunBundleValidationError( + "provenance.git.commit must be UNBORN or a 40/64-character revision" + ) + if not isinstance(git.get("dirty"), bool): + raise RunBundleValidationError("provenance.git.dirty must be boolean") + + +def _safe_relative_path(root: Path, value: Any, field: str) -> Path: + if not isinstance(value, str) or not value: + raise RunBundleValidationError(f"{field} must be a relative path") + relative = PurePosixPath(value) + if relative.is_absolute() or ".." in relative.parts: + raise RunBundleValidationError(f"{field} cannot escape the run directory") + destination = root.joinpath(*relative.parts) + if not destination.is_relative_to(root): + raise RunBundleValidationError(f"{field} cannot escape the run directory") + return destination + + +def _artifact_path( + root: Path, + manifest: Mapping[str, Any], + name: str, + fallbacks: Sequence[str], +) -> Path | None: + artifacts = manifest.get("artifacts", {}) + if not isinstance(artifacts, Mapping): + raise RunBundleValidationError("run_manifest.json artifacts must be an object") + declared = artifacts.get(name) + if declared is not None: + path = _safe_relative_path(root, declared, f"artifacts.{name}") + if not path.is_file(): + raise RunBundleValidationError( + f"declared artifact {name!r} does not exist: {path.relative_to(root)}" + ) + return path + for fallback in fallbacks: + candidate = root / fallback + if candidate.is_file(): + return candidate + return None + + +def _records_from_json(path: Path) -> tuple[Mapping[str, Any], ...]: + payload = _read_json(path) + if isinstance(payload, Mapping): + for key in ("rows", "records"): + if key in payload: + payload = payload[key] + break + if not isinstance(payload, list) or not all(isinstance(row, Mapping) for row in payload): + raise RunBundleValidationError(f"{path.name} must contain a list of row objects") + return tuple(cast(Mapping[str, Any], row) for row in payload) + + +def _read_records(path: Path | None) -> tuple[Mapping[str, Any], ...]: + if path is None: + return () + suffix = path.suffix.lower() + if suffix == ".json": + return _records_from_json(path) + if suffix == ".csv": + try: + with path.open(newline="", encoding="utf-8") as handle: + return tuple(dict(row) for row in csv.DictReader(handle)) + except OSError as error: + raise RunBundleValidationError(f"cannot read {path.name}: {error}") from error + if suffix == ".parquet": + try: + import polars as pl + + return tuple(pl.read_parquet(path).to_dicts()) + except Exception as error: + raise RunBundleValidationError(f"cannot read {path.name}: {error}") from error + raise RunBundleValidationError(f"unsupported artifact format for {path.name}") + + +def _read_quality(path: Path | None) -> Mapping[str, Any]: + if path is None: + return {} + payload = _read_json(path) + if not isinstance(payload, Mapping): + raise RunBundleValidationError(f"{path.name} must contain a JSON object") + return cast(Mapping[str, Any], payload) + + +def _bundle_files(root: Path) -> tuple[Path, ...]: + files: list[Path] = [] + for path in root.rglob("*"): + if path.is_symlink(): + raise RunBundleValidationError( + f"run bundles may not contain symlinks: {path.relative_to(root)}" + ) + if path.is_file() and path.relative_to(root).as_posix() not in _CHECKSUM_EXCLUSIONS: + files.append(path) + return tuple(sorted(files, key=lambda item: item.relative_to(root).as_posix())) + + +def _atomic_write_text(path: Path, content: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary_name = tempfile.mkstemp( + dir=path.parent, + prefix=f".{path.name}.", + suffix=".tmp", + text=True, + ) + try: + with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as handle: + handle.write(content) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary_name, path) + directory_descriptor = os.open(path.parent, os.O_RDONLY) + try: + os.fsync(directory_descriptor) + finally: + os.close(directory_descriptor) + except BaseException: + Path(temporary_name).unlink(missing_ok=True) + raise + + +def write_checksum_manifest(run_dir: str | Path) -> Path: + """Write deterministic checksums for all current run files. + + Call this only while staging a run, before creating ``_SUCCESS``. The + checksum file and completion marker are intentionally excluded. + """ + root = Path(run_dir).resolve() + if not root.is_dir(): + raise IncompleteRunError(f"run directory does not exist: {root}") + if (root / "_SUCCESS").exists() and (root / "INSUFFICIENT_DATA").exists(): + raise IncompleteRunError("run has conflicting completion and insufficient-data markers") + if (root / "_SUCCESS").exists(): + raise RunBundleValidationError( + "cannot rewrite checksums for a completed run; create a new run bundle" + ) + lines = [ + f"{sha256_file(path)} {path.relative_to(root).as_posix()}" for path in _bundle_files(root) + ] + if not lines: + raise IncompleteRunError("cannot checksum an empty run directory") + destination = root / "checksums.sha256" + _atomic_write_text(destination, "\n".join(lines) + "\n") + return destination + + +def verify_checksums(run_dir: str | Path) -> int: + """Verify checksum coverage and return the number of protected files.""" + root = Path(run_dir).resolve() + checksum_path = root / "checksums.sha256" + if not checksum_path.is_file(): + raise IncompleteRunError("missing checksums.sha256") + try: + lines = checksum_path.read_text(encoding="utf-8").splitlines() + except OSError as error: + raise ChecksumMismatchError(f"cannot read checksums.sha256: {error}") from error + if not lines: + raise ChecksumMismatchError("checksums.sha256 is empty") + + declared: dict[str, str] = {} + for line_number, line in enumerate(lines, start=1): + match = _CHECKSUM_LINE.fullmatch(line) + if match is None: + raise ChecksumMismatchError(f"invalid checksums.sha256 line {line_number}") + digest, relative_name = match.groups() + if relative_name in declared: + raise ChecksumMismatchError(f"duplicate checksum entry: {relative_name}") + path = _safe_relative_path(root, relative_name, "checksum path") + if not path.is_file() or path.is_symlink(): + raise ChecksumMismatchError(f"checksummed file is missing: {relative_name}") + actual = sha256_file(path) + if not hmac.compare_digest(actual, digest): + raise ChecksumMismatchError(f"checksum mismatch: {relative_name}") + declared[relative_name] = digest + + actual_files = {path.relative_to(root).as_posix() for path in _bundle_files(root)} + declared_files = set(declared) + missing = sorted(actual_files - declared_files) + extra = sorted(declared_files - actual_files) + if missing: + raise ChecksumMismatchError("files absent from checksum manifest: " + ", ".join(missing)) + if extra: + raise ChecksumMismatchError("checksum entries without files: " + ", ".join(extra)) + return len(declared) + + +def load_run_bundle( + run_dir: str | Path, + *, + require_complete: bool = True, + verify_integrity: bool = True, +) -> RunBundle: + """Load a run after validating provenance, evidence tier, and integrity.""" + root = Path(run_dir).resolve() + if not root.is_dir(): + raise IncompleteRunError(f"run directory does not exist: {root}") + if (root / "_SUCCESS").exists() and (root / "INSUFFICIENT_DATA").exists(): + raise IncompleteRunError("run has conflicting completion and insufficient-data markers") + if require_complete and not (root / "_SUCCESS").is_file(): + raise IncompleteRunError("missing _SUCCESS completion marker") + if require_complete and verify_integrity: + verify_checksums(root) + + manifest_path = root / "run_manifest.json" + provenance_path = root / "provenance.json" + if not manifest_path.is_file(): + raise IncompleteRunError("missing run_manifest.json") + if not provenance_path.is_file(): + raise IncompleteRunError("missing provenance.json") + manifest = _read_json_object(manifest_path) + provenance = _read_json_object(provenance_path) + _validate_manifest(manifest, provenance) + + predictive = _artifact_path( + root, + manifest, + "predictive_metrics", + ( + "metrics/predictive_metrics.json", + "metrics/predictive_metrics.csv", + "metrics/predictive_metrics.parquet", + ), + ) + execution = _artifact_path( + root, + manifest, + "execution_metrics", + ( + "metrics/execution_metrics.json", + "metrics/execution_metrics.csv", + "metrics/execution_metrics.parquet", + ), + ) + execution_sensitivity = _artifact_path( + root, + manifest, + "execution_sensitivity", + ( + "metrics/execution_sensitivity.json", + "metrics/execution_sensitivity.csv", + "metrics/execution_sensitivity.parquet", + ), + ) + market_state = _artifact_path( + root, + manifest, + "market_state", + ( + "dashboard/market_state.json", + "dashboard/market_state.csv", + "dashboard/market_state.parquet", + ), + ) + quality_path = _artifact_path( + root, + manifest, + "quality_summary", + ("quality/summary.json",), + ) + hypothesis_path = _artifact_path( + root, + manifest, + "hypothesis_evaluation", + (), + ) + return RunBundle( + root=root, + manifest=manifest, + provenance=provenance, + quality=_read_quality(quality_path), + hypothesis_evaluation=_read_quality(hypothesis_path), + predictive_metrics=_read_records(predictive), + execution_metrics=_read_records(execution), + execution_sensitivity=_read_records(execution_sensitivity), + market_state=_read_records(market_state), + ) diff --git a/Microstructure/src/microstructure/reporting/l2.py b/Microstructure/src/microstructure/reporting/l2.py new file mode 100644 index 0000000000000000000000000000000000000000..508dffb8f1bc27d09eb6373c270027e6d8d7cac6 --- /dev/null +++ b/Microstructure/src/microstructure/reporting/l2.py @@ -0,0 +1,365 @@ +"""Deterministic human-readable reports for the prospective live-L2 bundle.""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import tempfile +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from pathlib import Path +from typing import Any, cast + + +class L2ReportError(ValueError): + """Raised when machine artifacts cannot support an honest L2 report.""" + + +@dataclass(frozen=True, slots=True) +class L2ReportData: + """Verified machine artifacts consumed by all three report surfaces.""" + + manifest: Mapping[str, Any] + provenance: Mapping[str, Any] + session_gates: tuple[Mapping[str, Any], ...] + hypothesis: Mapping[str, Any] + predictive_metrics: tuple[Mapping[str, Any], ...] + paired_metrics: tuple[Mapping[str, Any], ...] + equal_session_metrics: tuple[Mapping[str, Any], ...] + execution_metrics: tuple[Mapping[str, Any], ...] + + +def _mapping(value: object, label: str) -> Mapping[str, Any]: + if not isinstance(value, Mapping): + raise L2ReportError(f"{label} must be an object") + return value + + +def _text(value: object, label: str) -> str: + if not isinstance(value, str) or not value: + raise L2ReportError(f"{label} must be nonempty text") + return value + + +def _number(value: object) -> str: + if value is None: + return "N/A" + try: + observed = float(cast(Any, value)) + except (TypeError, ValueError): + return str(value) + if not math.isfinite(observed): + return "N/A" + return f"{observed:.6f}" + + +def _ratio(value: object, label: str) -> str: + if value is None: + return "N/A" + try: + observed = float(cast(Any, value)) + except (TypeError, ValueError) as error: + raise L2ReportError(f"{label} must be a finite ratio") from error + if not math.isfinite(observed) or not 0.0 <= observed <= 1.0: + raise L2ReportError(f"{label} must lie in [0, 1]") + return f"{observed:.6f}" + + +def _bool(value: object) -> str: + return "yes" if value is True else "no" if value is False else "N/A" + + +def _session_table(rows: Sequence[Mapping[str, Any]]) -> str: + header = ( + "| Date | Role | Status | BTC gate | ETH gate | Overlap seconds |\n" + "| --- | --- | --- | --- | --- | ---: |" + ) + body = [ + "| {date} | {role} | {status} | {btc} | {eth} | {overlap} |".format( + date=row.get("study_date", "N/A"), + role=row.get("study_role", "N/A"), + status=row.get("status", "N/A"), + btc=row.get("BTCUSDT_gate", row.get("btc_gate", "N/A")), + eth=row.get("ETHUSDT_gate", row.get("eth_gate", "N/A")), + overlap=_number(row.get("overlap_seconds")), + ) + for row in rows + ] + return "\n".join([header, *body]) + + +def _predictive_table(rows: Sequence[Mapping[str, Any]]) -> str: + header = ( + "| Symbol | Endpoint | Session | Model | N | Log loss | Prior | Delta | Brier | ECE |\n" + "| --- | --- | --- | --- | ---: | ---: | ---: | ---: | ---: | ---: |" + ) + body = [ + "| {symbol} | {endpoint} | {date} | {model} | {n} | {loss} | {prior} | {delta} | {brier} | {ece} |".format( + symbol=row.get("symbol", "N/A"), + endpoint=row.get("endpoint_name", "N/A"), + date=row.get("study_date", row.get("study_role", "N/A")), + model=row.get("selected_model", row.get("model", "N/A")), + n=row.get("n_obs", "N/A"), + loss=_number(row.get("selected_log_loss", row.get("log_loss"))), + prior=_number(row.get("prior_log_loss")), + delta=_number(row.get("point_delta", row.get("delta_log_loss"))), + brier=_number(row.get("selected_brier_score", row.get("brier_score"))), + ece=_number( + row.get( + "selected_expected_calibration_error", row.get("expected_calibration_error") + ) + ), + ) + for row in rows + ] + return "\n".join([header, *body]) + + +def _paired_table(rows: Sequence[Mapping[str, Any]]) -> str: + header = ( + "| Symbol | Endpoint | Session/regime | N | Blocks | Δ log loss | 95% low | 95% high | Status |\n" + "| --- | --- | --- | ---: | ---: | ---: | ---: | ---: | --- |" + ) + + def scope(row: Mapping[str, Any]) -> str: + session = row.get("study_date", "equal-session") + regime = row.get("regime", "N/A") + return f"{session} / {regime}" + + body = [ + "| {symbol} | {endpoint} | {scope} | {n} | {blocks} | {delta} | {low} | {high} | {status} |".format( + symbol=row.get("symbol", "N/A"), + endpoint=row.get("endpoint_name", "N/A"), + scope=scope(row), + n=row.get("n_obs", "N/A"), + blocks=row.get("n_blocks", "N/A"), + delta=_number(row.get("point_delta")), + low=_number(row.get("ci_low", row.get("lower"))), + high=_number(row.get("ci_high", row.get("upper"))), + status=row.get("status", "N/A"), + ) + for row in rows + ] + return "\n".join([header, *body]) + + +def _execution_table(rows: Sequence[Mapping[str, Any]]) -> str: + header = ( + "| Symbol | Endpoint | Session | Decision/order latency | Orders | Fill ratio | Turnover | Marked net P&L | Residual inventory |\n" + "| --- | --- | --- | --- | ---: | ---: | ---: | ---: | ---: |" + ) + body = [ + "| {symbol} | {endpoint} | {date} | {decision}/{order} events | {orders} | {fill} | {turnover} | {pnl} | {residual} |".format( + symbol=row.get("symbol", "N/A"), + endpoint=row.get("endpoint_name", "N/A"), + date=row.get("study_date", "N/A"), + decision=row.get("decision_latency_events", "N/A"), + order=row.get("order_latency_events", "N/A"), + orders=row.get("strategy_orders", "N/A"), + fill=_ratio(row.get("fill_ratio"), "execution fill ratio"), + turnover=_number(row.get("turnover_notional")), + pnl=_number(row.get("marked_net_pnl", row.get("net_pnl"))), + residual=_number(row.get("unliquidated_quantity")), + ) + for row in rows + ] + return "\n".join([header, *body]) + + +def _authority( + data: L2ReportData, +) -> tuple[Mapping[str, Any], Mapping[str, Any], Mapping[str, Any]]: + research = _mapping(data.manifest.get("research"), "run manifest research") + git = _mapping(data.provenance.get("git"), "provenance Git") + inputs = _mapping(data.provenance.get("inputs"), "provenance inputs") + if data.manifest.get("evidence_tier") != "FULL_DATA": + raise L2ReportError("live-L2 reports require FULL_DATA session scope") + status = data.manifest.get("status") + effective_tier = data.manifest.get("effective_evidence_tier") + expected_tier = "FULL_DATA" if status == "COMPLETE" else "INSUFFICIENT_DATA" + if status not in {"COMPLETE", "INSUFFICIENT_DATA"} or effective_tier != expected_tier: + raise L2ReportError("live-L2 report status and effective evidence tier disagree") + if data.manifest.get("live_trading") is not False: + raise L2ReportError("live-L2 research reports must state live_trading=false") + return research, git, inputs + + +def _evidence_banner(data: L2ReportData) -> str: + if data.manifest.get("status") == "COMPLETE": + return ( + "FULL-DATA PUBLIC L2 RESEARCH — RESEARCH/SIMULATION ONLY; " + "NOT LIVE TRADING OR REALIZED PERFORMANCE" + ) + return ( + "INSUFFICIENT_DATA — NO HELD-OUT, EXECUTION, ECONOMIC, " + "SIGNIFICANCE, OR PROFITABILITY CONCLUSION" + ) + + +def render_l2_technical_report(data: L2ReportData) -> str: + research, git, inputs = _authority(data) + conclusion = _text(data.hypothesis.get("conclusion"), "hypothesis conclusion") + return f"""# M8 prospective live-L2 technical report + +> {_evidence_banner(data)} + +## Research question + +{_text(research.get("question"), "research question")} + +## Immutable authority + +- Capture period: `{research.get("period_start_utc")}` through `{research.get("period_end_utc")}` +- Capture config SHA-256: `{inputs.get("capture_config_sha256")}` +- Capture protocol SHA-256: `{inputs.get("capture_protocol_sha256")}` +- Analysis contract SHA-256: `{inputs.get("analysis_config_sha256")}` +- Development aggregate lock SHA-256: `{inputs.get("development_lock_sha256")}` +- Git commit: `{git.get("commit")}`; source-tree SHA-256: `{git.get("source_tree_sha256")}`; dirty: `{git.get("dirty")}` +- Test update policy: fit once on Aug 8-9, then no refit or recalibration on Aug 10-11. + +## Session data-quality gates + +{_session_table(data.session_gates)} + +## Held-out predictive quality + +{_predictive_table(data.predictive_metrics)} + +## Paired dependence-aware diagnostics + +{_paired_table(data.paired_metrics)} + +Equal-session summaries are reported separately and never pooled across symbols. P-values, H0 rejection, statistical-significance claims, and persistent-alpha claims are not authorized. + +## Market-order scenarios + +{_execution_table(data.execution_metrics)} + +These are exogenous historical replays at recorded L1 quotes with frozen fees, event latency, displayed-depth caps, inventory limits, and end liquidation. They are not realized execution; no capacity or profitability claim is authorized. + +## Outcome + +{conclusion} + +## Limitations + +- Public Binance depth data are exchange-specific and contain no authenticated account or order-entry path. +- Book-only data do not identify true queue priority, hidden liquidity, trade aggressor depletion, endogenous impact, or limit-fill probability. +- OFI-signed future-mid markout is a descriptive book-flow measure, not observed trade impact or a causal effect. +- Four fixed one-hour sessions cannot establish persistence outside the declared dates, instruments, or market regimes. +- All confidence intervals are seeded descriptive block-bootstrap diagnostics; multiple-testing and generalizability remain material limitations. +""" + + +def render_l2_executive_memo(data: L2ReportData) -> str: + research, git, inputs = _authority(data) + conclusion = _text(data.hypothesis.get("conclusion"), "hypothesis conclusion") + replicated = [ + row + for row in data.equal_session_metrics + if row.get("regime") == "ALL" and row.get("directionally_replicated") is True + ] + declared_replicated = data.hypothesis.get("directionally_replicated_pairs") + if declared_replicated != len(replicated): + raise L2ReportError( + "hypothesis replicated-pair count differs from overall equal-session metrics" + ) + return f"""# Investment committee memo — prospective live-L2 study + +> RESEARCH/SIMULATION ONLY — NO LIVE ORDERS, REALIZED EXECUTION, SIGNIFICANCE, CAPACITY, OR PROFITABILITY CLAIM + +**Evidence tier.** {_evidence_banner(data)}. + +**Decision.** Do not interpret this four-session study as deployment evidence. It is a predeclared test of whether book-state models improve direction log loss over a historical prior and whether that direction repeats on both untouched sessions. + +**Evidence boundary.** The study covers `{research.get("period_start_utc")}` through `{research.get("period_end_utc")}` for BTCUSDT and ETHUSDT. The exact capture/analysis inputs are bound by `{inputs.get("capture_config_sha256")}` and `{inputs.get("analysis_config_sha256")}`; the development lock is `{inputs.get("development_lock_sha256")}`. Code identity is `{git.get("commit")}` with source tree `{git.get("source_tree_sha256")}`. Primary and replication predictions restore that lock without update or refit. + +**Result.** {conclusion} + +Directionally replicated symbol/endpoint pairs: **{len(replicated)}**. This count is descriptive and is not a multiple-testing-adjusted discovery claim. + +**Economic interpretation.** Predictive scoring and the 3x3 market-order scenario grid are reported separately. Scenario P&L is a marked replay under recorded L1 depth, 4 bps taker fees, frozen event latency, partial fills, inventory limits, and end liquidation. It is not realized or deployable performance. + +**Recommendation.** Preserve the result—including null, adverse, or insufficient outcomes—without date replacement. Any next study requires a new preregistered authority and broader independent dates. +""" + + +def render_l2_model_comparison(data: L2ReportData) -> str: + research, git, inputs = _authority(data) + return f"""# M8 live-L2 model comparison + +> {_evidence_banner(data)}; NO CROSS-SYMBOL POOLING OR SIGNIFICANCE CLAIM + +Period: `{research.get("period_start_utc")}` through `{research.get("period_end_utc")}`. Capture config: `{inputs.get("capture_config_sha256")}`. Analysis config: `{inputs.get("analysis_config_sha256")}`. Development lock: `{inputs.get("development_lock_sha256")}`. Git commit: `{git.get("commit")}`; source tree: `{git.get("source_tree_sha256")}`. + +{_predictive_table(data.predictive_metrics)} + +## Selected-minus-prior paired diagnostics + +{_paired_table(data.equal_session_metrics)} + +Every endpoint was selected on the validation session only. The primary and replication sessions use the same persisted numeric fitted state without update. +""" + + +def _atomic_text(path: Path, text: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary_name = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.") + temporary = Path(temporary_name) + try: + with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as handle: + handle.write(text) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, path) + directory = os.open(path.parent, os.O_RDONLY) + try: + os.fsync(directory) + finally: + os.close(directory) + except BaseException: + temporary.unlink(missing_ok=True) + raise + + +def write_l2_report_set(output_dir: str | Path, data: L2ReportData) -> tuple[Path, Path, Path]: + """Write all L2 reports from the same verified machine-artifact view.""" + + root = Path(output_dir) + technical = root / "technical_report.md" + memo = root / "executive_memo.md" + comparison = root / "model_comparison.md" + _atomic_text(technical, render_l2_technical_report(data)) + _atomic_text(memo, render_l2_executive_memo(data)) + _atomic_text(comparison, render_l2_model_comparison(data)) + return technical, memo, comparison + + +def canonical_report_data_sha256(data: L2ReportData) -> str: + """Bind the exact machine inputs used to render all report prose.""" + + payload = { + "manifest": dict(data.manifest), + "provenance": dict(data.provenance), + "session_gates": [dict(row) for row in data.session_gates], + "hypothesis": dict(data.hypothesis), + "predictive_metrics": [dict(row) for row in data.predictive_metrics], + "paired_metrics": [dict(row) for row in data.paired_metrics], + "equal_session_metrics": [dict(row) for row in data.equal_session_metrics], + "execution_metrics": [dict(row) for row in data.execution_metrics], + } + encoded = json.dumps(payload, sort_keys=True, separators=(",", ":"), allow_nan=False).encode() + return hashlib.sha256(encoded).hexdigest() + + +__all__ = [ + "L2ReportData", + "L2ReportError", + "canonical_report_data_sha256", + "render_l2_executive_memo", + "render_l2_model_comparison", + "render_l2_technical_report", + "write_l2_report_set", +] diff --git a/Microstructure/src/microstructure/reporting/render.py b/Microstructure/src/microstructure/reporting/render.py new file mode 100644 index 0000000000000000000000000000000000000000..972781a835a8a1007ae65620e3af34c3871ce88e --- /dev/null +++ b/Microstructure/src/microstructure/reporting/render.py @@ -0,0 +1,781 @@ +"""Pure Markdown rendering from a validated, frozen run bundle.""" + +from __future__ import annotations + +import json +import os +import tempfile +from collections.abc import Mapping +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +from microstructure.reporting.bundle import RunBundle +from microstructure.reporting.tables import comparison_rows, render_model_comparison + +_DEFAULT_RESEARCH_QUESTION = ( + "When do order-flow imbalance, liquidity, and observable market state predict\n" + "short-horizon price movement, and how much apparent value survives the separately\n" + "specified execution model?" +) + + +def _display(value: Any) -> str: + if value is None or value == "": + return "N/A" + if isinstance(value, bool): + return "true" if value else "false" + if isinstance(value, (dict, list, tuple)): + return json.dumps(value, sort_keys=True, separators=(",", ":")) + return str(value).replace("|", "\\|").replace("\n", " ") + + +def _mapping_table(values: Mapping[str, Any]) -> str: + if not values: + return "No serialized values were supplied." + lines = ["| Field | Serialized value |", "| --- | --- |"] + for key in sorted(values): + lines.append(f"| {_display(key)} | {_display(values[key])} |") + return "\n".join(lines) + + +def _provenance_table(bundle: RunBundle) -> str: + git = bundle.provenance.get("git", {}) + if not isinstance(git, Mapping): + git = {} + input_hashes = bundle.provenance.get("input_manifest_sha256", []) + values = { + "Run ID": bundle.run_id, + "Evidence tier": bundle.evidence_tier, + "Symbols": ", ".join(bundle.symbols), + "Observed start (UTC)": bundle.observed_start_utc, + "Observed end (UTC)": bundle.observed_end_utc, + "Configuration SHA-256": bundle.provenance.get("config_sha256"), + "Input manifest SHA-256": input_hashes, + "Git commit": git.get("commit"), + "Git dirty at run time": git.get("dirty"), + "Seed": bundle.provenance.get("seed"), + "Runtime metadata": bundle.provenance.get("runtime"), + "Generated at (UTC)": bundle.provenance.get("generated_at_utc"), + } + return _mapping_table(values) + + +def _sensitivity_table(bundle: RunBundle) -> str: + if not bundle.execution_sensitivity: + return "No execution-sensitivity rows were serialized." + columns = ( + "order_type", + "size_multiplier", + "net_pnl", + "net_edge_bps", + "fill_ratio", + "turnover_notional", + "maximum_drawdown", + ) + lines = [ + "| " + " | ".join(columns) + " |", + "| " + " | ".join("---" for _ in columns) + " |", + ] + for row in bundle.execution_sensitivity: + lines.append("| " + " | ".join(_display(row.get(column)) for column in columns) + " |") + return "\n".join(lines) + + +def _research_question(bundle: RunBundle) -> str: + research = bundle.manifest.get("research") + if isinstance(research, Mapping): + question = research.get("question") + if isinstance(question, str) and question.strip(): + return question.strip() + return _DEFAULT_RESEARCH_QUESTION + + +def _hypothesis_number(value: object) -> str: + if value is None or isinstance(value, bool): + return "N/A" + if isinstance(value, (int, float)): + return f"{float(value):.6f}" + return _display(value) + + +def _paired_hypothesis_section(bundle: RunBundle) -> str: + payload = bundle.hypothesis_evaluation + if not payload: + return "" + if payload.get("evidence_scope") == "trade_only_complete_predeclared_daily_archives": + return _m8_multidate_hypothesis_section(payload) + values = payload.get("per_symbol") + if not isinstance(values, list) or not values: + return ( + "## Paired H0/H1 diagnostic\n\n" + "The declared hypothesis artifact contains no per-symbol rows." + ) + + rows = [value for value in values if isinstance(value, Mapping)] + metric = payload.get("selection_metric") + if metric == "log_loss": + direction_text = ( + "For Δ log-loss (selected minus historical prior), a negative value favors the " + "selected model." + ) + else: + directions = sorted( + { + str(row.get("favorable_direction")) + for row in rows + if row.get("favorable_direction") is not None + } + ) + direction_text = ( + "The serialized favorable direction is " + + (", ".join(f"`{value}`" for value in directions) if directions else "N/A") + + "." + ) + + lines = [ + "## Paired H0/H1 diagnostic", + "", + ( + "The frozen comparison is validation-selected test predictions versus the " + "historical-prior baseline on identical `row_id` and fixed 2x-horizon blocks. " + + direction_text + ), + "", + ( + "| Symbol | Selected model | Baseline | Metric | Point Δ | Paired 95% interval | " + "Observations | Blocks | Samples | Seed | Status |" + ), + "| --- | --- | --- | --- | ---: | --- | ---: | ---: | ---: | ---: | --- |", + ] + for row in rows: + interval = ( + f"[{_hypothesis_number(row.get('ci_low'))}, {_hypothesis_number(row.get('ci_high'))}]" + ) + cells = ( + row.get("symbol"), + row.get("selected_model"), + row.get("baseline"), + row.get("metric"), + _hypothesis_number(row.get("point_delta")), + interval, + row.get("n_obs"), + row.get("n_blocks"), + row.get("samples"), + row.get("seed"), + row.get("status"), + ) + lines.append("| " + " | ".join(_display(cell) for cell in cells) + " |") + + caveat = payload.get("caveat") + cross = payload.get("cross_instrument_conclusion") + cross_text: object = None + if isinstance(cross, Mapping): + cross_text = cross.get("text") + if not isinstance(cross_text, str) or not cross_text.strip(): + cross_text = ( + "No cross-instrument estimate was pooled. Mixed directions cannot support " + "persistent alpha; even matching directions remain sample-specific." + ) + lines.extend( + [ + "", + ( + "These paired percentile intervals are dependence diagnostics, not p-values " + "or confirmatory significance intervals; H0 is not rejected by this " + "exploratory design." + ), + _display(caveat) if isinstance(caveat, str) and caveat.strip() else "", + "", + ( + "No cross-instrument estimate was pooled. Mixed directions, if present, " + "cannot support persistent alpha; even matching directions would remain " + "bounded, sample-specific diagnostics." + ), + _display(cross_text), + ] + ) + return "\n".join(lines) + + +def _m8_multidate_hypothesis_section(payload: Mapping[str, Any]) -> str: + """Render the frozen M8 component dates and equal-date endpoint verbatim.""" + + raw_dates = payload.get("per_date") + raw_symbols = payload.get("per_symbol") + date_rows = ( + [row for row in raw_dates if isinstance(row, Mapping)] + if isinstance(raw_dates, list) + else [] + ) + symbol_rows = ( + [row for row in raw_symbols if isinstance(row, Mapping)] + if isinstance(raw_symbols, list) + else [] + ) + lines = [ + "## M8 predeclared multi-date endpoint", + "", + ( + "`FULL_DATA` here means only that every byte of all eight predeclared " + "Binance daily aggregate-trade archives was verified and included. This is a " + "trade-only study; it does not mean full market observability, order-book " + "evidence, execution evidence, or deployable performance." + ), + "", + "### Untouched-date components", + "", + ( + "| Symbol | UTC date | Frozen role | Locked model | Baseline | Selected log loss | " + "Prior log loss | Point Δ | Paired 95% interval | N | Blocks | Status |" + ), + "| --- | --- | --- | --- | --- | ---: | ---: | ---: | --- | ---: | ---: | --- |", + ] + for row in sorted( + date_rows, + key=lambda value: (str(value.get("symbol", "")), str(value.get("study_date", ""))), + ): + interval = ( + f"[{_hypothesis_number(row.get('ci_low'))}, {_hypothesis_number(row.get('ci_high'))}]" + ) + date_cells = ( + row.get("symbol"), + row.get("study_date"), + row.get("study_role"), + row.get("selected_model"), + row.get("baseline"), + _hypothesis_number(row.get("selected_log_loss")), + _hypothesis_number(row.get("prior_log_loss")), + _hypothesis_number(row.get("point_delta")), + interval, + row.get("n_obs"), + row.get("n_blocks"), + row.get("bootstrap_status"), + ) + lines.append("| " + " | ".join(_display(cell) for cell in date_cells) + " |") + if not date_rows: + lines.append( + "| N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | missing |" + ) + + lines.extend( + [ + "", + "### Equal-date-weighted endpoint", + "", + ( + "| Symbol | Locked model | Baseline | Point Δ | Paired 95% interval | " + "Dates | N | Blocks | Status | Replication status |" + ), + "| --- | --- | --- | ---: | --- | ---: | ---: | ---: | --- | --- |", + ] + ) + for row in sorted(symbol_rows, key=lambda value: str(value.get("symbol", ""))): + interval = ( + f"[{_hypothesis_number(row.get('ci_low'))}, {_hypothesis_number(row.get('ci_high'))}]" + ) + aggregate_cells = ( + row.get("symbol"), + row.get("selected_model"), + row.get("baseline"), + _hypothesis_number(row.get("point_delta")), + interval, + row.get("n_dates"), + row.get("n_obs"), + row.get("n_blocks"), + row.get("status"), + row.get("replication_status"), + ) + lines.append("| " + " | ".join(_display(cell) for cell in aggregate_cells) + " |") + if not symbol_rows: + lines.append("| N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | insufficient_data | N/A |") + + direction_rows = [row for row in symbol_rows if "validation_primary_replication_status" in row] + if direction_rows: + lines.extend( + [ + "", + "### Validation → primary → replication direction consistency", + "", + ( + "| Symbol | Validation date | Validation Δ | Primary date | Primary Δ | " + "Replication date | Replication Δ | Same direction | All favorable | Status |" + ), + "| --- | --- | ---: | --- | ---: | --- | ---: | --- | --- | --- |", + ] + ) + for row in sorted(direction_rows, key=lambda value: str(value.get("symbol", ""))): + direction_cells = ( + row.get("symbol"), + row.get("validation_date"), + _hypothesis_number(row.get("validation_point_delta")), + row.get("primary_date"), + _hypothesis_number(row.get("primary_point_delta")), + row.get("replication_date"), + _hypothesis_number(row.get("replication_point_delta")), + row.get("direction_consistent_across_validation_primary_replication"), + row.get("favorable_across_validation_primary_replication"), + row.get("validation_primary_replication_status"), + ) + lines.append("| " + " | ".join(_display(cell) for cell in direction_cells) + " |") + + caveat = payload.get("caveat") + cross = payload.get("cross_instrument_conclusion") + cross_text = cross.get("text") if isinstance(cross, Mapping) else None + lines.extend( + [ + "", + ( + "Negative Δ log loss favors the locked selected model. The two date rows " + "are mandatory components of each equal-date estimate; neither date nor " + "instrument is omitted because of its direction." + ), + ( + _display(caveat) + if isinstance(caveat, str) and caveat.strip() + else ( + "Intervals are descriptive paired block-bootstrap diagnostics. No " + "p-value, H0 rejection, or significance claim is authorized." + ) + ), + ( + _display(cross_text) + if isinstance(cross_text, str) and cross_text.strip() + else "No cross-instrument estimate or persistent-alpha conclusion is inferred." + ), + "No execution, P&L, capacity, or profitability claim is authorized.", + ] + ) + return "\n".join(lines) + + +def _symbol_coverage_table(bundle: RunBundle) -> str: + coverage = bundle.data.get("symbol_coverage") + if not isinstance(coverage, list): + return "" + + columns = ( + "Symbol", + "Rows", + "Observed start (UTC)", + "Observed end (UTC, inclusive)", + "Requested range complete", + ) + lines = [ + "### Per-symbol observed coverage", + "", + "| " + " | ".join(columns) + " |", + "| " + " | ".join("---" for _ in columns) + " |", + ] + for item in coverage: + if isinstance(item, Mapping): + observed_end = item.get("observed_end_inclusive_utc", item.get("observed_end_utc")) + complete = item.get("complete_range", item.get("complete")) + values = ( + item.get("symbol"), + item.get("rows"), + item.get("observed_start_utc"), + observed_end, + complete, + ) + else: + values = (item, None, None, None, None) + lines.append("| " + " | ".join(_display(value) for value in values) + " |") + if not coverage: + lines.append("| N/A | N/A | N/A | N/A | N/A |") + return "\n".join(lines) + + +def _date_coverage_table(bundle: RunBundle) -> str: + coverage = bundle.data.get("date_coverage") + if not isinstance(coverage, list): + return "" + lines = [ + "### Per-date observed coverage", + "", + ( + "| Symbol | UTC date | Frozen role | Rows | Observed start (UTC) | " + "Observed end (UTC, inclusive) | Complete | DQ errors | DQ warnings |" + ), + "| --- | --- | --- | ---: | --- | --- | --- | ---: | ---: |", + ] + for item in coverage: + if not isinstance(item, Mapping): + continue + cells = ( + item.get("symbol"), + item.get("date"), + item.get("role"), + item.get("rows"), + item.get("observed_start_utc"), + item.get("observed_end_inclusive_utc"), + item.get("complete"), + item.get("quality_errors"), + item.get("quality_warnings"), + ) + lines.append("| " + " | ".join(_display(cell) for cell in cells) + " |") + if len(lines) == 3: + lines.append("| N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A | N/A |") + return "\n".join(lines) + + +def _execution_not_run(assumptions: Mapping[str, Any]) -> bool: + return assumptions.get("status") == "NOT_RUN" + + +def _execution_not_run_reason(assumptions: Mapping[str, Any]) -> str: + reason = assumptions.get("reason") + if isinstance(reason, str) and reason.strip(): + return reason.strip() + return "No reason was serialized." + + +def _executive_summary(bundle: RunBundle) -> str: + row_count = len(comparison_rows(bundle)) + if bundle.evidence_tier == "SYNTHETIC_SMOKE": + return ( + "This run is an offline software smoke test. Its serialized values may be useful " + "for checking data flow, metric accounting, and presentation, but they do not " + "measure a market relationship, tradable edge, or statistical significance. " + f"The bundle contains {row_count} held-out comparison row(s)." + ) + if bundle.evidence_tier == "PUBLIC_SAMPLE_PARTIAL": + return ( + "This is a bounded public-data sample, not a full empirical study. The table " + "reports serialized held-out diagnostics without extrapolating beyond the stated " + f"UTC interval. The bundle contains {row_count} comparison row(s)." + ) + research = bundle.manifest.get("research") + trade_only = isinstance(research, Mapping) and research.get("scope") == "trade_only" + if trade_only: + return ( + "This full-data label is narrowly scoped to every byte of the predeclared " + "trade archives, not to full market observability. The run is exchange-specific " + "and contains no order-book, execution, P&L, capacity, or profitability evidence. " + f"The bundle contains {row_count} held-out comparison row(s)." + ) + return ( + "This bundle is labeled as a full-data research run. Results remain simulated, " + "exchange-specific, and conditional on the recorded execution assumptions. " + f"The bundle contains {row_count} held-out comparison row(s)." + ) + + +def render_technical_report(bundle: RunBundle) -> str: + """Render a deterministic technical report without calculating new statistics.""" + model_table = render_model_comparison(bundle).rstrip() + hypothesis_section = _paired_hypothesis_section(bundle) + hypothesis_text = f"\n\n{hypothesis_section}" if hypothesis_section else "" + quality = _mapping_table(bundle.quality) + coverage_table = _symbol_coverage_table(bundle) + date_coverage_table = _date_coverage_table(bundle) + coverage_sections = [value for value in (coverage_table, date_coverage_table) if value] + coverage_text = "\n\n" + "\n\n".join(coverage_sections) + "\n\n" if coverage_sections else " " + execution_assumptions = bundle.manifest.get("execution_assumptions", {}) + if not isinstance(execution_assumptions, Mapping): + execution_assumptions = {"serialized_value": execution_assumptions} + execution_text = _mapping_table(execution_assumptions) + if _execution_not_run(execution_assumptions): + exclusion_reason = _display(_execution_not_run_reason(execution_assumptions)) + model_execution_text = ( + "Only predictive diagnostics are serialized for this run. Execution simulation, " + "fills, and P&L are absent by design, so predictive metrics cannot be interpreted " + "as executable or profitable performance." + ) + execution_scope_text = ( + "**Execution simulation and P&L were not run for this bundle.** " + f"Reason: {exclusion_reason}\n\n" + "No fill, fee, slippage, latency, queue, inventory, liquidation, capacity, " + "turnover, or profitability result is available from this run." + ) + sensitivity_text = ( + "Execution sensitivity was not run, and no scenario rows are available. " + f"Reason: {exclusion_reason}" + ) + economic_text = ( + "No capital recommendation is made by this renderer. This run contains no " + "execution simulation or P&L, so its predictive diagnostics provide no evidence " + "of fillability, net returns, deployable capacity, or profitability. Predictive " + "outputs remain bounded by the declared evidence tier and observed interval." + ) + execution_limitation = ( + "- Execution simulation and P&L were not run; no execution-performance or " + "profitability inference is available." + ) + else: + model_execution_text = ( + "Predictive metrics and execution results remain distinct serialized inputs. A\n" + "model metric does not establish that a fill was possible or that its signal\n" + "survives fees and latency." + ) + execution_scope_text = ( + "Any fill probability, queue position, partial-fill behavior, fee, slippage,\n" + "latency, inventory, liquidation, or capacity result is conditional on these\n" + "assumptions and on the observability of the source data." + ) + sensitivity_text = ( + f"{_sensitivity_table(bundle)}\n\n" + "This scenario grid changes declared execution size assumptions only. It is not\n" + "an estimate of endogenous market impact or deployable capacity." + ) + economic_text = ( + "No capital recommendation is made by this renderer. Synthetic outputs have no\n" + "empirical interpretation. Public-sample outputs are interval-specific. Full-data\n" + "outputs still require robustness across instruments, regimes, costs, latency,\n" + "fill specifications, and alternative periods before an investment conclusion." + ) + execution_limitation = ( + "- Approximate fills and simulated P&L are not realized execution performance." + ) + return f"""# Technical report — {bundle.run_id} + +> **{bundle.watermark}** + +This document was rendered only from a checksum-verified frozen run bundle. It +does not retrain a model, recompute a statistic, or infer a missing value. + +## Run identity and provenance + +{_provenance_table(bundle)} + +## Executive summary + +{_executive_summary(bundle)} + +## Research question + +{_research_question(bundle)} + +## Data lineage and quality + +The report covers only `{bundle.observed_start_utc}` through +`{bundle.observed_end_utc}` in UTC for {", ".join(bundle.symbols)}. Data source and +mode are `{_display(bundle.data.get("source"))}` and +`{_display(bundle.data.get("mode"))}`.{coverage_text}The frozen quality summary is: + +{quality} + +Questionable observations are findings, not silently repaired inputs. Consult +the run's data manifests and transformation records before interpreting any row. + +## Temporal design and evaluation + +Feature observability, future-label boundaries, fold definitions, purging, and +embargo decisions belong to the serialized research artifacts. This reporting +layer does not reconstruct them. A model row is eligible for the comparison +table only when its serialized split is `test`, `final_test`, `holdout`, or +`held_out`; validation rows are not promoted as final evidence. + +## Model comparison + +{model_table}{hypothesis_text} + +{model_execution_text} + +## Execution assumptions + +{execution_text} + +{execution_scope_text} + +## Execution sensitivity + +{sensitivity_text} + +## Economic interpretation + +{economic_text} + +## Limitations + +- Exchange behavior and public data coverage may not generalize to other venues. +- Exchange event time does not prove local receipt or decision-time availability. +- Trade-only data cannot identify true queue position or cancellation dynamics. +{execution_limitation} +- Small or selected periods can exaggerate stability; multiple comparisons raise + false-discovery risk. +- Checksums establish artifact integrity, not economic validity. + +## Reproduction record + +Use the exact resolved configuration and input-manifest hashes shown above. The +Git dirty flag describes the code state at run time; `UNBORN` means that no commit +was available and therefore weakens code-level reproducibility. Verify +`checksums.sha256` before using the bundle. +""" + + +def render_executive_memo(bundle: RunBundle) -> str: + """Render a compact, explicitly two-page investment-committee-style memo.""" + evidence_note = _executive_summary(bundle) + comparison_count = len(comparison_rows(bundle)) + sensitivity_count = len(bundle.execution_sensitivity) + git = bundle.provenance.get("git", {}) + if not isinstance(git, Mapping): + git = {} + input_hashes = bundle.provenance.get("input_manifest_sha256", []) + hypothesis_section = _paired_hypothesis_section(bundle) + hypothesis_text = f"\n\n{hypothesis_section}" if hypothesis_section else "" + execution_assumptions = bundle.manifest.get("execution_assumptions", {}) + if not isinstance(execution_assumptions, Mapping): + execution_assumptions = {"serialized_value": execution_assumptions} + if _execution_not_run(execution_assumptions): + exclusion_reason = _display(_execution_not_run_reason(execution_assumptions)) + artifact_inventory = ( + f"It contains {comparison_count} held-out comparison row(s). Execution " + "simulation, fills, execution sensitivity, and P&L were not run. " + f"Reason: {exclusion_reason} No absent execution metric should be interpreted " + "as zero." + ) + decision_framing = ( + "**Decision framing.** This bundle can assess only the serialized predictive " + "diagnostics. It cannot assess fillability, fees, spread, latency, adverse " + "selection, inventory, capacity, net returns, or profitability because no " + "execution model or P&L calculation was run." + ) + material_risks = ( + "**Material risks.** Public exchange data may omit receipt-time information and " + "matching-engine state. Trade-only observations cannot reveal spread, depth, " + "cancellations, queue priority, or fillability. Clock gaps, sequence gaps, " + "regime concentration, and repeated model searches can create optimistic " + "predictive diagnostics." + ) + kill_criteria = ( + "**Kill criteria.** Stop escalation if the apparent effect disappears on the " + "untouched test period; changes sign across instruments or regimes without an " + "economic explanation; fails checksum, timing, or leakage controls; or depends " + "on repeated sample or model selection. Predictive diagnostics alone cannot " + "clear an execution or capital gate." + ) + next_evidence = ( + "**Next evidence requested.** Reproduce the same frozen configuration, then test " + "a predeclared adjacent period and both default instruments. Publish data-quality " + "exceptions, fold boundaries, calibration, and dependence-aware intervals. " + "Acquire appropriate quote or order-book data before any separate execution, " + "fill, cost, capacity, or P&L study. Record failed hypotheses as carefully as " + "favorable ones." + ) + else: + artifact_inventory = ( + f"It contains\n{comparison_count} held-out comparison row(s) and " + f"{sensitivity_count} execution-\nsensitivity scenario row(s). Those rows are " + "diagnostics, not a\nclaim that a signal is stable, executable, or profitable." + ) + decision_framing = ( + "**Decision framing.** Predictive quality, execution assumptions, and simulated\n" + "strategy outcomes must be assessed separately. A higher classification score is\n" + "not sufficient: the apparent edge must remain after fees, spread, latency,\n" + "partial fills, adverse selection, liquidation, and inventory constraints. Any\n" + "missing metric is reported as unavailable rather than zero." + ) + material_risks = ( + "**Material risks.** Public exchange data may omit receipt-time information and\n" + "matching-engine state. Trade-only observations cannot reveal true queue priority.\n" + "Clock gaps, sequence gaps, regime concentration, cost assumptions, and repeated\n" + "model searches can all create optimistic results. Simulated fills do not prove\n" + "capacity or operational executability." + ) + kill_criteria = ( + "**Kill criteria.** Stop escalation if the apparent effect disappears on the\n" + "untouched test period; changes sign across instruments or regimes without an\n" + "economic explanation; fails checksum, timing, or leakage controls; depends on an\n" + "implausibly favorable fee, latency, or fill assumption; or cannot beat the\n" + "declared baseline after costs with uncertainty reported." + ) + next_evidence = ( + "**Next evidence requested.** Reproduce the same frozen configuration, then test a\n" + "predeclared adjacent period and both default instruments. Publish data-quality\n" + "exceptions, fold boundaries, calibration, bootstrap intervals, gross-to-net\n" + "attribution, fill/latency sensitivity, turnover, inventory, and liquidation\n" + "effects. Record failed hypotheses as carefully as favorable ones." + ) + return f"""# Research review memo — {bundle.run_id} + +> **{bundle.watermark}** + +## Page 1 — Decision and evidence + +**Recommendation:** Continue research only; authorize no capital deployment and +no live-order connection on the basis of this run. + +**Evidence boundary.** {evidence_note} + +The observed interval is `{bundle.observed_start_utc}` through +`{bundle.observed_end_utc}` for {", ".join(bundle.symbols)}. The run records +configuration `{bundle.provenance.get("config_sha256")}`, input-manifest hashes +`{_display(input_hashes)}`, and Git commit `{_display(git.get("commit"))}` with +dirty flag `{_display(git.get("dirty"))}`. {artifact_inventory} + +{decision_framing}{hypothesis_text} + +**Current conclusion.** The defensible decision is to preserve the run as +reproducible evidence and use it to choose the next falsification test. It is not +to extrapolate beyond the recorded venue, instruments, UTC period, or evidence +tier. + +
+ +## Page 2 — Risks, kill criteria, and next work + +{material_risks} + +{kill_criteria} + +{next_evidence} + +**Governance.** Any later memo must retain the evidence banner, actual UTC data +period, configuration and input hashes, and Git state. A changed assumption is a +new run, not a revision of this one. Live trading remains outside project scope. +""" + + +@dataclass(frozen=True, slots=True) +class ReportPaths: + technical_report: Path + executive_memo: Path + model_comparison: Path + + +def render_model_comparison_report(bundle: RunBundle) -> str: + """Render the comparison table together with its frozen hypothesis evidence.""" + + content = render_model_comparison(bundle).rstrip() + hypothesis_section = _paired_hypothesis_section(bundle) + if hypothesis_section: + content += "\n\n" + hypothesis_section + return content + "\n" + + +def _atomic_write(path: Path, content: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary_name = tempfile.mkstemp( + dir=path.parent, + prefix=f".{path.name}.", + suffix=".tmp", + text=True, + ) + try: + with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as handle: + handle.write(content.rstrip() + "\n") + os.replace(temporary_name, path) + except BaseException: + Path(temporary_name).unlink(missing_ok=True) + raise + + +def write_report_set(bundle: RunBundle, output_dir: str | Path) -> ReportPaths: + """Atomically write a deterministic report set outside the frozen input bundle.""" + output = Path(output_dir).resolve() + if output == bundle.root or output.is_relative_to(bundle.root): + raise ValueError("report output cannot mutate the frozen input run bundle") + technical = output / "technical_report.md" + memo = output / "executive_memo.md" + comparison = output / "model_comparison.md" + _atomic_write(technical, render_technical_report(bundle)) + _atomic_write(memo, render_executive_memo(bundle)) + _atomic_write(comparison, render_model_comparison_report(bundle)) + return ReportPaths( + technical_report=technical, + executive_memo=memo, + model_comparison=comparison, + ) diff --git a/Microstructure/src/microstructure/reporting/tables.py b/Microstructure/src/microstructure/reporting/tables.py new file mode 100644 index 0000000000000000000000000000000000000000..1330ac77bda8114ac814446c614973b24f87ab83 --- /dev/null +++ b/Microstructure/src/microstructure/reporting/tables.py @@ -0,0 +1,210 @@ +"""Deterministic, presentation-only model comparison tables.""" + +from __future__ import annotations + +import math +from collections.abc import Mapping, Sequence +from typing import Any + +from microstructure.reporting.bundle import RunBundle + +_JOIN_KEYS = ("instrument", "model", "horizon_events", "split", "study_date") +_TEST_SPLITS = frozenset({"test", "final_test", "holdout", "held_out"}) + + +def _first(row: Mapping[str, Any], names: Sequence[str], default: Any = None) -> Any: + for name in names: + if name in row: + return row[name] + return default + + +def _canonical_row(row: Mapping[str, Any]) -> dict[str, Any]: + result = dict(row) + result["instrument"] = _first(row, ("instrument", "symbol"), "N/A") + result["model"] = _first(row, ("model", "model_name"), "N/A") + result["horizon_events"] = _first( + row, ("horizon_events", "label_horizon_events", "horizon"), "N/A" + ) + # Missing split provenance is not evidence that a row is held out. Keep the + # presentation layer fail-closed so an unsplit metric cannot be promoted to + # final-test evidence merely by being serialized. + result["split"] = str(_first(row, ("split", "evaluation_split"), "unknown")) + # A multi-date held-out study can legitimately emit the same model/split + # combination more than once. Preserve the declared study date in the + # presentation join so a replication period cannot overwrite the primary + # test period. Legacy single-period rows retain one explicit sentinel and + # therefore keep their previous join behaviour. + result["study_date"] = str(_first(row, ("study_date", "period_date", "date"), "N/A")) + result["n_obs"] = _first(row, ("n_obs", "observations", "sample_size")) + result["period_start_utc"] = _first(row, ("period_start_utc", "test_start_utc", "start_utc")) + result["period_end_utc"] = _first(row, ("period_end_utc", "test_end_utc", "end_utc")) + result["brier_score"] = _first(row, ("brier_score", "brier")) + result["expected_calibration_error"] = _first(row, ("expected_calibration_error", "ece")) + result["fees_bps"] = _first(row, ("fees_bps", "cost_bps", "costs_bps")) + result["max_drawdown"] = _first(row, ("max_drawdown", "max_drawdown_units")) + return result + + +def _join_key(row: Mapping[str, Any]) -> tuple[str, ...]: + return tuple(str(row.get(key, "N/A")) for key in _JOIN_KEYS) + + +def comparison_rows(bundle: RunBundle) -> tuple[Mapping[str, Any], ...]: + """Join predictive and execution results without recomputing any metric.""" + joined: dict[tuple[str, ...], dict[str, Any]] = {} + for source_row in bundle.predictive_metrics: + row = _canonical_row(source_row) + if row["split"].lower() not in _TEST_SPLITS: + continue + joined[_join_key(row)] = row + for source_row in bundle.execution_metrics: + row = _canonical_row(source_row) + if row["split"].lower() not in _TEST_SPLITS: + continue + key = _join_key(row) + if key in joined: + joined[key].update({name: value for name, value in row.items() if value is not None}) + else: + joined[key] = row + return tuple(joined[key] for key in sorted(joined)) + + +def _number(value: Any) -> float | None: + if value is None or isinstance(value, bool): + return None + try: + number = float(value) + except (TypeError, ValueError): + return None + return number if math.isfinite(number) else None + + +def _format_plain(value: Any) -> str: + if value is None or value == "": + return "N/A" + return str(value).replace("|", "\\|").replace("\n", " ") + + +def _format_integer(value: Any) -> str: + number = _number(value) + return f"{int(number):,}" if number is not None and number.is_integer() else "N/A" + + +def _format_estimate( + row: Mapping[str, Any], key: str, *, decimals: int, percent: bool = False +) -> str: + estimate = _number(row.get(key)) + if estimate is None: + return "N/A" + scale = 100.0 if percent else 1.0 + suffix = "%" if percent else "" + rendered = f"{estimate * scale:.{decimals}f}{suffix}" + lower = _number(row.get(f"{key}_ci_low")) + upper = _number(row.get(f"{key}_ci_high")) + if lower is not None and upper is not None: + rendered += f" [{lower * scale:.{decimals}f}, {upper * scale:.{decimals}f}]{suffix}" + return rendered + + +def _period(row: Mapping[str, Any]) -> str: + start = _format_plain(row.get("period_start_utc")) + end = _format_plain(row.get("period_end_utc")) + if start == "N/A" and end == "N/A": + return "N/A" + return f"{start} → {end}" + + +def render_model_comparison(bundle: RunBundle) -> str: + """Render a Markdown table from serialized held-out metrics only.""" + git = bundle.provenance.get("git", {}) + if not isinstance(git, Mapping): + git = {} + input_hashes = bundle.provenance.get("input_manifest_sha256", []) + input_hash_text = ( + ", ".join(str(value) for value in input_hashes) + if isinstance(input_hashes, Sequence) and not isinstance(input_hashes, str) + else _format_plain(input_hashes) + ) + lines = [ + f"> **{bundle.watermark}**", + "", + ( + f"Run `{bundle.run_id}`; observed UTC period " + f"`{bundle.observed_start_utc}` to `{bundle.observed_end_utc}`." + ), + "", + f"Configuration SHA-256: `{_format_plain(bundle.provenance.get('config_sha256'))}`.", + f"Input manifest SHA-256: `{input_hash_text or 'none'}`.", + ( + f"Git commit: `{_format_plain(git.get('commit'))}`; dirty at run time: " + f"`{str(git.get('dirty')).lower()}`." + ), + "", + ] + rows = comparison_rows(bundle) + if not rows: + lines.extend( + [ + "No held-out model-comparison rows were serialized in this run bundle.", + "", + ] + ) + return "\n".join(lines) + + headers = ( + "Instrument", + "Horizon", + "Model", + "Split", + "N", + "Test period (UTC)", + "ROC-AUC", + "PR-AUC", + "Log loss", + "Brier", + "ECE", + "Gross bps", + "Fees bps", + "Net bps", + "Fill rate", + "Turnover", + "Max drawdown", + "Selected on", + ) + lines.append("| " + " | ".join(headers) + " |") + lines.append("| " + " | ".join("---" for _ in headers) + " |") + for row in rows: + values = ( + _format_plain(row.get("instrument")), + _format_plain(row.get("horizon_events")), + _format_plain(row.get("model")), + _format_plain(row.get("split")), + _format_integer(row.get("n_obs")), + _period(row), + _format_estimate(row, "roc_auc", decimals=4), + _format_estimate(row, "pr_auc", decimals=4), + _format_estimate(row, "log_loss", decimals=4), + _format_estimate(row, "brier_score", decimals=4), + _format_estimate(row, "expected_calibration_error", decimals=4), + _format_estimate(row, "gross_bps", decimals=3), + _format_estimate(row, "fees_bps", decimals=3), + _format_estimate(row, "net_bps", decimals=3), + _format_estimate(row, "fill_rate", decimals=1, percent=True), + _format_estimate(row, "turnover", decimals=3), + _format_estimate(row, "max_drawdown", decimals=3), + _format_plain(row.get("selected_on")), + ) + lines.append("| " + " | ".join(values) + " |") + lines.extend( + [ + "", + ( + "`N/A` means the producer did not serialize a comparable metric; " + "it is never interpreted as zero. Confidence intervals, when supplied, " + "are shown in brackets." + ), + "", + ] + ) + return "\n".join(lines) diff --git a/Microstructure/src/microstructure/research/__init__.py b/Microstructure/src/microstructure/research/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..89f7f67281dcc5af80ceb61f796dad628e3ac891 --- /dev/null +++ b/Microstructure/src/microstructure/research/__init__.py @@ -0,0 +1,75 @@ +"""Leakage-safe research datasets, time splits, and transparent models.""" + +from microstructure.research.features import ( + ResearchDataError, + TemporalAudit, + TemporalLeakageError, + add_future_event_labels, + build_l1_trade_features, + build_research_features, + build_research_frame, + model_feature_columns, + validate_temporal_contract, +) +from microstructure.research.l2_analysis import ( + L2DescriptiveAnalysis, + build_l2_descriptive_analysis, +) +from microstructure.research.l2_multidate import ( + L2EndpointSpec, + L2ObservedInterval, + L2RegimeFit, + L2ResearchError, + apply_l2_regimes, + build_l2_endpoint_frames, + dependency_block_expression, + fit_l2_regime_thresholds, + l2_model_feature_columns, +) +from microstructure.research.models import ( + BootstrapResult, + ModelLadderResult, + block_bootstrap_metric, + classification_metrics, + evaluate_model_ladder, + paired_block_bootstrap_difference, +) +from microstructure.research.splits import ( + PurgedFold, + SplitError, + WalkForwardPlan, + expanding_walk_forward_splits, +) + +__all__ = [ + "BootstrapResult", + "L2DescriptiveAnalysis", + "L2EndpointSpec", + "L2ObservedInterval", + "L2RegimeFit", + "L2ResearchError", + "ModelLadderResult", + "PurgedFold", + "ResearchDataError", + "SplitError", + "TemporalAudit", + "TemporalLeakageError", + "WalkForwardPlan", + "add_future_event_labels", + "apply_l2_regimes", + "block_bootstrap_metric", + "build_l1_trade_features", + "build_l2_descriptive_analysis", + "build_l2_endpoint_frames", + "build_research_features", + "build_research_frame", + "classification_metrics", + "dependency_block_expression", + "evaluate_model_ladder", + "expanding_walk_forward_splits", + "fit_l2_regime_thresholds", + "l2_model_feature_columns", + "model_feature_columns", + "paired_block_bootstrap_difference", + "validate_temporal_contract", +] diff --git a/Microstructure/src/microstructure/research/analysis.py b/Microstructure/src/microstructure/research/analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..f8986e07fd2d08a1ae97e8bae7a4933c5b0d7fdc --- /dev/null +++ b/Microstructure/src/microstructure/research/analysis.py @@ -0,0 +1,793 @@ +"""Reproducible descriptive market-microstructure diagnostics. + +No function in this module claims causal or tradable significance. Thresholds +used for large trades, shocks, recovery, and regimes are supplied explicitly by +the caller and are tagged as train-period inputs; they are never estimated from +the analyzed evaluation sample. +""" + +from __future__ import annotations + +import math +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from typing import cast + +import numpy as np +import polars as pl +from numpy.typing import NDArray + + +class DescriptiveAnalysisError(ValueError): + """Raised when a descriptive diagnostic lacks a valid input contract.""" + + +@dataclass(frozen=True, slots=True) +class HalfLifeResult: + """Correlation-decay curve and per-instrument descriptive half-life summary.""" + + curve: pl.DataFrame + summary: pl.DataFrame + + +@dataclass(frozen=True, slots=True) +class LiquidityShockThresholds: + """Externally fitted shock and recovery thresholds for one instrument.""" + + spread_shock_bps: float + depth_shock_max: float + spread_recovery_bps: float + depth_recovery_min: float + max_recovery_events: int + + def __post_init__(self) -> None: + values = ( + self.spread_shock_bps, + self.depth_shock_max, + self.spread_recovery_bps, + self.depth_recovery_min, + ) + if not all(math.isfinite(value) and value >= 0 for value in values): + raise DescriptiveAnalysisError("liquidity thresholds must be finite and nonnegative") + if self.max_recovery_events < 1: + raise DescriptiveAnalysisError("max_recovery_events must be positive") + + +@dataclass(frozen=True, slots=True) +class RegimeThresholds: + """Externally fitted volatility and liquidity regime boundaries.""" + + volatility_low: float + volatility_high: float + spread_tight_bps: float + spread_wide_bps: float + depth_low: float + depth_high: float + + def __post_init__(self) -> None: + values = ( + self.volatility_low, + self.volatility_high, + self.spread_tight_bps, + self.spread_wide_bps, + self.depth_low, + self.depth_high, + ) + if not all(math.isfinite(value) and value >= 0 for value in values): + raise DescriptiveAnalysisError("regime thresholds must be finite and nonnegative") + if self.volatility_low > self.volatility_high: + raise DescriptiveAnalysisError("volatility_low cannot exceed volatility_high") + if self.spread_tight_bps > self.spread_wide_bps: + raise DescriptiveAnalysisError("tight spread cannot exceed wide spread") + if self.depth_low > self.depth_high: + raise DescriptiveAnalysisError("low depth cannot exceed high depth") + + +def _require(frame: pl.DataFrame, columns: Sequence[str], table: str) -> None: + missing = sorted(set(columns).difference(frame.columns)) + if missing: + raise DescriptiveAnalysisError(f"{table} is missing required columns: {missing}") + if frame.is_empty(): + raise DescriptiveAnalysisError(f"{table} must not be empty") + + +def _finite_pair( + frame: pl.DataFrame, left: str, right: str +) -> tuple[NDArray[np.float64], NDArray[np.float64]]: + paired = frame.select(left, right).drop_nulls() + x = paired.get_column(left).to_numpy().astype(np.float64) + y = paired.get_column(right).to_numpy().astype(np.float64) + finite = np.isfinite(x) & np.isfinite(y) + return x[finite], y[finite] + + +def _pearson(x: NDArray[np.float64], y: NDArray[np.float64]) -> float: + if x.size < 2 or np.std(x) == 0 or np.std(y) == 0: + return math.nan + return float(np.corrcoef(x, y)[0, 1]) + + +def _average_rank(values: NDArray[np.float64]) -> NDArray[np.float64]: + order = np.argsort(values, kind="mergesort") + ranks = np.empty(values.size, dtype=np.float64) + start = 0 + while start < values.size: + end = start + 1 + while end < values.size and values[order[end]] == values[order[start]]: + end += 1 + ranks[order[start:end]] = (start + end - 1) / 2.0 + start = end + return ranks + + +def intraday_liquidity_summary( + frame: pl.DataFrame, + *, + timestamp_column: str = "decision_ts_ns", + bucket_minutes: int = 60, + utc_offset_minutes: int = 0, + spread_column: str = "spread_bps", + depth_column: str = "depth_total_l1", + imbalance_column: str = "queue_imbalance_l1", +) -> pl.DataFrame: + """Summarize liquidity by fixed minute-of-day buckets.""" + + _require( + frame, + ("symbol", timestamp_column, spread_column, depth_column, imbalance_column), + "intraday frame", + ) + if bucket_minutes < 1 or bucket_minutes > 1_440 or 1_440 % bucket_minutes: + raise DescriptiveAnalysisError("bucket_minutes must be a positive divisor of 1440") + minute_ns = 60_000_000_000 + prepared = frame.with_columns( + ( + ((pl.col(timestamp_column) // minute_ns + utc_offset_minutes) % 1_440) + // bucket_minutes + * bucket_minutes + ) + .cast(pl.Int32) + .alias("intraday_bucket_start_minute") + ) + result = ( + prepared.group_by("symbol", "intraday_bucket_start_minute") + .agg( + pl.len().alias("n_observations"), + pl.col(spread_column).mean().alias("mean_spread_bps"), + pl.col(spread_column).median().alias("median_spread_bps"), + pl.col(depth_column).mean().alias("mean_depth_l1"), + pl.col(depth_column).median().alias("median_depth_l1"), + pl.col(imbalance_column).mean().alias("mean_queue_imbalance_l1"), + ) + .with_columns( + ( + (pl.col("intraday_bucket_start_minute") // 60).cast(pl.String).str.pad_start(2, "0") + + pl.lit(":") + + (pl.col("intraday_bucket_start_minute") % 60) + .cast(pl.String) + .str.pad_start(2, "0") + ).alias("intraday_bucket_label"), + pl.lit(utc_offset_minutes, dtype=pl.Int32).alias("utc_offset_minutes"), + pl.lit("intraday_liquidity_descriptive").alias("analysis_kind"), + pl.lit(True).alias("descriptive_only"), + ) + .sort("symbol", "intraday_bucket_start_minute") + ) + return result + + +def ofi_future_return_association( + frame: pl.DataFrame, + *, + horizon_return_columns: Mapping[int, str], + ofi_column: str = "ofi_l1", + min_observations: int = 3, +) -> pl.DataFrame: + """Report descriptive OFI/return slopes and rank/linear correlations.""" + + if not horizon_return_columns or any(horizon <= 0 for horizon in horizon_return_columns): + raise DescriptiveAnalysisError("supplied event horizons must be positive") + _require(frame, ("symbol", ofi_column, *horizon_return_columns.values()), "OFI frame") + if min_observations < 2: + raise DescriptiveAnalysisError("min_observations must be at least two") + + rows: list[dict[str, object]] = [] + for symbol_frame in frame.partition_by("symbol", maintain_order=True): + symbol = str(symbol_frame.get_column("symbol")[0]) + for horizon, return_column in sorted(horizon_return_columns.items()): + x, y = _finite_pair(symbol_frame, ofi_column, return_column) + enough = x.size >= min_observations + variance = float(np.var(x)) if x.size else math.nan + slope = ( + float(np.mean((x - x.mean()) * (y - y.mean())) / variance) + if enough and variance > 0 + else math.nan + ) + intercept = float(y.mean() - slope * x.mean()) if math.isfinite(slope) else math.nan + rows.append( + { + "symbol": symbol, + "horizon_events": horizon, + "ofi_column": ofi_column, + "return_column": return_column, + "n_observations": int(x.size), + "pearson_correlation": _pearson(x, y) if enough else math.nan, + "spearman_correlation": ( + _pearson(_average_rank(x), _average_rank(y)) if enough else math.nan + ), + "ols_slope_return_per_ofi_unit": slope, + "ols_intercept": intercept, + "mean_future_return": float(y.mean()) if y.size else math.nan, + "analysis_status": "ok" if enough else "insufficient_observations", + "analysis_kind": "ofi_future_return_descriptive_association", + "descriptive_only": True, + } + ) + return pl.DataFrame(rows).sort("symbol", "horizon_events") + + +def estimate_signal_half_life( + association_curve: pl.DataFrame, + *, + correlation_column: str = "pearson_correlation", +) -> HalfLifeResult: + """Estimate correlation half-life from a caller-supplied horizon curve.""" + + _require( + association_curve, + ("symbol", "horizon_events", correlation_column, "n_observations"), + "association curve", + ) + curve = association_curve.with_columns( + pl.col(correlation_column).abs().alias("absolute_correlation") + ).sort("symbol", "horizon_events") + curve_rows: list[dict[str, object]] = [] + summaries: list[dict[str, object]] = [] + for symbol_curve in curve.partition_by("symbol", maintain_order=True): + symbol = str(symbol_curve.get_column("symbol")[0]) + horizons = symbol_curve.get_column("horizon_events").to_numpy().astype(np.float64) + correlations = symbol_curve.get_column("absolute_correlation").to_numpy().astype(np.float64) + finite = np.isfinite(horizons) & np.isfinite(correlations) + horizons = horizons[finite] + correlations = correlations[finite] + if not correlations.size: + for row in symbol_curve.iter_rows(named=True): + curve_rows.append( + { + **row, + "normalized_absolute_correlation": None, + "half_correlation_threshold": None, + "analysis_kind": "signal_decay_curve_descriptive", + "descriptive_only": True, + } + ) + summaries.append( + { + "symbol": symbol, + "reference_horizon_events": None, + "reference_absolute_correlation": None, + "half_correlation_threshold": None, + "first_crossing_half_life_events": None, + "exponential_half_life_events": None, + "analysis_status": "no_finite_correlations", + "analysis_kind": "signal_half_life_descriptive", + "descriptive_only": True, + } + ) + continue + reference = float(correlations[0]) + half_threshold = reference / 2.0 + crossing = horizons[correlations <= half_threshold] + first_crossing = float(crossing[0]) if crossing.size else None + positive = correlations > 0 + exponential_half_life: float | None = None + if positive.sum() >= 2: + slope = float(np.polyfit(horizons[positive], np.log(correlations[positive]), 1)[0]) + if slope < 0: + exponential_half_life = math.log(2.0) / -slope + status = "ok" if reference > 0 else "zero_reference_correlation" + summaries.append( + { + "symbol": symbol, + "reference_horizon_events": int(horizons[0]), + "reference_absolute_correlation": reference, + "half_correlation_threshold": half_threshold, + "first_crossing_half_life_events": first_crossing, + "exponential_half_life_events": exponential_half_life, + "analysis_status": status, + "analysis_kind": "signal_half_life_descriptive", + "descriptive_only": True, + } + ) + for row in symbol_curve.iter_rows(named=True): + value = float(row["absolute_correlation"]) + curve_rows.append( + { + **row, + "normalized_absolute_correlation": ( + value / reference if reference > 0 and math.isfinite(value) else None + ), + "half_correlation_threshold": half_threshold, + "analysis_kind": "signal_decay_curve_descriptive", + "descriptive_only": True, + } + ) + return HalfLifeResult( + curve=pl.DataFrame(curve_rows).sort("symbol", "horizon_events"), + summary=pl.DataFrame(summaries).sort("symbol"), + ) + + +def large_trade_price_impact_summary( + frame: pl.DataFrame, + *, + impact_columns: Mapping[int, str], + train_quantity_thresholds: Mapping[str, float], + quantity_column: str = "quantity", +) -> pl.DataFrame: + """Compare impact above/below externally supplied train-period size cutoffs.""" + + if not impact_columns or any(horizon <= 0 for horizon in impact_columns): + raise DescriptiveAnalysisError("impact horizons must be positive") + _require(frame, ("symbol", quantity_column, *impact_columns.values()), "trade-impact frame") + symbols = {str(value) for value in frame.get_column("symbol").unique()} + missing = sorted(symbols.difference(train_quantity_thresholds)) + if missing: + raise DescriptiveAnalysisError(f"missing train-period quantity thresholds: {missing}") + if any( + not math.isfinite(train_quantity_thresholds[symbol]) + or train_quantity_thresholds[symbol] <= 0 + for symbol in symbols + ): + raise DescriptiveAnalysisError("large-trade thresholds must be finite and positive") + + rows: list[dict[str, object]] = [] + for symbol_frame in frame.partition_by("symbol", maintain_order=True): + symbol = str(symbol_frame.get_column("symbol")[0]) + threshold = train_quantity_thresholds[symbol] + for horizon, impact_column in sorted(impact_columns.items()): + for is_large in (False, True): + subset = ( + symbol_frame.filter((pl.col(quantity_column) >= threshold) == is_large) + .select(impact_column) + .drop_nulls() + ) + values = subset.get_column(impact_column).to_numpy().astype(np.float64) + values = values[np.isfinite(values)] + rows.append( + { + "symbol": symbol, + "horizon_events": horizon, + "impact_column": impact_column, + "large_trade": is_large, + "train_quantity_threshold": threshold, + "n_observations": int(values.size), + "mean_signed_impact_bps": ( + float(values.mean()) if values.size else math.nan + ), + "median_signed_impact_bps": ( + float(np.median(values)) if values.size else math.nan + ), + "mean_absolute_impact_bps": ( + float(np.abs(values).mean()) if values.size else math.nan + ), + "threshold_source": "caller_supplied_train_period", + "analysis_kind": "large_trade_price_impact_descriptive", + "descriptive_only": True, + } + ) + return pl.DataFrame(rows).sort("symbol", "horizon_events", "large_trade") + + +def liquidity_recovery_summary( + frame: pl.DataFrame, + *, + train_thresholds: Mapping[str, LiquidityShockThresholds], + spread_column: str = "spread_bps", + depth_column: str = "depth_total_l1", + time_column: str = "decision_ts_ns", + sequence_column: str = "decision_sequence", +) -> pl.DataFrame: + """Track nonoverlapping recovery episodes after threshold-defined shocks.""" + + _require( + frame, + ("symbol", "continuity_id", spread_column, depth_column, time_column, sequence_column), + "liquidity-recovery frame", + ) + symbols = {str(value) for value in frame.get_column("symbol").unique()} + missing = sorted(symbols.difference(train_thresholds)) + if missing: + raise DescriptiveAnalysisError(f"missing train-period liquidity thresholds: {missing}") + + episodes: list[dict[str, object]] = [] + for segment in frame.sort(["symbol", "continuity_id", sequence_column]).partition_by( + ["symbol", "continuity_id"], maintain_order=True + ): + symbol = str(segment.get_column("symbol")[0]) + continuity_id = str(segment.get_column("continuity_id")[0]) + threshold = train_thresholds[symbol] + rows = list(segment.iter_rows(named=True)) + index = 0 + while index < len(rows): + row = rows[index] + spread = cast(float, row[spread_column]) + depth = cast(float, row[depth_column]) + spread_shock = spread >= threshold.spread_shock_bps + depth_shock = depth <= threshold.depth_shock_max + if not (spread_shock or depth_shock): + index += 1 + continue + search_end = min(len(rows) - 1, index + threshold.max_recovery_events) + recovery_index: int | None = None + for candidate_index in range(index + 1, search_end + 1): + candidate = rows[candidate_index] + if ( + cast(float, candidate[spread_column]) <= threshold.spread_recovery_bps + and cast(float, candidate[depth_column]) >= threshold.depth_recovery_min + ): + recovery_index = candidate_index + break + full_horizon_observed = index + threshold.max_recovery_events < len(rows) + right_censored = recovery_index is None and not full_horizon_observed + information_end_index = ( + recovery_index + if recovery_index is not None + else index + threshold.max_recovery_events + if full_horizon_observed + else None + ) + shock_ts = cast(int, row[time_column]) + recovery_row = rows[recovery_index] if recovery_index is not None else None + episodes.append( + { + "symbol": symbol, + "continuity_id": continuity_id, + "shock_ts_ns": shock_ts, + "shock_sequence": cast(int, row[sequence_column]), + "shock_spread_bps": spread, + "shock_depth_l1": depth, + "spread_shock": spread_shock, + "depth_shock": depth_shock, + "recovered": None if right_censored else recovery_index is not None, + "recovery_events": ( + recovery_index - index if recovery_index is not None else None + ), + "recovery_time_ns": ( + cast(int, recovery_row[time_column]) - shock_ts + if recovery_row is not None + else None + ), + "recovery_ts_ns": ( + cast(int, recovery_row[time_column]) if recovery_row is not None else None + ), + "recovery_right_censored": right_censored, + "recovery_censor_reason": ( + "segment_ends_before_max_horizon" if right_censored else None + ), + "recovery_information_end_ts_ns": ( + cast(int, rows[information_end_index][time_column]) + if information_end_index is not None + else None + ), + "spread_shock_threshold_bps": threshold.spread_shock_bps, + "depth_shock_threshold_max": threshold.depth_shock_max, + "spread_recovery_threshold_bps": threshold.spread_recovery_bps, + "depth_recovery_threshold_min": threshold.depth_recovery_min, + "max_recovery_events": threshold.max_recovery_events, + "threshold_source": "caller_supplied_train_period", + "analysis_kind": "liquidity_recovery_descriptive", + "descriptive_only": True, + } + ) + index = (recovery_index + 1) if recovery_index is not None else search_end + 1 + if not episodes: + return pl.DataFrame( + schema={ + "symbol": pl.String, + "continuity_id": pl.String, + "shock_ts_ns": pl.Int64, + "analysis_kind": pl.String, + "descriptive_only": pl.Boolean, + } + ) + return pl.DataFrame(episodes, infer_schema_length=None).sort("symbol", "shock_ts_ns") + + +def assign_market_regimes( + frame: pl.DataFrame, + *, + train_thresholds: Mapping[str, RegimeThresholds], + volatility_column: str, + spread_column: str = "spread_bps", + depth_column: str = "depth_total_l1", +) -> pl.DataFrame: + """Assign regimes using only explicit instrument-specific train thresholds.""" + + _require( + frame, + ("symbol", volatility_column, spread_column, depth_column), + "market-regime frame", + ) + symbols = {str(value) for value in frame.get_column("symbol").unique()} + missing = sorted(symbols.difference(train_thresholds)) + if missing: + raise DescriptiveAnalysisError(f"missing train-period regime thresholds: {missing}") + outputs: list[pl.DataFrame] = [] + for symbol_frame in frame.partition_by("symbol", maintain_order=True): + symbol = str(symbol_frame.get_column("symbol")[0]) + threshold = train_thresholds[symbol] + outputs.append( + symbol_frame.with_columns( + pl.when(pl.col(volatility_column) <= threshold.volatility_low) + .then(pl.lit("low")) + .when(pl.col(volatility_column) >= threshold.volatility_high) + .then(pl.lit("high")) + .otherwise(pl.lit("medium")) + .alias("volatility_regime"), + pl.when( + (pl.col(spread_column) >= threshold.spread_wide_bps) + | (pl.col(depth_column) <= threshold.depth_low) + ) + .then(pl.lit("stressed")) + .when( + (pl.col(spread_column) <= threshold.spread_tight_bps) + & (pl.col(depth_column) >= threshold.depth_high) + ) + .then(pl.lit("liquid")) + .otherwise(pl.lit("normal")) + .alias("liquidity_regime"), + pl.lit(threshold.volatility_low).alias("train_volatility_low"), + pl.lit(threshold.volatility_high).alias("train_volatility_high"), + pl.lit(threshold.spread_tight_bps).alias("train_spread_tight_bps"), + pl.lit(threshold.spread_wide_bps).alias("train_spread_wide_bps"), + pl.lit(threshold.depth_low).alias("train_depth_low"), + pl.lit(threshold.depth_high).alias("train_depth_high"), + ).with_columns( + (pl.col("volatility_regime") + pl.lit("__") + pl.col("liquidity_regime")).alias( + "joint_market_regime" + ), + pl.lit("caller_supplied_train_period").alias("regime_threshold_source"), + pl.lit("volatility_liquidity_regime_descriptive").alias("analysis_kind"), + pl.lit(True).alias("descriptive_only"), + ) + ) + return pl.concat(outputs, how="vertical_relaxed") + + +def regime_outcome_summary( + regime_frame: pl.DataFrame, + *, + outcome_columns: Sequence[str], +) -> pl.DataFrame: + """Summarize supplied outcomes without using them to define regimes.""" + + _require( + regime_frame, + ("symbol", "volatility_regime", "liquidity_regime", *outcome_columns), + "regime outcomes", + ) + expressions: list[pl.Expr] = [pl.len().alias("n_observations")] + for column in outcome_columns: + expressions.extend( + [ + pl.col(column).mean().alias(f"mean__{column}"), + pl.col(column).median().alias(f"median__{column}"), + ] + ) + return ( + regime_frame.group_by("symbol", "volatility_regime", "liquidity_regime") + .agg(expressions) + .with_columns( + pl.lit("regime_outcomes_descriptive").alias("analysis_kind"), + pl.lit(True).alias("descriptive_only"), + ) + .sort("symbol", "volatility_regime", "liquidity_regime") + ) + + +def cross_instrument_stability_summary( + effects: pl.DataFrame, + *, + value_column: str, + comparison_columns: Sequence[str] = ("horizon_events",), + instrument_column: str = "symbol", +) -> pl.DataFrame: + """Summarize effect direction and dispersion across instruments.""" + + _require(effects, (instrument_column, value_column, *comparison_columns), "effects") + rows: list[dict[str, object]] = [] + partitions = ( + effects.partition_by(list(comparison_columns), maintain_order=True) + if comparison_columns + else [effects] + ) + for partition in partitions: + by_instrument = partition.group_by(instrument_column).agg( + pl.col(value_column).mean().alias("_instrument_effect") + ) + values = ( + by_instrument.get_column("_instrument_effect") + .drop_nulls() + .to_numpy() + .astype(np.float64) + ) + values = values[np.isfinite(values)] + nonzero = values[values != 0] + sign_agreement = ( + max(float((nonzero > 0).mean()), float((nonzero < 0).mean())) + if nonzero.size + else math.nan + ) + row: dict[str, object] = { + column: partition.get_column(column)[0] for column in comparison_columns + } + row.update( + { + "value_column": value_column, + "n_instruments": int(values.size), + "mean_effect": float(values.mean()) if values.size else math.nan, + "median_effect": float(np.median(values)) if values.size else math.nan, + "effect_std": float(values.std(ddof=0)) if values.size else math.nan, + "minimum_effect": float(values.min()) if values.size else math.nan, + "maximum_effect": float(values.max()) if values.size else math.nan, + "sign_agreement_fraction": sign_agreement, + "analysis_kind": "cross_instrument_stability_descriptive", + "descriptive_only": True, + } + ) + rows.append(row) + return ( + pl.DataFrame(rows).sort(list(comparison_columns)) + if comparison_columns + else pl.DataFrame(rows) + ) + + +def _population_stability_index( + reference: NDArray[np.float64], + comparison: NDArray[np.float64], + *, + bins: int, + reference_missing: int, + comparison_missing: int, +) -> float: + quantiles = np.linspace(0.0, 1.0, bins + 1) + internal = ( + np.unique(np.quantile(reference, quantiles)[1:-1]) if reference.size else np.array([]) + ) + edges = np.concatenate(([-np.inf], internal, [np.inf])) + reference_counts = np.histogram(reference, bins=edges)[0].astype(np.float64) + comparison_counts = np.histogram(comparison, bins=edges)[0].astype(np.float64) + reference_counts = np.append(reference_counts, reference_missing) + comparison_counts = np.append(comparison_counts, comparison_missing) + epsilon = 1e-6 + reference_share = (reference_counts + epsilon) / ( + reference_counts.sum() + epsilon * reference_counts.size + ) + comparison_share = (comparison_counts + epsilon) / ( + comparison_counts.sum() + epsilon * comparison_counts.size + ) + return float( + np.sum((comparison_share - reference_share) * np.log(comparison_share / reference_share)) + ) + + +def _max_cdf_distance(reference: NDArray[np.float64], comparison: NDArray[np.float64]) -> float: + if not reference.size or not comparison.size: + return math.nan + points = np.sort(np.unique(np.concatenate((reference, comparison)))) + reference_cdf = np.searchsorted(np.sort(reference), points, side="right") / reference.size + comparison_cdf = np.searchsorted(np.sort(comparison), points, side="right") / comparison.size + return float(np.max(np.abs(reference_cdf - comparison_cdf))) + + +def feature_stability_summary( + reference: pl.DataFrame, + comparison: pl.DataFrame, + *, + feature_columns: Sequence[str], + group_columns: Sequence[str] = ("symbol",), + bins: int = 10, +) -> pl.DataFrame: + """Compare feature distributions using bins learned from reference only.""" + + if not feature_columns: + raise DescriptiveAnalysisError("feature_columns must not be empty") + if bins < 2: + raise DescriptiveAnalysisError("feature stability requires at least two bins") + _require(reference, (*group_columns, *feature_columns), "reference features") + _require(comparison, (*group_columns, *feature_columns), "comparison features") + + if group_columns: + reference_groups = reference.partition_by(list(group_columns), as_dict=True) + comparison_groups = comparison.partition_by(list(group_columns), as_dict=True) + missing_groups = sorted(set(reference_groups).difference(comparison_groups), key=str) + if missing_groups: + raise DescriptiveAnalysisError( + f"comparison is missing reference groups: {missing_groups}" + ) + else: + reference_groups = {(): reference} + comparison_groups = {(): comparison} + + rows: list[dict[str, object]] = [] + for key, reference_group in reference_groups.items(): + comparison_group = comparison_groups[key] + key_tuple = key if isinstance(key, tuple) else (key,) + group_values = dict(zip(group_columns, key_tuple, strict=True)) + for feature in feature_columns: + reference_series = reference_group.get_column(feature) + comparison_series = comparison_group.get_column(feature) + reference_values = reference_series.drop_nulls().to_numpy().astype(np.float64) + comparison_values = comparison_series.drop_nulls().to_numpy().astype(np.float64) + reference_values = reference_values[np.isfinite(reference_values)] + comparison_values = comparison_values[np.isfinite(comparison_values)] + reference_invalid = reference_group.height - reference_values.size + comparison_invalid = comparison_group.height - comparison_values.size + reference_mean = float(reference_values.mean()) if reference_values.size else math.nan + comparison_mean = ( + float(comparison_values.mean()) if comparison_values.size else math.nan + ) + reference_std = ( + float(reference_values.std(ddof=0)) if reference_values.size else math.nan + ) + comparison_std = ( + float(comparison_values.std(ddof=0)) if comparison_values.size else math.nan + ) + rows.append( + { + **group_values, + "feature": feature, + "reference_n": int(reference_group.height), + "comparison_n": int(comparison_group.height), + "reference_missing_rate": reference_invalid / reference_group.height, + "comparison_missing_rate": comparison_invalid / comparison_group.height, + "reference_mean": reference_mean, + "comparison_mean": comparison_mean, + "reference_std": reference_std, + "comparison_std": comparison_std, + "standardized_mean_shift": ( + (comparison_mean - reference_mean) / reference_std + if reference_std > 0 and math.isfinite(comparison_mean) + else None + ), + "variance_ratio": ( + (comparison_std**2) / (reference_std**2) + if reference_std > 0 and math.isfinite(comparison_std) + else None + ), + "population_stability_index": _population_stability_index( + reference_values, + comparison_values, + bins=bins, + reference_missing=reference_invalid, + comparison_missing=comparison_invalid, + ), + "max_empirical_cdf_distance": _max_cdf_distance( + reference_values, comparison_values + ), + "reference_constant": bool(reference_std == 0), + "bin_source": "reference_period_only", + "analysis_kind": "feature_stability_descriptive", + "descriptive_only": True, + } + ) + return pl.DataFrame(rows).sort([*group_columns, "feature"]) + + +__all__ = [ + "DescriptiveAnalysisError", + "HalfLifeResult", + "LiquidityShockThresholds", + "RegimeThresholds", + "assign_market_regimes", + "cross_instrument_stability_summary", + "estimate_signal_half_life", + "feature_stability_summary", + "intraday_liquidity_summary", + "large_trade_price_impact_summary", + "liquidity_recovery_summary", + "ofi_future_return_association", + "regime_outcome_summary", +] diff --git a/Microstructure/src/microstructure/research/features.py b/Microstructure/src/microstructure/research/features.py new file mode 100644 index 0000000000000000000000000000000000000000..b97bd9acf4b7c1fcb175c131c023e8314307869b --- /dev/null +++ b/Microstructure/src/microstructure/research/features.py @@ -0,0 +1,824 @@ +"""Leakage-safe L1 and trade-flow research features and labels. + +The normalized ``available_ts_ns`` column is the information-set clock. Book +observations at a decision are observable at that decision, while trades from a +separate archive stream are joined strictly before it unless a future adapter +can prove a shared ordering. Every rolling operation is scoped by +``continuity_id`` so sequence gaps cannot contaminate a new book segment. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +import polars as pl + +from microstructure.config import FeatureConfig + + +class ResearchDataError(ValueError): + """Raised when normalized inputs do not satisfy the research contract.""" + + +class TemporalLeakageError(ResearchDataError): + """Raised when feature lineage or label timing reaches beyond its cutoff.""" + + +@dataclass(frozen=True, slots=True) +class TemporalAudit: + """Summary returned after validating a supervised research frame.""" + + rows: int + labeled_rows: int + right_censored_rows: int + continuity_segments: int + + +BOOK_REQUIRED_COLUMNS = frozenset( + { + "symbol", + "event_ts_ns", + "available_ts_ns", + "continuity_id", + "sequence_end", + "is_valid", + "best_bid", + "best_ask", + "bid_quantity", + "ask_quantity", + } +) +TRADE_REQUIRED_COLUMNS = frozenset( + { + "symbol", + "trade_id", + "available_ts_ns", + "quantity", + "aggressor_side", + } +) + +_STATIC_MODEL_FEATURES = ( + "spread_bps", + "depth_total_l1", + "depth_total_l5", + "depth_total_l10", + "queue_imbalance_l1", + "queue_imbalance_l5", + "queue_imbalance_l10", + "microprice_deviation_bps", + "ofi_l1", + "log_mid_return_1", + "realized_price_impact_bps_1", + "spread_recovery_bps_1", + "depth_recovery_l1_1", +) +_MODEL_FEATURE_PREFIXES = ( + "cancellation_intensity_w", + "ofi_w", + "signed_trade_volume_w", + "trade_volume_w", + "trade_count_w", + "trade_intensity_w", + "realized_volatility_w", +) + +DEPTH_DELTA_REQUIRED_COLUMNS = frozenset( + { + "venue", + "symbol", + "event_ts_ns", + "available_ts_ns", + "continuity_id", + "first_update_id", + "last_update_id", + "bids", + "asks", + } +) + + +def _require_columns(frame: pl.DataFrame, required: frozenset[str], table: str) -> None: + missing = sorted(required.difference(frame.columns)) + if missing: + raise ResearchDataError(f"{table} is missing required columns: {missing}") + + +def _assert_normalized_books(books: pl.DataFrame) -> None: + _require_columns(books, BOOK_REQUIRED_COLUMNS, "book observations") + if books.is_empty(): + raise ResearchDataError("book observations must not be empty") + + invalid = books.filter( + (pl.col("available_ts_ns") < pl.col("event_ts_ns")) + | (pl.col("best_bid") <= 0) + | (pl.col("best_ask") <= 0) + | (pl.col("bid_quantity") < 0) + | (pl.col("ask_quantity") < 0) + | (pl.col("is_valid") & (pl.col("best_bid") >= pl.col("best_ask"))) + ) + if not invalid.is_empty(): + raise ResearchDataError( + "book observations contain impossible timing, price, quantity, or valid crossed-book rows" + ) + + duplicates = ( + books.group_by(["symbol", "continuity_id", "sequence_end"]).len().filter(pl.col("len") > 1) + ) + if not duplicates.is_empty(): + raise ResearchDataError("book sequence keys must be unique within each continuity segment") + + ordered = books.sort(["symbol", "continuity_id", "sequence_end"]) + backwards = ordered.filter( + pl.col("available_ts_ns") + < pl.col("available_ts_ns").shift(1).over(["symbol", "continuity_id"]) + ) + if not backwards.is_empty(): + raise ResearchDataError( + "available_ts_ns must be nondecreasing by sequence within each continuity segment" + ) + + +def _prepare_trades(trades: pl.DataFrame | None) -> pl.DataFrame | None: + if trades is None or trades.is_empty(): + return None + _require_columns(trades, TRADE_REQUIRED_COLUMNS, "trades") + invalid = trades.filter( + (pl.col("quantity") < 0) + | (~pl.col("aggressor_side").str.to_lowercase().is_in(["buy", "sell"])) + ) + if not invalid.is_empty(): + raise ResearchDataError("trades require nonnegative quantity and buy/sell aggressor_side") + + group = ["symbol", "continuity_id"] if "continuity_id" in trades.columns else ["symbol"] + identity_columns = ["symbol"] + if "continuity_id" in trades.columns: + identity_columns.append("continuity_id") + return ( + trades.sort([*group, "available_ts_ns", "trade_id"]) + .with_columns( + pl.when(pl.col("aggressor_side").str.to_lowercase() == "buy") + .then(1.0) + .otherwise(-1.0) + .alias("_trade_sign"), + ) + .with_columns( + (pl.col("quantity") * pl.col("_trade_sign")).alias("_signed_quantity"), + pl.col("quantity").alias("_absolute_quantity"), + pl.lit(1, dtype=pl.Int64).alias("_trade_observation"), + ) + .with_columns( + pl.col("_signed_quantity").cum_sum().over(group).alias("_cum_signed"), + pl.col("_absolute_quantity").cum_sum().over(group).alias("_cum_volume"), + pl.col("_trade_observation").cum_sum().over(group).alias("_cum_count"), + ) + .select( + *identity_columns, + pl.col("available_ts_ns").alias("trade_feature_max_source_ts_ns"), + "_cum_signed", + "_cum_volume", + "_cum_count", + ) + ) + + +def build_cancellation_intensity_features( + depth_deltas: pl.DataFrame, + *, + windows: tuple[int, ...] = (20, 100), +) -> pl.DataFrame: + """Build causal cancellation-intensity proxies from observable L2 deletes. + + Binance diff-depth encodes a zero quantity as removal of that price level. + Those deletes are directly observable; an update to a smaller nonzero + quantity is not classified here because its cancellation/execution split is + not identifiable from the delta alone. Windows are event-count windows, + include the current available delta, and reset at every continuity epoch. + """ + + _require_columns(depth_deltas, DEPTH_DELTA_REQUIRED_COLUMNS, "depth deltas") + if depth_deltas.is_empty(): + raise ResearchDataError("depth deltas must not be empty") + normalized_windows = tuple(sorted(set(windows))) + if not normalized_windows or any(isinstance(window, bool) or window < 1 for window in windows): + raise ResearchDataError("cancellation windows must be positive integers") + + group = ["venue", "symbol", "continuity_id"] + ordered = depth_deltas.sort([*group, "last_update_id", "first_update_id"]) + invalid = ordered.filter( + pl.col("continuity_id").is_null() + | (pl.col("available_ts_ns") < pl.col("event_ts_ns")) + | (pl.col("first_update_id") > pl.col("last_update_id")) + ) + if not invalid.is_empty(): + raise ResearchDataError( + "depth deltas require a continuity ID, observable availability, and valid ranges" + ) + duplicates = ( + ordered.group_by([*group, "first_update_id", "last_update_id"]) + .len() + .filter(pl.col("len") > 1) + ) + if not duplicates.is_empty(): + raise ResearchDataError("depth-delta sequence ranges must be unique within an epoch") + + prior_end = pl.col("last_update_id").shift(1).over(group) + prior_available = pl.col("available_ts_ns").shift(1).over(group) + broken = ordered.filter( + prior_end.is_not_null() + & ( + (pl.col("last_update_id") <= prior_end) + | (pl.col("first_update_id") > prior_end + 1) + | (pl.col("available_ts_ns") < prior_available) + ) + ) + if not broken.is_empty(): + raise ResearchDataError( + "depth deltas contain a stale/gapped sequence or reversing availability clock" + ) + + per_event = ordered.with_columns( + ( + pl.col("bids").list.eval(pl.element().struct.field("quantity_lots") == 0).list.sum() + + pl.col("asks").list.eval(pl.element().struct.field("quantity_lots") == 0).list.sum() + ) + .fill_null(0) + .cast(pl.Int64) + .alias("cancellation_deletes_current"), + (pl.col("bids").list.len() + pl.col("asks").list.len()) + .cast(pl.Int64) + .alias("depth_updates_current"), + pl.col("available_ts_ns").alias("decision_ts_ns"), + pl.col("available_ts_ns").alias("feature_cutoff_ts_ns"), + pl.col("available_ts_ns").alias("max_feature_source_ts_ns"), + pl.col("last_update_id").alias("decision_sequence"), + pl.col("last_update_id").alias("max_feature_source_sequence"), + pl.lit("zero_quantity_level_deletes_only").alias("cancellation_observation_policy"), + pl.lit(False).alias("nonzero_reduction_classified_as_cancellation"), + ) + expressions: list[pl.Expr] = [] + for window in normalized_windows: + deletes = ( + pl.col("cancellation_deletes_current") + .rolling_sum(window_size=window, min_samples=1) + .over(group) + ) + updates = ( + pl.col("depth_updates_current") + .rolling_sum(window_size=window, min_samples=1) + .over(group) + ) + expressions.extend( + [ + deletes.alias(f"cancellation_deletes_w{window}"), + updates.alias(f"depth_updates_w{window}"), + pl.when(updates > 0) + .then(deletes / updates) + .otherwise(0.0) + .cast(pl.Float64) + .alias(f"cancellation_intensity_w{window}"), + ] + ) + return per_event.with_columns(expressions).sort( + ["decision_ts_ns", "venue", "symbol", "continuity_id", "decision_sequence"] + ) + + +def _join_trade_history(books: pl.DataFrame, trades: pl.DataFrame | None) -> pl.DataFrame: + if trades is None: + return books.with_columns( + pl.lit(None, dtype=pl.Int64).alias("trade_feature_max_source_ts_ns"), + pl.lit(0.0).alias("_cum_signed"), + pl.lit(0.0).alias("_cum_volume"), + pl.lit(0, dtype=pl.Int64).alias("_cum_count"), + ) + + # Equal timestamps are deliberately excluded. Archive trade and book + # streams do not share a provable exchange-wide sequence. When trades carry + # segment provenance, both their cumulative state and join stay gap-local. + group = ["symbol", "continuity_id"] if "continuity_id" in trades.columns else ["symbol"] + joined = books.sort(["feature_cutoff_ts_ns", "symbol", "sequence_end"]).join_asof( + trades.sort(["trade_feature_max_source_ts_ns", *group]), + left_on="feature_cutoff_ts_ns", + right_on="trade_feature_max_source_ts_ns", + by=group, + strategy="backward", + allow_exact_matches=False, + check_sortedness=False, + ) + return joined.with_columns( + pl.col("_cum_signed").fill_null(0.0), + pl.col("_cum_volume").fill_null(0.0), + pl.col("_cum_count").fill_null(0), + ) + + +def _join_cancellation_history( + features: pl.DataFrame, + depth_deltas: pl.DataFrame | None, + config: FeatureConfig, +) -> pl.DataFrame: + if depth_deltas is None: + return features + if "venue" not in features.columns: + raise ResearchDataError( + "book observations require venue when cancellation features are requested" + ) + cancellation = build_cancellation_intensity_features( + depth_deltas, + windows=config.trade_windows, + ) + feature_columns = [ + name + for name in cancellation.columns + if name.startswith("cancellation_deletes_w") + or name.startswith("depth_updates_w") + or name.startswith("cancellation_intensity_w") + ] + keyed = cancellation.select( + "venue", + "symbol", + "continuity_id", + pl.col("decision_sequence").alias("sequence_end"), + pl.col("max_feature_source_ts_ns").alias("cancellation_feature_max_source_ts_ns"), + pl.col("max_feature_source_sequence").alias("cancellation_feature_max_source_sequence"), + "cancellation_observation_policy", + "nonzero_reduction_classified_as_cancellation", + *feature_columns, + ) + keys = ["venue", "symbol", "continuity_id", "sequence_end"] + joined = features.join(keyed, on=keys, how="left", validate="1:1") + missing = joined.filter(pl.col("cancellation_feature_max_source_ts_ns").is_null()) + if not missing.is_empty(): + raise ResearchDataError( + "supplied depth deltas do not cover every research-eligible book observation" + ) + future = joined.filter( + (pl.col("cancellation_feature_max_source_ts_ns") > pl.col("feature_cutoff_ts_ns")) + | ( + (pl.col("cancellation_feature_max_source_ts_ns") == pl.col("feature_cutoff_ts_ns")) + & (pl.col("cancellation_feature_max_source_sequence") > pl.col("decision_sequence")) + ) + ) + if not future.is_empty(): + raise TemporalLeakageError("cancellation feature lineage extends beyond its decision") + return joined + + +def build_l1_trade_features( + book_observations: pl.DataFrame, + trades: pl.DataFrame | None, + config: FeatureConfig, +) -> pl.DataFrame: + """Build causal event-time features from normalized L1 states and trades. + + Invalid book rows are not repaired or used as decisions. The caller keeps + the normalized/quality tables as the audit record; this returned table is a + research-eligible view containing valid states only. + """ + + _assert_normalized_books(book_observations) + if trades is not None and not trades.is_empty() and "continuity_id" not in trades.columns: + multi_segment_symbols = ( + book_observations.group_by("symbol") + .agg(pl.col("continuity_id").n_unique().alias("_continuity_count")) + .filter(pl.col("_continuity_count") > 1) + .get_column("symbol") + .to_list() + ) + if multi_segment_symbols: + raise ResearchDataError( + "trades require continuity_id when book history contains multiple continuity " + f"segments for symbols: {sorted(str(value) for value in multi_segment_symbols)}" + ) + prepared_trades = _prepare_trades(trades) + group = ["symbol", "continuity_id"] + depth_expressions: list[pl.Expr] = [] + for level in (5, 10): + bid_column = f"depth_bid_{level}" + ask_column = f"depth_ask_{level}" + presence = ( + bid_column in book_observations.columns, + ask_column in book_observations.columns, + ) + if presence[0] != presence[1]: + raise ResearchDataError( + f"book observations must supply both {bid_column} and {ask_column}" + ) + if all(presence): + total = pl.col(bid_column) + pl.col(ask_column) + depth_expressions.extend( + [ + total.alias(f"depth_total_l{level}"), + pl.when(total > 0) + .then((pl.col(bid_column) - pl.col(ask_column)) / total) + .otherwise(None) + .alias(f"queue_imbalance_l{level}"), + ] + ) + + books = ( + book_observations.filter(pl.col("is_valid")) + .sort(["symbol", "continuity_id", "sequence_end"]) + .with_columns( + pl.col("event_ts_ns").alias("market_event_ts_ns"), + pl.col("available_ts_ns").alias("decision_ts_ns"), + pl.col("available_ts_ns").alias("feature_cutoff_ts_ns"), + pl.col("sequence_end").alias("decision_sequence"), + ((pl.col("best_bid") + pl.col("best_ask")) / 2.0).alias("mid_price"), + (pl.col("best_ask") - pl.col("best_bid")).alias("spread"), + (pl.col("bid_quantity") + pl.col("ask_quantity")).alias("depth_total_l1"), + *depth_expressions, + ) + .with_columns( + pl.col("best_bid").shift(1).over(group).alias("_previous_bid"), + pl.col("best_ask").shift(1).over(group).alias("_previous_ask"), + pl.col("bid_quantity").shift(1).over(group).alias("_previous_bid_quantity"), + pl.col("ask_quantity").shift(1).over(group).alias("_previous_ask_quantity"), + pl.col("mid_price").shift(1).over(group).alias("_previous_mid"), + pl.col("spread").shift(1).over(group).alias("_previous_spread"), + pl.col("depth_total_l1").shift(1).over(group).alias("_previous_depth_l1"), + pl.col("sequence_end").cum_count().over(group).alias("history_events"), + ) + .with_columns( + (10_000.0 * pl.col("spread") / pl.col("mid_price")).alias("spread_bps"), + pl.when(pl.col("depth_total_l1") > 0) + .then((pl.col("bid_quantity") - pl.col("ask_quantity")) / pl.col("depth_total_l1")) + .otherwise(None) + .alias("queue_imbalance_l1"), + pl.when(pl.col("depth_total_l1") > 0) + .then( + ( + pl.col("best_ask") * pl.col("bid_quantity") + + pl.col("best_bid") * pl.col("ask_quantity") + ) + / pl.col("depth_total_l1") + ) + .otherwise(None) + .alias("causal_microprice"), + pl.when(pl.col("_previous_mid").is_not_null()) + .then((pl.col("mid_price") / pl.col("_previous_mid")).log()) + .otherwise(0.0) + .alias("log_mid_return_1"), + pl.when(pl.col("_previous_mid").is_not_null()) + .then(10_000.0 * (pl.col("mid_price") / pl.col("_previous_mid") - 1.0)) + .otherwise(0.0) + .alias("realized_price_impact_bps_1"), + pl.when(pl.col("_previous_spread").is_not_null()) + .then(10_000.0 * (pl.col("_previous_spread") - pl.col("spread")) / pl.col("mid_price")) + .otherwise(0.0) + .alias("spread_recovery_bps_1"), + pl.when(pl.col("_previous_depth_l1").is_not_null()) + .then(pl.col("depth_total_l1") - pl.col("_previous_depth_l1")) + .otherwise(0.0) + .alias("depth_recovery_l1_1"), + pl.when(pl.col("_previous_bid").is_null()) + .then(0.0) + .otherwise( + pl.when(pl.col("best_bid") >= pl.col("_previous_bid")) + .then(pl.col("bid_quantity")) + .otherwise(0.0) + - pl.when(pl.col("best_bid") <= pl.col("_previous_bid")) + .then(pl.col("_previous_bid_quantity")) + .otherwise(0.0) + - pl.when(pl.col("best_ask") <= pl.col("_previous_ask")) + .then(pl.col("ask_quantity")) + .otherwise(0.0) + + pl.when(pl.col("best_ask") >= pl.col("_previous_ask")) + .then(pl.col("_previous_ask_quantity")) + .otherwise(0.0) + ) + .alias("ofi_l1"), + ) + .with_columns( + ( + 10_000.0 * (pl.col("causal_microprice") - pl.col("mid_price")) / pl.col("mid_price") + ).alias("microprice_deviation_bps"), + pl.col("feature_cutoff_ts_ns").first().over(group).alias("_segment_start_ts_ns"), + ) + ) + + joined = _join_trade_history(books, prepared_trades).sort( + ["symbol", "continuity_id", "sequence_end"] + ) + joined = joined.with_columns( + pl.when(pl.col("trade_feature_max_source_ts_ns") >= pl.col("_segment_start_ts_ns")) + .then(pl.col("trade_feature_max_source_ts_ns")) + .otherwise(None) + .alias("trade_feature_max_source_ts_ns"), + pl.col("_cum_signed").first().over(group).alias("_segment_base_signed"), + pl.col("_cum_volume").first().over(group).alias("_segment_base_volume"), + pl.col("_cum_count").first().over(group).alias("_segment_base_count"), + ) + + rolling_expressions: list[pl.Expr] = [] + trade_feature_windows = sorted(set((*config.trade_windows, config.intensity_window))) + for window in trade_feature_windows: + lag_signed = pl.col("_cum_signed").shift(window).over(group) + lag_volume = pl.col("_cum_volume").shift(window).over(group) + lag_count = pl.col("_cum_count").shift(window).over(group) + lag_time = pl.col("feature_cutoff_ts_ns").shift(window).over(group) + signed = pl.col("_cum_signed") - pl.coalesce([lag_signed, pl.col("_segment_base_signed")]) + volume = pl.col("_cum_volume") - pl.coalesce([lag_volume, pl.col("_segment_base_volume")]) + count = pl.col("_cum_count") - pl.coalesce([lag_count, pl.col("_segment_base_count")]) + elapsed_seconds = ( + pl.col("feature_cutoff_ts_ns") - pl.coalesce([lag_time, pl.col("_segment_start_ts_ns")]) + ) / 1_000_000_000.0 + rolling_expressions.extend( + [ + signed.alias(f"signed_trade_volume_w{window}"), + volume.alias(f"trade_volume_w{window}"), + count.cast(pl.Float64).alias(f"trade_count_w{window}"), + pl.when(elapsed_seconds > 0) + .then(count / elapsed_seconds) + .otherwise(0.0) + .cast(pl.Float64) + .alias(f"trade_intensity_w{window}"), + pl.col("ofi_l1") + .rolling_sum(window_size=window, min_samples=1) + .over(group) + .alias(f"ofi_w{window}"), + ] + ) + + volatility_window = config.volatility_window + rolling_expressions.append( + pl.col("log_mid_return_1") + .pow(2) + .rolling_sum(window_size=volatility_window, min_samples=1) + .over(group) + .sqrt() + .alias(f"realized_volatility_w{volatility_window}") + ) + warmup = max((*config.trade_windows, config.volatility_window, config.intensity_window)) + + return ( + joined.with_columns(rolling_expressions) + .with_columns( + (pl.col("history_events") >= warmup).alias("feature_ready"), + pl.col("feature_cutoff_ts_ns").alias("max_feature_source_ts_ns"), + pl.col("decision_sequence").alias("max_feature_source_sequence"), + ) + .drop( + "_previous_bid", + "_previous_ask", + "_previous_bid_quantity", + "_previous_ask_quantity", + "_previous_mid", + "_previous_spread", + "_previous_depth_l1", + "_segment_start_ts_ns", + "_cum_signed", + "_cum_volume", + "_cum_count", + "_segment_base_signed", + "_segment_base_volume", + "_segment_base_count", + ) + .sort(["decision_ts_ns", "symbol", "decision_sequence"]) + ) + + +def add_future_event_labels(frame: pl.DataFrame, horizon_events: int) -> pl.DataFrame: + """Attach strictly subsequent mid-return/direction labels within each segment.""" + + if horizon_events < 1: + raise ResearchDataError("label horizon must be at least one event") + _require_columns( + frame, + frozenset( + { + "symbol", + "continuity_id", + "decision_ts_ns", + "decision_sequence", + "mid_price", + } + ), + "feature frame", + ) + group = ["symbol", "continuity_id"] + labeled = ( + frame.sort(["symbol", "continuity_id", "decision_sequence"]) + .with_columns( + pl.col("mid_price").shift(-horizon_events).over(group).alias("_target_mid"), + pl.col("decision_ts_ns").shift(-horizon_events).over(group).alias("_target_ts_ns"), + pl.col("decision_sequence") + .shift(-horizon_events) + .over(group) + .alias("_target_sequence"), + pl.col("continuity_id") + .shift(-horizon_events) + .over(group) + .alias("_target_continuity_id"), + ) + .with_columns( + ( + pl.col("_target_mid").is_null() + | (pl.col("_target_sequence") <= pl.col("decision_sequence")) + | ( + (pl.col("_target_ts_ns") < pl.col("decision_ts_ns")) + | ( + (pl.col("_target_ts_ns") == pl.col("decision_ts_ns")) + & (pl.col("_target_sequence") <= pl.col("decision_sequence")) + ) + ) + ).alias("right_censored") + ) + .with_columns( + pl.when(~pl.col("right_censored")) + .then((pl.col("_target_mid") / pl.col("mid_price")).log()) + .otherwise(None) + .alias("future_mid_return"), + pl.when(~pl.col("right_censored")) + .then(pl.col("_target_ts_ns")) + .otherwise(None) + .alias("label_information_end_ts_ns"), + pl.when(~pl.col("right_censored")) + .then(pl.col("_target_sequence")) + .otherwise(None) + .alias("label_information_end_sequence"), + pl.when(~pl.col("right_censored")) + .then(pl.col("_target_continuity_id")) + .otherwise(None) + .alias("label_continuity_id"), + pl.lit(horizon_events, dtype=pl.Int64).alias("label_horizon_events"), + pl.col("decision_ts_ns").alias("label_start_ts_ns"), + pl.col("decision_sequence").alias("label_start_sequence"), + ) + .with_columns( + pl.when(pl.col("future_mid_return").is_null()) + .then(None) + .when(pl.col("future_mid_return") > 0) + .then(1) + .when(pl.col("future_mid_return") < 0) + .then(-1) + .otherwise(0) + .cast(pl.Int8) + .alias("future_mid_direction"), + pl.when(pl.col("future_mid_return").is_null()) + .then(None) + .otherwise((pl.col("future_mid_return") > 0).cast(pl.Int8)) + .alias("future_mid_up"), + ) + .drop("_target_mid", "_target_ts_ns", "_target_sequence", "_target_continuity_id") + .sort(["decision_ts_ns", "symbol", "decision_sequence"]) + ) + validate_temporal_contract(labeled) + return labeled + + +def build_research_frame( + book_observations: pl.DataFrame, + trades: pl.DataFrame | None, + config: FeatureConfig, + *, + depth_deltas: pl.DataFrame | None = None, +) -> pl.DataFrame: + """Build the complete causal feature/strictly-future-label event frame.""" + + features = build_research_features( + book_observations, + trades, + config, + depth_deltas=depth_deltas, + ) + return add_future_event_labels(features, config.label_horizon_events) + + +def build_research_features( + book_observations: pl.DataFrame, + trades: pl.DataFrame | None, + config: FeatureConfig, + *, + depth_deltas: pl.DataFrame | None = None, +) -> pl.DataFrame: + """Build causal features without opening any future-label horizon. + + Separating this stage lets a caller attach several predeclared event- and + clock-time labels to the exact same information set. Cancellation inputs + remain continuity-local and are joined at the current observable update. + """ + + features = build_l1_trade_features(book_observations, trades, config) + return _join_cancellation_history(features, depth_deltas, config) + + +def validate_temporal_contract(frame: pl.DataFrame) -> TemporalAudit: + """Fail closed when feature lineage or labels violate event-time ordering.""" + + required = frozenset( + { + "symbol", + "continuity_id", + "decision_ts_ns", + "decision_sequence", + "feature_cutoff_ts_ns", + "max_feature_source_ts_ns", + "max_feature_source_sequence", + "trade_feature_max_source_ts_ns", + "right_censored", + "future_mid_return", + "future_mid_direction", + "future_mid_up", + "label_information_end_ts_ns", + "label_information_end_sequence", + "label_continuity_id", + } + ) + _require_columns(frame, required, "research frame") + + future_feature = frame.filter( + (pl.col("max_feature_source_ts_ns") > pl.col("feature_cutoff_ts_ns")) + | ( + (pl.col("max_feature_source_ts_ns") == pl.col("feature_cutoff_ts_ns")) + & (pl.col("max_feature_source_sequence") > pl.col("decision_sequence")) + ) + | ( + pl.col("trade_feature_max_source_ts_ns").is_not_null() + & (pl.col("trade_feature_max_source_ts_ns") >= pl.col("decision_ts_ns")) + ) + ) + if not future_feature.is_empty(): + raise TemporalLeakageError("feature lineage extends beyond its decision cutoff") + + if { + "cancellation_feature_max_source_ts_ns", + "cancellation_feature_max_source_sequence", + }.issubset(frame.columns): + future_cancellation = frame.filter( + (pl.col("cancellation_feature_max_source_ts_ns") > pl.col("feature_cutoff_ts_ns")) + | ( + (pl.col("cancellation_feature_max_source_ts_ns") == pl.col("feature_cutoff_ts_ns")) + & (pl.col("cancellation_feature_max_source_sequence") > pl.col("decision_sequence")) + ) + ) + if not future_cancellation.is_empty(): + raise TemporalLeakageError( + "cancellation feature lineage extends beyond its decision cutoff" + ) + + uncensored = ~pl.col("right_censored") + invalid_label = frame.filter( + ( + uncensored + & ( + pl.col("label_information_end_ts_ns").is_null() + | pl.col("label_information_end_sequence").is_null() + | (pl.col("label_continuity_id") != pl.col("continuity_id")) + | (pl.col("label_information_end_ts_ns") < pl.col("decision_ts_ns")) + | ( + (pl.col("label_information_end_ts_ns") == pl.col("decision_ts_ns")) + & (pl.col("label_information_end_sequence") <= pl.col("decision_sequence")) + ) + ) + ) + | ( + pl.col("right_censored") + & ( + pl.col("future_mid_return").is_not_null() + | pl.col("future_mid_direction").is_not_null() + | pl.col("future_mid_up").is_not_null() + | pl.col("label_information_end_ts_ns").is_not_null() + | pl.col("label_information_end_sequence").is_not_null() + ) + ) + ) + if not invalid_label.is_empty(): + raise TemporalLeakageError("labels are not strictly future, gap-local, and censor-safe") + + censored_rows = frame.filter(pl.col("right_censored")).height + return TemporalAudit( + rows=frame.height, + labeled_rows=frame.height - censored_rows, + right_censored_rows=censored_rows, + continuity_segments=frame.select("symbol", "continuity_id").unique().height, + ) + + +def model_feature_columns(frame: pl.DataFrame) -> tuple[str, ...]: + """Return the explicit leakage-safe allowlist present in ``frame``.""" + + selected = [name for name in _STATIC_MODEL_FEATURES if name in frame.columns] + selected.extend( + name + for name in frame.columns + if name.startswith(_MODEL_FEATURE_PREFIXES) and name not in selected + ) + if not selected: + raise ResearchDataError("research frame contains no recognized model features") + return tuple(selected) + + +__all__ = [ + "ResearchDataError", + "TemporalAudit", + "TemporalLeakageError", + "add_future_event_labels", + "build_cancellation_intensity_features", + "build_l1_trade_features", + "build_research_features", + "build_research_frame", + "model_feature_columns", + "validate_temporal_contract", +] diff --git a/Microstructure/src/microstructure/research/l2_analysis.py b/Microstructure/src/microstructure/research/l2_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..9c741cdf705eac3ca404262ee09471a756778f0f --- /dev/null +++ b/Microstructure/src/microstructure/research/l2_analysis.py @@ -0,0 +1,360 @@ +"""Reproducible descriptive economics for the frozen live-L2 study. + +These functions run only after endpoint labels are opened. They never select a +model or refit a threshold used by prediction. Shock thresholds and stability +bins are fitted on the declared development reference, then applied unchanged +to held-out sessions. +""" + +from __future__ import annotations + +import math +from collections.abc import Sequence +from dataclasses import dataclass + +import polars as pl + +from microstructure.research.analysis import feature_stability_summary +from microstructure.research.l2_multidate import L2ResearchError, validate_l2_endpoint_frame + +_NANOSECONDS_PER_MINUTE = 60_000_000_000 +_DEVELOPMENT_ROLES = frozenset({"train", "validation"}) +_TEST_ROLES = ("primary_test", "replication_test") + + +@dataclass(frozen=True, slots=True) +class L2DescriptiveAnalysis: + """Machine-readable L2 economic analyses, kept separate from model scores.""" + + intraday_liquidity: pl.DataFrame + ofi_return_association: pl.DataFrame + signal_half_life: pl.DataFrame + liquidity_recovery: pl.DataFrame + regime_diagnostics: pl.DataFrame + feature_stability: pl.DataFrame + cross_instrument_stability: pl.DataFrame + + +def _combined(frames: Sequence[pl.DataFrame]) -> pl.DataFrame: + values = tuple(frames) + if not values: + raise L2ResearchError("L2 descriptive analysis requires endpoint frames") + for frame in values: + validate_l2_endpoint_frame(frame) + combined = pl.concat(values, how="diagonal_relaxed") + keys = ["study_date", "symbol", "endpoint_name", "sample_id"] + if combined.select(keys).unique().height != combined.height: + raise L2ResearchError("L2 descriptive endpoint identities are not unique") + return combined + + +def _canonical_books(combined: pl.DataFrame) -> pl.DataFrame: + endpoint_names = sorted(str(value) for value in combined.get_column("endpoint_name").unique()) + chosen = "event_20" if "event_20" in endpoint_names else endpoint_names[0] + books = combined.filter(pl.col("endpoint_name") == chosen) + keys = ["study_date", "symbol", "continuity_id", "decision_sequence"] + if books.select(keys).unique().height != books.height: + raise L2ResearchError("canonical L2 book observations are not unique") + return books + + +def _intraday_liquidity(books: pl.DataFrame) -> pl.DataFrame: + return ( + books.with_columns( + ((pl.col("decision_ts_ns") // _NANOSECONDS_PER_MINUTE) % (24 * 60)) + .cast(pl.Int32) + .alias("utc_minute_of_day") + ) + .group_by("study_date", "study_role", "symbol", "utc_minute_of_day") + .agg( + pl.len().alias("n_observations"), + pl.col("spread_bps").mean().alias("mean_spread_bps"), + pl.col("spread_bps").median().alias("median_spread_bps"), + pl.col("depth_total_l1").mean().alias("mean_depth_l1"), + pl.col("depth_total_l5").mean().alias("mean_depth_l5"), + pl.col("depth_total_l10").mean().alias("mean_depth_l10"), + pl.col("queue_imbalance_l1").mean().alias("mean_queue_imbalance_l1"), + pl.col("realized_volatility_w100").mean().alias("mean_realized_volatility_w100"), + ) + .sort("study_date", "symbol", "utc_minute_of_day") + ) + + +def _finite_correlation(x: pl.Series, y: pl.Series) -> float | None: + pairs = ( + pl.DataFrame({"x": x, "y": y}) + .drop_nulls() + .filter(pl.col("x").is_finite() & pl.col("y").is_finite()) + ) + if ( + pairs.height < 3 + or pairs.get_column("x").n_unique() < 2 + or pairs.get_column("y").n_unique() < 2 + ): + return None + value = pairs.select(pl.corr("x", "y")).item() + return float(value) if value is not None and math.isfinite(float(value)) else None + + +def _ofi_association(combined: pl.DataFrame) -> pl.DataFrame: + rows: list[dict[str, object]] = [] + for key, frame in combined.filter(~pl.col("right_censored")).group_by( + "study_date", "study_role", "symbol", "endpoint_name", maintain_order=True + ): + study_date, study_role, symbol, endpoint_name = (str(value) for value in key) + side_source = str(frame.get_column("signed_markout_side_source")[0]) + rows.append( + { + "study_date": study_date, + "study_role": study_role, + "symbol": symbol, + "endpoint_name": endpoint_name, + "side_source": side_source, + "n_observations": frame.height, + "ofi_return_correlation": _finite_correlation( + frame.get_column(side_source), frame.get_column("future_mid_return") + ), + "mean_ofi_signed_future_mid_markout_bps": frame.get_column( + "ofi_signed_future_mid_markout_bps" + ).mean(), + "positive_direction_rate": frame.get_column("future_mid_up").mean(), + "interpretation": "descriptive_book_flow_markout_not_trade_impact", + } + ) + return pl.DataFrame(rows, infer_schema_length=None).sort( + "study_date", "symbol", "endpoint_name" + ) + + +def _signal_half_life(association: pl.DataFrame, combined: pl.DataFrame) -> pl.DataFrame: + endpoint_contract = ( + combined.select( + "endpoint_name", "endpoint_domain", "endpoint_horizon_value", "endpoint_horizon_unit" + ) + .unique() + .sort("endpoint_domain", "endpoint_horizon_value") + ) + enriched = association.join(endpoint_contract, on="endpoint_name", how="left") + rows: list[dict[str, object]] = [] + for key, frame in enriched.group_by( + "study_date", "study_role", "symbol", "endpoint_domain", maintain_order=True + ): + study_date, study_role, symbol, domain = (str(value) for value in key) + ordered = frame.sort("endpoint_horizon_value") + correlations = ordered.get_column("ofi_return_correlation").to_list() + baseline = ( + abs(float(correlations[0])) if correlations and correlations[0] is not None else None + ) + crossed: int | None = None + if baseline is not None and baseline > 0: + for horizon, correlation in zip( + ordered.get_column("endpoint_horizon_value").to_list(), + correlations, + strict=True, + ): + if correlation is not None and abs(float(correlation)) <= 0.5 * baseline: + crossed = int(horizon) + break + for row in ordered.to_dicts(): + correlation = row["ofi_return_correlation"] + association_ratio = None + if correlation is not None and baseline is not None and baseline != 0.0: + association_ratio = abs(float(correlation)) / baseline + rows.append( + { + "study_date": study_date, + "study_role": study_role, + "symbol": symbol, + "endpoint_domain": domain, + "endpoint_name": row["endpoint_name"], + "horizon_value": row["endpoint_horizon_value"], + "horizon_unit": row["endpoint_horizon_unit"], + "ofi_return_correlation": correlation, + "absolute_association_ratio_to_shortest": association_ratio, + "half_life_crossed_at_horizon": crossed, + "half_life_status": ( + "crossed_within_declared_horizons" + if crossed is not None + else "not_crossed_or_unidentified" + ), + } + ) + return pl.DataFrame(rows, infer_schema_length=None).sort( + "study_date", "symbol", "endpoint_domain", "horizon_value" + ) + + +def _training_shock_thresholds(books: pl.DataFrame) -> pl.DataFrame: + train = books.filter(pl.col("study_role") == "train").with_columns( + pl.min_horizontal("bid_quantity", "ask_quantity").alias("executable_l1_depth") + ) + symbols = set(str(value) for value in books.get_column("symbol").unique()) + if set(str(value) for value in train.get_column("symbol").unique()) != symbols: + raise L2ResearchError("liquidity shock thresholds require train rows for every symbol") + return train.group_by("symbol").agg( + pl.col("spread_bps").quantile(0.95, interpolation="linear").alias("train_spread_q95"), + pl.col("executable_l1_depth") + .quantile(0.05, interpolation="linear") + .alias("train_executable_depth_q05"), + ) + + +def _liquidity_recovery(books: pl.DataFrame) -> pl.DataFrame: + thresholds = _training_shock_thresholds(books) + joined = books.with_columns( + pl.min_horizontal("bid_quantity", "ask_quantity").alias("executable_l1_depth") + ).join(thresholds, on="symbol", how="left") + group = ["study_date", "symbol", "continuity_id"] + rows: list[pl.DataFrame] = [] + for horizon in (20, 100): + rows.append( + joined.with_columns( + pl.col("spread_bps").shift(-horizon).over(group).alias("future_spread_bps"), + pl.col("executable_l1_depth") + .shift(-horizon) + .over(group) + .alias("future_executable_l1_depth"), + ) + .filter( + (pl.col("spread_bps") >= pl.col("train_spread_q95")) + | (pl.col("executable_l1_depth") <= pl.col("train_executable_depth_q05")) + ) + .drop_nulls(["future_spread_bps", "future_executable_l1_depth"]) + .with_columns( + pl.lit(horizon).alias("recovery_horizon_events"), + (pl.col("future_spread_bps") - pl.col("spread_bps")).alias("spread_change_bps"), + (pl.col("future_executable_l1_depth") - pl.col("executable_l1_depth")).alias( + "executable_depth_change" + ), + ) + .group_by("study_date", "study_role", "symbol", "recovery_horizon_events") + .agg( + pl.len().alias("n_shocks"), + pl.col("spread_change_bps").mean().alias("mean_spread_change_bps"), + pl.col("executable_depth_change").mean().alias("mean_executable_depth_change"), + pl.col("train_spread_q95").first(), + pl.col("train_executable_depth_q05").first(), + ) + ) + return pl.concat(rows, how="vertical_relaxed").sort( + "study_date", "symbol", "recovery_horizon_events" + ) + + +def _regime_diagnostics(combined: pl.DataFrame) -> pl.DataFrame: + required = {"volatility_regime", "liquidity_regime"} + missing = sorted(required.difference(combined.columns)) + if missing: + raise L2ResearchError(f"regime diagnostics are missing columns: {missing}") + return ( + combined.filter(~pl.col("right_censored")) + .group_by( + "study_date", + "study_role", + "symbol", + "endpoint_name", + "volatility_regime", + "liquidity_regime", + ) + .agg( + pl.len().alias("n_observations"), + pl.col("future_mid_up").mean().alias("positive_direction_rate"), + pl.col("future_mid_return").mean().alias("mean_future_mid_return"), + pl.col("ofi_signed_future_mid_markout_bps") + .mean() + .alias("mean_ofi_signed_future_mid_markout_bps"), + ) + .sort("study_date", "symbol", "endpoint_name", "volatility_regime", "liquidity_regime") + ) + + +def _feature_stability( + combined: pl.DataFrame, *, feature_columns: tuple[str, ...], bins: int +) -> pl.DataFrame: + reference = combined.filter(pl.col("study_role").is_in(list(_DEVELOPMENT_ROLES))) + if reference.is_empty(): + raise L2ResearchError("feature stability requires development rows") + outputs: list[pl.DataFrame] = [] + for role in _TEST_ROLES: + comparison = combined.filter(pl.col("study_role") == role) + if comparison.is_empty(): + raise L2ResearchError(f"feature stability requires {role} rows") + outputs.append( + feature_stability_summary( + reference, + comparison, + feature_columns=feature_columns, + group_columns=("symbol", "endpoint_name"), + bins=bins, + ).with_columns( + pl.lit(role).alias("comparison_role"), + pl.lit("train_plus_validation_only").alias("reference_scope"), + ) + ) + return pl.concat(outputs, how="vertical_relaxed").sort( + "comparison_role", "symbol", "endpoint_name", "feature" + ) + + +def _cross_instrument_stability(association: pl.DataFrame) -> pl.DataFrame: + rows: list[dict[str, object]] = [] + for key, frame in association.group_by( + "study_date", "study_role", "endpoint_name", maintain_order=True + ): + study_date, study_role, endpoint_name = (str(value) for value in key) + by_symbol: dict[str, float | None] = { + str(row["symbol"]): ( + None + if row["ofi_return_correlation"] is None + else float(row["ofi_return_correlation"]) + ) + for row in frame.to_dicts() + } + btc = by_symbol.get("BTCUSDT") + eth = by_symbol.get("ETHUSDT") + same_direction = None + if btc is not None and eth is not None and btc != 0.0 and eth != 0.0: + same_direction = math.copysign(1.0, btc) == math.copysign(1.0, eth) + rows.append( + { + "study_date": study_date, + "study_role": study_role, + "endpoint_name": endpoint_name, + "btc_ofi_return_correlation": btc, + "eth_ofi_return_correlation": eth, + "both_observed": btc is not None and eth is not None, + "same_direction": same_direction, + "cross_instrument_pooling": False, + } + ) + return pl.DataFrame(rows, infer_schema_length=None).sort("study_date", "endpoint_name") + + +def build_l2_descriptive_analysis( + endpoint_frames: Sequence[pl.DataFrame], + *, + feature_columns: Sequence[str], + stability_bins: int, +) -> L2DescriptiveAnalysis: + """Build all frozen descriptive outputs without fitting a predictive model.""" + + features = tuple(str(value) for value in feature_columns) + if not features or stability_bins < 2: + raise L2ResearchError("descriptive feature columns and stability bins are required") + combined = _combined(endpoint_frames) + books = _canonical_books(combined) + association = _ofi_association(combined) + return L2DescriptiveAnalysis( + intraday_liquidity=_intraday_liquidity(books), + ofi_return_association=association, + signal_half_life=_signal_half_life(association, combined), + liquidity_recovery=_liquidity_recovery(books), + regime_diagnostics=_regime_diagnostics(combined), + feature_stability=_feature_stability( + combined, feature_columns=features, bins=stability_bins + ), + cross_instrument_stability=_cross_instrument_stability(association), + ) + + +__all__ = ["L2DescriptiveAnalysis", "build_l2_descriptive_analysis"] diff --git a/Microstructure/src/microstructure/research/l2_evaluation.py b/Microstructure/src/microstructure/research/l2_evaluation.py new file mode 100644 index 0000000000000000000000000000000000000000..4dd504dca04ccc3dd84ebcaa71a04ca9270fa17a --- /dev/null +++ b/Microstructure/src/microstructure/research/l2_evaluation.py @@ -0,0 +1,1563 @@ +"""Lock-only evaluation and market-order scenarios for the M8 live-L2 study. + +This module intentionally exposes no fitting, calibration, selection, or regime- +threshold API. Its only model operation is restoring numeric development state +through :class:`~microstructure.research.multidate.FinalFittedState` and asking +that state for probabilities on already-built primary/replication endpoint +frames. + +All uncertainty is descriptive. Paired log-loss differences resample frozen- +width overlapping windows locally inside each continuity/OBSERVED interval, +never pool symbols, never compute a p-value, and weight the primary and +replication sessions equally. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import re +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from typing import Any, Literal, cast + +import numpy as np +import polars as pl +from numpy.typing import NDArray + +from microstructure.config import ExecutionConfig +from microstructure.execution.simulator import simulate_predictions +from microstructure.m8_l2_analysis_config import ( + M8_L2_ANALYSIS_CONFIG_SEMANTIC_SHA256, + M8_L2_ANALYSIS_CONFIG_SOURCE_SHA256, +) +from microstructure.research.l2_multidate import ( + L2EndpointSpec, + L2ResearchError, + validate_l2_endpoint_frame, +) +from microstructure.research.models import classification_metrics +from microstructure.research.multidate import FinalFittedState + +HeldoutRole = Literal["primary_test", "replication_test"] + +_NANOSECONDS_PER_MILLISECOND = 1_000_000 +_HEX_SHA256 = re.compile(r"^[0-9a-f]{64}$") +_HELDOUT_ROLES = frozenset({"primary_test", "replication_test"}) +_EXPECTED_EVENT_LATENCIES = (0, 1, 5) +_EXPECTED_REGIMES = tuple( + f"{volatility}__{liquidity}" + for volatility in ("low", "medium", "high") + for liquidity in ("liquid", "normal", "stressed") +) +_ALL_REGIME = "ALL" +_TARGET = "future_mid_up" +_REFERENCE_PRICE_STATISTIC = "train_median_mid_price" +_REFERENCE_DEPTH_STATISTIC = "train_q05_min_bid_ask_l1_depth" +_REFERENCE_SCHEMA_VERSION = "m8-l2-execution-reference-v1" +_FROZEN_ENDPOINTS: Mapping[str, tuple[str, int, str, int, int]] = { + # domain, horizon, unit, paired-block width, impact OFI window + "event_20": ("event", 20, "events", 40, 20), + "event_100": ("event", 100, "events", 200, 100), + "clock_1000ms": ("clock", 1_000, "milliseconds", 2_000, 20), + "clock_5000ms": ("clock", 5_000, "milliseconds", 10_000, 100), +} + + +class L2LockedEvaluationError(ValueError): + """Raised when lock-only evaluation or scenario replay would be invalid.""" + + +def _sha256(value: str, label: str) -> str: + if _HEX_SHA256.fullmatch(value) is None: + raise L2LockedEvaluationError(f"{label} must be a lowercase SHA-256 digest") + return value + + +def _mapping(value: object, label: str) -> Mapping[str, Any]: + if not isinstance(value, Mapping): + raise L2LockedEvaluationError(f"{label} must be an object") + return cast(Mapping[str, Any], value) + + +def _require(frame: pl.DataFrame, columns: Sequence[str], label: str) -> None: + missing = sorted(set(columns).difference(frame.columns)) + if missing: + raise L2LockedEvaluationError(f"{label} is missing required columns: {missing}") + if frame.is_empty(): + raise L2LockedEvaluationError(f"{label} must not be empty") + + +def _null_nonfinite(frame: pl.DataFrame) -> pl.DataFrame: + """Make every tabular output safe for strict ``allow_nan=False`` JSON.""" + + float_columns = [name for name, dtype in frame.schema.items() if dtype.is_float()] + if not float_columns: + return frame + return frame.with_columns( + *[ + pl.when(pl.col(name).is_finite().fill_null(False)) + .then(pl.col(name)) + .otherwise(None) + .alias(name) + for name in float_columns + ] + ) + + +def _candidate_name(model: Mapping[str, Any], label: str) -> str: + candidate = _mapping(model.get("requested_candidate"), f"{label} requested candidate") + value = candidate.get("name") + if not isinstance(value, str) or not value: + raise L2LockedEvaluationError(f"{label} requested candidate has no name") + return value + + +def _validate_frozen_endpoint(endpoint: L2EndpointSpec) -> None: + expected = _FROZEN_ENDPOINTS.get(endpoint.name) + if expected is None: + raise L2LockedEvaluationError(f"unknown frozen M8 L2 endpoint: {endpoint.name!r}") + domain, horizon, unit, block_width, impact_window = expected + observed_block = ( + endpoint.paired_block_events + if endpoint.domain == "event" + else endpoint.paired_block_milliseconds + ) + observed = ( + endpoint.domain, + endpoint.horizon_value, + endpoint.horizon_unit, + observed_block, + endpoint.impact_ofi_window, + ) + if observed != (domain, horizon, unit, block_width, impact_window): + raise L2LockedEvaluationError( + f"endpoint {endpoint.name!r} differs from the frozen M8 L2 endpoint contract" + ) + + +@dataclass(frozen=True, slots=True) +class LockedL2EndpointState: + """One externally verified child lock and its restored numeric model state.""" + + symbol: str + endpoint: L2EndpointSpec + child_lock_sha256: str + aggregate_lock_sha256: str + regime_thresholds_sha256: str + fitted_state: FinalFittedState + + def __post_init__(self) -> None: + if not self.symbol or self.symbol != self.symbol.upper(): + raise L2LockedEvaluationError("locked L2 symbol must be nonempty uppercase text") + _sha256(self.child_lock_sha256, "child lock SHA-256") + _sha256(self.aggregate_lock_sha256, "aggregate lock SHA-256") + _sha256(self.regime_thresholds_sha256, "regime-threshold SHA-256") + _validate_frozen_endpoint(self.endpoint) + payload = self.fitted_state.payload() + if payload.get("target") != _TARGET: + raise L2LockedEvaluationError("locked L2 fitted state must target future_mid_up") + features = payload.get("feature_columns") + if ( + not isinstance(features, list) + or not features + or not all(isinstance(value, str) and value for value in features) + or len(set(features)) != len(features) + ): + raise L2LockedEvaluationError("locked L2 fitted-state features are invalid") + models = _mapping(payload.get("models"), "locked L2 fitted-state models") + if set(models) != {"selected", "historical_prior"}: + raise L2LockedEvaluationError( + "locked L2 fitted state requires selected and historical-prior models" + ) + _candidate_name(_mapping(models["selected"], "selected model"), "selected model") + prior_name = _candidate_name( + _mapping(models["historical_prior"], "historical-prior model"), + "historical-prior model", + ) + if prior_name != "historical_prior": + raise L2LockedEvaluationError("locked baseline must be historical_prior") + + @property + def feature_columns(self) -> tuple[str, ...]: + return tuple(cast(list[str], self.fitted_state.payload()["feature_columns"])) + + @property + def selected_model(self) -> str: + models = _mapping(self.fitted_state.payload()["models"], "fitted-state models") + return _candidate_name(_mapping(models["selected"], "selected model"), "selected model") + + def fit_cutoff(self, role: Literal["selected", "historical_prior"]) -> int: + models = _mapping(self.fitted_state.payload()["models"], "fitted-state models") + model = _mapping(models[role], f"{role} model") + value = model.get("fit_cutoff_ts_ns") + if isinstance(value, bool) or not isinstance(value, int) or value < 1: + raise L2LockedEvaluationError(f"{role} model has an invalid fit cutoff") + return value + + +@dataclass(frozen=True, slots=True) +class L2HeldoutEndpointFrame: + """One verified primary or replication endpoint frame.""" + + symbol: str + endpoint_name: str + study_date: str + study_role: HeldoutRole + frame: pl.DataFrame + + def __post_init__(self) -> None: + if not self.symbol or self.symbol != self.symbol.upper(): + raise L2LockedEvaluationError("held-out L2 symbol must be uppercase") + if not self.endpoint_name: + raise L2LockedEvaluationError("held-out endpoint name must not be empty") + if self.study_role not in _HELDOUT_ROLES: + raise L2LockedEvaluationError("held-out frame role must be primary or replication") + try: + # ISO syntax is also checked by validate_l2_endpoint_frame; this + # lightweight guard prevents ambiguous mapping keys before that call. + year, month, day = (int(value) for value in self.study_date.split("-")) + if year < 1 or not 1 <= month <= 12 or not 1 <= day <= 31: + raise ValueError + except (TypeError, ValueError): + raise L2LockedEvaluationError("held-out study date must use YYYY-MM-DD") from None + + +@dataclass(frozen=True, slots=True) +class L2EvaluationResult: + """Frozen lock-only predictions and descriptive endpoint diagnostics.""" + + predictions: pl.DataFrame + predictive_metrics: pl.DataFrame + paired_by_session_regime: pl.DataFrame + equal_session_summary: pl.DataFrame + signed_markout: pl.DataFrame + + +@dataclass(frozen=True, slots=True) +class L2ExecutionReference: + """Development-lock-persisted market-scenario sizing authority.""" + + symbol: str + training_date: str + reference_mid_price: float + train_l1_depth_q05: float + lot_size: float + reference_quantity: float + reference_sha256: str + aggregate_lock_sha256: str + reference_price_statistic: str = _REFERENCE_PRICE_STATISTIC + reference_depth_statistic: str = _REFERENCE_DEPTH_STATISTIC + analysis_config_source_sha256: str = M8_L2_ANALYSIS_CONFIG_SOURCE_SHA256 + analysis_config_semantic_sha256: str = M8_L2_ANALYSIS_CONFIG_SEMANTIC_SHA256 + + def __post_init__(self) -> None: + if not self.symbol or self.symbol != self.symbol.upper(): + raise L2LockedEvaluationError("execution-reference symbol must be uppercase") + try: + from datetime import date + + date.fromisoformat(self.training_date) + except (TypeError, ValueError): + raise L2LockedEvaluationError( + "execution-reference training date must use YYYY-MM-DD" + ) from None + if self.training_date != "2026-08-10": + raise L2LockedEvaluationError( + "M8 L2 execution reference must come from the Aug 10 train session" + ) + _sha256(self.aggregate_lock_sha256, "execution-reference aggregate-lock SHA-256") + if self.reference_price_statistic != _REFERENCE_PRICE_STATISTIC: + raise L2LockedEvaluationError("execution reference must use train median midpoint") + if self.reference_depth_statistic != _REFERENCE_DEPTH_STATISTIC: + raise L2LockedEvaluationError( + "execution reference must use train q05 minimum bid/ask L1 depth" + ) + if self.analysis_config_source_sha256 != M8_L2_ANALYSIS_CONFIG_SOURCE_SHA256: + raise L2LockedEvaluationError("execution reference has the wrong analysis source hash") + if self.analysis_config_semantic_sha256 != M8_L2_ANALYSIS_CONFIG_SEMANTIC_SHA256: + raise L2LockedEvaluationError( + "execution reference has the wrong analysis semantic hash" + ) + values = ( + self.reference_mid_price, + self.train_l1_depth_q05, + self.lot_size, + self.reference_quantity, + ) + if not all(math.isfinite(value) and value > 0.0 for value in values): + raise L2LockedEvaluationError("execution-reference values must be finite and positive") + cap = min(100.0 / self.reference_mid_price, 0.10 * self.train_l1_depth_q05) + expected = math.floor((cap + self.lot_size * 1e-12) / self.lot_size) * self.lot_size + if expected <= 0.0 or not math.isclose( + self.reference_quantity, + expected, + rel_tol=0.0, + abs_tol=max(1e-15, self.lot_size * 1e-10), + ): + raise L2LockedEvaluationError( + "persisted execution quantity disagrees with the frozen development formula" + ) + observed_sha = hashlib.sha256(_json(self.payload()).encode("utf-8")).hexdigest() + if _sha256(self.reference_sha256, "execution-reference SHA-256") != observed_sha: + raise L2LockedEvaluationError("execution-reference payload does not match its SHA-256") + + def payload(self) -> dict[str, object]: + """Return the complete canonical development-reference hash payload.""" + + return { + "schema_version": _REFERENCE_SCHEMA_VERSION, + "symbol": self.symbol, + "training_date": self.training_date, + "reference_mid_price": float(self.reference_mid_price), + "train_l1_depth_q05": float(self.train_l1_depth_q05), + "lot_size": float(self.lot_size), + "reference_quantity": float(self.reference_quantity), + "reference_price_statistic": self.reference_price_statistic, + "reference_depth_statistic": self.reference_depth_statistic, + "analysis_config_source_sha256": self.analysis_config_source_sha256, + "analysis_config_semantic_sha256": self.analysis_config_semantic_sha256, + "aggregate_lock_sha256": self.aggregate_lock_sha256, + } + + @classmethod + def create( + cls, + *, + symbol: str, + training_date: str, + reference_mid_price: float, + train_l1_depth_q05: float, + lot_size: float, + reference_quantity: float, + aggregate_lock_sha256: str, + ) -> L2ExecutionReference: + """Create the canonical persistable reference after development fitting.""" + + payload: dict[str, object] = { + "schema_version": _REFERENCE_SCHEMA_VERSION, + "symbol": symbol, + "training_date": training_date, + "reference_mid_price": float(reference_mid_price), + "train_l1_depth_q05": float(train_l1_depth_q05), + "lot_size": float(lot_size), + "reference_quantity": float(reference_quantity), + "reference_price_statistic": _REFERENCE_PRICE_STATISTIC, + "reference_depth_statistic": _REFERENCE_DEPTH_STATISTIC, + "analysis_config_source_sha256": M8_L2_ANALYSIS_CONFIG_SOURCE_SHA256, + "analysis_config_semantic_sha256": M8_L2_ANALYSIS_CONFIG_SEMANTIC_SHA256, + "aggregate_lock_sha256": aggregate_lock_sha256, + } + return cls( + symbol=symbol, + training_date=training_date, + reference_mid_price=reference_mid_price, + train_l1_depth_q05=train_l1_depth_q05, + lot_size=lot_size, + reference_quantity=reference_quantity, + reference_sha256=hashlib.sha256(_json(payload).encode("utf-8")).hexdigest(), + aggregate_lock_sha256=aggregate_lock_sha256, + ) + + +@dataclass(frozen=True, slots=True) +class L2MarketExecutionResult: + """Market-only latency ledgers and explicitly non-claiming scenario summaries.""" + + orders: pl.DataFrame + fills: pl.DataFrame + positions: pl.DataFrame + metrics: pl.DataFrame + assumptions: pl.DataFrame + + +@dataclass(frozen=True, slots=True) +class _PairedDelta: + selected_log_loss: float | None + prior_log_loss: float | None + point_delta: float | None + ci_low: float | None + ci_high: float | None + n_obs: int + n_blocks: int + samples: int + seed: int + status: str + draws: NDArray[np.float64] + + +@dataclass(frozen=True, slots=True) +class _MovingBlockInterval: + """Bounded sufficient statistics for one interval's overlapping blocks.""" + + full: NDArray[np.float64] + tail: NDArray[np.float64] | None + blocks_per_draw: int + + +def _stable_seed(base: int, *parts: str) -> int: + payload = "\x1f".join((str(base), *parts)).encode("utf-8") + return int.from_bytes(hashlib.sha256(payload).digest()[:8], "big") % (2**32) + + +def _frame_key(value: L2HeldoutEndpointFrame) -> tuple[str, str, HeldoutRole]: + return value.symbol, value.endpoint_name, value.study_role + + +def _state_key(value: LockedL2EndpointState) -> tuple[str, str]: + return value.symbol, value.endpoint.name + + +def _validate_frame_for_state( + value: L2HeldoutEndpointFrame, + state: LockedL2EndpointState, +) -> pl.DataFrame: + try: + validate_l2_endpoint_frame(value.frame) + except L2ResearchError as error: + raise L2LockedEvaluationError(str(error)) from error + _require( + value.frame, + ( + "feature_ready", + _TARGET, + "joint_market_regime", + "volatility_regime", + "liquidity_regime", + "ofi_signed_future_mid_markout_bps", + "decision_ts_ns", + "decision_sequence", + "observed_interval_id", + "observed_interval_start_ns", + "observed_interval_end_ns_exclusive", + *state.feature_columns, + ), + "held-out L2 endpoint frame", + ) + identities = value.frame.select( + pl.col("symbol").n_unique().alias("symbols"), + pl.col("endpoint_name").n_unique().alias("endpoints"), + pl.col("study_date").n_unique().alias("dates"), + pl.col("study_role").n_unique().alias("roles"), + ).row(0, named=True) + if any(int(identities[name]) != 1 for name in identities): + raise L2LockedEvaluationError("one held-out frame must have one symbol/endpoint/date/role") + observed = value.frame.select("symbol", "endpoint_name", "study_date", "study_role").row( + 0, named=True + ) + expected = { + "symbol": value.symbol, + "endpoint_name": value.endpoint_name, + "study_date": value.study_date, + "study_role": value.study_role, + } + if observed != expected: + raise L2LockedEvaluationError("held-out frame metadata differs from its typed coordinate") + if value.symbol != state.symbol or value.endpoint_name != state.endpoint.name: + raise L2LockedEvaluationError("held-out frame coordinate differs from its locked state") + endpoint_identity = value.frame.select( + "endpoint_domain", "endpoint_horizon_value", "endpoint_horizon_unit" + ).unique() + expected_endpoint_identity = { + "endpoint_domain": state.endpoint.domain, + "endpoint_horizon_value": state.endpoint.horizon_value, + "endpoint_horizon_unit": state.endpoint.horizon_unit, + } + if endpoint_identity.height != 1 or endpoint_identity.row(0, named=True) != ( + expected_endpoint_identity + ): + raise L2LockedEvaluationError("held-out endpoint semantics differ from its locked state") + if value.frame.filter(pl.col("continuity_id") != pl.col("observed_interval_id")).height: + raise L2LockedEvaluationError( + "L2 research continuity must equal the verified observed-interval identity" + ) + regimes = set(str(item) for item in value.frame["joint_market_regime"].drop_nulls().unique()) + unknown = regimes.difference(_EXPECTED_REGIMES) + if unknown: + raise L2LockedEvaluationError( + f"held-out frame has unknown train-defined regimes: {sorted(unknown)}" + ) + block_group = ["study_date", "symbol", "continuity_id", "observed_interval_id"] + with_event_ordinal = value.frame.sort( + *block_group, "decision_ts_ns", "decision_sequence" + ).with_columns( + (pl.col("decision_sequence").cum_count().over(block_group) - 1) + .cast(pl.Int64) + .alias("_endpoint_event_ordinal") + ) + eligible = with_event_ordinal.filter( + pl.col("feature_ready") & (~pl.col("right_censored")) & pl.col(_TARGET).is_not_null() + ) + if eligible.is_empty(): + raise L2LockedEvaluationError("held-out endpoint has no feature-ready labeled rows") + targets = set(eligible[_TARGET].unique().to_list()) + if not targets.issubset({0, 1}): + raise L2LockedEvaluationError("held-out binary target must contain only zero and one") + first_decision = int(cast(int, eligible["decision_ts_ns"].min())) + if ( + state.fit_cutoff("selected") >= first_decision + or state.fit_cutoff("historical_prior") >= first_decision + ): + raise L2LockedEvaluationError("development fitting information reaches held-out decisions") + return eligible.sort( + "study_date", + "symbol", + "endpoint_name", + "decision_ts_ns", + "decision_sequence", + ) + + +def _predict_one( + value: L2HeldoutEndpointFrame, + state: LockedL2EndpointState, +) -> pl.DataFrame: + eligible = _validate_frame_for_state(value, state) + matrix = eligible.select(state.feature_columns).to_numpy().astype(np.float64, copy=False) + if not np.isfinite(matrix).all(): + raise L2LockedEvaluationError("held-out fitted-state features must be finite") + selected_raw, selected_probability = state.fitted_state.predict("selected", matrix) + prior_raw, prior_probability = state.fitted_state.predict("historical_prior", matrix) + for label, probability in ( + ("selected raw", selected_raw), + ("selected calibrated", selected_probability), + ("prior raw", prior_raw), + ("prior calibrated", prior_probability), + ): + if probability.shape != (eligible.height,) or not np.isfinite(probability).all(): + raise L2LockedEvaluationError(f"{label} predictions are not finite row-aligned data") + if bool(np.any((probability < 0.0) | (probability > 1.0))): + raise L2LockedEvaluationError(f"{label} predictions escape the probability interval") + selected_cutoff = state.fit_cutoff("selected") + prior_cutoff = state.fit_cutoff("historical_prior") + identity_columns = ( + "sample_id", + "symbol", + "study_date", + "study_role", + "endpoint_name", + "endpoint_domain", + "endpoint_horizon_value", + "endpoint_horizon_unit", + "continuity_id", + "observed_interval_id", + "observed_interval_start_ns", + "observed_interval_end_ns_exclusive", + "decision_ts_ns", + "decision_sequence", + "volatility_regime", + "liquidity_regime", + "joint_market_regime", + "ofi_signed_future_mid_markout_bps", + "_endpoint_event_ordinal", + ) + return ( + eligible.select(*identity_columns, pl.col(_TARGET).cast(pl.Int8).alias("y_true")) + .with_columns( + pl.Series("selected_raw_probability", selected_raw), + pl.Series("selected_probability", selected_probability), + pl.Series("prior_raw_probability", prior_raw), + pl.Series("prior_probability", prior_probability), + pl.lit(state.selected_model).alias("selected_model"), + pl.lit("historical_prior").alias("baseline_model"), + pl.lit(selected_cutoff, dtype=pl.Int64).alias("selected_fit_cutoff_ts_ns"), + pl.lit(prior_cutoff, dtype=pl.Int64).alias("prior_fit_cutoff_ts_ns"), + pl.lit(state.child_lock_sha256).alias("child_lock_sha256"), + pl.lit(state.aggregate_lock_sha256).alias("aggregate_lock_sha256"), + pl.lit(state.regime_thresholds_sha256).alias("regime_thresholds_sha256"), + pl.lit(state.fitted_state.sha256).alias("fitted_state_sha256"), + pl.lit(state.endpoint.impact_ofi_window, dtype=pl.Int64).alias( + "endpoint_impact_ofi_window" + ), + pl.lit(True).alias("is_oos"), + pl.lit("final_test").alias("split"), + pl.lit(False).alias("test_used_for_selection"), + pl.lit(False).alias("model_updated_between_test_dates"), + pl.lit(False).alias("p_value_computed"), + pl.lit(False).alias("significance_claim_authorized"), + ) + .sort("study_date", "symbol", "endpoint_name", "decision_ts_ns", "decision_sequence") + ) + + +def _metric_rows(predictions: pl.DataFrame, *, calibration_bins: int) -> list[dict[str, object]]: + rows: list[dict[str, object]] = [] + partitions = predictions.partition_by( + ["symbol", "study_date", "study_role", "endpoint_name"], maintain_order=True + ) + for frame in partitions: + y_true = frame["y_true"].to_numpy().astype(np.int64, copy=False) + specifications = ( + ( + "selected", + str(frame["selected_model"][0]), + "selected_probability", + int(frame["selected_fit_cutoff_ts_ns"][0]), + ), + ( + "historical_prior", + "historical_prior", + "prior_probability", + int(frame["prior_fit_cutoff_ts_ns"][0]), + ), + ) + for role, model, probability_column, cutoff in specifications: + probability = frame[probability_column].to_numpy().astype(np.float64, copy=False) + rows.append( + { + "symbol": str(frame["symbol"][0]), + "study_date": str(frame["study_date"][0]), + "study_role": str(frame["study_role"][0]), + "endpoint_name": str(frame["endpoint_name"][0]), + "endpoint_domain": str(frame["endpoint_domain"][0]), + "endpoint_horizon_value": int(frame["endpoint_horizon_value"][0]), + "endpoint_horizon_unit": str(frame["endpoint_horizon_unit"][0]), + "model_role": role, + "model": model, + "baseline": "historical_prior", + "n_obs": frame.height, + "period_start_ts_ns": int(cast(int, frame["decision_ts_ns"].min())), + "period_end_ts_ns": int(cast(int, frame["decision_ts_ns"].max())), + "fit_cutoff_ts_ns": cutoff, + "child_lock_sha256": str(frame["child_lock_sha256"][0]), + "aggregate_lock_sha256": str(frame["aggregate_lock_sha256"][0]), + "regime_thresholds_sha256": str(frame["regime_thresholds_sha256"][0]), + "fitted_state_sha256": str(frame["fitted_state_sha256"][0]), + "is_oos": True, + "test_used_for_selection": False, + "model_updated_between_test_dates": False, + "p_value": None, + "p_value_computed": False, + "significance_claim_authorized": False, + **classification_metrics( + y_true, + probability, + calibration_bins=calibration_bins, + ), + } + ) + return rows + + +def _loss(probability: NDArray[np.float64], target: NDArray[np.int64]) -> NDArray[np.float64]: + clipped = np.clip(probability, 1e-12, 1.0 - 1e-12) + return np.asarray( + -(target * np.log(clipped) + (1 - target) * np.log1p(-clipped)), + dtype=np.float64, + ) + + +def _window_sufficient_statistics( + coordinate: NDArray[np.int64], + starts: NDArray[np.int64], + width: int, + selected_loss: NDArray[np.float64], + prior_loss: NDArray[np.float64], + included: NDArray[np.bool_], +) -> NDArray[np.float64]: + """Return O(n + candidates) window sums without materializing event rows.""" + + if width < 1: + raise L2LockedEvaluationError("moving-block width must be positive") + selected_prefix = np.concatenate( + (np.zeros(1, dtype=np.float64), np.cumsum(selected_loss * included)) + ) + prior_prefix = np.concatenate((np.zeros(1, dtype=np.float64), np.cumsum(prior_loss * included))) + count_prefix = np.concatenate( + (np.zeros(1, dtype=np.int64), np.cumsum(included, dtype=np.int64)) + ) + left = np.searchsorted(coordinate, starts, side="left") + right = np.searchsorted(coordinate, starts + width, side="left") + return np.column_stack( + ( + selected_prefix[right] - selected_prefix[left], + prior_prefix[right] - prior_prefix[left], + count_prefix[right] - count_prefix[left], + ) + ) + + +def _moving_block_intervals( + frame: pl.DataFrame, + endpoint: L2EndpointSpec, + selected_loss: NDArray[np.float64], + prior_loss: NDArray[np.float64], + included: NDArray[np.bool_], +) -> tuple[tuple[_MovingBlockInterval, ...], int, bool]: + """Build interval-local overlapping candidates from prefix-sum statistics. + + Event windows use the ordinal assigned before model-row/regime filtering, + so sparse rows never compress a frozen dependency width. Clock candidates + start only at observed decisions and use half-open wall-time windows. Empty + regime candidates are discarded, but candidates are never pooled across + verified observed intervals. + """ + + identity = ["study_date", "symbol", "continuity_id", "observed_interval_id"] + ordered = frame.with_row_index("_moving_block_row").sort( + *identity, "decision_ts_ns", "decision_sequence" + ) + intervals: list[_MovingBlockInterval] = [] + candidate_count = 0 + unsupported_interval = False + for current in ordered.partition_by(identity, maintain_order=True): + indices = current["_moving_block_row"].to_numpy().astype(np.int64, copy=False) + current_selected = selected_loss[indices] + current_prior = prior_loss[indices] + current_included = included[indices] + if not bool(current_included.any()): + continue + if endpoint.domain == "event": + width = endpoint.paired_block_events + if width is None or width < 1: + raise L2LockedEvaluationError("event endpoint has no frozen event block width") + coordinate = current["_endpoint_event_ordinal"].to_numpy().astype(np.int64, copy=False) + if bool(np.any(coordinate < 0)) or bool(np.any(np.diff(coordinate) <= 0)): + raise L2LockedEvaluationError( + "event moving-block ordinals must be bounded and strictly increasing" + ) + domain_start = int(coordinate[0]) + domain_end = int(coordinate[-1]) + 1 + domain_span = domain_end - domain_start + if domain_span < width: + unsupported_interval = True + continue + starts = np.arange(domain_start, domain_end - width + 1, dtype=np.int64) + full = _window_sufficient_statistics( + coordinate, + starts, + width, + current_selected, + current_prior, + current_included, + ) + nonempty = full[:, 2] > 0.0 + full = full[nonempty] + starts = starts[nonempty] + if full.shape[0] == 0: + unsupported_interval = True + continue + blocks_per_draw = math.ceil(domain_span / width) + remainder = domain_span % width + tail = ( + _window_sufficient_statistics( + coordinate, + starts, + remainder, + current_selected, + current_prior, + current_included, + ) + if remainder + else None + ) + else: + width_ms = endpoint.paired_block_milliseconds + if width_ms is None or width_ms < 1: + raise L2LockedEvaluationError("clock endpoint has no frozen wall-time block width") + width = width_ms * _NANOSECONDS_PER_MILLISECOND + coordinate = current["decision_ts_ns"].to_numpy().astype(np.int64, copy=False) + interval_start = int(current["observed_interval_start_ns"][0]) + interval_end = int(current["observed_interval_end_ns_exclusive"][0]) + if ( + interval_start < 0 + or interval_end <= interval_start + or bool(np.any(coordinate < interval_start)) + or bool(np.any(coordinate >= interval_end)) + or bool(np.any(np.diff(coordinate) < 0)) + ): + raise L2LockedEvaluationError("clock moving-block coordinates are invalid") + interval_span = interval_end - interval_start + legal = coordinate <= interval_end - width + starts = coordinate[legal] + if interval_span < width or starts.size == 0: + unsupported_interval = True + continue + full = _window_sufficient_statistics( + coordinate, + starts, + width, + current_selected, + current_prior, + current_included, + ) + full = full[full[:, 2] > 0.0] + if full.shape[0] == 0: + unsupported_interval = True + continue + blocks_per_draw = math.ceil(interval_span / width) + tail = None + candidate_count += int(full.shape[0]) + intervals.append( + _MovingBlockInterval( + full=np.asarray(full, dtype=np.float64), + tail=(np.asarray(tail, dtype=np.float64) if tail is not None else None), + blocks_per_draw=blocks_per_draw, + ) + ) + return tuple(intervals), candidate_count, unsupported_interval + + +def _paired_delta( + frame: pl.DataFrame, + endpoint: L2EndpointSpec, + *, + regime: str, + samples: int, + seed: int, +) -> _PairedDelta: + included = ( + np.ones(frame.height, dtype=np.bool_) + if regime == _ALL_REGIME + else frame["joint_market_regime"].to_numpy() == regime + ) + n_obs = int(np.count_nonzero(included)) + if n_obs == 0: + return _PairedDelta( + None, None, None, None, None, 0, 0, samples, seed, "empty_regime", np.empty(0) + ) + target = frame["y_true"].to_numpy().astype(np.int64, copy=False) + selected_loss = _loss( + frame["selected_probability"].to_numpy().astype(np.float64, copy=False), target + ) + prior_loss = _loss(frame["prior_probability"].to_numpy().astype(np.float64, copy=False), target) + selected_point = float(selected_loss[included].mean()) + prior_point = float(prior_loss[included].mean()) + point = selected_point - prior_point + intervals, n_blocks, unsupported = _moving_block_intervals( + frame, + endpoint, + selected_loss, + prior_loss, + included, + ) + has_sampling_choice = any(value.full.shape[0] > 1 for value in intervals) + if unsupported or not intervals or not has_sampling_choice: + return _PairedDelta( + selected_point, + prior_point, + point, + None, + None, + n_obs, + n_blocks, + samples, + seed, + "insufficient_blocks", + np.empty(0), + ) + random = np.random.default_rng(seed) + draws = np.empty(samples, dtype=np.float64) + # Resample bounded block sufficient statistics, never per-draw event rows. + # Each interval has an independent draw and is therefore never pooled with + # another continuity/OBSERVED interval. + for draw_index in range(samples): + totals = np.zeros(3, dtype=np.float64) + for interval in intervals: + sampled = random.integers( + 0, + interval.full.shape[0], + size=interval.blocks_per_draw, + ) + if interval.tail is None: + totals += interval.full[sampled].sum(axis=0) + else: + if sampled.size > 1: + totals += interval.full[sampled[:-1]].sum(axis=0) + totals += interval.tail[sampled[-1]] + if totals[2] <= 0.0: + raise L2LockedEvaluationError("moving-block draw has no regime observations") + draws[draw_index] = totals[0] / totals[2] - totals[1] / totals[2] + return _PairedDelta( + selected_point, + prior_point, + point, + float(np.quantile(draws, 0.025)), + float(np.quantile(draws, 0.975)), + n_obs, + n_blocks, + samples, + seed, + "ok", + draws, + ) + + +def _diagnostics( + predictions: pl.DataFrame, + states: Mapping[tuple[str, str], LockedL2EndpointState], + *, + samples: int, + seed: int, +) -> tuple[pl.DataFrame, pl.DataFrame, pl.DataFrame]: + per_session_rows: list[dict[str, object]] = [] + markout_rows: list[dict[str, object]] = [] + draws_by_key: dict[tuple[str, str, str, str], _PairedDelta] = {} + partitions = predictions.partition_by( + ["symbol", "study_date", "study_role", "endpoint_name"], maintain_order=True + ) + for raw in partitions: + symbol = str(raw["symbol"][0]) + study_date = str(raw["study_date"][0]) + study_role = str(raw["study_role"][0]) + endpoint_name = str(raw["endpoint_name"][0]) + state = states[(symbol, endpoint_name)] + blocked = raw.sort( + "study_date", + "symbol", + "continuity_id", + "observed_interval_id", + "decision_ts_ns", + "decision_sequence", + ) + for regime in (_ALL_REGIME, *_EXPECTED_REGIMES): + current = ( + blocked + if regime == _ALL_REGIME + else blocked.filter(pl.col("joint_market_regime") == regime) + ) + row_seed = _stable_seed(seed, symbol, study_date, endpoint_name, regime) + paired = _paired_delta( + blocked, + state.endpoint, + regime=regime, + samples=samples, + seed=row_seed, + ) + draws_by_key[(symbol, endpoint_name, regime, study_role)] = paired + block_width: int + block_unit: str + if state.endpoint.domain == "event": + block_width = cast(int, state.endpoint.paired_block_events) + block_unit = "events" + else: + block_width = cast(int, state.endpoint.paired_block_milliseconds) + block_unit = "milliseconds" + per_session_rows.append( + { + "symbol": symbol, + "study_date": study_date, + "study_role": study_role, + "endpoint_name": endpoint_name, + "endpoint_domain": state.endpoint.domain, + "regime": regime, + "regime_scope": "overall" if regime == _ALL_REGIME else "train_defined_joint", + "selected_model": state.selected_model, + "baseline": "historical_prior", + "metric": "log_loss", + "delta_definition": "selected_minus_historical_prior", + "selected_log_loss": paired.selected_log_loss, + "prior_log_loss": paired.prior_log_loss, + "point_delta": paired.point_delta, + "ci_low": paired.ci_low, + "ci_high": paired.ci_high, + "n_obs": paired.n_obs, + "n_blocks": paired.n_blocks, + "samples": paired.samples, + "seed": paired.seed, + "bootstrap_status": paired.status, + "block_width": block_width, + "block_unit": block_unit, + "date_weight": 0.5, + "point_favorable": ( + paired.point_delta < 0.0 if paired.point_delta is not None else False + ), + "child_lock_sha256": state.child_lock_sha256, + "aggregate_lock_sha256": state.aggregate_lock_sha256, + "regime_thresholds_sha256": state.regime_thresholds_sha256, + "p_value": None, + "p_value_computed": False, + "h0_rejected": False, + "significance_claim_authorized": False, + "cross_symbol_pooling": False, + } + ) + markout = current["ofi_signed_future_mid_markout_bps"].drop_nulls() + markout_rows.append( + { + "symbol": symbol, + "study_date": study_date, + "study_role": study_role, + "endpoint_name": endpoint_name, + "regime": regime, + "n_obs": len(markout), + "mean_ofi_signed_future_mid_markout_bps": ( + float(cast(Any, markout.mean())) if len(markout) else None + ), + "median_ofi_signed_future_mid_markout_bps": ( + float(cast(Any, markout.median())) if len(markout) else None + ), + "positive_fraction": ( + float(cast(Any, (markout > 0.0).mean())) if len(markout) else None + ), + "metric": "ofi_signed_future_mid_markout", + "descriptive_only": True, + "observed_trade_impact": False, + "child_lock_sha256": state.child_lock_sha256, + "aggregate_lock_sha256": state.aggregate_lock_sha256, + "regime_thresholds_sha256": state.regime_thresholds_sha256, + "p_value_computed": False, + "significance_claim_authorized": False, + } + ) + + aggregate_rows: list[dict[str, object]] = [] + for (symbol, endpoint_name), state in sorted(states.items()): + for regime in (_ALL_REGIME, *_EXPECTED_REGIMES): + primary = draws_by_key.get((symbol, endpoint_name, regime, "primary_test")) + replication = draws_by_key.get((symbol, endpoint_name, regime, "replication_test")) + if primary is None or replication is None: + raise L2LockedEvaluationError("paired diagnostics lack a declared held-out role") + points = (primary.point_delta, replication.point_delta) + complete_points = all(value is not None for value in points) + point = ( + 0.5 * cast(float, points[0]) + 0.5 * cast(float, points[1]) + if complete_points + else None + ) + bootstrap_ok = primary.status == "ok" and replication.status == "ok" + if bootstrap_ok: + aggregate_draws = 0.5 * primary.draws + 0.5 * replication.draws + ci_low = float(np.quantile(aggregate_draws, 0.025)) + ci_high = float(np.quantile(aggregate_draws, 0.975)) + status = "ok" + else: + ci_low = None + ci_high = None + status = ( + "empty_regime" + if primary.status == "empty_regime" or replication.status == "empty_regime" + else "insufficient_blocks" + ) + primary_favorable = primary.point_delta is not None and primary.point_delta < 0.0 + replication_favorable = ( + replication.point_delta is not None and replication.point_delta < 0.0 + ) + replicated = primary_favorable and replication_favorable + if not complete_points: + replication_status = "insufficient_data" + elif replicated: + replication_status = "replicated" + elif not primary_favorable: + replication_status = "no_primary_improvement" + else: + replication_status = "failed_replication" + aggregate_rows.append( + { + "symbol": symbol, + "endpoint_name": endpoint_name, + "endpoint_domain": state.endpoint.domain, + "regime": regime, + "regime_scope": "overall" if regime == _ALL_REGIME else "train_defined_joint", + "selected_model": state.selected_model, + "baseline": "historical_prior", + "metric": "log_loss", + "delta_definition": "selected_minus_historical_prior", + "date_weighting": "equal_primary_replication", + "primary_weight": 0.5, + "replication_weight": 0.5, + "primary_point_delta": primary.point_delta, + "replication_point_delta": replication.point_delta, + "point_delta": point, + "ci_low": ci_low, + "ci_high": ci_high, + "n_obs": primary.n_obs + replication.n_obs, + "n_sessions": 2, + "n_blocks": primary.n_blocks + replication.n_blocks, + "samples": samples, + "bootstrap_status": status, + "directionally_replicated": replicated, + "replication_status": replication_status, + "child_lock_sha256": state.child_lock_sha256, + "aggregate_lock_sha256": state.aggregate_lock_sha256, + "regime_thresholds_sha256": state.regime_thresholds_sha256, + "p_value": None, + "p_value_computed": False, + "h0_rejected": False, + "significance_claim_authorized": False, + "cross_symbol_pooling": False, + } + ) + return ( + pl.DataFrame(per_session_rows, infer_schema_length=None).sort( + "symbol", "endpoint_name", "regime", "study_date" + ), + pl.DataFrame(aggregate_rows, infer_schema_length=None).sort( + "symbol", "endpoint_name", "regime" + ), + pl.DataFrame(markout_rows, infer_schema_length=None).sort( + "symbol", "endpoint_name", "regime", "study_date" + ), + ) + + +def evaluate_locked_l2_endpoints( + locked_states: Sequence[LockedL2EndpointState], + heldout_frames: Sequence[L2HeldoutEndpointFrame], + *, + bootstrap_samples: int = 2_000, + seed: int = 20_260_807, + calibration_bins: int = 10, +) -> L2EvaluationResult: + """Evaluate all declared held-out frames without exposing any fitting path.""" + + if bootstrap_samples != 2_000: + raise L2LockedEvaluationError("M8 L2 bootstrap samples are frozen at 2000") + if calibration_bins != 10: + raise L2LockedEvaluationError("M8 L2 calibration bins are frozen at 10") + states = tuple(locked_states) + frames = tuple(heldout_frames) + if not states or not frames: + raise L2LockedEvaluationError("locked states and held-out frames must be nonempty") + by_state: dict[tuple[str, str], LockedL2EndpointState] = {} + for state in states: + key = _state_key(state) + if key in by_state: + raise L2LockedEvaluationError(f"duplicate locked L2 endpoint state: {key}") + by_state[key] = state + aggregate_hashes = {state.aggregate_lock_sha256 for state in states} + if len(aggregate_hashes) != 1: + raise L2LockedEvaluationError("all endpoint states must share one aggregate lock") + by_frame: dict[tuple[str, str, HeldoutRole], L2HeldoutEndpointFrame] = {} + for frame in frames: + frame_key = _frame_key(frame) + if frame_key in by_frame: + raise L2LockedEvaluationError(f"duplicate held-out L2 endpoint frame: {frame_key}") + by_frame[frame_key] = frame + expected = { + (symbol, endpoint, cast(HeldoutRole, role)) + for symbol, endpoint in by_state + for role in ("primary_test", "replication_test") + } + if set(by_frame) != expected: + raise L2LockedEvaluationError( + "held-out frames differ from the exact primary/replication locked endpoint set" + ) + predictions = pl.concat( + [ + _predict_one(by_frame[(symbol, endpoint, role)], state) + for (symbol, endpoint), state in sorted(by_state.items()) + for role in cast(tuple[HeldoutRole, ...], ("primary_test", "replication_test")) + ], + how="vertical_relaxed", + ).sort("symbol", "endpoint_name", "study_date", "decision_ts_ns", "decision_sequence") + if predictions["sample_id"].n_unique() != predictions.height: + raise L2LockedEvaluationError("held-out sample identities collide across endpoint frames") + metrics = pl.DataFrame( + _metric_rows(predictions, calibration_bins=calibration_bins), infer_schema_length=None + ).sort("symbol", "endpoint_name", "study_date", "model_role") + paired, aggregate, markout = _diagnostics( + predictions, + by_state, + samples=bootstrap_samples, + seed=seed, + ) + return L2EvaluationResult( + predictions=_null_nonfinite(predictions), + predictive_metrics=_null_nonfinite(metrics), + paired_by_session_regime=_null_nonfinite(paired), + equal_session_summary=_null_nonfinite(aggregate), + signed_markout=_null_nonfinite(markout), + ) + + +def _metadata_columns( + frame: pl.DataFrame, + *, + scenario_id: str, + symbol: str, + study_date: str, + study_role: str, + endpoint_name: str, + decision_latency: int, + order_latency: int, + reference: L2ExecutionReference, + child_lock_sha256: str, +) -> pl.DataFrame: + return frame.with_columns( + pl.lit(scenario_id).alias("scenario_id"), + pl.lit(symbol).alias("scenario_symbol"), + pl.lit(study_date).alias("study_date"), + pl.lit(study_role).alias("study_role"), + pl.lit(endpoint_name).alias("endpoint_name"), + pl.lit(decision_latency, dtype=pl.Int64).alias("decision_latency_events"), + pl.lit(order_latency, dtype=pl.Int64).alias("order_latency_events"), + pl.lit(reference.reference_quantity).alias("reference_quantity"), + pl.lit(reference.training_date).alias("execution_reference_training_date"), + pl.lit(reference.reference_price_statistic).alias("reference_price_statistic"), + pl.lit(reference.reference_depth_statistic).alias("reference_depth_statistic"), + pl.lit(reference.analysis_config_source_sha256).alias("analysis_config_source_sha256"), + pl.lit(reference.analysis_config_semantic_sha256).alias("analysis_config_semantic_sha256"), + pl.lit(reference.reference_sha256).alias("execution_reference_sha256"), + pl.lit(child_lock_sha256).alias("child_lock_sha256"), + pl.lit(reference.aggregate_lock_sha256).alias("aggregate_lock_sha256"), + ) + + +def _json(value: object) -> str: + return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False) + + +def run_locked_l2_market_execution( + evaluation: L2EvaluationResult, + heldout_frames: Sequence[L2HeldoutEndpointFrame], + references: Sequence[L2ExecutionReference], + *, + decision_latency_events: Sequence[int] = _EXPECTED_EVENT_LATENCIES, + order_latency_events: Sequence[int] = _EXPECTED_EVENT_LATENCIES, + probability_threshold: float = 0.55, + taker_fee_bps: float = 4.0, + inventory_order_multiples: int = 10, +) -> L2MarketExecutionResult: + """Replay selected OOS predictions over the frozen market-only event grid.""" + + decisions = tuple(decision_latency_events) + orders = tuple(order_latency_events) + if decisions != _EXPECTED_EVENT_LATENCIES or orders != _EXPECTED_EVENT_LATENCIES: + raise L2LockedEvaluationError("M8 L2 latency grids are frozen at event counts 0, 1, 5") + if probability_threshold != 0.55 or taker_fee_bps != 4.0: + raise L2LockedEvaluationError("M8 L2 probability threshold and taker fee are frozen") + if inventory_order_multiples != 10: + raise L2LockedEvaluationError("M8 L2 inventory bound is frozen at ten order multiples") + _require( + evaluation.predictions, + ( + "symbol", + "study_date", + "study_role", + "endpoint_name", + "decision_sequence", + "selected_probability", + "is_oos", + "split", + "child_lock_sha256", + "aggregate_lock_sha256", + "endpoint_impact_ofi_window", + ), + "locked L2 predictions", + ) + if not bool(evaluation.predictions["is_oos"].all()) or set( + evaluation.predictions["split"].unique() + ) != {"final_test"}: + raise L2LockedEvaluationError("market scenarios require only explicit held-out OOS rows") + frame_map = {_frame_key(value): value for value in heldout_frames} + if len(frame_map) != len(tuple(heldout_frames)): + raise L2LockedEvaluationError("execution frames contain duplicate coordinates") + reference_map: dict[str, L2ExecutionReference] = {} + for reference in references: + if reference.symbol in reference_map: + raise L2LockedEvaluationError("execution references contain duplicate symbols") + reference_map[reference.symbol] = reference + prediction_keys = { + (str(row["symbol"]), str(row["endpoint_name"]), str(row["study_role"])) + for row in evaluation.predictions.select("symbol", "endpoint_name", "study_role") + .unique() + .to_dicts() + } + if set(frame_map) != prediction_keys: + raise L2LockedEvaluationError("execution frames differ from evaluated held-out coordinates") + if set(reference_map) != {symbol for symbol, _, _ in prediction_keys}: + raise L2LockedEvaluationError("execution references differ from evaluated symbols") + + order_frames: list[pl.DataFrame] = [] + fill_frames: list[pl.DataFrame] = [] + position_frames: list[pl.DataFrame] = [] + metric_rows: list[dict[str, object]] = [] + assumption_rows: list[dict[str, object]] = [] + for symbol, endpoint_name, role in sorted(prediction_keys): + coordinate = cast(tuple[str, str, HeldoutRole], (symbol, endpoint_name, role)) + heldout = frame_map[coordinate] + reference = reference_map[symbol] + if reference.training_date >= heldout.study_date: + raise L2LockedEvaluationError( + "execution reference training date must precede every held-out session" + ) + current_predictions = evaluation.predictions.filter( + (pl.col("symbol") == symbol) + & (pl.col("endpoint_name") == endpoint_name) + & (pl.col("study_role") == role) + ) + try: + validate_l2_endpoint_frame(heldout.frame) + except L2ResearchError as error: + raise L2LockedEvaluationError(str(error)) from error + frame_coordinate = heldout.frame.select( + "symbol", "study_date", "study_role", "endpoint_name" + ).unique() + expected_coordinate = { + "symbol": symbol, + "study_date": heldout.study_date, + "study_role": role, + "endpoint_name": endpoint_name, + } + if frame_coordinate.height != 1 or frame_coordinate.row(0, named=True) != ( + expected_coordinate + ): + raise L2LockedEvaluationError( + "execution event frame differs from its evaluated coordinate" + ) + if heldout.frame.filter(pl.col("continuity_id") != pl.col("observed_interval_id")).height: + raise L2LockedEvaluationError( + "execution continuity must equal the verified observed interval" + ) + evaluated_identity = current_predictions.select("sample_id", "decision_sequence").sort( + "decision_sequence" + ) + replay_identity = ( + heldout.frame.join(evaluated_identity.select("sample_id"), on="sample_id", how="inner") + .select("sample_id", "decision_sequence") + .sort("decision_sequence") + ) + if not replay_identity.equals(evaluated_identity): + raise L2LockedEvaluationError( + "execution event frame is not row-identical to evaluated predictions" + ) + aggregate_hashes = set( + str(value) for value in current_predictions["aggregate_lock_sha256"].unique() + ) + child_hashes = set( + str(value) for value in current_predictions["child_lock_sha256"].unique() + ) + if aggregate_hashes != {reference.aggregate_lock_sha256} or len(child_hashes) != 1: + raise L2LockedEvaluationError("execution reference and prediction locks disagree") + _require( + heldout.frame, + ( + "decision_ts_ns", + "decision_sequence", + "continuity_id", + "best_bid", + "best_ask", + "bid_quantity", + "ask_quantity", + "mid_price", + "tick_size", + "lot_size", + ), + "L2 execution event frame", + ) + observed_lots = heldout.frame["lot_size"].drop_nulls().unique().to_list() + if len(observed_lots) != 1 or not math.isclose( + float(observed_lots[0]), reference.lot_size, rel_tol=0.0, abs_tol=1e-15 + ): + raise L2LockedEvaluationError("execution reference lot size differs from held-out data") + event_columns = [name for name in heldout.frame.columns if name != "event_ts_ns"] + events = ( + heldout.frame.select(*event_columns) + .with_columns(pl.col("decision_ts_ns").alias("event_ts_ns")) + .sort("decision_ts_ns", "decision_sequence") + ) + simulation_predictions = current_predictions.select( + "symbol", + "decision_sequence", + pl.col("selected_probability").alias("probability"), + "is_oos", + "split", + ) + for decision_latency in decisions: + for order_latency in orders: + scenario_id = ( + f"{symbol}::{heldout.study_date}::{endpoint_name}::" + f"d{decision_latency}::o{order_latency}" + ) + execution_config = ExecutionConfig( + decision_latency_events=decision_latency, + order_latency_events=order_latency, + maker_fee_bps=0.0, + taker_fee_bps=taker_fee_bps, + half_spread_bps=0.0, + slippage_bps_per_unit=0.0, + signal_threshold=probability_threshold, + max_position_units=(reference.reference_quantity * inventory_order_multiples), + order_size_units=reference.reference_quantity, + limit_fill_base_probability=0.0, + queue_ahead_units=0.0, + limit_max_age_events=1, + cancel_latency_events=0, + liquidate_at_end=True, + capacity_multipliers=(1.0,), + ) + result = simulate_predictions( + events, + simulation_predictions, + execution_config, + order_type="market", + size_multiplier=1.0, + seed=_stable_seed(20_260_807, scenario_id), + markout_events=int(current_predictions["endpoint_impact_ofi_window"][0]), + ) + child_hash = next(iter(child_hashes)) + scenario_orders = _metadata_columns( + result.orders, + scenario_id=scenario_id, + symbol=symbol, + study_date=heldout.study_date, + study_role=role, + endpoint_name=endpoint_name, + decision_latency=decision_latency, + order_latency=order_latency, + reference=reference, + child_lock_sha256=child_hash, + ) + if "order_type" in scenario_orders.columns and set( + scenario_orders["order_type"].drop_nulls().unique() + ).difference({"market"}): + raise L2LockedEvaluationError("market-only replay emitted a non-market order") + scenario_fills = _metadata_columns( + result.fills, + scenario_id=scenario_id, + symbol=symbol, + study_date=heldout.study_date, + study_role=role, + endpoint_name=endpoint_name, + decision_latency=decision_latency, + order_latency=order_latency, + reference=reference, + child_lock_sha256=child_hash, + ) + if "liquidity" in scenario_fills.columns and set( + scenario_fills["liquidity"].drop_nulls().unique() + ).difference({"taker"}): + raise L2LockedEvaluationError("market-only replay emitted a maker fill") + scenario_positions = _metadata_columns( + result.positions, + scenario_id=scenario_id, + symbol=symbol, + study_date=heldout.study_date, + study_role=role, + endpoint_name=endpoint_name, + decision_latency=decision_latency, + order_latency=order_latency, + reference=reference, + child_lock_sha256=child_hash, + ) + order_frames.append(scenario_orders) + fill_frames.append(scenario_fills) + position_frames.append(scenario_positions) + metric_rows.append( + { + "scenario_id": scenario_id, + "symbol": symbol, + "study_date": heldout.study_date, + "study_role": role, + "endpoint_name": endpoint_name, + "decision_latency_events": decision_latency, + "order_latency_events": order_latency, + "order_type": "market", + "strategy_orders": result.metrics["strategy_orders"], + "strategy_fills": result.metrics["strategy_fills"], + "forced_liquidation_fills": result.metrics["forced_liquidation_fills"], + "requested_quantity": result.metrics["requested_quantity"], + "accepted_quantity": result.metrics["accepted_quantity"], + "filled_quantity": result.metrics["filled_quantity"], + "fill_ratio": result.metrics["fill_ratio"], + "fill_ratio_requested": result.metrics["fill_ratio_requested"], + "partial_fill_order_ratio": result.metrics["partial_fill_order_ratio"], + "gross_pnl": result.metrics["gross_pnl"], + "total_fees": result.metrics["total_fees"], + "net_pnl": result.metrics["net_pnl"], + "turnover_notional": result.metrics["turnover_notional"], + "maximum_drawdown": result.metrics["maximum_drawdown"], + "maximum_absolute_inventory": result.metrics["maximum_absolute_inventory"], + "forced_liquidation_quantity": result.metrics[ + "forced_liquidation_quantity" + ], + "unliquidated_quantity": result.metrics["unliquidated_quantity"], + "mean_arrival_cost_bps": result.metrics["mean_arrival_cost_bps"], + "mean_post_fill_markout_bps": result.metrics["mean_post_fill_markout_bps"], + "reference_quantity": reference.reference_quantity, + "execution_reference_training_date": reference.training_date, + "reference_price_statistic": reference.reference_price_statistic, + "reference_depth_statistic": reference.reference_depth_statistic, + "analysis_config_source_sha256": (reference.analysis_config_source_sha256), + "analysis_config_semantic_sha256": ( + reference.analysis_config_semantic_sha256 + ), + "inventory_limit_units": ( + reference.reference_quantity * inventory_order_multiples + ), + "execution_reference_sha256": reference.reference_sha256, + "child_lock_sha256": child_hash, + "aggregate_lock_sha256": reference.aggregate_lock_sha256, + "scenario_only": True, + "capacity_claim_authorized": False, + "realized_execution_claim_authorized": False, + "profitability_claim_authorized": False, + } + ) + assumption_rows.append( + { + "scenario_id": scenario_id, + "symbol": symbol, + "study_date": heldout.study_date, + "study_role": role, + "endpoint_name": endpoint_name, + "market_orders_only": True, + "probability_buy_threshold": probability_threshold, + "probability_sell_threshold": 1.0 - probability_threshold, + "decision_latency_events": decision_latency, + "order_latency_events": order_latency, + "taker_fee_bps": taker_fee_bps, + "reference_quantity": reference.reference_quantity, + "reference_mid_price": reference.reference_mid_price, + "train_l1_depth_q05": reference.train_l1_depth_q05, + "execution_reference_training_date": reference.training_date, + "reference_price_statistic": reference.reference_price_statistic, + "reference_depth_statistic": reference.reference_depth_statistic, + "analysis_config_source_sha256": (reference.analysis_config_source_sha256), + "analysis_config_semantic_sha256": ( + reference.analysis_config_semantic_sha256 + ), + "max_l1_participation": 0.10, + "inventory_order_multiples": inventory_order_multiples, + "extra_slippage_bps": 0.0, + "l1_fill_policy": "fill_up_to_recorded_l1_depth_cancel_remainder", + "scenario_reset_policy": ("per_symbol_session_endpoint_latency_pair"), + "end_liquidation": True, + "replay_is_exogenous": True, + "live_trading": False, + "limit_fill_model": "NOT_RUN", + "capacity_sensitivity": "NOT_RUN", + "execution_reference_sha256": reference.reference_sha256, + "child_lock_sha256": child_hash, + "aggregate_lock_sha256": reference.aggregate_lock_sha256, + "simulator_assumptions_json": _json(result.assumptions), + "capacity_claim_authorized": False, + "realized_execution_claim_authorized": False, + "profitability_claim_authorized": False, + } + ) + + concatenated_orders = ( + pl.concat(order_frames, how="diagonal_relaxed") if order_frames else pl.DataFrame() + ) + concatenated_fills = ( + pl.concat(fill_frames, how="diagonal_relaxed") if fill_frames else pl.DataFrame() + ) + concatenated_positions = ( + pl.concat(position_frames, how="diagonal_relaxed") if position_frames else pl.DataFrame() + ) + return L2MarketExecutionResult( + orders=_null_nonfinite(concatenated_orders), + fills=_null_nonfinite(concatenated_fills), + positions=_null_nonfinite(concatenated_positions), + metrics=_null_nonfinite( + pl.DataFrame(metric_rows, infer_schema_length=None).sort("scenario_id") + ), + assumptions=_null_nonfinite( + pl.DataFrame(assumption_rows, infer_schema_length=None).sort("scenario_id") + ), + ) + + +__all__ = [ + "L2EvaluationResult", + "L2ExecutionReference", + "L2HeldoutEndpointFrame", + "L2LockedEvaluationError", + "L2MarketExecutionResult", + "LockedL2EndpointState", + "evaluate_locked_l2_endpoints", + "run_locked_l2_market_execution", +] diff --git a/Microstructure/src/microstructure/research/l2_multidate.py b/Microstructure/src/microstructure/research/l2_multidate.py new file mode 100644 index 0000000000000000000000000000000000000000..f04a39236c228dae22e86bcf2e19a0c33f115e49 --- /dev/null +++ b/Microstructure/src/microstructure/research/l2_multidate.py @@ -0,0 +1,718 @@ +"""Outcome-blind causal frames for the prospective four-session L2 study. + +The capture continuity identifier is not sufficient for research: a period of +silence may split one capture epoch into several intervals that are actually +backed by continuously observed book states. This module therefore resegments +both books and deltas by the verified OBSERVED intervals before any rolling +feature or future label is calculated. + +Clock labels are exact-horizon labels. They use the last state observable at +``t+h`` (never the first state after it), require the target to remain inside +the same verified interval, and censor stale carried-forward states. +""" + +from __future__ import annotations + +import math +from collections.abc import Mapping, Sequence +from dataclasses import asdict, dataclass +from datetime import datetime +from typing import Literal + +import polars as pl + +from microstructure.config import FeatureConfig +from microstructure.research.analysis import RegimeThresholds, assign_market_regimes +from microstructure.research.features import add_future_event_labels, build_research_features + +EndpointDomain = Literal["event", "clock"] +StudyRole = Literal["train", "validation", "primary_test", "replication_test"] + +_NANOSECONDS_PER_MILLISECOND = 1_000_000 +_NANOSECONDS_PER_DAY = 86_400_000_000_000 +_ALLOWED_ROLES = frozenset({"train", "validation", "primary_test", "replication_test"}) +_REGIME_FEATURES = ( + "volatility_regime_low", + "volatility_regime_high", + "liquidity_regime_liquid", + "liquidity_regime_stressed", +) + + +class L2ResearchError(ValueError): + """Raised when a live-L2 input would violate the frozen research contract.""" + + +@dataclass(frozen=True, slots=True) +class L2ObservedInterval: + """One capture-verified interval of continuously OBSERVED book state.""" + + continuity_id: str + start_received_ns: int + end_received_ns_exclusive: int + + def __post_init__(self) -> None: + if not self.continuity_id: + raise ValueError("L2 interval continuity_id must not be empty") + if self.start_received_ns < 0 or self.end_received_ns_exclusive <= self.start_received_ns: + raise ValueError("L2 interval bounds are invalid") + + +@dataclass(frozen=True, slots=True) +class L2EndpointSpec: + """One independently selected prediction endpoint.""" + + name: str + domain: EndpointDomain + horizon_value: int + horizon_unit: Literal["events", "milliseconds"] + paired_block_events: int | None + paired_block_milliseconds: int | None + impact_ofi_window: int + + def __post_init__(self) -> None: + if not self.name or self.domain not in {"event", "clock"}: + raise ValueError("L2 endpoint name/domain is invalid") + if self.horizon_value < 1 or self.impact_ofi_window < 1: + raise ValueError("L2 endpoint horizons and OFI window must be positive") + if self.domain == "event": + if ( + self.horizon_unit != "events" + or self.paired_block_events is None + or self.paired_block_events < 1 + or self.paired_block_milliseconds is not None + ): + raise ValueError("event endpoint requires only a positive event block") + elif ( + self.horizon_unit != "milliseconds" + or self.paired_block_milliseconds is None + or self.paired_block_milliseconds < 1 + or self.paired_block_events is not None + ): + raise ValueError("clock endpoint requires only a positive wall-time block") + + @property + def horizon_ns(self) -> int: + if self.domain != "clock": + raise ValueError("event endpoints do not have a clock horizon") + return self.horizon_value * _NANOSECONDS_PER_MILLISECOND + + +@dataclass(frozen=True, slots=True) +class L2RegimeFit: + """Train-only regime thresholds plus their explicit fit contract.""" + + symbol: str + study_date: str + volatility_column: str + lower_quantile: float + upper_quantile: float + thresholds: RegimeThresholds + + def to_dict(self) -> dict[str, object]: + return { + "symbol": self.symbol, + "study_date": self.study_date, + "volatility_column": self.volatility_column, + "lower_quantile": self.lower_quantile, + "upper_quantile": self.upper_quantile, + "thresholds": asdict(self.thresholds), + "fit_scope": "train_session_only", + } + + +def _require(frame: pl.DataFrame, columns: Sequence[str], label: str) -> None: + missing = sorted(set(columns).difference(frame.columns)) + if missing: + raise L2ResearchError(f"{label} is missing required columns: {missing}") + if frame.is_empty(): + raise L2ResearchError(f"{label} must not be empty") + + +def _date_bounds(study_date: str) -> tuple[int, int]: + try: + start = datetime.fromisoformat(f"{study_date}T00:00:00+00:00") + except ValueError as error: + raise L2ResearchError("study_date must use ISO YYYY-MM-DD") from error + start_ns = int(start.timestamp()) * 1_000_000_000 + return start_ns, start_ns + _NANOSECONDS_PER_DAY + + +def _validate_intervals( + intervals: Sequence[L2ObservedInterval], + *, + study_date: str, +) -> tuple[L2ObservedInterval, ...]: + values = tuple( + sorted( + intervals, + key=lambda item: ( + item.start_received_ns, + item.end_received_ns_exclusive, + item.continuity_id, + ), + ) + ) + if not values: + raise L2ResearchError("L2 research requires at least one verified OBSERVED interval") + date_start, date_end = _date_bounds(study_date) + prior_end = -1 + for item in values: + if item.start_received_ns < date_start or item.end_received_ns_exclusive > date_end: + raise L2ResearchError("OBSERVED interval escapes its frozen study date") + if item.start_received_ns < prior_end: + raise L2ResearchError("OBSERVED intervals overlap") + prior_end = item.end_received_ns_exclusive + return values + + +def _segment_one( + frame: pl.DataFrame, + intervals: Sequence[L2ObservedInterval], + *, + study_date: str, + time_column: str, + label: str, +) -> pl.DataFrame: + _require(frame, ("symbol", "continuity_id", time_column), label) + outputs: list[pl.DataFrame] = [] + for ordinal, interval in enumerate(intervals): + research_id = f"{study_date}::{interval.continuity_id}::observed-{ordinal:04d}" + subset = frame.filter( + (pl.col("continuity_id") == interval.continuity_id) + & (pl.col(time_column) >= interval.start_received_ns) + & (pl.col(time_column) < interval.end_received_ns_exclusive) + ) + if subset.is_empty(): + raise L2ResearchError(f"{label} has no rows for verified interval {research_id}") + outputs.append( + subset.rename({"continuity_id": "capture_continuity_id"}).with_columns( + pl.lit(research_id).alias("continuity_id"), + pl.lit(research_id).alias("observed_interval_id"), + pl.lit(interval.start_received_ns, dtype=pl.Int64).alias( + "observed_interval_start_ns" + ), + pl.lit(interval.end_received_ns_exclusive, dtype=pl.Int64).alias( + "observed_interval_end_ns_exclusive" + ), + ) + ) + result = pl.concat(outputs, how="vertical_relaxed") + if ( + result.height + != frame.filter( + pl.any_horizontal( + [ + (pl.col("continuity_id") == item.continuity_id) + & (pl.col(time_column) >= item.start_received_ns) + & (pl.col(time_column) < item.end_received_ns_exclusive) + for item in intervals + ] + ) + ).height + ): + raise L2ResearchError(f"{label} interval segmentation is not one-to-one") + return result + + +def segment_l2_inputs( + book_observations: pl.DataFrame, + depth_deltas: pl.DataFrame, + intervals: Sequence[L2ObservedInterval], + *, + study_date: str, +) -> tuple[pl.DataFrame, pl.DataFrame]: + """Restrict and re-key books/deltas to verified continuous-observation intervals.""" + + verified = _validate_intervals(intervals, study_date=study_date) + books = _segment_one( + book_observations, + verified, + study_date=study_date, + time_column="available_ts_ns", + label="book observations", + ) + deltas = _segment_one( + depth_deltas, + verified, + study_date=study_date, + time_column="available_ts_ns", + label="depth deltas", + ) + return books, deltas + + +def _add_volatility_windows(frame: pl.DataFrame, windows: Sequence[int]) -> pl.DataFrame: + group = ["symbol", "continuity_id"] + expressions = [ + pl.col("log_mid_return_1") + .pow(2) + .rolling_sum(window_size=window, min_samples=1) + .over(group) + .sqrt() + .alias(f"realized_volatility_w{window}") + for window in sorted(set(windows)) + ] + return frame.with_columns(expressions) + + +def _exact_clock_label( + features: pl.DataFrame, + endpoint: L2EndpointSpec, + *, + max_state_age_ns: int, +) -> pl.DataFrame: + if endpoint.domain != "clock": + raise L2ResearchError("exact clock label requires a clock endpoint") + if max_state_age_ns < 0: + raise L2ResearchError("clock max state age must be nonnegative") + keys = ["symbol", "continuity_id"] + decisions = features.with_columns( + (pl.col("decision_ts_ns") + endpoint.horizon_ns).alias("clock_target_ts_ns") + ) + right = features.select( + *keys, + pl.col("decision_ts_ns").alias("_target_state_ts_ns"), + pl.col("decision_sequence").alias("_target_state_sequence"), + pl.col("mid_price").alias("_target_state_mid"), + ).sort(["_target_state_ts_ns", *keys, "_target_state_sequence"]) + # ``join_asof(..., strategy="backward")`` selects the last matching row. + # Sorting equal-time states by sequence therefore makes the exact-target + # tie-break explicit: the greatest observable sequence at ``t + h`` wins. + joined = decisions.sort(["clock_target_ts_ns", *keys, "decision_sequence"]).join_asof( + right, + left_on="clock_target_ts_ns", + right_on="_target_state_ts_ns", + by=keys, + strategy="backward", + allow_exact_matches=True, + check_sortedness=False, + ) + state_age = pl.col("clock_target_ts_ns") - pl.col("_target_state_ts_ns") + censored = ( + pl.col("_target_state_ts_ns").is_null() + | (pl.col("clock_target_ts_ns") >= pl.col("observed_interval_end_ns_exclusive")) + | (state_age > max_state_age_ns) + | (pl.col("_target_state_sequence") < pl.col("decision_sequence")) + ) + return ( + joined.with_columns( + censored.alias("right_censored"), + state_age.alias("clock_target_state_age_ns"), + pl.lit(endpoint.horizon_ns, dtype=pl.Int64).alias("clock_horizon_ns"), + ) + .with_columns( + pl.when(~pl.col("right_censored")) + .then((pl.col("_target_state_mid") / pl.col("mid_price")).log()) + .otherwise(None) + .alias("future_mid_return"), + pl.when(~pl.col("right_censored")) + .then(pl.col("clock_target_ts_ns")) + .otherwise(None) + .alias("label_information_end_ts_ns"), + pl.when(~pl.col("right_censored")) + .then(pl.col("_target_state_sequence")) + .otherwise(None) + .alias("label_information_end_sequence"), + pl.when(~pl.col("right_censored")) + .then(pl.col("continuity_id")) + .otherwise(None) + .alias("label_continuity_id"), + pl.col("decision_ts_ns").alias("label_start_ts_ns"), + pl.col("decision_sequence").alias("label_start_sequence"), + ) + .with_columns( + pl.when(pl.col("future_mid_return").is_null()) + .then(None) + .when(pl.col("future_mid_return") > 0) + .then(1) + .when(pl.col("future_mid_return") < 0) + .then(-1) + .otherwise(0) + .cast(pl.Int8) + .alias("future_mid_direction"), + pl.when(pl.col("future_mid_return").is_null()) + .then(None) + .otherwise((pl.col("future_mid_return") > 0).cast(pl.Int8)) + .alias("future_mid_up"), + ) + .drop("_target_state_ts_ns", "_target_state_sequence", "_target_state_mid") + .sort("decision_ts_ns", "decision_sequence") + ) + + +def _standardize_endpoint( + frame: pl.DataFrame, + endpoint: L2EndpointSpec, + *, + study_date: str, + study_role: StudyRole, +) -> pl.DataFrame: + ofi_column = f"ofi_w{endpoint.impact_ofi_window}" + _require(frame, (ofi_column, "future_mid_return", "right_censored"), "endpoint frame") + signed_markout = ( + pl.when(pl.col("right_censored") | pl.col("future_mid_return").is_null()) + .then(None) + .otherwise( + pl.when(pl.col(ofi_column) > 0) + .then(1.0) + .when(pl.col(ofi_column) < 0) + .then(-1.0) + .otherwise(0.0) + * 10_000.0 + * pl.col("future_mid_return") + ) + ) + result = frame.with_columns( + pl.lit(study_date).alias("study_date"), + pl.lit(study_role).alias("study_role"), + pl.lit(endpoint.name).alias("endpoint_name"), + pl.lit(endpoint.domain).alias("endpoint_domain"), + pl.lit(endpoint.horizon_value, dtype=pl.Int64).alias("endpoint_horizon_value"), + pl.lit(endpoint.horizon_unit).alias("endpoint_horizon_unit"), + pl.col("continuity_id").alias("feature_continuity_id"), + pl.col("decision_sequence").alias("decision_trade_id"), + pl.col("max_feature_source_sequence").alias("max_feature_source_trade_id"), + pl.col("label_start_sequence").alias("label_start_trade_id"), + pl.col("label_information_end_sequence").alias("label_information_end_trade_id"), + signed_markout.alias("ofi_signed_future_mid_markout_bps"), + pl.lit(ofi_column).alias("signed_markout_side_source"), + pl.lit("descriptive_ofi_sign_times_future_mid_log_return").alias("signed_markout_policy"), + ).with_columns( + pl.concat_str( + "study_date", + "symbol", + "endpoint_name", + "continuity_id", + pl.col("decision_sequence").cast(pl.String), + separator="::", + ).alias("sample_id") + ) + validate_l2_endpoint_frame(result) + return result + + +def build_l2_endpoint_frames( + book_observations: pl.DataFrame, + depth_deltas: pl.DataFrame, + intervals: Sequence[L2ObservedInterval], + *, + study_date: str, + study_role: StudyRole, + feature_windows: Sequence[int], + volatility_window: int, + clock_max_state_age_ms: int, + endpoints: Sequence[L2EndpointSpec], +) -> Mapping[str, pl.DataFrame]: + """Build every predeclared endpoint from one verified symbol/session capture.""" + + if study_role not in _ALLOWED_ROLES: + raise L2ResearchError(f"unsupported L2 study role {study_role!r}") + windows = tuple(sorted(set(feature_windows))) + if not windows or any(window < 1 for window in windows) or volatility_window < 1: + raise L2ResearchError("L2 rolling windows must be positive") + specs = tuple(endpoints) + if not specs or len({item.name for item in specs}) != len(specs): + raise L2ResearchError("L2 endpoints must be nonempty and uniquely named") + books, deltas = segment_l2_inputs( + book_observations, + depth_deltas, + intervals, + study_date=study_date, + ) + feature_config = FeatureConfig( + trade_windows=windows, + volatility_window=volatility_window, + intensity_window=max(windows), + label_horizon_events=1, + large_trade_quantile=0.95, + ) + features = build_research_features( + books, + None, + feature_config, + depth_deltas=deltas, + ) + features = _add_volatility_windows(features, windows) + result: dict[str, pl.DataFrame] = {} + max_state_age_ns = clock_max_state_age_ms * _NANOSECONDS_PER_MILLISECOND + for endpoint in specs: + labeled = ( + add_future_event_labels(features, endpoint.horizon_value) + if endpoint.domain == "event" + else _exact_clock_label(features, endpoint, max_state_age_ns=max_state_age_ns) + ) + result[endpoint.name] = _standardize_endpoint( + labeled, + endpoint, + study_date=study_date, + study_role=study_role, + ) + return result + + +def validate_l2_endpoint_frame(frame: pl.DataFrame) -> None: + """Fail closed on date, interval, feature-lineage, or label leakage.""" + + required = ( + "study_date", + "study_role", + "endpoint_name", + "endpoint_domain", + "symbol", + "continuity_id", + "observed_interval_id", + "observed_interval_start_ns", + "observed_interval_end_ns_exclusive", + "decision_ts_ns", + "decision_sequence", + "feature_cutoff_ts_ns", + "max_feature_source_ts_ns", + "max_feature_source_sequence", + "feature_continuity_id", + "label_start_ts_ns", + "label_start_sequence", + "right_censored", + "future_mid_return", + "future_mid_up", + "label_information_end_ts_ns", + "label_information_end_sequence", + "label_continuity_id", + "ofi_signed_future_mid_markout_bps", + "sample_id", + ) + _require(frame, required, "L2 endpoint frame") + for column in ( + "study_date", + "study_role", + "endpoint_name", + "endpoint_domain", + "symbol", + "continuity_id", + "observed_interval_id", + "decision_ts_ns", + "decision_sequence", + "feature_cutoff_ts_ns", + "max_feature_source_ts_ns", + "max_feature_source_sequence", + "feature_continuity_id", + "label_start_ts_ns", + "label_start_sequence", + "right_censored", + "sample_id", + ): + if frame.get_column(column).null_count(): + raise L2ResearchError(f"L2 endpoint column {column!r} must not contain nulls") + if frame.get_column("study_date").n_unique() != 1: + raise L2ResearchError("one L2 endpoint frame must contain exactly one study date") + study_date = str(frame.get_column("study_date")[0]) + date_start, date_end = _date_bounds(study_date) + invalid = frame.filter( + (pl.col("study_role").is_in(list(_ALLOWED_ROLES)).not_()) + | (pl.col("decision_ts_ns") < date_start) + | (pl.col("decision_ts_ns") >= date_end) + | (pl.col("decision_ts_ns") < pl.col("observed_interval_start_ns")) + | (pl.col("decision_ts_ns") >= pl.col("observed_interval_end_ns_exclusive")) + | (pl.col("feature_cutoff_ts_ns") != pl.col("decision_ts_ns")) + | (pl.col("max_feature_source_ts_ns") > pl.col("decision_ts_ns")) + | ( + (pl.col("max_feature_source_ts_ns") == pl.col("decision_ts_ns")) + & (pl.col("max_feature_source_sequence") > pl.col("decision_sequence")) + ) + | (pl.col("feature_continuity_id") != pl.col("continuity_id")) + | (pl.col("label_start_ts_ns") != pl.col("decision_ts_ns")) + | (pl.col("label_start_sequence") != pl.col("decision_sequence")) + ) + if invalid.height: + raise L2ResearchError("L2 endpoint base timing or interval lineage is invalid") + if frame.get_column("sample_id").n_unique() != frame.height: + raise L2ResearchError("L2 endpoint sample identities must be unique") + labeled = frame.filter(~pl.col("right_censored")) + for column in ( + "future_mid_return", + "future_mid_up", + "label_information_end_ts_ns", + "label_information_end_sequence", + "label_continuity_id", + "ofi_signed_future_mid_markout_bps", + ): + if labeled.get_column(column).null_count(): + raise L2ResearchError(f"uncensored L2 labels require non-null {column}") + if labeled.filter( + (pl.col("label_continuity_id") != pl.col("continuity_id")) + | (pl.col("label_information_end_ts_ns") < pl.col("decision_ts_ns")) + | ( + (pl.col("label_information_end_ts_ns") == pl.col("decision_ts_ns")) + & (pl.col("label_information_end_sequence") <= pl.col("decision_sequence")) + ) + | (pl.col("label_information_end_ts_ns") >= pl.col("observed_interval_end_ns_exclusive")) + | (pl.col("label_information_end_ts_ns") >= date_end) + | (pl.col("label_information_end_sequence") < pl.col("decision_sequence")) + ).height: + raise L2ResearchError("L2 labels are not strictly future and interval-local") + censored = frame.filter(pl.col("right_censored")) + if censored.filter( + pl.col("future_mid_return").is_not_null() + | pl.col("future_mid_up").is_not_null() + | pl.col("label_information_end_ts_ns").is_not_null() + | pl.col("label_information_end_sequence").is_not_null() + | pl.col("label_continuity_id").is_not_null() + | pl.col("ofi_signed_future_mid_markout_bps").is_not_null() + ).height: + raise L2ResearchError("censored L2 labels must not retain future outcomes") + + +def _finite_quantile(frame: pl.DataFrame, column: str, quantile: float) -> float: + value = frame.get_column(column).quantile(quantile, interpolation="linear") + if value is None or not math.isfinite(float(value)): + raise L2ResearchError(f"cannot fit finite train threshold for {column}") + return float(value) + + +def fit_l2_regime_thresholds( + train_frame: pl.DataFrame, + *, + lower_quantile: float, + upper_quantile: float, + volatility_column: str, +) -> L2RegimeFit: + """Fit volatility/liquidity thresholds on the train session only.""" + + if not 0.0 < lower_quantile < upper_quantile < 1.0: + raise L2ResearchError("regime quantiles must satisfy 0 < lower < upper < 1") + _require( + train_frame, + ( + "symbol", + "study_date", + "study_role", + "feature_ready", + volatility_column, + "spread_bps", + "depth_total_l1", + ), + "L2 regime training frame", + ) + if set(train_frame.get_column("study_role").unique().to_list()) != {"train"}: + raise L2ResearchError("regime thresholds may be fit only on the train session") + if train_frame.get_column("symbol").n_unique() != 1: + raise L2ResearchError("regime thresholds are fit separately per symbol") + eligible = train_frame.filter(pl.col("feature_ready")).drop_nulls( + [volatility_column, "spread_bps", "depth_total_l1"] + ) + if eligible.is_empty(): + raise L2ResearchError("no feature-ready train rows are available for regime fitting") + symbol = str(eligible.get_column("symbol")[0]) + study_date = str(eligible.get_column("study_date")[0]) + return L2RegimeFit( + symbol=symbol, + study_date=study_date, + volatility_column=volatility_column, + lower_quantile=lower_quantile, + upper_quantile=upper_quantile, + thresholds=RegimeThresholds( + volatility_low=_finite_quantile(eligible, volatility_column, lower_quantile), + volatility_high=_finite_quantile(eligible, volatility_column, upper_quantile), + spread_tight_bps=_finite_quantile(eligible, "spread_bps", lower_quantile), + spread_wide_bps=_finite_quantile(eligible, "spread_bps", upper_quantile), + depth_low=_finite_quantile(eligible, "depth_total_l1", lower_quantile), + depth_high=_finite_quantile(eligible, "depth_total_l1", upper_quantile), + ), + ) + + +def apply_l2_regimes(frame: pl.DataFrame, fitted: L2RegimeFit) -> pl.DataFrame: + """Apply one symbol's persisted train-only thresholds and numeric dummies.""" + + if set(str(value) for value in frame.get_column("symbol").unique().to_list()) != { + fitted.symbol + }: + raise L2ResearchError("regime thresholds and endpoint symbol disagree") + assigned = assign_market_regimes( + frame, + train_thresholds={fitted.symbol: fitted.thresholds}, + volatility_column=fitted.volatility_column, + ) + return assigned.with_columns( + (pl.col("volatility_regime") == "low").cast(pl.Float64).alias("volatility_regime_low"), + (pl.col("volatility_regime") == "high").cast(pl.Float64).alias("volatility_regime_high"), + (pl.col("liquidity_regime") == "liquid").cast(pl.Float64).alias("liquidity_regime_liquid"), + (pl.col("liquidity_regime") == "stressed") + .cast(pl.Float64) + .alias("liquidity_regime_stressed"), + pl.lit(fitted.study_date).alias("regime_fit_study_date"), + pl.lit("train_session_only").alias("regime_fit_scope"), + ) + + +def l2_model_feature_columns(frame: pl.DataFrame, *, windows: Sequence[int]) -> tuple[str, ...]: + """Return the exact book-only feature ladder; all-zero trade proxies are forbidden.""" + + rolling = tuple(sorted(set(windows))) + columns = ( + "spread_bps", + "depth_total_l1", + "depth_total_l5", + "depth_total_l10", + "queue_imbalance_l1", + "queue_imbalance_l5", + "queue_imbalance_l10", + "microprice_deviation_bps", + "ofi_l1", + *(f"ofi_w{window}" for window in rolling), + *(f"cancellation_intensity_w{window}" for window in rolling), + *(f"realized_volatility_w{window}" for window in rolling), + *_REGIME_FEATURES, + ) + missing = sorted(set(columns).difference(frame.columns)) + if missing: + raise L2ResearchError(f"L2 model feature contract is incomplete: {missing}") + forbidden = [ + name + for name in columns + if name.startswith(("signed_trade_", "trade_volume_", "trade_count_", "trade_intensity_")) + ] + if forbidden: + raise L2ResearchError(f"trade-only proxies cannot enter the book-only model: {forbidden}") + return tuple(columns) + + +def dependency_block_expression(endpoint: L2EndpointSpec) -> pl.Expr: + """Return a continuity-local paired dependency-block identifier expression.""" + + if endpoint.domain == "event": + assert endpoint.paired_block_events is not None + block = ( + pl.col("decision_sequence") + .rank("ordinal") + .over(["study_date", "symbol", "continuity_id"]) + - 1 + ) // endpoint.paired_block_events + else: + assert endpoint.paired_block_milliseconds is not None + block_ns = endpoint.paired_block_milliseconds * _NANOSECONDS_PER_MILLISECOND + block = (pl.col("decision_ts_ns") - pl.col("observed_interval_start_ns")) // block_ns + return pl.concat_str( + "study_date", + "symbol", + "continuity_id", + block.cast(pl.Int64).cast(pl.String), + separator="::", + ).alias("bootstrap_block") + + +__all__ = [ + "EndpointDomain", + "L2EndpointSpec", + "L2ObservedInterval", + "L2RegimeFit", + "L2ResearchError", + "StudyRole", + "apply_l2_regimes", + "build_l2_endpoint_frames", + "dependency_block_expression", + "fit_l2_regime_thresholds", + "l2_model_feature_columns", + "segment_l2_inputs", + "validate_l2_endpoint_frame", +] diff --git a/Microstructure/src/microstructure/research/labels.py b/Microstructure/src/microstructure/research/labels.py new file mode 100644 index 0000000000000000000000000000000000000000..075c86fb02f0f7847344e9ead326ad35ba3156cd --- /dev/null +++ b/Microstructure/src/microstructure/research/labels.py @@ -0,0 +1,635 @@ +"""Auxiliary, explicitly future-dependent research labels. + +These builders never produce model features. Each output records the end of +the information interval, right-censoring, and the assumptions needed to +interpret the label. Clock joins and fill evidence are strict with respect to +the decision/activation time and never cross ``continuity_id`` boundaries. +""" + +from __future__ import annotations + +import math +from collections.abc import Sequence +from dataclasses import dataclass +from typing import Literal, cast + +import polars as pl + + +class AuxiliaryLabelError(ValueError): + """Raised when an auxiliary label cannot satisfy its temporal contract.""" + + +Side = Literal["buy", "sell"] + + +@dataclass(frozen=True, slots=True) +class ClockTimeLabelSpec: + """Clock horizons and admissible delay to the first observed target state.""" + + horizons_ns: tuple[int, ...] + max_target_staleness_ns: int | None = None + + def __post_init__(self) -> None: + if not self.horizons_ns or any(value <= 0 for value in self.horizons_ns): + raise AuxiliaryLabelError("clock horizons must be nonempty and strictly positive") + if self.max_target_staleness_ns is not None and self.max_target_staleness_ns < 0: + raise AuxiliaryLabelError("max target staleness must be nonnegative") + + +@dataclass(frozen=True, slots=True) +class LimitFillAssumptions: + """Observable-input queue proxy for a hypothetical best-quote limit order.""" + + side: Side + horizon_ns: int + order_quantity: float + queue_ahead_fraction: float = 1.0 + activation_latency_ns: int = 0 + + def __post_init__(self) -> None: + if self.side not in {"buy", "sell"}: + raise AuxiliaryLabelError("limit side must be buy or sell") + if self.horizon_ns <= 0: + raise AuxiliaryLabelError("fill horizon must be positive") + if not math.isfinite(self.order_quantity) or self.order_quantity <= 0: + raise AuxiliaryLabelError("order quantity must be finite and positive") + if not 0.0 <= self.queue_ahead_fraction <= 1.0: + raise AuxiliaryLabelError("queue_ahead_fraction must be in [0, 1]") + if self.activation_latency_ns < 0: + raise AuxiliaryLabelError("activation latency must be nonnegative") + + +@dataclass(frozen=True, slots=True) +class AdverseSelectionSpec: + """Post-fill markout horizons and target-state staleness bound.""" + + horizons_ns: tuple[int, ...] + max_target_staleness_ns: int | None = None + + def __post_init__(self) -> None: + ClockTimeLabelSpec(self.horizons_ns, self.max_target_staleness_ns) + + +_GROUP_COLUMNS = ("symbol", "continuity_id") + + +def _require( + frame: pl.DataFrame, + columns: Sequence[str], + table: str, + *, + allow_empty: bool = False, +) -> None: + missing = sorted(set(columns).difference(frame.columns)) + if missing: + raise AuxiliaryLabelError(f"{table} is missing required columns: {missing}") + if frame.is_empty() and not allow_empty: + raise AuxiliaryLabelError(f"{table} must not be empty") + + +def _valid_books( + books: pl.DataFrame, + *, + time_column: str, + mid_column: str, +) -> pl.DataFrame: + _require(books, (*_GROUP_COLUMNS, time_column, mid_column), "book states") + result = books.filter(pl.col("is_valid")) if "is_valid" in books.columns else books + if result.is_empty(): + raise AuxiliaryLabelError("no valid book states are available") + invalid = result.filter( + pl.col("continuity_id").is_null() + | pl.col(time_column).is_null() + | pl.col(mid_column).is_null() + | (pl.col(mid_column) <= 0) + ) + if not invalid.is_empty(): + raise AuxiliaryLabelError("valid book states require segment, time, and positive mid") + return result.sort([time_column, *_GROUP_COLUMNS]) + + +def _forward_mid_join( + decisions: pl.DataFrame, + books: pl.DataFrame, + *, + decision_time_column: str, + book_time_column: str, + mid_column: str, + target_column: str, + book_identity_column: str | None = None, +) -> pl.DataFrame: + right_columns: list[pl.Expr | str] = [ + *_GROUP_COLUMNS, + pl.col(book_time_column).alias("_matched_target_ts_ns"), + pl.col(mid_column).alias("_matched_target_mid"), + ] + if book_identity_column is not None: + right_columns.append(pl.col(book_identity_column).alias("_matched_target_identity")) + right = books.select(right_columns).sort(["_matched_target_ts_ns", *_GROUP_COLUMNS]) + return ( + decisions.sort([target_column, *_GROUP_COLUMNS]) + .join_asof( + right, + left_on=target_column, + right_on="_matched_target_ts_ns", + by=list(_GROUP_COLUMNS), + strategy="forward", + allow_exact_matches=True, + check_sortedness=False, + ) + .sort([decision_time_column, *_GROUP_COLUMNS]) + ) + + +def build_clock_time_mid_labels( + decisions: pl.DataFrame, + spec: ClockTimeLabelSpec, + *, + book_states: pl.DataFrame | None = None, + decision_time_column: str = "decision_ts_ns", + mid_column: str = "mid_price", + book_time_column: str | None = None, + book_mid_column: str | None = None, + book_identity_column: str | None = None, +) -> pl.DataFrame: + """Build long-form clock-time return/direction labels within book segments.""" + + _require(decisions, (*_GROUP_COLUMNS, decision_time_column, mid_column), "decisions") + invalid_decisions = decisions.filter( + pl.col("continuity_id").is_null() + | pl.col(decision_time_column).is_null() + | pl.col(mid_column).is_null() + | (pl.col(mid_column) <= 0) + ) + if invalid_decisions.height: + raise AuxiliaryLabelError("decisions require segment, time, and positive current mid") + target_states = decisions if book_states is None else book_states + target_time = book_time_column or decision_time_column + target_mid = book_mid_column or mid_column + books = _valid_books(target_states, time_column=target_time, mid_column=target_mid) + if book_identity_column is not None: + _require(books, (book_identity_column,), "clock-time target states") + if books.get_column(book_identity_column).null_count(): + raise AuxiliaryLabelError("clock-time target identity must not contain nulls") + eligible_decisions = ( + decisions.filter(pl.col("is_valid")) + if book_states is None and "is_valid" in decisions.columns + else decisions + ) + outputs: list[pl.DataFrame] = [] + for horizon_ns in sorted(set(spec.horizons_ns)): + with_target = eligible_decisions.with_columns( + (pl.col(decision_time_column) + horizon_ns).alias("clock_target_ts_ns") + ) + joined = _forward_mid_join( + with_target, + books, + decision_time_column=decision_time_column, + book_time_column=target_time, + mid_column=target_mid, + target_column="clock_target_ts_ns", + book_identity_column=book_identity_column, + ).with_columns( + (pl.col("_matched_target_ts_ns") - pl.col("clock_target_ts_ns")).alias( + "clock_target_staleness_ns" + ) + ) + censored = pl.col("_matched_target_ts_ns").is_null() + if spec.max_target_staleness_ns is not None: + censored = censored | ( + pl.col("clock_target_staleness_ns") > spec.max_target_staleness_ns + ) + labeled = ( + joined.with_columns( + censored.alias("clock_right_censored"), + pl.lit(horizon_ns, dtype=pl.Int64).alias("clock_horizon_ns"), + pl.lit("clock_time_mid_return", dtype=pl.String).alias("clock_label_kind"), + pl.lit( + "first valid state at or after t+h in the same continuity segment", + dtype=pl.String, + ).alias("clock_label_assumption"), + pl.lit(True).alias("clock_label_is_descriptive"), + pl.col(decision_time_column).alias("clock_label_start_ts_ns"), + pl.when(pl.col("_matched_target_ts_ns").is_null()) + .then(pl.lit("no_same_segment_future_state")) + .when(censored) + .then(pl.lit("target_state_too_stale")) + .otherwise(None) + .alias("clock_censor_reason"), + ) + .with_columns( + pl.when(~pl.col("clock_right_censored")) + .then((pl.col("_matched_target_mid") / pl.col(mid_column)).log()) + .otherwise(None) + .alias("clock_future_mid_return"), + pl.when(~pl.col("clock_right_censored")) + .then(pl.col("_matched_target_mid")) + .otherwise(None) + .alias("clock_target_mid_price"), + pl.when(~pl.col("clock_right_censored")) + .then(pl.col("_matched_target_ts_ns")) + .otherwise(None) + .alias("clock_label_information_end_ts_ns"), + pl.when(~pl.col("clock_right_censored")) + .then(pl.col("clock_target_staleness_ns")) + .otherwise(None) + .alias("clock_observed_target_staleness_ns"), + ) + .with_columns( + pl.when(pl.col("clock_future_mid_return").is_null()) + .then(None) + .when(pl.col("clock_future_mid_return") > 0) + .then(1) + .when(pl.col("clock_future_mid_return") < 0) + .then(-1) + .otherwise(0) + .cast(pl.Int8) + .alias("clock_future_mid_direction") + ) + ) + if book_identity_column is not None: + labeled = labeled.with_columns( + pl.when(~pl.col("clock_right_censored")) + .then(pl.col("_matched_target_identity")) + .otherwise(None) + .alias("clock_label_information_end_identity") + ) + outputs.append(labeled) + drop_columns = ["_matched_target_ts_ns", "_matched_target_mid"] + if book_identity_column is not None: + drop_columns.append("_matched_target_identity") + return ( + pl.concat(outputs, how="diagonal_relaxed") + .drop(*drop_columns) + .sort([decision_time_column, "clock_horizon_ns", *_GROUP_COLUMNS]) + ) + + +def _side_expression(column: str) -> pl.Expr: + return ( + pl.when(pl.col(column).cast(pl.String).str.to_lowercase().is_in(["buy", "1", "1.0"])) + .then(1.0) + .when(pl.col(column).cast(pl.String).str.to_lowercase().is_in(["sell", "-1", "-1.0"])) + .then(-1.0) + .otherwise(None) + ) + + +def add_event_time_price_impact_labels( + frame: pl.DataFrame, + *, + side_column: str, + return_column: str = "future_mid_return", + information_end_column: str = "label_information_end_ts_ns", + right_censored_column: str = "right_censored", +) -> pl.DataFrame: + """Side-sign a strictly future event-time return without changing its horizon.""" + + _require( + frame, + ( + side_column, + return_column, + information_end_column, + right_censored_column, + "label_horizon_events", + ), + "event-time impact frame", + ) + result = frame.with_columns(_side_expression(side_column).alias("event_impact_side_sign")) + if result.filter(pl.col("event_impact_side_sign").is_null()).height: + raise AuxiliaryLabelError("event-time impact side must be buy/sell or +1/-1") + invalid_timing = result.filter( + (~pl.col(right_censored_column) & pl.col(information_end_column).is_null()) + | (pl.col(right_censored_column) & pl.col(return_column).is_not_null()) + ) + if invalid_timing.height: + raise AuxiliaryLabelError("event-time return censoring and information end disagree") + return result.with_columns( + pl.when(~pl.col(right_censored_column)) + .then(10_000.0 * pl.col("event_impact_side_sign") * pl.col(return_column)) + .otherwise(None) + .alias("event_time_signed_price_impact_bps"), + pl.col(information_end_column).alias("event_impact_label_information_end_ts_ns"), + pl.col(right_censored_column).alias("event_impact_right_censored"), + pl.lit("event_time_signed_price_impact").alias("event_impact_label_kind"), + pl.lit(True).alias("event_impact_label_is_descriptive"), + pl.lit("aggressor-side sign times strictly future same-segment log-mid return").alias( + "event_impact_label_assumption" + ), + ) + + +def build_clock_time_price_impact_labels( + decisions: pl.DataFrame, + spec: ClockTimeLabelSpec, + *, + book_states: pl.DataFrame | None = None, + side_column: str = "trade_sign", + decision_time_column: str = "decision_ts_ns", + mid_column: str = "mid_price", + book_time_column: str | None = None, + book_mid_column: str | None = None, +) -> pl.DataFrame: + """Add aggressor-signed clock-time price impact to mid-return labels.""" + + _require(decisions, (side_column,), "impact decisions") + result = build_clock_time_mid_labels( + decisions, + spec, + book_states=book_states, + decision_time_column=decision_time_column, + mid_column=mid_column, + book_time_column=book_time_column, + book_mid_column=book_mid_column, + ).with_columns(_side_expression(side_column).alias("clock_impact_side_sign")) + if result.filter(pl.col("clock_impact_side_sign").is_null()).height: + raise AuxiliaryLabelError("impact side must be buy/sell or +1/-1") + return result.with_columns( + pl.when(~pl.col("clock_right_censored")) + .then(10_000.0 * pl.col("clock_impact_side_sign") * pl.col("clock_future_mid_return")) + .otherwise(None) + .alias("clock_signed_price_impact_bps"), + pl.lit("clock_time_signed_price_impact").alias("clock_label_kind"), + ) + + +def build_hypothetical_limit_fill_labels( + book_states: pl.DataFrame, + trades: pl.DataFrame, + assumptions: LimitFillAssumptions, + *, + decision_time_column: str = "decision_ts_ns", +) -> pl.DataFrame: + """Label a conservative best-quote fill proxy from subsequent trade prints. + + The proxy ignores cancellations and hidden liquidity. Opposing prints + strictly after activation deplete a fixed fraction of displayed queue before + reaching the hypothetical order. Historical printed quantity is never + reused within one candidate order, but separate decision labels remain + counterfactual scenarios rather than simultaneously live orders. + """ + + _require( + book_states, + ( + *_GROUP_COLUMNS, + decision_time_column, + "best_bid", + "best_ask", + "bid_quantity", + "ask_quantity", + ), + "limit-fill book states", + ) + _require( + trades, + (*_GROUP_COLUMNS, "available_ts_ns", "price", "quantity", "aggressor_side"), + "limit-fill trades", + allow_empty=True, + ) + invalid_trades = trades.filter( + (pl.col("quantity") < 0) + | (~pl.col("aggressor_side").str.to_lowercase().is_in(["buy", "sell"])) + ) + if invalid_trades.height: + raise AuxiliaryLabelError("trades require nonnegative quantity and buy/sell side") + + trade_groups: dict[tuple[str, str], list[dict[str, object]]] = {} + for row in trades.sort("available_ts_ns").iter_rows(named=True): + key = (str(row["symbol"]), str(row["continuity_id"])) + trade_groups.setdefault(key, []).append(row) + + valid_for_coverage = ( + book_states.filter(pl.col("is_valid")) if "is_valid" in book_states.columns else book_states + ) + coverage: dict[tuple[str, str], int] = {} + for row in ( + valid_for_coverage.group_by(list(_GROUP_COLUMNS)) + .agg(pl.col(decision_time_column).max().alias("_coverage_end")) + .iter_rows(named=True) + ): + coverage[(str(row["symbol"]), str(row["continuity_id"]))] = int(row["_coverage_end"]) + + output: list[dict[str, object]] = [] + for row in book_states.sort([decision_time_column, *_GROUP_COLUMNS]).iter_rows(named=True): + symbol = str(row["symbol"]) + continuity_id = str(row["continuity_id"]) + decision_ts = int(row[decision_time_column]) + activation_ts = decision_ts + assumptions.activation_latency_ns + deadline_ts = activation_ts + assumptions.horizon_ns + valid_decision = bool(row.get("is_valid", True)) + limit_price = float(row["best_bid"] if assumptions.side == "buy" else row["best_ask"]) + displayed_quantity = float( + row["bid_quantity"] if assumptions.side == "buy" else row["ask_quantity"] + ) + queue_ahead = displayed_quantity * assumptions.queue_ahead_fraction + cumulative_executable = 0.0 + full_fill_ts: int | None = None + if valid_decision: + for trade in trade_groups.get((symbol, continuity_id), []): + trade_ts = cast(int, trade["available_ts_ns"]) + if trade_ts <= activation_ts: + continue + if trade_ts > deadline_ts: + break + trade_side = str(trade["aggressor_side"]).lower() + trade_price = cast(float, trade["price"]) + marketable = ( + assumptions.side == "buy" + and trade_side == "sell" + and trade_price <= limit_price + ) or ( + assumptions.side == "sell" + and trade_side == "buy" + and trade_price >= limit_price + ) + if not marketable: + continue + cumulative_executable += cast(float, trade["quantity"]) + if cumulative_executable >= queue_ahead + assumptions.order_quantity: + full_fill_ts = trade_ts + break + + observed_fill = min( + assumptions.order_quantity, max(0.0, cumulative_executable - queue_ahead) + ) + segment_covers_deadline = coverage.get((symbol, continuity_id), -1) >= deadline_ts + full_fill = full_fill_ts is not None + right_censored = (not valid_decision) or (not full_fill and not segment_covers_deadline) + information_end = ( + full_fill_ts + if full_fill + else deadline_ts + if segment_covers_deadline and valid_decision + else None + ) + base = { + name: row[name] + for name in ( + "sample_id", + "symbol", + "continuity_id", + decision_time_column, + "decision_sequence", + ) + if name in row + } + output.append( + { + **base, + "limit_label_kind": "hypothetical_best_quote_fill_proxy", + "limit_label_is_descriptive": True, + "limit_label_assumption": ( + "trade-print depletion of fixed displayed queue; cancellations, hidden liquidity, " + "and endogenous impact ignored" + ), + "limit_side": assumptions.side, + "limit_price": limit_price, + "limit_order_quantity": assumptions.order_quantity, + "limit_initial_displayed_quantity": displayed_quantity, + "limit_initial_queue_ahead": queue_ahead, + "limit_queue_ahead_fraction": assumptions.queue_ahead_fraction, + "limit_activation_latency_ns": assumptions.activation_latency_ns, + "limit_horizon_ns": assumptions.horizon_ns, + "limit_activation_ts_ns": activation_ts, + "limit_deadline_ts_ns": deadline_ts, + "limit_trade_evidence_required": True, + "limit_equal_time_ordering": "trade_at_activation_excluded", + "limit_cancellation_handling": "ignored_no_order_level_attribution", + "limit_observed_executable_quantity": cumulative_executable, + "limit_observed_fill_before_censoring": observed_fill, + "limit_right_censored": right_censored, + "limit_censor_reason": ( + "invalid_decision_book" + if not valid_decision + else "segment_ends_before_horizon" + if right_censored + else None + ), + "limit_fill_quantity": None if right_censored else observed_fill, + "limit_fill_fraction": ( + None if right_censored else observed_fill / assumptions.order_quantity + ), + "limit_full_fill": None if right_censored else full_fill, + "limit_full_fill_ts_ns": full_fill_ts, + "limit_label_start_ts_ns": decision_ts, + "limit_label_information_end_ts_ns": information_end, + } + ) + return pl.DataFrame(output).sort([decision_time_column, *_GROUP_COLUMNS]) + + +def build_post_fill_adverse_selection_labels( + fills: pl.DataFrame, + book_states: pl.DataFrame, + spec: AdverseSelectionSpec, + *, + fill_time_column: str = "fill_ts_ns", + fill_price_column: str = "fill_price", + side_column: str = "side", + book_time_column: str = "decision_ts_ns", + mid_column: str = "mid_price", +) -> pl.DataFrame: + """Build side-aware post-fill markout and adverse-selection labels.""" + + _require( + fills, + (*_GROUP_COLUMNS, fill_time_column, fill_price_column, side_column), + "fills", + ) + books = _valid_books(book_states, time_column=book_time_column, mid_column=mid_column) + prepared_fills = fills.with_columns(_side_expression(side_column).alias("_fill_side_sign")) + invalid = prepared_fills.filter( + pl.col("_fill_side_sign").is_null() + | (pl.col(fill_price_column) <= 0) + | pl.col("continuity_id").is_null() + ) + if invalid.height: + raise AuxiliaryLabelError("fills require buy/sell side, positive price, and continuity_id") + + outputs: list[pl.DataFrame] = [] + for horizon_ns in sorted(set(spec.horizons_ns)): + with_target = prepared_fills.with_columns( + (pl.col(fill_time_column) + horizon_ns).alias("adverse_target_ts_ns") + ) + joined = _forward_mid_join( + with_target, + books, + decision_time_column=fill_time_column, + book_time_column=book_time_column, + mid_column=mid_column, + target_column="adverse_target_ts_ns", + ).with_columns( + (pl.col("_matched_target_ts_ns") - pl.col("adverse_target_ts_ns")).alias( + "adverse_target_staleness_ns" + ) + ) + censored = pl.col("_matched_target_ts_ns").is_null() + if spec.max_target_staleness_ns is not None: + censored = censored | ( + pl.col("adverse_target_staleness_ns") > spec.max_target_staleness_ns + ) + outputs.append( + joined.with_columns( + censored.alias("adverse_right_censored"), + pl.lit(horizon_ns, dtype=pl.Int64).alias("adverse_horizon_ns"), + pl.lit("post_fill_adverse_selection").alias("adverse_label_kind"), + pl.lit(True).alias("adverse_label_is_descriptive"), + pl.lit( + "first valid same-segment mid at or after fill+h; exogenous book and no own impact" + ).alias("adverse_label_assumption"), + pl.col(fill_time_column).alias("adverse_label_start_ts_ns"), + pl.when(pl.col("_matched_target_ts_ns").is_null()) + .then(pl.lit("no_same_segment_future_state")) + .when(censored) + .then(pl.lit("target_state_too_stale")) + .otherwise(None) + .alias("adverse_censor_reason"), + ) + .with_columns( + pl.when(~pl.col("adverse_right_censored")) + .then(pl.col("_matched_target_mid")) + .otherwise(None) + .alias("adverse_target_mid_price"), + pl.when(~pl.col("adverse_right_censored")) + .then(pl.col("_matched_target_ts_ns")) + .otherwise(None) + .alias("adverse_label_information_end_ts_ns"), + pl.when(~pl.col("adverse_right_censored")) + .then( + 10_000.0 + * pl.col("_fill_side_sign") + * (pl.col("_matched_target_mid") - pl.col(fill_price_column)) + / pl.col(fill_price_column) + ) + .otherwise(None) + .alias("post_fill_markout_bps"), + ) + .with_columns( + (-pl.col("post_fill_markout_bps")).alias("adverse_selection_bps"), + pl.when(pl.col("post_fill_markout_bps").is_null()) + .then(None) + .otherwise(pl.col("post_fill_markout_bps") < 0) + .alias("adverse_selection_indicator"), + ) + ) + return ( + pl.concat(outputs, how="diagonal_relaxed") + .drop("_matched_target_ts_ns", "_matched_target_mid", "_fill_side_sign") + .sort([fill_time_column, "adverse_horizon_ns", *_GROUP_COLUMNS]) + ) + + +__all__ = [ + "AdverseSelectionSpec", + "AuxiliaryLabelError", + "ClockTimeLabelSpec", + "LimitFillAssumptions", + "add_event_time_price_impact_labels", + "build_clock_time_mid_labels", + "build_clock_time_price_impact_labels", + "build_hypothetical_limit_fill_labels", + "build_post_fill_adverse_selection_labels", +] diff --git a/Microstructure/src/microstructure/research/models.py b/Microstructure/src/microstructure/research/models.py new file mode 100644 index 0000000000000000000000000000000000000000..669c5cf5a46e1113a0028e8fc2100d961ef7c933 --- /dev/null +++ b/Microstructure/src/microstructure/research/models.py @@ -0,0 +1,736 @@ +"""Transparent model ladder, calibration, metrics, and dependent bootstrap.""" + +from __future__ import annotations + +import math +from dataclasses import dataclass +from datetime import UTC, datetime +from typing import Literal, cast + +import numpy as np +import polars as pl +from numpy.typing import NDArray +from sklearn.base import ClassifierMixin # type: ignore[import-untyped] +from sklearn.dummy import DummyClassifier # type: ignore[import-untyped] +from sklearn.impute import SimpleImputer # type: ignore[import-untyped] +from sklearn.linear_model import LogisticRegression # type: ignore[import-untyped] +from sklearn.metrics import ( # type: ignore[import-untyped] + accuracy_score, + average_precision_score, + balanced_accuracy_score, + brier_score_loss, + log_loss, + roc_auc_score, +) +from sklearn.pipeline import Pipeline # type: ignore[import-untyped] +from sklearn.preprocessing import StandardScaler # type: ignore[import-untyped] +from sklearn.tree import DecisionTreeClassifier # type: ignore[import-untyped] + +from microstructure.config import ModelConfig +from microstructure.research.features import model_feature_columns +from microstructure.research.splits import WalkForwardPlan + + +class ModelEvaluationError(ValueError): + """Raised when a model evaluation would be invalid or underidentified.""" + + +ModelFamily = Literal["baseline", "logistic", "logistic_l2", "shallow_tree"] + + +@dataclass(frozen=True, slots=True) +class ModelCandidate: + """One predeclared member of the transparent classification ladder.""" + + name: str + family: ModelFamily + c: float | None = None + max_depth: int | None = None + min_samples_leaf: int = 1 + + +@dataclass(frozen=True, slots=True) +class BootstrapResult: + """A deterministic block-bootstrap percentile interval.""" + + point_estimate: float + lower: float | None + upper: float | None + n_bootstrap: int + n_blocks: int + seed: int + status: Literal["ok", "insufficient_blocks"] + draws: tuple[float, ...] + + +@dataclass(frozen=True, slots=True) +class ModelLadderResult: + """Out-of-time predictions and fold/final-test comparison rows.""" + + predictions: pl.DataFrame + comparison: pl.DataFrame + selected_model: str + feature_columns: tuple[str, ...] + selection_metric: str + + +@dataclass(slots=True) +class SigmoidCalibrator: + """Platt-style calibration fitted only on a chronological calibration tail.""" + + estimator: LogisticRegression | None = None + status: str = "identity_not_fitted" + + def fit(self, y_true: NDArray[np.int64], raw_probability: NDArray[np.float64]) -> None: + if y_true.size < 8 or np.unique(y_true).size < 2: + self.status = "identity_insufficient_calibration_data" + return + transformed = _logit(raw_probability).reshape(-1, 1) + estimator = LogisticRegression(C=1.0, solver="lbfgs", max_iter=2_000) + estimator.fit(transformed, y_true) + self.estimator = estimator + self.status = "sigmoid" + + def transform(self, raw_probability: NDArray[np.float64]) -> NDArray[np.float64]: + if self.estimator is None: + return np.asarray(np.clip(raw_probability, 1e-12, 1.0 - 1e-12), dtype=np.float64) + probability = self.estimator.predict_proba(_logit(raw_probability).reshape(-1, 1))[:, 1] + return np.asarray(probability, dtype=np.float64) + + +def _logit(probability: NDArray[np.float64]) -> NDArray[np.float64]: + clipped = np.clip(probability, 1e-6, 1.0 - 1e-6) + return np.log(clipped / (1.0 - clipped)) + + +def build_model_candidates(config: ModelConfig) -> tuple[ModelCandidate, ...]: + """Expand the typed configuration into a stable, auditable model ladder.""" + + candidates: list[ModelCandidate] = [ModelCandidate("historical_prior", "baseline")] + candidates.append(ModelCandidate(name="logistic_unpenalized", family="logistic")) + candidates.extend( + ModelCandidate(name=f"logistic_l2_c_{value:g}", family="logistic_l2", c=value) + for value in config.logistic_c_values + ) + candidates.extend( + ModelCandidate( + name=f"tree_depth_{depth}", + family="shallow_tree", + max_depth=depth, + min_samples_leaf=config.tree_min_samples_leaf, + ) + for depth in config.tree_max_depth_values + ) + return tuple(candidates) + + +def make_classifier(candidate: ModelCandidate, *, seed: int) -> Pipeline: + """Construct a CPU-light classifier with train-only preprocessing.""" + + imputer = SimpleImputer(strategy="median", keep_empty_features=True) + if candidate.family == "baseline": + model: ClassifierMixin = DummyClassifier(strategy="prior") + return Pipeline([("imputer", imputer), ("model", model)]) + if candidate.family in {"logistic", "logistic_l2"}: + if candidate.family == "logistic_l2" and (candidate.c is None or candidate.c <= 0): + raise ModelEvaluationError("regularized logistic C must be positive") + model = LogisticRegression( + C=np.inf if candidate.family == "logistic" else candidate.c, + solver="lbfgs", + max_iter=2_000, + random_state=seed, + ) + return Pipeline([("imputer", imputer), ("scale", StandardScaler()), ("model", model)]) + if candidate.family == "shallow_tree": + if candidate.max_depth is None or candidate.max_depth < 1: + raise ModelEvaluationError("tree max_depth must be positive") + model = DecisionTreeClassifier( + max_depth=candidate.max_depth, + min_samples_leaf=candidate.min_samples_leaf, + random_state=seed, + ) + return Pipeline([("imputer", imputer), ("model", model)]) + raise ModelEvaluationError(f"unsupported model family: {candidate.family}") + + +def expected_calibration_error( + y_true: NDArray[np.int64], + probability: NDArray[np.float64], + *, + bins: int, +) -> float: + """Return fixed-width expected calibration error.""" + + if bins < 1: + raise ModelEvaluationError("calibration bins must be positive") + if y_true.size == 0: + return math.nan + probability = np.clip(probability, 0.0, 1.0) + assignments = np.digitize(probability, np.linspace(0.0, 1.0, bins + 1)[1:-1]) + result = 0.0 + for bin_index in range(bins): + mask = assignments == bin_index + if np.any(mask): + result += float(mask.mean()) * abs( + float(y_true[mask].mean()) - float(probability[mask].mean()) + ) + return result + + +def classification_metrics( + y_true: NDArray[np.int64], + probability: NDArray[np.float64], + *, + calibration_bins: int, +) -> dict[str, float]: + """Compute proper scoring, discrimination, and calibration metrics.""" + + if y_true.size == 0 or y_true.shape != probability.shape: + raise ModelEvaluationError("metric inputs must be equally sized and nonempty") + if not np.isin(y_true, [0, 1]).all(): + raise ModelEvaluationError("classification target must contain only 0 and 1") + probability = np.clip(probability.astype(np.float64), 1e-12, 1.0 - 1e-12) + prediction = (probability >= 0.5).astype(np.int64) + two_classes = np.unique(y_true).size == 2 + return { + "accuracy": float(accuracy_score(y_true, prediction)), + "balanced_accuracy": ( + float(balanced_accuracy_score(y_true, prediction)) if two_classes else math.nan + ), + "log_loss": float(log_loss(y_true, probability, labels=[0, 1])), + "brier_score": float(brier_score_loss(y_true, probability)), + "roc_auc": float(roc_auc_score(y_true, probability)) if two_classes else math.nan, + "pr_auc": ( + float(average_precision_score(y_true, probability)) if two_classes else math.nan + ), + "expected_calibration_error": expected_calibration_error( + y_true, probability, bins=calibration_bins + ), + "positive_rate": float(y_true.mean()), + } + + +def _positive_probability( + estimator: Pipeline, features: NDArray[np.float64] +) -> NDArray[np.float64]: + probabilities = np.asarray(estimator.predict_proba(features), dtype=np.float64) + classes = np.asarray(estimator.classes_) + if classes.size == 1: + return np.full(features.shape[0], float(classes[0] == 1), dtype=np.float64) + positive = np.flatnonzero(classes == 1) + if positive.size != 1: + raise ModelEvaluationError("classifier does not expose a binary positive class") + return np.asarray(probabilities[:, int(positive[0])], dtype=np.float64) + + +def _rows(frame: pl.DataFrame, indices: NDArray[np.int64]) -> pl.DataFrame: + return frame.filter(pl.col("_research_row_id").is_in(indices)) + + +def _chronological_calibration_split( + train: pl.DataFrame, + *, + fraction: float, +) -> tuple[pl.DataFrame, pl.DataFrame]: + if not 0.0 < fraction < 0.5: + raise ModelEvaluationError("calibration_fraction must be between zero and one half") + times = sorted(train.get_column("decision_ts_ns").unique().to_list()) + if len(times) < 6: + return train, train.head(0) + calibration_count = max(2, math.ceil(len(times) * fraction)) + calibration_start = int(times[-calibration_count]) + base = train.filter( + (pl.col("decision_ts_ns") < calibration_start) + & (pl.col("label_information_end_ts_ns") < calibration_start) + ) + calibration = train.filter(pl.col("decision_ts_ns") >= calibration_start) + if base.height < 4 or calibration.height < 8: + return train, train.head(0) + return base, calibration + + +def _fit_candidate( + candidate: ModelCandidate, + train: pl.DataFrame, + evaluate: pl.DataFrame, + *, + features: tuple[str, ...], + target: str, + seed: int, + calibration_fraction: float, +) -> tuple[NDArray[np.float64], NDArray[np.float64], str, int, ModelCandidate]: + base, calibration = _chronological_calibration_split(train, fraction=calibration_fraction) + x_base = base.select(features).to_numpy().astype(np.float64) + y_base = base.get_column(target).to_numpy().astype(np.int64) + fit_status = "ok" + effective_candidate = candidate + if np.unique(y_base).size < 2 and candidate.family != "baseline": + effective_candidate = ModelCandidate( + name=f"{candidate.name}__prior_fallback", + family="baseline", + ) + fit_status = "single_class_prior_fallback" + estimator = make_classifier(effective_candidate, seed=seed) + estimator.fit(x_base, y_base) + + calibrator = SigmoidCalibrator() + if not calibration.is_empty(): + x_calibration = calibration.select(features).to_numpy().astype(np.float64) + y_calibration = calibration.get_column(target).to_numpy().astype(np.int64) + calibrator.fit(y_calibration, _positive_probability(estimator, x_calibration)) + x_evaluate = evaluate.select(features).to_numpy().astype(np.float64) + raw_probability = _positive_probability(estimator, x_evaluate) + probability = calibrator.transform(raw_probability) + + fitting_rows = pl.concat([base, calibration]) if not calibration.is_empty() else base + fit_cutoff_value = fitting_rows.get_column("label_information_end_ts_ns").max() + if fit_cutoff_value is None: + raise ModelEvaluationError("training rows have no observable labels") + status = f"{fit_status};{calibrator.status}" + return raw_probability, probability, status, cast(int, fit_cutoff_value), effective_candidate + + +def _prediction_rows( + evaluated: pl.DataFrame, + *, + candidate: ModelCandidate, + requested_candidate: ModelCandidate, + fold_id: int, + split: Literal["validation", "test"], + target: str, + raw_probability: NDArray[np.float64], + probability: NDArray[np.float64], + fit_cutoff_ts_ns: int, +) -> list[dict[str, object]]: + result: list[dict[str, object]] = [] + for index, row in enumerate(evaluated.iter_rows(named=True)): + decision_ts_ns = int(row["decision_ts_ns"]) + symbol = str(row.get("symbol", "UNKNOWN")) + decision_sequence = int(row.get("decision_sequence", row["_research_row_id"])) + sample_id = str(row.get("sample_id", f"{symbol}:{decision_ts_ns}:{decision_sequence}")) + if fit_cutoff_ts_ns >= decision_ts_ns: + raise ModelEvaluationError("model fitting information reaches the evaluation decision") + result.append( + { + "row_id": int(row["_research_row_id"]), + "sample_id": sample_id, + "symbol": symbol, + "instrument": symbol, + "decision_ts_ns": decision_ts_ns, + "decision_sequence": decision_sequence, + "continuity_id": str(row.get("continuity_id", "UNKNOWN")), + "fold_id": fold_id, + "split": split, + "model": candidate.name, + "family": candidate.family, + "requested_model": requested_candidate.name, + "requested_family": requested_candidate.family, + "y_true": int(row[target]), + "raw_probability": float(raw_probability[index]), + "probability": float(probability[index]), + "predicted_class": int(probability[index] >= 0.5), + "fit_cutoff_ts_ns": fit_cutoff_ts_ns, + "is_oos": True, + } + ) + return result + + +def _metric_row( + *, + candidate: ModelCandidate, + requested_candidate: ModelCandidate, + fold_id: int, + split: Literal["validation", "test"], + y_true: NDArray[np.int64], + probability: NDArray[np.float64], + calibration_bins: int, + fit_status: str, + evaluated: pl.DataFrame, + horizon_events: int | None, +) -> dict[str, object]: + metrics = classification_metrics(y_true, probability, calibration_bins=calibration_bins) + period_start = cast(int, evaluated.get_column("decision_ts_ns").min()) + period_end = cast(int, evaluated.get_column("decision_ts_ns").max()) + instruments = sorted(str(value) for value in evaluated.get_column("symbol").unique()) + instrument_scope = instruments[0] if len(instruments) == 1 else "POOLED" + return { + "model": candidate.name, + "family": candidate.family, + "requested_model": requested_candidate.name, + "requested_family": requested_candidate.family, + "symbol": instrument_scope, + "instrument": instrument_scope, + "instrument_scope": instrument_scope, + "horizon_events": horizon_events, + "fold_id": fold_id, + "split": split, + "period_start_ts_ns": period_start, + "period_end_ts_ns": period_end, + "period_start_utc": _ns_to_utc(period_start), + "period_end_utc": _ns_to_utc(period_end), + "n_obs": int(y_true.size), + "fit_status": fit_status, + **metrics, + } + + +def _ns_to_utc(timestamp_ns: int) -> str: + return ( + datetime.fromtimestamp(timestamp_ns / 1_000_000_000, tz=UTC) + .isoformat() + .replace("+00:00", "Z") + ) + + +def _metric_direction(metric: str) -> Literal["min", "max"]: + if metric in {"log_loss", "brier_score", "expected_calibration_error"}: + return "min" + if metric in {"accuracy", "balanced_accuracy", "roc_auc", "pr_auc"}: + return "max" + raise ModelEvaluationError(f"unsupported selection metric: {metric}") + + +def _select_model( + comparison_rows: list[dict[str, object]], + candidates: tuple[ModelCandidate, ...], + metric: str, +) -> str: + direction = _metric_direction(metric) + scores: list[tuple[float, int, str]] = [] + for order, candidate in enumerate(candidates): + candidate_rows = [ + row + for row in comparison_rows + if row["split"] == "validation" + and row.get("requested_model", row["model"]) == candidate.name + ] + used_fallback = any(row["model"] != candidate.name for row in candidate_rows) + values = ( + [ + cast(float, row[metric]) + for row in candidate_rows + if math.isfinite(cast(float, row[metric])) + ] + if not used_fallback + else [] + ) + score = float(np.mean(values)) if values else math.nan + sortable = score if direction == "min" else -score + if not math.isfinite(sortable): + sortable = math.inf + scores.append((sortable, order, candidate.name)) + return min(scores)[2] + + +def evaluate_model_ladder( + frame: pl.DataFrame, + plan: WalkForwardPlan, + model_config: ModelConfig, + *, + seed: int, + calibration_bins: int, + target: str = "future_mid_up", + features: tuple[str, ...] | None = None, + calibration_fraction: float = 0.2, +) -> ModelLadderResult: + """Evaluate every model OOT, select on validation, then open final test once.""" + + if target not in frame.columns: + raise ModelEvaluationError(f"target column not found: {target}") + selected_features = features or model_feature_columns(frame) + missing_features = sorted(set(selected_features).difference(frame.columns)) + if missing_features: + raise ModelEvaluationError(f"feature columns not found: {missing_features}") + forbidden = [ + name + for name in selected_features + if name.startswith("future_") or name.startswith("label_") or name == "right_censored" + ] + if forbidden: + raise ModelEvaluationError(f"label/timing columns cannot be model features: {forbidden}") + + indexed = frame.with_row_index("_research_row_id") + candidates = build_model_candidates(model_config) + horizon: int | None = None + if "label_horizon_events" in frame.columns: + horizon_values = frame.get_column("label_horizon_events").drop_nulls().unique().to_list() + if len(horizon_values) == 1: + horizon = int(horizon_values[0]) + predictions: list[dict[str, object]] = [] + comparison: list[dict[str, object]] = [] + + for fold in plan.folds: + train = _rows(indexed, fold.train_indices).filter(pl.col(target).is_not_null()) + validation = _rows(indexed, fold.validation_indices).filter(pl.col(target).is_not_null()) + for candidate in candidates: + raw, calibrated, fit_status, fit_cutoff, effective_candidate = _fit_candidate( + candidate, + train, + validation, + features=selected_features, + target=target, + seed=seed, + calibration_fraction=calibration_fraction, + ) + y_validation = validation.get_column(target).to_numpy().astype(np.int64) + predictions.extend( + _prediction_rows( + validation, + candidate=effective_candidate, + requested_candidate=candidate, + fold_id=fold.fold_id, + split="validation", + target=target, + raw_probability=raw, + probability=calibrated, + fit_cutoff_ts_ns=fit_cutoff, + ) + ) + comparison.append( + _metric_row( + candidate=effective_candidate, + requested_candidate=candidate, + fold_id=fold.fold_id, + split="validation", + y_true=y_validation, + probability=calibrated, + calibration_bins=calibration_bins, + fit_status=fit_status, + evaluated=validation, + horizon_events=horizon, + ) + ) + + selected_model = _select_model(comparison, candidates, model_config.selection_metric) + + final_train = _rows(indexed, plan.final_train_indices).filter(pl.col(target).is_not_null()) + final_test = _rows(indexed, plan.test_indices).filter(pl.col(target).is_not_null()) + for candidate in candidates: + raw, calibrated, fit_status, fit_cutoff, effective_candidate = _fit_candidate( + candidate, + final_train, + final_test, + features=selected_features, + target=target, + seed=seed, + calibration_fraction=calibration_fraction, + ) + y_test = final_test.get_column(target).to_numpy().astype(np.int64) + predictions.extend( + _prediction_rows( + final_test, + candidate=effective_candidate, + requested_candidate=candidate, + fold_id=-1, + split="test", + target=target, + raw_probability=raw, + probability=calibrated, + fit_cutoff_ts_ns=fit_cutoff, + ) + ) + comparison.append( + _metric_row( + candidate=effective_candidate, + requested_candidate=candidate, + fold_id=-1, + split="test", + y_true=y_test, + probability=calibrated, + calibration_bins=calibration_bins, + fit_status=fit_status, + evaluated=final_test, + horizon_events=horizon, + ) + ) + + comparison_frame = pl.DataFrame(comparison).with_columns( + (pl.col("model") == selected_model).alias("selected_on_validation"), + pl.when(pl.col("model") == selected_model) + .then(pl.lit("validation")) + .otherwise(None) + .alias("selected_on"), + ) + prediction_frame = ( + pl.DataFrame(predictions) + .sort(["split", "fold_id", "model", "decision_ts_ns", "symbol"]) + .with_columns(pl.lit(horizon, dtype=pl.Int64).alias("horizon_events")) + ) + return ModelLadderResult( + predictions=prediction_frame, + comparison=comparison_frame, + selected_model=selected_model, + feature_columns=selected_features, + selection_metric=model_config.selection_metric, + ) + + +def _metric_from_arrays( + y_true: NDArray[np.int64], + probability: NDArray[np.float64], + metric: str, +) -> float: + metrics = classification_metrics(y_true, probability, calibration_bins=10) + if metric not in metrics: + raise ModelEvaluationError(f"unsupported bootstrap metric: {metric}") + return metrics[metric] + + +def _bootstrap_arrays( + predictions: pl.DataFrame, + *, + block_column: str, +) -> tuple[NDArray[np.int64], NDArray[np.float64], NDArray[np.object_], list[object]]: + required = {"y_true", "probability", block_column} + missing = sorted(required.difference(predictions.columns)) + if missing: + raise ModelEvaluationError(f"bootstrap predictions missing columns: {missing}") + y_true = predictions.get_column("y_true").to_numpy().astype(np.int64) + probability = predictions.get_column("probability").to_numpy().astype(np.float64) + blocks = predictions.get_column(block_column).to_numpy().astype(object) + unique_blocks = list(dict.fromkeys(blocks.tolist())) + return y_true, probability, blocks, unique_blocks + + +def block_bootstrap_metric( + predictions: pl.DataFrame, + *, + metric: str, + block_column: str, + n_bootstrap: int, + seed: int, +) -> BootstrapResult: + """Bootstrap complete dependency blocks rather than overlapping events.""" + + if n_bootstrap < 1: + raise ModelEvaluationError("n_bootstrap must be positive") + y_true, probability, blocks, unique_blocks = _bootstrap_arrays( + predictions, block_column=block_column + ) + point = _metric_from_arrays(y_true, probability, metric) + if len(unique_blocks) < 2: + return BootstrapResult( + point_estimate=point, + lower=None, + upper=None, + n_bootstrap=n_bootstrap, + n_blocks=len(unique_blocks), + seed=seed, + status="insufficient_blocks", + draws=(), + ) + + indices_by_block = {block: np.flatnonzero(blocks == block) for block in unique_blocks} + random = np.random.default_rng(seed) + draws: list[float] = [] + for _ in range(n_bootstrap): + sampled_positions = random.choice(len(unique_blocks), size=len(unique_blocks), replace=True) + sampled_blocks = [unique_blocks[int(position)] for position in sampled_positions] + sampled_indices = np.concatenate([indices_by_block[block] for block in sampled_blocks]) + draws.append( + _metric_from_arrays(y_true[sampled_indices], probability[sampled_indices], metric) + ) + finite = np.asarray([draw for draw in draws if math.isfinite(draw)], dtype=np.float64) + lower = float(np.quantile(finite, 0.025)) if finite.size else None + upper = float(np.quantile(finite, 0.975)) if finite.size else None + return BootstrapResult( + point_estimate=point, + lower=lower, + upper=upper, + n_bootstrap=n_bootstrap, + n_blocks=len(unique_blocks), + seed=seed, + status="ok", + draws=tuple(draws), + ) + + +def paired_block_bootstrap_difference( + left: pl.DataFrame, + right: pl.DataFrame, + *, + metric: str, + block_column: str, + n_bootstrap: int, + seed: int, +) -> BootstrapResult: + """Return a paired left-minus-right metric interval using common blocks.""" + + required = {"row_id", "y_true", "probability", block_column} + for name, frame in (("left", left), ("right", right)): + missing = sorted(required.difference(frame.columns)) + if missing: + raise ModelEvaluationError(f"{name} predictions missing columns: {missing}") + paired = left.select( + "row_id", + "y_true", + block_column, + pl.col("probability").alias("left_probability"), + ).join( + right.select( + "row_id", + pl.col("y_true").alias("right_y_true"), + pl.col("probability").alias("right_probability"), + ), + on="row_id", + how="inner", + validate="1:1", + ) + if paired.height != left.height or paired.height != right.height: + raise ModelEvaluationError("paired predictions must contain identical unique row IDs") + if paired.filter(pl.col("y_true") != pl.col("right_y_true")).height: + raise ModelEvaluationError("paired predictions disagree on target values") + + y_true = paired.get_column("y_true").to_numpy().astype(np.int64) + left_probability = paired.get_column("left_probability").to_numpy().astype(np.float64) + right_probability = paired.get_column("right_probability").to_numpy().astype(np.float64) + blocks = paired.get_column(block_column).to_numpy().astype(object) + unique_blocks = list(dict.fromkeys(blocks.tolist())) + point = _metric_from_arrays(y_true, left_probability, metric) - _metric_from_arrays( + y_true, right_probability, metric + ) + if len(unique_blocks) < 2: + return BootstrapResult( + point, None, None, n_bootstrap, len(unique_blocks), seed, "insufficient_blocks", () + ) + indices_by_block = {block: np.flatnonzero(blocks == block) for block in unique_blocks} + random = np.random.default_rng(seed) + draws: list[float] = [] + for _ in range(n_bootstrap): + sampled_positions = random.choice(len(unique_blocks), size=len(unique_blocks), replace=True) + sampled_blocks = [unique_blocks[int(position)] for position in sampled_positions] + sampled_indices = np.concatenate([indices_by_block[block] for block in sampled_blocks]) + draws.append( + _metric_from_arrays(y_true[sampled_indices], left_probability[sampled_indices], metric) + - _metric_from_arrays( + y_true[sampled_indices], right_probability[sampled_indices], metric + ) + ) + finite = np.asarray([draw for draw in draws if math.isfinite(draw)], dtype=np.float64) + return BootstrapResult( + point_estimate=point, + lower=float(np.quantile(finite, 0.025)) if finite.size else None, + upper=float(np.quantile(finite, 0.975)) if finite.size else None, + n_bootstrap=n_bootstrap, + n_blocks=len(unique_blocks), + seed=seed, + status="ok", + draws=tuple(draws), + ) + + +__all__ = [ + "BootstrapResult", + "ModelCandidate", + "ModelEvaluationError", + "ModelLadderResult", + "SigmoidCalibrator", + "block_bootstrap_metric", + "build_model_candidates", + "classification_metrics", + "evaluate_model_ladder", + "expected_calibration_error", + "make_classifier", + "paired_block_bootstrap_difference", +] diff --git a/Microstructure/src/microstructure/research/multidate.py b/Microstructure/src/microstructure/research/multidate.py new file mode 100644 index 0000000000000000000000000000000000000000..bda4c0c7f13205cfe7d8fa14d733225f96dd5fd5 --- /dev/null +++ b/Microstructure/src/microstructure/research/multidate.py @@ -0,0 +1,1950 @@ +"""Locked, date-level evaluation primitives for the public trade-only study. + +The module deliberately separates model selection from final-test evaluation. +``select_multidate_model`` accepts development data only, selects the requested +candidate, fits that candidate and an independent historical prior on the +combined train/validation reference period, and emits their transparent numeric +state in a content-hashed analysis lock. ``evaluate_locked_multidate_tests`` +restores only that verified state and predicts all declared test dates without +calling a fitting or update API. + +Date-level uncertainty is computed from fixed 40-event block sufficient +statistics. Bootstrap draws never materialize resampled event rows and are +generated in bounded chunks, which keeps the procedure usable for multi-million +row studies on a local machine. +""" + +from __future__ import annotations + +import hashlib +import json +import math +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from datetime import date, datetime +from typing import Any, Literal, cast + +import numpy as np +import polars as pl +import sklearn # type: ignore[import-untyped] +from numpy.typing import NDArray + +from microstructure.config import ModelConfig +from microstructure.research.analysis import feature_stability_summary +from microstructure.research.models import ( + BootstrapResult, + ModelCandidate, + SigmoidCalibrator, + build_model_candidates, + classification_metrics, + make_classifier, +) +from microstructure.research.splits import PurgedFold, WalkForwardPlan + +DATE_BOOTSTRAP_DRAWS = 2_000 +DATE_BOOTSTRAP_BLOCK_EVENTS = 40 +_BOOTSTRAP_DRAW_CHUNK = 32 +_MAX_BOOTSTRAP_INDEX_ELEMENTS = 1_000_000 +_LOCK_SCHEMA_VERSION = "multidate-selection-lock-v2" +_FITTED_STATE_SCHEMA_VERSION = "multidate-fitted-model-state-v1" +_FITTED_STATE_ARTIFACT_KIND = "multidate_final_fitted_models" +_FITTED_STATE_SERIALIZATION_FORMAT = "canonical-json-numeric-v1" +_DEVELOPMENT_ROLES = frozenset({"train", "validation"}) +_TEST_ROLES = frozenset({"test", "primary_test", "replication_test"}) +_ALL_ROLES = _DEVELOPMENT_ROLES | _TEST_ROLES + +ReplicationStatus = Literal[ + "replicated", + "failed_replication", + "no_primary_improvement", + "insufficient_replication_dates", +] + + +class MultiDateEvaluationError(ValueError): + """Raised when the locked date-level protocol would be violated.""" + + +@dataclass(frozen=True, slots=True) +class AnalysisLock: + """Canonical JSON selection lock suitable for persistence before testing.""" + + payload_json: str + sha256: str + + @classmethod + def create(cls, payload: Mapping[str, object]) -> AnalysisLock: + encoded = json.dumps( + dict(payload), + sort_keys=True, + separators=(",", ":"), + allow_nan=False, + ) + return cls(encoded, hashlib.sha256(encoded.encode()).hexdigest()) + + @classmethod + def restore(cls, payload_json: str, sha256: str) -> AnalysisLock: + lock = cls(payload_json=payload_json, sha256=sha256.lower()) + lock.payload() + return lock + + def payload(self) -> dict[str, Any]: + observed = hashlib.sha256(self.payload_json.encode()).hexdigest() + if observed != self.sha256: + raise MultiDateEvaluationError("selection lock payload does not match its SHA-256") + decoded = json.loads(self.payload_json) + if not isinstance(decoded, dict): + raise MultiDateEvaluationError("selection lock payload must be a JSON object") + if decoded.get("schema_version") != _LOCK_SCHEMA_VERSION: + raise MultiDateEvaluationError("unsupported selection lock schema version") + return cast(dict[str, Any], decoded) + + +@dataclass(frozen=True, slots=True) +class FinalFittedState: + """Canonical, non-executable numeric state for the two final classifiers.""" + + payload_json: str + sha256: str + + @classmethod + def create(cls, payload: Mapping[str, object]) -> FinalFittedState: + encoded = _canonical_json_text(payload) + state = cls(encoded, hashlib.sha256(encoded.encode()).hexdigest()) + state.payload() + return state + + @classmethod + def restore(cls, payload_json: str, sha256: str) -> FinalFittedState: + state = cls(payload_json=payload_json, sha256=sha256.lower()) + state.payload() + return state + + def payload(self) -> dict[str, Any]: + observed = hashlib.sha256(self.payload_json.encode()).hexdigest() + if observed != self.sha256: + raise MultiDateEvaluationError("fitted-state payload does not match its SHA-256") + decoded = _decode_json_object(self.payload_json, "fitted-state payload") + if self.payload_json != _canonical_json_text(decoded): + raise MultiDateEvaluationError("fitted-state payload is not canonical JSON") + _validate_final_fitted_state_payload(decoded) + return decoded + + def predict( + self, + role: Literal["selected", "historical_prior"], + features: NDArray[np.float64], + ) -> tuple[NDArray[np.float64], NDArray[np.float64]]: + payload = self.payload() + models = cast(Mapping[str, Any], payload["models"]) + model = cast(Mapping[str, Any], models[role]) + return _predict_serialized_model(model, features) + + +@dataclass(frozen=True, slots=True) +class LockedSelection: + """Validation-only model selection plus its persistable analysis lock.""" + + lock: AnalysisLock + validation_comparison: pl.DataFrame + selected_candidate: ModelCandidate + feature_columns: tuple[str, ...] + target: str + train_dates: tuple[str, ...] + validation_date: str + declared_test_dates: tuple[str, ...] + development_frame_sha256: str + fitted_data_cutoff_policy: str + fitted_state: FinalFittedState + + @property + def selected_model(self) -> str: + return self.selected_candidate.name + + +@dataclass(frozen=True, slots=True) +class PairedDateLogLossResult: + """Per-date paired loss diagnostics and equal-date-weighted uncertainty.""" + + predictions: pl.DataFrame + per_date: pl.DataFrame + aggregate: BootstrapResult + replication_status: ReplicationStatus + + +@dataclass(frozen=True, slots=True) +class LockedMultiDateTestResult: + """Final locked predictions and descriptive diagnostics for all test dates.""" + + plan: WalkForwardPlan + predictions: pl.DataFrame + paired_log_loss: PairedDateLogLossResult + feature_stability: pl.DataFrame + selected_model: str + lock_sha256: str + + +@dataclass(frozen=True, slots=True) +class _FitMatrices: + x_base: NDArray[np.float64] + y_base: NDArray[np.int64] + x_calibration: NDArray[np.float64] + y_calibration: NDArray[np.int64] + x_evaluate: NDArray[np.float64] + fit_cutoff_ts_ns: int + + +@dataclass(frozen=True, slots=True) +class _FitOutcome: + raw_probability: NDArray[np.float64] + probability: NDArray[np.float64] + fit_status: str + fit_cutoff_ts_ns: int + effective_candidate: ModelCandidate + fitted_state: Mapping[str, object] | None + + +@dataclass(frozen=True, slots=True) +class _SelectionSpec: + lock: AnalysisLock + candidate: ModelCandidate + feature_columns: tuple[str, ...] + target: str + seed: int + calibration_bins: int + calibration_fraction: float + train_dates: tuple[str, ...] + validation_date: str + test_dates: tuple[str, ...] + development_frame_sha256: str + block_width_events: int + bootstrap_draws: int + fitted_state: FinalFittedState + + +def _canonical_json_text(value: Mapping[str, object]) -> str: + try: + return json.dumps( + dict(value), + sort_keys=True, + separators=(",", ":"), + ensure_ascii=True, + allow_nan=False, + ) + except (TypeError, ValueError) as error: + raise MultiDateEvaluationError("fitted state is not finite canonical JSON") from error + + +def _decode_json_object(payload_json: str, label: str) -> dict[str, Any]: + def reject_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + raise MultiDateEvaluationError(f"{label} repeats key {key!r}") + result[key] = value + return result + + def reject_constant(value: str) -> object: + raise MultiDateEvaluationError(f"{label} contains forbidden constant {value}") + + try: + decoded = json.loads( + payload_json, + object_pairs_hook=reject_duplicates, + parse_constant=reject_constant, + ) + except MultiDateEvaluationError: + raise + except (TypeError, json.JSONDecodeError) as error: + raise MultiDateEvaluationError(f"{label} is not valid JSON") from error + if not isinstance(decoded, dict) or not all(type(key) is str for key in decoded): + raise MultiDateEvaluationError(f"{label} must be a JSON object") + return cast(dict[str, Any], decoded) + + +def _mapping(value: object, label: str) -> Mapping[str, Any]: + if not isinstance(value, Mapping) or not all(type(key) is str for key in value): + raise MultiDateEvaluationError(f"{label} must be a JSON object") + return cast(Mapping[str, Any], value) + + +def _exact_keys(value: Mapping[str, Any], expected: frozenset[str], label: str) -> None: + observed = frozenset(value) + if observed != expected: + raise MultiDateEvaluationError( + f"{label} keys differ: missing={sorted(expected - observed)}, " + f"extra={sorted(observed - expected)}" + ) + + +def _strict_int(value: object, label: str, *, minimum: int | None = None) -> int: + if isinstance(value, bool) or not isinstance(value, int): + raise MultiDateEvaluationError(f"{label} must be an integer") + if minimum is not None and value < minimum: + raise MultiDateEvaluationError(f"{label} must be >= {minimum}") + return value + + +def _finite_float(value: object, label: str) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise MultiDateEvaluationError(f"{label} must be numeric") + result = float(value) + if not math.isfinite(result): + raise MultiDateEvaluationError(f"{label} must be finite") + return result + + +def _string(value: object, label: str) -> str: + if type(value) is not str or not value: + raise MultiDateEvaluationError(f"{label} must be a nonempty string") + return value + + +def _numeric_vector(value: object, label: str, *, length: int) -> list[float]: + if not isinstance(value, list) or len(value) != length: + raise MultiDateEvaluationError(f"{label} must contain exactly {length} values") + return [_finite_float(item, f"{label}[{index}]") for index, item in enumerate(value)] + + +def _integer_vector(value: object, label: str, *, length: int) -> list[int]: + if not isinstance(value, list) or len(value) != length: + raise MultiDateEvaluationError(f"{label} must contain exactly {length} integers") + return [_strict_int(item, f"{label}[{index}]") for index, item in enumerate(value)] + + +def _class_vector(value: object, label: str) -> list[int]: + if not isinstance(value, list) or not value: + raise MultiDateEvaluationError(f"{label} must be a nonempty class array") + result = [_strict_int(item, f"{label}[{index}]") for index, item in enumerate(value)] + if result != sorted(set(result)) or not set(result).issubset({0, 1}): + raise MultiDateEvaluationError(f"{label} must be unique ordered binary classes") + return result + + +def _validate_candidate_payload_strict(value: object, label: str) -> ModelCandidate: + payload = _mapping(value, label) + _exact_keys( + payload, + frozenset({"name", "family", "c", "max_depth", "min_samples_leaf"}), + label, + ) + name = _string(payload["name"], f"{label}.name") + family = _string(payload["family"], f"{label}.family") + if family not in {"baseline", "logistic", "logistic_l2", "shallow_tree"}: + raise MultiDateEvaluationError(f"{label} has an unsupported model family") + raw_c = payload["c"] + c = None if raw_c is None else _finite_float(raw_c, f"{label}.c") + raw_depth = payload["max_depth"] + max_depth = ( + None if raw_depth is None else _strict_int(raw_depth, f"{label}.max_depth", minimum=1) + ) + min_samples_leaf = _strict_int( + payload["min_samples_leaf"], + f"{label}.min_samples_leaf", + minimum=1, + ) + if c is not None and c <= 0.0: + raise MultiDateEvaluationError(f"{label}.c must be positive") + if family == "logistic_l2" and c is None: + raise MultiDateEvaluationError(f"{label}.c is required for logistic_l2") + if family != "logistic_l2" and c is not None: + raise MultiDateEvaluationError(f"{label}.c is only valid for logistic_l2") + if family == "shallow_tree" and max_depth is None: + raise MultiDateEvaluationError(f"{label}.max_depth is required for shallow_tree") + if family != "shallow_tree" and max_depth is not None: + raise MultiDateEvaluationError(f"{label}.max_depth is only valid for shallow_tree") + return ModelCandidate( + name=name, + family=cast(Any, family), + c=c, + max_depth=max_depth, + min_samples_leaf=min_samples_leaf, + ) + + +def _validate_classifier_payload( + value: object, + *, + feature_count: int, + effective: ModelCandidate, + label: str, +) -> None: + payload = _mapping(value, label) + kind = _string(payload.get("kind"), f"{label}.kind") + if kind == "prior": + _exact_keys(payload, frozenset({"kind", "classes", "class_probabilities"}), label) + classes = _class_vector(payload["classes"], f"{label}.classes") + probabilities = _numeric_vector( + payload["class_probabilities"], + f"{label}.class_probabilities", + length=len(classes), + ) + if any(not 0.0 <= item <= 1.0 for item in probabilities) or not math.isclose( + sum(probabilities), 1.0, rel_tol=0.0, abs_tol=1e-12 + ): + raise MultiDateEvaluationError(f"{label} has invalid class probabilities") + if effective.family != "baseline": + raise MultiDateEvaluationError( + f"{label} prior state disagrees with effective candidate" + ) + return + if kind == "logistic": + _exact_keys( + payload, + frozenset( + { + "kind", + "classes", + "scaler_mean", + "scaler_scale", + "coefficients", + "intercept", + } + ), + label, + ) + if _class_vector(payload["classes"], f"{label}.classes") != [0, 1]: + raise MultiDateEvaluationError(f"{label} logistic state requires classes [0, 1]") + _numeric_vector(payload["scaler_mean"], f"{label}.scaler_mean", length=feature_count) + scales = _numeric_vector( + payload["scaler_scale"], f"{label}.scaler_scale", length=feature_count + ) + if any(item <= 0.0 for item in scales): + raise MultiDateEvaluationError(f"{label} scaler scales must be positive") + _numeric_vector(payload["coefficients"], f"{label}.coefficients", length=feature_count) + _finite_float(payload["intercept"], f"{label}.intercept") + if effective.family not in {"logistic", "logistic_l2"}: + raise MultiDateEvaluationError( + f"{label} logistic state disagrees with effective candidate" + ) + return + if kind != "decision_tree": + raise MultiDateEvaluationError(f"{label} has an unsupported classifier kind") + _exact_keys( + payload, + frozenset( + { + "kind", + "classes", + "node_count", + "children_left", + "children_right", + "feature", + "threshold", + "positive_probability", + } + ), + label, + ) + if effective.family != "shallow_tree": + raise MultiDateEvaluationError(f"{label} tree state disagrees with effective candidate") + _class_vector(payload["classes"], f"{label}.classes") + node_count = _strict_int(payload["node_count"], f"{label}.node_count", minimum=1) + left = _integer_vector(payload["children_left"], f"{label}.children_left", length=node_count) + right = _integer_vector(payload["children_right"], f"{label}.children_right", length=node_count) + features = _integer_vector(payload["feature"], f"{label}.feature", length=node_count) + _numeric_vector(payload["threshold"], f"{label}.threshold", length=node_count) + positive = _numeric_vector( + payload["positive_probability"], + f"{label}.positive_probability", + length=node_count, + ) + if any(not 0.0 <= item <= 1.0 for item in positive): + raise MultiDateEvaluationError(f"{label} has an invalid leaf probability") + for index, (left_child, right_child, feature) in enumerate( + zip(left, right, features, strict=True) + ): + leaf = left_child == -1 and right_child == -1 + if leaf: + continue + if not (0 <= left_child < node_count and 0 <= right_child < node_count): + raise MultiDateEvaluationError(f"{label} node {index} has an invalid child") + if not 0 <= feature < feature_count: + raise MultiDateEvaluationError(f"{label} node {index} has an invalid feature") + + +def _validate_calibrator_payload(value: object, label: str) -> None: + payload = _mapping(value, label) + kind = _string(payload.get("kind"), f"{label}.kind") + if kind == "identity": + _exact_keys(payload, frozenset({"kind", "status"}), label) + status = _string(payload["status"], f"{label}.status") + if not status.startswith("identity_"): + raise MultiDateEvaluationError(f"{label} identity status is invalid") + return + if kind != "sigmoid": + raise MultiDateEvaluationError(f"{label} has an unsupported calibrator kind") + _exact_keys( + payload, + frozenset({"kind", "status", "classes", "coefficient", "intercept"}), + label, + ) + if payload["status"] != "sigmoid": + raise MultiDateEvaluationError(f"{label} sigmoid status is invalid") + if _class_vector(payload["classes"], f"{label}.classes") != [0, 1]: + raise MultiDateEvaluationError(f"{label} sigmoid state requires classes [0, 1]") + _finite_float(payload["coefficient"], f"{label}.coefficient") + _finite_float(payload["intercept"], f"{label}.intercept") + + +def _validate_serialized_model( + value: object, + *, + role: str, + feature_count: int, +) -> None: + label = f"fitted state model {role}" + payload = _mapping(value, label) + _exact_keys( + payload, + frozenset( + { + "role", + "requested_candidate", + "effective_candidate", + "fit_status", + "fit_cutoff_ts_ns", + "base_fit_rows", + "calibration_rows", + "imputer_statistics", + "classifier", + "calibrator", + } + ), + label, + ) + if payload["role"] != role: + raise MultiDateEvaluationError(f"{label} has a mismatched role") + _validate_candidate_payload_strict(payload["requested_candidate"], f"{label}.requested") + effective = _validate_candidate_payload_strict( + payload["effective_candidate"], f"{label}.effective" + ) + _string(payload["fit_status"], f"{label}.fit_status") + _strict_int(payload["fit_cutoff_ts_ns"], f"{label}.fit_cutoff_ts_ns", minimum=1) + _strict_int(payload["base_fit_rows"], f"{label}.base_fit_rows", minimum=1) + _strict_int(payload["calibration_rows"], f"{label}.calibration_rows", minimum=0) + _numeric_vector( + payload["imputer_statistics"], + f"{label}.imputer_statistics", + length=feature_count, + ) + _validate_classifier_payload( + payload["classifier"], + feature_count=feature_count, + effective=effective, + label=f"{label}.classifier", + ) + _validate_calibrator_payload(payload["calibrator"], f"{label}.calibrator") + + +def _validate_final_fitted_state_payload(payload: Mapping[str, Any]) -> None: + _exact_keys( + payload, + frozenset( + { + "schema_version", + "artifact_kind", + "serialization_format", + "library_versions", + "feature_columns", + "target", + "development_frame_sha256", + "fit_cutoff_ts_ns", + "eligible_development_rows", + "models", + } + ), + "final fitted state", + ) + if payload["schema_version"] != _FITTED_STATE_SCHEMA_VERSION: + raise MultiDateEvaluationError("unsupported fitted-state schema version") + if payload["artifact_kind"] != _FITTED_STATE_ARTIFACT_KIND: + raise MultiDateEvaluationError("unsupported fitted-state artifact kind") + if payload["serialization_format"] != _FITTED_STATE_SERIALIZATION_FORMAT: + raise MultiDateEvaluationError("unsupported fitted-state serialization format") + versions = _mapping(payload["library_versions"], "fitted-state library versions") + _exact_keys(versions, frozenset({"numpy", "scikit_learn"}), "fitted-state library versions") + _string(versions["numpy"], "fitted-state NumPy version") + _string(versions["scikit_learn"], "fitted-state scikit-learn version") + features_raw = payload["feature_columns"] + if not isinstance(features_raw, list) or not features_raw: + raise MultiDateEvaluationError("fitted-state feature columns must be nonempty") + features = tuple(_string(item, "fitted-state feature") for item in features_raw) + if len(set(features)) != len(features): + raise MultiDateEvaluationError("fitted-state feature columns must be unique") + _string(payload["target"], "fitted-state target") + development_sha = _string(payload["development_frame_sha256"], "fitted-state development SHA") + if len(development_sha) != 64 or any( + character not in "0123456789abcdef" for character in development_sha + ): + raise MultiDateEvaluationError("fitted-state development SHA is invalid") + cutoff = _strict_int(payload["fit_cutoff_ts_ns"], "fitted-state cutoff", minimum=1) + _strict_int( + payload["eligible_development_rows"], + "fitted-state eligible rows", + minimum=1, + ) + models = _mapping(payload["models"], "fitted-state models") + _exact_keys(models, frozenset({"selected", "historical_prior"}), "fitted-state models") + for role in ("selected", "historical_prior"): + _validate_serialized_model(models[role], role=role, feature_count=len(features)) + model = _mapping(models[role], f"fitted-state model {role}") + if model["fit_cutoff_ts_ns"] != cutoff: + raise MultiDateEvaluationError("fitted-state model cutoffs disagree") + + +_TEMPORAL_COLUMNS = frozenset( + { + "study_date", + "study_role", + "symbol", + "decision_ts_ns", + "decision_trade_id", + "decision_sequence", + "continuity_id", + "feature_continuity_id", + "label_continuity_id", + "max_feature_source_ts_ns", + "max_feature_source_trade_id", + "label_start_ts_ns", + "label_start_trade_id", + "label_information_end_ts_ns", + "label_information_end_trade_id", + "feature_ready", + "right_censored", + } +) + + +def _require_columns(frame: pl.DataFrame, columns: Sequence[str], label: str) -> None: + missing = sorted(set(columns).difference(frame.columns)) + if missing: + raise MultiDateEvaluationError(f"{label} is missing required columns: {missing}") + if frame.is_empty(): + raise MultiDateEvaluationError(f"{label} must not be empty") + + +def _parse_dates(values: Sequence[object], *, label: str) -> tuple[str, ...]: + normalized = tuple(str(value) for value in values) + if not normalized or len(set(normalized)) != len(normalized): + raise MultiDateEvaluationError(f"{label} must contain unique dates") + try: + for value in normalized: + date.fromisoformat(value) + except ValueError as error: + raise MultiDateEvaluationError(f"{label} must use ISO YYYY-MM-DD dates") from error + return tuple(sorted(normalized)) + + +def _timestamp_date(column: str) -> pl.Expr: + return pl.col(column).cast(pl.Datetime("ns", time_zone="UTC")).dt.strftime("%Y-%m-%d") + + +def _validate_date_local_temporal_contract(frame: pl.DataFrame) -> None: + _require_columns(frame, tuple(_TEMPORAL_COLUMNS), "multi-date evaluation frame") + for column in ( + "study_date", + "study_role", + "symbol", + "decision_ts_ns", + "decision_trade_id", + "decision_sequence", + "continuity_id", + "feature_continuity_id", + "max_feature_source_ts_ns", + "max_feature_source_trade_id", + "label_start_ts_ns", + "label_start_trade_id", + "feature_ready", + "right_censored", + ): + if frame.get_column(column).null_count(): + raise MultiDateEvaluationError(f"multi-date column {column!r} must not contain nulls") + + roles = set(str(value) for value in frame.get_column("study_role").unique().to_list()) + if not roles.issubset(_ALL_ROLES): + raise MultiDateEvaluationError(f"unsupported study roles: {sorted(roles - _ALL_ROLES)}") + _parse_dates(frame.get_column("study_date").unique().to_list(), label="study_date") + + date_roles = frame.group_by("study_date").agg(pl.col("study_role").n_unique().alias("n")) + if date_roles.filter(pl.col("n") != 1).height: + raise MultiDateEvaluationError("each study date must have exactly one study role") + if frame.get_column("symbol").n_unique() != 1: + raise MultiDateEvaluationError( + "multi-date evaluation is per instrument; pool instruments only after reporting" + ) + duplicate_identity = ( + frame.group_by("symbol", "study_date", "decision_sequence").len().filter(pl.col("len") != 1) + ) + if duplicate_identity.height: + raise MultiDateEvaluationError("date-level decision identities must be unique") + + if frame.filter(_timestamp_date("decision_ts_ns") != pl.col("study_date")).height: + raise MultiDateEvaluationError("decision timestamps must fall inside study_date") + if frame.filter(_timestamp_date("max_feature_source_ts_ns") != pl.col("study_date")).height: + raise MultiDateEvaluationError("feature lineage must remain inside study_date") + if frame.filter(pl.col("max_feature_source_ts_ns") > pl.col("decision_ts_ns")).height: + raise MultiDateEvaluationError("feature lineage reaches beyond its decision") + if frame.filter( + (pl.col("max_feature_source_ts_ns") == pl.col("decision_ts_ns")) + & (pl.col("max_feature_source_trade_id") > pl.col("decision_trade_id")) + ).height: + raise MultiDateEvaluationError("feature lineage reaches beyond its decision boundary") + if frame.filter(pl.col("feature_continuity_id") != pl.col("continuity_id")).height: + raise MultiDateEvaluationError("feature lookbacks must remain in decision continuity") + + if frame.filter( + (pl.col("label_start_ts_ns") != pl.col("decision_ts_ns")) + | (pl.col("label_start_trade_id") != pl.col("decision_trade_id")) + ).height: + raise MultiDateEvaluationError( + "label start boundary must equal the decision timestamp and trade ID" + ) + if frame.filter(_timestamp_date("label_start_ts_ns") != pl.col("study_date")).height: + raise MultiDateEvaluationError("label starts must remain inside study_date") + + labeled = frame.filter(~pl.col("right_censored")) + for column in ( + "label_continuity_id", + "label_start_ts_ns", + "label_start_trade_id", + "label_information_end_ts_ns", + "label_information_end_trade_id", + ): + if labeled.get_column(column).null_count(): + raise MultiDateEvaluationError(f"uncensored labels require non-null {column}") + if labeled.filter(pl.col("label_continuity_id") != pl.col("continuity_id")).height: + raise MultiDateEvaluationError("labels must remain in decision continuity") + if labeled.filter( + (pl.col("label_information_end_ts_ns") < pl.col("decision_ts_ns")) + | ( + (pl.col("label_information_end_ts_ns") == pl.col("decision_ts_ns")) + & (pl.col("label_information_end_trade_id") <= pl.col("decision_trade_id")) + ) + ).height: + raise MultiDateEvaluationError( + "label information end must be strictly later by timestamp/trade-ID order" + ) + if labeled.filter( + _timestamp_date("label_information_end_ts_ns") != pl.col("study_date") + ).height: + raise MultiDateEvaluationError("label endpoints must remain inside study_date") + + for column in ("continuity_id", "feature_continuity_id"): + reused = ( + frame.group_by(column) + .agg(pl.col("study_date").n_unique().alias("date_count")) + .filter(pl.col("date_count") != 1) + ) + if reused.height: + raise MultiDateEvaluationError(f"{column} cannot span study dates") + label_reused = ( + labeled.group_by("label_continuity_id") + .agg(pl.col("study_date").n_unique().alias("date_count")) + .filter(pl.col("date_count") != 1) + ) + if label_reused.height: + raise MultiDateEvaluationError("label_continuity_id cannot span study dates") + censored = frame.filter(pl.col("right_censored")) + if censored.filter( + pl.col("label_information_end_ts_ns").is_not_null() + | pl.col("label_information_end_trade_id").is_not_null() + | pl.col("label_continuity_id").is_not_null() + ).height: + raise MultiDateEvaluationError("censored label endpoints and continuity must remain null") + + +def _combine_date_frames( + frames: Sequence[pl.DataFrame], + *, + allowed_roles: frozenset[str], + label: str, +) -> pl.DataFrame: + materialized = tuple(frames) + if not materialized: + raise MultiDateEvaluationError(f"{label} must include at least one per-date frame") + normalized: list[tuple[str, pl.DataFrame]] = [] + for index, source in enumerate(materialized): + _require_columns(source, tuple(_TEMPORAL_COLUMNS), f"{label}[{index}]") + frame = source.with_columns( + pl.col("study_date").cast(pl.String), + pl.col("study_role").cast(pl.String), + ) + dates = frame.get_column("study_date").unique().to_list() + roles = frame.get_column("study_role").unique().to_list() + if len(dates) != 1 or len(roles) != 1: + raise MultiDateEvaluationError(f"{label}[{index}] must contain exactly one date/role") + role = str(roles[0]) + if role not in allowed_roles: + raise MultiDateEvaluationError(f"{label}[{index}] has disallowed role {role!r}") + ordering = frame.select("decision_ts_ns", "decision_sequence").with_columns( + pl.col("decision_ts_ns").shift(1).alias("_prior_ts"), + pl.col("decision_sequence").shift(1).alias("_prior_sequence"), + ) + if ordering.filter( + (pl.col("decision_ts_ns") < pl.col("_prior_ts")) + | ( + (pl.col("decision_ts_ns") == pl.col("_prior_ts")) + & (pl.col("decision_sequence") < pl.col("_prior_sequence")) + ) + ).height: + raise MultiDateEvaluationError( + f"{label}[{index}] must already be in decision/sequence order" + ) + normalized.append((str(dates[0]), frame)) + # Per-date inputs are already physically ordered; ordering the small list of + # frame descriptors avoids a full-width multi-million-row sort/copy. + combined = pl.concat( + [frame for _, frame in sorted(normalized, key=lambda item: item[0])], + how="vertical", + ) + _validate_date_local_temporal_contract(combined) + return combined + + +def _eligible() -> pl.Expr: + return pl.col("feature_ready") & (~pl.col("right_censored")) + + +def _frame_sha256(frame: pl.DataFrame) -> str: + """Hash ordered row identities without serializing a second full frame.""" + + digest = hashlib.sha256() + schema = [(name, str(dtype)) for name, dtype in frame.schema.items()] + digest.update(json.dumps(schema, separators=(",", ":")).encode()) + row_hashes = frame.hash_rows(seed=0, seed_1=1, seed_2=2, seed_3=3) + for chunk in row_hashes.get_chunks(): + values = chunk.to_numpy().astype(" tuple[pl.DataFrame, pl.DataFrame]: + if not 0.0 < fraction < 0.5: + raise MultiDateEvaluationError("calibration_fraction must be between zero and one half") + times = sorted(int(value) for value in train.get_column("decision_ts_ns").unique().to_list()) + if len(times) < 6: + return train, train.head(0) + calibration_count = max(2, math.ceil(len(times) * fraction)) + calibration_start = times[-calibration_count] + base = train.filter( + (pl.col("decision_ts_ns") < calibration_start) + & (pl.col("label_information_end_ts_ns") < calibration_start) + ) + calibration = train.filter(pl.col("decision_ts_ns") >= calibration_start) + if base.height < 4 or calibration.height < 8: + return train, train.head(0) + return base, calibration + + +def _fit_matrices( + train: pl.DataFrame, + evaluate: pl.DataFrame, + *, + features: tuple[str, ...], + target: str, + calibration_fraction: float, +) -> _FitMatrices: + base, calibration = _chronological_calibration_split(train, fraction=calibration_fraction) + fit_cutoff = train.get_column("label_information_end_ts_ns").max() + if fit_cutoff is None: + raise MultiDateEvaluationError("training data have no observable labels") + empty_features = np.empty((0, len(features)), dtype=np.float64) + empty_targets = np.empty(0, dtype=np.int64) + return _FitMatrices( + x_base=base.select(features).to_numpy().astype(np.float64, copy=False), + y_base=base.get_column(target).to_numpy().astype(np.int64, copy=False), + x_calibration=( + calibration.select(features).to_numpy().astype(np.float64, copy=False) + if not calibration.is_empty() + else empty_features + ), + y_calibration=( + calibration.get_column(target).to_numpy().astype(np.int64, copy=False) + if not calibration.is_empty() + else empty_targets + ), + x_evaluate=evaluate.select(features).to_numpy().astype(np.float64, copy=False), + fit_cutoff_ts_ns=int(cast(int, fit_cutoff)), + ) + + +def _positive_probability(estimator: Any, features: NDArray[np.float64]) -> NDArray[np.float64]: + probabilities = np.asarray(estimator.predict_proba(features), dtype=np.float64) + classes = np.asarray(estimator.classes_) + if classes.size == 1: + return np.full(features.shape[0], float(classes[0] == 1), dtype=np.float64) + positive = np.flatnonzero(classes == 1) + if positive.size != 1: + raise MultiDateEvaluationError("classifier does not expose one binary positive class") + return np.asarray(probabilities[:, int(positive[0])], dtype=np.float64) + + +def _float_list(values: object) -> list[float]: + array = np.asarray(values, dtype=np.float64).reshape(-1) + result = [float(value) for value in array] + if any(not math.isfinite(value) for value in result): + raise MultiDateEvaluationError("fitted estimator contains a non-finite parameter") + return result + + +def _integer_list(values: object) -> list[int]: + return [int(value) for value in np.asarray(values).reshape(-1)] + + +def _classifier_state(estimator: Any, effective: ModelCandidate) -> dict[str, object]: + model = estimator.named_steps["model"] + classes = _integer_list(model.classes_) + if effective.family == "baseline": + return { + "kind": "prior", + "classes": classes, + "class_probabilities": _float_list(model.class_prior_), + } + if effective.family in {"logistic", "logistic_l2"}: + scaler = estimator.named_steps["scale"] + coefficients = np.asarray(model.coef_, dtype=np.float64) + intercept = np.asarray(model.intercept_, dtype=np.float64) + if coefficients.shape[0] != 1 or intercept.shape != (1,): + raise MultiDateEvaluationError("final logistic estimator is not binary") + return { + "kind": "logistic", + "classes": classes, + "scaler_mean": _float_list(scaler.mean_), + "scaler_scale": _float_list(scaler.scale_), + "coefficients": _float_list(coefficients[0]), + "intercept": float(intercept[0]), + } + if effective.family != "shallow_tree": + raise MultiDateEvaluationError("cannot serialize an unsupported final classifier") + tree = model.tree_ + values = np.asarray(tree.value, dtype=np.float64) + if values.ndim != 3 or values.shape[1] != 1 or values.shape[0] != int(tree.node_count): + raise MultiDateEvaluationError("final decision-tree state has an unsupported shape") + positive_index = classes.index(1) if 1 in classes else None + totals = values[:, 0, :].sum(axis=1) + if np.any(totals <= 0.0): + raise MultiDateEvaluationError("final decision tree contains an empty node") + positive_probability = ( + np.zeros(int(tree.node_count), dtype=np.float64) + if positive_index is None + else values[:, 0, positive_index] / totals + ) + return { + "kind": "decision_tree", + "classes": classes, + "node_count": int(tree.node_count), + "children_left": _integer_list(tree.children_left), + "children_right": _integer_list(tree.children_right), + "feature": _integer_list(tree.feature), + "threshold": _float_list(tree.threshold), + "positive_probability": _float_list(positive_probability), + } + + +def _calibrator_state(calibrator: SigmoidCalibrator) -> dict[str, object]: + if calibrator.estimator is None: + return {"kind": "identity", "status": calibrator.status} + estimator = calibrator.estimator + classes = _integer_list(estimator.classes_) + coefficients = np.asarray(estimator.coef_, dtype=np.float64) + intercept = np.asarray(estimator.intercept_, dtype=np.float64) + if classes != [0, 1] or coefficients.shape != (1, 1) or intercept.shape != (1,): + raise MultiDateEvaluationError("final sigmoid calibrator is not binary") + return { + "kind": "sigmoid", + "status": calibrator.status, + "classes": classes, + "coefficient": float(coefficients[0, 0]), + "intercept": float(intercept[0]), + } + + +def _serialized_model_state( + *, + role: Literal["selected", "historical_prior"], + requested: ModelCandidate, + effective: ModelCandidate, + estimator: Any, + calibrator: SigmoidCalibrator, + fit_status: str, + matrices: _FitMatrices, +) -> dict[str, object]: + imputer = estimator.named_steps["imputer"] + return { + "role": role, + "requested_candidate": _candidate_payload(requested), + "effective_candidate": _candidate_payload(effective), + "fit_status": fit_status, + "fit_cutoff_ts_ns": matrices.fit_cutoff_ts_ns, + "base_fit_rows": int(matrices.y_base.size), + "calibration_rows": int(matrices.y_calibration.size), + "imputer_statistics": _float_list(imputer.statistics_), + "classifier": _classifier_state(estimator, effective), + "calibrator": _calibrator_state(calibrator), + } + + +def _stable_sigmoid(value: NDArray[np.float64]) -> NDArray[np.float64]: + result = np.empty_like(value, dtype=np.float64) + nonnegative = value >= 0.0 + result[nonnegative] = 1.0 / (1.0 + np.exp(-value[nonnegative])) + exponential = np.exp(value[~nonnegative]) + result[~nonnegative] = exponential / (1.0 + exponential) + return result + + +def _predict_serialized_model( + payload: Mapping[str, Any], + features: NDArray[np.float64], +) -> tuple[NDArray[np.float64], NDArray[np.float64]]: + statistics = np.asarray(payload["imputer_statistics"], dtype=np.float64) + matrix = np.asarray(features, dtype=np.float64) + if matrix.ndim != 2 or matrix.shape[1] != statistics.size: + raise MultiDateEvaluationError("test feature matrix disagrees with fitted state") + imputed = np.where(np.isnan(matrix), statistics.reshape(1, -1), matrix) + if not np.isfinite(imputed).all(): + raise MultiDateEvaluationError( + "test feature matrix contains non-finite values after imputation" + ) + classifier = cast(Mapping[str, Any], payload["classifier"]) + kind = str(classifier["kind"]) + if kind == "prior": + classes = [int(value) for value in classifier["classes"]] + probabilities = [float(value) for value in classifier["class_probabilities"]] + positive = probabilities[classes.index(1)] if 1 in classes else 0.0 + raw = np.full(matrix.shape[0], positive, dtype=np.float64) + elif kind == "logistic": + mean = np.asarray(classifier["scaler_mean"], dtype=np.float64) + scale = np.asarray(classifier["scaler_scale"], dtype=np.float64) + coefficient = np.asarray(classifier["coefficients"], dtype=np.float64) + linear = ((imputed - mean) / scale) @ coefficient + float(classifier["intercept"]) + raw = _stable_sigmoid(np.asarray(linear, dtype=np.float64)) + elif kind == "decision_tree": + left = np.asarray(classifier["children_left"], dtype=np.int64) + right = np.asarray(classifier["children_right"], dtype=np.int64) + split_feature = np.asarray(classifier["feature"], dtype=np.int64) + threshold = np.asarray(classifier["threshold"], dtype=np.float64) + leaf_probability = np.asarray(classifier["positive_probability"], dtype=np.float64) + tree_features = np.asarray(imputed, dtype=np.float32) + raw = np.empty(matrix.shape[0], dtype=np.float64) + for row_index in range(matrix.shape[0]): + node = 0 + for _ in range(left.size + 1): + if left[node] == -1 and right[node] == -1: + raw[row_index] = leaf_probability[node] + break + node = ( + int(left[node]) + if tree_features[row_index, split_feature[node]] <= threshold[node] + else int(right[node]) + ) + else: + raise MultiDateEvaluationError("fitted decision-tree state contains a cycle") + else: + raise MultiDateEvaluationError("fitted state has an unsupported classifier kind") + + calibrator = cast(Mapping[str, Any], payload["calibrator"]) + if calibrator["kind"] == "identity": + calibrated = np.clip(raw, 1e-12, 1.0 - 1e-12) + else: + clipped = np.clip(raw, 1e-6, 1.0 - 1e-6) + logit = np.log(clipped / (1.0 - clipped)) + calibrated = _stable_sigmoid( + logit * float(calibrator["coefficient"]) + float(calibrator["intercept"]) + ) + raw = np.asarray(raw, dtype=np.float64) + calibrated = np.asarray(calibrated, dtype=np.float64) + if ( + not np.isfinite(raw).all() + or not np.isfinite(calibrated).all() + or np.any((raw < 0.0) | (raw > 1.0)) + or np.any((calibrated < 0.0) | (calibrated > 1.0)) + ): + raise MultiDateEvaluationError("fitted state produced invalid probabilities") + return raw, calibrated + + +def _fit_candidate( + candidate: ModelCandidate, + matrices: _FitMatrices, + *, + seed: int, + state_role: Literal["selected", "historical_prior"] | None = None, +) -> _FitOutcome: + effective = candidate + fit_status = "ok" + if np.unique(matrices.y_base).size < 2 and candidate.family != "baseline": + effective = ModelCandidate(f"{candidate.name}__prior_fallback", "baseline") + fit_status = "single_class_prior_fallback" + estimator = make_classifier(effective, seed=seed) + estimator.fit(matrices.x_base, matrices.y_base) + calibrator = SigmoidCalibrator() + if matrices.y_calibration.size: + raw_calibration = _positive_probability(estimator, matrices.x_calibration) + calibrator.fit(matrices.y_calibration, raw_calibration) + if matrices.x_evaluate.shape[0]: + raw = _positive_probability(estimator, matrices.x_evaluate) + calibrated = calibrator.transform(raw) + else: + raw = np.empty(0, dtype=np.float64) + calibrated = np.empty(0, dtype=np.float64) + status = f"{fit_status};{calibrator.status}" + fitted_state = ( + _serialized_model_state( + role=state_role, + requested=candidate, + effective=effective, + estimator=estimator, + calibrator=calibrator, + fit_status=status, + matrices=matrices, + ) + if state_role is not None + else None + ) + return _FitOutcome( + raw_probability=raw, + probability=calibrated, + fit_status=status, + fit_cutoff_ts_ns=matrices.fit_cutoff_ts_ns, + effective_candidate=effective, + fitted_state=fitted_state, + ) + + +def _candidate_payload(candidate: ModelCandidate) -> dict[str, object]: + return { + "name": candidate.name, + "family": candidate.family, + "c": candidate.c, + "max_depth": candidate.max_depth, + "min_samples_leaf": candidate.min_samples_leaf, + } + + +def _candidate_from_payload(payload: Mapping[str, Any]) -> ModelCandidate: + try: + return ModelCandidate( + name=str(payload["name"]), + family=cast(Any, str(payload["family"])), + c=float(payload["c"]) if payload.get("c") is not None else None, + max_depth=(int(payload["max_depth"]) if payload.get("max_depth") is not None else None), + min_samples_leaf=int(payload["min_samples_leaf"]), + ) + except (KeyError, TypeError, ValueError) as error: + raise MultiDateEvaluationError( + "selection lock has an invalid model specification" + ) from error + + +def _validate_feature_contract( + frame: pl.DataFrame, + *, + features: tuple[str, ...], + target: str, +) -> None: + if not features or len(set(features)) != len(features): + raise MultiDateEvaluationError("feature_columns must be unique and nonempty") + missing = sorted(set((*features, target)).difference(frame.columns)) + if missing: + raise MultiDateEvaluationError(f"model columns are missing: {missing}") + forbidden = [ + name + for name in features + if name.startswith("future_") or name.startswith("label_") or name == "right_censored" + ] + if forbidden: + raise MultiDateEvaluationError(f"label/timing columns cannot be features: {forbidden}") + eligible_target = frame.filter(_eligible()).get_column(target) + if eligible_target.null_count(): + raise MultiDateEvaluationError("eligible rows must have a non-null classification target") + target_values = set(eligible_target.unique().to_list()) + if not target_values.issubset({0, 1}): + raise MultiDateEvaluationError("classification target must contain only 0 and 1") + + +def select_multidate_model( + development_frames: Sequence[pl.DataFrame], + model_config: ModelConfig, + *, + feature_columns: Sequence[str], + declared_test_dates: Sequence[str], + seed: int, + calibration_bins: int, + target: str = "future_trade_up", + calibration_fraction: float = 0.2, + bootstrap_draws: int = DATE_BOOTSTRAP_DRAWS, + block_width_events: int = DATE_BOOTSTRAP_BLOCK_EVENTS, +) -> LockedSelection: + """Select on train/validation data without accepting or touching test rows. + + The caller must persist ``result.lock.payload_json`` and ``result.lock.sha256`` + before loading primary or replication test frames. + """ + + if model_config.selection_metric != "log_loss": + raise MultiDateEvaluationError("the multi-date protocol freezes log_loss selection") + if calibration_bins < 1: + raise MultiDateEvaluationError("calibration_bins must be positive") + if bootstrap_draws < 1 or block_width_events < 1: + raise MultiDateEvaluationError("bootstrap draws and block width must be positive") + development = _combine_date_frames( + development_frames, + allowed_roles=_DEVELOPMENT_ROLES, + label="development_frames", + ) + roles = { + str(row["study_date"]): str(row["study_role"]) + for row in development.select("study_date", "study_role").unique().to_dicts() + } + train_dates = tuple(sorted(value for value, role in roles.items() if role == "train")) + validation_dates = tuple(sorted(value for value, role in roles.items() if role == "validation")) + if not train_dates or len(validation_dates) != 1: + raise MultiDateEvaluationError( + "development protocol requires at least one train date and one validation date" + ) + validation_date = validation_dates[0] + test_dates = _parse_dates(declared_test_dates, label="declared_test_dates") + if len(test_dates) < 2: + raise MultiDateEvaluationError("declare one primary and at least one replication date") + if max(train_dates) >= validation_date or validation_date >= min(test_dates): + raise MultiDateEvaluationError("study roles must be strictly chronological by date") + + features = tuple(str(value) for value in feature_columns) + _validate_feature_contract(development, features=features, target=target) + eligible = development.filter(_eligible() & pl.col(target).is_not_null()) + train = eligible.filter(pl.col("study_role") == "train") + validation = eligible.filter(pl.col("study_role") == "validation") + if train.is_empty() or validation.is_empty(): + raise MultiDateEvaluationError("train and validation must contain eligible labeled rows") + validation_start = cast(int, validation.get_column("decision_ts_ns").min()) + train_label_end = cast(int, train.get_column("label_information_end_ts_ns").max()) + if train_label_end >= validation_start: + raise MultiDateEvaluationError("training label information reaches validation") + + matrices = _fit_matrices( + train, + validation, + features=features, + target=target, + calibration_fraction=calibration_fraction, + ) + y_validation = validation.get_column(target).to_numpy().astype(np.int64, copy=False) + candidates = build_model_candidates(model_config) + comparison_rows: list[dict[str, object]] = [] + for order, candidate in enumerate(candidates): + outcome = _fit_candidate(candidate, matrices, seed=seed) + metrics = classification_metrics( + y_validation, + outcome.probability, + calibration_bins=calibration_bins, + ) + comparison_rows.append( + { + "candidate_order": order, + "study_date": validation_date, + "study_role": "validation", + "requested_model": candidate.name, + "requested_family": candidate.family, + "model": outcome.effective_candidate.name, + "family": outcome.effective_candidate.family, + "fit_status": outcome.fit_status, + "fit_cutoff_ts_ns": outcome.fit_cutoff_ts_ns, + "n_obs": validation.height, + **metrics, + } + ) + comparison = pl.DataFrame(comparison_rows, infer_schema_length=None) + selectable = comparison.with_columns( + pl.when( + (pl.col("requested_family") != "baseline") + & pl.col("fit_status").str.contains("single_class_prior_fallback") + ) + .then(float("inf")) + .otherwise(pl.col("log_loss")) + .alias("_selection_score") + ).sort("_selection_score", "candidate_order") + selected_name = str(selectable.get_column("requested_model")[0]) + selected = next(candidate for candidate in candidates if candidate.name == selected_name) + comparison = comparison.with_columns( + (pl.col("requested_model") == selected_name).alias("selected_on_validation"), + pl.when(pl.col("requested_model") == selected_name) + .then(pl.lit("validation_log_loss")) + .otherwise(None) + .alias("selected_on"), + pl.lit(False).alias("test_rows_accessed"), + ).sort("candidate_order") + + development_sha = _frame_sha256(development) + comparison_sha = _frame_sha256(comparison) + final_matrices = _fit_matrices( + eligible, + eligible.head(min(1_024, eligible.height)), + features=features, + target=target, + calibration_fraction=calibration_fraction, + ) + final_selected = _fit_candidate( + selected, + final_matrices, + seed=seed, + state_role="selected", + ) + historical_prior = ModelCandidate("historical_prior", "baseline") + final_prior = _fit_candidate( + historical_prior, + final_matrices, + seed=seed, + state_role="historical_prior", + ) + if final_selected.fitted_state is None or final_prior.fitted_state is None: + raise MultiDateEvaluationError("final development fit did not produce serializable state") + primary_start = int( + datetime.fromisoformat(f"{test_dates[0]}T00:00:00+00:00").timestamp() * 1_000_000_000 + ) + if final_matrices.fit_cutoff_ts_ns >= primary_start: + raise MultiDateEvaluationError("final development fitting information reaches primary test") + fitted_state = FinalFittedState.create( + { + "schema_version": _FITTED_STATE_SCHEMA_VERSION, + "artifact_kind": _FITTED_STATE_ARTIFACT_KIND, + "serialization_format": _FITTED_STATE_SERIALIZATION_FORMAT, + "library_versions": { + "numpy": np.__version__, + "scikit_learn": sklearn.__version__, + }, + "feature_columns": list(features), + "target": target, + "development_frame_sha256": development_sha, + "fit_cutoff_ts_ns": final_matrices.fit_cutoff_ts_ns, + "eligible_development_rows": eligible.height, + "models": { + "selected": dict(final_selected.fitted_state), + "historical_prior": dict(final_prior.fitted_state), + }, + } + ) + serialized_selected = fitted_state.predict("selected", final_matrices.x_evaluate) + serialized_prior = fitted_state.predict("historical_prior", final_matrices.x_evaluate) + if not ( + np.allclose(serialized_selected[0], final_selected.raw_probability, rtol=0.0, atol=1e-12) + and np.allclose(serialized_selected[1], final_selected.probability, rtol=0.0, atol=1e-12) + and np.allclose(serialized_prior[0], final_prior.raw_probability, rtol=0.0, atol=1e-12) + and np.allclose(serialized_prior[1], final_prior.probability, rtol=0.0, atol=1e-12) + ): + raise MultiDateEvaluationError("serialized final fitted state changes model predictions") + fitted_policy = ( + "selection fits each declared candidate on train-role rows only; final evaluation " + "fits only the locked selected specification and an independent historical prior once " + "on eligible train+validation rows before the lock; test evaluation restores numeric " + "state and neither model updates between test dates" + ) + lock = AnalysisLock.create( + { + "schema_version": _LOCK_SCHEMA_VERSION, + "selected_candidate": _candidate_payload(selected), + "declared_candidates": [_candidate_payload(candidate) for candidate in candidates], + "validation_selection_scores": comparison.select( + "candidate_order", + "requested_model", + "requested_family", + "model", + "family", + "fit_status", + "n_obs", + "log_loss", + "selected_on_validation", + ).to_dicts(), + "selection_metric": "log_loss", + "target": target, + "feature_columns": list(features), + "seed": seed, + "calibration_bins": calibration_bins, + "calibration_fraction": calibration_fraction, + "train_dates": list(train_dates), + "validation_date": validation_date, + "declared_test_dates": list(test_dates), + "development_frame_sha256": development_sha, + "validation_comparison_sha256": comparison_sha, + "validation_rows": validation.height, + "validation_start_ts_ns": validation_start, + "validation_end_ts_ns": int(cast(int, validation.get_column("decision_ts_ns").max())), + "selection_fit_cutoff_policy": ( + "all fitted labels end before the first validation decision" + ), + "final_fit_policy": fitted_policy, + "final_fitted_state_sha256": fitted_state.sha256, + "final_fitted_state": fitted_state.payload(), + "test_rows_accessed_during_selection": False, + "test_update_policy": "fit_once_before_primary_test; no updates through replication", + "bootstrap": { + "metric": "selected_minus_historical_prior_log_loss", + "draws": bootstrap_draws, + "block_width_events": block_width_events, + "date_weighting": "equal", + }, + } + ) + return LockedSelection( + lock=lock, + validation_comparison=comparison, + selected_candidate=selected, + feature_columns=features, + target=target, + train_dates=train_dates, + validation_date=validation_date, + declared_test_dates=test_dates, + development_frame_sha256=development_sha, + fitted_data_cutoff_policy=fitted_policy, + fitted_state=fitted_state, + ) + + +def _indices(indexed: pl.DataFrame, condition: pl.Expr) -> NDArray[np.int64]: + return ( + indexed.filter(condition) + .get_column("_research_row_id") + .to_numpy() + .astype(np.int64, copy=False) + ) + + +def build_multidate_walk_forward_plan(frame: pl.DataFrame) -> WalkForwardPlan: + """Build one date-level development fold and a frozen multi-date test plan.""" + + _validate_date_local_temporal_contract(frame) + if not frame.get_column("decision_ts_ns").is_sorted(): + raise MultiDateEvaluationError("plan frame must be sorted by decision time") + roles = { + str(row["study_date"]): str(row["study_role"]) + for row in frame.select("study_date", "study_role").unique().to_dicts() + } + train_dates = sorted(value for value, role in roles.items() if role == "train") + validation_dates = sorted(value for value, role in roles.items() if role == "validation") + test_dates = sorted(value for value, role in roles.items() if role in _TEST_ROLES) + if not train_dates or len(validation_dates) != 1 or len(test_dates) < 2: + raise MultiDateEvaluationError( + "plan requires train date(s), one validation date, and at least two test dates" + ) + if max(train_dates) >= validation_dates[0] or validation_dates[0] >= min(test_dates): + raise MultiDateEvaluationError("plan roles are not strictly chronological") + + indexed = frame.with_row_index("_research_row_id") + eligible = _eligible() + train_candidates = indexed.filter(eligible & (pl.col("study_role") == "train")) + validation_candidates = indexed.filter(eligible & (pl.col("study_role") == "validation")) + test_candidates = indexed.filter(eligible & pl.col("study_role").is_in(_TEST_ROLES)) + if any(part.is_empty() for part in (train_candidates, validation_candidates, test_candidates)): + raise MultiDateEvaluationError("one or more date-level plan roles have no eligible rows") + validation_start = int(cast(int, validation_candidates.get_column("decision_ts_ns").min())) + test_start = int(cast(int, test_candidates.get_column("decision_ts_ns").min())) + train = train_candidates.filter(pl.col("label_information_end_ts_ns") < validation_start) + validation = validation_candidates.filter(pl.col("label_information_end_ts_ns") < test_start) + final_train = indexed.filter( + eligible + & pl.col("study_role").is_in(_DEVELOPMENT_ROLES) + & (pl.col("label_information_end_ts_ns") < test_start) + ) + test = test_candidates + if any(part.is_empty() for part in (train, validation, final_train, test)): + raise MultiDateEvaluationError("one or more date-level plan partitions are empty") + train_indices = train.get_column("_research_row_id").to_numpy().astype(np.int64) + validation_indices = validation.get_column("_research_row_id").to_numpy().astype(np.int64) + final_train_indices = final_train.get_column("_research_row_id").to_numpy().astype(np.int64) + test_indices = test.get_column("_research_row_id").to_numpy().astype(np.int64) + fold = PurgedFold( + fold_id=0, + train_indices=train_indices, + validation_indices=validation_indices, + train_start_ts_ns=int(cast(int, train.get_column("decision_ts_ns").min())), + train_end_ts_ns=int(cast(int, train.get_column("decision_ts_ns").max())), + validation_start_ts_ns=validation_start, + validation_end_ts_ns=int(cast(int, validation.get_column("decision_ts_ns").max())), + purged_rows=train_candidates.height - train.height, + embargoed_time_buckets=0, + ) + return WalkForwardPlan( + folds=(fold,), + final_train_indices=final_train_indices, + test_indices=test_indices, + test_start_ts_ns=test_start, + test_end_ts_ns=int(cast(int, test.get_column("decision_ts_ns").max())), + decision_time_count=frame.get_column("decision_ts_ns").n_unique(), + ) + + +def _selection_spec(selection: LockedSelection | AnalysisLock) -> _SelectionSpec: + lock = selection.lock if isinstance(selection, LockedSelection) else selection + payload = lock.payload() + try: + bootstrap = cast(Mapping[str, Any], payload["bootstrap"]) + fitted_payload = _mapping(payload["final_fitted_state"], "locked final fitted state") + fitted_state = FinalFittedState.create(cast(Mapping[str, object], fitted_payload)) + claimed_state_sha = str(payload["final_fitted_state_sha256"]) + if fitted_state.sha256 != claimed_state_sha: + raise MultiDateEvaluationError( + "selection lock final fitted-state hash does not match its bytes" + ) + spec = _SelectionSpec( + lock=lock, + candidate=_validate_candidate_payload_strict( + payload["selected_candidate"], "selection lock selected candidate" + ), + feature_columns=tuple(str(value) for value in payload["feature_columns"]), + target=str(payload["target"]), + seed=int(payload["seed"]), + calibration_bins=int(payload["calibration_bins"]), + calibration_fraction=float(payload["calibration_fraction"]), + train_dates=tuple(str(value) for value in payload["train_dates"]), + validation_date=str(payload["validation_date"]), + test_dates=tuple(str(value) for value in payload["declared_test_dates"]), + development_frame_sha256=str(payload["development_frame_sha256"]), + block_width_events=int(bootstrap["block_width_events"]), + bootstrap_draws=int(bootstrap["draws"]), + fitted_state=fitted_state, + ) + except MultiDateEvaluationError: + raise + except (KeyError, TypeError, ValueError) as error: + raise MultiDateEvaluationError("selection lock is missing typed protocol fields") from error + if spec.block_width_events < 1 or spec.bootstrap_draws < 1: + raise MultiDateEvaluationError("selection lock bootstrap contract must be positive") + fitted_payload = spec.fitted_state.payload() + if ( + tuple(fitted_payload["feature_columns"]) != spec.feature_columns + or fitted_payload["target"] != spec.target + or fitted_payload["development_frame_sha256"] != spec.development_frame_sha256 + ): + raise MultiDateEvaluationError("selection lock and fitted-state contracts disagree") + selected_model = cast( + Mapping[str, Any], cast(Mapping[str, Any], fitted_payload["models"])["selected"] + ) + requested = _validate_candidate_payload_strict( + selected_model["requested_candidate"], "fitted selected requested candidate" + ) + if requested != spec.candidate: + raise MultiDateEvaluationError( + "selection lock candidate differs from fitted selected state" + ) + if isinstance(selection, LockedSelection) and selection.fitted_state != fitted_state: + raise MultiDateEvaluationError("in-memory fitted state differs from selection lock") + return spec + + +def _rows_by_indices(frame: pl.DataFrame, indices: NDArray[np.int64]) -> pl.DataFrame: + return frame.with_row_index("_research_row_id").filter( + pl.col("_research_row_id").is_in(indices) + ) + + +def _test_phase_expression(primary_date: str) -> pl.Expr: + return ( + pl.when(pl.col("study_date") == primary_date) + .then(pl.lit("primary")) + .otherwise(pl.lit("replication")) + .alias("test_phase") + ) + + +def _block_predictions(predictions: pl.DataFrame, *, block_width_events: int) -> pl.DataFrame: + if block_width_events < 1: + raise MultiDateEvaluationError("block_width_events must be positive") + _require_columns( + predictions, + ( + "row_id", + "study_date", + "study_role", + "decision_ts_ns", + "decision_sequence", + "y_true", + "selected_probability", + "prior_probability", + ), + "paired test predictions", + ) + if predictions.get_column("row_id").n_unique() != predictions.height: + raise MultiDateEvaluationError("paired predictions require unique row IDs") + if not set(predictions.get_column("y_true").unique().to_list()).issubset({0, 1}): + raise MultiDateEvaluationError("paired predictions require binary targets") + for probability in ("selected_probability", "prior_probability"): + if ( + predictions.get_column(probability).null_count() + or predictions.filter( + (~pl.col(probability).is_finite()) + | (pl.col(probability) < 0.0) + | (pl.col(probability) > 1.0) + ).height + ): + raise MultiDateEvaluationError(f"{probability} must contain finite probabilities") + ordering = ( + predictions.select("row_id", "study_date", "decision_ts_ns", "decision_sequence") + .sort("study_date", "decision_ts_ns", "decision_sequence", "row_id") + .with_columns(pl.int_range(0, pl.len()).over("study_date").alias("_date_event_index")) + .with_columns( + (pl.col("_date_event_index") // block_width_events) + .cast(pl.Int64) + .alias("date_block_index") + ) + .with_columns( + pl.concat_str( + "study_date", + pl.col("date_block_index").cast(pl.String), + separator=":", + ).alias("date_block_id"), + pl.lit(block_width_events, dtype=pl.Int64).alias("date_block_width_events"), + ) + .drop("_date_event_index") + ) + return predictions.join( + ordering.select("row_id", "date_block_index", "date_block_id", "date_block_width_events"), + on="row_id", + how="inner", + validate="1:1", + ) + + +def _loss_sufficient_statistics(blocked: pl.DataFrame) -> pl.DataFrame: + clipped = blocked.with_columns( + pl.col("selected_probability").clip(1e-12, 1.0 - 1e-12).alias("_selected_p"), + pl.col("prior_probability").clip(1e-12, 1.0 - 1e-12).alias("_prior_p"), + ).with_columns( + pl.when(pl.col("y_true") == 1) + .then(-pl.col("_selected_p").log()) + .otherwise(-(1.0 - pl.col("_selected_p")).log()) + .alias("_selected_loss"), + pl.when(pl.col("y_true") == 1) + .then(-pl.col("_prior_p").log()) + .otherwise(-(1.0 - pl.col("_prior_p")).log()) + .alias("_prior_loss"), + ) + return ( + clipped.with_columns((pl.col("_selected_loss") - pl.col("_prior_loss")).alias("_loss_diff")) + .group_by("study_date", "study_role", "test_phase", "date_block_index") + .agg( + pl.len().alias("event_count"), + pl.col("_selected_loss").sum().alias("selected_loss_sum"), + pl.col("_prior_loss").sum().alias("prior_loss_sum"), + pl.col("_loss_diff").sum().alias("loss_diff_sum"), + ) + .sort("study_date", "date_block_index") + ) + + +def _date_draws_from_blocks( + loss_sums: NDArray[np.float64], + event_counts: NDArray[np.int64], + *, + n_bootstrap: int, + random: np.random.Generator, + draw_chunk_size: int, +) -> NDArray[np.float64]: + blocks = loss_sums.size + if blocks < 2: + return np.empty(0, dtype=np.float64) + bounded_chunk = min( + draw_chunk_size, + max(1, _MAX_BOOTSTRAP_INDEX_ELEMENTS // blocks), + ) + draws = np.empty(n_bootstrap, dtype=np.float64) + for start in range(0, n_bootstrap, bounded_chunk): + stop = min(n_bootstrap, start + bounded_chunk) + sampled = random.integers(0, blocks, size=(stop - start, blocks), dtype=np.int64) + sampled_loss = np.take(loss_sums, sampled).sum(axis=1) + sampled_count = np.take(event_counts, sampled).sum(axis=1) + draws[start:stop] = sampled_loss / sampled_count + return draws + + +def paired_date_log_loss( + predictions: pl.DataFrame, + *, + seed: int, + n_bootstrap: int = DATE_BOOTSTRAP_DRAWS, + block_width_events: int = DATE_BOOTSTRAP_BLOCK_EVENTS, + draw_chunk_size: int = _BOOTSTRAP_DRAW_CHUNK, +) -> PairedDateLogLossResult: + """Compute per-date and equal-date-weighted selected-minus-prior log loss.""" + + if n_bootstrap < 1 or draw_chunk_size < 1: + raise MultiDateEvaluationError("bootstrap draws and chunk size must be positive") + blocked = _block_predictions(predictions, block_width_events=block_width_events) + if "test_phase" not in blocked.columns: + dates = sorted(str(value) for value in blocked.get_column("study_date").unique()) + blocked = blocked.with_columns(_test_phase_expression(dates[0])) + blocks = _loss_sufficient_statistics(blocked) + dates = sorted(str(value) for value in blocks.get_column("study_date").unique()) + random = np.random.default_rng(seed) + date_rows: list[dict[str, object]] = [] + date_draws: list[NDArray[np.float64]] = [] + all_dates_sufficient = True + for study_date in dates: + current = blocks.filter(pl.col("study_date") == study_date) + loss_sums = current.get_column("loss_diff_sum").to_numpy().astype(np.float64) + counts = current.get_column("event_count").to_numpy().astype(np.int64) + selected_sum = float(cast(float, current.get_column("selected_loss_sum").sum())) + prior_sum = float(cast(float, current.get_column("prior_loss_sum").sum())) + observations = int(counts.sum()) + point = float(loss_sums.sum() / observations) + draws = _date_draws_from_blocks( + loss_sums, + counts, + n_bootstrap=n_bootstrap, + random=random, + draw_chunk_size=draw_chunk_size, + ) + sufficient = draws.size == n_bootstrap + all_dates_sufficient &= sufficient + if sufficient: + date_draws.append(draws) + study_role = str(current.get_column("study_role")[0]) + test_phase = str(current.get_column("test_phase")[0]) + date_rows.append( + { + "study_date": study_date, + "study_role": study_role, + "test_phase": test_phase, + "metric": "log_loss", + "delta_definition": "selected_model_minus_historical_prior", + "selected_log_loss": selected_sum / observations, + "prior_log_loss": prior_sum / observations, + "point_delta": point, + "ci_low": float(np.quantile(draws, 0.025)) if sufficient else None, + "ci_high": float(np.quantile(draws, 0.975)) if sufficient else None, + "n_obs": observations, + "n_blocks": current.height, + "bootstrap_samples": n_bootstrap, + "bootstrap_status": "ok" if sufficient else "insufficient_blocks", + "block_width_events": block_width_events, + "date_weight": 1.0 / len(dates), + "point_favorable": point < 0.0, + "significance_claim_authorized": False, + } + ) + per_date = pl.DataFrame(date_rows, infer_schema_length=None).sort("study_date") + point_estimate = float(cast(float, per_date.get_column("point_delta").mean())) + if len(dates) >= 2 and all_dates_sufficient: + aggregate_draws = np.mean(np.vstack(date_draws), axis=0) + aggregate = BootstrapResult( + point_estimate=point_estimate, + lower=float(np.quantile(aggregate_draws, 0.025)), + upper=float(np.quantile(aggregate_draws, 0.975)), + n_bootstrap=n_bootstrap, + n_blocks=int(per_date.get_column("n_blocks").sum()), + seed=seed, + status="ok", + draws=tuple(float(value) for value in aggregate_draws), + ) + else: + aggregate = BootstrapResult( + point_estimate=point_estimate, + lower=None, + upper=None, + n_bootstrap=n_bootstrap, + n_blocks=int(per_date.get_column("n_blocks").sum()), + seed=seed, + status="insufficient_blocks", + draws=(), + ) + + primary = per_date.filter(pl.col("test_phase") == "primary") + replication = per_date.filter(pl.col("test_phase") == "replication") + if primary.height != 1 or replication.is_empty(): + replication_status: ReplicationStatus = "insufficient_replication_dates" + elif not bool(primary.get_column("point_favorable")[0]): + replication_status = "no_primary_improvement" + elif replication.get_column("point_favorable").all(): + replication_status = "replicated" + else: + replication_status = "failed_replication" + return PairedDateLogLossResult( + predictions=blocked, + per_date=per_date, + aggregate=aggregate, + replication_status=replication_status, + ) + + +def reference_only_feature_stability( + frame: pl.DataFrame, + plan: WalkForwardPlan, + *, + feature_columns: Sequence[str], + bins: int = 10, + lock_sha256: str | None = None, +) -> pl.DataFrame: + """Compare each test date with bins fitted only on final train+validation.""" + + features = tuple(str(value) for value in feature_columns) + reference = _rows_by_indices(frame, plan.final_train_indices).drop("_research_row_id") + tests = _rows_by_indices(frame, plan.test_indices).drop("_research_row_id") + reference_dates = ",".join( + sorted(str(value) for value in reference.get_column("study_date").unique()) + ) + test_dates = sorted(str(value) for value in tests.get_column("study_date").unique()) + rows: list[pl.DataFrame] = [] + for index, study_date in enumerate(test_dates): + comparison = tests.filter(pl.col("study_date") == study_date) + rows.append( + feature_stability_summary( + reference, + comparison, + feature_columns=features, + group_columns=("symbol",), + bins=bins, + ).with_columns( + pl.lit(reference_dates).alias("reference_dates"), + pl.lit("train_plus_validation").alias("reference_role"), + pl.lit(study_date).alias("comparison_study_date"), + pl.lit("primary" if index == 0 else "replication").alias("test_phase"), + pl.lit(True).alias("reference_only"), + pl.lit(lock_sha256).alias("selection_lock_sha256"), + ) + ) + return pl.concat(rows, how="vertical").sort("comparison_study_date", "symbol", "feature") + + +def evaluate_locked_multidate_tests( + development_frames: Sequence[pl.DataFrame], + test_frames: Sequence[pl.DataFrame], + selection: LockedSelection | AnalysisLock, +) -> LockedMultiDateTestResult: + """Open declared tests under a persisted lock, with no between-date update.""" + + spec = _selection_spec(selection) + development = _combine_date_frames( + development_frames, + allowed_roles=_DEVELOPMENT_ROLES, + label="development_frames", + ) + if _frame_sha256(development) != spec.development_frame_sha256: + raise MultiDateEvaluationError("development data changed after model selection") + roles = { + str(row["study_date"]): str(row["study_role"]) + for row in development.select("study_date", "study_role").unique().to_dicts() + } + observed_train = tuple(sorted(value for value, role in roles.items() if role == "train")) + observed_validation = tuple( + sorted(value for value, role in roles.items() if role == "validation") + ) + if observed_train != spec.train_dates or observed_validation != (spec.validation_date,): + raise MultiDateEvaluationError("development schedule changed after model selection") + + tests = _combine_date_frames( + test_frames, + allowed_roles=_TEST_ROLES, + label="test_frames", + ) + observed_tests = tuple(sorted(str(value) for value in tests.get_column("study_date").unique())) + if observed_tests != spec.test_dates: + raise MultiDateEvaluationError("test dates do not match the persisted selection lock") + test_roles = { + str(row["study_date"]): str(row["study_role"]) + for row in tests.select("study_date", "study_role").unique().to_dicts() + } + if test_roles[spec.test_dates[0]] not in {"test", "primary_test"}: + raise MultiDateEvaluationError("the first declared test date must be primary_test") + if any( + test_roles[study_date] not in {"test", "replication_test"} + for study_date in spec.test_dates[1:] + ): + raise MultiDateEvaluationError("later declared test dates must be replication_test") + # The locked schedule guarantees every development date precedes every test + # date, so concatenation preserves global order without sorting the wide frame. + combined = pl.concat([development, tests], how="vertical") + _validate_feature_contract( + combined, + features=spec.feature_columns, + target=spec.target, + ) + plan = build_multidate_walk_forward_plan(combined) + final_test = _rows_by_indices(combined, plan.test_indices) + test_matrix = final_test.select(spec.feature_columns).to_numpy().astype(np.float64, copy=False) + selected_raw, selected_probability = spec.fitted_state.predict("selected", test_matrix) + prior_raw, prior_probability = spec.fitted_state.predict("historical_prior", test_matrix) + state_payload = spec.fitted_state.payload() + state_models = cast(Mapping[str, Any], state_payload["models"]) + selected_state = cast(Mapping[str, Any], state_models["selected"]) + prior_state = cast(Mapping[str, Any], state_models["historical_prior"]) + selected_effective = _validate_candidate_payload_strict( + selected_state["effective_candidate"], "locked selected effective candidate" + ) + selected_cutoff = int(selected_state["fit_cutoff_ts_ns"]) + prior_cutoff = int(prior_state["fit_cutoff_ts_ns"]) + first_test_decision = int(cast(int, final_test.get_column("decision_ts_ns").min())) + if selected_cutoff >= first_test_decision or prior_cutoff >= first_test_decision: + raise MultiDateEvaluationError("final fitting information reaches the primary test") + + identity_columns = [ + "_research_row_id", + "study_date", + "study_role", + "symbol", + "decision_ts_ns", + "decision_sequence", + "continuity_id", + ] + if "sample_id" in final_test.columns: + identity_columns.append("sample_id") + predictions = ( + final_test.select(*identity_columns, spec.target) + .rename({"_research_row_id": "row_id", spec.target: "y_true"}) + .with_columns( + pl.Series("selected_raw_probability", selected_raw), + pl.Series("selected_probability", selected_probability), + pl.Series("prior_raw_probability", prior_raw), + pl.Series("prior_probability", prior_probability), + _test_phase_expression(spec.test_dates[0]), + pl.lit(spec.candidate.name).alias("selected_model"), + pl.lit(selected_effective.name).alias("selected_effective_model"), + pl.lit(str(selected_state["fit_status"])).alias("selected_fit_status"), + pl.lit(selected_cutoff).alias("selected_fit_cutoff_ts_ns"), + pl.lit(str(prior_state["fit_status"])).alias("prior_fit_status"), + pl.lit(prior_cutoff).alias("prior_fit_cutoff_ts_ns"), + pl.lit(spec.lock.sha256).alias("selection_lock_sha256"), + pl.lit(True).alias("is_oos"), + pl.lit(False).alias("model_updated_between_test_dates"), + ) + ) + paired = paired_date_log_loss( + predictions, + seed=spec.seed + 20_000, + n_bootstrap=spec.bootstrap_draws, + block_width_events=spec.block_width_events, + ) + stability = reference_only_feature_stability( + combined, + plan, + feature_columns=spec.feature_columns, + lock_sha256=spec.lock.sha256, + ) + return LockedMultiDateTestResult( + plan=plan, + predictions=paired.predictions, + paired_log_loss=paired, + feature_stability=stability, + selected_model=spec.candidate.name, + lock_sha256=spec.lock.sha256, + ) + + +__all__ = [ + "DATE_BOOTSTRAP_BLOCK_EVENTS", + "DATE_BOOTSTRAP_DRAWS", + "AnalysisLock", + "FinalFittedState", + "LockedMultiDateTestResult", + "LockedSelection", + "MultiDateEvaluationError", + "PairedDateLogLossResult", + "ReplicationStatus", + "build_multidate_walk_forward_plan", + "evaluate_locked_multidate_tests", + "paired_date_log_loss", + "reference_only_feature_stability", + "select_multidate_model", +] diff --git a/Microstructure/src/microstructure/research/splits.py b/Microstructure/src/microstructure/research/splits.py new file mode 100644 index 0000000000000000000000000000000000000000..9954bacac695f6217f022af349e2b3f6004816b8 --- /dev/null +++ b/Microstructure/src/microstructure/research/splits.py @@ -0,0 +1,205 @@ +"""Purged expanding walk-forward splits for overlapping event labels.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import cast + +import numpy as np +import polars as pl +from numpy.typing import NDArray + +from microstructure.config import EvaluationConfig + + +class SplitError(ValueError): + """Raised when a leakage-safe walk-forward plan cannot be constructed.""" + + +IndexArray = NDArray[np.int64] + + +@dataclass(frozen=True, slots=True) +class PurgedFold: + """One expanding training window and its strictly later validation window.""" + + fold_id: int + train_indices: IndexArray + validation_indices: IndexArray + train_start_ts_ns: int + train_end_ts_ns: int + validation_start_ts_ns: int + validation_end_ts_ns: int + purged_rows: int + embargoed_time_buckets: int + + +@dataclass(frozen=True, slots=True) +class WalkForwardPlan: + """Development folds plus a frozen, never-used-for-selection final test.""" + + folds: tuple[PurgedFold, ...] + final_train_indices: IndexArray + test_indices: IndexArray + test_start_ts_ns: int + test_end_ts_ns: int + decision_time_count: int + + +_REQUIRED = frozenset( + { + "decision_ts_ns", + "label_information_end_ts_ns", + "right_censored", + } +) + + +def _require_contract(frame: pl.DataFrame) -> None: + missing = sorted(_REQUIRED.difference(frame.columns)) + if missing: + raise SplitError(f"research frame is missing split columns: {missing}") + if frame.is_empty(): + raise SplitError("research frame must not be empty") + + +def _indices(frame: pl.DataFrame, condition: pl.Expr) -> IndexArray: + return frame.filter(condition).get_column("_research_row_id").to_numpy().astype(np.int64) + + +def _eligible(frame: pl.DataFrame) -> pl.Expr: + ready = pl.col("feature_ready") if "feature_ready" in frame.columns else pl.lit(True) + return (~pl.col("right_censored")) & ready + + +def _purged_training_indices( + indexed: pl.DataFrame, + *, + validation_start_ts_ns: int, + decision_cutoff_ts_ns: int, +) -> tuple[IndexArray, int]: + candidates = indexed.filter( + _eligible(indexed) & (pl.col("decision_ts_ns") < validation_start_ts_ns) + ) + safe = candidates.filter( + (pl.col("decision_ts_ns") < decision_cutoff_ts_ns) + & (pl.col("label_information_end_ts_ns") < validation_start_ts_ns) + ) + return ( + safe.get_column("_research_row_id").to_numpy().astype(np.int64), + candidates.height - safe.height, + ) + + +def expanding_walk_forward_splits( + frame: pl.DataFrame, + config: EvaluationConfig, +) -> WalkForwardPlan: + """Create global-time expanding folds and a frozen final-test period. + + Configuration counts refer to unique decision-time buckets, not physical + rows, so instruments sharing a timestamp always remain in the same split. + Candidate training decisions are separated by ``embargo_events`` buckets; + label intervals ending at or beyond the evaluation start are purged as an + independent second guard. Development labels ending at or beyond the final + test start are also excluded so model selection cannot observe test outcomes. + """ + + _require_contract(frame) + if config.min_train_events < 1: + raise SplitError("min_train_events must be positive") + if config.validation_events < 1 or config.test_events < 1: + raise SplitError("validation_events and test_events must be positive") + if config.step_events < 1 or config.embargo_events < 0: + raise SplitError("step_events must be positive and embargo_events nonnegative") + + indexed = frame.with_row_index("_research_row_id") + decision_times = sorted(indexed.get_column("decision_ts_ns").unique().to_list()) + required_times = config.min_train_events + config.validation_events + config.test_events + if len(decision_times) < required_times: + raise SplitError( + f"need at least {required_times} decision-time buckets, got {len(decision_times)}" + ) + + development_end = len(decision_times) - config.test_events + test_start_position = development_end + test_start = int(decision_times[test_start_position]) + folds: list[PurgedFold] = [] + validation_start_position = config.min_train_events + while validation_start_position + config.validation_events <= development_end: + validation_end_position = validation_start_position + config.validation_events + validation_start = int(decision_times[validation_start_position]) + validation_end = int(decision_times[validation_end_position - 1]) + decision_cut_position = max(0, validation_start_position - config.embargo_events) + decision_cutoff = int(decision_times[decision_cut_position]) + train_indices, purged_rows = _purged_training_indices( + indexed, + validation_start_ts_ns=validation_start, + decision_cutoff_ts_ns=decision_cutoff, + ) + validation_indices = _indices( + indexed, + _eligible(indexed) + & (pl.col("decision_ts_ns") >= validation_start) + & (pl.col("decision_ts_ns") <= validation_end) + & (pl.col("label_information_end_ts_ns") < test_start), + ) + if train_indices.size == 0: + raise SplitError(f"fold {len(folds)} has no training rows after purge and embargo") + if validation_indices.size == 0: + raise SplitError(f"fold {len(folds)} has no labeled validation rows") + + train_times = indexed.filter(pl.col("_research_row_id").is_in(train_indices)).get_column( + "decision_ts_ns" + ) + folds.append( + PurgedFold( + fold_id=len(folds), + train_indices=train_indices, + validation_indices=validation_indices, + train_start_ts_ns=cast(int, train_times.min()), + train_end_ts_ns=cast(int, train_times.max()), + validation_start_ts_ns=validation_start, + validation_end_ts_ns=validation_end, + purged_rows=purged_rows, + embargoed_time_buckets=min(config.embargo_events, validation_start_position), + ) + ) + validation_start_position += config.step_events + + if not folds: + raise SplitError("configuration produced no development folds") + + test_end = int(decision_times[-1]) + final_decision_cut_position = max(0, test_start_position - config.embargo_events) + final_decision_cutoff = int(decision_times[final_decision_cut_position]) + final_train_indices, _ = _purged_training_indices( + indexed, + validation_start_ts_ns=test_start, + decision_cutoff_ts_ns=final_decision_cutoff, + ) + test_indices = _indices( + indexed, + _eligible(indexed) + & (pl.col("decision_ts_ns") >= test_start) + & (pl.col("decision_ts_ns") <= test_end), + ) + if final_train_indices.size == 0 or test_indices.size == 0: + raise SplitError("final train or labeled test set is empty after temporal filtering") + + return WalkForwardPlan( + folds=tuple(folds), + final_train_indices=final_train_indices, + test_indices=test_indices, + test_start_ts_ns=test_start, + test_end_ts_ns=test_end, + decision_time_count=len(decision_times), + ) + + +__all__ = [ + "PurgedFold", + "SplitError", + "WalkForwardPlan", + "expanding_walk_forward_splits", +] diff --git a/Microstructure/src/microstructure/research/trade_only.py b/Microstructure/src/microstructure/research/trade_only.py new file mode 100644 index 0000000000000000000000000000000000000000..5b72ab936e80631cb9ffe2efd321d0a0d451160e --- /dev/null +++ b/Microstructure/src/microstructure/research/trade_only.py @@ -0,0 +1,379 @@ +"""Leakage-safe empirical features and labels from normalized trades alone. + +Trade availability time is the decision clock. Feature windows contain only the +current trade and earlier trades in the same ``(symbol, continuity_id)`` segment. +Future labels advance by trade ID inside that segment and preserve their explicit +information end so purged time-series evaluation can treat overlap correctly. +""" + +from __future__ import annotations + +import polars as pl + +from microstructure.config import FeatureConfig +from microstructure.research.features import ( + ResearchDataError, + TemporalAudit, + TemporalLeakageError, +) + +_GROUP = ["symbol", "continuity_id"] +_REQUIRED_TRADES = frozenset( + { + "symbol", + "continuity_id", + "trade_id", + "available_ts_ns", + "event_ts_ns", + "price", + "quantity", + "aggressor_side", + } +) + + +def _require_columns(frame: pl.DataFrame, required: frozenset[str], table: str) -> None: + missing = sorted(required.difference(frame.columns)) + if missing: + raise ResearchDataError(f"{table} is missing required columns: {missing}") + if frame.is_empty(): + raise ResearchDataError(f"{table} must not be empty") + + +def _validate_config(config: FeatureConfig) -> None: + windows = (*config.trade_windows, config.intensity_window, config.volatility_window) + if not config.trade_windows or any(window < 1 for window in windows): + raise ResearchDataError("trade-only feature windows must be nonempty and positive") + if config.label_horizon_events < 1: + raise ResearchDataError("trade-only label horizon must be positive") + + +def _validate_normalized_trades(trades: pl.DataFrame) -> pl.DataFrame: + _require_columns(trades, _REQUIRED_TRADES, "normalized trades") + invalid = trades.filter( + pl.col("symbol").is_null() + | pl.col("continuity_id").is_null() + | pl.col("trade_id").is_null() + | pl.col("available_ts_ns").is_null() + | pl.col("event_ts_ns").is_null() + | (pl.col("available_ts_ns") < pl.col("event_ts_ns")) + | (~pl.col("price").cast(pl.Float64).is_finite()) + | (pl.col("price") <= 0) + | (~pl.col("quantity").cast(pl.Float64).is_finite()) + | (pl.col("quantity") <= 0) + | (~pl.col("aggressor_side").cast(pl.String).str.to_lowercase().is_in(["buy", "sell"])) + ) + if not invalid.is_empty(): + raise ResearchDataError( + "normalized trades require segment identity, observable timing, positive finite values, " + "and buy/sell aggressor side" + ) + + duplicates = trades.group_by(*_GROUP, "trade_id").len().filter(pl.col("len") > 1) + if not duplicates.is_empty(): + raise ResearchDataError("trade IDs must be unique within each continuity segment") + + ordered = trades.sort([*_GROUP, "trade_id"]) + backwards = ordered.filter( + pl.col("available_ts_ns") < pl.col("available_ts_ns").shift(1).over(_GROUP) + ) + if not backwards.is_empty(): + raise ResearchDataError( + "available_ts_ns must be nondecreasing by trade_id within each continuity segment" + ) + return ordered + + +def build_trade_only_features(trades: pl.DataFrame, config: FeatureConfig) -> pl.DataFrame: + """Build causal rolling trade features on the availability-time clock.""" + + _validate_config(config) + ordered = _validate_normalized_trades(trades) + prepared = ( + ordered.with_columns( + pl.col("event_ts_ns").alias("market_event_ts_ns"), + pl.col("available_ts_ns").alias("decision_ts_ns"), + pl.col("available_ts_ns").alias("feature_cutoff_ts_ns"), + pl.col("trade_id").alias("decision_trade_id"), + pl.col("trade_id").alias("decision_sequence"), + pl.col("continuity_id").alias("feature_continuity_id"), + pl.when(pl.col("aggressor_side").str.to_lowercase() == "buy") + .then(1.0) + .otherwise(-1.0) + .alias("trade_sign"), + pl.lit(1, dtype=pl.Int64).alias("_trade_observation"), + ) + .with_columns( + (pl.col("quantity") * pl.col("trade_sign")).alias("signed_trade_quantity"), + pl.col("price").shift(1).over(_GROUP).alias("_previous_trade_price"), + pl.col("available_ts_ns").first().over(_GROUP).alias("_segment_start_ts_ns"), + pl.col("trade_id").cum_count().over(_GROUP).alias("history_trades"), + pl.concat_str( + ["symbol", "continuity_id", pl.col("trade_id").cast(pl.String)], + separator=":", + ).alias("sample_id"), + ) + .with_columns( + pl.when(pl.col("_previous_trade_price").is_not_null()) + .then((pl.col("price") / pl.col("_previous_trade_price")).log()) + .otherwise(0.0) + .alias("log_trade_return_1") + ) + ) + + expressions: list[pl.Expr] = [] + windows = sorted(set((*config.trade_windows, config.intensity_window))) + for window in windows: + signed = ( + pl.col("signed_trade_quantity") + .rolling_sum(window_size=window, min_samples=1) + .over(_GROUP) + ) + volume = pl.col("quantity").rolling_sum(window_size=window, min_samples=1).over(_GROUP) + count = ( + pl.col("_trade_observation").rolling_sum(window_size=window, min_samples=1).over(_GROUP) + ) + window_start = pl.coalesce( + [ + pl.col("decision_ts_ns").shift(window - 1).over(_GROUP), + pl.col("_segment_start_ts_ns"), + ] + ) + elapsed_seconds = (pl.col("decision_ts_ns") - window_start) / 1_000_000_000.0 + expressions.extend( + [ + signed.alias(f"signed_trade_volume_w{window}"), + volume.alias(f"trade_volume_w{window}"), + pl.when(volume > 0) + .then(signed / volume) + .otherwise(None) + .alias(f"trade_imbalance_w{window}"), + count.cast(pl.Float64).alias(f"trade_count_w{window}"), + pl.when(elapsed_seconds > 0) + .then(count / elapsed_seconds) + .otherwise(0.0) + .cast(pl.Float64) + .alias(f"trade_intensity_w{window}"), + ] + ) + + volatility_window = config.volatility_window + expressions.append( + pl.col("log_trade_return_1") + .pow(2) + .rolling_sum(window_size=volatility_window, min_samples=1) + .over(_GROUP) + .sqrt() + .alias(f"realized_volatility_w{volatility_window}") + ) + warmup = max((*config.trade_windows, config.intensity_window, config.volatility_window)) + return ( + prepared.with_columns(expressions) + .with_columns( + (pl.col("history_trades") >= warmup).alias("feature_ready"), + pl.col("decision_ts_ns").alias("max_feature_source_ts_ns"), + pl.col("decision_trade_id").alias("max_feature_source_trade_id"), + ) + .drop("_trade_observation", "_previous_trade_price", "_segment_start_ts_ns") + .sort(["decision_ts_ns", "symbol", "continuity_id", "decision_trade_id"]) + ) + + +def add_future_trade_labels(frame: pl.DataFrame, horizon_trades: int) -> pl.DataFrame: + """Attach strictly subsequent trade-price labels without crossing a gap.""" + + if horizon_trades < 1: + raise ResearchDataError("trade label horizon must be at least one trade") + _require_columns( + frame, + frozenset( + { + "symbol", + "continuity_id", + "decision_ts_ns", + "decision_trade_id", + "price", + } + ), + "trade feature frame", + ) + labeled = ( + frame.sort([*_GROUP, "decision_trade_id"]) + .with_columns( + pl.col("price").shift(-horizon_trades).over(_GROUP).alias("_target_trade_price"), + pl.col("decision_ts_ns") + .shift(-horizon_trades) + .over(_GROUP) + .alias("_target_trade_ts_ns"), + pl.col("decision_trade_id") + .shift(-horizon_trades) + .over(_GROUP) + .alias("_target_trade_id"), + pl.col("continuity_id") + .shift(-horizon_trades) + .over(_GROUP) + .alias("_target_continuity_id"), + ) + .with_columns( + ( + pl.col("_target_trade_price").is_null() + | (pl.col("_target_trade_id") <= pl.col("decision_trade_id")) + | (pl.col("_target_trade_ts_ns") < pl.col("decision_ts_ns")) + | ( + (pl.col("_target_trade_ts_ns") == pl.col("decision_ts_ns")) + & (pl.col("_target_trade_id") <= pl.col("decision_trade_id")) + ) + | (pl.col("_target_continuity_id") != pl.col("continuity_id")) + ).alias("right_censored") + ) + .with_columns( + pl.when(~pl.col("right_censored")) + .then((pl.col("_target_trade_price") / pl.col("price")).log()) + .otherwise(None) + .alias("future_trade_return"), + pl.when(~pl.col("right_censored")) + .then(pl.col("_target_trade_price")) + .otherwise(None) + .alias("future_trade_price"), + pl.when(~pl.col("right_censored")) + .then(pl.col("_target_trade_ts_ns")) + .otherwise(None) + .alias("label_information_end_ts_ns"), + pl.when(~pl.col("right_censored")) + .then(pl.col("_target_trade_id")) + .otherwise(None) + .alias("label_information_end_trade_id"), + pl.when(~pl.col("right_censored")) + .then(pl.col("_target_continuity_id")) + .otherwise(None) + .alias("label_continuity_id"), + pl.lit(horizon_trades, dtype=pl.Int64).alias("label_horizon_trades"), + pl.col("decision_ts_ns").alias("label_start_ts_ns"), + pl.col("decision_trade_id").alias("label_start_trade_id"), + ) + .with_columns( + pl.when(pl.col("future_trade_return").is_null()) + .then(None) + .when(pl.col("future_trade_return") > 0) + .then(1) + .when(pl.col("future_trade_return") < 0) + .then(-1) + .otherwise(0) + .cast(pl.Int8) + .alias("future_trade_direction"), + pl.when(pl.col("future_trade_return").is_null()) + .then(None) + .otherwise((pl.col("future_trade_return") > 0).cast(pl.Int8)) + .alias("future_trade_up"), + ) + .drop( + "_target_trade_price", + "_target_trade_ts_ns", + "_target_trade_id", + "_target_continuity_id", + ) + .sort(["decision_ts_ns", "symbol", "continuity_id", "decision_trade_id"]) + ) + validate_trade_only_temporal_contract(labeled) + return labeled + + +def build_trade_only_research_frame(trades: pl.DataFrame, config: FeatureConfig) -> pl.DataFrame: + """Build the complete causal trade-only feature and future-label frame.""" + + features = build_trade_only_features(trades, config) + return add_future_trade_labels(features, config.label_horizon_events) + + +def validate_trade_only_temporal_contract(frame: pl.DataFrame) -> TemporalAudit: + """Fail closed when trade feature lineage or label timing is noncausal.""" + + required = frozenset( + { + "symbol", + "continuity_id", + "decision_ts_ns", + "decision_trade_id", + "feature_cutoff_ts_ns", + "feature_continuity_id", + "max_feature_source_ts_ns", + "max_feature_source_trade_id", + "right_censored", + "future_trade_return", + "future_trade_price", + "future_trade_direction", + "future_trade_up", + "label_start_ts_ns", + "label_start_trade_id", + "label_information_end_ts_ns", + "label_information_end_trade_id", + "label_continuity_id", + } + ) + _require_columns(frame, required, "trade-only research frame") + future_feature = frame.filter( + (pl.col("feature_continuity_id") != pl.col("continuity_id")) + | (pl.col("max_feature_source_ts_ns") > pl.col("feature_cutoff_ts_ns")) + | ( + (pl.col("max_feature_source_ts_ns") == pl.col("feature_cutoff_ts_ns")) + & (pl.col("max_feature_source_trade_id") > pl.col("decision_trade_id")) + ) + ) + if not future_feature.is_empty(): + raise TemporalLeakageError("trade feature lineage extends beyond its decision cutoff") + + uncensored = ~pl.col("right_censored") + invalid_label = frame.filter( + (pl.col("label_start_ts_ns") != pl.col("decision_ts_ns")) + | (pl.col("label_start_trade_id") != pl.col("decision_trade_id")) + | ( + uncensored + & ( + pl.col("future_trade_return").is_null() + | pl.col("future_trade_price").is_null() + | pl.col("future_trade_direction").is_null() + | pl.col("future_trade_up").is_null() + | pl.col("label_information_end_ts_ns").is_null() + | pl.col("label_information_end_trade_id").is_null() + | (pl.col("label_continuity_id") != pl.col("continuity_id")) + | (pl.col("label_information_end_trade_id") <= pl.col("decision_trade_id")) + | (pl.col("label_information_end_ts_ns") < pl.col("decision_ts_ns")) + | ( + (pl.col("label_information_end_ts_ns") == pl.col("decision_ts_ns")) + & (pl.col("label_information_end_trade_id") <= pl.col("decision_trade_id")) + ) + ) + ) + | ( + pl.col("right_censored") + & ( + pl.col("future_trade_return").is_not_null() + | pl.col("future_trade_price").is_not_null() + | pl.col("future_trade_direction").is_not_null() + | pl.col("future_trade_up").is_not_null() + | pl.col("label_information_end_ts_ns").is_not_null() + | pl.col("label_information_end_trade_id").is_not_null() + | pl.col("label_continuity_id").is_not_null() + ) + ) + ) + if not invalid_label.is_empty(): + raise TemporalLeakageError( + "trade labels are not strictly future, gap-local, and censor-safe" + ) + + censored_rows = frame.filter(pl.col("right_censored")).height + return TemporalAudit( + rows=frame.height, + labeled_rows=frame.height - censored_rows, + right_censored_rows=censored_rows, + continuity_segments=frame.select("symbol", "continuity_id").unique().height, + ) + + +__all__ = [ + "add_future_trade_labels", + "build_trade_only_features", + "build_trade_only_research_frame", + "validate_trade_only_temporal_contract", +] diff --git a/Microstructure/tests/test_analysis.py b/Microstructure/tests/test_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..820a90e5c5f94dfb40b22f27679ad25d33b1c6b6 --- /dev/null +++ b/Microstructure/tests/test_analysis.py @@ -0,0 +1,236 @@ +from __future__ import annotations + +import polars as pl +import pytest + +from microstructure.research.analysis import ( + LiquidityShockThresholds, + RegimeThresholds, + assign_market_regimes, + cross_instrument_stability_summary, + estimate_signal_half_life, + feature_stability_summary, + intraday_liquidity_summary, + large_trade_price_impact_summary, + liquidity_recovery_summary, + ofi_future_return_association, + regime_outcome_summary, +) + +MINUTE = 60_000_000_000 + + +def test_intraday_liquidity_uses_fixed_reproducible_buckets() -> None: + frame = pl.DataFrame( + { + "symbol": ["BTCUSDT"] * 4, + "decision_ts_ns": [0, 30 * MINUTE, 60 * MINUTE, 90 * MINUTE], + "spread_bps": [2.0, 4.0, 6.0, 8.0], + "depth_total_l1": [100.0, 80.0, 60.0, 40.0], + "queue_imbalance_l1": [0.2, 0.0, -0.2, 0.4], + } + ) + summary = intraday_liquidity_summary(frame, bucket_minutes=60) + first = summary.row(0, named=True) + assert first["intraday_bucket_label"] == "00:00" + assert first["n_observations"] == 2 + assert first["mean_spread_bps"] == 3.0 + assert first["mean_depth_l1"] == 90.0 + assert summary.get_column("descriptive_only").all() + + +def test_ofi_association_and_half_life_use_supplied_horizons() -> None: + ofi = [-3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0] + orthogonal_noise = [1.0, -1.0, -1.0, 1.0, 1.0, -1.0, -1.0, 1.0] + frame = pl.DataFrame( + { + "symbol": ["BTCUSDT"] * len(ofi), + "ofi_l1": ofi, + "return_h1": ofi, + "return_h2": [ + value + noise for value, noise in zip(ofi, orthogonal_noise, strict=True) + ], + "return_h4": orthogonal_noise, + } + ) + association = ofi_future_return_association( + frame, + horizon_return_columns={1: "return_h1", 2: "return_h2", 4: "return_h4"}, + ) + at_one = association.filter(pl.col("horizon_events") == 1).row(0, named=True) + assert at_one["pearson_correlation"] == pytest.approx(1.0) + assert at_one["ols_slope_return_per_ofi_unit"] == pytest.approx(1.0) + assert at_one["descriptive_only"] is True + + half_life = estimate_signal_half_life(association) + result = half_life.summary.row(0, named=True) + assert result["reference_horizon_events"] == 1 + assert result["first_crossing_half_life_events"] == 4.0 + assert result["analysis_kind"] == "signal_half_life_descriptive" + assert half_life.curve.get_column("normalized_absolute_correlation")[0] == pytest.approx(1.0) + + +def test_large_trade_impact_requires_caller_supplied_train_threshold() -> None: + frame = pl.DataFrame( + { + "symbol": ["BTCUSDT"] * 4, + "quantity": [1.0, 2.0, 10.0, 20.0], + "impact_h2": [1.0, 2.0, 10.0, 20.0], + } + ) + summary = large_trade_price_impact_summary( + frame, + impact_columns={2: "impact_h2"}, + train_quantity_thresholds={"BTCUSDT": 5.0}, + ) + regular = summary.filter(~pl.col("large_trade")).row(0, named=True) + large = summary.filter(pl.col("large_trade")).row(0, named=True) + assert regular["mean_signed_impact_bps"] == 1.5 + assert large["mean_signed_impact_bps"] == 15.0 + assert large["train_quantity_threshold"] == 5.0 + assert large["threshold_source"] == "caller_supplied_train_period" + + +def test_liquidity_recovery_tracks_one_episode_and_censors_segment_tail() -> None: + frame = pl.DataFrame( + { + "symbol": ["BTCUSDT"] * 6, + "continuity_id": ["a"] * 6, + "decision_ts_ns": list(range(6)), + "decision_sequence": list(range(1, 7)), + "spread_bps": [2.0, 10.0, 8.0, 4.0, 3.0, 9.0], + "depth_total_l1": [100.0, 40.0, 60.0, 90.0, 100.0, 30.0], + } + ) + summary = liquidity_recovery_summary( + frame, + train_thresholds={ + "BTCUSDT": LiquidityShockThresholds( + spread_shock_bps=8.0, + depth_shock_max=50.0, + spread_recovery_bps=4.0, + depth_recovery_min=80.0, + max_recovery_events=3, + ) + }, + ) + assert summary.height == 2 + recovered = summary.row(0, named=True) + assert recovered["shock_sequence"] == 2 + assert recovered["recovery_events"] == 2 + assert recovered["recovery_time_ns"] == 2 + assert recovered["recovery_right_censored"] is False + assert recovered["threshold_source"] == "caller_supplied_train_period" + + tail = summary.row(1, named=True) + assert tail["shock_sequence"] == 6 + assert tail["recovered"] is None + assert tail["recovery_right_censored"] is True + assert tail["recovery_information_end_ts_ns"] is None + + +def test_liquidity_recovery_infers_late_censor_status_without_row_limit() -> None: + row_count = 201 + frame = pl.DataFrame( + { + "symbol": ["BTCUSDT"] * row_count, + "continuity_id": ["a"] * row_count, + "decision_ts_ns": list(range(row_count)), + "decision_sequence": list(range(row_count)), + "spread_bps": [10.0 if index % 2 == 0 else 2.0 for index in range(row_count)], + "depth_total_l1": [40.0 if index % 2 == 0 else 100.0 for index in range(row_count)], + } + ) + + summary = liquidity_recovery_summary( + frame, + train_thresholds={ + "BTCUSDT": LiquidityShockThresholds( + spread_shock_bps=8.0, + depth_shock_max=50.0, + spread_recovery_bps=4.0, + depth_recovery_min=80.0, + max_recovery_events=1, + ) + }, + ) + + assert summary.height == 101 + assert summary.get_column("recovery_censor_reason")[-1] == ("segment_ends_before_max_horizon") + + +def test_regimes_are_assigned_from_supplied_train_boundaries() -> None: + frame = pl.DataFrame( + { + "symbol": ["BTCUSDT"] * 3, + "volatility": [0.1, 0.5, 0.9], + "spread_bps": [1.0, 3.0, 6.0], + "depth_total_l1": [120.0, 80.0, 40.0], + "future_return": [0.01, 0.0, -0.02], + } + ) + thresholds = { + "BTCUSDT": RegimeThresholds( + volatility_low=0.2, + volatility_high=0.8, + spread_tight_bps=2.0, + spread_wide_bps=5.0, + depth_low=50.0, + depth_high=100.0, + ) + } + regimes = assign_market_regimes( + frame, train_thresholds=thresholds, volatility_column="volatility" + ) + assert regimes.get_column("joint_market_regime").to_list() == [ + "low__liquid", + "medium__normal", + "high__stressed", + ] + assert regimes.get_column("regime_threshold_source").unique().to_list() == [ + "caller_supplied_train_period" + ] + outcomes = regime_outcome_summary(regimes, outcome_columns=("future_return",)) + assert outcomes.get_column("n_observations").sum() == 3 + assert outcomes.get_column("descriptive_only").all() + + +def test_cross_instrument_and_feature_stability_are_descriptive() -> None: + effects = pl.DataFrame( + { + "symbol": ["BTCUSDT", "ETHUSDT", "BTCUSDT", "ETHUSDT"], + "horizon_events": [1, 1, 2, 2], + "effect": [0.2, 0.1, -0.1, -0.2], + } + ) + cross = cross_instrument_stability_summary(effects, value_column="effect") + assert cross.get_column("sign_agreement_fraction").to_list() == [1.0, 1.0] + assert cross.get_column("n_instruments").to_list() == [2, 2] + + reference = pl.DataFrame( + { + "symbol": ["BTCUSDT"] * 4, + "stable": [0.0, 1.0, 2.0, 3.0], + "shifted": [0.0, 1.0, 2.0, 3.0], + } + ) + comparison = pl.DataFrame( + { + "symbol": ["BTCUSDT"] * 4, + "stable": [0.0, 1.0, 2.0, 3.0], + "shifted": [2.0, 3.0, 4.0, 5.0], + } + ) + stability = feature_stability_summary( + reference, + comparison, + feature_columns=("stable", "shifted"), + bins=2, + ) + stable = stability.filter(pl.col("feature") == "stable").row(0, named=True) + shifted = stability.filter(pl.col("feature") == "shifted").row(0, named=True) + assert stable["population_stability_index"] == pytest.approx(0.0) + assert shifted["population_stability_index"] > 0 + assert shifted["standardized_mean_shift"] > 1.0 + assert shifted["bin_source"] == "reference_period_only" + assert shifted["descriptive_only"] is True diff --git a/Microstructure/tests/test_binance.py b/Microstructure/tests/test_binance.py new file mode 100644 index 0000000000000000000000000000000000000000..2846b16da1b6c2fd8ca929d74febd089976d5620 --- /dev/null +++ b/Microstructure/tests/test_binance.py @@ -0,0 +1,985 @@ +from __future__ import annotations + +import asyncio +import json +from collections.abc import AsyncIterator, Iterator, Mapping +from decimal import Decimal +from pathlib import Path +from typing import Any +from urllib.parse import urlencode + +import pyarrow as pa # type: ignore[import-untyped] +import pytest +import requests + +from microstructure.data.binance import ( + BinanceHistoricalTradeDownloader, + BinanceHTTPError, + BinanceLiveDepthCollector, + BinancePayloadError, + BinancePublicClient, + BinanceTradeStreamStopReason, + RawDepthFrame, + RawPage, + RetryPolicy, + _write_raw_response, + parse_depth_message, +) +from microstructure.data.evidence_budget import EvidenceBudgetExceeded, RetainedEvidenceBudget + + +class _FakeWebSocket: + def __init__(self, frames: list[str | bytes]) -> None: + self.frames = frames + + async def __aenter__(self) -> _FakeWebSocket: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: object | None, + ) -> None: + return None + + def __aiter__(self) -> AsyncIterator[str | bytes]: + async def iterate() -> AsyncIterator[str | bytes]: + for frame in self.frames: + yield frame + + return iterate() + + +class FakeResponse: + def __init__( + self, + status_code: int, + payload: Any, + *, + headers: Mapping[str, str] | None = None, + ) -> None: + self.status_code = status_code + self._payload = payload + self.content = json.dumps(payload, separators=(",", ":")).encode() + self.text = self.content.decode() + self.headers = dict(headers or {}) + self.url = "https://data-api.binance.vision/fixture" + + def json(self) -> Any: + return self._payload + + +class FakeSession: + def __init__(self, responses: list[FakeResponse]) -> None: + self.responses = responses + self.calls: list[dict[str, object]] = [] + + def get(self, url: str, *, params: Mapping[str, object], timeout: float) -> FakeResponse: + self.calls.append({"url": url, "params": dict(params), "timeout": timeout}) + response = self.responses.pop(0) + response.url = f"{url}?{urlencode(params)}" + return response + + +class ChunkedResponse: + def __init__( + self, + chunks: list[bytes], + *, + headers: Mapping[str, str] | None = None, + status_code: int = 200, + ) -> None: + self.status_code = status_code + self.headers = dict(headers or {}) + self.url = "https://data-api.binance.vision/fixture" + self.chunks = chunks + self.chunks_read = 0 + self.requested_chunk_sizes: list[int] = [] + self.closed = False + + @property + def content(self) -> bytes: + raise AssertionError("streaming trade path must not access response.content") + + @property + def text(self) -> str: + raise AssertionError("streaming trade path must not access response.text") + + def iter_content(self, *, chunk_size: int) -> Iterator[bytes]: + self.requested_chunk_sizes.append(chunk_size) + for chunk in self.chunks: + self.chunks_read += 1 + yield chunk + + def close(self) -> None: + self.closed = True + + +class StreamingSession: + def __init__(self, responses: list[ChunkedResponse]) -> None: + self.responses = responses + self.calls: list[dict[str, object]] = [] + + def get( + self, + url: str, + *, + params: Mapping[str, object], + timeout: float, + stream: bool = False, + ) -> ChunkedResponse: + self.calls.append( + { + "url": url, + "params": dict(params), + "timeout": timeout, + "stream": stream, + } + ) + response = self.responses.pop(0) + response.url = f"{url}?{urlencode(params)}" + return response + + +class InterruptedChunkedResponse(ChunkedResponse): + def iter_content(self, *, chunk_size: int) -> Iterator[bytes]: + self.requested_chunk_sizes.append(chunk_size) + self.chunks_read += 1 + yield self.chunks[0] + raise requests.ConnectionError("fixture stream interrupted") + + +def _write_budget_fixture_raw( + root: Path, + *, + budget: RetainedEvidenceBudget | None = None, +) -> RawPage: + return _write_raw_response( + b'{"fixture":true}', + raw_root=root, + dataset="budget_fixture", + symbol="BTCUSDT", + request_uri="https://data-api.binance.vision/fixture", + downloaded_at_utc="2026-08-07T00:00:00.000000000Z", + requested_start_ns=1, + requested_end_ns=2, + response_headers={"content-type": "application/json"}, + retained_evidence_budget=budget, + ) + + +def _client(session: FakeSession, *, sleeps: list[float] | None = None) -> BinancePublicClient: + recorded_sleeps = sleeps if sleeps is not None else [] + return BinancePublicClient( + session=session, # type: ignore[arg-type] + retry_policy=RetryPolicy(max_retries=2, base_delay_seconds=0.5), + sleep=recorded_sleeps.append, + random_value=lambda: 1.0, + ) + + +def test_final_retryable_streaming_response_is_closed() -> None: + response = ChunkedResponse([], status_code=503) + session = StreamingSession([response]) + client = BinancePublicClient( + session=session, # type: ignore[arg-type] + retry_policy=RetryPolicy(max_retries=0), + ) + + with pytest.raises(BinanceHTTPError, match="public Binance GET failed"): + client._request("/api/v3/aggTrades", {"symbol": "BTCUSDT"}, stream_response=True) + + assert response.closed + + +def test_interrupted_stream_preserves_bounded_prefix_before_failure(tmp_path: Path) -> None: + prefix = b'[{"a":1' + response = InterruptedChunkedResponse([prefix]) + session = StreamingSession([response]) + downloader = BinanceHistoricalTradeDownloader( + client=BinancePublicClient( + session=session, # type: ignore[arg-type] + retry_policy=RetryPolicy(max_retries=0), + ), + raw_root=tmp_path, + tick_size=Decimal("0.01"), + lot_size=Decimal("0.001"), + ) + + stream = downloader.stream( + symbol="BTCUSDT", + start_ts_ns=0, + end_ts_ns=2_000_000_000, + max_events=1, + ) + with pytest.raises(BinancePayloadError, match="interrupted after 7 bytes"): + next(stream) + + rejected = list((tmp_path / "binance_spot" / "agg_trades_rejected").rglob("*.json")) + raw_paths = [path for path in rejected if ".manifest-" not in path.name] + assert len(raw_paths) == 1 + assert raw_paths[0].read_bytes() == prefix + assert response.closed + + +def test_interrupted_stream_retries_after_preserving_failed_attempt(tmp_path: Path) -> None: + prefix = b'[{"a":1' + successful = json.dumps([_trade(1)], separators=(",", ":")).encode() + interrupted = InterruptedChunkedResponse([prefix]) + completed = ChunkedResponse([successful]) + session = StreamingSession([interrupted, completed]) + sleeps: list[float] = [] + downloader = BinanceHistoricalTradeDownloader( + client=BinancePublicClient( + session=session, # type: ignore[arg-type] + retry_policy=RetryPolicy(max_retries=1, base_delay_seconds=0.25), + sleep=sleeps.append, + random_value=lambda: 1.0, + ), + raw_root=tmp_path, + tick_size=Decimal("0.01"), + lot_size=Decimal("0.001"), + ) + + stream = downloader.stream( + symbol="BTCUSDT", + start_ts_ns=1_000_000_000, + end_ts_ns=2_000_000_000, + max_events=1, + ) + + batch = next(stream) + + assert batch.num_rows == 1 + assert len(session.calls) == 2 + assert sleeps == [0.25] + assert interrupted.closed and completed.closed + rejected = _raw_trade_payloads(tmp_path, dataset="agg_trades_rejected") + assert len(rejected) == 1 + assert rejected[0].read_bytes() == prefix + + +def test_retained_budget_charges_retry_prefix_and_success_sidecars(tmp_path: Path) -> None: + prefix = b'[{"a":1' + successful = json.dumps([_trade(1)], separators=(",", ":")).encode() + interrupted = InterruptedChunkedResponse([prefix]) + completed = ChunkedResponse([successful]) + session = StreamingSession([interrupted, completed]) + budget = RetainedEvidenceBudget(tmp_path, limit_bytes=100_000) + downloader = BinanceHistoricalTradeDownloader( + client=BinancePublicClient( + session=session, # type: ignore[arg-type] + retry_policy=RetryPolicy(max_retries=1, base_delay_seconds=0.0), + sleep=lambda _: None, + random_value=lambda: 0.0, + retained_evidence_budget=budget, + ), + raw_root=tmp_path, + tick_size=Decimal("0.01"), + lot_size=Decimal("0.001"), + ) + + batch = next( + downloader.stream( + symbol="BTCUSDT", + start_ts_ns=1_000_000_000, + end_ts_ns=2_000_000_000, + max_events=1, + ) + ) + + retained_files = [path for path in tmp_path.rglob("*") if path.is_file()] + assert batch.num_rows == 1 + assert any(path.read_bytes() == prefix for path in retained_files) + assert any(path.read_bytes() == successful for path in retained_files) + assert len([path for path in retained_files if ".manifest-" in path.name]) == 2 + assert budget.used_bytes == sum(path.stat().st_size for path in retained_files) + assert budget.reserved_bytes == 0 + + +def test_raw_body_and_sidecar_honor_exact_combined_budget_and_deduplicate( + tmp_path: Path, +) -> None: + reference = tmp_path / "reference" + reference_page = _write_budget_fixture_raw(reference) + exact_bytes = reference_page.path.stat().st_size + reference_page.manifest_path.stat().st_size + + root = tmp_path / "bounded" + budget = RetainedEvidenceBudget(root, limit_bytes=exact_bytes) + first = _write_budget_fixture_raw(root, budget=budget) + assert budget.used_bytes == exact_bytes + assert budget.remaining_bytes == 0 + + duplicate = _write_budget_fixture_raw(root, budget=budget) + assert duplicate.path == first.path + assert duplicate.manifest_path == first.manifest_path + assert budget.used_bytes == exact_bytes + assert budget.reserved_bytes == 0 + + +def test_raw_sidecar_overage_rolls_back_new_body_and_reservation(tmp_path: Path) -> None: + reference = tmp_path / "reference" + reference_page = _write_budget_fixture_raw(reference) + exact_bytes = reference_page.path.stat().st_size + reference_page.manifest_path.stat().st_size + + root = tmp_path / "bounded" + budget = RetainedEvidenceBudget(root, limit_bytes=exact_bytes - 1) + + with pytest.raises(EvidenceBudgetExceeded, match="raw source manifest"): + _write_budget_fixture_raw(root, budget=budget) + + assert [path for path in root.rglob("*") if path.is_file()] == [] + assert budget.used_bytes == 0 + assert budget.reserved_bytes == 0 + assert budget.remaining_bytes == exact_bytes - 1 + + +def test_raw_temp_creation_failure_releases_body_reservation( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + budget = RetainedEvidenceBudget(tmp_path, limit_bytes=10_000) + + def fail_mkstemp(*args: object, **kwargs: object) -> tuple[int, str]: + raise OSError("fixture temp failure") + + monkeypatch.setattr("microstructure.data.binance.tempfile.mkstemp", fail_mkstemp) + + with pytest.raises(OSError, match="fixture temp failure"): + _write_budget_fixture_raw(tmp_path, budget=budget) + + assert [path for path in tmp_path.rglob("*") if path.is_file()] == [] + assert budget.used_bytes == 0 + assert budget.reserved_bytes == 0 + assert budget.remaining_bytes == 10_000 + + +def test_exchange_info_response_is_transport_bounded_and_preserved(tmp_path: Path) -> None: + content = json.dumps(_exchange_info_payload(), separators=(",", ":")).encode() + response = ChunkedResponse([content]) + session = StreamingSession([response]) + client = BinancePublicClient( + session=session, # type: ignore[arg-type] + retry_policy=RetryPolicy(max_retries=0), + max_response_bytes=len(content) - 1, + ) + + with pytest.raises(BinancePayloadError, match="response body exceeded"): + client.fetch_exchange_info(symbol="BTCUSDT", raw_root=tmp_path) + + assert session.calls[0]["stream"] is True + assert response.closed + rejected = list((tmp_path / "binance_spot" / "exchange_info_rejected").rglob("*.json")) + raw_paths = [path for path in rejected if ".manifest-" not in path.name] + assert len(raw_paths) == 1 + assert len(raw_paths[0].read_bytes()) == len(content) - 1 + + +def test_depth_snapshot_response_is_transport_bounded_and_preserved(tmp_path: Path) -> None: + content = json.dumps( + {"lastUpdateId": 10, "bids": [["100.00", "0.002"]], "asks": []}, + separators=(",", ":"), + ).encode() + response = ChunkedResponse([content]) + session = StreamingSession([response]) + client = BinancePublicClient( + session=session, # type: ignore[arg-type] + retry_policy=RetryPolicy(max_retries=0), + max_response_bytes=len(content) - 1, + ) + + with pytest.raises(BinancePayloadError, match="response body exceeded"): + client.fetch_depth_snapshot( + symbol="BTCUSDT", + raw_root=tmp_path, + continuity_id="epoch-1", + tick_size=Decimal("0.01"), + lot_size=Decimal("0.001"), + limit=5, + ) + + assert session.calls[0]["stream"] is True + assert response.closed + rejected = list((tmp_path / "binance_spot" / "depth_snapshots_rejected").rglob("*.json")) + raw_paths = [path for path in rejected if ".manifest-" not in path.name] + assert len(raw_paths) == 1 + assert len(raw_paths[0].read_bytes()) == len(content) - 1 + + +def _trade( + aggregate_id: int, + *, + timestamp_ms: int = 1000, + buyer_is_maker: bool = False, +) -> dict[str, object]: + return { + "a": aggregate_id, + "p": "100.01", + "q": "0.002", + "f": aggregate_id * 10, + "l": aggregate_id * 10, + "T": timestamp_ms, + "m": buyer_is_maker, + } + + +def _exchange_info_payload(symbol: str = "BTCUSDT") -> dict[str, object]: + return { + "symbols": [ + { + "symbol": symbol, + "status": "TRADING", + "baseAsset": "BTC", + "quoteAsset": "USDT", + "filters": [ + { + "filterType": "PRICE_FILTER", + "minPrice": "0.01000000", + "maxPrice": "1000000.00000000", + "tickSize": "0.01000000", + }, + { + "filterType": "LOT_SIZE", + "minQty": "0.00001000", + "maxQty": "9000.00000000", + "stepSize": "0.00001000", + }, + ], + } + ] + } + + +def _raw_trade_payloads(root: Path, *, dataset: str = "agg_trades") -> list[Path]: + directory = root / "binance_spot" / dataset / "BTCUSDT" + return sorted(path for path in directory.glob("*.json") if ".manifest-" not in path.name) + + +def test_public_client_honors_retry_after_on_rate_limit() -> None: + sleeps: list[float] = [] + session = FakeSession( + [ + FakeResponse(429, {"code": -1003}, headers={"Retry-After": "2"}), + FakeResponse(200, []), + ] + ) + client = _client(session, sleeps=sleeps) + + response = client._request("/api/v3/aggTrades", {"symbol": "BTCUSDT"}) + + assert response.status_code == 200 + assert sleeps == [2.0] + assert len(session.calls) == 2 + + +def test_exchange_info_extracts_exact_public_tick_and_lot_filters(tmp_path: Path) -> None: + session = FakeSession([FakeResponse(200, _exchange_info_payload())]) + + metadata = _client(session).fetch_exchange_info(symbol="btcusdt", raw_root=tmp_path) + + assert metadata.symbol == "BTCUSDT" + assert metadata.status == "TRADING" + assert metadata.base_asset == "BTC" + assert metadata.quote_asset == "USDT" + assert metadata.tick_size == Decimal("0.01000000") + assert metadata.lot_size == Decimal("0.00001000") + assert (tmp_path / "binance_spot" / "exchange_info" / "BTCUSDT").is_dir() + + +def test_trade_stream_is_lazy_even_when_symbol_metadata_must_be_fetched( + tmp_path: Path, +) -> None: + session = FakeSession( + [ + FakeResponse(200, _exchange_info_payload()), + FakeResponse(200, [_trade(1)]), + ] + ) + pages: list[RawPage] = [] + downloader = BinanceHistoricalTradeDownloader( + client=_client(session), + raw_root=tmp_path, + request_limit=2, + ) + + stream = downloader.stream( + symbol="btcusdt", + start_ts_ns=1_000_000_000, + end_ts_ns=2_000_000_000, + max_events=10, + on_raw_page=pages.append, + ) + + assert session.calls == [] + with pytest.raises(RuntimeError, match="before normal exhaustion"): + _ = stream.summary + + batch = next(stream) + + assert isinstance(batch, pa.RecordBatch) + assert batch.num_rows == 1 + assert batch.column("trade_id").to_pylist() == [1] + assert len(session.calls) == 2 + assert len(pages) == 1 + assert stream.last_raw_page == pages[0] + assert stream.summary.rows_yielded == 1 + assert stream.summary.raw_page_count == 1 + assert stream.summary.stop_reason is BinanceTradeStreamStopReason.SHORT_PAGE + assert stream.summary.complete_range + with pytest.raises(StopIteration): + next(stream) + + +def test_trade_stream_uses_chunked_transport_without_accessing_response_content( + tmp_path: Path, +) -> None: + encoded = json.dumps([_trade(1)], separators=(",", ":")).encode() + response = ChunkedResponse( + [encoded[:11], encoded[11:]], + headers={"Content-Length": str(len(encoded))}, + ) + session = StreamingSession([response]) + client = BinancePublicClient( + session=session, # type: ignore[arg-type] + retry_policy=RetryPolicy(max_retries=0), + ) + downloader = BinanceHistoricalTradeDownloader( + client=client, + raw_root=tmp_path, + request_limit=2, + max_response_bytes=len(encoded), + tick_size=Decimal("0.01"), + lot_size=Decimal("0.001"), + ) + + stream = downloader.stream( + symbol="BTCUSDT", + start_ts_ns=1_000_000_000, + end_ts_ns=2_000_000_000, + max_events=10, + ) + batch = next(stream) + + assert batch.column("trade_id").to_pylist() == [1] + assert session.calls[0]["stream"] is True + assert response.chunks_read == 2 + assert response.closed + assert response.requested_chunk_sizes == [len(encoded) + 1] + + +def test_trade_stream_truncates_exactly_at_event_cap_before_yield(tmp_path: Path) -> None: + response = FakeResponse(200, [_trade(1), _trade(2), _trade(3)]) + session = FakeSession([response]) + downloader = BinanceHistoricalTradeDownloader( + client=_client(session), + raw_root=tmp_path, + request_limit=3, + tick_size=Decimal("0.01"), + lot_size=Decimal("0.001"), + ) + + stream = downloader.stream( + symbol="BTCUSDT", + start_ts_ns=1_000_000_000, + end_ts_ns=2_000_000_000, + max_events=2, + ) + batch = next(stream) + + assert batch.num_rows == 2 + assert batch.num_rows <= downloader.request_limit + assert batch.column("trade_id").to_pylist() == [1, 2] + assert stream.last_raw_page is not None + assert stream.last_raw_page.row_count == 3 + assert stream.summary.rows_yielded == 2 + assert stream.summary.stop_reason is BinanceTradeStreamStopReason.EVENT_CAP + assert not stream.summary.complete_range + assert len(session.calls) == 1 + + +def test_materialized_download_rejects_large_request_before_http(tmp_path: Path) -> None: + session = FakeSession([]) + downloader = BinanceHistoricalTradeDownloader( + client=_client(session), + raw_root=tmp_path, + materialization_max_rows=2, + tick_size=Decimal("0.01"), + lot_size=Decimal("0.001"), + ) + + with pytest.raises(ValueError, match=r"consume stream\(\) incrementally"): + downloader.download( + symbol="BTCUSDT", + start_ts_ns=1_000_000_000, + end_ts_ns=2_000_000_000, + max_events=3, + ) + + assert session.calls == [] + + +def test_trade_stream_empty_page_has_explicit_incomplete_summary(tmp_path: Path) -> None: + session = FakeSession([FakeResponse(200, [])]) + pages: list[RawPage] = [] + downloader = BinanceHistoricalTradeDownloader( + client=_client(session), + raw_root=tmp_path, + request_limit=2, + tick_size=Decimal("0.01"), + lot_size=Decimal("0.001"), + ) + + stream = downloader.stream( + symbol="BTCUSDT", + start_ts_ns=1_000_000_000, + end_ts_ns=2_000_000_000, + max_events=10, + on_raw_page=pages.append, + ) + + assert list(stream) == [] + assert stream.summary.rows_yielded == 0 + assert stream.summary.raw_page_count == 1 + assert stream.summary.stop_reason is BinanceTradeStreamStopReason.EMPTY_PAGE + assert not stream.summary.complete_range + assert len(pages) == 1 + assert pages[0].row_count == 0 + + +def test_trade_stream_stops_at_exclusive_range_end(tmp_path: Path) -> None: + session = FakeSession( + [FakeResponse(200, [_trade(1, timestamp_ms=1000), _trade(2, timestamp_ms=2000)])] + ) + downloader = BinanceHistoricalTradeDownloader( + client=_client(session), + raw_root=tmp_path, + request_limit=2, + tick_size=Decimal("0.01"), + lot_size=Decimal("0.001"), + ) + + stream = downloader.stream( + symbol="BTCUSDT", + start_ts_ns=1_000_000_000, + end_ts_ns=2_000_000_000, + max_events=10, + ) + batches = list(stream) + + assert len(batches) == 1 + assert batches[0].column("trade_id").to_pylist() == [1] + assert stream.summary.stop_reason is BinanceTradeStreamStopReason.RANGE_END + assert stream.summary.complete_range + + +def test_historical_trade_downloader_paginates_by_inclusive_id_and_preserves_raw( + tmp_path: Path, +) -> None: + page_one = [ + {"a": 1, "p": "100.01", "q": "0.002", "f": 10, "l": 10, "T": 1000, "m": False}, + {"a": 2, "p": "100.02", "q": "0.003", "f": 11, "l": 12, "T": 1000, "m": True}, + ] + page_two = [{"a": 3, "p": "100.03", "q": "0.004", "f": 13, "l": 13, "T": 1500, "m": False}] + session = FakeSession([FakeResponse(200, page_one), FakeResponse(200, page_two)]) + downloader = BinanceHistoricalTradeDownloader( + client=_client(session), + raw_root=tmp_path, + request_limit=2, + tick_size=Decimal("0.01"), + lot_size=Decimal("0.001"), + ) + + result = downloader.download( + symbol="BTCUSDT", + start_ts_ns=1_000_000_000, + end_ts_ns=2_000_000_000, + max_events=10, + ) + + assert result.complete_range + assert result.trades.column("trade_id").to_pylist() == [1, 2, 3] + assert result.trades.column("aggressor_side").to_pylist() == ["buy", "sell", "buy"] + assert result.trades.column("price_ticks").to_pylist() == [10_001, 10_002, 10_003] + assert ( + result.trades.column("availability_basis").to_pylist() == ["exchange_event_time_proxy"] * 3 + ) + assert session.calls[1]["params"] == {"symbol": "BTCUSDT", "fromId": 3, "limit": 2} + assert len(result.raw_pages) == 2 + assert all(page.path.is_file() and page.manifest_path.is_file() for page in result.raw_pages) + + +def test_historical_trade_downloader_rejects_oversized_page_after_preserving_raw( + tmp_path: Path, +) -> None: + payload = [ + { + "a": index, + "p": "100.01", + "q": "0.002", + "f": index, + "l": index, + "T": 1000, + "m": False, + } + for index in range(3) + ] + session = FakeSession([FakeResponse(200, payload)]) + downloader = BinanceHistoricalTradeDownloader( + client=_client(session), + raw_root=tmp_path, + request_limit=2, + tick_size=Decimal("0.01"), + lot_size=Decimal("0.001"), + ) + + with pytest.raises(BinancePayloadError, match="page-size bound"): + downloader.download( + symbol="BTCUSDT", + start_ts_ns=1_000_000_000, + end_ts_ns=2_000_000_000, + max_events=10, + ) + + raw_pages = _raw_trade_payloads(tmp_path) + assert raw_pages + + +def test_trade_stream_enforces_actual_response_byte_ceiling_and_preserves_raw( + tmp_path: Path, +) -> None: + response = FakeResponse(200, [_trade(1)]) + byte_ceiling = len(response.content) - 1 + session = FakeSession([response]) + downloader = BinanceHistoricalTradeDownloader( + client=_client(session), + raw_root=tmp_path, + request_limit=2, + max_response_bytes=byte_ceiling, + tick_size=Decimal("0.01"), + lot_size=Decimal("0.001"), + ) + + stream = downloader.stream( + symbol="BTCUSDT", + start_ts_ns=1_000_000_000, + end_ts_ns=2_000_000_000, + max_events=10, + ) + with pytest.raises(BinancePayloadError, match="body exceeded"): + next(stream) + + raw_pages = _raw_trade_payloads(tmp_path, dataset="agg_trades_rejected") + assert len(raw_pages) == 1 + assert raw_pages[0].read_bytes() == response.content[:byte_ceiling] + + +def test_chunked_oversized_body_stops_after_first_crossing_chunk(tmp_path: Path) -> None: + response = ChunkedResponse([b"abcd", b"efgh", b"must-not-be-read"]) + session = StreamingSession([response]) + client = BinancePublicClient( + session=session, # type: ignore[arg-type] + retry_policy=RetryPolicy(max_retries=0), + ) + downloader = BinanceHistoricalTradeDownloader( + client=client, + raw_root=tmp_path, + request_limit=2, + max_response_bytes=5, + tick_size=Decimal("0.01"), + lot_size=Decimal("0.001"), + ) + + stream = downloader.stream( + symbol="BTCUSDT", + start_ts_ns=1_000_000_000, + end_ts_ns=2_000_000_000, + max_events=10, + ) + with pytest.raises(BinancePayloadError, match="body exceeded"): + next(stream) + + assert response.chunks_read == 2 + assert response.requested_chunk_sizes == [6] + assert response.closed + assert session.calls[0]["stream"] is True + rejected = _raw_trade_payloads(tmp_path, dataset="agg_trades_rejected") + assert len(rejected) == 1 + assert rejected[0].read_bytes() == b"abcde" + sidecars = list(rejected[0].parent.glob(f"{rejected[0].name}.manifest-*.json")) + assert len(sidecars) == 1 + headers = json.loads(sidecars[0].read_text())["response_headers"] + assert headers["x-local-captured-bytes"] == "5" + assert headers["x-local-observed-bytes-lower-bound"] == "8" + + +def test_trade_stream_enforces_declared_response_byte_ceiling_and_preserves_raw( + tmp_path: Path, +) -> None: + response = ChunkedResponse([b"must-not-be-read"], headers={"Content-Length": "100000"}) + session = StreamingSession([response]) + client = BinancePublicClient( + session=session, # type: ignore[arg-type] + retry_policy=RetryPolicy(max_retries=0), + ) + downloader = BinanceHistoricalTradeDownloader( + client=client, + raw_root=tmp_path, + request_limit=2, + max_response_bytes=4096, + tick_size=Decimal("0.01"), + lot_size=Decimal("0.001"), + ) + + with pytest.raises(BinancePayloadError, match="Content-Length exceeded"): + downloader.download( + symbol="BTCUSDT", + start_ts_ns=1_000_000_000, + end_ts_ns=2_000_000_000, + max_events=10, + ) + + assert response.chunks_read == 0 + assert response.closed + assert session.calls[0]["stream"] is True + raw_pages = _raw_trade_payloads(tmp_path, dataset="agg_trades_rejected") + assert len(raw_pages) == 1 + assert raw_pages[0].read_bytes() == b"" + sidecars = list(raw_pages[0].parent.glob(f"{raw_pages[0].name}.manifest-*.json")) + assert len(sidecars) == 1 + sidecar = sidecars[0] + assert json.loads(sidecar.read_text())["response_headers"]["Content-Length"] == "100000" + + +def test_trade_stream_rejects_unordered_page_after_preserving_raw(tmp_path: Path) -> None: + response = FakeResponse(200, [_trade(2), _trade(1)]) + session = FakeSession([response]) + downloader = BinanceHistoricalTradeDownloader( + client=_client(session), + raw_root=tmp_path, + request_limit=2, + tick_size=Decimal("0.01"), + lot_size=Decimal("0.001"), + ) + + stream = downloader.stream( + symbol="BTCUSDT", + start_ts_ns=1_000_000_000, + end_ts_ns=2_000_000_000, + max_events=10, + ) + with pytest.raises(BinancePayloadError, match="not strictly increasing"): + next(stream) + + raw_pages = _raw_trade_payloads(tmp_path) + assert len(raw_pages) == 1 + assert raw_pages[0].read_bytes() == response.content + + +def test_trade_stream_rejects_nonprogressing_next_page(tmp_path: Path) -> None: + first_response = FakeResponse(200, [_trade(1), _trade(2)]) + repeated_response = FakeResponse(200, [_trade(2), _trade(3)]) + session = FakeSession([first_response, repeated_response]) + downloader = BinanceHistoricalTradeDownloader( + client=_client(session), + raw_root=tmp_path, + request_limit=2, + tick_size=Decimal("0.01"), + lot_size=Decimal("0.001"), + ) + stream = downloader.stream( + symbol="BTCUSDT", + start_ts_ns=1_000_000_000, + end_ts_ns=2_000_000_000, + max_events=10, + ) + + assert next(stream).column("trade_id").to_pylist() == [1, 2] + assert session.calls[1:] == [] + with pytest.raises(BinancePayloadError, match="did not advance"): + next(stream) + + assert session.calls[1]["params"] == {"symbol": "BTCUSDT", "fromId": 3, "limit": 2} + + +def test_trade_stream_preserves_malformed_raw_page_before_parsing_error(tmp_path: Path) -> None: + response = FakeResponse(200, {"not": "a trade list"}) + session = FakeSession([response]) + downloader = BinanceHistoricalTradeDownloader( + client=_client(session), + raw_root=tmp_path, + request_limit=2, + tick_size=Decimal("0.01"), + lot_size=Decimal("0.001"), + ) + + with pytest.raises(BinancePayloadError, match="malformed Binance aggregate-trade page"): + downloader.download( + symbol="BTCUSDT", + start_ts_ns=1_000_000_000, + end_ts_ns=2_000_000_000, + max_events=10, + ) + + raw_pages = _raw_trade_payloads(tmp_path) + assert len(raw_pages) == 1 + assert raw_pages[0].read_bytes() == response.content + + +def test_parse_spot_diff_depth_uses_u_ranges_and_zero_as_delete() -> None: + raw = json.dumps( + { + "stream": "btcusdt@depth@100ms", + "data": { + "e": "depthUpdate", + "E": 1_700_000_000_123_456, + "s": "BTCUSDT", + "U": 101, + "u": 104, + "b": [["100.01", "0.00000"], ["100.00", "0.00200"]], + "a": [["100.02", "0.00300"]], + }, + } + ) + + delta = parse_depth_message( + raw, + received_ts_ns=1_700_000_000_200_000_000, + capture_seq=9, + continuity_id="session-1", + tick_size=Decimal("0.01"), + lot_size=Decimal("0.001"), + timestamp_unit="us", + ) + + assert delta.first_update_id == 101 + assert delta.last_update_id == 104 + assert delta.previous_update_id is None # Spot's documented payload has no pu. + assert delta.bids == ((10_001, 0), (10_000, 2)) + assert delta.asks == ((10_002, 3),) + assert delta.event_ts_ns == 1_700_000_000_123_456_000 + assert delta.available_ts_ns == delta.received_ts_ns + + +def test_live_collector_reports_exact_raw_frame_before_utf8_parse_failure() -> None: + malformed = b"\xffnot-json" + observed: list[RawDepthFrame] = [] + connection = _FakeWebSocket([malformed]) + collector = BinanceLiveDepthCollector( + symbols=("BTCUSDT",), + max_reconnects=0, + connect_factory=lambda url: connection, + on_raw_frame=observed.append, + ) + + async def receive_one() -> object: + return await anext(collector.stream(max_messages=1)) + + with pytest.raises(UnicodeDecodeError): + asyncio.run(receive_one()) + + assert len(observed) == 1 + assert observed[0].payload == malformed + assert observed[0].was_text is False + assert observed[0].capture_seq == 0 + assert observed[0].continuity_id.startswith("binance-live-") diff --git a/Microstructure/tests/test_binance_archive.py b/Microstructure/tests/test_binance_archive.py new file mode 100644 index 0000000000000000000000000000000000000000..1293f7726d8e25dcb681c4c3b7447b9e287278d8 --- /dev/null +++ b/Microstructure/tests/test_binance_archive.py @@ -0,0 +1,920 @@ +from __future__ import annotations + +import hashlib +import io +import json +import os +import zipfile +from collections.abc import Iterator, Mapping +from dataclasses import replace +from datetime import date +from decimal import Decimal +from pathlib import Path + +import pyarrow as pa # type: ignore[import-untyped] +import pytest +import requests + +from microstructure.data.binance_archive import ( + ArchiveDownloadLimits, + BinanceArchiveClient, + BinanceArchiveHTTPError, + BinanceArchivePayloadError, + DailyArchiveRequest, + RetryPolicy, +) +from microstructure.data.evidence_budget import EvidenceBudgetExceeded, RetainedEvidenceBudget +from microstructure.data.schemas import ensure_schema +from microstructure.provenance import sha256_file + +BASE_URL = "https://fixtures.invalid" +DAY = date(2024, 1, 3) +START_MS = 1_704_240_000_000 + + +class _Response: + def __init__( + self, + chunks: list[bytes], + *, + headers: Mapping[str, str] | None = None, + status_code: int = 200, + interrupt_after: int | None = None, + final_url: str | None = None, + ) -> None: + self.chunks = chunks + self.headers = dict(headers or {}) + self.status_code = status_code + self.interrupt_after = interrupt_after + self.final_url = final_url + self.url = "" + self.closed = False + self.chunk_sizes: list[int] = [] + self.chunks_read = 0 + + @property + def content(self) -> bytes: + raise AssertionError("archive acquisition must not access response.content") + + @property + def text(self) -> str: + raise AssertionError("archive acquisition must not access response.text") + + def iter_content(self, *, chunk_size: int) -> Iterator[bytes]: + self.chunk_sizes.append(chunk_size) + for index, chunk in enumerate(self.chunks): + if self.interrupt_after is not None and index == self.interrupt_after: + raise requests.ConnectionError("fixture interrupted") + self.chunks_read += 1 + yield chunk + + def close(self) -> None: + self.closed = True + + +class _Session: + def __init__(self, responses: list[_Response | requests.RequestException]) -> None: + self.responses = responses + self.calls: list[dict[str, object]] = [] + + def get(self, url: str, *, timeout: float, stream: bool) -> _Response: + self.calls.append({"url": url, "timeout": timeout, "stream": stream}) + response = self.responses.pop(0) + if isinstance(response, requests.RequestException): + raise response + response.url = response.final_url or url + return response + + +def _request(*, archive_date: date = DAY) -> DailyArchiveRequest: + return DailyArchiveRequest( + symbol="BTCUSDT", + date=archive_date, + tick_size=Decimal("0.01"), + lot_size=Decimal("0.0001"), + ) + + +def _limits( + *, + compressed: int = 1_000_000, + uncompressed: int = 1_000_000, + checksum: int = 4_096, + chunk: int = 17, + line: int = 16_384, +) -> ArchiveDownloadLimits: + return ArchiveDownloadLimits( + max_compressed_bytes=compressed, + max_uncompressed_bytes=uncompressed, + max_checksum_bytes=checksum, + transfer_chunk_bytes=chunk, + max_csv_line_bytes=line, + ) + + +def _row( + aggregate_id: int, + *, + timestamp_ms: int, + price: str = "42000.01", + quantity: str = "0.0010", + first_trade_id: int | None = None, + last_trade_id: int | None = None, + buyer_is_maker: str = "true", + best_match: str = "true", +) -> bytes: + first = aggregate_id * 2 if first_trade_id is None else first_trade_id + last = first if last_trade_id is None else last_trade_id + return ( + f"{aggregate_id},{price},{quantity},{first},{last},{timestamp_ms}," + f"{buyer_is_maker},{best_match}" + ).encode() + + +def _zip_bytes( + content: bytes, + *, + member: str | None = None, + extra_member: bool = False, +) -> bytes: + request = _request() + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_DEFLATED) as archive: + archive.writestr(member or request.member_name, content) + if extra_member: + archive.writestr("unexpected.csv", b"x") + return buffer.getvalue() + + +def _responses( + archive: bytes, + *, + expected_sha: str | None = None, + checksum_body: bytes | None = None, + archive_chunks: list[bytes] | None = None, + archive_headers: Mapping[str, str] | None = None, +) -> tuple[_Session, _Response, _Response]: + request = _request() + official = expected_sha or hashlib.sha256(archive).hexdigest() + checksum = checksum_body or f"{official} {request.archive_name}\n".encode() + checksum_response = _Response([checksum], headers={"Content-Length": str(len(checksum))}) + chunks = ( + archive_chunks + if archive_chunks is not None + else [archive[index : index + 11] for index in range(0, len(archive), 11)] + ) + headers = dict( + archive_headers if archive_headers is not None else {"Content-Length": str(len(archive))} + ) + archive_response = _Response(chunks, headers=headers) + return _Session([checksum_response, archive_response]), checksum_response, archive_response + + +def _acquire( + tmp_path: Path, + csv_content: bytes, + *, + member: str | None = None, + extra_member: bool = False, + limits: ArchiveDownloadLimits | None = None, +): + archive = _zip_bytes(csv_content, member=member, extra_member=extra_member) + session, _, _ = _responses(archive) + acquired = BinanceArchiveClient( + session=session, # type: ignore[arg-type] + base_url=BASE_URL, + ).acquire(_request(), raw_root=tmp_path, limits=limits or _limits()) + return acquired, session, archive + + +def _retained_regular_file_bytes(root: Path) -> int: + return sum(path.stat().st_size for path in root.rglob("*") if path.is_file()) + + +def test_acquire_is_bounded_content_addressed_and_does_not_open_csv(tmp_path: Path) -> None: + csv_content = ( + b"\n".join( + [ + _row(10, timestamp_ms=START_MS), + _row(11, timestamp_ms=START_MS + 1, buyer_is_maker="false"), + _row(12, timestamp_ms=START_MS + 2), + ] + ) + + b"\n" + ) + archive = _zip_bytes(csv_content) + session, checksum_response, archive_response = _responses(archive) + acquired = BinanceArchiveClient( + session=session, # type: ignore[arg-type] + base_url=BASE_URL, + timeout_seconds=7.5, + ).acquire(_request(), raw_root=tmp_path, limits=_limits(chunk=13)) + + digest = hashlib.sha256(archive).hexdigest() + assert acquired.archive_artifact.path.name == _request().archive_name + assert acquired.archive_artifact.sha256 == digest == acquired.upstream_sha256 + assert acquired.archive_artifact.bytes == len(archive) + assert acquired.declared_uncompressed_bytes == len(csv_content) + assert acquired.archive_artifact.path.read_bytes() == archive + assert acquired.checksum_artifact.path.name == f"{_request().archive_name}.CHECKSUM" + checksum_manifest = json.loads(acquired.checksum_artifact.manifest_path.read_text()) + assert checksum_manifest["source"] == "binance_spot_daily_aggtrades_archive_checksum" + assert checksum_manifest["path"] == f"{_request().archive_name}.CHECKSUM" + assert sha256_file(acquired.archive_artifact.manifest_path) == ( + acquired.archive_artifact.manifest_sha256 + ) + manifest = json.loads(acquired.archive_artifact.manifest_path.read_text()) + assert manifest["source"] == "binance_spot_daily_aggtrades_archive" + assert manifest["path"] == _request().archive_name + assert manifest["upstream_checksum_sha256"] == digest + assert manifest["requested_range_ns"] == { + "start": 1_704_240_000_000_000_000, + "end_exclusive": 1_704_326_400_000_000_000, + } + assert [call["stream"] for call in session.calls] == [True, True] + assert [call["timeout"] for call in session.calls] == [7.5, 7.5] + assert checksum_response.closed and archive_response.closed + assert archive_response.chunk_sizes == [13] + assert not list(tmp_path.rglob(".download-*.tmp")) + + +def test_shared_evidence_budget_charges_every_success_artifact_exactly_once( + tmp_path: Path, +) -> None: + archive = _zip_bytes(_row(1, timestamp_ms=START_MS) + b"\n") + session, _, _ = _responses(archive) + budget = RetainedEvidenceBudget(tmp_path, limit_bytes=1_000_000) + + acquired = BinanceArchiveClient( + session=session, # type: ignore[arg-type] + base_url=BASE_URL, + retained_evidence_budget=budget, + ).acquire(_request(), raw_root=tmp_path, limits=_limits()) + + assert acquired.archive_artifact.path.is_file() + assert acquired.checksum_artifact.path.is_file() + assert acquired.archive_artifact.manifest_path.is_file() + assert acquired.checksum_artifact.manifest_path.is_file() + assert budget.reserved_bytes == 0 + assert budget.used_bytes == _retained_regular_file_bytes(tmp_path) + + +def test_budgeted_content_reuse_releases_download_reservations_without_double_charge( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr( + "microstructure.data.binance_archive.utc_now_iso", + lambda: "2026-08-07T00:00:00Z", + ) + archive = _zip_bytes(_row(1, timestamp_ms=START_MS) + b"\n") + first_session, _, _ = _responses(archive) + budget = RetainedEvidenceBudget(tmp_path, limit_bytes=1_000_000) + first = BinanceArchiveClient( + session=first_session, # type: ignore[arg-type] + base_url=BASE_URL, + retained_evidence_budget=budget, + ).acquire(_request(), raw_root=tmp_path, limits=_limits()) + first_used = budget.used_bytes + first_files = sorted( + path.relative_to(tmp_path) for path in tmp_path.rglob("*") if path.is_file() + ) + + second_session, _, _ = _responses(archive) + second = BinanceArchiveClient( + session=second_session, # type: ignore[arg-type] + base_url=BASE_URL, + retained_evidence_budget=budget, + ).acquire(_request(), raw_root=tmp_path, limits=_limits()) + + assert second.archive_artifact.path == first.archive_artifact.path + assert second.checksum_artifact.path == first.checksum_artifact.path + assert second.archive_artifact.manifest_path == first.archive_artifact.manifest_path + assert second.checksum_artifact.manifest_path == first.checksum_artifact.manifest_path + assert budget.used_bytes == first_used == _retained_regular_file_bytes(tmp_path) + assert budget.reserved_bytes == 0 + assert sorted(path.relative_to(tmp_path) for path in tmp_path.rglob("*") if path.is_file()) == ( + first_files + ) + assert not list(tmp_path.rglob(".download-*.tmp")) + + +def test_budgeted_retries_charge_one_duplicate_prefix_and_every_distinct_sidecar( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr( + "microstructure.data.binance_archive.utc_now_iso", + lambda: "2026-08-07T00:00:00Z", + ) + archive = _zip_bytes(_row(1, timestamp_ms=START_MS) + b"\n") + _, checksum_response, archive_response = _responses(archive) + first_interrupted = _Response( + [archive[:12], archive[12:]], + headers={"Content-Length": str(len(archive))}, + interrupt_after=1, + ) + second_interrupted = _Response( + [archive[:12], archive[12:]], + headers={"Content-Length": str(len(archive))}, + interrupt_after=1, + ) + session = _Session([checksum_response, first_interrupted, second_interrupted, archive_response]) + budget = RetainedEvidenceBudget(tmp_path, limit_bytes=1_000_000) + + BinanceArchiveClient( + session=session, # type: ignore[arg-type] + base_url=BASE_URL, + retry_policy=RetryPolicy(max_retries=2, base_delay_seconds=0.0), + sleep=lambda _: None, + random_value=lambda: 0.0, + retained_evidence_budget=budget, + ).acquire(_request(), raw_root=tmp_path, limits=_limits()) + + assert len(list(tmp_path.rglob("*.zip.rejected"))) == 1 + rejected_manifests = list(tmp_path.rglob("*.zip.rejected.manifest-*.json")) + assert len(rejected_manifests) == 2 + assert { + json.loads(path.read_text())["response_headers"]["x-local-download-attempt"] + for path in rejected_manifests + } == {"1", "2"} + assert budget.used_bytes == _retained_regular_file_bytes(tmp_path) + assert budget.reserved_bytes == 0 + assert not list(tmp_path.rglob(".download-*.tmp")) + + +def test_sidecar_budget_failure_rolls_back_new_body_and_all_reservations( + tmp_path: Path, +) -> None: + archive = _zip_bytes(_row(1, timestamp_ms=START_MS) + b"\n") + session, checksum_response, archive_response = _responses(archive) + checksum_bytes = sum(len(chunk) for chunk in checksum_response.chunks) + budget = RetainedEvidenceBudget(tmp_path, limit_bytes=checksum_bytes) + + with pytest.raises(EvidenceBudgetExceeded, match="raw source manifest"): + BinanceArchiveClient( + session=session, # type: ignore[arg-type] + base_url=BASE_URL, + retained_evidence_budget=budget, + ).acquire(_request(), raw_root=tmp_path, limits=_limits()) + + assert checksum_response.closed + assert archive_response.chunks_read == 0 + assert budget.used_bytes == budget.reserved_bytes == 0 + assert _retained_regular_file_bytes(tmp_path) == 0 + assert not list(tmp_path.rglob(".download-*.tmp")) + + +def test_normalized_stream_is_one_shot_bounded_and_terminally_summarized( + tmp_path: Path, +) -> None: + csv_content = ( + b"\n".join( + [ + _row(40, timestamp_ms=START_MS, quantity="0.0010"), + _row(41, timestamp_ms=START_MS, buyer_is_maker="false"), + _row(42, timestamp_ms=START_MS + 2, price="42000.02"), + ] + ) + + b"\n" + ) + acquired, _, archive = _acquire(tmp_path, csv_content) + stream = acquired.iter_normalized_batches(batch_rows=2) + assert iter(stream) is stream + with pytest.raises(RuntimeError, match="before full stream exhaustion"): + _ = stream.summary + + batches = list(stream) + assert [batch.num_rows for batch in batches] == [2, 1] + for batch in batches: + ensure_schema(batch, "trades") + table = pa.Table.from_batches(batches) + assert table.column("trade_id").to_pylist() == [40, 41, 42] + assert table.column("event_ts_ns").to_pylist() == [ + START_MS * 1_000_000, + START_MS * 1_000_000, + (START_MS + 2) * 1_000_000, + ] + assert table.column("price_ticks").to_pylist() == [4_200_001, 4_200_001, 4_200_002] + assert table.column("quantity_lots").to_pylist() == [10, 10, 10] + assert table.column("aggressor_side").to_pylist() == ["sell", "buy", "sell"] + assert set(table.column("continuity_id").to_pylist()) == {"binance_spot:BTCUSDT:2024-01-03"} + assert set(table.column("source_artifact_id").to_pylist()) == {acquired.archive_artifact.sha256} + summary = stream.summary + assert summary.rows == 3 + assert summary.first_trade_id == 40 + assert summary.last_trade_id == 42 + assert summary.first_event_ts_ns == START_MS * 1_000_000 + assert summary.last_event_ts_ns == (START_MS + 2) * 1_000_000 + assert summary.expanded_bytes == len(csv_content) + assert summary.compressed_bytes == len(archive) + with pytest.raises(StopIteration): + next(stream) + + +def test_member_stream_hash_directory_and_rows_are_bound_to_one_open_fd( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + official_csv = _row(1, timestamp_ms=START_MS, price="42000.01") + b"\n" + malicious_csv = _row(1, timestamp_ms=START_MS, price="99999.99") + b"\n" + assert len(official_csv) == len(malicious_csv) + acquired, _, _ = _acquire(tmp_path, official_csv) + acquired = replace(acquired, requires_member_open_guard=True) + official_path = acquired.archive_artifact.path + official_sha = acquired.archive_artifact.sha256 + malicious_path = tmp_path / "malicious.zip" + malicious_path.write_bytes(_zip_bytes(malicious_csv)) + official_backup = tmp_path / "official-backup.zip" + malicious_backup = tmp_path / "malicious-backup.zip" + original_zipfile = zipfile.ZipFile + swapped = False + + def swapping_zipfile(source: object, *args: object, **kwargs: object) -> zipfile.ZipFile: + nonlocal swapped + if not swapped: + os.replace(official_path, official_backup) + os.replace(malicious_path, official_path) + swapped = True + return original_zipfile(source, *args, **kwargs) # type: ignore[arg-type] + + def restore_and_verify_authority() -> None: + os.replace(official_path, malicious_backup) + os.replace(official_backup, official_path) + assert sha256_file(official_path) == official_sha + + monkeypatch.setattr(zipfile, "ZipFile", swapping_zipfile) + batches = list( + acquired.iter_normalized_batches( + batch_rows=1, + before_member_open=restore_and_verify_authority, + ) + ) + + table = pa.Table.from_batches(batches) + assert swapped is True + assert table.column("price").to_pylist() == [42000.01] + assert sha256_file(official_path) == official_sha + + +def test_early_close_cannot_fabricate_summary(tmp_path: Path) -> None: + content = b"\n".join([_row(1, timestamp_ms=START_MS), _row(2, timestamp_ms=START_MS + 1)]) + acquired, _, _ = _acquire(tmp_path, content) + stream = acquired.iter_normalized_batches(batch_rows=1) + assert next(stream).num_rows == 1 + stream.close() + with pytest.raises(RuntimeError, match="before full stream exhaustion"): + _ = stream.summary + with pytest.raises(StopIteration): + next(stream) + + +def test_archive_body_ceiling_preserves_only_bounded_prefix(tmp_path: Path) -> None: + csv_content = _row(1, timestamp_ms=START_MS) + b"\n" + archive = _zip_bytes(csv_content) + limit = max(1, len(archive) // 2) + session, checksum_response, archive_response = _responses( + archive, + archive_chunks=[archive[:limit], archive[limit:]], + archive_headers={}, + ) + client = BinanceArchiveClient(session=session, base_url=BASE_URL) # type: ignore[arg-type] + + with pytest.raises(BinanceArchivePayloadError, match="exceeds byte ceiling"): + client.acquire( + _request(), + raw_root=tmp_path, + limits=_limits(compressed=limit, chunk=limit), + ) + + rejected = list(tmp_path.rglob("*.zip.rejected")) + assert len(rejected) == 1 + assert rejected[0].stat().st_size == limit + assert rejected[0].read_bytes() == archive[:limit] + assert checksum_response.closed and archive_response.closed + assert not list(tmp_path.rglob(".download-*.tmp")) + + +def test_content_length_ceiling_rejects_without_reading_body(tmp_path: Path) -> None: + archive = _zip_bytes(_row(1, timestamp_ms=START_MS)) + session, _, archive_response = _responses( + archive, + archive_headers={"Content-Length": str(len(archive) + 1)}, + ) + with pytest.raises(BinanceArchivePayloadError, match="Content-Length"): + BinanceArchiveClient( + session=session, # type: ignore[arg-type] + base_url=BASE_URL, + ).acquire(_request(), raw_root=tmp_path, limits=_limits(compressed=len(archive))) + assert archive_response.chunks_read == 0 + rejected = list(tmp_path.rglob("*.zip.rejected")) + assert len(rejected) == 1 and rejected[0].stat().st_size == 0 + + +def test_interrupted_archive_stream_preserves_prefix_and_closes(tmp_path: Path) -> None: + archive = _zip_bytes(_row(1, timestamp_ms=START_MS)) + official = hashlib.sha256(archive).hexdigest() + checksum = f"{official} {_request().archive_name}\n".encode() + checksum_response = _Response([checksum], headers={"Content-Length": str(len(checksum))}) + archive_response = _Response([archive[:12], archive[12:]], interrupt_after=1) + session = _Session([checksum_response, archive_response]) + + with pytest.raises(BinanceArchiveHTTPError, match="interrupted after 12 bytes"): + BinanceArchiveClient( + session=session, # type: ignore[arg-type] + base_url=BASE_URL, + retry_policy=RetryPolicy(max_retries=0), + ).acquire(_request(), raw_root=tmp_path, limits=_limits()) + + rejected = list(tmp_path.rglob("*.zip.rejected")) + assert len(rejected) == 1 + assert rejected[0].read_bytes() == archive[:12] + assert archive_response.closed + + +def test_retryable_503_is_evidenced_then_succeeds(tmp_path: Path) -> None: + archive = _zip_bytes(_row(1, timestamp_ms=START_MS)) + _, checksum_response, archive_response = _responses(archive) + unavailable = _Response([], status_code=503) + session = _Session([unavailable, checksum_response, archive_response]) + delays: list[float] = [] + + acquired = BinanceArchiveClient( + session=session, # type: ignore[arg-type] + base_url=BASE_URL, + retry_policy=RetryPolicy( + max_retries=1, + base_delay_seconds=4.0, + max_delay_seconds=1.0, + ), + sleep=delays.append, + random_value=lambda: 0.5, + ).acquire(_request(), raw_root=tmp_path, limits=_limits()) + + assert acquired.archive_artifact.path.read_bytes() == archive + assert len(session.calls) == 3 + assert unavailable.closed and checksum_response.closed and archive_response.closed + assert delays == [0.5] + rejected = list(tmp_path.rglob("*.CHECKSUM.rejected")) + manifests = list(tmp_path.rglob("*.CHECKSUM.rejected.manifest-*.json")) + assert len(rejected) == len(manifests) == 1 + evidence = json.loads(manifests[0].read_text()) + assert evidence["response_headers"]["x-local-download-attempt"] == "1" + assert "HTTP 503" in evidence["response_headers"]["x-local-rejection-reason"] + assert not session.responses + + +def test_mid_body_interruption_retries_after_retaining_prefix_and_sidecar( + tmp_path: Path, +) -> None: + archive = _zip_bytes(_row(1, timestamp_ms=START_MS)) + _, checksum_response, archive_response = _responses(archive) + interrupted = _Response( + [archive[:12], archive[12:]], + headers={"Content-Length": str(len(archive))}, + interrupt_after=1, + ) + session = _Session([checksum_response, interrupted, archive_response]) + + acquired = BinanceArchiveClient( + session=session, # type: ignore[arg-type] + base_url=BASE_URL, + retry_policy=RetryPolicy(max_retries=1, base_delay_seconds=0.0), + sleep=lambda _: None, + random_value=lambda: 0.0, + ).acquire(_request(), raw_root=tmp_path, limits=_limits()) + + rejected = list(tmp_path.rglob("*.zip.rejected")) + manifests = list(tmp_path.rglob("*.zip.rejected.manifest-*.json")) + assert len(rejected) == len(manifests) == 1 + assert rejected[0].read_bytes() == archive[:12] + assert acquired.archive_artifact.path.read_bytes() == archive + assert interrupted.closed and archive_response.closed + assert not session.responses + + +def test_429_honors_retry_after_and_closes_before_sleep(tmp_path: Path) -> None: + archive = _zip_bytes(_row(1, timestamp_ms=START_MS)) + _, checksum_response, archive_response = _responses(archive) + throttled = _Response([], status_code=429, headers={"Retry-After": "2.75"}) + session = _Session([throttled, checksum_response, archive_response]) + delays: list[float] = [] + + def record_sleep(delay: float) -> None: + assert throttled.closed + delays.append(delay) + + def unexpected_random() -> float: + raise AssertionError("valid Retry-After must bypass jitter") + + BinanceArchiveClient( + session=session, # type: ignore[arg-type] + base_url=BASE_URL, + retry_policy=RetryPolicy(max_retries=1), + sleep=record_sleep, + random_value=unexpected_random, + ).acquire(_request(), raw_root=tmp_path, limits=_limits()) + + assert delays == [2.75] + assert not session.responses + + +def test_content_length_truncation_is_evidenced_and_retried(tmp_path: Path) -> None: + archive = _zip_bytes(_row(1, timestamp_ms=START_MS)) + _, checksum_response, archive_response = _responses(archive) + truncated = _Response( + [archive], + headers={"Content-Length": str(len(archive) + 7)}, + ) + session = _Session([checksum_response, truncated, archive_response]) + + acquired = BinanceArchiveClient( + session=session, # type: ignore[arg-type] + base_url=BASE_URL, + retry_policy=RetryPolicy(max_retries=1, base_delay_seconds=0.0), + sleep=lambda _: None, + random_value=lambda: 0.0, + ).acquire(_request(), raw_root=tmp_path, limits=_limits()) + + rejected = list(tmp_path.rglob("*.zip.rejected")) + assert len(rejected) == 1 and rejected[0].read_bytes() == archive + assert acquired.archive_artifact.path.read_bytes() == archive + assert truncated.closed + assert not session.responses + + +@pytest.mark.parametrize("failure_kind", ["404", "redirect"]) +def test_nonretryable_http_failures_stop_after_one_attempt( + tmp_path: Path, + failure_kind: str, +) -> None: + if failure_kind == "404": + failure = _Response([], status_code=404) + message = "HTTP 404" + else: + failure = _Response([], final_url="https://redirect.invalid/archive") + message = "redirected" + session = _Session([failure]) + delays: list[float] = [] + + with pytest.raises(BinanceArchiveHTTPError, match=message): + BinanceArchiveClient( + session=session, # type: ignore[arg-type] + base_url=BASE_URL, + retry_policy=RetryPolicy(max_retries=3), + sleep=delays.append, + ).acquire(_request(), raw_root=tmp_path, limits=_limits()) + + assert len(session.calls) == 1 + assert not delays + assert failure.closed + manifests = list(tmp_path.rglob("*.CHECKSUM.rejected.manifest-*.json")) + assert len(manifests) == 1 + + +def test_retry_attempt_exhaustion_retains_evidence_for_every_connect_failure( + tmp_path: Path, +) -> None: + session = _Session( + [ + requests.ConnectionError("connect one"), + requests.Timeout("connect two"), + requests.ConnectionError("connect three"), + ] + ) + delays: list[float] = [] + + with pytest.raises(BinanceArchiveHTTPError, match="failed before a response") as raised: + BinanceArchiveClient( + session=session, # type: ignore[arg-type] + base_url=BASE_URL, + retry_policy=RetryPolicy( + max_retries=2, + base_delay_seconds=2.0, + max_delay_seconds=3.0, + ), + sleep=delays.append, + random_value=lambda: 0.5, + ).acquire(_request(), raw_root=tmp_path, limits=_limits()) + + assert delays == [1.0, 1.5] + assert len(session.calls) == 3 + assert any("exhausted 3" in note for note in raised.value.__notes__) + rejected = list(tmp_path.rglob("*.CHECKSUM.rejected")) + manifests = list(tmp_path.rglob("*.CHECKSUM.rejected.manifest-*.json")) + assert len(rejected) == 1 + assert len(manifests) == 3 + attempts = sorted( + json.loads(path.read_text())["response_headers"]["x-local-download-attempt"] + for path in manifests + ) + assert attempts == ["1", "2", "3"] + assert not list(tmp_path.rglob(".download-*.tmp")) + + +def test_official_checksum_mismatch_never_publishes_trusted_zip(tmp_path: Path) -> None: + archive = _zip_bytes(_row(1, timestamp_ms=START_MS)) + session, _, archive_response = _responses(archive, expected_sha="0" * 64) + + with pytest.raises(BinanceArchivePayloadError, match="official CHECKSUM"): + BinanceArchiveClient( + session=session, # type: ignore[arg-type] + base_url=BASE_URL, + ).acquire(_request(), raw_root=tmp_path, limits=_limits()) + + assert not list((tmp_path / "binance_spot" / "daily_agg_trades_archive").rglob("*.zip")) + rejected = list(tmp_path.rglob("*.zip.rejected")) + assert len(rejected) == 1 and rejected[0].read_bytes() == archive + assert archive_response.closed + + +def test_official_checksum_basename_is_immutable_across_conflicting_acquisitions( + tmp_path: Path, +) -> None: + first_archive = _zip_bytes(_row(1, timestamp_ms=START_MS)) + first_session, _, _ = _responses(first_archive) + first = BinanceArchiveClient( + session=first_session, # type: ignore[arg-type] + base_url=BASE_URL, + ).acquire(_request(), raw_root=tmp_path, limits=_limits()) + + second_archive = _zip_bytes(_row(2, timestamp_ms=START_MS + 1)) + second_session, _, _ = _responses(second_archive) + with pytest.raises(BinanceArchivePayloadError, match="official CHECKSUM basename collides"): + BinanceArchiveClient( + session=second_session, # type: ignore[arg-type] + base_url=BASE_URL, + ).acquire(_request(), raw_root=tmp_path, limits=_limits()) + + assert first.archive_artifact.path.name == _request().archive_name + assert first.archive_artifact.path.read_bytes() == first_archive + assert len(second_session.calls) == 1 + rejected = list(tmp_path.rglob("*.CHECKSUM.rejected")) + expected_checksum = ( + f"{hashlib.sha256(second_archive).hexdigest()} {_request().archive_name}\n".encode() + ) + assert len(rejected) == 1 and rejected[0].read_bytes() == expected_checksum + assert not list(tmp_path.rglob(".download-*.tmp")) + + +@pytest.mark.parametrize( + "checksum", + [ + b"not-a-checksum\n", + f"{'0' * 64} {_request().archive_name}\n".encode(), + f"{'0' * 64} WRONG.zip\n".encode(), + f"{'A' * 64} {_request().archive_name}\n".encode(), + f"{'0' * 64} {_request().archive_name}\r".encode(), + ], +) +def test_malformed_checksum_fails_before_archive_request(tmp_path: Path, checksum: bytes) -> None: + response = _Response([checksum], headers={"Content-Length": str(len(checksum))}) + session = _Session([response]) + with pytest.raises(BinanceArchivePayloadError, match="CHECKSUM"): + BinanceArchiveClient( + session=session, # type: ignore[arg-type] + base_url=BASE_URL, + ).acquire(_request(), raw_root=tmp_path, limits=_limits()) + assert len(session.calls) == 1 + assert response.closed + assert len(list(tmp_path.rglob("*.CHECKSUM"))) == 1 + + +@pytest.mark.parametrize( + ("member", "extra", "message"), + [ + ("wrong.csv", False, "member path/name"), + ("../BTCUSDT-aggTrades-2024-01-03.csv", False, "member path/name"), + (None, True, "exactly one"), + ], +) +def test_zip_member_contract_is_fail_closed( + tmp_path: Path, + member: str | None, + extra: bool, + message: str, +) -> None: + archive = _zip_bytes(_row(1, timestamp_ms=START_MS), member=member, extra_member=extra) + session, _, _ = _responses(archive) + with pytest.raises(BinanceArchivePayloadError, match=message): + BinanceArchiveClient( + session=session, # type: ignore[arg-type] + base_url=BASE_URL, + ).acquire(_request(), raw_root=tmp_path, limits=_limits()) + trusted = list(tmp_path.rglob("daily_agg_trades_archive/*/*/*.zip")) + assert len(trusted) == 1 + assert trusted[0].read_bytes() == archive + + +def test_zip_local_and_central_member_names_must_agree(tmp_path: Path) -> None: + archive = bytearray(_zip_bytes(_row(1, timestamp_ms=START_MS))) + expected_name = _request().member_name.encode("ascii") + local_name_offset = archive.find(expected_name) + central_name_offset = archive.find(expected_name, local_name_offset + len(expected_name)) + assert local_name_offset >= 0 and central_name_offset > local_name_offset + archive[local_name_offset : local_name_offset + len(expected_name)] = b"x" * len(expected_name) + response_bytes = bytes(archive) + session, _, _ = _responses(response_bytes) + + with pytest.raises(BinanceArchivePayloadError, match="local member path/name"): + BinanceArchiveClient( + session=session, # type: ignore[arg-type] + base_url=BASE_URL, + ).acquire(_request(), raw_root=tmp_path, limits=_limits()) + + +def test_declared_uncompressed_size_ceiling_fails_before_csv_open(tmp_path: Path) -> None: + content = _row(1, timestamp_ms=START_MS) + b"\n" + archive = _zip_bytes(content) + session, _, _ = _responses(archive) + with pytest.raises(BinanceArchivePayloadError, match="uncompressed bytes"): + BinanceArchiveClient( + session=session, # type: ignore[arg-type] + base_url=BASE_URL, + ).acquire( + _request(), + raw_root=tmp_path, + limits=_limits(uncompressed=len(content) - 1), + ) + + +@pytest.mark.parametrize( + ("content", "message"), + [ + (b"1,2,3\n", "exactly 8 fields"), + ( + _row(1, timestamp_ms=START_MS) + b"\n" + _row(3, timestamp_ms=START_MS + 1), + "noncontiguous", + ), + ( + _row(1, timestamp_ms=START_MS + 2) + b"\n" + _row(2, timestamp_ms=START_MS + 1), + "time reverses", + ), + (_row(1, timestamp_ms=START_MS - 1), "outside declared UTC date"), + (_row(1, timestamp_ms=START_MS, price="42000.001"), "not aligned"), + (_row(1, timestamp_ms=START_MS, quantity="0"), "positive and finite"), + (_row(1, timestamp_ms=START_MS, buyer_is_maker="yes"), "true or false"), + (_row(1, timestamp_ms=START_MS, first_trade_id=9, last_trade_id=8), "exceeds"), + ], +) +def test_csv_shape_type_date_sequence_and_scale_contracts( + tmp_path: Path, + content: bytes, + message: str, +) -> None: + acquired, _, _ = _acquire(tmp_path, content) + with pytest.raises(BinanceArchivePayloadError, match=message): + list(acquired.iter_normalized_batches(batch_rows=2)) + assert acquired.archive_artifact.path.is_file() + assert not list(tmp_path.rglob(".download-*.tmp")) + + +def test_csv_line_ceiling_is_enforced_during_expansion(tmp_path: Path) -> None: + content = _row(1, timestamp_ms=START_MS) + acquired, _, _ = _acquire(tmp_path, content, limits=_limits(line=8)) + with pytest.raises(BinanceArchivePayloadError, match="CSV line exceeds"): + list(acquired.iter_normalized_batches()) + + +def test_archive_tampering_is_detected_before_csv_open(tmp_path: Path) -> None: + acquired, _, _ = _acquire(tmp_path, _row(1, timestamp_ms=START_MS)) + with acquired.archive_artifact.path.open("ab") as sink: + sink.write(b"tamper") + with pytest.raises(BinanceArchivePayloadError, match="bytes changed"): + next(acquired.iter_normalized_batches()) + + +def test_request_and_limit_validation() -> None: + with pytest.raises(ValueError, match="uppercase"): + DailyArchiveRequest("../btc", DAY, Decimal("0.01"), Decimal("0.001")) + with pytest.raises(ValueError, match="tick_size"): + DailyArchiveRequest("BTCUSDT", DAY, Decimal("0"), Decimal("0.001")) + with pytest.raises(ValueError, match="byte limits"): + _limits(compressed=0) + with pytest.raises(ValueError, match="HTTPS origin"): + BinanceArchiveClient(base_url="http://data.binance.vision/path") + + +def test_microsecond_archive_timestamp_policy_from_2025(tmp_path: Path) -> None: + archive_date = date(2025, 1, 1) + request = _request(archive_date=archive_date) + timestamp_us = 1_735_689_600_000_001 + content = _row(1, timestamp_ms=timestamp_us) + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_DEFLATED) as archive_file: + archive_file.writestr(request.member_name, content) + archive = buffer.getvalue() + official = hashlib.sha256(archive).hexdigest() + checksum = f"{official} {request.archive_name}\n".encode() + session = _Session( + [ + _Response([checksum], headers={"Content-Length": str(len(checksum))}), + _Response([archive], headers={"Content-Length": str(len(archive))}), + ] + ) + acquired = BinanceArchiveClient( + session=session, # type: ignore[arg-type] + base_url=BASE_URL, + ).acquire(request, raw_root=tmp_path, limits=_limits()) + table = pa.Table.from_batches(list(acquired.iter_normalized_batches())) + assert table.column("event_ts_ns").to_pylist() == [timestamp_us * 1_000] diff --git a/Microstructure/tests/test_book.py b/Microstructure/tests/test_book.py new file mode 100644 index 0000000000000000000000000000000000000000..345f57184a0e2240ce2be9bba82778d6ba9c75db --- /dev/null +++ b/Microstructure/tests/test_book.py @@ -0,0 +1,165 @@ +from __future__ import annotations + +import pytest + +from microstructure.data.book import ( + BookInvariantError, + BookSnapshot, + DepthDelta, + IncrementalBookReconstructor, + reconstruct_snapshot_and_deltas, +) + + +def _snapshot() -> BookSnapshot: + return BookSnapshot( + venue="binance_spot", + symbol="BTCUSDT", + snapshot_id="snapshot-fixture", + request_ts_ns=1_000, + received_ts_ns=1_100, + available_ts_ns=1_100, + continuity_id="session-1", + last_update_id=100, + depth_limit=5000, + bids=((10_000, 10), (9_999, 20), (9_998, 30)), + asks=((10_001, 15), (10_002, 25), (10_003, 35)), + tick_size=0.01, + lot_size=0.001, + source_artifact_id="snapshot-fixture", + ) + + +def _delta( + start: int, + end: int, + *, + bids: tuple[tuple[int, int], ...] = (), + asks: tuple[tuple[int, int], ...] = (), + event_ts_ns: int = 2_000, + previous: int | None = None, + continuity_id: str = "session-1", + tick_size: float = 0.01, + lot_size: float = 0.001, +) -> DepthDelta: + return DepthDelta( + venue="binance_spot", + symbol="BTCUSDT", + event_ts_ns=event_ts_ns, + received_ts_ns=event_ts_ns + 100, + available_ts_ns=event_ts_ns + 100, + availability_basis="local_receive_time", + capture_seq=end, + continuity_id=continuity_id, + first_update_id=start, + last_update_id=end, + previous_update_id=previous, + bids=bids, + asks=asks, + tick_size=tick_size, + lot_size=lot_size, + source_artifact_id=f"delta-{start}-{end}", + ) + + +def test_reconstruction_discards_stale_bridges_snapshot_and_accepts_overlap() -> None: + result = reconstruct_snapshot_and_deltas( + _snapshot(), + [ + _delta(98, 100, bids=((10_000, 999),)), + _delta(100, 102, bids=((10_000, 0),)), + _delta(102, 104, bids=((10_000, 12),), asks=((10_001, 18),)), + ], + ) + + assert result.status == "LIVE" + assert result.stale_events == 1 + assert result.final_update_id == 104 + assert result.observations.num_rows == 2 + first, second = result.observations.to_pylist() + assert first["best_bid_ticks"] == 9_999 + assert second["best_bid_ticks"] == 10_000 + assert second["sequence_start"] == 102 + assert result.gaps.num_rows == 0 + + +def test_forward_gap_is_recorded_and_later_events_are_not_applied() -> None: + result = reconstruct_snapshot_and_deltas( + _snapshot(), + [ + _delta(100, 102), + _delta(105, 106, bids=((10_000, 20),)), + _delta(107, 108, bids=((10_000, 30),)), + ], + ) + + assert result.status == "GAPPED" + assert result.final_update_id == 102 + assert result.observations.num_rows == 1 + [gap] = result.gaps.to_pylist() + assert gap["expected_sequence"] == 103 + assert gap["missing_start"] == 103 + assert gap["missing_end"] == 104 + assert gap["reason"] == "forward_sequence_gap" + + +def test_crossed_book_is_emitted_as_invalid_then_epoch_stops() -> None: + result = reconstruct_snapshot_and_deltas( + _snapshot(), + [_delta(100, 101, bids=((10_002, 5),)), _delta(102, 102)], + ) + + assert result.status == "INVALID" + assert result.observations.num_rows == 1 + assert result.observations.column("is_valid").to_pylist() == [False] + assert result.gaps.column("reason").to_pylist() == ["crossed_or_locked_book"] + assert result.final_update_id == 101 + + +def test_sequence_order_not_timestamp_order_and_availability_waits_for_snapshot() -> None: + result = reconstruct_snapshot_and_deltas( + _snapshot(), + [ + _delta(100, 101, event_ts_ns=5_000), + _delta(102, 102, event_ts_ns=4_000), + ], + ) + + assert result.status == "LIVE" + assert result.final_update_id == 102 + assert result.observations.column("event_ts_ns").to_pylist() == [5_000, 4_000] + assert all( + value >= _snapshot().available_ts_ns + for value in result.observations.column("available_ts_ns").to_pylist() + ) + + +def test_previous_update_id_mismatch_requires_resynchronization() -> None: + result = reconstruct_snapshot_and_deltas(_snapshot(), [_delta(100, 102, previous=99)]) + + assert result.status == "GAPPED" + assert result.observations.num_rows == 0 + assert result.gaps.column("reason").to_pylist() == ["previous_update_id_mismatch"] + + +def test_delta_scale_mismatch_fails_closed_before_reinterpretation() -> None: + with pytest.raises(BookInvariantError, match="scales do not match"): + reconstruct_snapshot_and_deltas( + _snapshot(), + [_delta(100, 101, tick_size=0.1)], + ) + + +def test_malformed_stale_looking_range_is_invalid_and_later_delta_is_audited() -> None: + reconstructor = IncrementalBookReconstructor(_snapshot()) + + malformed = reconstructor.update(_delta(101, 99)) + excluded = reconstructor.update(_delta(101, 101)) + + assert malformed.outcome == "INVALID" + assert malformed.gap is not None + assert malformed.gap.reason == "invalid_sequence_range" + assert reconstructor.stale_events == 0 + assert excluded.outcome == "EXCLUDED_AFTER_TERMINAL" + assert excluded.gap is not None + assert excluded.gap.reason == "epoch_already_invalid" diff --git a/Microstructure/tests/test_cancellation_features.py b/Microstructure/tests/test_cancellation_features.py new file mode 100644 index 0000000000000000000000000000000000000000..ed267beb9e12a4fcb37391965f62d8ba5f820bd7 --- /dev/null +++ b/Microstructure/tests/test_cancellation_features.py @@ -0,0 +1,130 @@ +from __future__ import annotations + +from typing import Any, cast + +import polars as pl +import pytest + +from microstructure.data.schemas import SCHEMA_VERSION, table_from_records +from microstructure.research.features import ( + ResearchDataError, + build_cancellation_intensity_features, + model_feature_columns, +) + + +def _delta( + update_id: int, + *, + bids: list[tuple[int, int]], + asks: list[tuple[int, int]], + continuity_id: str = "epoch-a", +) -> dict[str, Any]: + event_ts_ns = 1_700_000_000_000_000_000 + update_id * 1_000 + return { + "schema_version": SCHEMA_VERSION, + "venue": "binance_spot", + "symbol": "BTCUSDT", + "event_ts_ns": event_ts_ns, + "received_ts_ns": event_ts_ns + 100, + "available_ts_ns": event_ts_ns + 100, + "availability_basis": "local_receive_time", + "capture_seq": update_id, + "continuity_id": continuity_id, + "first_update_id": update_id, + "last_update_id": update_id, + "previous_update_id": update_id - 1 if update_id > 1 else None, + "bids": [ + {"price_ticks": price_ticks, "quantity_lots": quantity_lots} + for price_ticks, quantity_lots in bids + ], + "asks": [ + {"price_ticks": price_ticks, "quantity_lots": quantity_lots} + for price_ticks, quantity_lots in asks + ], + "tick_size": 0.01, + "lot_size": 0.001, + "source_artifact_id": f"{update_id:064x}", + } + + +def _frame(records: list[dict[str, Any]]) -> pl.DataFrame: + table = table_from_records("depth_deltas", records) + return cast(pl.DataFrame, pl.from_arrow(table)) + + +def test_cancellation_intensity_counts_only_observable_zero_quantity_deletes() -> None: + frame = _frame( + [ + _delta(1, bids=[(10_000, 0)], asks=[(10_002, 5)]), + _delta(2, bids=[(9_999, 0)], asks=[(10_003, 0)]), + _delta(3, bids=[(10_000, 4)], asks=[]), + _delta( + 10, + bids=[(10_000, 7)], + asks=[], + continuity_id="epoch-b", + ), + ] + ) + + result = build_cancellation_intensity_features(frame, windows=(2,)) + rows = result.sort(["continuity_id", "decision_sequence"]).to_dicts() + + assert [row["cancellation_deletes_current"] for row in rows] == [1, 2, 0, 0] + assert [row["depth_updates_current"] for row in rows] == [2, 2, 1, 1] + assert [row["cancellation_deletes_w2"] for row in rows] == [1, 3, 2, 0] + assert [row["depth_updates_w2"] for row in rows] == [2, 4, 3, 1] + assert [row["cancellation_intensity_w2"] for row in rows] == pytest.approx( + [0.5, 0.75, 2.0 / 3.0, 0.0] + ) + assert set(result.get_column("cancellation_observation_policy")) == { + "zero_quantity_level_deletes_only" + } + assert not result.get_column("nonzero_reduction_classified_as_cancellation").any() + assert result.get_column("max_feature_source_ts_ns").equals( + result.get_column("feature_cutoff_ts_ns") + ) + assert result.get_column("max_feature_source_sequence").equals( + result.get_column("decision_sequence") + ) + assert model_feature_columns(result) == ("cancellation_intensity_w2",) + + +def test_future_depth_mutation_cannot_change_past_cancellation_features() -> None: + records = [ + _delta(1, bids=[(10_000, 0)], asks=[]), + _delta(2, bids=[(10_000, 5)], asks=[]), + _delta(3, bids=[], asks=[(10_002, 0)]), + _delta(4, bids=[(9_999, 8)], asks=[]), + ] + before = build_cancellation_intensity_features(_frame(records), windows=(3,)) + mutated = [dict(record) for record in records] + mutated[3] = _delta(4, bids=[(9_999, 0)], asks=[(10_004, 0)]) + after = build_cancellation_intensity_features(_frame(mutated), windows=(3,)) + columns = [ + "decision_sequence", + "cancellation_deletes_w3", + "depth_updates_w3", + "cancellation_intensity_w3", + "max_feature_source_ts_ns", + "max_feature_source_sequence", + ] + + assert ( + before.filter(pl.col("decision_sequence") < 4) + .select(columns) + .equals(after.filter(pl.col("decision_sequence") < 4).select(columns)) + ) + + +def test_cancellation_features_fail_closed_on_unsegmented_sequence_gap() -> None: + frame = _frame( + [ + _delta(1, bids=[(10_000, 0)], asks=[]), + _delta(3, bids=[(10_000, 0)], asks=[]), + ] + ) + + with pytest.raises(ResearchDataError, match="stale/gapped sequence"): + build_cancellation_intensity_features(frame, windows=(2,)) diff --git a/Microstructure/tests/test_cli.py b/Microstructure/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..3ed5475f11564b233aaf7409eb828e7473566fbe --- /dev/null +++ b/Microstructure/tests/test_cli.py @@ -0,0 +1,2035 @@ +from __future__ import annotations + +import asyncio +import base64 +import hashlib +import json +import os +import subprocess +from collections.abc import AsyncIterator +from datetime import date +from decimal import Decimal +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from microstructure import cli as cli_module +from microstructure.cli import main +from microstructure.data.binance import CapturedDepth, RawDepthFrame +from microstructure.data.book import BookSnapshot, DepthDelta +from microstructure.data.storage import write_source_manifest +from microstructure.m8_acquisition import M8AcquisitionFailureResult +from microstructure.m8_l2_capture import M8L2VerificationError +from microstructure.provenance import read_json, sha256_file, utc_now_iso + +PROJECT_ROOT = Path(__file__).parents[1] + + +def _captured_depth( + *, + sequence: int, + continuity_id: str, + event_ts_ns: int, +) -> CapturedDepth: + raw_payload = json.dumps( + {"continuity_id": continuity_id, "sequence": sequence}, + separators=(",", ":"), + ) + return CapturedDepth( + raw_payload=raw_payload, + delta=DepthDelta( + venue="binance_spot", + symbol="BTCUSDT", + event_ts_ns=event_ts_ns, + received_ts_ns=event_ts_ns + 100, + available_ts_ns=event_ts_ns + 100, + availability_basis="local_receive_time", + capture_seq=sequence, + continuity_id=continuity_id, + first_update_id=sequence, + last_update_id=sequence, + previous_update_id=sequence - 1, + bids=((10_000, 10 + sequence),), + asks=(), + tick_size=0.01, + lot_size=0.001, + source_artifact_id=hashlib.sha256(raw_payload.encode()).hexdigest(), + ), + ) + + +def _preserved_snapshot( + *, + output_root: Path, + continuity_id: str, + last_update_id: int, + received_ts_ns: int, +) -> BookSnapshot: + payload = json.dumps( + { + "asks": [["100.02", "0.010"]], + "bids": [["100.00", "0.010"]], + "lastUpdateId": last_update_id, + }, + separators=(",", ":"), + sort_keys=True, + ).encode() + digest = hashlib.sha256(payload).hexdigest() + raw_path = ( + output_root / "raw" / "binance_spot" / "depth_snapshots" / "BTCUSDT" / f"{digest}.json" + ) + raw_path.parent.mkdir(parents=True, exist_ok=True) + raw_path.write_bytes(payload) + write_source_manifest( + raw_path, + source="binance_spot_public_api", + source_uri="https://example.invalid/api/v3/depth", + downloaded_at_utc=utc_now_iso(), + requested_start_ns=None, + requested_end_ns=None, + ) + return BookSnapshot( + venue="binance_spot", + symbol="BTCUSDT", + snapshot_id=digest, + request_ts_ns=received_ts_ns - 100, + received_ts_ns=received_ts_ns, + available_ts_ns=received_ts_ns, + continuity_id=continuity_id, + last_update_id=last_update_id, + depth_limit=100, + bids=((10_000, 10),), + asks=((10_002, 10),), + tick_size=0.01, + lot_size=0.001, + source_artifact_id=digest, + ) + + +def test_cli_help_and_version_are_available(capsys: object) -> None: + try: + main(["--help"]) + except SystemExit as error: + assert error.code == 0 + + +def test_validate_command_runs_offline(capsys: object) -> None: + exit_code = main(["validate", "--config", str(PROJECT_ROOT / "configs" / "smoke.toml")]) + + assert exit_code == 0 + + +def _mock_m8_config(*, allow_quality_warnings: bool = False) -> SimpleNamespace: + return SimpleNamespace( + periods=(SimpleNamespace(), SimpleNamespace()), + study=SimpleNamespace( + symbols=("BTCUSDT", "ETHUSDT"), + evidence_tier="FULL_DATA", + ), + quality=SimpleNamespace(allow_quality_warnings=allow_quality_warnings), + ) + + +def test_acquire_m8_command_prints_raw_only_authority_and_propagates_paths( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + config_path = tmp_path / "study.toml" + output_root = tmp_path / "m8-data" + manifest_path = output_root / "_manifests" / "m8-acquisition.manifest-aaaaaaaa.json" + digest = "a" * 64 + config = _mock_m8_config() + result = SimpleNamespace( + output_root=output_root.resolve(), + manifest_path=manifest_path, + manifest_sha256=digest, + metadata_count=2, + archive_count=8, + total_raw_evidence_bytes=12_345, + ) + calls: list[tuple[object, Path]] = [] + + def fake_load(path: Path) -> object: + assert path == config_path + return config + + def fake_acquire(loaded: object, destination: Path) -> object: + calls.append((loaded, destination)) + return result + + monkeypatch.setattr(cli_module, "load_m8_config", fake_load) + monkeypatch.setattr(cli_module, "acquire_m8_archives", fake_acquire) + + exit_code = main( + [ + "acquire-m8", + "--config", + str(config_path), + "--output-root", + str(output_root), + ] + ) + + assert exit_code == 0 + assert calls == [(config, output_root.resolve())] + assert json.loads(capsys.readouterr().out) == { + "archives": 8, + "csv_members_opened": False, + "economic_fields_inspected": False, + "metadata_responses": 2, + "output_root": str(output_root.resolve()), + "raw_manifest": str(manifest_path), + "raw_manifest_sha256": digest, + "scope": "raw_only", + "status": "acquired", + "total_raw_evidence_bytes": 12_345, + } + + +def test_acquire_m8_failure_is_reported_with_error_exit_code( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + monkeypatch.setattr(cli_module, "load_m8_config", lambda path: _mock_m8_config()) + + def fail_acquisition(config: object, root: Path) -> object: + raise RuntimeError("archive authentication failed") + + monkeypatch.setattr(cli_module, "acquire_m8_archives", fail_acquisition) + + exit_code = main( + [ + "acquire-m8", + "--config", + str(tmp_path / "study.toml"), + "--output-root", + str(tmp_path / "data"), + ] + ) + + assert exit_code == 2 + assert capsys.readouterr().err == "error: archive authentication failed\n" + + +def test_acquire_m8_deterministic_failure_prints_json_and_exits_one( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + output_root = tmp_path / "data" + attempt_dir = output_root / "_attempts" / f"m8-acquisition-attempt-{'a' * 20}" + result = M8AcquisitionFailureResult( + output_root=output_root, + attempt_dir=attempt_dir, + attempt_manifest_path=attempt_dir / "failure.json", + attempt_manifest_sha256="a" * 64, + checksums_path=attempt_dir / "checksums.sha256", + checksums_sha256="b" * 64, + terminal_path=attempt_dir / "INSUFFICIENT_DATA", + reason_code="DECLARED_OBJECT_UNAVAILABLE", + diagnostic="BinanceArchiveHTTPError: HTTP 404", + failed_symbol="BTCUSDT", + failed_date=date(2024, 1, 3), + failed_role="train", + completed_count=2, + remaining_count=7, + retained_inventory_sha256="c" * 64, + retained_artifact_count=6, + total_raw_evidence_bytes=1_234, + manifest=None, # type: ignore[arg-type] + ) + monkeypatch.setattr(cli_module, "load_m8_config", lambda path: _mock_m8_config()) + monkeypatch.setattr(cli_module, "acquire_m8_archives", lambda config, root: result) + + exit_code = main( + [ + "acquire-m8", + "--config", + str(tmp_path / "study.toml"), + "--output-root", + str(output_root), + ] + ) + + assert exit_code == 1 + payload = json.loads(capsys.readouterr().out) + assert payload["status"] == "INSUFFICIENT_DATA" + assert payload["reason_code"] == "DECLARED_OBJECT_UNAVAILABLE" + assert payload["failed_symbol"] == "BTCUSDT" + assert payload["failed_date"] == "2024-01-03" + assert payload["failure_manifest_sha256"] == "a" * 64 + assert payload["retained_inventory_sha256"] == "c" * 64 + assert payload["csv_members_opened"] is False + + +def test_reproduce_m8_propagates_explicit_manifest_coordinates_exactly( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + config_path = tmp_path / "study.toml" + run_dir = tmp_path / "run" + manifest_path = tmp_path / "data" / "_manifests" / "input.json" + digest = "0123456789abcdef" * 4 + config = _mock_m8_config() + calls: list[tuple[object, Path, Path, str]] = [] + + def fake_reproduce( + loaded: object, + destination: Path, + *, + raw_manifest_path: Path, + raw_manifest_sha256: str, + ) -> SimpleNamespace: + calls.append((loaded, destination, raw_manifest_path, raw_manifest_sha256)) + return SimpleNamespace( + path=run_dir, + status="COMPLETE", + raw_manifest_sha256=raw_manifest_sha256, + normalized_manifest_sha256="f" * 64, + ) + + bundle = SimpleNamespace( + run_id="m8-unit", + evidence_tier="FULL_DATA", + observed_start_utc="2024-01-03T00:00:00Z", + observed_end_utc="2024-01-06T23:59:59Z", + ) + monkeypatch.setattr(cli_module, "load_m8_config", lambda path: config) + monkeypatch.setattr(cli_module, "reproduce_m8", fake_reproduce) + monkeypatch.setattr(cli_module, "load_run_bundle", lambda path: bundle) + + exit_code = main( + [ + "reproduce-m8", + "--config", + str(config_path), + "--run-dir", + str(run_dir), + "--raw-manifest", + str(manifest_path), + "--raw-manifest-sha256", + digest, + ] + ) + + assert exit_code == 0 + assert calls == [(config, run_dir, manifest_path, digest)] + assert json.loads(capsys.readouterr().out) == { + "evidence_tier": "FULL_DATA", + "observed_end_utc": "2024-01-06T23:59:59Z", + "observed_start_utc": "2024-01-03T00:00:00Z", + "normalized_manifest_sha256": "f" * 64, + "raw_manifest_sha256": digest, + "run_dir": str(run_dir), + "run_id": "m8-unit", + "status": "COMPLETE", + } + + +def test_reproduce_m8_producer_failure_uses_error_exit_code( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + monkeypatch.setattr(cli_module, "load_m8_config", lambda path: _mock_m8_config()) + + def fail_producer(*args: object, **kwargs: object) -> Path: + raise RuntimeError("locked production failed") + + monkeypatch.setattr(cli_module, "reproduce_m8", fail_producer) + exit_code = main( + [ + "reproduce-m8", + "--config", + str(tmp_path / "study.toml"), + "--run-dir", + str(tmp_path / "run"), + "--raw-manifest", + str(tmp_path / "input.json"), + "--raw-manifest-sha256", + "c" * 64, + ] + ) + + assert exit_code == 2 + assert capsys.readouterr().err == "error: locked production failed\n" + + +def test_reproduce_m8_preserves_verified_insufficient_data_status( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + digest = "d" * 64 + run_dir = tmp_path / "run" + monkeypatch.setattr(cli_module, "load_m8_config", lambda path: _mock_m8_config()) + monkeypatch.setattr( + cli_module, + "reproduce_m8", + lambda *args, **kwargs: SimpleNamespace( + path=run_dir, + status="INSUFFICIENT_DATA", + raw_manifest_sha256=digest, + normalized_manifest_sha256=None, + ), + ) + monkeypatch.setattr( + cli_module, + "load_run_bundle", + lambda path: pytest.fail("an insufficient-data result is not a complete run bundle"), + ) + + exit_code = main( + [ + "reproduce-m8", + "--config", + str(tmp_path / "study.toml"), + "--run-dir", + str(run_dir), + "--raw-manifest", + str(tmp_path / "raw.json"), + "--raw-manifest-sha256", + digest, + ] + ) + + assert exit_code == 1 + assert json.loads(capsys.readouterr().out) == { + "normalized_manifest_sha256": None, + "raw_manifest_sha256": digest, + "run_dir": str(run_dir), + "status": "INSUFFICIENT_DATA", + } + + +def test_verify_m8_accepts_complete_or_insufficient_terminal_evidence( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + digest = "e" * 64 + run_dir = tmp_path / "run" + raw_manifest = tmp_path / "raw.json" + config = _mock_m8_config() + calls: list[tuple[object, Path, Path, str]] = [] + + def fake_verify( + path: Path, + observed_config: object, + *, + raw_manifest_path: Path, + raw_manifest_sha256: str, + ) -> SimpleNamespace: + calls.append((observed_config, path, raw_manifest_path, raw_manifest_sha256)) + return SimpleNamespace( + path=run_dir, + status="INSUFFICIENT_DATA", + raw_manifest_sha256=digest, + normalized_manifest_sha256=None, + ) + + monkeypatch.setattr(cli_module, "load_m8_config", lambda path: config) + monkeypatch.setattr(cli_module, "verify_m8_result", fake_verify) + monkeypatch.setattr(cli_module, "verify_checksums", lambda path: 17) + + assert ( + main( + [ + "verify-m8", + "--config", + str(tmp_path / "study.toml"), + "--run-dir", + str(run_dir), + "--raw-manifest", + str(raw_manifest), + "--raw-manifest-sha256", + digest, + ] + ) + == 0 + ) + assert calls == [(config, run_dir, raw_manifest, digest)] + assert json.loads(capsys.readouterr().out)["protected_files"] == 17 + + +def test_report_m8_writes_self_contained_insufficient_report_outside_frozen_bundle( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + digest = "9" * 64 + run_dir = tmp_path / "run" + output_dir = tmp_path / "external-report" + run_dir.mkdir() + failure = { + "failed_symbol": "ETHUSDT", + "failed_date": "2024-01-04", + "failed_role": "validation", + "failure_stage": "development_normalization", + "reason_code": "ARCHIVE_QUALITY_GATE", + "reason": "53 temporal.long_silence warnings violated the frozen gate", + "replacement_date_selected": False, + "reselection_performed": False, + "config_sha256": "a" * 64, + "config_source_sha256": "b" * 64, + "raw_acquisition_manifest_sha256": digest, + "bundled_raw_acquisition_manifest_sha256": "c" * 64, + "protocol_sha256": "d" * 64, + "selection_started": False, + "selection_completed_symbols": [], + "aggregate_lock_committed": False, + "held_out_member_opened": False, + "endpoint_evaluation_started": False, + "endpoint_evaluation_completed": False, + "endpoint_evaluation_completed_symbols": [], + "predictions_published": False, + "endpoint_artifacts_published": False, + "completed_normalizations": [{"symbol": "BTCUSDT", "date": "2024-01-03", "role": "train"}], + "stopped_before": [ + {"symbol": "BTCUSDT", "date": "2024-01-05", "role": "primary_test"}, + {"symbol": "BTCUSDT", "date": "2024-01-06", "role": "replication_test"}, + ], + } + provenance = { + "git": { + "commit": "e" * 40, + "dirty": False, + "source_tree_sha256": "f" * 64, + } + } + run_manifest = { + "research": {"endpoint_status": "insufficient_data"}, + "execution_assumptions": { + "status": "NOT_RUN", + "fills_calculated": False, + "pnl_calculated": False, + "capacity_calculated": False, + }, + } + for name, payload in ( + ("failure.json", failure), + ("provenance.json", provenance), + ("run_manifest.json", run_manifest), + ): + (run_dir / name).write_text(json.dumps(payload), encoding="utf-8") + bundled_before = {path.name: path.read_bytes() for path in run_dir.iterdir() if path.is_file()} + monkeypatch.setattr(cli_module, "load_m8_config", lambda path: _mock_m8_config()) + verification_calls: list[tuple[tuple[object, ...], dict[str, object]]] = [] + + def fake_verify(*args: object, **kwargs: object) -> object: + verification_calls.append((args, kwargs)) + return SimpleNamespace( + path=run_dir, + status="INSUFFICIENT_DATA", + raw_manifest_sha256=digest, + normalized_manifest_sha256=None, + ) + + monkeypatch.setattr(cli_module, "verify_m8_result", fake_verify) + monkeypatch.setattr( + cli_module, + "write_report_set", + lambda *args, **kwargs: pytest.fail("terminal failure report must not be rewritten"), + ) + + assert ( + main( + [ + "report-m8", + "--config", + str(tmp_path / "study.toml"), + "--run-dir", + str(run_dir), + "--raw-manifest", + str(tmp_path / "raw.json"), + "--raw-manifest-sha256", + digest, + "--output-dir", + str(output_dir), + ] + ) + == 0 + ) + payload = json.loads(capsys.readouterr().out) + report = output_dir / "insufficient_data.md" + assert payload["report"] == str(report) + assert payload["reports_regenerated"] is True + assert payload["source_bundle_modified"] is False + assert payload["report_sha256"] == sha256_file(report) + rendered = report.read_text(encoding="utf-8") + for expected in ( + "2024-01-03` through `2024-01-06", + "ETHUSDT", + "2024-01-04", + "validation", + "ARCHIVE_QUALITY_GATE", + "53 temporal.long_silence warnings", + "Config semantic SHA-256", + "Raw acquisition manifest SHA-256", + "Git commit", + "Git dirty: `false`", + "Source-tree SHA-256", + "Candidate selection started: `false`", + "Held-out member opened: `false`", + "Endpoint evaluation started: `false`", + "Execution status: `NOT_RUN`", + ): + assert expected in rendered + assert { + path.name: path.read_bytes() for path in run_dir.iterdir() if path.is_file() + } == bundled_before + assert len(verification_calls) == 2 + assert verification_calls[0] == verification_calls[1] + + +def test_report_m8_rejects_output_inside_immutable_bundle( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + digest = "8" * 64 + run_dir = tmp_path / "run" + monkeypatch.setattr(cli_module, "load_m8_config", lambda path: _mock_m8_config()) + monkeypatch.setattr( + cli_module, + "verify_m8_result", + lambda *args, **kwargs: SimpleNamespace( + path=run_dir, + status="INSUFFICIENT_DATA", + raw_manifest_sha256=digest, + normalized_manifest_sha256=None, + ), + ) + + exit_code = main( + [ + "report-m8", + "--config", + str(tmp_path / "study.toml"), + "--run-dir", + str(run_dir), + "--raw-manifest", + str(tmp_path / "raw.json"), + "--raw-manifest-sha256", + digest, + "--output-dir", + str(run_dir / "reports"), + ] + ) + + assert exit_code == 2 + assert "outside the immutable run bundle" in capsys.readouterr().err + + +@pytest.mark.parametrize( + "manifest_args", + [ + [], + ["--raw-manifest", "input.json"], + ["--raw-manifest-sha256", "a" * 64], + ["--raw-manifest", "input.json", "--raw-manifest-sha256", "A" * 64], + ["--raw-manifest", "input.json", "--raw-manifest-sha256", "a" * 63], + ["--raw-manifest", "input.json", "--raw-manifest-sha256", "g" * 64], + ], +) +def test_reproduce_m8_rejects_missing_or_noncanonical_manifest_coordinates( + manifest_args: list[str], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr( + cli_module, + "reproduce_m8", + lambda *args, **kwargs: pytest.fail("producer must not run after argument failure"), + ) + + with pytest.raises(SystemExit) as caught: + main( + [ + "reproduce-m8", + "--config", + str(tmp_path / "study.toml"), + "--run-dir", + str(tmp_path / "run"), + *manifest_args, + ] + ) + + assert caught.value.code == 2 + + +def test_m8_make_targets_keep_reproduction_explicit_and_checks_offline() -> None: + makefile = (PROJECT_ROOT / "Makefile").read_text(encoding="utf-8") + + reproduce_recipe = makefile.split("reproduce-m8:\n", maxsplit=1)[1].split( + "\nverify-run:", maxsplit=1 + )[0] + assert 'test -n "$(M8_RAW_MANIFEST)"' in reproduce_recipe + assert 'test -n "$(M8_RAW_MANIFEST_SHA256)"' in reproduce_recipe + assert '--raw-manifest "$(M8_RAW_MANIFEST)"' in reproduce_recipe + assert '--raw-manifest-sha256 "$(M8_RAW_MANIFEST_SHA256)"' in reproduce_recipe + assert "latest" not in reproduce_recipe.lower() + for target, following in (("verify-m8-run", "report:"), ("report-m8", "dashboard:")): + recipe = makefile.split(f"{target}:\n", maxsplit=1)[1].split(f"\n{following}", maxsplit=1)[ + 0 + ] + assert 'test -n "$(M8_RAW_MANIFEST)"' in recipe + assert 'test -n "$(M8_RAW_MANIFEST_SHA256)"' in recipe + assert '--raw-manifest "$(M8_RAW_MANIFEST)"' in recipe + assert '--raw-manifest-sha256 "$(M8_RAW_MANIFEST_SHA256)"' in recipe + check_dependencies = makefile.split("\ncheck:", maxsplit=1)[1].splitlines()[0] + assert "download-m8" not in check_dependencies + + +@pytest.mark.parametrize(("status", "expected_exit"), [("COMPLETE", 0), ("INSUFFICIENT_DATA", 1)]) +def test_capture_m8_l2_session_command_uses_frozen_runner_without_source_override( + status: str, + expected_exit: int, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + config_path = tmp_path / "m8-l2.toml" + output_root = tmp_path / "l2" + config = object() + adapter = object() + target = output_root / "sessions" / "authority" + bundle = SimpleNamespace( + root=target, + status=status, + session_id="a" * 64, + session_date="2026-08-10", + role="train", + manifest_path=target / "session_manifest.json", + manifest_sha256="b" * 64, + checksum_path=target / "CHECKSUMS.sha256", + marker_path=target / ("_SUCCESS" if status == "COMPLETE" else "INSUFFICIENT_DATA"), + reason_codes=() if status == "COMPLETE" else ("GATE_VALID_CONTINUITY_EPOCH_BTCUSDT",), + ) + calls: list[tuple[object, str, Path, object]] = [] + + async def fake_capture( + loaded: object, + session_date: str, + root: Path, + capture_one: object, + **kwargs: object, + ) -> object: + assert kwargs == {} + calls.append((loaded, session_date, root, capture_one)) + return bundle + + monkeypatch.setattr(cli_module, "load_m8_l2_config", lambda path: config) + monkeypatch.setattr(cli_module, "BinanceM8L2Capture", lambda: adapter) + monkeypatch.setattr(cli_module, "capture_m8_l2_session", fake_capture) + + exit_code = main( + [ + "capture-m8-l2-session", + "--config", + str(config_path), + "--date", + "2026-08-10", + "--output-root", + str(output_root), + ] + ) + + assert exit_code == expected_exit + assert calls == [(config, "2026-08-10", output_root.resolve(), adapter)] + payload = json.loads(capsys.readouterr().out) + assert payload["status"] == status + assert payload["session_date"] == "2026-08-10" + assert payload["session_manifest_sha256"] == "b" * 64 + assert payload["live_trading"] is False + + +def test_capture_m8_l2_session_system_failure_uses_error_exit_two( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + monkeypatch.setattr(cli_module, "load_m8_l2_config", lambda path: object()) + + async def fail(*args: object, **kwargs: object) -> object: + raise OSError("injected capture I/O failure") + + monkeypatch.setattr(cli_module, "capture_m8_l2_session", fail) + + exit_code = main( + [ + "capture-m8-l2-session", + "--config", + str(tmp_path / "m8-l2.toml"), + "--date", + "2026-08-10", + "--output-root", + str(tmp_path / "l2"), + ] + ) + + assert exit_code == 2 + assert capsys.readouterr().err == "error: injected capture I/O failure\n" + + +@pytest.mark.parametrize("status", ["COMPLETE", "INSUFFICIENT_DATA"]) +def test_verify_m8_l2_session_accepts_both_terminal_states( + status: str, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + config_path = tmp_path / "m8-l2.toml" + bundle_dir = tmp_path / "sessions" / ("a" * 64) + config = object() + result = SimpleNamespace( + root=bundle_dir.absolute(), + status=status, + session_id="a" * 64, + session_date="2026-08-10", + role="train", + manifest_path=bundle_dir / "session_manifest.json", + manifest_sha256="b" * 64, + checksum_path=bundle_dir / "CHECKSUMS.sha256", + marker_path=bundle_dir / ("_SUCCESS" if status == "COMPLETE" else "INSUFFICIENT_DATA"), + reason_codes=() if status == "COMPLETE" else ("GATE_CROSS_SYMBOL_OVERLAP",), + ) + calls: list[tuple[Path, object]] = [] + + def fake_verify(path: Path, *, expected_config: object) -> object: + calls.append((path, expected_config)) + return result + + monkeypatch.setattr(cli_module, "load_m8_l2_config", lambda path: config) + monkeypatch.setattr(cli_module, "verify_m8_l2_session_bundle", fake_verify) + + exit_code = main( + [ + "verify-m8-l2-session", + "--config", + str(config_path), + "--bundle-dir", + str(bundle_dir), + ] + ) + + assert exit_code == 0 + assert calls == [(bundle_dir, config)] + payload = json.loads(capsys.readouterr().out) + assert payload["status"] == status + assert payload["integrity"] == "verified" + assert payload["session_id"] == "a" * 64 + assert payload["reason_codes"] == list(result.reason_codes) + assert payload["live_trading"] is False + + +@pytest.mark.parametrize( + "message", + [ + "checksum mismatch for symbols/BTCUSDT/capture_summary.json", + "caller config semantics differ from the session authority", + ], +) +def test_verify_m8_l2_session_rejects_tampering_and_wrong_config( + message: str, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + config = object() + bundle_dir = tmp_path / "sessions" / ("a" * 64) + monkeypatch.setattr(cli_module, "load_m8_l2_config", lambda path: config) + + def fail(path: Path, *, expected_config: object) -> object: + assert path == bundle_dir + assert expected_config is config + raise M8L2VerificationError(message) + + monkeypatch.setattr(cli_module, "verify_m8_l2_session_bundle", fail) + + exit_code = main( + [ + "verify-m8-l2-session", + "--config", + str(tmp_path / "m8-l2.toml"), + "--bundle-dir", + str(bundle_dir), + ] + ) + + assert exit_code == 2 + captured = capsys.readouterr() + assert captured.out == "" + assert captured.err == f"error: {message}\n" + + +def test_m8_l2_make_target_is_explicit_and_check_remains_offline() -> None: + makefile = (PROJECT_ROOT / "Makefile").read_text(encoding="utf-8") + + assert "M8_L2_CONFIG ?= configs/m8_l2_capture_study.toml" in makefile + assert "M8_L2_DATA_ROOT ?= data/m8_l2" in makefile + assert "M8_L2_SESSION_DATE ?=" in makefile + assert "M8_L2_BUNDLE_DIR ?=" in makefile + capture_recipe = makefile.split("capture-m8-l2-session:\n", maxsplit=1)[1].split( + "\nverify-m8-l2-session:", maxsplit=1 + )[0] + assert 'test -n "$(M8_L2_SESSION_DATE)"' in capture_recipe + assert '--config "$(M8_L2_CONFIG)"' in capture_recipe + assert '--date "$(M8_L2_SESSION_DATE)"' in capture_recipe + assert '--output-root "$(M8_L2_DATA_ROOT)"' in capture_recipe + verify_recipe = makefile.split("verify-m8-l2-session:\n", maxsplit=1)[1].split( + "\nvalidate-data:", maxsplit=1 + )[0] + assert 'test -n "$(M8_L2_BUNDLE_DIR)"' in verify_recipe + assert '--config "$(M8_L2_CONFIG)"' in verify_recipe + assert '--bundle-dir "$(M8_L2_BUNDLE_DIR)"' in verify_recipe + check_dependencies = makefile.split("\ncheck:", maxsplit=1)[1].splitlines()[0] + assert "capture-m8-l2-session" not in check_dependencies + assert "verify-m8-l2-session" not in check_dependencies + + +def test_m8_l2_make_contract_normalizes_only_valid_terminal_exit_one( + tmp_path: Path, +) -> None: + fake_python = tmp_path / "fake-python" + fake_python.write_text( + '#!/bin/sh\nprintf \'{"status":"INSUFFICIENT_DATA"}\\n\'\nexit "$FAKE_EXIT"\n', + encoding="ascii", + ) + fake_python.chmod(0o755) + base_environment = {**os.environ, "FAKE_EXIT": "1"} + command = [ + "make", + "--no-print-directory", + "capture-m8-l2-session", + f"PYTHON={fake_python}", + "M8_L2_SESSION_DATE=2026-08-10", + ] + + valid_terminal = subprocess.run( + command, + cwd=PROJECT_ROOT, + env=base_environment, + check=False, + capture_output=True, + text=True, + ) + assert valid_terminal.returncode == 0 + assert json.loads(valid_terminal.stdout)["status"] == "INSUFFICIENT_DATA" + + system_failure = subprocess.run( + command, + cwd=PROJECT_ROOT, + env={**base_environment, "FAKE_EXIT": "2"}, + check=False, + capture_output=True, + text=True, + ) + assert system_failure.returncode != 0 + + makefile = (PROJECT_ROOT / "Makefile").read_text(encoding="utf-8") + for command_name in ( + "capture-m8-l2-session", + "lock-m8-l2-development", + "verify-m8-l2-development-lock", + "reproduce-m8-l2", + "verify-m8-l2-run", + "report-m8-l2", + ): + recipe_line = next( + line for line in makefile.splitlines() if f"microstructure.cli {command_name} " in line + ) + assert "|| status=$$?" in recipe_line + assert 'if [ "$$status" -eq 1 ]; then exit 0; fi' in recipe_line + assert 'exit "$$status"' in recipe_line + + +def _m8_l2_development_cli_fixture( + tmp_path: Path, + *, + train_status: str = "COMPLETE", + validation_status: str = "COMPLETE", +) -> tuple[list[str], SimpleNamespace, SimpleNamespace]: + train_root = tmp_path / "train" + validation_root = tmp_path / "validation" + train_root.mkdir() + validation_root.mkdir() + train_checksums = train_root / "CHECKSUMS.sha256" + validation_checksums = validation_root / "CHECKSUMS.sha256" + train_checksums.write_bytes(b"train checksums authority\n") + validation_checksums.write_bytes(b"validation checksums authority\n") + train = SimpleNamespace( + root=train_root.absolute(), + status=train_status, + session_id="1" * 64, + session_date="2026-08-10", + role="train", + manifest_path=train_root / "session_manifest.json", + manifest_sha256="a" * 64, + checksum_path=train_checksums, + marker_path=train_root + / ("_SUCCESS" if train_status == "COMPLETE" else "INSUFFICIENT_DATA"), + reason_codes=() if train_status == "COMPLETE" else ("GATE_TRAIN",), + ) + validation = SimpleNamespace( + root=validation_root.absolute(), + status=validation_status, + session_id="2" * 64, + session_date="2026-08-11", + role="validation", + manifest_path=validation_root / "session_manifest.json", + manifest_sha256="b" * 64, + checksum_path=validation_checksums, + marker_path=( + validation_root + / ("_SUCCESS" if validation_status == "COMPLETE" else "INSUFFICIENT_DATA") + ), + reason_codes=() if validation_status == "COMPLETE" else ("GATE_VALIDATION",), + ) + arguments = [ + "--capture-config", + str(tmp_path / "capture.toml"), + "--analysis-config", + str(tmp_path / "analysis.toml"), + "--train-bundle-dir", + str(train_root), + "--train-manifest-sha256", + train.manifest_sha256, + "--train-checksums-sha256", + sha256_file(train_checksums), + "--validation-bundle-dir", + str(validation_root), + "--validation-manifest-sha256", + validation.manifest_sha256, + "--validation-checksums-sha256", + sha256_file(validation_checksums), + "--lock-dir", + str(tmp_path / "development-lock"), + ] + return arguments, train, validation + + +def test_lock_m8_l2_development_uses_only_explicit_session_authorities( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + arguments, train, validation = _m8_l2_development_cli_fixture(tmp_path) + capture_config = object() + analysis_config = object() + strict_input = object() + calls: list[tuple[object, ...]] = [] + + monkeypatch.setattr(cli_module, "load_m8_l2_config", lambda path: capture_config) + monkeypatch.setattr(cli_module, "load_m8_l2_analysis_config", lambda path: analysis_config) + + def fake_verify(path: Path, *, expected_config: object) -> object: + assert expected_config is capture_config + return train if path == train.root else validation + + def fake_strict_input( + path: Path, + *, + expected_config: object, + expected_date: str, + expected_role: str, + expected_file_authority: object, + expected_campaign: object | None, + ) -> object: + calls.append( + ( + path, + expected_config, + expected_date, + expected_role, + expected_file_authority, + expected_campaign, + ) + ) + return strict_input + + def fake_lock( + capture: object, + analysis: object, + train_path: Path, + validation_path: Path, + lock_path: Path, + *, + input_loader: object, + expected_session_file_authorities: object, + ) -> object: + assert capture is capture_config + assert analysis is analysis_config + assert (train_path, validation_path) == (train.root, validation.root) + assert callable(input_loader) + assert expected_session_file_authorities == { + "2026-08-10": cli_module.L2SessionFileAuthority( + train.manifest_sha256, + hashlib.sha256(train.checksum_path.read_bytes()).hexdigest(), + ), + "2026-08-11": cli_module.L2SessionFileAuthority( + validation.manifest_sha256, + hashlib.sha256(validation.checksum_path.read_bytes()).hexdigest(), + ), + } + assert ( + input_loader( + train_path, + expected_config=capture_config, + expected_date="2026-08-10", + expected_role="train", + ) + is strict_input + ) + return SimpleNamespace( + root=lock_path, + aggregate_path=lock_path / "development_lock.json", + aggregate_sha256="d" * 64, + marker_path=lock_path / "_LOCKED", + created_at_utc="2026-08-11T15:00:00Z", + children=( + SimpleNamespace( + symbol="BTCUSDT", + endpoint="event_20", + path=lock_path / "BTCUSDT" / "event_20" / "lock.json", + sha256="e" * 64, + selection_lock_sha256="f" * 64, + fitted_state_sha256="0" * 64, + ), + ), + ) + + monkeypatch.setattr(cli_module, "verify_m8_l2_session_bundle", fake_verify) + monkeypatch.setattr(cli_module, "verify_m8_l2_development_input", fake_strict_input) + monkeypatch.setattr(cli_module, "lock_m8_l2_development", fake_lock) + + assert main(["lock-m8-l2-development", *arguments]) == 0 + payload = json.loads(capsys.readouterr().out) + assert payload["status"] == "LOCKED" + assert payload["development_lock_sha256"] == "d" * 64 + assert payload["heldout_accessed"] is False + assert payload["live_trading"] is False + assert calls[0][4].manifest_sha256 == "a" * 64 + assert calls[0][4].checksums_sha256 == sha256_file(train.checksum_path) + + +def test_lock_m8_l2_development_returns_one_for_verified_insufficient_session( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + arguments, train, validation = _m8_l2_development_cli_fixture( + tmp_path, + validation_status="INSUFFICIENT_DATA", + ) + monkeypatch.setattr(cli_module, "load_m8_l2_config", lambda path: object()) + monkeypatch.setattr(cli_module, "load_m8_l2_analysis_config", lambda path: object()) + monkeypatch.setattr( + cli_module, + "verify_m8_l2_session_bundle", + lambda path, **kwargs: train if path == train.root else validation, + ) + lock_dir = Path(arguments[arguments.index("--lock-dir") + 1]).absolute() + monkeypatch.setattr( + cli_module, + "lock_m8_l2_development", + lambda *args, **kwargs: SimpleNamespace( + root=lock_dir, + aggregate_path=lock_dir / "development_lock.json", + aggregate_sha256="d" * 64, + marker_path=lock_dir / "_NOT_CREATED", + created_at_utc="2026-08-11T15:00:00Z", + children=(), + status="NOT_CREATED", + reason_codes=("DEVELOPMENT_SESSION_INSUFFICIENT::validation::GATE_VALIDATION",), + ), + ) + + assert main(["lock-m8-l2-development", *arguments]) == 1 + payload = json.loads(capsys.readouterr().out) + assert payload["status"] == "NOT_CREATED" + assert payload["development_lock_sha256"] == "d" * 64 + assert payload["reason_codes"] == [ + "DEVELOPMENT_SESSION_INSUFFICIENT::validation::GATE_VALIDATION" + ] + assert payload["heldout_accessed"] is False + + +def test_verify_m8_l2_development_lock_binds_expected_aggregate_sha( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + arguments, train, validation = _m8_l2_development_cli_fixture(tmp_path) + capture_config = object() + analysis_config = object() + expected_lock_sha = "c" * 64 + lock_dir = (tmp_path / "development-lock").absolute() + + monkeypatch.setattr(cli_module, "load_m8_l2_config", lambda path: capture_config) + monkeypatch.setattr(cli_module, "load_m8_l2_analysis_config", lambda path: analysis_config) + monkeypatch.setattr( + cli_module, + "verify_m8_l2_session_bundle", + lambda path, **kwargs: train if path == train.root else validation, + ) + + def fake_verify_lock(*args: object, **kwargs: object) -> object: + assert args == (capture_config, analysis_config, train.root, validation.root, lock_dir) + assert kwargs == {"expected_lock_sha256": expected_lock_sha} + return SimpleNamespace( + root=lock_dir, + aggregate_path=lock_dir / "development_lock.json", + aggregate_sha256=expected_lock_sha, + marker_path=lock_dir / "_LOCKED", + created_at_utc="2026-08-11T15:00:00Z", + children=(), + ) + + monkeypatch.setattr(cli_module, "verify_m8_l2_development_lock", fake_verify_lock) + + assert ( + main( + [ + "verify-m8-l2-development-lock", + *arguments, + "--development-lock-sha256", + expected_lock_sha, + ] + ) + == 0 + ) + payload = json.loads(capsys.readouterr().out) + assert payload["integrity"] == "verified" + assert payload["development_lock_sha256"] == expected_lock_sha + + +def test_verify_m8_l2_not_created_authority_returns_one_with_verified_integrity( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + arguments, train, validation = _m8_l2_development_cli_fixture( + tmp_path, + validation_status="INSUFFICIENT_DATA", + ) + expected_sha = "c" * 64 + lock_dir = Path(arguments[arguments.index("--lock-dir") + 1]).absolute() + monkeypatch.setattr(cli_module, "load_m8_l2_config", lambda path: object()) + monkeypatch.setattr(cli_module, "load_m8_l2_analysis_config", lambda path: object()) + monkeypatch.setattr( + cli_module, + "verify_m8_l2_session_bundle", + lambda path, **kwargs: train if path == train.root else validation, + ) + monkeypatch.setattr( + cli_module, + "verify_m8_l2_development_lock", + lambda *args, **kwargs: SimpleNamespace( + root=lock_dir, + aggregate_path=lock_dir / "development_lock.json", + aggregate_sha256=expected_sha, + marker_path=lock_dir / "_NOT_CREATED", + created_at_utc="2026-08-11T15:00:00Z", + children=(), + status="NOT_CREATED", + reason_codes=("DEVELOPMENT_SESSION_INSUFFICIENT::validation::GATE_VALIDATION",), + ), + ) + + assert ( + main( + [ + "verify-m8-l2-development-lock", + *arguments, + "--development-lock-sha256", + expected_sha, + ] + ) + == 1 + ) + payload = json.loads(capsys.readouterr().out) + assert payload["status"] == "NOT_CREATED" + assert payload["integrity"] == "verified" + assert payload["terminal_marker"].endswith("/_NOT_CREATED") + + +def test_m8_l2_development_cli_rejects_noncanonical_authority_sha( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + arguments, _, _ = _m8_l2_development_cli_fixture(tmp_path) + digest_index = arguments.index("--train-manifest-sha256") + 1 + arguments[digest_index] = "A" * 64 + monkeypatch.setattr( + cli_module, + "lock_m8_l2_development", + lambda *args, **kwargs: pytest.fail("argument failure must precede lock production"), + ) + + with pytest.raises(SystemExit) as caught: + main(["lock-m8-l2-development", *arguments]) + + assert caught.value.code == 2 + + +def test_m8_l2_development_make_targets_are_explicit_and_not_in_check() -> None: + makefile = (PROJECT_ROOT / "Makefile").read_text(encoding="utf-8") + gitignore_lines = (PROJECT_ROOT / ".gitignore").read_text(encoding="utf-8").splitlines() + assert "data/m8_l2/**" in gitignore_lines + lock_recipe = makefile.split("lock-m8-l2-development:\n", maxsplit=1)[1].split( + "\nverify-m8-l2-development-lock:", maxsplit=1 + )[0] + verify_recipe = makefile.split("verify-m8-l2-development-lock:\n", maxsplit=1)[1].split( + "\nvalidate-data:", maxsplit=1 + )[0] + for variable in ( + "M8_L2_TRAIN_BUNDLE_DIR", + "M8_L2_TRAIN_MANIFEST_SHA256", + "M8_L2_TRAIN_CHECKSUMS_SHA256", + "M8_L2_VALIDATION_BUNDLE_DIR", + "M8_L2_VALIDATION_MANIFEST_SHA256", + "M8_L2_VALIDATION_CHECKSUMS_SHA256", + "M8_L2_DEVELOPMENT_LOCK_DIR", + ): + assert f'test -n "$({variable})"' in lock_recipe + assert f'"$({variable})"' in lock_recipe + assert f'test -n "$({variable})"' in verify_recipe + assert f'"$({variable})"' in verify_recipe + assert 'test -n "$(M8_L2_DEVELOPMENT_LOCK_SHA256)"' in verify_recipe + assert '--development-lock-sha256 "$(M8_L2_DEVELOPMENT_LOCK_SHA256)"' in verify_recipe + for recipe in (lock_recipe, verify_recipe): + assert "latest" not in recipe.lower() + check_dependencies = makefile.split("\ncheck:", maxsplit=1)[1].splitlines()[0] + assert "lock-m8-l2-development" not in check_dependencies + assert "verify-m8-l2-development-lock" not in check_dependencies + + +def test_m8_l2_final_make_targets_bind_four_sessions_and_stay_offline() -> None: + makefile = (PROJECT_ROOT / "Makefile").read_text(encoding="utf-8") + assert "M8_L2_RUN_DIR ?= artifacts/runs/binance-m8-live-l2" in makefile + assert "M8_L2_REPORT_DIR ?= artifacts/runs/binance-m8-live-l2-reports" in makefile + reproduce_recipe = makefile.split("reproduce-m8-l2:\n", maxsplit=1)[1].split( + "\nverify-m8-l2-run:", maxsplit=1 + )[0] + verify_recipe = makefile.split("verify-m8-l2-run:\n", maxsplit=1)[1].split( + "\nreport-m8-l2:", maxsplit=1 + )[0] + report_recipe = makefile.split("report-m8-l2:\n", maxsplit=1)[1].split( + "\nvalidate-data:", maxsplit=1 + )[0] + authority_variables = ( + "M8_L2_TRAIN_BUNDLE_DIR", + "M8_L2_TRAIN_MANIFEST_SHA256", + "M8_L2_TRAIN_CHECKSUMS_SHA256", + "M8_L2_VALIDATION_BUNDLE_DIR", + "M8_L2_VALIDATION_MANIFEST_SHA256", + "M8_L2_VALIDATION_CHECKSUMS_SHA256", + "M8_L2_DEVELOPMENT_LOCK_DIR", + "M8_L2_DEVELOPMENT_LOCK_SHA256", + "M8_L2_PRIMARY_BUNDLE_DIR", + "M8_L2_PRIMARY_MANIFEST_SHA256", + "M8_L2_PRIMARY_CHECKSUMS_SHA256", + "M8_L2_REPLICATION_BUNDLE_DIR", + "M8_L2_REPLICATION_MANIFEST_SHA256", + "M8_L2_REPLICATION_CHECKSUMS_SHA256", + ) + for recipe in (reproduce_recipe, verify_recipe, report_recipe): + for variable in authority_variables: + assert f'test -n "$({variable})"' in recipe + assert f'"$({variable})"' in recipe + for role in ("train", "validation", "primary", "replication"): + assert f"--{role}-bundle-dir" in recipe + assert f"--{role}-manifest-sha256" in recipe + assert f"--{role}-checksums-sha256" in recipe + assert "--development-lock-dir" in recipe + assert "--development-lock-sha256" in recipe + assert ' --run-dir "$(M8_L2_RUN_DIR)"' in recipe + assert "latest" not in recipe.lower() + for recipe in (verify_recipe, report_recipe): + assert 'test -n "$(M8_L2_RUN_MANIFEST_SHA256)"' in recipe + assert 'test -n "$(M8_L2_RUN_CHECKSUMS_SHA256)"' in recipe + assert '--run-manifest-sha256 "$(M8_L2_RUN_MANIFEST_SHA256)"' in recipe + assert '--run-checksums-sha256 "$(M8_L2_RUN_CHECKSUMS_SHA256)"' in recipe + assert '--output-dir "$(M8_L2_REPORT_DIR)"' in report_recipe + check_dependencies = makefile.split("\ncheck:", maxsplit=1)[1].splitlines()[0] + for target in ("reproduce-m8-l2", "verify-m8-l2-run", "report-m8-l2"): + assert target not in check_dependencies + + +def _m8_l2_study_cli_arguments( + tmp_path: Path, + *, + include_run_authority: bool, +) -> list[str]: + arguments = [ + "--capture-config", + str(tmp_path / "capture.toml"), + "--analysis-config", + str(tmp_path / "analysis.toml"), + ] + for index, role in enumerate(("train", "validation", "primary", "replication"), start=1): + arguments.extend( + [ + f"--{role}-bundle-dir", + str(tmp_path / role), + f"--{role}-manifest-sha256", + format(index, "x") * 64, + f"--{role}-checksums-sha256", + format(index + 4, "x") * 64, + ] + ) + arguments.extend( + [ + "--development-lock-dir", + str(tmp_path / "development-lock"), + "--development-lock-sha256", + "9" * 64, + "--run-dir", + str(tmp_path / "run"), + ] + ) + if include_run_authority: + arguments.extend( + [ + "--run-manifest-sha256", + "a" * 64, + "--run-checksums-sha256", + "b" * 64, + ] + ) + return arguments + + +def _fake_m8_l2_study_result(tmp_path: Path, status: str) -> SimpleNamespace: + root = (tmp_path / "run").absolute() + return SimpleNamespace( + root=root, + status=status, + manifest_path=root / "run_manifest.json", + manifest_sha256="a" * 64, + checksum_path=root / "CHECKSUMS.sha256", + checksum_sha256="b" * 64, + marker_path=root / ("_SUCCESS" if status == "COMPLETE" else "INSUFFICIENT_DATA"), + reason_codes=() if status == "COMPLETE" else ("PRIMARY_SESSION_NOT_COMPLETE",), + ) + + +@pytest.mark.parametrize(("status", "expected_exit"), [("COMPLETE", 0), ("INSUFFICIENT_DATA", 1)]) +def test_reproduce_m8_l2_binds_all_four_explicit_session_authorities( + status: str, + expected_exit: int, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + capture_config = object() + analysis_config = object() + result = _fake_m8_l2_study_result(tmp_path, status) + calls: list[tuple[object, ...]] = [] + monkeypatch.setattr(cli_module, "load_m8_l2_config", lambda path: capture_config) + monkeypatch.setattr(cli_module, "load_m8_l2_analysis_config", lambda path: analysis_config) + + def fake_reproduce(*args: object) -> object: + calls.append(args) + return result + + monkeypatch.setattr(cli_module, "reproduce_m8_l2_study", fake_reproduce) + + assert ( + main( + [ + "reproduce-m8-l2", + *_m8_l2_study_cli_arguments(tmp_path, include_run_authority=False), + ] + ) + == expected_exit + ) + assert len(calls) == 1 + call = calls[0] + assert call[0:2] == (capture_config, analysis_config) + for index, (position, role) in enumerate( + zip((2, 3, 6, 7), ("train", "validation", "primary", "replication"), strict=True), + start=1, + ): + authority = call[position] + assert isinstance(authority, cli_module.L2StudySessionAuthority) + assert authority.bundle_path == (tmp_path / role).absolute() + assert authority.manifest_sha256 == format(index, "x") * 64 + assert authority.checksums_sha256 == format(index + 4, "x") * 64 + assert call[4] == (tmp_path / "development-lock").absolute() + assert call[5] == "9" * 64 + assert call[8] == (tmp_path / "run").absolute() + payload = json.loads(capsys.readouterr().out) + assert payload["status"] == status + assert payload["run_manifest_sha256"] == "a" * 64 + assert payload["checksums_sha256"] == "b" * 64 + assert payload["reason_codes"] == list(result.reason_codes) + assert payload["live_trading"] is False + + +@pytest.mark.parametrize(("status", "expected_exit"), [("COMPLETE", 0), ("INSUFFICIENT_DATA", 1)]) +def test_verify_m8_l2_run_requires_and_forwards_terminal_run_authority( + status: str, + expected_exit: int, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + capture_config = object() + analysis_config = object() + result = _fake_m8_l2_study_result(tmp_path, status) + calls: list[tuple[tuple[object, ...], dict[str, object]]] = [] + monkeypatch.setattr(cli_module, "load_m8_l2_config", lambda path: capture_config) + monkeypatch.setattr(cli_module, "load_m8_l2_analysis_config", lambda path: analysis_config) + + def fake_verify(*args: object, **kwargs: object) -> object: + calls.append((args, kwargs)) + return result + + monkeypatch.setattr(cli_module, "verify_m8_l2_study_run", fake_verify) + + assert ( + main( + [ + "verify-m8-l2-run", + *_m8_l2_study_cli_arguments(tmp_path, include_run_authority=True), + ] + ) + == expected_exit + ) + assert calls[0][1] == { + "expected_manifest_sha256": "a" * 64, + "expected_checksums_sha256": "b" * 64, + } + payload = json.loads(capsys.readouterr().out) + assert payload["integrity"] == "verified" + assert payload["status"] == status + + +@pytest.mark.parametrize(("status", "expected_exit"), [("COMPLETE", 0), ("INSUFFICIENT_DATA", 1)]) +def test_report_m8_l2_reverifies_then_writes_only_to_external_output( + status: str, + expected_exit: int, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + capture_config = object() + analysis_config = object() + result = _fake_m8_l2_study_result(tmp_path, status) + report_data = object() + output = (tmp_path / "reports").absolute() + calls: list[tuple[str, tuple[object, ...], dict[str, object]]] = [] + monkeypatch.setattr(cli_module, "load_m8_l2_config", lambda path: capture_config) + monkeypatch.setattr(cli_module, "load_m8_l2_analysis_config", lambda path: analysis_config) + + def fake_verify(*args: object, **kwargs: object) -> object: + calls.append(("verify", args, kwargs)) + return result + + def fake_load(*args: object, **kwargs: object) -> object: + calls.append(("load", args, kwargs)) + return report_data + + def fake_write(path: Path, data: object) -> tuple[Path, Path, Path]: + assert path == output + assert data is report_data + return ( + path / "technical_report.md", + path / "executive_memo.md", + path / "model_comparison.md", + ) + + monkeypatch.setattr(cli_module, "verify_m8_l2_study_run", fake_verify) + monkeypatch.setattr(cli_module, "load_m8_l2_report_data", fake_load) + monkeypatch.setattr(cli_module, "write_l2_report_set", fake_write) + monkeypatch.setattr(cli_module, "canonical_report_data_sha256", lambda data: "c" * 64) + + assert ( + main( + [ + "report-m8-l2", + *_m8_l2_study_cli_arguments(tmp_path, include_run_authority=True), + "--output-dir", + str(output), + ] + ) + == expected_exit + ) + assert [call[0] for call in calls] == ["verify", "load"] + assert calls[0][1:] == calls[1][1:] + payload = json.loads(capsys.readouterr().out) + assert payload["output_dir"] == str(output) + assert payload["technical_report"] == str(output / "technical_report.md") + assert payload["executive_memo"] == str(output / "executive_memo.md") + assert payload["model_comparison"] == str(output / "model_comparison.md") + assert payload["report_inputs_sha256"] == "c" * 64 + assert payload["source_bundle_modified"] is False + + +@pytest.mark.parametrize( + ("command", "include_run_authority"), + [ + ("reproduce-m8-l2", False), + ("verify-m8-l2-run", True), + ("report-m8-l2", True), + ], +) +def test_m8_l2_final_commands_reject_noncanonical_session_authority_before_io( + command: str, + include_run_authority: bool, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + arguments = _m8_l2_study_cli_arguments( + tmp_path, + include_run_authority=include_run_authority, + ) + arguments[arguments.index("--primary-manifest-sha256") + 1] = "A" * 64 + if command == "report-m8-l2": + arguments.extend(["--output-dir", str(tmp_path / "reports")]) + monkeypatch.setattr( + cli_module, + "load_m8_l2_config", + lambda path: pytest.fail("argument rejection must precede config I/O"), + ) + + with pytest.raises(SystemExit) as caught: + main([command, *arguments]) + + assert caught.value.code == 2 + + +def test_live_depth_capture_resnapshots_and_preserves_every_reconnect_epoch( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + captured = [ + _captured_depth( + sequence=11, + continuity_id="epoch-1", + event_ts_ns=2_000_000_000, + ), + _captured_depth( + sequence=21, + continuity_id="epoch-2", + event_ts_ns=3_000_000_000, + ), + ] + snapshot_calls: list[str] = [] + + class FakeClient: + def fetch_exchange_info(self, *, symbol: str, raw_root: Path) -> SimpleNamespace: + assert symbol == "BTCUSDT" + assert raw_root == tmp_path / "raw" + return SimpleNamespace(tick_size=Decimal("0.01"), lot_size=Decimal("0.001")) + + def fetch_depth_snapshot( + self, + *, + symbol: str, + raw_root: Path, + continuity_id: str, + tick_size: Decimal, + lot_size: Decimal, + ) -> BookSnapshot: + snapshot_calls.append(continuity_id) + last_update_id = 10 if continuity_id == "epoch-1" else 20 + received_ts_ns = 1_900_000_000 if continuity_id == "epoch-1" else 2_900_000_000 + return _preserved_snapshot( + output_root=tmp_path, + continuity_id=continuity_id, + last_update_id=last_update_id, + received_ts_ns=received_ts_ns, + ) + + class FakeCollector: + url = "wss://example.invalid/stream" + + def __init__(self, **kwargs: object) -> None: + assert kwargs["symbols"] == ("BTCUSDT",) + + async def stream(self, *, max_messages: int | None = None) -> AsyncIterator[CapturedDepth]: + assert max_messages == 2 + for item in captured: + yield item + + monkeypatch.setattr(cli_module, "BinancePublicClient", FakeClient) + monkeypatch.setattr(cli_module, "BinanceLiveDepthCollector", FakeCollector) + + result = asyncio.run( + cli_module._capture_depth( + symbol="BTCUSDT", + max_messages=2, + output_root=tmp_path, + ) + ) + + assert result.messages == 2 + assert snapshot_calls == ["epoch-1", "epoch-2"] + assert result.reconstruction_status == "LIVE" + assert result.book_observations == 2 + assert result.quality_errors == 0 + summary = read_json(result.summary_path) + assert summary["capture_status"] == "COMPLETE" + assert summary["continuity_epochs"] == 2 + assert [item["continuity_id"] for item in summary["continuity_epoch_coverage"]] == [ + "epoch-1", + "epoch-2", + ] + assert sum(item["messages"] for item in summary["continuity_epoch_coverage"]) == 2 + assert summary["normalized_messages"] == 2 + assert summary["excluded_messages"] == 0 + assert all( + entry["rows"] == expected + for entry, expected in ( + (summary["normalized_dataset_manifests"]["book_snapshots"], 2), + (summary["normalized_dataset_manifests"]["depth_deltas"], 2), + (summary["normalized_dataset_manifests"]["book_observations"], 2), + (summary["normalized_dataset_manifests"]["sequence_gaps"], 0), + ) + ) + with result.raw_path.open(encoding="utf-8") as handle: + journal = [json.loads(line) for line in handle] + assert [event["event_kind"] for event in journal] == [ + "websocket_frame", + "rest_snapshot_anchor", + "websocket_frame", + "rest_snapshot_anchor", + ] + assert base64.b64decode(journal[0]["payload_base64"]).decode() == captured[0].raw_payload + + second_result = asyncio.run( + cli_module._capture_depth( + symbol="BTCUSDT", + max_messages=2, + output_root=tmp_path, + ) + ) + latest_pointer = read_json(tmp_path / "quality" / "live_depth_capture.summary.json") + assert result.summary_path.is_file() + assert second_result.summary_path.is_file() + assert second_result.summary_path != result.summary_path + assert latest_pointer["capture_status"] == "LATEST_POINTER" + assert latest_pointer["authoritative_summary_path"] == str(second_result.summary_path) + + +def test_live_depth_duration_completes_gracefully_before_message_ceiling( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + item = _captured_depth( + sequence=1, + continuity_id="epoch-duration", + event_ts_ns=2_000_000_000, + ) + + class FakeClient: + def fetch_exchange_info(self, *, symbol: str, raw_root: Path) -> SimpleNamespace: + return SimpleNamespace(tick_size=Decimal("0.01"), lot_size=Decimal("0.001")) + + def fetch_depth_snapshot(self, **kwargs: object) -> BookSnapshot: + return _preserved_snapshot( + output_root=tmp_path, + continuity_id=str(kwargs["continuity_id"]), + last_update_id=0, + received_ts_ns=1_900_000_000, + ) + + class FakeCollector: + url = "wss://example.invalid/stream" + + def __init__(self, **kwargs: object) -> None: + self.callback = kwargs["on_raw_frame"] + + async def stream(self, *, max_messages: int | None = None) -> AsyncIterator[CapturedDepth]: + assert max_messages == 10 + received_ts_ns = item.delta.received_ts_ns + assert received_ts_ns is not None + self.callback( + RawDepthFrame( + payload=item.raw_payload.encode(), + was_text=True, + received_ts_ns=received_ts_ns, + capture_seq=1, + continuity_id="epoch-duration", + ) + ) + yield item + await asyncio.sleep(60) + + monkeypatch.setattr(cli_module, "BinancePublicClient", FakeClient) + monkeypatch.setattr(cli_module, "BinanceLiveDepthCollector", FakeCollector) + + result = asyncio.run( + cli_module._capture_depth( + symbol="BTCUSDT", + max_messages=10, + duration_seconds=0.01, + output_root=tmp_path, + ) + ) + + assert result.messages == 1 + assert result.completion_reason == "duration_elapsed" + assert result.requested_duration_seconds == 0.01 + assert result.elapsed_monotonic_seconds >= 0.009 + summary = read_json(result.summary_path) + assert summary["completion_reason"] == "duration_elapsed" + assert summary["message_safety_ceiling"] == 10 + assert summary["requested_duration_seconds"] == 0.01 + assert summary["max_continuity_epoch_seconds"] == 0.0 + + +def test_live_depth_duration_fails_if_message_safety_ceiling_arrives_first( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + class FakeClient: + def fetch_exchange_info(self, *, symbol: str, raw_root: Path) -> SimpleNamespace: + return SimpleNamespace(tick_size=Decimal("0.01"), lot_size=Decimal("0.001")) + + def fetch_depth_snapshot(self, **kwargs: object) -> BookSnapshot: + return _preserved_snapshot( + output_root=tmp_path, + continuity_id=str(kwargs["continuity_id"]), + last_update_id=0, + received_ts_ns=1_900_000_000, + ) + + class FakeCollector: + url = "wss://example.invalid/stream" + + def __init__(self, **kwargs: object) -> None: + self.callback = kwargs["on_raw_frame"] + + async def stream(self, *, max_messages: int | None = None) -> AsyncIterator[CapturedDepth]: + assert max_messages == 2 + for sequence in (1, 2): + item = _captured_depth( + sequence=sequence, + continuity_id="epoch-cap", + event_ts_ns=2_000_000_000 + sequence, + ) + received_ts_ns = item.delta.received_ts_ns + assert received_ts_ns is not None + self.callback( + RawDepthFrame( + payload=item.raw_payload.encode(), + was_text=True, + received_ts_ns=received_ts_ns, + capture_seq=sequence, + continuity_id="epoch-cap", + ) + ) + yield item + + monkeypatch.setattr(cli_module, "BinancePublicClient", FakeClient) + monkeypatch.setattr(cli_module, "BinanceLiveDepthCollector", FakeCollector) + + with pytest.raises(RuntimeError, match="message safety ceiling"): + asyncio.run( + cli_module._capture_depth( + symbol="BTCUSDT", + max_messages=2, + duration_seconds=60.0, + output_root=tmp_path, + ) + ) + + assert not list((tmp_path / "quality").glob("live_depth_capture.*.summary.json")) + assert list((tmp_path / "quality").glob("live_depth_capture.*.failed.json")) + + +def test_live_depth_capture_is_one_pass_and_history_independent_in_memory( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + message_count = 2_050 + yielded = 0 + stream_calls = 0 + snapshot_calls = 0 + + class FakeClient: + def fetch_exchange_info(self, *, symbol: str, raw_root: Path) -> SimpleNamespace: + return SimpleNamespace(tick_size=Decimal("0.01"), lot_size=Decimal("0.001")) + + def fetch_depth_snapshot(self, **kwargs: object) -> BookSnapshot: + nonlocal snapshot_calls + snapshot_calls += 1 + return _preserved_snapshot( + output_root=tmp_path, + continuity_id=str(kwargs["continuity_id"]), + last_update_id=0, + received_ts_ns=1_000_000_000, + ) + + class FakeCollector: + url = "wss://example.invalid/stream" + + def __init__(self, **kwargs: object) -> None: + callback = kwargs["on_raw_frame"] + assert callable(callback) + self.callback = callback + + async def stream(self, *, max_messages: int | None = None) -> AsyncIterator[CapturedDepth]: + nonlocal stream_calls, yielded + stream_calls += 1 + assert max_messages == message_count + for sequence in range(1, message_count + 1): + item = _captured_depth( + sequence=sequence, + continuity_id="epoch-1", + event_ts_ns=2_000_000_000 + sequence, + ) + received_ts_ns = item.delta.received_ts_ns + assert received_ts_ns is not None + self.callback( + RawDepthFrame( + payload=item.raw_payload.encode(), + was_text=True, + received_ts_ns=received_ts_ns, + capture_seq=sequence, + continuity_id="epoch-1", + ) + ) + yielded += 1 + yield item + + monkeypatch.setattr(cli_module, "BinancePublicClient", FakeClient) + monkeypatch.setattr(cli_module, "BinanceLiveDepthCollector", FakeCollector) + + result = asyncio.run( + cli_module._capture_depth( + symbol="BTCUSDT", + max_messages=message_count, + output_root=tmp_path, + ) + ) + + assert stream_calls == 1 + assert yielded == message_count + assert snapshot_calls == 1 + assert result.messages == message_count + assert result.book_observations == message_count + summary = read_json(result.summary_path) + assert max(summary["max_buffered_rows_per_dataset"].values()) <= 1_024 + assert max(summary["max_buffered_estimated_bytes_per_dataset"].values()) <= 16 * 1024 * 1024 + depth_manifest_entry = summary["normalized_dataset_manifests"]["depth_deltas"] + depth_manifest = read_json(depth_manifest_entry["manifest_path"]) + assert depth_manifest["rows"] == message_count + assert len(depth_manifest["artifacts"]) == 1 + with result.raw_path.open(encoding="utf-8") as handle: + assert sum(1 for _ in handle) == message_count + 1 + + +def test_live_depth_failure_atomically_preserves_preparse_frame_without_completion( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + malformed = b"\xffnot-json\n" + + class FakeClient: + def fetch_exchange_info(self, *, symbol: str, raw_root: Path) -> SimpleNamespace: + return SimpleNamespace(tick_size=Decimal("0.01"), lot_size=Decimal("0.001")) + + class FakeCollector: + url = "wss://example.invalid/stream" + + def __init__(self, **kwargs: object) -> None: + self.callback = kwargs["on_raw_frame"] + + async def stream(self, *, max_messages: int | None = None) -> AsyncIterator[CapturedDepth]: + self.callback( + RawDepthFrame( + payload=malformed, + was_text=False, + received_ts_ns=2_000_000_100, + capture_seq=0, + continuity_id="epoch-parse-failure", + ) + ) + raise UnicodeDecodeError("utf-8", malformed, 0, 1, "invalid start byte") + if False: # pragma: no cover - makes this an async generator + yield _captured_depth( + sequence=1, + continuity_id="unreachable", + event_ts_ns=1, + ) + + monkeypatch.setattr(cli_module, "BinancePublicClient", FakeClient) + monkeypatch.setattr(cli_module, "BinanceLiveDepthCollector", FakeCollector) + + with pytest.raises(UnicodeDecodeError): + asyncio.run( + cli_module._capture_depth( + symbol="BTCUSDT", + max_messages=1, + output_root=tmp_path, + ) + ) + + assert not (tmp_path / "quality" / "live_depth_capture.summary.json").exists() + [failed_raw] = list( + (tmp_path / "raw" / "binance_spot" / "depth_stream" / "BTCUSDT").glob( + "capture-failed-*.ndjson" + ) + ) + [event] = [json.loads(line) for line in failed_raw.read_text().splitlines()] + assert base64.b64decode(event["payload_base64"]) == malformed + manifests = list(failed_raw.parent.glob(f"{failed_raw.name}.manifest-*.json")) + assert manifests + assert any( + read_json(path)["response_headers"]["x-local-capture-status"] + == "incomplete_capture_failure" + for path in manifests + ) + [failure] = list((tmp_path / "quality").glob("live_depth_capture.*.failed.json")) + assert read_json(failure)["completion_manifest_published"] is False + + +def test_raw_journal_publish_recovers_if_manifest_write_fails_after_rename( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + spool = cli_module._RawMessageSpool( + root=tmp_path, + symbol="BTCUSDT", + source_uri="wss://example.invalid/stream", + ) + spool.append_frame( + RawDepthFrame( + payload=b"{}", + was_text=True, + received_ts_ns=1, + capture_seq=0, + continuity_id="epoch-1", + ) + ) + real_write_manifest = cli_module.write_source_manifest + attempts = 0 + + def flaky_manifest(*args: object, **kwargs: object) -> tuple[Path, str]: + nonlocal attempts + attempts += 1 + if attempts == 1: + raise RuntimeError("injected manifest failure") + return real_write_manifest(*args, **kwargs) # type: ignore[arg-type] + + monkeypatch.setattr(cli_module, "write_source_manifest", flaky_manifest) + + with pytest.raises(RuntimeError, match="injected manifest failure"): + spool.publish(status="raw_capture_complete") + renamed_path = spool.evidence_path + assert renamed_path.is_file() + + evidence = spool.publish(status="incomplete_capture_failure") + + assert evidence.path == renamed_path + assert evidence.sha256 == sha256_file(renamed_path) + assert attempts == 2 diff --git a/Microstructure/tests/test_config.py b/Microstructure/tests/test_config.py new file mode 100644 index 0000000000000000000000000000000000000000..102078fb22b954e1a870038de5295e158a7333fc --- /dev/null +++ b/Microstructure/tests/test_config.py @@ -0,0 +1,90 @@ +from __future__ import annotations + +from datetime import UTC +from pathlib import Path + +import pytest + +from microstructure.config import ConfigError, datetime_to_ns, load_config + +PROJECT_ROOT = Path(__file__).parents[1] + + +def test_smoke_config_is_typed_and_stably_hashed() -> None: + first = load_config(PROJECT_ROOT / "configs" / "smoke.toml") + second = load_config(PROJECT_ROOT / "configs" / "smoke.toml") + + assert first.hash == second.hash + assert len(first.hash) == 64 + assert first.data.symbols == ("BTCUSDT", "ETHUSDT") + assert first.data.start.tzinfo == UTC + assert first.data.partition_root == PROJECT_ROOT / "data" / "normalized" + assert first.evaluation.embargo_events >= first.features.label_horizon_events + + +def test_datetime_to_ns_rejects_naive_values() -> None: + from datetime import datetime + + with pytest.raises(ConfigError, match="timezone aware"): + datetime_to_ns(datetime(2024, 1, 1)) + + +def test_config_rejects_unimplemented_schema_version(tmp_path: Path) -> None: + source = (PROJECT_ROOT / "configs" / "smoke.toml").read_text(encoding="utf-8") + path = tmp_path / "unsupported-schema.toml" + path.write_text( + source.replace('schema_version = "1.0.0"', 'schema_version = "2.0.0"'), + encoding="utf-8", + ) + + with pytest.raises(ConfigError, match=r"unsupported data\.schema_version"): + load_config(path) + + +def test_config_accepts_extensible_adapter_mode_identifier(tmp_path: Path) -> None: + source = (PROJECT_ROOT / "configs" / "smoke.toml").read_text(encoding="utf-8") + path = tmp_path / "third-party-mode.toml" + path.write_text( + source.replace('mode = "synthetic"', 'mode = "fixture_vendor.v1"'), + encoding="utf-8", + ) + + assert load_config(path).data.mode == "fixture_vendor.v1" + + +def test_config_rejects_unsafe_adapter_mode_identifier(tmp_path: Path) -> None: + source = (PROJECT_ROOT / "configs" / "smoke.toml").read_text(encoding="utf-8") + path = tmp_path / "unsafe-mode.toml" + path.write_text( + source.replace('mode = "synthetic"', 'mode = "Fixture Vendor"'), + encoding="utf-8", + ) + + with pytest.raises(ConfigError, match="lowercase adapter identifier"): + load_config(path) + + +@pytest.mark.parametrize( + ("line", "replacement", "message"), + [ + ( + 'end = "2024-01-02T00:10:00Z"', + "", + r"requires a bounded data\.end", + ), + ( + "max_events_per_symbol = 5000", + "max_events_per_symbol = 0", + "requires positive data.max_events_per_symbol", + ), + ], +) +def test_public_config_fails_fast_on_unbounded_inputs( + tmp_path: Path, line: str, replacement: str, message: str +) -> None: + source = (PROJECT_ROOT / "configs" / "public_sample.toml").read_text(encoding="utf-8") + path = tmp_path / "invalid-public.toml" + path.write_text(source.replace(line, replacement), encoding="utf-8") + + with pytest.raises(ConfigError, match=message): + load_config(path) diff --git a/Microstructure/tests/test_dashboard.py b/Microstructure/tests/test_dashboard.py new file mode 100644 index 0000000000000000000000000000000000000000..0468a02432fdcb3366d65405435afd212db33c64 --- /dev/null +++ b/Microstructure/tests/test_dashboard.py @@ -0,0 +1,110 @@ +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +from streamlit.testing.v1 import AppTest + +from microstructure.reporting import write_checksum_manifest + +PROJECT_ROOT = Path(__file__).parents[1] +APP_PATH = PROJECT_ROOT / "dashboard" / "app.py" + + +def _write_json(path: Path, payload: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(payload, sort_keys=True) + "\n", encoding="utf-8") + + +def _dashboard_bundle(root: Path) -> Path: + _write_json( + root / "run_manifest.json", + { + "artifacts": { + "execution_metrics": "metrics/execution_metrics.json", + "execution_sensitivity": "metrics/execution_sensitivity.json", + "market_state": "dashboard/market_state.json", + "predictive_metrics": "metrics/predictive_metrics.json", + "quality_summary": "quality/summary.json", + }, + "data": { + "mode": "synthetic", + "observed_end_utc": "2024-01-02T00:10:00Z", + "observed_start_utc": "2024-01-02T00:00:00Z", + "source": "synthetic_fixture_v1", + "symbols": ["BTCUSDT", "ETHUSDT"], + }, + "evidence_tier": "SYNTHETIC_SMOKE", + "execution_assumptions": {"taker_fee_bps": 4.0}, + "run_id": "dashboard-smoke", + "status": "complete", + }, + ) + _write_json( + root / "provenance.json", + { + "config_sha256": "c" * 64, + "evidence_tier": "SYNTHETIC_SMOKE", + "generated_at_utc": "2026-08-07T12:00:00Z", + "git": {"commit": "UNBORN", "dirty": True}, + "input_manifest_sha256": ["d" * 64], + }, + ) + _write_json(root / "metrics" / "predictive_metrics.json", [{"model": "baseline"}]) + _write_json(root / "metrics" / "execution_metrics.json", [{"net_bps": -1.0}]) + _write_json( + root / "metrics" / "execution_sensitivity.json", + [{"order_type": "market", "size_multiplier": 1.0, "net_pnl": -1.0}], + ) + _write_json(root / "dashboard" / "market_state.json", [{"spread_bps": 2.0}]) + _write_json(root / "quality" / "summary.json", {"error_count": 0}) + write_checksum_manifest(root) + (root / "_SUCCESS").write_text("", encoding="utf-8") + return root + + +def test_dashboard_rejects_an_incomplete_run(tmp_path: Path, monkeypatch: Any) -> None: + incomplete = tmp_path / "incomplete" + incomplete.mkdir() + monkeypatch.setenv("MICROSTRUCTURE_RUN_DIR", str(incomplete)) + + app = AppTest.from_file(str(APP_PATH)).run(timeout=10) + + assert not app.exception + assert app.error + assert "incomplete or invalid" in app.error[0].value + assert "_SUCCESS" in app.caption[0].value + + +def test_dashboard_is_read_only_and_displays_all_evidence_tabs( + tmp_path: Path, monkeypatch: Any +) -> None: + run_dir = _dashboard_bundle(tmp_path / "complete") + before = { + path.relative_to(run_dir): path.read_bytes() + for path in run_dir.rglob("*") + if path.is_file() + } + monkeypatch.setenv("MICROSTRUCTURE_RUN_DIR", str(run_dir)) + + app = AppTest.from_file(str(APP_PATH)).run(timeout=10) + + assert not app.exception + assert app.warning + assert "SYNTHETIC SMOKE" in app.warning[0].value + assert [tab.label for tab in app.tabs] == [ + "Overview", + "Data Quality", + "Market State", + "Predictions", + "Simulated Performance", + "Reproducibility & Limitations", + ] + assert any("Execution sensitivity grid" in item.value for item in app.markdown) + after = { + path.relative_to(run_dir): path.read_bytes() + for path in run_dir.rglob("*") + if path.is_file() + } + assert after == before diff --git a/Microstructure/tests/test_evidence_budget.py b/Microstructure/tests/test_evidence_budget.py new file mode 100644 index 0000000000000000000000000000000000000000..66d858d252bf3999397843d6afb07790a8672d16 --- /dev/null +++ b/Microstructure/tests/test_evidence_budget.py @@ -0,0 +1,158 @@ +from __future__ import annotations + +from pathlib import Path + +import pytest + +from microstructure.data.evidence_budget import ( + EvidenceBudgetError, + EvidenceBudgetExceeded, + EvidenceBudgetStateError, + RetainedEvidenceBudget, +) +from microstructure.data.storage import write_source_manifest + + +def _write_fixture_source_manifest( + raw_path: Path, + *, + budget: RetainedEvidenceBudget | None = None, +) -> Path: + manifest_path, _ = write_source_manifest( + raw_path, + source="fixture", + source_uri="https://example.test/raw.bin", + downloaded_at_utc="2026-08-07T00:00:00Z", + requested_start_ns=1, + requested_end_ns=2, + response_headers={"content-type": "application/octet-stream"}, + retained_evidence_budget=budget, + ) + return manifest_path + + +def test_counts_preexisting_regular_files_and_honors_exact_boundary(tmp_path: Path) -> None: + root = tmp_path / "raw" + (root / "nested").mkdir(parents=True) + (root / "first.bin").write_bytes(b"abc") + (root / "nested" / "second.bin").write_bytes(b"de") + budget = RetainedEvidenceBudget(root, limit_bytes=8) + + assert budget.used_bytes == 5 + assert budget.reserved_bytes == 0 + assert budget.remaining_bytes == 3 + + reservation = budget.reserve(3, label="boundary fixture") + assert budget.remaining_bytes == 0 + reservation.commit() + + assert budget.used_bytes == 8 + assert budget.reserved_bytes == 0 + with pytest.raises(EvidenceBudgetExceeded, match="boundary overflow"): + budget.reserve(1, label="boundary overflow") + + +def test_outstanding_reservations_prevent_oversubscription_and_release(tmp_path: Path) -> None: + budget = RetainedEvidenceBudget(tmp_path, limit_bytes=7) + first = budget.reserve(5) + + with pytest.raises(EvidenceBudgetExceeded): + budget.reserve(3) + + first.release() + second = budget.reserve(7) + second.commit() + assert budget.used_bytes == 7 + with pytest.raises(EvidenceBudgetStateError, match="already committed"): + second.release() + + +def test_context_manager_releases_uncommitted_reservation(tmp_path: Path) -> None: + budget = RetainedEvidenceBudget(tmp_path, limit_bytes=4) + + with pytest.raises(RuntimeError, match="fixture"), budget.reserve(4): + raise RuntimeError("fixture") + + assert budget.used_bytes == 0 + assert budget.reserved_bytes == 0 + assert budget.remaining_bytes == 4 + + +def test_scan_does_not_follow_or_charge_symlinks(tmp_path: Path) -> None: + external = tmp_path / "external" + external.mkdir() + (external / "large.bin").write_bytes(b"x" * 100) + root = tmp_path / "raw" + root.mkdir() + (root / "link").symlink_to(external, target_is_directory=True) + + budget = RetainedEvidenceBudget(root, limit_bytes=0) + + assert budget.used_bytes == 0 + with pytest.raises(EvidenceBudgetError, match="traverses a symlink"): + budget.assert_contains(root / "link" / "new.bin") + + +def test_rejects_preexisting_overage_and_outside_target(tmp_path: Path) -> None: + root = tmp_path / "raw" + root.mkdir() + (root / "existing.bin").write_bytes(b"abcd") + + with pytest.raises(EvidenceBudgetExceeded, match="preexisting"): + RetainedEvidenceBudget(root, limit_bytes=3) + + budget = RetainedEvidenceBudget(root, limit_bytes=4) + with pytest.raises(EvidenceBudgetError, match="outside budget root"): + budget.assert_contains(tmp_path / "elsewhere.bin") + + +def test_source_manifest_charges_exact_bytes_and_reuses_without_double_charge( + tmp_path: Path, +) -> None: + reference_root = tmp_path / "reference" + reference_root.mkdir() + reference_raw = reference_root / "raw.bin" + reference_raw.write_bytes(b"abc") + reference_manifest = _write_fixture_source_manifest(reference_raw) + exact_total = reference_raw.stat().st_size + reference_manifest.stat().st_size + + root = tmp_path / "bounded" + root.mkdir() + raw = root / "raw.bin" + raw.write_bytes(b"abc") + budget = RetainedEvidenceBudget(root, limit_bytes=exact_total) + + manifest = _write_fixture_source_manifest(raw, budget=budget) + assert budget.used_bytes == exact_total + assert budget.remaining_bytes == 0 + assert budget.used_bytes == sum( + path.stat().st_size for path in root.iterdir() if path.is_file() + ) + + duplicate = _write_fixture_source_manifest(raw, budget=budget) + assert duplicate == manifest + assert budget.used_bytes == exact_total + + +def test_source_manifest_budget_failure_writes_no_sidecar_and_releases_reservation( + tmp_path: Path, +) -> None: + reference_root = tmp_path / "reference" + reference_root.mkdir() + reference_raw = reference_root / "raw.bin" + reference_raw.write_bytes(b"abc") + reference_manifest = _write_fixture_source_manifest(reference_raw) + exact_total = reference_raw.stat().st_size + reference_manifest.stat().st_size + + root = tmp_path / "bounded" + root.mkdir() + raw = root / "raw.bin" + raw.write_bytes(b"abc") + budget = RetainedEvidenceBudget(root, limit_bytes=exact_total - 1) + + with pytest.raises(EvidenceBudgetExceeded, match="raw source manifest"): + _write_fixture_source_manifest(raw, budget=budget) + + assert list(root.iterdir()) == [raw] + assert budget.used_bytes == len(b"abc") + assert budget.reserved_bytes == 0 diff --git a/Microstructure/tests/test_execution.py b/Microstructure/tests/test_execution.py new file mode 100644 index 0000000000000000000000000000000000000000..34adb836115e4f46924be305f02559825714b40b --- /dev/null +++ b/Microstructure/tests/test_execution.py @@ -0,0 +1,390 @@ +from __future__ import annotations + +import polars as pl +import pytest + +from microstructure.config import ExecutionConfig +from microstructure.execution import simulate_predictions + + +def execution_config(**overrides: object) -> ExecutionConfig: + values: dict[str, object] = { + "decision_latency_events": 0, + "order_latency_events": 0, + "maker_fee_bps": 10.0, + "taker_fee_bps": 10.0, + "half_spread_bps": 1.0, + "slippage_bps_per_unit": 0.0, + "signal_threshold": 0.6, + "max_position_units": 10.0, + "order_size_units": 1.0, + "limit_fill_base_probability": 1.0, + "queue_ahead_units": 0.0, + "limit_max_age_events": 10, + "cancel_latency_events": 1, + "liquidate_at_end": False, + "capacity_multipliers": (1.0,), + } + values.update(overrides) + return ExecutionConfig(**values) # type: ignore[arg-type] + + +def event_frame(rows: list[dict[str, object]]) -> pl.DataFrame: + defaults: dict[str, object] = { + "symbol": "BTCUSDT", + "bid_depth_1": 100.0, + "ask_depth_1": 100.0, + "trade_side": 0, + "trade_quantity": 0.0, + "trade_price": 101.0, + } + return pl.DataFrame([{**defaults, **row} for row in rows]) + + +def test_market_round_trip_accounts_for_taker_fees() -> None: + events = event_frame( + [ + {"sample_id": 0, "event_ts_ns": 0, "best_bid": 100.0, "best_ask": 102.0}, + {"sample_id": 1, "event_ts_ns": 1, "best_bid": 103.0, "best_ask": 105.0}, + ] + ) + predictions = pl.DataFrame( + { + "sample_id": [0, 1], + "symbol": ["BTCUSDT", "BTCUSDT"], + "probability_up": [0.9, 0.1], + "is_oos": [True, True], + "split": ["test", "test"], + } + ) + + result = simulate_predictions(events, predictions, execution_config()) + + assert result.metrics["gross_pnl"] == pytest.approx(1.0) + assert result.metrics["total_fees"] == pytest.approx(0.205) + assert result.metrics["net_pnl"] == pytest.approx(0.795) + assert result.metrics["turnover_notional"] == pytest.approx(205.0) + assert result.metrics["maximum_drawdown"] == pytest.approx(1.102) + assert "net_equity" in result.positions.columns + + +def test_maximum_drawdown_marks_inventory_on_intervening_events_without_fills() -> None: + events = event_frame( + [ + {"sample_id": 0, "event_ts_ns": 0, "best_bid": 99.0, "best_ask": 101.0}, + {"sample_id": 1, "event_ts_ns": 1, "best_bid": 49.0, "best_ask": 51.0}, + {"sample_id": 2, "event_ts_ns": 2, "best_bid": 100.0, "best_ask": 102.0}, + ] + ) + predictions = pl.DataFrame( + { + "sample_id": [0, 2], + "symbol": ["BTCUSDT", "BTCUSDT"], + "probability_up": [0.9, 0.1], + "is_oos": [True, True], + "split": ["test", "test"], + } + ) + + result = simulate_predictions(events, predictions, execution_config()) + + assert result.metrics["maximum_drawdown"] == pytest.approx(51.101) + + +def test_market_order_uses_arrival_state_and_top_depth_only() -> None: + events = event_frame( + [ + {"sample_id": 0, "event_ts_ns": 0, "best_bid": 99.0, "best_ask": 101.0}, + { + "sample_id": 1, + "event_ts_ns": 1, + "best_bid": 109.0, + "best_ask": 111.0, + "ask_depth_1": 1.5, + }, + ] + ) + predictions = pl.DataFrame( + { + "sample_id": [0], + "symbol": ["BTCUSDT"], + "probability_up": [0.9], + "is_oos": [True], + "split": ["test"], + } + ) + config = execution_config(order_latency_events=1, order_size_units=2.0) + + result = simulate_predictions(events, predictions, config) + + assert result.fills["price"].to_list() == [111.0] + assert result.fills["quantity"].to_list() == [1.5] + assert result.orders["status"].to_list() == ["partially_filled_canceled"] + + +def test_limit_queue_proxy_produces_partial_then_complete_fill() -> None: + events = event_frame( + [ + { + "sample_id": 0, + "event_ts_ns": 0, + "best_bid": 100.0, + "best_ask": 102.0, + "trade_price": 101.0, + }, + { + "sample_id": 1, + "event_ts_ns": 1, + "best_bid": 100.0, + "best_ask": 102.0, + "trade_side": -1, + "trade_quantity": 3.0, + "trade_price": 100.0, + }, + { + "sample_id": 2, + "event_ts_ns": 2, + "best_bid": 100.0, + "best_ask": 102.0, + "trade_side": -1, + "trade_quantity": 4.0, + "trade_price": 100.0, + }, + { + "sample_id": 3, + "event_ts_ns": 3, + "best_bid": 100.0, + "best_ask": 102.0, + "trade_side": -1, + "trade_quantity": 1.0, + "trade_price": 100.0, + }, + ] + ) + predictions = pl.DataFrame( + { + "sample_id": [0], + "symbol": ["BTCUSDT"], + "probability_up": [0.9], + "is_oos": [True], + "split": ["test"], + } + ) + config = execution_config(order_size_units=3.0, queue_ahead_units=5.0) + + result = simulate_predictions(events, predictions, config, order_type="limit", seed=7) + + assert result.fills["quantity"].to_list() == [2.0, 1.0] + assert result.fills["event_id"].to_list() == [2, 3] + assert result.orders["status"].to_list() == ["filled"] + + +def test_equal_position_trade_occurs_before_limit_arrival() -> None: + events = event_frame( + [ + {"sample_id": 0, "event_ts_ns": 0, "best_bid": 100.0, "best_ask": 102.0}, + { + "sample_id": 1, + "event_ts_ns": 1, + "best_bid": 100.0, + "best_ask": 102.0, + "trade_side": -1, + "trade_quantity": 10.0, + "trade_price": 100.0, + }, + ] + ) + predictions = pl.DataFrame( + { + "sample_id": [0], + "symbol": ["BTCUSDT"], + "probability_up": [0.9], + "is_oos": [True], + "split": ["test"], + } + ) + config = execution_config(order_latency_events=1) + + result = simulate_predictions(events, predictions, config, order_type="limit") + + assert result.fills.is_empty() + assert result.orders["status"].to_list() == ["end_of_data"] + + +def test_simulator_rejects_in_sample_predictions() -> None: + events = event_frame([{"sample_id": 0, "event_ts_ns": 0, "best_bid": 100.0, "best_ask": 102.0}]) + predictions = pl.DataFrame( + { + "sample_id": [0], + "symbol": ["BTCUSDT"], + "probability_up": [0.9], + "is_oos": [False], + "split": ["test"], + } + ) + + with pytest.raises(ValueError, match="non-OOS"): + simulate_predictions(events, predictions, execution_config()) + + +def test_inventory_cap_and_partial_end_liquidation_are_explicit() -> None: + events = event_frame( + [ + {"sample_id": 0, "event_ts_ns": 0, "best_bid": 99.0, "best_ask": 101.0}, + {"sample_id": 1, "event_ts_ns": 1, "best_bid": 99.0, "best_ask": 101.0}, + { + "sample_id": 2, + "event_ts_ns": 2, + "best_bid": 100.0, + "best_ask": 102.0, + "bid_depth_1": 1.0, + }, + ] + ) + predictions = pl.DataFrame( + { + "sample_id": [0, 1, 2], + "symbol": ["BTCUSDT"] * 3, + "probability_up": [0.9, 0.9, 0.9], + "is_oos": [True] * 3, + "split": ["test"] * 3, + } + ) + config = execution_config(max_position_units=2.0, liquidate_at_end=True) + + result = simulate_predictions(events, predictions, config) + + assert result.orders.filter(pl.col("status") == "rejected").height == 1 + assert result.metrics["maximum_absolute_inventory"] == pytest.approx(2.0) + assert result.metrics["forced_liquidation_quantity"] == pytest.approx(1.0) + assert result.metrics["unliquidated_quantity"] == pytest.approx(1.0) + assert result.metrics["gross_pnl"] == pytest.approx(-1.0) + + +def test_execution_requires_explicit_held_out_provenance() -> None: + events = event_frame([{"sample_id": 0, "event_ts_ns": 0, "best_bid": 100.0, "best_ask": 102.0}]) + missing_oos = pl.DataFrame( + { + "sample_id": [0], + "symbol": ["BTCUSDT"], + "probability_up": [0.9], + "split": ["test"], + } + ) + validation = missing_oos.with_columns( + pl.lit(True).alias("is_oos"), pl.lit("validation").alias("split") + ) + + with pytest.raises(ValueError, match="explicit OOS"): + simulate_predictions(events, missing_oos, execution_config()) + with pytest.raises(ValueError, match="held-out test"): + simulate_predictions(events, validation, execution_config()) + + +def test_invalid_probability_and_negative_latency_or_markout_fail_closed() -> None: + events = event_frame([{"sample_id": 0, "event_ts_ns": 0, "best_bid": 100.0, "best_ask": 102.0}]) + predictions = pl.DataFrame( + { + "sample_id": [0], + "symbol": ["BTCUSDT"], + "probability_up": [float("nan")], + "is_oos": [True], + "split": ["test"], + } + ) + + with pytest.raises(ValueError, match="finite"): + simulate_predictions(events, predictions, execution_config()) + valid = predictions.with_columns(pl.lit(0.9).alias("probability_up")) + with pytest.raises(ValueError, match="latency"): + simulate_predictions(events, valid, execution_config(order_latency_events=-1)) + with pytest.raises(ValueError, match="markout"): + simulate_predictions(events, valid, execution_config(), markout_events=-1) + with pytest.raises(ValueError, match="queue_ahead_units"): + simulate_predictions( + events, + valid, + execution_config(queue_ahead_units=-1.0), + order_type="limit", + ) + + +def test_one_print_cannot_fill_multiple_passive_orders_beyond_its_volume() -> None: + events = event_frame( + [ + {"sample_id": 0, "event_ts_ns": 0, "best_bid": 100.0, "best_ask": 102.0}, + { + "sample_id": 1, + "event_ts_ns": 1, + "best_bid": 100.0, + "best_ask": 102.0, + "trade_side": -1, + "trade_quantity": 1.0, + "trade_price": 100.0, + }, + ] + ) + predictions = pl.DataFrame( + { + "sample_id": [0, 0], + "symbol": ["BTCUSDT", "BTCUSDT"], + "probability_up": [0.9, 0.9], + "is_oos": [True, True], + "split": ["test", "test"], + } + ) + + result = simulate_predictions( + events, predictions, execution_config(), order_type="limit", seed=5 + ) + + assert result.fills["quantity"].sum() == pytest.approx(1.0) + assert result.metrics["filled_quantity"] == pytest.approx(1.0) + + +def test_orders_and_markouts_do_not_cross_continuity_gaps() -> None: + events = event_frame( + [ + { + "sample_id": 0, + "event_ts_ns": 0, + "continuity_id": "A", + "best_bid": 100.0, + "best_ask": 102.0, + }, + { + "sample_id": 1, + "event_ts_ns": 1, + "continuity_id": "B", + "best_bid": 101.0, + "best_ask": 103.0, + "trade_side": -1, + "trade_quantity": 10.0, + "trade_price": 100.0, + }, + ] + ) + predictions = pl.DataFrame( + { + "sample_id": [0], + "symbol": ["BTCUSDT"], + "probability_up": [0.9], + "is_oos": [True], + "split": ["test"], + } + ) + + delayed = simulate_predictions( + events, + predictions, + execution_config(order_latency_events=1), + order_type="limit", + ) + immediate = simulate_predictions( + events, predictions, execution_config(), order_type="market", markout_events=1 + ) + + assert delayed.fills.is_empty() + assert delayed.orders["status"].to_list() == ["canceled_continuity_gap"] + assert immediate.fills["markout_available"].to_list() == [False] + assert immediate.fills["post_fill_markout_bps"].to_list() == [None] diff --git a/Microstructure/tests/test_exploratory_trade_study.py b/Microstructure/tests/test_exploratory_trade_study.py new file mode 100644 index 0000000000000000000000000000000000000000..b22ac5cd0ba41da5e3f5ce201077b63a835963e7 --- /dev/null +++ b/Microstructure/tests/test_exploratory_trade_study.py @@ -0,0 +1,62 @@ +from __future__ import annotations + +import json +from dataclasses import asdict +from pathlib import Path + +import pytest + +from microstructure.exploratory_trade_study import ( + ExploratoryStudyError, + _checksums, + _load_config, + verify_exploratory_run, +) +from microstructure.provenance import sha256_file + + +def test_exploratory_config_freezes_four_date_roles() -> None: + root = Path(__file__).resolve().parents[1] + config = _load_config(root / "configs" / "exploratory_aggtrades_2026-08-05_08.toml") + + assert tuple((item.date.isoformat(), item.role) for item in config.periods) == ( + ("2026-08-05", "train"), + ("2026-08-06", "validation"), + ("2026-08-07", "primary_test"), + ("2026-08-08", "replication_test"), + ) + assert config.study.evidence_tier == "PUBLIC_ARCHIVE_EXPLORATORY" + assert config.quality.allow_quality_warnings is True + assert not any(asdict(config.claims).values()) + + +def test_exploratory_verifier_rejects_external_input_tamper(tmp_path: Path) -> None: + external = tmp_path / "external.bin" + external.write_bytes(b"input\n") + run = tmp_path / "run" + (run / "data").mkdir(parents=True) + (run / "run_manifest.json").write_text("{}\n", encoding="utf-8") + (run / "data" / "input_evidence.json").write_text( + json.dumps( + { + "raw_manifest": str(external), + "raw_manifest_sha256": sha256_file(external), + "files": [ + { + "absolute_path": str(external), + "sha256": sha256_file(external), + "bytes": external.stat().st_size, + } + ], + } + ) + + "\n", + encoding="utf-8", + ) + _checksums(run) + (run / "_SUCCESS").write_bytes(b"complete\n") + + assert verify_exploratory_run(run)["integrity"] == "verified" + external.write_bytes(b"tampered\n") + with pytest.raises(ExploratoryStudyError, match="external input changed"): + verify_exploratory_run(run) diff --git a/Microstructure/tests/test_features.py b/Microstructure/tests/test_features.py new file mode 100644 index 0000000000000000000000000000000000000000..62a0758bee51fe6c64ee75d77f05d8d2fb875a37 --- /dev/null +++ b/Microstructure/tests/test_features.py @@ -0,0 +1,258 @@ +from __future__ import annotations + +import math + +import polars as pl +import pytest + +from microstructure.config import FeatureConfig +from microstructure.research.features import ( + ResearchDataError, + TemporalLeakageError, + build_research_features, + build_research_frame, + model_feature_columns, + validate_temporal_contract, +) + +SECOND = 1_000_000_000 + + +def _feature_config() -> FeatureConfig: + return FeatureConfig( + trade_windows=(2,), + volatility_window=2, + intensity_window=2, + label_horizon_events=2, + large_trade_quantile=0.9, + ) + + +def _books() -> pl.DataFrame: + rows = [ + (0, "segment-a", 1, 100.0, 10.0, 102.0, 10.0), + (1, "segment-a", 2, 100.0, 12.0, 102.0, 8.0), + (2, "segment-a", 3, 101.0, 5.0, 102.0, 5.0), + (3, "segment-a", 4, 101.0, 4.0, 103.0, 6.0), + (4, "segment-a", 5, 102.0, 8.0, 103.0, 4.0), + (5, "segment-a", 6, 102.0, 6.0, 104.0, 6.0), + (6, "segment-b", 20, 110.0, 5.0, 112.0, 5.0), + (7, "segment-b", 21, 110.0, 7.0, 112.0, 3.0), + (8, "segment-b", 22, 111.0, 5.0, 112.0, 5.0), + ] + return pl.DataFrame( + { + "symbol": ["BTCUSDT"] * len(rows), + "event_ts_ns": [row[0] * SECOND for row in rows], + "available_ts_ns": [row[0] * SECOND for row in rows], + "continuity_id": [row[1] for row in rows], + "sequence_end": [row[2] for row in rows], + "is_valid": [True] * len(rows), + "best_bid": [row[3] for row in rows], + "bid_quantity": [row[4] for row in rows], + "best_ask": [row[5] for row in rows], + "ask_quantity": [row[6] for row in rows], + } + ) + + +def _trades() -> pl.DataFrame: + return pl.DataFrame( + { + "symbol": ["BTCUSDT", "BTCUSDT", "BTCUSDT", "BTCUSDT"], + "continuity_id": ["segment-a", "segment-a", "segment-a", "segment-b"], + "trade_id": [1, 2, 3, 4], + "available_ts_ns": [SECOND // 2, SECOND, 3 * SECOND // 2, 7 * SECOND], + "quantity": [2.0, 7.0, 3.0, 100.0], + "aggressor_side": ["buy", "sell", "sell", "buy"], + } + ) + + +def test_hand_checked_causal_features_and_strict_trade_tie() -> None: + frame = build_research_frame(_books(), _trades(), _feature_config()) + at_one = frame.filter(pl.col("decision_ts_ns") == SECOND).row(0, named=True) + + assert at_one["mid_price"] == 101.0 + assert at_one["spread"] == 2.0 + assert at_one["queue_imbalance_l1"] == pytest.approx(0.2) + assert at_one["causal_microprice"] == pytest.approx(101.2) + assert at_one["ofi_l1"] == pytest.approx(4.0) + # The buy at 0.5 seconds is known. The sell timestamped exactly at this + # book decision is from a separately ordered archive stream and is excluded. + assert at_one["signed_trade_volume_w2"] == pytest.approx(2.0) + assert at_one["trade_feature_max_source_ts_ns"] == SECOND // 2 + assert at_one["trade_feature_max_source_ts_ns"] < at_one["decision_ts_ns"] + assert at_one["realized_price_impact_bps_1"] == pytest.approx(0.0) + assert at_one["spread_recovery_bps_1"] == pytest.approx(0.0) + assert at_one["depth_recovery_l1_1"] == pytest.approx(0.0) + + +def test_feature_stage_can_be_reused_before_any_label_horizon_is_opened() -> None: + features = build_research_features(_books(), _trades(), _feature_config()) + labeled = build_research_frame(_books(), _trades(), _feature_config()) + + assert "future_mid_return" not in features.columns + assert features.select("symbol", "continuity_id", "decision_sequence").equals( + labeled.select("symbol", "continuity_id", "decision_sequence") + ) + assert ( + features.get_column("max_feature_source_ts_ns").to_list() + == labeled.get_column("max_feature_source_ts_ns").to_list() + ) + + +def test_optional_multilevel_depth_and_cancellation_enter_canonical_frame() -> None: + books = _books().with_columns( + pl.lit("binance_spot").alias("venue"), + (pl.col("bid_quantity") + 4.0).alias("depth_bid_5"), + (pl.col("ask_quantity") + 6.0).alias("depth_ask_5"), + (pl.col("bid_quantity") + 14.0).alias("depth_bid_10"), + (pl.col("ask_quantity") + 16.0).alias("depth_ask_10"), + ) + depth_deltas = pl.DataFrame( + { + "venue": ["binance_spot"] * books.height, + "symbol": ["BTCUSDT"] * books.height, + "event_ts_ns": books.get_column("event_ts_ns"), + "available_ts_ns": books.get_column("available_ts_ns"), + "continuity_id": books.get_column("continuity_id"), + "first_update_id": books.get_column("sequence_end"), + "last_update_id": books.get_column("sequence_end"), + "bids": [ + [{"price_ticks": 10_000, "quantity_lots": 0 if index == 1 else 10}] + for index in range(books.height) + ], + "asks": [[{"price_ticks": 10_200, "quantity_lots": 10}] for _ in range(books.height)], + } + ) + + frame = build_research_frame( + books, + _trades(), + _feature_config(), + depth_deltas=depth_deltas, + ) + at_one = frame.filter(pl.col("decision_ts_ns") == SECOND).row(0, named=True) + + assert at_one["depth_total_l5"] == pytest.approx(30.0) + assert at_one["queue_imbalance_l5"] == pytest.approx(2.0 / 30.0) + assert at_one["cancellation_deletes_w2"] == 1 + assert at_one["cancellation_intensity_w2"] == pytest.approx(0.25) + assert at_one["cancellation_feature_max_source_ts_ns"] == SECOND + assert "cancellation_intensity_w2" in model_feature_columns(frame) + validate_temporal_contract(frame) + + +def test_future_event_label_is_exact_right_censored_and_gap_local() -> None: + frame = build_research_frame(_books(), _trades(), _feature_config()) + at_two = frame.filter(pl.col("decision_ts_ns") == 2 * SECOND).row(0, named=True) + assert at_two["future_mid_return"] == pytest.approx(math.log(102.5 / 101.5)) + assert at_two["future_mid_direction"] == 1 + assert at_two["future_mid_up"] == 1 + assert at_two["label_information_end_ts_ns"] == 4 * SECOND + + # The final two rows of segment A may not look into segment B even though + # later book observations exist globally. + segment_a_tail = frame.filter( + (pl.col("continuity_id") == "segment-a") & (pl.col("decision_ts_ns") >= 4 * SECOND) + ) + assert segment_a_tail.get_column("right_censored").to_list() == [True, True] + assert segment_a_tail.get_column("future_mid_return").null_count() == 2 + + first_b = ( + frame.filter(pl.col("continuity_id") == "segment-b") + .sort("decision_sequence") + .row(0, named=True) + ) + assert first_b["ofi_l1"] == 0.0 + assert first_b["signed_trade_volume_w2"] == 0.0 + + audit = validate_temporal_contract(frame) + assert audit.rows == 9 + assert audit.right_censored_rows == 4 + assert audit.continuity_segments == 2 + + +def test_delayed_old_continuity_trade_cannot_enter_new_segment_features() -> None: + trades = pl.DataFrame( + { + "symbol": ["BTCUSDT", "BTCUSDT"], + "continuity_id": ["segment-b", "segment-a"], + "trade_id": [20, 21], + "available_ts_ns": [6 * SECOND + SECOND // 4, 6 * SECOND + SECOND // 2], + "quantity": [3.0, 100.0], + "aggressor_side": ["sell", "buy"], + } + ) + frame = build_research_frame(_books(), trades, _feature_config()) + second_b = frame.filter( + (pl.col("continuity_id") == "segment-b") & (pl.col("decision_ts_ns") == 7 * SECOND) + ).row(0, named=True) + + assert second_b["signed_trade_volume_w2"] == pytest.approx(-3.0) + assert second_b["trade_volume_w2"] == pytest.approx(3.0) + assert second_b["trade_feature_max_source_ts_ns"] == 6 * SECOND + SECOND // 4 + + +def test_unsegmented_trades_fail_closed_for_multi_segment_books() -> None: + trades_without_continuity = _trades().drop("continuity_id") + + with pytest.raises(ResearchDataError, match="require continuity_id"): + build_research_frame(_books(), trades_without_continuity, _feature_config()) + + +def test_mutating_the_future_cannot_change_past_features() -> None: + original_books = _books() + original = build_research_frame(original_books, _trades(), _feature_config()) + mutated_books = original_books.with_columns( + pl.when(pl.col("available_ts_ns") > 2 * SECOND) + .then(pl.col("best_bid") + 10_000.0) + .otherwise(pl.col("best_bid")) + .alias("best_bid"), + pl.when(pl.col("available_ts_ns") > 2 * SECOND) + .then(pl.col("best_ask") + 10_000.0) + .otherwise(pl.col("best_ask")) + .alias("best_ask"), + ) + mutated_trades = pl.concat( + [ + _trades(), + pl.DataFrame( + { + "symbol": ["BTCUSDT"], + "continuity_id": ["segment-a"], + "trade_id": [99], + "available_ts_ns": [3 * SECOND], + "quantity": [1_000_000.0], + "aggressor_side": ["buy"], + } + ), + ] + ) + mutated = build_research_frame(mutated_books, mutated_trades, _feature_config()) + feature_columns = [ + "mid_price", + "spread_bps", + "queue_imbalance_l1", + "causal_microprice", + "ofi_l1", + "signed_trade_volume_w2", + "trade_volume_w2", + "realized_volatility_w2", + ] + cutoff = pl.col("decision_ts_ns") <= 2 * SECOND + assert ( + original.filter(cutoff) + .select(feature_columns) + .equals(mutated.filter(cutoff).select(feature_columns)) + ) + + +def test_lineage_guard_rejects_deliberate_future_source() -> None: + frame = build_research_frame(_books(), _trades(), _feature_config()) + leaked = frame.with_columns( + (pl.col("feature_cutoff_ts_ns") + 1).alias("max_feature_source_ts_ns") + ) + with pytest.raises(TemporalLeakageError, match="feature lineage"): + validate_temporal_contract(leaked) diff --git a/Microstructure/tests/test_ingestion.py b/Microstructure/tests/test_ingestion.py new file mode 100644 index 0000000000000000000000000000000000000000..5f0d62140622f83999a9dc19f533510137582a1e --- /dev/null +++ b/Microstructure/tests/test_ingestion.py @@ -0,0 +1,679 @@ +from __future__ import annotations + +import json +from collections.abc import Iterable, Mapping +from dataclasses import replace +from decimal import Decimal +from pathlib import Path +from typing import Any +from urllib.parse import urlencode + +import pyarrow as pa # type: ignore[import-untyped] +import pyarrow.parquet as pq # type: ignore[import-untyped] +import pytest + +import microstructure.ingestion as ingestion_module +from microstructure.config import ProjectConfig, load_config +from microstructure.data.binance import BinanceHistoricalTradeDownloader +from microstructure.data.quality import validate_table +from microstructure.data.schemas import table_from_records +from microstructure.data.storage import DatasetWriteResult +from microstructure.ingestion import ( + DataAdapterRegistry, + DataQualityGateError, + IngestionError, + IngestionResult, + builtin_data_adapter_registry, + ingest_from_config, + ingest_public_trades, + ingest_synthetic, + validate_configured_input, +) +from microstructure.provenance import read_json, sha256_file, write_json + +PROJECT_ROOT = Path(__file__).parents[1] + + +class FakeResponse: + def __init__( + self, + status_code: int, + payload: Any, + *, + headers: Mapping[str, str] | None = None, + ) -> None: + self.status_code = status_code + self._payload = payload + self.content = json.dumps(payload, separators=(",", ":")).encode() + self.text = self.content.decode() + self.headers = dict(headers or {}) + self.url = "https://data-api.binance.vision/fixture" + + def json(self) -> Any: + return self._payload + + +class FakeSession: + def __init__(self, responses: list[FakeResponse]) -> None: + self.responses = responses + self.calls: list[dict[str, object]] = [] + + def get(self, url: str, *, params: Mapping[str, object], timeout: float) -> FakeResponse: + self.calls.append({"url": url, "params": dict(params), "timeout": timeout}) + response = self.responses.pop(0) + response.url = f"{url}?{urlencode(params)}" + return response + + +def _metadata(symbol: str, *, lot_size: str) -> dict[str, object]: + base = "BTC" if symbol == "BTCUSDT" else "ETH" + return { + "symbols": [ + { + "symbol": symbol, + "status": "TRADING", + "baseAsset": base, + "quoteAsset": "USDT", + "filters": [ + { + "filterType": "PRICE_FILTER", + "minPrice": "0.01", + "maxPrice": "1000000.00", + "tickSize": "0.01", + }, + { + "filterType": "LOT_SIZE", + "minQty": lot_size, + "maxQty": "9000.0", + "stepSize": lot_size, + }, + ], + } + ] + } + + +def _trades(symbol: str, start_ms: int, quantity: str) -> list[dict[str, object]]: + offset = 0 if symbol == "BTCUSDT" else 100 + return [ + { + "a": offset + 1, + "p": "100.01", + "q": quantity, + "f": offset + 10, + "l": offset + 10, + "T": start_ms, + "m": False, + }, + { + "a": offset + 2, + "p": "100.02", + "q": quantity, + "f": offset + 11, + "l": offset + 11, + "T": start_ms + 1, + "m": True, + }, + ] + + +def test_synthetic_ingestion_validates_and_stages_immutable_bundle(tmp_path: Path) -> None: + base = load_config(PROJECT_ROOT / "configs" / "smoke.toml") + config = replace( + base, + data=replace( + base.data, + events_per_symbol=8, + partition_root=tmp_path / "normalized", + ), + ) + + result = ingest_synthetic(config, tmp_path) + + assert result.mode == "synthetic" + assert result.evidence_tier == "SYNTHETIC_SMOKE" + assert result.validation.passed + assert result.dataset("trades").rows == 16 + assert result.dataset("book_observations").rows == 16 + trades = result.dataset("trades") + assert trades.table is not None + assert trades.materialize(max_rows=16) is trades.table + assert result.rows == 32 + assert result.raw_artifacts == () + assert result.ingestion_manifest_path.is_file() + assert result.ingestion_manifest_sha256 == sha256_file(result.ingestion_manifest_path) + assert all(dataset.storage.manifest_path.is_file() for dataset in result.datasets) + assert all(path.is_file() for path in result.validation.report_paths) + assert validate_configured_input(config).passed + + +def test_dispatcher_uses_synthetic_mode_and_caller_output_root(tmp_path: Path) -> None: + base = load_config(PROJECT_ROOT / "configs" / "smoke.toml") + config = replace(base, data=replace(base.data, events_per_symbol=2)) + + result = ingest_from_config(config, tmp_path) + + assert result.mode == "synthetic" + assert result.output_root == tmp_path.resolve() + assert (tmp_path / "normalized").is_dir() + + +def test_dispatcher_accepts_a_mode_checked_external_adapter(tmp_path: Path) -> None: + base = load_config(PROJECT_ROOT / "configs" / "smoke.toml") + + class FixtureAdapter: + mode = "synthetic" + + def ingest(self, config: ProjectConfig, output_root: str | Path) -> IngestionResult: + assert config is base + return ingest_synthetic(base, output_root) + + result = ingest_from_config(base, tmp_path, adapter=FixtureAdapter()) + + assert result.mode == "synthetic" + + +def test_registry_dispatches_a_configured_third_party_adapter(tmp_path: Path) -> None: + base = load_config(PROJECT_ROOT / "configs" / "smoke.toml") + config = replace(base, data=replace(base.data, mode="fixture_vendor")) + calls: list[tuple[ProjectConfig, Path]] = [] + + class FixtureVendorAdapter: + mode = "fixture_vendor" + + def ingest(self, config: ProjectConfig, output_root: str | Path) -> IngestionResult: + destination = Path(output_root) + calls.append((config, destination)) + synthetic = ingest_synthetic(base, destination) + return replace(synthetic, mode=self.mode) + + registry = DataAdapterRegistry() + registry.register(FixtureVendorAdapter()) + + result = ingest_from_config(config, tmp_path, registry=registry) + + assert result.mode == "fixture_vendor" + assert calls == [(config, tmp_path)] + + +def test_registry_rejects_unknown_and_duplicate_modes_without_fallback(tmp_path: Path) -> None: + base = load_config(PROJECT_ROOT / "configs" / "smoke.toml") + unknown = replace(base, data=replace(base.data, mode="unregistered_vendor")) + registry = builtin_data_adapter_registry() + + with pytest.raises(IngestionError, match=r"no data adapter registered.*unregistered_vendor"): + ingest_from_config(unknown, tmp_path, registry=registry) + + class DuplicateSyntheticAdapter: + mode = "synthetic" + + def ingest(self, config: ProjectConfig, output_root: str | Path) -> IngestionResult: + raise AssertionError("duplicate adapter must never be selected") + + with pytest.raises(IngestionError, match="already registered"): + registry.register(DuplicateSyntheticAdapter()) + + assert registry.modes == ("binance_rest", "synthetic") + + +def test_validation_only_reports_errors_without_mutating_input(tmp_path: Path) -> None: + base = load_config(PROJECT_ROOT / "configs" / "smoke.toml") + generated = ingest_synthetic( + replace(base, data=replace(base.data, symbols=("BTCUSDT",), events_per_symbol=2)), + tmp_path, + ) + records = generated.dataset("trades").table.to_pylist() + records[1]["trade_id"] = records[0]["trade_id"] + invalid = table_from_records("trades", records) + before = invalid.to_pylist() + + summary = validate_configured_input(base, tables={"trades": invalid}) + + assert not summary.passed + assert summary.error_count >= 1 + assert invalid.to_pylist() == before + + +def test_discovered_validation_streams_parquet_without_legacy_eager_reads( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + base = load_config(PROJECT_ROOT / "configs" / "smoke.toml") + config = replace( + base, + data=replace( + base.data, + events_per_symbol=4, + partition_root=tmp_path / "normalized", + ), + ) + generated = ingest_synthetic(config, tmp_path) + + def forbidden(*args: object, **kwargs: object) -> None: + del args, kwargs + raise AssertionError("discovered validation must not materialize whole Parquet files") + + monkeypatch.setattr(ingestion_module.pq, "read_table", forbidden) + monkeypatch.setattr(ingestion_module.pa, "concat_tables", forbidden) + + summary = validate_configured_input(config) + + assert summary.passed + assert summary.rows_checked == generated.rows + assert tuple(report.dataset for report in summary.reports) == ( + "book_observations", + "trades", + ) + assert summary.report_paths == () + + +def test_discovered_validation_rejects_metadata_rows_before_streaming( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + base = load_config(PROJECT_ROOT / "configs" / "smoke.toml") + stored_config = replace( + base, + data=replace( + base.data, + events_per_symbol=4, + partition_root=tmp_path / "normalized", + ), + ) + ingest_synthetic(stored_config, tmp_path) + bounded_config = replace( + stored_config, + data=replace(stored_config.data, events_per_symbol=1), + ) + + def forbidden(*args: object, **kwargs: object) -> None: + del args, kwargs + raise AssertionError("row data must not be read after the metadata guard fails") + + monkeypatch.setattr(ingestion_module, "validate_batches", forbidden) + + with pytest.raises(IngestionError, match="above configured validation bound"): + validate_configured_input(bounded_config) + + +def test_public_ingestion_uses_exchange_scales_retries_caps_and_preserves_raw( + tmp_path: Path, +) -> None: + base = load_config(PROJECT_ROOT / "configs" / "public_sample.toml") + config = replace( + base, + run=replace(base.run, evidence_tier="FULL_DATA"), + data=replace( + base.data, + max_events_per_symbol=2, + request_limit=2, + max_retries=1, + partition_root=tmp_path / "normalized", + ), + ) + start_ms = int(config.data.start.timestamp() * 1000) + session = FakeSession( + [ + FakeResponse(429, {"code": -1003}, headers={"Retry-After": "1"}), + FakeResponse(200, _metadata("BTCUSDT", lot_size="0.00001")), + FakeResponse(200, _trades("BTCUSDT", start_ms, "0.00002")), + FakeResponse(200, _metadata("ETHUSDT", lot_size="0.0001")), + FakeResponse(200, _trades("ETHUSDT", start_ms, "0.0002")), + ] + ) + sleeps: list[float] = [] + + result = ingest_from_config( + config, + tmp_path, + session=session, # type: ignore[arg-type] + sleep=sleeps.append, + random_value=lambda: 1.0, + ) + + assert sleeps == [1.0] + assert result.mode == "binance_rest" + assert result.evidence_tier == "PUBLIC_SAMPLE_PARTIAL" + assert result.validation.passed + assert result.dataset("trades").rows == 4 + assert {item.symbol: item.rows for item in result.symbols} == { + "BTCUSDT": 2, + "ETHUSDT": 2, + } + assert all(not item.complete_range for item in result.symbols) + assert [item.metadata.lot_size for item in result.symbols] == [ + Decimal("0.00001"), + Decimal("0.0001"), + ] + dataset = result.dataset("trades") + assert dataset.table is None + with pytest.raises(IngestionError, match="materialization bound 3"): + dataset.materialize(max_rows=3) + rows = dataset.materialize(max_rows=4).to_pylist() + assert [row["quantity_lots"] for row in rows] == [2, 2, 2, 2] + assert len(result.raw_artifacts) == 4 + assert all( + item.path.is_file() and item.manifest_path.is_file() for item in result.raw_artifacts + ) + assert len(session.calls) == 5 + manifest = read_json(result.ingestion_manifest_path) + assert manifest["all_requested_ranges_complete"] is False + assert manifest["requested_evidence_tier"] == "FULL_DATA" + assert manifest["evidence_tier"] == "PUBLIC_SAMPLE_PARTIAL" + assert manifest["row_cap_per_symbol"] == 2 + assert {item["symbol"] for item in manifest["symbols"]} == {"BTCUSDT", "ETHUSDT"} + assert all(item["raw_page_count"] == 1 for item in manifest["symbols"]) + assert all(item["stop_reason"] == "event_cap" for item in manifest["symbols"]) + assert all(item["last_raw_page_sha256"] for item in manifest["symbols"]) + assert len(manifest["raw_artifacts"]) == 4 + by_symbol = {item.symbol: item for item in result.symbols} + for item in manifest["symbols"]: + observed = by_symbol[item["symbol"]] + terminal = observed.stream_summary + stream_claim = item["stream_summary"] + assert stream_claim == { + "requested_start_ns": terminal.requested_start_ns, + "requested_end_ns": terminal.requested_end_ns, + "rows_yielded": terminal.rows_yielded, + "raw_page_count": terminal.raw_page_count, + "stop_reason": str(terminal.stop_reason), + "complete_range": terminal.complete_range, + "last_raw_page": { + "path": str(terminal.last_raw_page.path.relative_to(result.output_root)), + "manifest_path": str( + terminal.last_raw_page.manifest_path.relative_to(result.output_root) + ), + "sha256": terminal.last_raw_page.sha256, + "request_uri": terminal.last_raw_page.request_uri, + "row_count": terminal.last_raw_page.row_count, + }, + } + assert len(result.raw_artifacts) == len(result.symbols) + sum( + item.stream_summary.raw_page_count for item in result.symbols + ) + + +def test_public_ingestion_is_one_shot_and_avoids_legacy_materializers( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + base = load_config(PROJECT_ROOT / "configs" / "public_sample.toml") + config = replace( + base, + data=replace( + base.data, + max_events_per_symbol=2, + request_limit=2, + partition_root=tmp_path / "normalized", + ), + ) + start_ms = int(config.data.start.timestamp() * 1000) + session = FakeSession( + [ + FakeResponse(200, _metadata("BTCUSDT", lot_size="0.00001")), + FakeResponse(200, _trades("BTCUSDT", start_ms, "0.00002")), + FakeResponse(200, _metadata("ETHUSDT", lot_size="0.0001")), + FakeResponse(200, _trades("ETHUSDT", start_ms, "0.0002")), + ] + ) + + def forbidden(*args: object, **kwargs: object) -> None: + del args, kwargs + raise AssertionError("legacy eager path must not be called") + + original_stream = BinanceHistoricalTradeDownloader.stream + stream_iterations: list[int] = [] + + class OneShotStream: + def __init__(self, inner: Any) -> None: + self.inner = inner + self.iterations = 0 + stream_iterations.append(0) + self.index = len(stream_iterations) - 1 + + def __iter__(self) -> OneShotStream: + self.iterations += 1 + stream_iterations[self.index] = self.iterations + if self.iterations != 1: + raise AssertionError("stream was iterated more than once") + return self + + def __next__(self) -> Any: + return next(self.inner) + + @property + def summary(self) -> Any: + return self.inner.summary + + def one_shot_stream( + downloader: BinanceHistoricalTradeDownloader, **kwargs: Any + ) -> OneShotStream: + return OneShotStream(original_stream(downloader, **kwargs)) + + original_write = ingestion_module.write_partitioned_parquet + write_calls: list[dict[str, Any]] = [] + + def counted_write(batches: Iterable[Any], **kwargs: Any) -> DatasetWriteResult: + write_calls.append(dict(kwargs)) + return original_write(batches, **kwargs) + + monkeypatch.setattr(BinanceHistoricalTradeDownloader, "download", forbidden) + monkeypatch.setattr(BinanceHistoricalTradeDownloader, "stream", one_shot_stream) + monkeypatch.setattr(ingestion_module, "validate_table", forbidden) + monkeypatch.setattr(ingestion_module.pa, "concat_tables", forbidden) + monkeypatch.setattr(ingestion_module, "write_partitioned_parquet", counted_write) + + result = ingest_public_trades( + config, + tmp_path, + session=session, # type: ignore[arg-type] + ) + + assert result.dataset("trades").table is None + assert stream_iterations == [1, 1] + assert len(write_calls) == 1 + assert write_calls[0]["max_input_batch_rows"] == config.data.request_limit + assert len(result.dataset("trades").storage.artifacts) == 2 + + +def test_public_incremental_quality_matches_eager_rules_across_pages( + tmp_path: Path, +) -> None: + base = load_config(PROJECT_ROOT / "configs" / "public_sample.toml") + config = replace( + base, + data=replace( + base.data, + symbols=("BTCUSDT",), + max_events_per_symbol=2, + request_limit=1, + partition_root=tmp_path / "normalized", + ), + ) + start_ms = int(config.data.start.timestamp() * 1000) + trades = _trades("BTCUSDT", start_ms, "0.00002") + trades[1]["T"] = start_ms + config.quality.max_silence_ms + 1 + session = FakeSession( + [ + FakeResponse(200, _metadata("BTCUSDT", lot_size="0.00001")), + FakeResponse(200, [trades[0]]), + FakeResponse(200, [trades[1]]), + ] + ) + + result = ingest_public_trades( + config, + tmp_path, + session=session, # type: ignore[arg-type] + ) + materialized = result.dataset("trades").materialize(max_rows=2) + eager = validate_table( + materialized, + "trades", + max_spread_bps=config.quality.max_spread_bps, + max_silence_ns=config.quality.max_silence_ms * 1_000_000, + ) + incremental = result.validation.report_for("trades") + write_order = tuple(item.data_path for item in result.dataset("trades").storage.artifacts) + assert write_order != tuple(sorted(write_order)) + discovered = validate_configured_input(config).report_for("trades") + result.dataset("trades").storage.manifest_path.unlink() + legacy_discovered = validate_configured_input(config).report_for("trades") + + assert incremental.rows_checked == eager.rows_checked == 2 + assert incremental.error_count == eager.error_count == 0 + assert incremental.warning_count == eager.warning_count == 1 + assert incremental.findings == eager.findings + assert discovered.findings == incremental.findings + assert legacy_discovered.findings == incremental.findings + assert incremental.findings[0].rule_id == "temporal.long_silence" + assert incremental.findings[0].row_index == 1 + + +def test_public_quality_gate_preserves_raw_normalized_and_manifest_evidence( + tmp_path: Path, +) -> None: + base = load_config(PROJECT_ROOT / "configs" / "public_sample.toml") + config = replace( + base, + data=replace( + base.data, + symbols=("BTCUSDT",), + max_events_per_symbol=2, + request_limit=2, + partition_root=tmp_path / "normalized", + ), + ) + start_ms = int(config.data.start.timestamp() * 1000) + session = FakeSession( + [ + FakeResponse(200, _metadata("BTCUSDT", lot_size="0.00001")), + FakeResponse(200, _trades("BTCUSDT", start_ms, "0.00000")), + ] + ) + + with pytest.raises(DataQualityGateError) as captured: + ingest_public_trades( + config, + tmp_path, + session=session, # type: ignore[arg-type] + ) + + assert captured.value.summary.error_count == 2 + assert list((tmp_path / "raw").rglob("*.json")) + parquet_paths = list((tmp_path / "normalized").rglob("*.parquet")) + assert parquet_paths + manifest_paths = list((tmp_path / "_ingestion_manifests").glob("*.json")) + assert len(manifest_paths) == 1 + manifest = read_json(manifest_paths[0]) + assert manifest["normalized_datasets"][0]["rows"] == 2 + assert len(manifest["raw_artifacts"]) == 2 + quality_paths = list((tmp_path / "quality").glob("trades.validation-*.json")) + assert len(quality_paths) == 1 + quality = read_json(quality_paths[0]) + assert quality["summary"] == {"errors": 2, "warnings": 0} + findings_paths = list((tmp_path / "quality").glob("trades.findings-*.jsonl")) + assert len(findings_paths) == 1 + findings = findings_paths[0].read_text().splitlines() + assert len(findings) == 2 + quality_claims = manifest["quality_artifacts"] + assert len(quality_claims) == 2 + for claim in quality_claims: + path = tmp_path / claim["path"] + assert claim["sha256"] == sha256_file(path) + assert claim["bytes"] == path.stat().st_size + + +def test_discovered_validation_rejects_conflicting_manifest_write_orders( + tmp_path: Path, +) -> None: + base = load_config(PROJECT_ROOT / "configs" / "public_sample.toml") + config = replace( + base, + data=replace( + base.data, + symbols=("BTCUSDT",), + max_events_per_symbol=2, + request_limit=1, + partition_root=tmp_path / "normalized", + ), + ) + start_ms = int(config.data.start.timestamp() * 1000) + trades = _trades("BTCUSDT", start_ms, "0.00002") + session = FakeSession( + [ + FakeResponse(200, _metadata("BTCUSDT", lot_size="0.00001")), + FakeResponse(200, [trades[0]]), + FakeResponse(200, [trades[1]]), + ] + ) + result = ingest_public_trades( + config, + tmp_path, + session=session, # type: ignore[arg-type] + ) + storage = result.dataset("trades").storage + payload = read_json(storage.manifest_path) + payload["artifacts"] = list(reversed(payload["artifacts"])) + for ordinal, artifact in enumerate(payload["artifacts"]): + artifact["write_ordinal"] = ordinal + write_json(storage.manifest_path.parent / "trades.manifest-conflict.json", payload) + + with pytest.raises(IngestionError, match="write_ordinal"): + validate_configured_input(config) + + +def test_discovered_validation_rejects_same_row_count_parquet_tampering( + tmp_path: Path, +) -> None: + base = load_config(PROJECT_ROOT / "configs" / "smoke.toml") + config = replace( + base, + data=replace( + base.data, + events_per_symbol=4, + partition_root=tmp_path / "normalized", + ), + ) + generated = ingest_synthetic(config, tmp_path) + artifact = generated.dataset("trades").storage.artifacts[0] + table = pq.read_table(artifact.data_path) + prices = table.column("price") + replacement = pa.chunked_array( + [pa.array([float(prices[0].as_py()) + 1.0, *prices.slice(1).to_pylist()])], + type=pa.float64(), + ) + tampered = table.set_column(table.schema.get_field_index("price"), "price", replacement) + pq.write_table(tampered, artifact.data_path) + + with pytest.raises(IngestionError, match="data_sha256 checksum mismatch"): + validate_configured_input(config) + + +def test_public_ingestion_requires_bounded_supported_universe(tmp_path: Path) -> None: + base = load_config(PROJECT_ROOT / "configs" / "public_sample.toml") + missing_cap = replace(base, data=replace(base.data, max_events_per_symbol=None)) + unsupported = replace(base, data=replace(base.data, symbols=("BNBUSDT",))) + + with pytest.raises(IngestionError, match="max_events_per_symbol"): + ingest_public_trades(missing_cap, tmp_path) + with pytest.raises(IngestionError, match="unsupported public-sample symbols"): + ingest_public_trades(unsupported, tmp_path) + + +def test_public_ingestion_rejects_empty_requested_coverage_but_preserves_raw( + tmp_path: Path, +) -> None: + base = load_config(PROJECT_ROOT / "configs" / "public_sample.toml") + config = replace(base, data=replace(base.data, symbols=("BTCUSDT",))) + session = FakeSession( + [ + FakeResponse(200, _metadata("BTCUSDT", lot_size="0.00001")), + FakeResponse(200, []), + ] + ) + + with pytest.raises(IngestionError, match="no aggregate trades"): + ingest_public_trades(config, tmp_path, session=session) # type: ignore[arg-type] + + assert list((tmp_path / "raw").rglob("*.json")) diff --git a/Microstructure/tests/test_l2_analysis.py b/Microstructure/tests/test_l2_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..b12a14ccfb92029a9a9cae2299dbda4f8bd89763 --- /dev/null +++ b/Microstructure/tests/test_l2_analysis.py @@ -0,0 +1,162 @@ +from __future__ import annotations + +from datetime import datetime + +import polars as pl + +from microstructure.research.l2_analysis import build_l2_descriptive_analysis + +SECOND = 1_000_000_000 +DATES = ( + ("2026-08-10", "train"), + ("2026-08-11", "validation"), + ("2026-08-12", "primary_test"), + ("2026-08-13", "replication_test"), +) +ENDPOINTS = ( + ("event_20", "event", 20, "events"), + ("event_100", "event", 100, "events"), + ("clock_1000ms", "clock", 1_000, "milliseconds"), + ("clock_5000ms", "clock", 5_000, "milliseconds"), +) +FEATURES = ( + "spread_bps", + "depth_total_l1", + "ofi_w20", + "realized_volatility_w100", +) + + +def _frame( + study_date: str, + study_role: str, + symbol: str, + endpoint_name: str, + domain: str, + horizon: int, + unit: str, +) -> pl.DataFrame: + start = int(datetime.fromisoformat(f"{study_date}T14:00:00+00:00").timestamp()) * SECOND + continuity = f"{study_date}::{symbol}::observed-0000" + rows: list[dict[str, object]] = [] + for sequence in range(140): + decision = start + sequence * SECOND + censored = sequence >= 120 + label_end = decision + (horizon * SECOND if domain == "event" else horizon * 1_000_000) + ofi = float((sequence % 9) - 4) + future_return = ofi * 1e-5 + (0.25e-5 if symbol == "BTCUSDT" else -0.1e-5) + bid_quantity = 1.0 if sequence % 19 == 0 else 5.0 + (sequence % 7) * 0.2 + ask_quantity = 1.2 if sequence % 23 == 0 else 4.5 + (sequence % 5) * 0.2 + spread = 8.0 if sequence % 17 == 0 else 1.0 + (sequence % 3) * 0.1 + rows.append( + { + "study_date": study_date, + "study_role": study_role, + "endpoint_name": endpoint_name, + "endpoint_domain": domain, + "endpoint_horizon_value": horizon, + "endpoint_horizon_unit": unit, + "symbol": symbol, + "continuity_id": continuity, + "observed_interval_id": continuity, + "observed_interval_start_ns": start, + "observed_interval_end_ns_exclusive": start + 3_600 * SECOND, + "decision_ts_ns": decision, + "decision_sequence": sequence, + "feature_cutoff_ts_ns": decision, + "max_feature_source_ts_ns": decision, + "max_feature_source_sequence": sequence, + "feature_continuity_id": continuity, + "label_start_ts_ns": decision, + "label_start_sequence": sequence, + "right_censored": censored, + "future_mid_return": None if censored else future_return, + "future_mid_up": None if censored else int(future_return > 0), + "label_information_end_ts_ns": None if censored else label_end, + "label_information_end_sequence": None if censored else sequence + horizon, + "label_continuity_id": None if censored else continuity, + "ofi_signed_future_mid_markout_bps": ( + None + if censored + else (1.0 if ofi > 0 else -1.0 if ofi < 0 else 0.0) * future_return * 10_000.0 + ), + "signed_markout_side_source": ( + "ofi_w20" if endpoint_name in {"event_20", "clock_1000ms"} else "ofi_w100" + ), + "sample_id": f"{study_date}::{symbol}::{endpoint_name}::{sequence}", + "mid_price": 100.0 + sequence * 0.01, + "bid_quantity": bid_quantity, + "ask_quantity": ask_quantity, + "spread_bps": spread, + "depth_total_l1": bid_quantity + ask_quantity, + "depth_total_l5": bid_quantity + ask_quantity + 10.0, + "depth_total_l10": bid_quantity + ask_quantity + 20.0, + "queue_imbalance_l1": (bid_quantity - ask_quantity) / (bid_quantity + ask_quantity), + "realized_volatility_w100": 0.001 + (sequence % 13) * 0.0001, + "ofi_w20": ofi, + "ofi_w100": ofi * 0.8, + "volatility_regime": ("low" if sequence % 3 == 0 else "high"), + "liquidity_regime": ("liquid" if sequence % 4 else "stressed"), + } + ) + return pl.DataFrame(rows, infer_schema_length=None) + + +def _all_frames() -> list[pl.DataFrame]: + return [ + _frame(study_date, role, symbol, name, domain, horizon, unit) + for study_date, role in DATES + for symbol in ("BTCUSDT", "ETHUSDT") + for name, domain, horizon, unit in ENDPOINTS + ] + + +def test_l2_descriptive_outputs_are_date_symbol_endpoint_explicit() -> None: + result = build_l2_descriptive_analysis( + _all_frames(), feature_columns=FEATURES, stability_bins=5 + ) + + assert result.intraday_liquidity.height == 8 * 3 + assert result.ofi_return_association.height == 32 + assert result.signal_half_life.height == 32 + assert result.liquidity_recovery.height == 16 + assert result.regime_diagnostics.height > 32 + assert result.feature_stability.height == 2 * 2 * 4 * len(FEATURES) + assert result.cross_instrument_stability.height == 16 + assert result.cross_instrument_stability.get_column("cross_instrument_pooling").not_().all() + assert set(result.ofi_return_association.get_column("interpretation").unique()) == { + "descriptive_book_flow_markout_not_trade_impact" + } + + +def test_shock_thresholds_and_stability_reference_are_development_only() -> None: + frames = _all_frames() + original = build_l2_descriptive_analysis(frames, feature_columns=FEATURES, stability_bins=5) + mutated = [ + frame.with_columns( + pl.when(pl.col("study_role").is_in(["primary_test", "replication_test"])) + .then(pl.col("spread_bps") * 100.0) + .otherwise(pl.col("spread_bps")) + .alias("spread_bps") + ) + for frame in frames + ] + changed = build_l2_descriptive_analysis(mutated, feature_columns=FEATURES, stability_bins=5) + + assert ( + original.liquidity_recovery.select( + "symbol", "train_spread_q95", "train_executable_depth_q05" + ) + .unique() + .sort("symbol") + .equals( + changed.liquidity_recovery.select( + "symbol", "train_spread_q95", "train_executable_depth_q05" + ) + .unique() + .sort("symbol") + ) + ) + assert set(changed.feature_stability.get_column("reference_scope").unique()) == { + "train_plus_validation_only" + } diff --git a/Microstructure/tests/test_l2_evaluation.py b/Microstructure/tests/test_l2_evaluation.py new file mode 100644 index 0000000000000000000000000000000000000000..efbad88426d8643f1f36a6281cc50dc3e2e57f35 --- /dev/null +++ b/Microstructure/tests/test_l2_evaluation.py @@ -0,0 +1,740 @@ +from __future__ import annotations + +import math +from dataclasses import replace +from datetime import datetime +from typing import Any, cast + +import numpy as np +import polars as pl +import pytest +from sklearn.dummy import DummyClassifier # type: ignore[import-untyped] +from sklearn.linear_model import LogisticRegression # type: ignore[import-untyped] +from sklearn.tree import DecisionTreeClassifier # type: ignore[import-untyped] + +from microstructure.config import ModelConfig +from microstructure.m8_l2_analysis_config import ( + M8_L2_ANALYSIS_CONFIG_SEMANTIC_SHA256, + M8_L2_ANALYSIS_CONFIG_SOURCE_SHA256, +) +from microstructure.research import l2_evaluation +from microstructure.research.l2_evaluation import ( + L2ExecutionReference, + L2HeldoutEndpointFrame, + L2LockedEvaluationError, + LockedL2EndpointState, + evaluate_locked_l2_endpoints, + run_locked_l2_market_execution, +) +from microstructure.research.l2_multidate import L2EndpointSpec +from microstructure.research.multidate import FinalFittedState, select_multidate_model + +_AGGREGATE_SHA = "a" * 64 +_REGIME_SHA = "b" * 64 +_ENDPOINTS = ( + L2EndpointSpec("event_20", "event", 20, "events", 40, None, 20), + L2EndpointSpec("event_100", "event", 100, "events", 200, None, 100), + L2EndpointSpec("clock_1000ms", "clock", 1_000, "milliseconds", None, 2_000, 20), + L2EndpointSpec("clock_5000ms", "clock", 5_000, "milliseconds", None, 10_000, 100), +) + + +def _date_start_ns(study_date: str) -> int: + return int(datetime.fromisoformat(f"{study_date}T00:00:00+00:00").timestamp() * 1_000_000_000) + + +def _development_frame(study_date: str, role: str, *, rows: int = 120) -> pl.DataFrame: + start = _date_start_ns(study_date) + 1_000_000_000 + continuity = f"{study_date}::development" + records: list[dict[str, object]] = [] + for index in range(rows): + decision = start + index * 10_000_000 + sequence = index + 1 + target = index % 2 + records.append( + { + "study_date": study_date, + "study_role": role, + "symbol": "BTCUSDT", + "decision_ts_ns": decision, + "decision_trade_id": sequence, + "decision_sequence": sequence, + "continuity_id": continuity, + "feature_continuity_id": continuity, + "label_continuity_id": continuity, + "max_feature_source_ts_ns": decision, + "max_feature_source_trade_id": sequence, + "label_start_ts_ns": decision, + "label_start_trade_id": sequence, + "label_information_end_ts_ns": decision + 1_000_000, + "label_information_end_trade_id": sequence + 1, + "feature_ready": True, + "right_censored": False, + "signal": 5.0 if target else -5.0, + "future_mid_up": target, + } + ) + return pl.DataFrame(records, infer_schema_length=None) + + +@pytest.fixture(scope="module") +def fitted_state() -> FinalFittedState: + selected = select_multidate_model( + ( + _development_frame("2026-08-10", "train"), + _development_frame("2026-08-11", "validation"), + ), + ModelConfig( + selection_metric="log_loss", + logistic_c_values=(1.0,), + tree_max_depth_values=(2,), + tree_min_samples_leaf=4, + ), + feature_columns=("signal",), + target="future_mid_up", + declared_test_dates=("2026-08-12", "2026-08-13"), + seed=20260807, + calibration_bins=10, + ) + assert selected.selected_model != "historical_prior" + return selected.fitted_state + + +def _locked_states( + fitted_state: FinalFittedState, + endpoints: tuple[L2EndpointSpec, ...] = _ENDPOINTS, +) -> tuple[LockedL2EndpointState, ...]: + return tuple( + LockedL2EndpointState( + symbol="BTCUSDT", + endpoint=endpoint, + child_lock_sha256=(f"{index + 1:064x}"), + aggregate_lock_sha256=_AGGREGATE_SHA, + regime_thresholds_sha256=_REGIME_SHA, + fitted_state=fitted_state, + ) + for index, endpoint in enumerate(endpoints) + ) + + +def _heldout_frame( + endpoint: L2EndpointSpec, + *, + study_date: str, + study_role: str, + aligned: bool, + rows_per_interval: int = 50, +) -> pl.DataFrame: + date_start = _date_start_ns(study_date) + records: list[dict[str, object]] = [] + for interval_index in range(2): + interval_start = date_start + (interval_index + 1) * 10_000_000_000 + interval_end = interval_start + 6_000_000_000 + interval_id = f"{study_date}::observed-{interval_index}" + for local_index in range(rows_per_interval): + row_index = interval_index * rows_per_interval + local_index + decision = interval_start + local_index * 100_000_000 + sequence = row_index + 1 + signal = 5.0 if aligned else -5.0 + records.append( + { + "study_date": study_date, + "study_role": study_role, + "endpoint_name": endpoint.name, + "endpoint_domain": endpoint.domain, + "endpoint_horizon_value": endpoint.horizon_value, + "endpoint_horizon_unit": endpoint.horizon_unit, + "symbol": "BTCUSDT", + "continuity_id": interval_id, + "observed_interval_id": interval_id, + "observed_interval_start_ns": interval_start, + "observed_interval_end_ns_exclusive": interval_end, + "decision_ts_ns": decision, + "decision_sequence": sequence, + "feature_cutoff_ts_ns": decision, + "max_feature_source_ts_ns": decision, + "max_feature_source_sequence": sequence, + "feature_continuity_id": interval_id, + "label_start_ts_ns": decision, + "label_start_sequence": sequence, + "right_censored": False, + "future_mid_return": 0.001, + "future_mid_up": 1, + "label_information_end_ts_ns": decision + 1_000_000, + "label_information_end_sequence": sequence + 1, + "label_continuity_id": interval_id, + "ofi_signed_future_mid_markout_bps": 1.25, + "sample_id": (f"BTCUSDT::{study_date}::{endpoint.name}::{sequence}"), + "feature_ready": True, + "signal": signal, + "volatility_regime": "low", + "liquidity_regime": "liquid", + "joint_market_regime": "low__liquid", + "best_bid": 99.99, + "best_ask": 100.01, + "bid_quantity": 0.4, + "ask_quantity": 0.4, + "mid_price": 100.0, + "tick_size": 0.01, + "lot_size": 0.1, + } + ) + return pl.DataFrame(records, infer_schema_length=None) + + +def _heldout_frames( + endpoints: tuple[L2EndpointSpec, ...] = _ENDPOINTS, + *, + replication_aligned: bool = True, +) -> tuple[L2HeldoutEndpointFrame, ...]: + values: list[L2HeldoutEndpointFrame] = [] + for endpoint in endpoints: + for study_date, role, aligned in ( + ("2026-08-12", "primary_test", True), + ("2026-08-13", "replication_test", replication_aligned), + ): + values.append( + L2HeldoutEndpointFrame( + symbol="BTCUSDT", + endpoint_name=endpoint.name, + study_date=study_date, + study_role=role, # type: ignore[arg-type] + frame=_heldout_frame( + endpoint, + study_date=study_date, + study_role=role, + aligned=aligned, + ), + ) + ) + return tuple(values) + + +def _forbid_fit(monkeypatch: pytest.MonkeyPatch) -> None: + def fail(*args: object, **kwargs: object) -> None: + del args, kwargs + raise AssertionError("locked evaluation must never fit") + + classifiers: tuple[type[object], ...] = ( + LogisticRegression, + DecisionTreeClassifier, + DummyClassifier, + ) + for classifier in classifiers: + monkeypatch.setattr(classifier, "fit", fail) + + +def _assert_strict_json_numbers(frame: pl.DataFrame) -> None: + for row in frame.to_dicts(): + for value in row.values(): + if isinstance(value, float): + assert math.isfinite(value) + + +def test_locked_evaluation_never_fits_and_uses_exact_endpoint_blocks( + fitted_state: FinalFittedState, + monkeypatch: pytest.MonkeyPatch, +) -> None: + states = _locked_states(fitted_state) + frames = _heldout_frames() + _forbid_fit(monkeypatch) + + result = evaluate_locked_l2_endpoints(states, frames) + + assert result.predictions.height == 800 + assert result.predictions["sample_id"].n_unique() == result.predictions.height + assert { + "selected_raw_probability", + "selected_probability", + "prior_raw_probability", + "prior_probability", + }.issubset(result.predictions.columns) + assert set(result.predictions["aggregate_lock_sha256"].unique()) == {_AGGREGATE_SHA} + assert not bool(result.predictions["test_used_for_selection"].any()) + assert not bool(result.predictions["model_updated_between_test_dates"].any()) + + overall = result.paired_by_session_regime.filter( + (pl.col("study_role") == "primary_test") & (pl.col("regime") == "ALL") + ) + observed = { + str(row["endpoint_name"]): ( + int(row["block_width"]), + str(row["block_unit"]), + int(row["n_blocks"]), + ) + for row in overall.to_dicts() + } + assert observed == { + "event_20": (40, "events", 22), + "event_100": (200, "events", 0), + "clock_1000ms": (2_000, "milliseconds", 82), + "clock_5000ms": (10_000, "milliseconds", 0), + } + assert set(overall["samples"].unique()) == {2_000} + assert not bool(result.paired_by_session_regime["p_value_computed"].any()) + assert result.paired_by_session_regime["p_value"].null_count() == ( + result.paired_by_session_regime.height + ) + assert not bool(result.paired_by_session_regime["cross_symbol_pooling"].any()) + + empty_regime = result.paired_by_session_regime.filter( + (pl.col("endpoint_name") == "event_20") & (pl.col("regime") == "medium__normal") + ) + assert empty_regime.height == 2 + assert set(empty_regime["bootstrap_status"].unique()) == {"empty_regime"} + assert set(empty_regime["n_obs"].unique()) == {0} + + summary = result.equal_session_summary.filter(pl.col("regime") == "ALL") + assert bool(summary["directionally_replicated"].all()) + assert set(summary["replication_status"].unique()) == {"replicated"} + for row in summary.to_dicts(): + expected_delta = 0.5 * float(row["primary_point_delta"]) + 0.5 * float( + row["replication_point_delta"] + ) + assert float(row["point_delta"]) == pytest.approx(expected_delta) + assert float(row["primary_point_delta"]) < 0.0 + assert float(row["replication_point_delta"]) < 0.0 + markout = result.signed_markout.filter( + (pl.col("endpoint_name") == "event_20") & (pl.col("regime") == "ALL") + ) + assert set(markout["mean_ofi_signed_future_mid_markout_bps"].unique()) == {1.25} + assert bool(markout["descriptive_only"].all()) + assert not bool(markout["observed_trade_impact"].any()) + for frame in ( + result.predictions, + result.predictive_metrics, + result.paired_by_session_regime, + result.equal_session_summary, + result.signed_markout, + ): + _assert_strict_json_numbers(frame) + + +def _moving_block_probe_frame(*, intervals: int, width: int) -> pl.DataFrame: + records: list[dict[str, object]] = [] + rows_per_interval = 2 * width + 1 + for interval_index in range(intervals): + interval_id = f"probe-{interval_index}" + interval_start = interval_index * 1_000_000_000 + for ordinal in range(rows_per_interval): + index = interval_index * rows_per_interval + ordinal + records.append( + { + "study_date": "2026-08-12", + "symbol": "BTCUSDT", + "continuity_id": interval_id, + "observed_interval_id": interval_id, + "observed_interval_start_ns": interval_start, + "observed_interval_end_ns_exclusive": interval_start + 1_000_000_000, + "decision_ts_ns": interval_start + ordinal * 1_000, + "decision_sequence": index + 1, + "_endpoint_event_ordinal": ordinal, + "joint_market_regime": "low__liquid", + "y_true": ordinal % 2, + "selected_probability": 0.15 + 0.7 * ((index % 7) / 7.0), + "prior_probability": 0.25 + 0.5 * ((index % 5) / 5.0), + } + ) + return pl.DataFrame(records, infer_schema_length=None) + + +def _independent_event_moving_block_draws( + frame: pl.DataFrame, + *, + width: int, + samples: int, + seed: int, +) -> np.ndarray: + random = np.random.default_rng(seed) + draws = np.empty(samples, dtype=np.float64) + interval_statistics: list[ + tuple[list[tuple[float, float, int]], list[tuple[float, float, int]] | None, int] + ] = [] + for current in frame.partition_by("observed_interval_id", maintain_order=True): + target = current["y_true"].to_numpy().astype(np.int64, copy=False) + selected_probability = np.clip( + current["selected_probability"].to_numpy(), 1e-12, 1.0 - 1e-12 + ) + prior_probability = np.clip(current["prior_probability"].to_numpy(), 1e-12, 1.0 - 1e-12) + selected = -( + target * np.log(selected_probability) + (1 - target) * np.log1p(-selected_probability) + ) + prior = -(target * np.log(prior_probability) + (1 - target) * np.log1p(-prior_probability)) + size = current.height + full = [ + ( + float(selected[start : start + width].sum()), + float(prior[start : start + width].sum()), + width, + ) + for start in range(size - width + 1) + ] + remainder = size % width + tail = ( + [ + ( + float(selected[start : start + remainder].sum()), + float(prior[start : start + remainder].sum()), + remainder, + ) + for start in range(size - width + 1) + ] + if remainder + else None + ) + interval_statistics.append((full, tail, math.ceil(size / width))) + for draw_index in range(samples): + selected_total = 0.0 + prior_total = 0.0 + count_total = 0 + for full, tail, blocks_per_draw in interval_statistics: + sampled = random.integers(0, len(full), size=blocks_per_draw) + for block_index, candidate_index in enumerate(sampled): + statistics = ( + tail[int(candidate_index)] + if tail is not None and block_index == blocks_per_draw - 1 + else full[int(candidate_index)] + ) + selected_total += statistics[0] + prior_total += statistics[1] + count_total += statistics[2] + draws[draw_index] = selected_total / count_total - prior_total / count_total + return draws + + +def _clock_moving_block_probe_frame(*, intervals: int, width_ms: int) -> pl.DataFrame: + records: list[dict[str, object]] = [] + rows_per_interval = 2 * width_ms + 1 + for interval_index in range(intervals): + interval_id = f"clock-probe-{interval_index}" + interval_start = interval_index * 1_000_000_000 + interval_end = interval_start + rows_per_interval * 1_000_000 + for ordinal in range(rows_per_interval): + index = interval_index * rows_per_interval + ordinal + records.append( + { + "study_date": "2026-08-12", + "symbol": "BTCUSDT", + "continuity_id": interval_id, + "observed_interval_id": interval_id, + "observed_interval_start_ns": interval_start, + "observed_interval_end_ns_exclusive": interval_end, + "decision_ts_ns": interval_start + ordinal * 1_000_000, + "decision_sequence": index + 1, + "_endpoint_event_ordinal": ordinal, + "joint_market_regime": "low__liquid", + "y_true": ordinal % 2, + "selected_probability": 0.15 + 0.7 * ((index % 7) / 7.0), + "prior_probability": 0.25 + 0.5 * ((index % 5) / 5.0), + } + ) + return pl.DataFrame(records, infer_schema_length=None) + + +def _independent_clock_moving_block_draws( + frame: pl.DataFrame, + *, + width_ms: int, + samples: int, + seed: int, +) -> np.ndarray: + random = np.random.default_rng(seed) + draws = np.empty(samples, dtype=np.float64) + width_ns = width_ms * 1_000_000 + interval_statistics: list[tuple[list[tuple[float, float, int]], int]] = [] + for current in frame.partition_by("observed_interval_id", maintain_order=True): + target = current["y_true"].to_numpy().astype(np.int64, copy=False) + selected_probability = np.clip( + current["selected_probability"].to_numpy(), 1e-12, 1.0 - 1e-12 + ) + prior_probability = np.clip(current["prior_probability"].to_numpy(), 1e-12, 1.0 - 1e-12) + selected = -( + target * np.log(selected_probability) + (1 - target) * np.log1p(-selected_probability) + ) + prior = -(target * np.log(prior_probability) + (1 - target) * np.log1p(-prior_probability)) + times = current["decision_ts_ns"].to_numpy() + interval_start = int(current["observed_interval_start_ns"][0]) + interval_end = int(current["observed_interval_end_ns_exclusive"][0]) + candidates: list[tuple[float, float, int]] = [] + for start in times: + if int(start) + width_ns > interval_end: + continue + members = (times >= start) & (times < start + width_ns) + candidates.append( + ( + float(selected[members].sum()), + float(prior[members].sum()), + int(np.count_nonzero(members)), + ) + ) + interval_statistics.append( + (candidates, math.ceil((interval_end - interval_start) / width_ns)) + ) + for draw_index in range(samples): + selected_total = 0.0 + prior_total = 0.0 + count_total = 0 + for candidates, blocks_per_draw in interval_statistics: + sampled = random.integers(0, len(candidates), size=blocks_per_draw) + for candidate_index in sampled: + statistics = candidates[int(candidate_index)] + selected_total += statistics[0] + prior_total += statistics[1] + count_total += statistics[2] + draws[draw_index] = selected_total / count_total - prior_total / count_total + return draws + + +def test_event_moving_blocks_overlap_truncate_and_draw_locally_by_interval() -> None: + width = 4 + samples = 31 + seed = 91_337 + endpoint = L2EndpointSpec("probe", "event", 2, "events", width, None, 2) + + one_interval = _moving_block_probe_frame(intervals=1, width=width) + one = l2_evaluation._paired_delta( + one_interval, + endpoint, + regime="ALL", + samples=samples, + seed=seed, + ) + assert one.status == "ok" + assert one.n_blocks == width + 2 + np.testing.assert_allclose( + one.draws, + _independent_event_moving_block_draws( + one_interval, + width=width, + samples=samples, + seed=seed, + ), + rtol=0.0, + atol=2e-15, + ) + + sparse_regime = one_interval.with_columns( + pl.when(pl.col("_endpoint_event_ordinal") % 2 == 0) + .then(pl.lit("low__liquid")) + .otherwise(pl.lit("medium__normal")) + .alias("joint_market_regime") + ) + sparse = l2_evaluation._paired_delta( + sparse_regime, + endpoint, + regime="low__liquid", + samples=samples, + seed=seed, + ) + assert sparse.n_obs == width + 1 + assert sparse.n_blocks == width + 2 + + two_intervals = _moving_block_probe_frame(intervals=2, width=width) + two = l2_evaluation._paired_delta( + two_intervals, + endpoint, + regime="ALL", + samples=samples, + seed=seed, + ) + assert two.n_blocks == 2 * (width + 2) + np.testing.assert_allclose( + two.draws, + _independent_event_moving_block_draws( + two_intervals, + width=width, + samples=samples, + seed=seed, + ), + rtol=0.0, + atol=2e-15, + ) + + +def test_clock_moving_blocks_use_legal_half_open_interval_local_windows() -> None: + width_ms = 4 + samples = 31 + seed = 29_771 + endpoint = L2EndpointSpec("probe", "clock", 2, "milliseconds", None, width_ms, 2) + frame = _clock_moving_block_probe_frame(intervals=2, width_ms=width_ms) + + result = l2_evaluation._paired_delta( + frame, + endpoint, + regime="ALL", + samples=samples, + seed=seed, + ) + + assert result.status == "ok" + assert result.n_blocks == 2 * (width_ms + 2) + np.testing.assert_allclose( + result.draws, + _independent_clock_moving_block_draws( + frame, + width_ms=width_ms, + samples=samples, + seed=seed, + ), + rtol=0.0, + atol=2e-15, + ) + + +def test_directional_replication_requires_negative_delta_on_both_dates( + fitted_state: FinalFittedState, +) -> None: + endpoint = (_ENDPOINTS[0],) + result = evaluate_locked_l2_endpoints( + _locked_states(fitted_state, endpoint), + _heldout_frames(endpoint, replication_aligned=False), + ) + row = result.equal_session_summary.filter(pl.col("regime") == "ALL").row(0, named=True) + assert float(row["primary_point_delta"]) < 0.0 + assert float(row["replication_point_delta"]) > 0.0 + assert row["directionally_replicated"] is False + assert row["replication_status"] == "failed_replication" + + +def test_reference_is_formula_checked_config_bound_and_payload_hashed() -> None: + reference = L2ExecutionReference.create( + symbol="BTCUSDT", + training_date="2026-08-10", + reference_mid_price=100.0, + train_l1_depth_q05=20.0, + lot_size=0.1, + reference_quantity=1.0, + aggregate_lock_sha256=_AGGREGATE_SHA, + ) + assert reference.reference_price_statistic == "train_median_mid_price" + assert reference.reference_depth_statistic == "train_q05_min_bid_ask_l1_depth" + assert reference.analysis_config_source_sha256 == M8_L2_ANALYSIS_CONFIG_SOURCE_SHA256 + assert reference.analysis_config_semantic_sha256 == M8_L2_ANALYSIS_CONFIG_SEMANTIC_SHA256 + with pytest.raises(L2LockedEvaluationError, match="formula"): + replace(reference, reference_quantity=0.9) + with pytest.raises(L2LockedEvaluationError, match="payload"): + replace(reference, train_l1_depth_q05=21.0) + with pytest.raises(L2LockedEvaluationError, match="median midpoint"): + replace(reference, reference_price_statistic="heldout_midpoint") + + +def test_market_only_execution_grid_reconciles_and_never_authorizes_claims( + fitted_state: FinalFittedState, + monkeypatch: pytest.MonkeyPatch, +) -> None: + endpoint = (_ENDPOINTS[0],) + states = _locked_states(fitted_state, endpoint) + frames = _heldout_frames(endpoint) + evaluation = evaluate_locked_l2_endpoints(states, frames) + reference = L2ExecutionReference.create( + symbol="BTCUSDT", + training_date="2026-08-10", + reference_mid_price=100.0, + train_l1_depth_q05=20.0, + lot_size=0.1, + reference_quantity=1.0, + aggregate_lock_sha256=_AGGREGATE_SHA, + ) + _forbid_fit(monkeypatch) + + execution = run_locked_l2_market_execution(evaluation, frames, (reference,)) + + assert execution.metrics.height == 18 + assert set(execution.metrics["decision_latency_events"].unique()) == {0, 1, 5} + assert set(execution.metrics["order_latency_events"].unique()) == {0, 1, 5} + assert set(execution.orders["order_type"].drop_nulls().unique()) == {"market"} + assert set(execution.fills["liquidity"].drop_nulls().unique()) == {"taker"} + assert float(cast(Any, execution.fills["quantity"].max())) <= 0.4 + 1e-12 + assert "partially_filled_canceled" in set(execution.orders["status"].unique()) + assert "canceled_continuity_gap" in set(execution.orders["status"].unique()) + assert "forced_liquidation" in set(execution.orders["status"].unique()) + assert float(cast(Any, execution.metrics["maximum_absolute_inventory"].max())) <= 10.0 + 1e-12 + for column in ("fill_ratio", "fill_ratio_requested", "partial_fill_order_ratio"): + observed = execution.metrics.get_column(column).drop_nulls() + assert len(observed) > 0 + assert bool(((observed >= 0.0) & (observed <= 1.0)).all()) + + first_order = execution.orders.group_by("scenario_id").agg( + pl.col("order_id").min().alias("first_order_id") + ) + assert set(first_order["first_order_id"].unique()) == {1} + strategy_fills = ( + execution.fills.filter(~pl.col("forced_liquidation")) + .group_by("scenario_id") + .agg( + pl.col("quantity").sum().alias("ledger_filled_quantity"), + pl.col("fee").sum().alias("ledger_strategy_fees"), + ) + ) + reconciled = execution.metrics.join(strategy_fills, on="scenario_id", how="left") + assert bool( + reconciled.select( + (pl.col("filled_quantity") - pl.col("ledger_filled_quantity")).abs().max().le(1e-12) + ).item() + ) + fee_reconciliation = execution.fills.group_by("scenario_id").agg( + pl.col("fee").sum().alias("ledger_total_fees") + ) + reconciled = execution.metrics.join(fee_reconciliation, on="scenario_id", how="left") + assert bool( + reconciled.select( + (pl.col("total_fees") - pl.col("ledger_total_fees")).abs().max().le(1e-12) + ).item() + ) + assert bool( + execution.fills.select( + (pl.col("fee") - pl.col("notional") * pl.lit(4.0 / 10_000.0)).abs().max().le(1e-12) + ).item() + ) + assert bool( + execution.metrics.select( + (pl.col("net_pnl") - (pl.col("gross_pnl") - pl.col("total_fees"))).abs().max().le(1e-12) + ).item() + ) + + for frame in (execution.metrics, execution.assumptions): + assert not bool(frame["capacity_claim_authorized"].any()) + assert not bool(frame["realized_execution_claim_authorized"].any()) + assert not bool(frame["profitability_claim_authorized"].any()) + assert set(frame["aggregate_lock_sha256"].unique()) == {_AGGREGATE_SHA} + for frame in ( + execution.orders, + execution.fills, + execution.positions, + execution.metrics, + execution.assumptions, + ): + _assert_strict_json_numbers(frame) + assert set(execution.assumptions["limit_fill_model"].unique()) == {"NOT_RUN"} + assert set(execution.assumptions["capacity_sensitivity"].unique()) == {"NOT_RUN"} + assert set(execution.assumptions["reference_price_statistic"].unique()) == { + "train_median_mid_price" + } + assert set(execution.assumptions["reference_depth_statistic"].unique()) == { + "train_q05_min_bid_ask_l1_depth" + } + with pytest.raises(L2LockedEvaluationError, match="latency grids"): + run_locked_l2_market_execution( + evaluation, + frames, + (reference,), + decision_latency_events=(0, 1, 4), + ) + + +def test_tampered_endpoint_width_and_observed_interval_identity_fail_closed( + fitted_state: FinalFittedState, +) -> None: + wrong = L2EndpointSpec("event_20", "event", 20, "events", 41, None, 20) + with pytest.raises(L2LockedEvaluationError, match="frozen M8 L2 endpoint"): + _locked_states(fitted_state, (wrong,)) + + endpoint = (_ENDPOINTS[0],) + states = _locked_states(fitted_state, endpoint) + frames = list(_heldout_frames(endpoint)) + damaged = frames[0].frame.with_columns( + pl.lit("different-observed-interval").alias("observed_interval_id") + ) + frames[0] = replace(frames[0], frame=damaged) + with pytest.raises(L2LockedEvaluationError, match="observed-interval identity"): + evaluate_locked_l2_endpoints(states, frames) diff --git a/Microstructure/tests/test_l2_multidate.py b/Microstructure/tests/test_l2_multidate.py new file mode 100644 index 0000000000000000000000000000000000000000..33fd06203f975be70f85260c176564223db1f984 --- /dev/null +++ b/Microstructure/tests/test_l2_multidate.py @@ -0,0 +1,417 @@ +from __future__ import annotations + +import math +from datetime import UTC, datetime + +import polars as pl +import pytest + +from microstructure.research.l2_multidate import ( + L2EndpointSpec, + L2ObservedInterval, + L2ResearchError, + apply_l2_regimes, + build_l2_endpoint_frames, + dependency_block_expression, + fit_l2_regime_thresholds, + l2_model_feature_columns, + validate_l2_endpoint_frame, +) + +MILLISECOND = 1_000_000 +SECOND = 1_000_000_000 +DATE = "2026-08-08" +DATE_START = int(datetime(2026, 8, 8, tzinfo=UTC).timestamp()) * SECOND + + +def _endpoints() -> tuple[L2EndpointSpec, ...]: + return ( + L2EndpointSpec("event_20", "event", 20, "events", 40, None, 20), + L2EndpointSpec("event_100", "event", 100, "events", 200, None, 100), + L2EndpointSpec("clock_1000ms", "clock", 1_000, "milliseconds", None, 2_000, 20), + L2EndpointSpec("clock_5000ms", "clock", 5_000, "milliseconds", None, 10_000, 100), + ) + + +def _inputs() -> tuple[pl.DataFrame, pl.DataFrame, tuple[L2ObservedInterval, ...]]: + times = [DATE_START + index * 100 * MILLISECOND for index in range(300)] + second_start = DATE_START + 60 * SECOND + times.extend(second_start + index * 100 * MILLISECOND for index in range(300)) + sequences = list(range(1, len(times) + 1)) + midpoint = [100.0 + index * 0.001 + (index // 17) * 0.002 for index in sequences] + bid = [value - 0.01 for value in midpoint] + ask = [value + 0.01 for value in midpoint] + bid_quantity = [4.0 + (index % 11) * 0.1 for index in sequences] + ask_quantity = [3.0 + (index % 7) * 0.1 for index in sequences] + books = pl.DataFrame( + { + "venue": ["binance_spot"] * len(times), + "symbol": ["BTCUSDT"] * len(times), + "event_ts_ns": times, + "available_ts_ns": times, + "continuity_id": ["capture-a"] * len(times), + "sequence_end": sequences, + "is_valid": [True] * len(times), + "best_bid": bid, + "best_ask": ask, + "bid_quantity": bid_quantity, + "ask_quantity": ask_quantity, + "depth_bid_5": [value + 8.0 for value in bid_quantity], + "depth_ask_5": [value + 7.0 for value in ask_quantity], + "depth_bid_10": [value + 18.0 for value in bid_quantity], + "depth_ask_10": [value + 17.0 for value in ask_quantity], + "tick_size": [0.01] * len(times), + "lot_size": [0.00001] * len(times), + } + ) + deltas = pl.DataFrame( + { + "venue": ["binance_spot"] * len(times), + "symbol": ["BTCUSDT"] * len(times), + "event_ts_ns": times, + "available_ts_ns": times, + "continuity_id": ["capture-a"] * len(times), + "first_update_id": sequences, + "last_update_id": sequences, + "bids": [ + [ + { + "price_ticks": 10_000 + index, + "quantity_lots": 0 if index % 13 == 0 else 10, + } + ] + for index in sequences + ], + "asks": [[{"price_ticks": 10_002 + index, "quantity_lots": 10}] for index in sequences], + } + ) + intervals = ( + L2ObservedInterval("capture-a", DATE_START, DATE_START + 30 * SECOND), + L2ObservedInterval("capture-a", second_start, second_start + 30 * SECOND), + ) + return books, deltas, intervals + + +def _frames( + *, books: pl.DataFrame | None = None, deltas: pl.DataFrame | None = None +) -> dict[str, pl.DataFrame]: + default_books, default_deltas, intervals = _inputs() + return dict( + build_l2_endpoint_frames( + default_books if books is None else books, + default_deltas if deltas is None else deltas, + intervals, + study_date=DATE, + study_role="train", + feature_windows=(20, 100), + volatility_window=100, + clock_max_state_age_ms=500, + endpoints=_endpoints(), + ) + ) + + +def _tied_target_inputs() -> tuple[ + pl.DataFrame, + pl.DataFrame, + tuple[L2ObservedInterval, ...], + int, + int, + int, + int, +]: + books, deltas, intervals = _inputs() + decision_ts = DATE_START + 20 * SECOND + target_ts = decision_ts + SECOND + target_sequences = ( + books.filter(pl.col("available_ts_ns") == target_ts).get_column("sequence_end").to_list() + ) + assert len(target_sequences) == 1 + lower_sequence = int(target_sequences[0]) + higher_sequence = lower_sequence + 1 + books = books.with_columns( + pl.when(pl.col("sequence_end") == higher_sequence) + .then(pl.lit(target_ts)) + .otherwise(pl.col("event_ts_ns")) + .alias("event_ts_ns"), + pl.when(pl.col("sequence_end") == higher_sequence) + .then(pl.lit(target_ts)) + .otherwise(pl.col("available_ts_ns")) + .alias("available_ts_ns"), + ) + deltas = deltas.with_columns( + pl.when(pl.col("last_update_id") == higher_sequence) + .then(pl.lit(target_ts)) + .otherwise(pl.col("event_ts_ns")) + .alias("event_ts_ns"), + pl.when(pl.col("last_update_id") == higher_sequence) + .then(pl.lit(target_ts)) + .otherwise(pl.col("available_ts_ns")) + .alias("available_ts_ns"), + ) + return ( + books, + deltas, + intervals, + decision_ts, + target_ts, + lower_sequence, + higher_sequence, + ) + + +def _tied_target_frames() -> dict[str, pl.DataFrame]: + books, deltas, intervals, *_ = _tied_target_inputs() + endpoints = ( + L2EndpointSpec("event_1", "event", 1, "events", 1, None, 1), + L2EndpointSpec("clock_1000ms", "clock", 1_000, "milliseconds", None, 2_000, 1), + ) + return dict( + build_l2_endpoint_frames( + books, + deltas, + intervals, + study_date=DATE, + study_role="train", + feature_windows=(1,), + volatility_window=1, + clock_max_state_age_ms=500, + endpoints=endpoints, + ) + ) + + +def test_four_endpoints_are_interval_local_and_exclude_trade_only_features() -> None: + frames = _frames() + assert set(frames) == {"event_20", "event_100", "clock_1000ms", "clock_5000ms"} + + event = frames["event_20"] + assert event.get_column("continuity_id").n_unique() == 2 + assert event.get_column("capture_continuity_id").unique().to_list() == ["capture-a"] + assert event.group_by("continuity_id").len().get_column("len").to_list() == [300, 300] + assert event.group_by("continuity_id").agg( + pl.col("right_censored").sum().alias("censored") + ).get_column("censored").to_list() == [20, 20] + + regime = fit_l2_regime_thresholds( + event, + lower_quantile=1.0 / 3.0, + upper_quantile=2.0 / 3.0, + volatility_column="realized_volatility_w100", + ) + modeled = apply_l2_regimes(event, regime) + features = l2_model_feature_columns(modeled, windows=(20, 100)) + assert "depth_total_l10" in features + assert "cancellation_intensity_w100" in features + assert "volatility_regime_high" in features + assert not any("trade_" in name for name in features) + + +def test_exact_clock_target_uses_last_known_state_and_never_looks_forward() -> None: + books, deltas, _ = _inputs() + decision_ts = DATE_START + 20 * SECOND + target_ts = decision_ts + SECOND + target_sequence = int( + books.filter(pl.col("available_ts_ns") == target_ts).get_column("sequence_end")[0] + ) + prior_mid = float( + books.filter(pl.col("available_ts_ns") == target_ts - 100 * MILLISECOND).get_column( + "best_bid" + )[0] + + 0.01 + ) + books_without_exact_target = books.filter(pl.col("available_ts_ns") != target_ts) + frame = _frames(books=books_without_exact_target, deltas=deltas)["clock_1000ms"] + row = frame.filter(pl.col("decision_ts_ns") == decision_ts).row(0, named=True) + + assert row["right_censored"] is False + assert row["label_information_end_ts_ns"] == target_ts + assert row["label_information_end_sequence"] == target_sequence - 1 + assert row["clock_target_state_age_ns"] == 100 * MILLISECOND + current_mid = float(row["mid_price"]) + assert row["future_mid_return"] == pytest.approx(math.log(prior_mid / current_mid)) + + +def test_tied_timestamp_event_label_uses_lexicographic_future_order() -> None: + *_, target_ts, lower_sequence, higher_sequence = _tied_target_inputs() + frame = _tied_target_frames()["event_1"] + row = frame.filter(pl.col("decision_sequence") == lower_sequence).row(0, named=True) + + assert row["decision_ts_ns"] == target_ts + assert row["right_censored"] is False + assert row["label_information_end_ts_ns"] == target_ts + assert row["label_information_end_sequence"] == higher_sequence + + for invalid_sequence in (lower_sequence, lower_sequence - 1): + corrupted = frame.with_columns( + pl.when(pl.col("decision_sequence") == lower_sequence) + .then(pl.lit(invalid_sequence)) + .otherwise(pl.col("label_information_end_sequence")) + .alias("label_information_end_sequence") + ) + with pytest.raises(L2ResearchError, match="strictly future"): + validate_l2_endpoint_frame(corrupted) + + +def test_exact_clock_target_tie_selects_greatest_observable_sequence() -> None: + books, _, _, decision_ts, target_ts, _, higher_sequence = _tied_target_inputs() + frame = _tied_target_frames()["clock_1000ms"] + row = frame.filter(pl.col("decision_ts_ns") == decision_ts).row(0, named=True) + expected_mid = float( + ( + books.filter(pl.col("sequence_end") == higher_sequence).get_column("best_bid")[0] + + books.filter(pl.col("sequence_end") == higher_sequence).get_column("best_ask")[0] + ) + / 2.0 + ) + + assert row["right_censored"] is False + assert row["label_information_end_ts_ns"] == target_ts + assert row["label_information_end_sequence"] == higher_sequence + assert row["clock_target_state_age_ns"] == 0 + assert row["future_mid_return"] == pytest.approx(math.log(expected_mid / row["mid_price"])) + + +def test_same_timestamp_higher_sequence_mutation_cannot_change_past_features() -> None: + books, deltas, intervals, _, target_ts, lower_sequence, higher_sequence = _tied_target_inputs() + endpoint = L2EndpointSpec("event_1", "event", 1, "events", 1, None, 1) + + def build(candidate: pl.DataFrame) -> pl.DataFrame: + return build_l2_endpoint_frames( + candidate, + deltas, + intervals, + study_date=DATE, + study_role="train", + feature_windows=(1,), + volatility_window=1, + clock_max_state_age_ms=500, + endpoints=(endpoint,), + )["event_1"] + + original = build(books) + mutated = build( + books.with_columns( + pl.when(pl.col("sequence_end") == higher_sequence) + .then(pl.col("best_bid") * 3.0) + .otherwise(pl.col("best_bid")) + .alias("best_bid"), + pl.when(pl.col("sequence_end") == higher_sequence) + .then(pl.col("best_ask") * 3.0) + .otherwise(pl.col("best_ask")) + .alias("best_ask"), + ) + ) + causal_prefix = (pl.col("decision_ts_ns") < target_ts) | ( + (pl.col("decision_ts_ns") == target_ts) & (pl.col("decision_sequence") <= lower_sequence) + ) + feature_columns = [ + "sample_id", + "mid_price", + "spread_bps", + "ofi_w1", + "realized_volatility_w1", + "max_feature_source_ts_ns", + "max_feature_source_sequence", + ] + assert ( + original.filter(causal_prefix) + .select(feature_columns) + .equals(mutated.filter(causal_prefix).select(feature_columns)) + ) + + +def test_clock_target_outside_interval_or_too_stale_is_censored() -> None: + books, deltas, _ = _inputs() + near_end = DATE_START + 27 * SECOND + five_second = _frames(books=books, deltas=deltas)["clock_5000ms"] + assert five_second.filter(pl.col("decision_ts_ns") == near_end).get_column("right_censored")[0] + + decision_ts = DATE_START + 20 * SECOND + target_ts = decision_ts + SECOND + stale_books = books.filter( + (pl.col("available_ts_ns") <= target_ts - 600 * MILLISECOND) + | (pl.col("available_ts_ns") > target_ts) + ) + stale = _frames(books=stale_books, deltas=deltas)["clock_1000ms"] + row = stale.filter(pl.col("decision_ts_ns") == decision_ts).row(0, named=True) + assert row["right_censored"] is True + assert row["future_mid_return"] is None + assert row["label_information_end_ts_ns"] is None + + +def test_future_price_mutation_cannot_change_past_l2_features() -> None: + books, deltas, _ = _inputs() + cutoff = DATE_START + 20 * SECOND + original = _frames(books=books, deltas=deltas)["event_20"] + mutated_books = books.with_columns( + pl.when(pl.col("available_ts_ns") > cutoff) + .then(pl.col("best_bid") * 3.0) + .otherwise(pl.col("best_bid")) + .alias("best_bid"), + pl.when(pl.col("available_ts_ns") > cutoff) + .then(pl.col("best_ask") * 3.0) + .otherwise(pl.col("best_ask")) + .alias("best_ask"), + ) + mutated = _frames(books=mutated_books, deltas=deltas)["event_20"] + feature_columns = [ + "spread_bps", + "depth_total_l1", + "queue_imbalance_l1", + "microprice_deviation_bps", + "ofi_w20", + "cancellation_intensity_w20", + "realized_volatility_w100", + "max_feature_source_ts_ns", + ] + assert ( + original.filter(pl.col("decision_ts_ns") <= cutoff) + .select(feature_columns) + .equals(mutated.filter(pl.col("decision_ts_ns") <= cutoff).select(feature_columns)) + ) + + +def test_train_regimes_reject_validation_fit_and_blocks_are_deterministic() -> None: + event = _frames()["event_20"] + with pytest.raises(L2ResearchError, match="train session"): + fit_l2_regime_thresholds( + event.with_columns(pl.lit("validation").alias("study_role")), + lower_quantile=1.0 / 3.0, + upper_quantile=2.0 / 3.0, + volatility_column="realized_volatility_w100", + ) + + blocked = event.with_columns(dependency_block_expression(_endpoints()[0])) + assert blocked.get_column("bootstrap_block").null_count() == 0 + assert blocked.select("sample_id", "bootstrap_block").equals( + event.with_columns(dependency_block_expression(_endpoints()[0])).select( + "sample_id", "bootstrap_block" + ) + ) + + +def test_temporal_validator_rejects_label_crossing_observed_interval() -> None: + frame = _frames()["event_20"] + row_id = str(frame.filter(~pl.col("right_censored")).get_column("sample_id")[0]) + corrupted = frame.with_columns( + pl.when(pl.col("sample_id") == row_id) + .then(pl.col("observed_interval_end_ns_exclusive")) + .otherwise(pl.col("label_information_end_ts_ns")) + .alias("label_information_end_ts_ns") + ) + with pytest.raises(L2ResearchError, match="interval-local"): + validate_l2_endpoint_frame(corrupted) + + +def test_temporal_validator_rejects_same_timestamp_future_feature_sequence() -> None: + frame = _tied_target_frames()["event_1"] + *_, lower_sequence, _ = _tied_target_inputs() + corrupted = frame.with_columns( + pl.when(pl.col("decision_sequence") == lower_sequence) + .then(pl.col("decision_sequence") + 1) + .otherwise(pl.col("max_feature_source_sequence")) + .alias("max_feature_source_sequence") + ) + with pytest.raises(L2ResearchError, match="base timing"): + validate_l2_endpoint_frame(corrupted) diff --git a/Microstructure/tests/test_l2_reporting.py b/Microstructure/tests/test_l2_reporting.py new file mode 100644 index 0000000000000000000000000000000000000000..b1ed9d1892afcfb17770568737f8a74dd8dca8ae --- /dev/null +++ b/Microstructure/tests/test_l2_reporting.py @@ -0,0 +1,217 @@ +from __future__ import annotations + +from dataclasses import replace +from pathlib import Path + +import pytest + +from microstructure.reporting.l2 import ( + L2ReportData, + L2ReportError, + canonical_report_data_sha256, + render_l2_executive_memo, + render_l2_model_comparison, + render_l2_technical_report, + write_l2_report_set, +) + + +def _data() -> L2ReportData: + manifest = { + "status": "COMPLETE", + "evidence_tier": "FULL_DATA", + "effective_evidence_tier": "FULL_DATA", + "live_trading": False, + "research": { + "question": "Do causal L2 states improve future-mid direction log loss?", + "period_start_utc": "2026-08-10T14:00:00Z", + "period_end_utc": "2026-08-13T15:00:00Z", + }, + } + provenance = { + "git": {"commit": "a" * 40, "source_tree_sha256": "b" * 64, "dirty": False}, + "inputs": { + "capture_config_sha256": "c" * 64, + "capture_protocol_sha256": "d" * 64, + "analysis_config_sha256": "e" * 64, + "development_lock_sha256": "f" * 64, + }, + } + session_gates = tuple( + { + "study_date": f"2026-08-{day:02d}", + "study_role": role, + "status": "COMPLETE", + "BTCUSDT_gate": "passed", + "ETHUSDT_gate": "passed", + "overlap_seconds": 3_590.0, + } + for day, role in ( + (8, "train"), + (9, "validation"), + (10, "primary_test"), + (11, "replication_test"), + ) + ) + predictive = ( + { + "symbol": "BTCUSDT", + "endpoint_name": "event_20", + "study_date": "2026-08-12", + "selected_model": "logistic_l2_c_1", + "n_obs": 400, + "selected_log_loss": 0.65, + "prior_log_loss": 0.69, + "point_delta": -0.04, + "selected_brier_score": 0.23, + "selected_expected_calibration_error": 0.02, + }, + ) + paired = ( + { + "symbol": "BTCUSDT", + "endpoint_name": "event_20", + "study_date": "2026-08-12", + "n_obs": 400, + "n_blocks": 10, + "point_delta": -0.04, + "ci_low": -0.08, + "ci_high": 0.01, + "status": "ok", + "regime": "ALL", + }, + ) + equal = ( + { + **{key: value for key, value in paired[0].items() if key != "study_date"}, + "directionally_replicated": True, + }, + ) + execution = ( + { + "symbol": "BTCUSDT", + "endpoint_name": "event_20", + "study_date": "2026-08-12", + "decision_latency_events": 0, + "order_latency_events": 1, + "strategy_orders": 20, + "fill_ratio": 0.8, + "turnover_notional": 1_000.0, + "marked_net_pnl": -2.0, + "unliquidated_quantity": 0.0, + }, + ) + return L2ReportData( + manifest=manifest, + provenance=provenance, + session_gates=session_gates, + hypothesis={ + "conclusion": "The endpoint improved on primary and replication sessions.", + "directionally_replicated_pairs": 1, + }, + predictive_metrics=predictive, + paired_metrics=paired, + equal_session_metrics=equal, + execution_metrics=execution, + ) + + +def test_l2_reports_are_artifact_driven_and_keep_claim_boundaries() -> None: + data = _data() + technical = render_l2_technical_report(data) + memo = render_l2_executive_memo(data) + comparison = render_l2_model_comparison(data) + + for report in (technical, memo, comparison): + assert "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" in report + assert "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" in report + assert "no refit" in report.lower() or "without update" in report.lower() + assert "not realized execution" in technical.lower() + assert "no capacity or profitability claim" in technical.lower() + assert "Directionally replicated symbol/endpoint pairs: **1**" in memo + assert "2026-08-12 / ALL" in technical + assert "equal-session / ALL" in comparison + assert "0.650000" in comparison + assert len(canonical_report_data_sha256(data)) == 64 + + +def test_l2_report_set_is_deterministic_and_complete(tmp_path: Path) -> None: + paths = write_l2_report_set(tmp_path, _data()) + first = [path.read_bytes() for path in paths] + repeated = write_l2_report_set(tmp_path, _data()) + + assert paths == repeated + assert [path.read_bytes() for path in repeated] == first + assert {path.name for path in paths} == { + "technical_report.md", + "executive_memo.md", + "model_comparison.md", + } + + +def test_l2_reports_reject_promoted_or_underspecified_authority() -> None: + data = _data() + with pytest.raises(L2ReportError, match="FULL_DATA"): + render_l2_technical_report( + replace( + data, + manifest={**data.manifest, "evidence_tier": "PUBLIC_SAMPLE_PARTIAL"}, + ) + ) + + with pytest.raises(L2ReportError, match="conclusion"): + render_l2_executive_memo(replace(data, hypothesis={})) + + +def test_l2_report_counts_only_overall_pairs_and_labels_insufficient_data() -> None: + data = _data() + duplicated_regime = { + **data.equal_session_metrics[0], + "regime": "HIGH_SPREAD__HIGH_VOLATILITY", + "directionally_replicated": True, + } + memo = render_l2_executive_memo( + replace(data, equal_session_metrics=(*data.equal_session_metrics, duplicated_regime)) + ) + assert "Directionally replicated symbol/endpoint pairs: **1**" in memo + + insufficient_manifest = { + **data.manifest, + "status": "INSUFFICIENT_DATA", + "effective_evidence_tier": "INSUFFICIENT_DATA", + } + insufficient = replace( + data, + manifest=insufficient_manifest, + hypothesis={ + "conclusion": "The frozen study is INSUFFICIENT_DATA.", + "directionally_replicated_pairs": 0, + }, + predictive_metrics=(), + paired_metrics=(), + equal_session_metrics=(), + execution_metrics=(), + ) + technical = render_l2_technical_report(insufficient) + assert "INSUFFICIENT_DATA" in technical + assert "FULL-DATA PUBLIC L2 RESEARCH" not in technical + + +def test_l2_report_rejects_replicated_pair_count_mismatch() -> None: + with pytest.raises(L2ReportError, match="replicated-pair count"): + render_l2_executive_memo( + replace( + _data(), + hypothesis={ + "conclusion": "Mismatch.", + "directionally_replicated_pairs": 2, + }, + ) + ) + + +def test_l2_report_rejects_invalid_execution_fill_ratio() -> None: + data = _data() + invalid = ({**data.execution_metrics[0], "fill_ratio": 1.01},) + with pytest.raises(L2ReportError, match=r"\[0, 1\]"): + render_l2_technical_report(replace(data, execution_metrics=invalid)) diff --git a/Microstructure/tests/test_labels.py b/Microstructure/tests/test_labels.py new file mode 100644 index 0000000000000000000000000000000000000000..00d5a3feebaaf2549d6c2c5f090ee5ea4f059864 --- /dev/null +++ b/Microstructure/tests/test_labels.py @@ -0,0 +1,214 @@ +from __future__ import annotations + +import math + +import polars as pl +import pytest + +from microstructure.research.labels import ( + AdverseSelectionSpec, + ClockTimeLabelSpec, + LimitFillAssumptions, + add_event_time_price_impact_labels, + build_clock_time_mid_labels, + build_clock_time_price_impact_labels, + build_hypothetical_limit_fill_labels, + build_post_fill_adverse_selection_labels, +) + +SECOND = 1_000_000_000 + + +def _clock_books() -> pl.DataFrame: + return pl.DataFrame( + { + "sample_id": ["a0", "a1", "a3", "a6", "b7", "b8", "b9"], + "symbol": ["BTCUSDT"] * 7, + "continuity_id": ["a", "a", "a", "a", "b", "b", "b"], + "decision_ts_ns": [value * SECOND for value in (0, 1, 3, 6, 7, 8, 9)], + "decision_sequence": [1, 2, 3, 4, 10, 11, 12], + "mid_price": [100.0, 101.0, 103.0, 106.0, 200.0, 201.0, 202.0], + "trade_sign": [1, -1, 1, -1, 1, -1, 1], + "is_valid": [True] * 7, + } + ) + + +def test_clock_time_labels_use_first_later_state_and_do_not_cross_gaps() -> None: + labels = build_clock_time_mid_labels( + _clock_books(), + ClockTimeLabelSpec(horizons_ns=(2 * SECOND,), max_target_staleness_ns=SECOND), + ) + at_zero = labels.filter(pl.col("sample_id") == "a0").row(0, named=True) + assert at_zero["clock_target_ts_ns"] == 2 * SECOND + assert at_zero["clock_label_information_end_ts_ns"] == 3 * SECOND + assert at_zero["clock_observed_target_staleness_ns"] == SECOND + assert at_zero["clock_future_mid_return"] == pytest.approx(math.log(103.0 / 100.0)) + assert at_zero["clock_future_mid_direction"] == 1 + assert at_zero["clock_label_is_descriptive"] is True + + # Segment B has observations after t=6, but they are not valid targets for A. + at_six = labels.filter(pl.col("sample_id") == "a6").row(0, named=True) + assert at_six["clock_right_censored"] is True + assert at_six["clock_censor_reason"] == "no_same_segment_future_state" + assert at_six["clock_future_mid_return"] is None + assert at_six["clock_label_information_end_ts_ns"] is None + + +def test_clock_time_labels_preserve_exact_future_book_identity_when_requested() -> None: + labels = build_clock_time_mid_labels( + _clock_books(), + ClockTimeLabelSpec(horizons_ns=(2 * SECOND,), max_target_staleness_ns=SECOND), + book_identity_column="decision_sequence", + ) + + at_zero = labels.filter(pl.col("sample_id") == "a0").row(0, named=True) + assert at_zero["clock_label_information_end_ts_ns"] == 3 * SECOND + assert at_zero["clock_label_information_end_identity"] == 3 + + at_six = labels.filter(pl.col("sample_id") == "a6").row(0, named=True) + assert at_six["clock_right_censored"] is True + assert at_six["clock_label_information_end_identity"] is None + + +def test_clock_price_impact_is_side_signed() -> None: + decisions = _clock_books().filter(pl.col("sample_id").is_in(["a0", "a1"])) + labels = build_clock_time_price_impact_labels( + decisions, + ClockTimeLabelSpec(horizons_ns=(2 * SECOND,)), + book_states=_clock_books(), + ) + buy = labels.filter(pl.col("sample_id") == "a0").row(0, named=True) + sell = labels.filter(pl.col("sample_id") == "a1").row(0, named=True) + assert buy["clock_signed_price_impact_bps"] == pytest.approx(10_000.0 * math.log(103.0 / 100.0)) + assert sell["clock_signed_price_impact_bps"] == pytest.approx( + -10_000.0 * math.log(103.0 / 101.0) + ) + assert labels.get_column("clock_label_kind").unique().to_list() == [ + "clock_time_signed_price_impact" + ] + + +def test_event_time_price_impact_preserves_future_information_end() -> None: + frame = pl.DataFrame( + { + "trade_side": [1, -1, 1], + "future_mid_return": [0.01, 0.02, None], + "label_information_end_ts_ns": [20, 21, None], + "right_censored": [False, False, True], + "label_horizon_events": [2, 2, 2], + } + ) + + labeled = add_event_time_price_impact_labels(frame, side_column="trade_side") + + assert labeled["event_time_signed_price_impact_bps"].to_list() == [100.0, -200.0, None] + assert labeled["event_impact_label_information_end_ts_ns"].to_list() == [20, 21, None] + assert labeled["event_impact_right_censored"].to_list() == [False, False, True] + + +def _limit_books() -> pl.DataFrame: + return pl.DataFrame( + { + "sample_id": [f"a{index}" for index in range(5)], + "symbol": ["BTCUSDT"] * 5, + "continuity_id": ["a"] * 5, + "decision_ts_ns": [index * SECOND for index in range(5)], + "decision_sequence": list(range(1, 6)), + "best_bid": [100.0] * 5, + "best_ask": [102.0] * 5, + "bid_quantity": [10.0] * 5, + "ask_quantity": [10.0] * 5, + "is_valid": [True] * 5, + } + ) + + +def _limit_trades() -> pl.DataFrame: + return pl.DataFrame( + { + "symbol": ["BTCUSDT"] * 3, + "continuity_id": ["a"] * 3, + # The huge print exactly at t=0 must not fill an order activated at t=0. + "available_ts_ns": [0, SECOND, 2 * SECOND], + "price": [100.0, 100.0, 100.0], + "quantity": [100.0, 3.0, 4.0], + "aggressor_side": ["sell", "sell", "sell"], + } + ) + + +def test_limit_fill_proxy_is_strict_partial_and_explicitly_censored() -> None: + labels = build_hypothetical_limit_fill_labels( + _limit_books(), + _limit_trades(), + LimitFillAssumptions( + side="buy", + horizon_ns=2 * SECOND, + order_quantity=3.0, + queue_ahead_fraction=0.5, + ), + ) + at_zero = labels.filter(pl.col("sample_id") == "a0").row(0, named=True) + assert at_zero["limit_initial_queue_ahead"] == 5.0 + assert at_zero["limit_observed_executable_quantity"] == 7.0 + assert at_zero["limit_fill_quantity"] == 2.0 + assert at_zero["limit_fill_fraction"] == pytest.approx(2.0 / 3.0) + assert at_zero["limit_full_fill"] is False + assert at_zero["limit_label_information_end_ts_ns"] == 2 * SECOND + assert at_zero["limit_trade_evidence_required"] is True + assert at_zero["limit_equal_time_ordering"] == "trade_at_activation_excluded" + assert "cancellations" in at_zero["limit_label_assumption"] + + at_three = labels.filter(pl.col("sample_id") == "a3").row(0, named=True) + assert at_three["limit_right_censored"] is True + assert at_three["limit_censor_reason"] == "segment_ends_before_horizon" + assert at_three["limit_fill_fraction"] is None + assert at_three["limit_label_information_end_ts_ns"] is None + + no_trade_labels = build_hypothetical_limit_fill_labels( + _limit_books(), + _limit_trades().head(0), + LimitFillAssumptions( + side="buy", + horizon_ns=2 * SECOND, + order_quantity=3.0, + queue_ahead_fraction=0.5, + ), + ) + no_trade_at_zero = no_trade_labels.filter(pl.col("sample_id") == "a0").row(0, named=True) + assert no_trade_at_zero["limit_right_censored"] is False + assert no_trade_at_zero["limit_fill_quantity"] == 0.0 + + +def test_post_fill_adverse_selection_has_side_aware_markout_and_gap_censoring() -> None: + fills = pl.DataFrame( + { + "fill_id": ["buy", "sell", "gap"], + "symbol": ["BTCUSDT"] * 3, + "continuity_id": ["a", "a", "a"], + "fill_ts_ns": [0, SECOND, 6 * SECOND], + "fill_price": [100.0, 104.0, 106.0], + "side": ["buy", "sell", "buy"], + } + ) + labels = build_post_fill_adverse_selection_labels( + fills, + _clock_books(), + AdverseSelectionSpec(horizons_ns=(2 * SECOND,), max_target_staleness_ns=SECOND), + ) + buy = labels.filter(pl.col("fill_id") == "buy").row(0, named=True) + assert buy["post_fill_markout_bps"] == pytest.approx(300.0) + assert buy["adverse_selection_bps"] == pytest.approx(-300.0) + assert buy["adverse_selection_indicator"] is False + assert buy["adverse_label_information_end_ts_ns"] == 3 * SECOND + + sell = labels.filter(pl.col("fill_id") == "sell").row(0, named=True) + assert sell["post_fill_markout_bps"] == pytest.approx(10_000.0 / 104.0) + assert sell["adverse_selection_bps"] < 0 + + gap = labels.filter(pl.col("fill_id") == "gap").row(0, named=True) + assert gap["adverse_right_censored"] is True + assert gap["adverse_censor_reason"] == "no_same_segment_future_state" + assert gap["post_fill_markout_bps"] is None + assert gap["adverse_label_information_end_ts_ns"] is None diff --git a/Microstructure/tests/test_m8_acquisition.py b/Microstructure/tests/test_m8_acquisition.py new file mode 100644 index 0000000000000000000000000000000000000000..d363ad89b88d44cb3b24227eee3fc7b1e1e6fb4e --- /dev/null +++ b/Microstructure/tests/test_m8_acquisition.py @@ -0,0 +1,836 @@ +from __future__ import annotations + +import hashlib +import io +import json +import os +import zipfile +from collections.abc import Iterator, Mapping +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import pytest + +import microstructure.m8_acquisition as m8_acquisition +from microstructure.data.binance import ( + BinanceHTTPError, + BinanceMetadataContractError, + BinancePublicClient, + BinanceResponseSizeLimitError, + RetryPolicy, +) +from microstructure.data.binance_archive import ( + BinanceArchiveClient, + BinanceArchiveContractError, + BinanceArchiveHTTPError, + BinanceArchivePayloadError, +) +from microstructure.data.evidence_budget import EvidenceBudgetExceeded, RetainedEvidenceBudget +from microstructure.m8_acquisition import ( + M8AcquisitionError, + M8AcquisitionFailureResult, + M8AcquisitionResult, + acquire_m8_archives, + copy_m8_acquisition_into, + read_m8_acquisition_failure, + read_m8_acquisition_manifest, + verify_m8_acquisition_manifest, +) +from microstructure.m8_config import M8StudyConfig, load_m8_config + +_ORIGINAL_ZIPFILE_OPEN = zipfile.ZipFile.open + + +@dataclass +class _FakeResponse: + url: str + content: bytes + status_code: int = 200 + + @property + def headers(self) -> Mapping[str, str]: + return { + "Content-Length": str(len(self.content)), + "Content-Type": "application/octet-stream", + } + + @property + def text(self) -> str: + return self.content.decode("utf-8", errors="replace") + + def iter_content(self, *, chunk_size: int) -> Iterator[bytes]: + for start in range(0, len(self.content), chunk_size): + yield self.content[start : start + chunk_size] + + def close(self) -> None: + return None + + +class _MetadataSession: + def __init__(self, bodies: Mapping[str, bytes]) -> None: + self.bodies = bodies + self.calls: list[str] = [] + + def get( + self, + url: str, + params: Mapping[str, str | int], + timeout: float, + stream: bool = False, + ) -> _FakeResponse: + del timeout, stream + symbol = str(params["symbol"]) + request_uri = f"{url}?symbol={symbol}" + self.calls.append(request_uri) + return _FakeResponse(request_uri, self.bodies[symbol]) + + +class _ArchiveSession: + def __init__(self, bodies: Mapping[str, bytes]) -> None: + self.bodies = bodies + self.calls: list[str] = [] + + def get(self, url: str, *, timeout: float, stream: bool) -> _FakeResponse: + del timeout, stream + self.calls.append(url) + return _FakeResponse(url, self.bodies[url]) + + +class _StatusArchiveSession: + def __init__(self, status_code: int) -> None: + self.status_code = status_code + self.calls: list[str] = [] + + def get(self, url: str, *, timeout: float, stream: bool) -> _FakeResponse: + del timeout, stream + self.calls.append(url) + return _FakeResponse(url, b"declared object unavailable", self.status_code) + + +def _exchange_info(symbol: str) -> bytes: + base_asset = symbol.removesuffix("USDT") + return json.dumps( + { + "timezone": "UTC", + "serverTime": 1_704_067_200_000, + "symbols": [ + { + "symbol": symbol, + "status": "TRADING", + "baseAsset": base_asset, + "quoteAsset": "USDT", + "filters": [ + { + "filterType": "PRICE_FILTER", + "minPrice": "0.01000000", + "maxPrice": "1000000.00000000", + "tickSize": "0.01000000", + }, + { + "filterType": "LOT_SIZE", + "minQty": "0.00010000", + "maxQty": "100000.00000000", + "stepSize": "0.00010000", + }, + ], + } + ], + }, + sort_keys=True, + separators=(",", ":"), + ).encode() + + +def _zip_bytes(member_name: str, marker: str) -> bytes: + destination = io.BytesIO() + with zipfile.ZipFile(destination, "w", compression=zipfile.ZIP_DEFLATED) as archive: + archive.writestr( + member_name, + ( + "agg_trade_id,price,quantity,first_trade_id,last_trade_id,timestamp,buyer_maker\n" + f"1,100.00,0.1000,1,1,1704067200000,{marker}\n" + ).encode(), + ) + return destination.getvalue() + + +def _archive_responses(config: M8StudyConfig) -> dict[str, bytes]: + responses: dict[str, bytes] = {} + for period in config.periods: + for symbol in config.study.symbols: + archive_name = f"{symbol}-aggTrades-{period.date.isoformat()}.zip" + member_name = archive_name.removesuffix(".zip") + ".csv" + archive_uri = ( + f"https://data.binance.vision/data/spot/daily/aggTrades/{symbol}/{archive_name}" + ) + archive_body = _zip_bytes(member_name, f"{symbol}-{period.role}") + digest = hashlib.sha256(archive_body).hexdigest() + responses[archive_uri] = archive_body + responses[f"{archive_uri}.CHECKSUM"] = f"{digest} {archive_name}\n".encode() + return responses + + +def _acquire_fixture(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> M8AcquisitionResult: + config = load_m8_config(Path(__file__).parents[1] / "configs/m8_multidate_trade_study.toml") + metadata_session = _MetadataSession( + {symbol: _exchange_info(symbol) for symbol in config.study.symbols} + ) + archive_session = _ArchiveSession(_archive_responses(config)) + client_budget_ids: list[int] = [] + + def public_client_factory(**kwargs: Any) -> BinancePublicClient: + client_budget_ids.append(id(kwargs["retained_evidence_budget"])) + return BinancePublicClient( + session=metadata_session, # type: ignore[arg-type] + retry_policy=RetryPolicy(max_retries=0), + **kwargs, + ) + + def archive_client_factory(**kwargs: Any) -> BinanceArchiveClient: + client_budget_ids.append(id(kwargs["retained_evidence_budget"])) + return BinanceArchiveClient( + session=archive_session, + retry_policy=RetryPolicy(max_retries=0), + **kwargs, + ) + + monkeypatch.setattr(m8_acquisition, "BinancePublicClient", public_client_factory) + monkeypatch.setattr(m8_acquisition, "BinanceArchiveClient", archive_client_factory) + member_open_calls: list[str] = [] + + def forbidden_member_open(*args: object, **kwargs: object) -> object: + del args, kwargs + member_open_calls.append("opened") + raise AssertionError("raw acquisition must never open a ZIP member") + + monkeypatch.setattr(zipfile.ZipFile, "open", forbidden_member_open) + result = acquire_m8_archives(config, tmp_path / "authority") + assert member_open_calls == [] + assert len(client_budget_ids) == 2 + assert len(set(client_budget_ids)) == 1 + assert len(metadata_session.calls) == 2 + assert len(archive_session.calls) == 16 + return result + + +def _install_status_clients( + monkeypatch: pytest.MonkeyPatch, + *, + status_code: int, +) -> tuple[M8StudyConfig, _StatusArchiveSession]: + config = load_m8_config(Path(__file__).parents[1] / "configs/m8_multidate_trade_study.toml") + metadata_session = _MetadataSession( + {symbol: _exchange_info(symbol) for symbol in config.study.symbols} + ) + archive_session = _StatusArchiveSession(status_code) + + def public_client_factory(**kwargs: Any) -> BinancePublicClient: + return BinancePublicClient( + session=metadata_session, # type: ignore[arg-type] + retry_policy=RetryPolicy(max_retries=0), + **kwargs, + ) + + def archive_client_factory(**kwargs: Any) -> BinanceArchiveClient: + return BinanceArchiveClient( + session=archive_session, + retry_policy=RetryPolicy(max_retries=0), + **kwargs, + ) + + monkeypatch.setattr(m8_acquisition, "BinancePublicClient", public_client_factory) + monkeypatch.setattr(m8_acquisition, "BinanceArchiveClient", archive_client_factory) + return config, archive_session + + +def _install_metadata_body_clients( + monkeypatch: pytest.MonkeyPatch, + bodies: Mapping[str, bytes], +) -> tuple[M8StudyConfig, _MetadataSession, _ArchiveSession]: + config = load_m8_config(Path(__file__).parents[1] / "configs/m8_multidate_trade_study.toml") + metadata_session = _MetadataSession(bodies) + archive_session = _ArchiveSession(_archive_responses(config)) + + def public_client_factory(**kwargs: Any) -> BinancePublicClient: + return BinancePublicClient( + session=metadata_session, # type: ignore[arg-type] + retry_policy=RetryPolicy(max_retries=0), + **kwargs, + ) + + def archive_client_factory(**kwargs: Any) -> BinanceArchiveClient: + return BinanceArchiveClient( + session=archive_session, + retry_policy=RetryPolicy(max_retries=0), + **kwargs, + ) + + monkeypatch.setattr(m8_acquisition, "BinancePublicClient", public_client_factory) + monkeypatch.setattr(m8_acquisition, "BinanceArchiveClient", archive_client_factory) + return config, metadata_session, archive_session + + +def test_raw_only_acquisition_is_complete_content_addressed_and_budget_exact( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + result = _acquire_fixture(tmp_path, monkeypatch) + + assert result.metadata_count == 2 + assert result.archive_count == 8 + assert result.manifest_path.name == ( + f"m8-acquisition.manifest-{result.manifest_sha256[:20]}.json" + ) + assert result.manifest.copied_from_manifest_sha256 is None + assert result.manifest.content_identity_sha256 == result.manifest.evidence_set_sha256 + assert all(not item.csv_member_opened for item in result.manifest.archives) + assert all(not item.economic_fields_inspected for item in result.manifest.archives) + assert len(result.manifest.retained_artifacts) == 36 + assert sum(item.bytes for item in result.manifest.retained_artifacts) == ( + result.total_raw_evidence_bytes + ) + raw_budget = RetainedEvidenceBudget( + result.output_root / "raw", + result.manifest.config.study.max_total_download_bytes, + ) + assert raw_budget.used_bytes == result.total_raw_evidence_bytes + assert result.manifest_path.stat().st_size not in { + item.bytes for item in result.manifest.retained_artifacts + } or result.manifest_path.relative_to(result.output_root).as_posix() not in { + item.path for item in result.manifest.retained_artifacts + } + reconstructed = result.manifest.archive_descriptor_for("BTCUSDT", "2024-01-05").reconstruct() + assert reconstructed.request.symbol == "BTCUSDT" + assert reconstructed.request.date.isoformat() == "2024-01-05" + assert reconstructed.declared_uncompressed_bytes > 0 + assert verify_m8_acquisition_manifest is read_m8_acquisition_manifest + + +def test_reader_rejects_raw_tamper_without_opening_member( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + result = _acquire_fixture(tmp_path, monkeypatch) + checksum = result.manifest.archives[0].checksum_path + checksum.write_bytes(checksum.read_bytes() + b"x") + + with pytest.raises(M8AcquisitionError, match="byte count changed"): + read_m8_acquisition_manifest( + result.manifest_path, + expected_sha256=result.manifest_sha256, + config=result.manifest.config, + ) + + +def test_held_out_descriptor_requires_guard_and_runs_it_immediately_before_open( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + result = _acquire_fixture(tmp_path, monkeypatch) + held_out = result.manifest.archive_descriptor_for("BTCUSDT", "2024-01-05").reconstruct() + development = result.manifest.archive_descriptor_for("BTCUSDT", "2024-01-03").reconstruct() + assert held_out.requires_member_open_guard is True + assert development.requires_member_open_guard is False + events: list[str] = [] + + def tracked_open( + archive: zipfile.ZipFile, + name: str | zipfile.ZipInfo, + mode: str = "r", + pwd: bytes | None = None, + *, + force_zip64: bool = False, + ) -> Any: + events.append("open") + return _ORIGINAL_ZIPFILE_OPEN( + archive, + name, + mode=mode, + pwd=pwd, + force_zip64=force_zip64, + ) + + monkeypatch.setattr(zipfile.ZipFile, "open", tracked_open) + unguarded = held_out.iter_normalized_batches(batch_rows=1) + with pytest.raises(BinanceArchivePayloadError, match="requires a member-open authority guard"): + next(unguarded) + assert events == [] + + guarded = held_out.iter_normalized_batches( + batch_rows=1, + before_member_open=lambda: events.append("guard"), + ) + with pytest.raises(BinanceArchivePayloadError): + next(guarded) + assert events == ["guard", "open"] + + +def test_copy_is_self_contained_source_equivalent_and_has_no_extra_raw_copy( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + result = _acquire_fixture(tmp_path, monkeypatch) + copied = copy_m8_acquisition_into(result.manifest, tmp_path / "bundle-input") + + assert copied.copied_from_manifest_sha256 == result.manifest_sha256 + assert copied.content_identity_sha256 == result.manifest.content_identity_sha256 + assert copied.retained_artifacts == result.manifest.retained_artifacts + assert copied.total_raw_evidence_bytes == result.total_raw_evidence_bytes + assert copied.total_accepted_zip_bytes == result.manifest.total_accepted_zip_bytes + copied_raw_files = tuple(path for path in (copied.root / "raw").rglob("*") if path.is_file()) + assert len(copied_raw_files) == len(copied.retained_artifacts) + assert all(path.resolve().is_relative_to(copied.root) for path in copied_raw_files) + assert len(tuple((copied.root / "_manifests").glob("*.json"))) == 1 + assert copied.path.name != result.manifest_path.name + for source_item, copied_item in zip( + result.manifest.archives, + copied.archives, + strict=True, + ): + assert source_item.archive_path != copied_item.archive_path + assert source_item.archive_sha256 == copied_item.archive_sha256 + + +def test_distinct_copy_budget_has_exact_boundary() -> None: + m8_acquisition._assert_distinct_copy_budget(5, 10) + with pytest.raises(M8AcquisitionError, match="distinct self-contained copy"): + m8_acquisition._assert_distinct_copy_budget(6, 10) + + +def test_repeated_acquisition_excludes_manifest_indexes_from_raw_budget( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + first = _acquire_fixture(tmp_path, monkeypatch) + second = acquire_m8_archives(first.manifest.config, first.output_root) + + raw_files = tuple(path for path in (second.output_root / "raw").rglob("*") if path.is_file()) + assert second.total_raw_evidence_bytes == sum(path.stat().st_size for path in raw_files) + assert second.total_raw_evidence_bytes == sum( + item.bytes for item in second.manifest.retained_artifacts + ) + manifest_paths = { + path.relative_to(second.output_root).as_posix() + for path in (second.output_root / "_manifests").glob("*.json") + } + assert len(manifest_paths) == 2 + assert manifest_paths.isdisjoint({item.path for item in second.manifest.retained_artifacts}) + assert second.total_raw_evidence_bytes >= first.total_raw_evidence_bytes + + +def test_zip_preflight_rejects_many_entries_before_zipfile_parser( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + destination = tmp_path / "many.zip" + with zipfile.ZipFile(destination, "w", compression=zipfile.ZIP_DEFLATED) as archive: + archive.writestr("first.csv", b"1") + archive.writestr("second.csv", b"2") + parser_calls: list[str] = [] + + def forbidden_parser(*args: object, **kwargs: object) -> object: + del args, kwargs + parser_calls.append("called") + raise AssertionError("unbounded ZIP parser must not run") + + monkeypatch.setattr(m8_acquisition.zipfile, "ZipFile", forbidden_parser) + with pytest.raises(M8AcquisitionError, match="one single-disk member"): + m8_acquisition._zip_directory_member(destination, "first.csv", 1024) + assert parser_calls == [] + + +def test_zip_preflight_rejects_oversized_directory_claim_before_zipfile_parser( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + destination = tmp_path / "oversized-directory.zip" + destination.write_bytes(_zip_bytes("expected.csv", "marker")) + body = bytearray(destination.read_bytes()) + eocd_offset = body.rfind(m8_acquisition._EOCD_SIGNATURE) + values = list(m8_acquisition._EOCD_STRUCT.unpack_from(body, eocd_offset)) + values[5] = m8_acquisition._MAX_ZIP_DIRECTORY_BYTES + 1 + m8_acquisition._EOCD_STRUCT.pack_into(body, eocd_offset, *values) + destination.write_bytes(body) + parser_calls: list[str] = [] + + def forbidden_parser(*args: object, **kwargs: object) -> object: + del args, kwargs + parser_calls.append("called") + raise AssertionError("unbounded ZIP parser must not run") + + monkeypatch.setattr(m8_acquisition.zipfile, "ZipFile", forbidden_parser) + with pytest.raises(M8AcquisitionError, match="central directory exceeds"): + m8_acquisition._zip_directory_member(destination, "expected.csv", 1024) + assert parser_calls == [] + + +def test_zip_preflight_rejects_malformed_eocd_before_zipfile_parser( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + destination = tmp_path / "malformed-eocd.zip" + body = bytearray(_zip_bytes("expected.csv", "marker")) + eocd_offset = body.rfind(m8_acquisition._EOCD_SIGNATURE) + assert eocd_offset >= 0 + body[eocd_offset : eocd_offset + 4] = b"NOPE" + destination.write_bytes(body) + parser_calls: list[str] = [] + + def forbidden_parser(*args: object, **kwargs: object) -> object: + del args, kwargs + parser_calls.append("called") + raise AssertionError("unbounded ZIP parser must not run") + + monkeypatch.setattr(m8_acquisition.zipfile, "ZipFile", forbidden_parser) + with pytest.raises(M8AcquisitionError, match="end-of-directory record is missing"): + m8_acquisition._zip_directory_member(destination, "expected.csv", 1024) + assert parser_calls == [] + + +def test_exact_404_publishes_verified_raw_only_failure_authority( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + config, archive_session = _install_status_clients(monkeypatch, status_code=404) + member_opens: list[str] = [] + + def forbidden_member_open(*args: object, **kwargs: object) -> object: + del args, kwargs + member_opens.append("opened") + raise AssertionError("deterministic acquisition failure must not open a CSV member") + + monkeypatch.setattr(zipfile.ZipFile, "open", forbidden_member_open) + result = acquire_m8_archives(config, tmp_path / "authority") + + assert isinstance(result, M8AcquisitionFailureResult) + assert result.status == "INSUFFICIENT_DATA" + assert result.reason_code == "DECLARED_OBJECT_UNAVAILABLE" + assert result.failed_symbol == "BTCUSDT" + assert result.failed_date is not None + assert result.failed_date.isoformat() == "2024-01-03" + assert result.failed_role == "train" + assert result.completed_count == 2 + assert result.remaining_count == 7 + assert result.retained_artifact_count == 6 + assert result.terminal_path.read_bytes() == b"terminal\n" + assert result.attempt_dir.name.endswith(result.attempt_manifest_sha256[:20]) + assert member_opens == [] + assert len(archive_session.calls) == 1 + + verified = read_m8_acquisition_failure( + result.attempt_manifest_path, + expected_sha256=result.attempt_manifest_sha256, + config=config, + ) + assert verified.reason_code == result.reason_code + assert verified.retained_inventory_sha256 == result.retained_inventory_sha256 + assert verified.total_raw_evidence_bytes == result.total_raw_evidence_bytes + assert verified.checksums_sha256 == result.checksums_sha256 + + +def test_nontrading_exchange_info_publishes_verified_metadata_failure( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + config = load_m8_config(Path(__file__).parents[1] / "configs/m8_multidate_trade_study.toml") + bodies = {symbol: _exchange_info(symbol) for symbol in config.study.symbols} + payload = json.loads(bodies["BTCUSDT"]) + payload["symbols"][0]["status"] = "HALT" + bodies["BTCUSDT"] = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode() + config, metadata_session, archive_session = _install_metadata_body_clients( + monkeypatch, + bodies, + ) + member_opens: list[str] = [] + + def forbidden_member_open(*args: object, **kwargs: object) -> object: + del args, kwargs + member_opens.append("opened") + raise AssertionError("metadata failure must not open a CSV member") + + monkeypatch.setattr(zipfile.ZipFile, "open", forbidden_member_open) + result = acquire_m8_archives(config, tmp_path / "authority") + + assert isinstance(result, M8AcquisitionFailureResult) + assert result.reason_code == "METADATA_CONTRACT" + assert result.failed_symbol == "BTCUSDT" + assert result.failed_date is None + assert result.failed_role == "metadata" + assert result.completed_count == 0 + assert result.remaining_count == 9 + assert result.retained_artifact_count == 2 + assert result.terminal_path.read_bytes() == b"terminal\n" + assert metadata_session.calls == [ + "https://data-api.binance.vision/api/v3/exchangeInfo?symbol=BTCUSDT" + ] + assert archive_session.calls == [] + assert member_opens == [] + + verified = read_m8_acquisition_failure( + result.attempt_manifest_path, + expected_sha256=result.attempt_manifest_sha256, + config=config, + ) + assert verified.reason_code == "METADATA_CONTRACT" + assert verified.retained_artifacts == result.manifest.retained_artifacts + + +@pytest.mark.parametrize( + ("filter_type", "field", "value"), + [ + ("PRICE_FILTER", "minPrice", "NaN"), + ("LOT_SIZE", "maxQty", "Infinity"), + ("PRICE_FILTER", "tickSize", "not-a-decimal"), + ], +) +def test_invalid_exchange_info_filter_number_is_terminal_metadata_contract( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + filter_type: str, + field: str, + value: str, +) -> None: + config = load_m8_config(Path(__file__).parents[1] / "configs/m8_multidate_trade_study.toml") + bodies = {symbol: _exchange_info(symbol) for symbol in config.study.symbols} + payload = json.loads(bodies["BTCUSDT"]) + filters = payload["symbols"][0]["filters"] + next(item for item in filters if item["filterType"] == filter_type)[field] = value + bodies["BTCUSDT"] = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode() + config, _, archive_session = _install_metadata_body_clients(monkeypatch, bodies) + + result = acquire_m8_archives(config, tmp_path / "authority") + + assert isinstance(result, M8AcquisitionFailureResult) + assert result.reason_code == "METADATA_CONTRACT" + assert result.failed_role == "metadata" + assert archive_session.calls == [] + verified = read_m8_acquisition_failure( + result.attempt_manifest_path, + expected_sha256=result.attempt_manifest_sha256, + config=config, + ) + assert verified.reason_code == "METADATA_CONTRACT" + + +@pytest.mark.parametrize( + "failure", + [ + PermissionError("metadata permission denied"), + OSError("metadata disk fault"), + RuntimeError("metadata implementation fault"), + M8AcquisitionError("metadata hash identity fault"), + ], +) +def test_metadata_verification_system_or_integrity_fault_never_terminalizes( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + failure: Exception, +) -> None: + config = load_m8_config(Path(__file__).parents[1] / "configs/m8_multidate_trade_study.toml") + bodies = {symbol: _exchange_info(symbol) for symbol in config.study.symbols} + config, _, archive_session = _install_metadata_body_clients(monkeypatch, bodies) + + def fail_verification(*args: object, **kwargs: object) -> None: + del args, kwargs + raise failure + + monkeypatch.setattr(m8_acquisition, "_verify_metadata_files", fail_verification) + output_root = tmp_path / "authority" + with pytest.raises(M8AcquisitionError, match=str(failure)): + acquire_m8_archives(config, output_root) + + assert archive_session.calls == [] + assert not (output_root / "_attempts").exists() + assert not list(output_root.rglob("INSUFFICIENT_DATA")) + + +def test_earlier_failure_attempt_remains_verifiable_after_later_raw_attempt( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + config, _ = _install_status_clients(monkeypatch, status_code=404) + output_root = tmp_path / "authority" + first = acquire_m8_archives(config, output_root) + second = acquire_m8_archives(config, output_root) + assert isinstance(first, M8AcquisitionFailureResult) + assert isinstance(second, M8AcquisitionFailureResult) + + verified_first = read_m8_acquisition_failure( + first.attempt_manifest_path, + expected_sha256=first.attempt_manifest_sha256, + config=config, + ) + assert verified_first.retained_artifacts == first.manifest.retained_artifacts + assert verified_first.reason_code == "DECLARED_OBJECT_UNAVAILABLE" + + +def test_retry_exhausted_http_failure_remains_retryable_and_publishes_no_terminal( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + config, archive_session = _install_status_clients(monkeypatch, status_code=503) + output_root = tmp_path / "authority" + + with pytest.raises(M8AcquisitionError, match="failed closed"): + acquire_m8_archives(config, output_root) + + assert len(archive_session.calls) == 1 + assert not (output_root / "_attempts").exists() + assert not list(output_root.rglob("INSUFFICIENT_DATA")) + + +@pytest.mark.parametrize( + ("error", "expected"), + [ + (BinanceHTTPError("missing", status_code=404), "DECLARED_OBJECT_UNAVAILABLE"), + (BinanceArchiveHTTPError("gone", status_code=410), "DECLARED_OBJECT_UNAVAILABLE"), + (BinanceMetadataContractError("bad metadata"), "METADATA_CONTRACT"), + (BinanceResponseSizeLimitError("too large"), "RESPONSE_SIZE_LIMIT"), + ( + BinanceArchiveContractError("bad checksum", reason_code="CHECKSUM_CONTRACT"), + "CHECKSUM_CONTRACT", + ), + ( + BinanceArchiveContractError("bad zip", reason_code="ZIP_CONTRACT"), + "ZIP_CONTRACT", + ), + (EvidenceBudgetExceeded("budget"), "TOTAL_EVIDENCE_BUDGET"), + (BinanceHTTPError("retry", status_code=503, retry_exhausted=True), None), + (PermissionError("denied"), None), + (OSError("disk fault"), None), + ], +) +def test_acquisition_failure_classification_is_typed_and_stable( + error: BaseException, + expected: str | None, +) -> None: + assert m8_acquisition._deterministic_failure_reason(error) == expected + + +def test_success_manifest_is_published_only_after_recursive_raw_durability_barrier( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + events: list[str] = [] + original_fsync_tree = m8_acquisition._fsync_tree + original_write_manifest = m8_acquisition._write_manifest_payload + + def tracked_fsync_tree(path: Path) -> None: + events.append(f"barrier:{path.name}") + original_fsync_tree(path) + + def tracked_write_manifest(*args: object, **kwargs: object) -> tuple[Path, str]: + events.append("publish:manifest") + return original_write_manifest(*args, **kwargs) + + monkeypatch.setattr(m8_acquisition, "_fsync_tree", tracked_fsync_tree) + monkeypatch.setattr(m8_acquisition, "_write_manifest_payload", tracked_write_manifest) + _acquire_fixture(tmp_path, monkeypatch) + + assert events.index("barrier:raw") < events.index("publish:manifest") + + +def test_failure_attempt_is_published_only_after_recursive_raw_durability_barrier( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + config, _ = _install_status_clients(monkeypatch, status_code=404) + events: list[str] = [] + original_fsync_tree = m8_acquisition._fsync_tree + original_publish = m8_acquisition._publish_failure_authority + + def tracked_fsync_tree(path: Path) -> None: + events.append(f"barrier:{path.name}") + original_fsync_tree(path) + + def tracked_publish(*args: object, **kwargs: object) -> object: + events.append("publish:failure") + return original_publish(*args, **kwargs) + + monkeypatch.setattr(m8_acquisition, "_fsync_tree", tracked_fsync_tree) + monkeypatch.setattr(m8_acquisition, "_publish_failure_authority", tracked_publish) + result = acquire_m8_archives(config, tmp_path / "authority") + + assert isinstance(result, M8AcquisitionFailureResult) + assert events.index("barrier:raw") < events.index("publish:failure") + + +def test_failure_terminal_is_not_published_when_raw_durability_barrier_fails( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + config, _ = _install_status_clients(monkeypatch, status_code=404) + output_root = tmp_path / "authority" + + def fail_raw_barrier(path: Path) -> None: + assert path.name == "raw" + raise OSError("injected raw fsync failure") + + monkeypatch.setattr(m8_acquisition, "_fsync_tree", fail_raw_barrier) + with pytest.raises(M8AcquisitionError, match="failed closed"): + acquire_m8_archives(config, output_root) + + assert not (output_root / "_attempts").exists() + assert not list(output_root.rglob("INSUFFICIENT_DATA")) + + +def test_self_contained_copy_flushes_raw_tree_before_manifest_publication( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + result = _acquire_fixture(tmp_path, monkeypatch) + events: list[str] = [] + original_fsync_tree = m8_acquisition._fsync_tree + original_write_manifest = m8_acquisition._write_manifest_payload + + def tracked_fsync_tree(path: Path) -> None: + events.append(f"barrier:{path.name}") + original_fsync_tree(path) + + def tracked_write_manifest(*args: object, **kwargs: object) -> tuple[Path, str]: + events.append("publish:manifest") + return original_write_manifest(*args, **kwargs) + + monkeypatch.setattr(m8_acquisition, "_fsync_tree", tracked_fsync_tree) + monkeypatch.setattr(m8_acquisition, "_write_manifest_payload", tracked_write_manifest) + copy_m8_acquisition_into(result.manifest, tmp_path / "copy") + + assert events.index("barrier:raw") < events.index("publish:manifest") + + +def test_manifest_snapshot_rejects_path_swap_after_same_fd_hash_and_read( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + result = _acquire_fixture(tmp_path, monkeypatch) + original = result.manifest_path.read_bytes() + replacement_payload = json.loads(original) + replacement_payload["evidence_set_sha256"] = "0" * 64 + replacement = m8_acquisition._canonical_json_bytes(replacement_payload) + assert len(replacement) == len(original) + replacement_path = tmp_path / "replacement.json" + replacement_path.write_bytes(replacement) + original_snapshot = m8_acquisition._read_bounded_regular_snapshot + swapped = False + + def swapping_snapshot( + path: Path, + label: str, + *, + byte_limit: int, + ) -> object: + nonlocal swapped + snapshot = original_snapshot(path, label, byte_limit=byte_limit) + if path == result.manifest_path and not swapped: + os.replace(replacement_path, result.manifest_path) + swapped = True + return snapshot + + monkeypatch.setattr(m8_acquisition, "_read_bounded_regular_snapshot", swapping_snapshot) + with pytest.raises(M8AcquisitionError, match="path changed after snapshot"): + read_m8_acquisition_manifest( + result.manifest_path, + expected_sha256=result.manifest_sha256, + config=result.manifest.config, + ) diff --git a/Microstructure/tests/test_m8_config.py b/Microstructure/tests/test_m8_config.py new file mode 100644 index 0000000000000000000000000000000000000000..fbc9072fe07dea9758a922d75bae913648bc1596 --- /dev/null +++ b/Microstructure/tests/test_m8_config.py @@ -0,0 +1,186 @@ +from __future__ import annotations + +import hashlib +import json +from dataclasses import FrozenInstanceError +from datetime import date +from pathlib import Path + +import pytest + +from microstructure.m8_config import M8ConfigError, load_m8_config + +PROJECT_ROOT = Path(__file__).parents[1] +CONFIG_PATH = PROJECT_ROOT / "configs" / "m8_multidate_trade_study.toml" + + +def _mutated_config(tmp_path: Path, old: str, new: str) -> Path: + source = CONFIG_PATH.read_text(encoding="utf-8") + assert old in source + path = tmp_path / "m8-invalid.toml" + path.write_text(source.replace(old, new, 1), encoding="utf-8") + return path + + +def test_frozen_m8_config_is_typed_hashed_and_json_safe() -> None: + config = load_m8_config(CONFIG_PATH) + + assert config.path == CONFIG_PATH.resolve() + assert config.study.protocol_version == "1.0.2" + assert config.study.source == "binance_spot_daily_aggtrades_archive" + assert config.study.symbols == ("BTCUSDT", "ETHUSDT") + assert tuple((period.date, period.role) for period in config.periods) == ( + (date(2024, 1, 3), "train"), + (date(2024, 1, 4), "validation"), + (date(2024, 1, 5), "primary_test"), + (date(2024, 1, 6), "replication_test"), + ) + assert config.source_sha256 == hashlib.sha256(CONFIG_PATH.read_bytes()).hexdigest() + assert len(config.hash) == 64 + public = config.public_dict() + assert public["config_sha256"] == config.hash + assert public["source_sha256"] == config.source_sha256 + assert json.loads(json.dumps(public))["periods"][3]["role"] == "replication_test" + + +def test_semantic_hash_ignores_path_comments_and_formatting(tmp_path: Path) -> None: + original = load_m8_config(CONFIG_PATH) + relocated_path = tmp_path / "relocated.toml" + relocated_path.write_text( + "# formatting-only comment\n" + CONFIG_PATH.read_text(encoding="utf-8") + "\n", + encoding="utf-8", + ) + + relocated = load_m8_config(relocated_path) + + assert relocated.hash == original.hash + assert relocated.source_sha256 != original.source_sha256 + assert relocated.path != original.path + + +def test_config_objects_are_immutable() -> None: + config = load_m8_config(CONFIG_PATH) + + with pytest.raises(FrozenInstanceError): + config.study.seed = 1 # type: ignore[misc] + + +@pytest.mark.parametrize( + ("old", "new", "message"), + [ + ( + 'source = "binance_spot_daily_aggtrades_archive"', + 'source = "binance_spot_rest"', + r"study\.source is frozen", + ), + ( + 'symbols = ["BTCUSDT", "ETHUSDT"]', + 'symbols = ["ETHUSDT", "BTCUSDT"]', + r"study\.symbols is frozen", + ), + ( + 'symbols = ["BTCUSDT", "ETHUSDT"]', + 'symbols = ["BTCUSDT", "BTCUSDT"]', + r"study\.symbols is frozen|must be unique", + ), + ( + "max_archive_compressed_bytes = 268435456", + "max_archive_compressed_bytes = 268435457", + "max_archive_compressed_bytes is frozen", + ), + ( + "max_archive_uncompressed_bytes = 2147483648", + "max_archive_uncompressed_bytes = 0", + "max_archive_uncompressed_bytes is frozen", + ), + ( + "max_total_download_bytes = 8589934592", + "max_total_download_bytes = 8589934593", + "max_total_download_bytes is frozen", + ), + ( + "trade_windows = [5, 20, 100]", + "trade_windows = [5, 20, 200]", + r"features\.trade_windows is frozen", + ), + ( + "large_trade_quantile = 0.95", + "large_trade_quantile = 0.90", + "large_trade_quantile is frozen", + ), + ( + "logistic_c_values = [0.1, 1.0, 10.0]", + "logistic_c_values = [0.1, 1.0, 100.0]", + r"models\.logistic_c_values is frozen", + ), + ( + "tree_max_depth_values = [2, 4, 6]", + "tree_max_depth_values = [2, 4, 8]", + "tree_max_depth_values is frozen", + ), + ( + "allow_significance_claim = false", + "allow_significance_claim = true", + r"claims\.allow_significance_claim is frozen", + ), + ( + "allow_quality_warnings = false", + "allow_quality_warnings = true", + r"quality\.allow_quality_warnings is frozen", + ), + ], +) +def test_frozen_study_dimensions_fail_closed( + tmp_path: Path, old: str, new: str, message: str +) -> None: + path = _mutated_config(tmp_path, old, new) + + with pytest.raises(M8ConfigError, match=message): + load_m8_config(path) + + +def test_period_roles_must_have_the_exact_frozen_order(tmp_path: Path) -> None: + path = _mutated_config(tmp_path, 'role = "validation"', 'role = "primary_test"') + + with pytest.raises(M8ConfigError, match="period date/role order is frozen"): + load_m8_config(path) + + +def test_period_dates_must_be_unique(tmp_path: Path) -> None: + path = _mutated_config(tmp_path, 'date = "2024-01-04"', 'date = "2024-01-03"') + + with pytest.raises(M8ConfigError, match="period dates must be unique"): + load_m8_config(path) + + +def test_period_dates_cannot_be_reordered_or_replaced(tmp_path: Path) -> None: + path = _mutated_config(tmp_path, 'date = "2024-01-06"', 'date = "2024-01-07"') + + with pytest.raises(M8ConfigError, match="period date/role order is frozen"): + load_m8_config(path) + + +def test_unknown_or_missing_fields_fail_closed(tmp_path: Path) -> None: + path = _mutated_config( + tmp_path, + 'target = "future_trade_up"', + 'target = "future_trade_up"\nunreviewed_option = true', + ) + + with pytest.raises(M8ConfigError, match=r"study keys.*unknown=unreviewed_option"): + load_m8_config(path) + + +def test_invalid_types_do_not_coerce_bool_to_integer(tmp_path: Path) -> None: + path = _mutated_config(tmp_path, "bootstrap_samples = 2000", "bootstrap_samples = true") + + with pytest.raises(M8ConfigError, match=r"study\.bootstrap_samples must be an integer"): + load_m8_config(path) + + +def test_invalid_toml_is_wrapped_as_m8_config_error(tmp_path: Path) -> None: + path = tmp_path / "invalid.toml" + path.write_text("[study\n", encoding="utf-8") + + with pytest.raises(M8ConfigError, match="cannot parse M8 TOML"): + load_m8_config(path) diff --git a/Microstructure/tests/test_m8_ingestion.py b/Microstructure/tests/test_m8_ingestion.py new file mode 100644 index 0000000000000000000000000000000000000000..163ba51d0c136c571a0cbdeabcce40a3de6df1ab --- /dev/null +++ b/Microstructure/tests/test_m8_ingestion.py @@ -0,0 +1,25 @@ +"""Regression test for the retired unsafe all-calendar M8 entry point.""" + +from pathlib import Path +from types import SimpleNamespace +from typing import cast + +import pytest + +from microstructure.m8_config import M8StudyConfig +from microstructure.m8_ingestion import M8IngestionError, ingest_m8_archives + + +def test_legacy_all_calendar_ingestion_fails_before_any_adapter_call(tmp_path: Path) -> None: + class ForbiddenAdapter: + def __getattribute__(self, name: str) -> object: + raise AssertionError(f"retired ingestion touched adapter attribute {name!r}") + + config = cast(M8StudyConfig, SimpleNamespace()) + with pytest.raises(M8IngestionError, match="before the analysis lock"): + ingest_m8_archives( + config, + tmp_path, + archive_client=ForbiddenAdapter(), + metadata_provider=ForbiddenAdapter(), + ) diff --git a/Microstructure/tests/test_m8_l2_analysis_config.py b/Microstructure/tests/test_m8_l2_analysis_config.py new file mode 100644 index 0000000000000000000000000000000000000000..0179f29d75d8a94cd809cb1b9aa9743da1373621 --- /dev/null +++ b/Microstructure/tests/test_m8_l2_analysis_config.py @@ -0,0 +1,250 @@ +from __future__ import annotations + +import hashlib +from dataclasses import FrozenInstanceError +from pathlib import Path + +import pytest + +from microstructure.m8_l2_analysis_config import ( + M8_L2_ANALYSIS_CONFIG_SEMANTIC_SHA256, + M8_L2_ANALYSIS_CONFIG_SOURCE_SHA256, + M8L2AnalysisConfigError, + load_m8_l2_analysis_config, + semantic_hash_m8_l2_analysis_config, +) + +PROJECT_ROOT = Path(__file__).parents[1] +CONFIG_PATH = PROJECT_ROOT / "configs" / "m8_l2_analysis.toml" + + +def _write_mutation(tmp_path: Path, old: str, new: str) -> Path: + source = CONFIG_PATH.read_text(encoding="utf-8") + assert old in source + path = tmp_path / "mutated.toml" + path.write_text(source.replace(old, new, 1), encoding="utf-8") + return path + + +def _changed_assignment(value: str) -> str: + if value == "true": + return "false" + if value == "false": + return "true" + if value.startswith('"'): + assert value.endswith('"') + return value[:-1] + '-changed"' + if value.startswith("["): + assert value.endswith("]") + addition = '"CHANGED"' if '"' in value else "999" + return value[:-1] + f", {addition}]" + if "." in value: + return str(float(value) + 0.01) + return str(int(value) + 1) + + +def _all_field_mutations() -> list[tuple[int, str]]: + lines = CONFIG_PATH.read_text(encoding="utf-8").splitlines() + mutations: list[tuple[int, str]] = [] + for index, line in enumerate(lines): + if not line or line.startswith("["): + continue + key, separator, value = line.partition(" = ") + assert separator and key and value + changed = list(lines) + changed[index] = f"{key} = {_changed_assignment(value)}" + mutations.append((index + 1, "\n".join(changed) + "\n")) + return mutations + + +def test_frozen_analysis_contract_binds_exact_bytes_and_all_rules() -> None: + config = load_m8_l2_analysis_config(CONFIG_PATH) + + assert hashlib.sha256(CONFIG_PATH.read_bytes()).hexdigest() == ( + M8_L2_ANALYSIS_CONFIG_SOURCE_SHA256 + ) + assert config.source_sha256 == M8_L2_ANALYSIS_CONFIG_SOURCE_SHA256 + assert config.semantic_sha256 == M8_L2_ANALYSIS_CONFIG_SEMANTIC_SHA256 + assert config.hash == M8_L2_ANALYSIS_CONFIG_SEMANTIC_SHA256 + assert config.study.symbols == ("BTCUSDT", "ETHUSDT") + assert config.study.training_role == "train" + assert config.study.selection_role == "validation" + assert config.study.primary_endpoint_role == "primary_test" + assert config.study.replication_endpoint_role == "replication_test" + + assert config.features.decision_scope == "per_symbol_verified_observed_intervals" + assert config.features.flat_direction_policy == "flat_is_non_up" + assert config.features.rolling_windows == (20, 100) + assert config.features.volatility_window == 100 + assert config.features.model_feature_columns == ( + "spread_bps", + "depth_total_l1", + "depth_total_l5", + "depth_total_l10", + "queue_imbalance_l1", + "queue_imbalance_l5", + "queue_imbalance_l10", + "microprice_deviation_bps", + "ofi_l1", + "ofi_w20", + "ofi_w100", + "cancellation_intensity_w20", + "cancellation_intensity_w100", + "realized_volatility_w20", + "realized_volatility_w100", + "volatility_regime_low", + "volatility_regime_high", + "liquidity_regime_liquid", + "liquidity_regime_stressed", + ) + assert config.features.clock_max_state_age_ms == 500 + assert config.features.clock_target_policy == ("exact_target_locf_same_valid_observed_interval") + assert config.features.clock_label_information_end == "exact_target" + assert config.features.clock_record_target_sequence is True + assert config.features.clock_censor_if_no_eligible_state is True + + assert [endpoint.name for endpoint in config.endpoints] == [ + "event_20", + "event_100", + "clock_1000ms", + "clock_5000ms", + ] + assert [(endpoint.domain, endpoint.horizon_value) for endpoint in config.endpoints] == [ + ("event", 20), + ("event", 100), + ("clock", 1000), + ("clock", 5000), + ] + assert [endpoint.paired_block_width for endpoint in config.endpoints] == [40, 200, 2000, 10000] + assert [endpoint.paired_block_unit for endpoint in config.endpoints] == [ + "events", + "events", + "milliseconds", + "milliseconds", + ] + assert [endpoint.nominal_event_block_width for endpoint in config.endpoints] == [ + 40, + 200, + 20, + 100, + ] + + assert config.regimes.fit_role == "train" + assert config.regimes.feature == "realized_volatility_w100" + assert config.regimes.quantile_numerators == (1, 2) + assert config.regimes.quantile_denominator == 3 + assert config.calibration.bins == 10 + assert config.bootstrap.method == "paired_moving_block" + assert config.bootstrap.samples == 2000 + assert config.signed_impact.metric == "ofi_signed_future_mid_markout" + assert config.signed_impact.side_rule == "sign_of_horizon_matched_ofi" + assert config.signed_impact.price_rule == "ofi_sign_times_future_log_mid_return_bps" + + assert config.execution.market_orders_only is True + assert config.execution.probability_threshold == 0.55 + assert config.execution.symmetric_probability_thresholds is True + assert config.execution.order_notional_usd == 100.0 + assert config.execution.max_l1_participation == 0.10 + assert config.execution.inventory_order_multiples == 10 + assert config.execution.reference_price_fit_role == "train" + assert config.execution.reference_depth_fit_role == "train" + assert config.execution.reference_price_statistic == "train_median_mid_price" + assert config.execution.reference_depth_statistic == "train_q05_min_bid_ask_l1_depth" + assert config.execution.reference_quantity_policy == ( + "min_100usd_and_10pct_train_q05_l1_depth_rounded_down_to_lot" + ) + assert config.execution.l1_fill_policy == "fill_up_to_recorded_l1_depth_cancel_remainder" + assert config.execution.scenario_reset_policy == ("per_symbol_session_endpoint_latency_pair") + assert config.execution.extra_slippage_bps == 0.0 + assert config.execution.liquidate_at_end is True + assert config.claims.allow_capacity_claim is False + assert config.claims.allow_realized_execution_claim is False + assert config.claims.allow_profitability_claim is False + + public = config.public_dict() + assert public["semantic_sha256"] == M8_L2_ANALYSIS_CONFIG_SEMANTIC_SHA256 + assert public["source_sha256"] == M8_L2_ANALYSIS_CONFIG_SOURCE_SHA256 + + +def test_analysis_config_objects_are_immutable() -> None: + config = load_m8_l2_analysis_config(CONFIG_PATH) + + with pytest.raises(FrozenInstanceError): + config.execution.probability_threshold = 0.99 # type: ignore[misc] + + +def test_semantic_hash_ignores_formatting_but_authority_loader_does_not(tmp_path: Path) -> None: + canonical_hash = semantic_hash_m8_l2_analysis_config(CONFIG_PATH) + formatted = tmp_path / "formatted.toml" + formatted.write_text( + "# Formatting is not part of the semantic identity.\n\n" + + CONFIG_PATH.read_text(encoding="utf-8"), + encoding="utf-8", + ) + + assert semantic_hash_m8_l2_analysis_config(formatted) == canonical_hash + with pytest.raises(M8L2AnalysisConfigError, match="configuration bytes do not match"): + load_m8_l2_analysis_config(formatted) + + +@pytest.mark.parametrize( + ("line_number", "mutated_source"), + _all_field_mutations(), + ids=lambda value: f"line-{value}" if isinstance(value, int) else None, +) +def test_changing_any_declared_field_fails_closed( + line_number: int, mutated_source: str, tmp_path: Path +) -> None: + path = tmp_path / f"changed-line-{line_number}.toml" + path.write_text(mutated_source, encoding="utf-8") + + with pytest.raises(M8L2AnalysisConfigError): + load_m8_l2_analysis_config(path) + + +def test_extra_and_missing_keys_fail_closed(tmp_path: Path) -> None: + extra = _write_mutation( + tmp_path, + "[calibration]\nbins = 10", + "[calibration]\nbins = 10\nunreviewed = true", + ) + with pytest.raises(M8L2AnalysisConfigError, match=r"calibration keys differ.*unreviewed"): + load_m8_l2_analysis_config(extra) + + missing = _write_mutation(tmp_path, "bins = 10\n", "") + with pytest.raises(M8L2AnalysisConfigError, match=r"calibration keys differ.*bins"): + load_m8_l2_analysis_config(missing) + + +@pytest.mark.parametrize( + ("old", "new", "message"), + [ + ( + "probability_threshold = 0.55", + "probability_threshold = nan", + "must be a finite number", + ), + ( + "max_l1_participation = 0.10", + "max_l1_participation = -0.10", + r"must be in \(0, 1\]", + ), + ( + "clock_max_state_age_ms = 500", + "clock_max_state_age_ms = -1", + "must be nonnegative", + ), + ( + "samples = 2000", + "samples = true", + "must be an integer", + ), + ], +) +def test_illegal_numeric_values_fail_before_source_authority( + old: str, new: str, message: str, tmp_path: Path +) -> None: + path = _write_mutation(tmp_path, old, new) + + with pytest.raises(M8L2AnalysisConfigError, match=message): + load_m8_l2_analysis_config(path) diff --git a/Microstructure/tests/test_m8_l2_binance.py b/Microstructure/tests/test_m8_l2_binance.py new file mode 100644 index 0000000000000000000000000000000000000000..623c1d78c5ba4b1bebd504c5167901813c103de6 --- /dev/null +++ b/Microstructure/tests/test_m8_l2_binance.py @@ -0,0 +1,786 @@ +from __future__ import annotations + +import asyncio +import base64 +import hashlib +import json +import threading +import time +from collections.abc import AsyncIterator, Callable +from decimal import Decimal +from pathlib import Path + +import pytest + +from microstructure import m8_l2_binance as adapter_module +from microstructure.data.binance import ( + BinanceHTTPError, + CapturedDepth, + RawDepthFrame, + SymbolMetadata, +) +from microstructure.data.book import BookSnapshot, DepthDelta +from microstructure.data.storage import write_source_manifest +from microstructure.m8_l2_binance import BinanceM8L2Capture +from microstructure.m8_l2_capture import M8L2DataFailure +from microstructure.m8_l2_config import M8L2CaptureLimits +from microstructure.provenance import read_json, sha256_file, utc_now_iso + +START_NS = 1_000_000_000 +END_NS = 20_000_000_000 +SESSION_ID = "a" * 64 + + +def _limits( + *, + max_messages: int = 100, + max_raw_frame_bytes: int = 1_048_576, + max_arrow_batch_bytes: int = 16_777_216, +) -> M8L2CaptureLimits: + return M8L2CaptureLimits( + duration_seconds=19, + max_messages_per_symbol=max_messages, + max_raw_frame_bytes=max_raw_frame_bytes, + max_arrow_batch_bytes=max_arrow_batch_bytes, + min_overlapping_coverage_seconds=1, + min_single_continuity_epoch_seconds=1, + require_complete_status=True, + require_live_reconstruction=True, + max_sequence_gaps=0, + max_quality_errors=0, + max_quality_warnings=0, + ) + + +def _raw_artifact( + raw_root: Path, + *, + dataset: str, + symbol: str, + payload: bytes, +) -> tuple[Path, Path, str]: + digest = hashlib.sha256(payload).hexdigest() + path = raw_root / "binance_spot" / dataset / symbol / f"{digest}.json" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(payload) + manifest, _ = write_source_manifest( + path, + source="binance_spot_public_api", + source_uri="https://example.invalid/public", + downloaded_at_utc=utc_now_iso(), + requested_start_ns=None, + requested_end_ns=None, + ) + return path, manifest, digest + + +def _metadata(raw_root: Path, symbol: str) -> SymbolMetadata: + payload = json.dumps({"symbol": symbol}, sort_keys=True).encode() + path, manifest, digest = _raw_artifact( + raw_root, dataset="exchange_info", symbol=symbol, payload=payload + ) + return SymbolMetadata( + venue="binance_spot", + symbol=symbol, + status="TRADING", + base_asset=symbol[:-4], + quote_asset="USDT", + tick_size=Decimal("0.01"), + lot_size=Decimal("0.001"), + min_price=Decimal("0.01"), + max_price=Decimal("1000000"), + min_quantity=Decimal("0.001"), + max_quantity=Decimal("1000000"), + observed_ts_ns=START_NS, + source_artifact_id=digest, + source_path=path, + source_manifest_path=manifest, + ) + + +def _snapshot( + raw_root: Path, + symbol: str, + continuity_id: str, + *, + last_update_id: int = 0, +) -> BookSnapshot: + payload = json.dumps( + { + "asks": [["100.02", "0.010"]], + "bids": [["100.00", "0.010"]], + "lastUpdateId": last_update_id, + }, + sort_keys=True, + separators=(",", ":"), + ).encode() + _, _, digest = _raw_artifact( + raw_root, dataset="depth_snapshots", symbol=symbol, payload=payload + ) + return BookSnapshot( + venue="binance_spot", + symbol=symbol, + snapshot_id=digest, + request_ts_ns=START_NS, + received_ts_ns=START_NS + 1, + available_ts_ns=START_NS + 1, + continuity_id=continuity_id, + last_update_id=last_update_id, + depth_limit=5_000, + bids=((10_000, 10),), + asks=((10_002, 10),), + tick_size=0.01, + lot_size=0.001, + source_artifact_id=digest, + ) + + +def _captured( + symbol: str, + *, + sequence: int, + received_ns: int, + continuity_id: str = "continuity-1", + first_update_id: int | None = None, + previous_update_id: int | None = None, +) -> CapturedDepth: + payload = json.dumps( + { + "continuity": continuity_id, + "received": received_ns, + "sequence": sequence, + "symbol": symbol, + }, + sort_keys=True, + separators=(",", ":"), + ) + return CapturedDepth( + raw_payload=payload, + delta=DepthDelta( + venue="binance_spot", + symbol=symbol, + event_ts_ns=received_ns - 10, + received_ts_ns=received_ns, + available_ts_ns=received_ns, + availability_basis="local_receive_time", + capture_seq=sequence, + continuity_id=continuity_id, + first_update_id=(sequence if first_update_id is None else first_update_id), + last_update_id=sequence, + previous_update_id=(sequence - 1 if previous_update_id is None else previous_update_id), + bids=((10_000, 10 + sequence),), + asks=(), + tick_size=0.01, + lot_size=0.001, + source_artifact_id=hashlib.sha256(payload.encode()).hexdigest(), + ), + ) + + +class _FakeClient: + def __init__( + self, + *, + snapshot_last_update_id: int = 0, + snapshot_hook: Callable[[], None] | None = None, + metadata_hook: Callable[[], None] | None = None, + ) -> None: + self.snapshot_last_update_id = snapshot_last_update_id + self.snapshot_hook = snapshot_hook + self.metadata_hook = metadata_hook + + def fetch_exchange_info(self, *, symbol: str, raw_root: Path) -> SymbolMetadata: + if self.metadata_hook is not None: + self.metadata_hook() + return _metadata(raw_root, symbol) + + def fetch_depth_snapshot(self, **kwargs: object) -> BookSnapshot: + if self.snapshot_hook is not None: + self.snapshot_hook() + return _snapshot( + Path(kwargs["raw_root"]), + str(kwargs["symbol"]), + str(kwargs["continuity_id"]), + last_update_id=self.snapshot_last_update_id, + ) + + +def _collector_factory( + items: list[CapturedDepth], + *, + on_yield: Callable[[int], None] | None = None, + event_clock: list[int] | None = None, +) -> Callable[..., object]: + class FakeCollector: + url = "wss://example.invalid/depth" + + def __init__(self, **kwargs: object) -> None: + self.callback = kwargs["on_raw_frame"] + + async def stream(self, *, max_messages: int | None = None) -> AsyncIterator[CapturedDepth]: + assert max_messages is None + for index, item in enumerate(items): + received_ns = item.delta.received_ts_ns + capture_seq = item.delta.capture_seq + assert received_ns is not None and capture_seq is not None + if event_clock is not None: + event_clock[0] = max(event_clock[0], received_ns) + callback = cast_callback(self.callback) + callback( + RawDepthFrame( + payload=item.raw_payload.encode(), + was_text=True, + received_ts_ns=received_ns, + capture_seq=capture_seq, + continuity_id=item.delta.continuity_id, + ) + ) + if on_yield is not None: + on_yield(index) + yield item + await asyncio.sleep(0) + + return FakeCollector + + +def cast_callback(value: object) -> Callable[[RawDepthFrame], None]: + assert callable(value) + return value # type: ignore[return-value] + + +def _run( + root: Path, + items: list[CapturedDepth], + *, + client: _FakeClient | None = None, + limits: M8L2CaptureLimits | None = None, + queue_capacity: int = 1_024, +) -> object: + event_clock = [START_NS] + adapter = BinanceM8L2Capture( + client_factory=lambda: client or _FakeClient(), + collector_factory=_collector_factory(items, event_clock=event_clock), + clock_ns=lambda: event_clock[0], + receiver_queue_capacity=queue_capacity, + ) + return asyncio.run( + adapter( + symbol="BTCUSDT", + scheduled_start_ns=START_NS, + scheduled_end_ns=END_NS, + stage_root=root, + limits=limits or _limits(), + session_id=SESSION_ID, + ) + ) + + +def test_exact_end_excludes_future_frame_and_reconciles_all_artifacts(tmp_path: Path) -> None: + items = [ + _captured("BTCUSDT", sequence=1, received_ns=START_NS + 1_000), + _captured("BTCUSDT", sequence=2, received_ns=START_NS + 2_000), + _captured("BTCUSDT", sequence=3, received_ns=END_NS), + ] + + result = _run(tmp_path, items) + + assert result.status == "COMPLETE" # type: ignore[union-attr] + assert result.completion_reason == "scheduled_end_reached" # type: ignore[union-attr] + assert result.messages == result.normalized_rows == 2 # type: ignore[union-attr] + assert result.reconstructed_rows == 2 # type: ignore[union-attr] + assert result.excluded_rows == 0 # type: ignore[union-attr] + [interval] = result.valid_observed_intervals # type: ignore[union-attr] + assert interval.start_received_ns == START_NS + 1_000 + assert interval.end_received_ns_exclusive == START_NS + 2_001 + actual = {path.resolve() for path in tmp_path.rglob("*") if path.is_file()} + declared = {item.path.resolve() for item in result.artifacts} # type: ignore[union-attr] + assert declared == actual + assert all(sha256_file(item.path) == item.sha256 for item in result.artifacts) # type: ignore[union-attr] + kinds = {item.kind for item in result.artifacts} # type: ignore[union-attr] + assert { + "capture_summary", + "normalized_data", + "normalized_manifest", + "quality_report", + "raw_journal", + "raw_journal_manifest", + "raw_snapshot", + "raw_snapshot_manifest", + }.issubset(kinds) + summary = read_json(tmp_path / "quality" / "capture.summary.json") + assert summary["first_raw_received_ns"] == START_NS + 1_000 + assert summary["last_raw_received_ns"] == START_NS + 2_000 + expected_inventory = [ + { + "path": item.path.relative_to(tmp_path).as_posix(), + "kind": item.kind, + "sha256": item.sha256, + "bytes": item.path.stat().st_size, + } + for item in result.artifacts # type: ignore[union-attr] + if item.kind != "capture_summary" + ] + assert summary["artifact_inventory_without_summary"] == expected_inventory + journal_path = next( + item.path + for item in result.artifacts + if item.kind == "raw_journal" # type: ignore[union-attr] + ) + events = [json.loads(line) for line in journal_path.read_text().splitlines()] + raw_frames = [item for item in events if item["event_kind"] == "websocket_frame"] + assert len(raw_frames) == 2 + assert all(START_NS <= item["received_ts_ns"] < END_NS for item in raw_frames) + + +@pytest.mark.parametrize( + ("items", "snapshot_last_update_id", "expected_reconstructed", "expected_intervals"), + [ + ( + [ + _captured("BTCUSDT", sequence=1, received_ns=START_NS + 100), + _captured("BTCUSDT", sequence=2, received_ns=END_NS), + ], + 0, + 1, + 0, + ), + ( + [ + _captured("BTCUSDT", sequence=1, received_ns=START_NS + 100), + _captured("BTCUSDT", sequence=2, received_ns=START_NS + 200), + _captured("BTCUSDT", sequence=3, received_ns=END_NS), + ], + 10, + 0, + 0, + ), + ], +) +def test_one_message_and_stale_only_never_fabricate_coverage( + tmp_path: Path, + items: list[CapturedDepth], + snapshot_last_update_id: int, + expected_reconstructed: int, + expected_intervals: int, +) -> None: + result = _run( + tmp_path, + items, + client=_FakeClient(snapshot_last_update_id=snapshot_last_update_id), + ) + + assert result.reconstructed_rows == expected_reconstructed # type: ignore[union-attr] + assert len(result.valid_observed_intervals) == expected_intervals # type: ignore[union-attr] + + +def test_long_silence_splits_observed_intervals(tmp_path: Path) -> None: + first = START_NS + 100 + items = [ + _captured("BTCUSDT", sequence=1, received_ns=first), + _captured("BTCUSDT", sequence=2, received_ns=first + 1_000_000_000), + _captured("BTCUSDT", sequence=3, received_ns=first + 7_000_000_000), + _captured("BTCUSDT", sequence=4, received_ns=first + 8_000_000_000), + _captured("BTCUSDT", sequence=5, received_ns=END_NS), + ] + + result = _run(tmp_path, items) + + intervals = result.valid_observed_intervals # type: ignore[union-attr] + assert len(intervals) == 2 + assert intervals[0].end_received_ns_exclusive < intervals[1].start_received_ns + + +def test_snapshot_thread_does_not_block_bounded_receiver(tmp_path: Path) -> None: + snapshot_started = threading.Event() + release_snapshot = threading.Event() + yielded = 0 + + def block_snapshot() -> None: + snapshot_started.set() + assert release_snapshot.wait(timeout=5) + + def observe_yield(_: int) -> None: + nonlocal yielded + yielded += 1 + + items = [ + *[ + _captured("BTCUSDT", sequence=index, received_ns=START_NS + index * 1_000) + for index in range(1, 11) + ], + _captured("BTCUSDT", sequence=11, received_ns=END_NS), + ] + event_clock = [START_NS] + adapter = BinanceM8L2Capture( + client_factory=lambda: _FakeClient(snapshot_hook=block_snapshot), + collector_factory=_collector_factory( + items, on_yield=observe_yield, event_clock=event_clock + ), + clock_ns=lambda: event_clock[0], + receiver_queue_capacity=32, + ) + + async def scenario() -> object: + task = asyncio.create_task( + adapter( + symbol="BTCUSDT", + scheduled_start_ns=START_NS, + scheduled_end_ns=END_NS, + stage_root=tmp_path, + limits=_limits(), + session_id=SESSION_ID, + ) + ) + assert await asyncio.to_thread(snapshot_started.wait, 2) + for _ in range(100): + if yielded >= 10: + break + await asyncio.sleep(0.001) + assert yielded >= 10 + release_snapshot.set() + return await task + + result = asyncio.run(scenario()) + summary = read_json(tmp_path / "quality" / "capture.summary.json") + assert result.messages == 10 # type: ignore[union-attr] + assert summary["max_receiver_queue_depth"] > 1 + assert ( + summary["max_receiver_queue_estimated_bytes"] + <= summary["receiver_queue_estimated_byte_budget"] + ) + + +def test_metadata_thread_does_not_block_event_loop(tmp_path: Path) -> None: + metadata_started = threading.Event() + release_metadata = threading.Event() + heartbeat = False + + def block_metadata() -> None: + metadata_started.set() + assert release_metadata.wait(timeout=5) + + items = [ + _captured("BTCUSDT", sequence=1, received_ns=START_NS + 100), + _captured("BTCUSDT", sequence=2, received_ns=END_NS), + ] + event_clock = [START_NS] + adapter = BinanceM8L2Capture( + client_factory=lambda: _FakeClient(metadata_hook=block_metadata), + collector_factory=_collector_factory(items, event_clock=event_clock), + clock_ns=lambda: event_clock[0], + ) + + async def scenario() -> None: + nonlocal heartbeat + task = asyncio.create_task( + adapter( + symbol="BTCUSDT", + scheduled_start_ns=START_NS, + scheduled_end_ns=END_NS, + stage_root=tmp_path, + limits=_limits(), + session_id=SESSION_ID, + ) + ) + assert await asyncio.to_thread(metadata_started.wait, 2) + await asyncio.sleep(0) + heartbeat = True + release_metadata.set() + await task + + asyncio.run(scenario()) + assert heartbeat + + +def test_sequence_gap_is_typed_data_failure_with_exhaustive_partial_artifacts( + tmp_path: Path, +) -> None: + items = [ + _captured("BTCUSDT", sequence=1, received_ns=START_NS + 100), + _captured( + "BTCUSDT", + sequence=3, + received_ns=START_NS + 200, + first_update_id=3, + previous_update_id=1, + ), + _captured("BTCUSDT", sequence=4, received_ns=END_NS), + ] + + with pytest.raises(M8L2DataFailure) as raised: + _run(tmp_path, items) + + assert raised.value.reason_code == "SEQUENCE_CONTINUITY_FAILED" + partial = raised.value.partial_result + assert partial is not None + assert partial.status == "FAILED" + assert partial.sequence_gaps == 1 + actual = {path.resolve() for path in tmp_path.rglob("*") if path.is_file()} + assert {item.path.resolve() for item in partial.artifacts} == actual + + +def test_message_cap_preserves_raw_and_raises_typed_failure(tmp_path: Path) -> None: + items = [_captured("BTCUSDT", sequence=1, received_ns=START_NS + 100)] + + with pytest.raises(M8L2DataFailure) as raised: + _run(tmp_path, items, limits=_limits(max_messages=1)) + + assert raised.value.reason_code == "MESSAGE_SAFETY_CEILING_REACHED" + partial = raised.value.partial_result + assert partial is not None + assert partial.messages == 1 + assert partial.normalized_rows == 0 + + +def test_preparse_utf8_failure_retains_exact_bytes_and_is_typed(tmp_path: Path) -> None: + malformed = b"\xffnot-json" + + class MalformedCollector: + url = "wss://example.invalid/depth" + + def __init__(self, **kwargs: object) -> None: + self.callback = cast_callback(kwargs["on_raw_frame"]) + + async def stream(self, *, max_messages: int | None = None) -> AsyncIterator[CapturedDepth]: + self.callback( + RawDepthFrame( + payload=malformed, + was_text=False, + received_ts_ns=START_NS + 100, + capture_seq=0, + continuity_id="parse-failure", + ) + ) + raise UnicodeDecodeError("utf-8", malformed, 0, 1, "invalid start byte") + if False: # pragma: no cover + yield _captured("BTCUSDT", sequence=1, received_ns=START_NS + 100) + + adapter = BinanceM8L2Capture( + client_factory=lambda: _FakeClient(), + collector_factory=MalformedCollector, + clock_ns=lambda: START_NS, + ) + + with pytest.raises(M8L2DataFailure) as raised: + asyncio.run( + adapter( + symbol="BTCUSDT", + scheduled_start_ns=START_NS, + scheduled_end_ns=END_NS, + stage_root=tmp_path, + limits=_limits(), + session_id=SESSION_ID, + ) + ) + + assert raised.value.reason_code == "RAW_UTF8_DECODE_FAILED" + partial = raised.value.partial_result + assert partial is not None + journal = next(item.path for item in partial.artifacts if item.kind == "raw_journal") + [event] = [json.loads(line) for line in journal.read_text().splitlines()] + assert base64.b64decode(event["payload_base64"]) == malformed + + +def test_queue_byte_budget_is_hard_even_with_large_item_capacity(tmp_path: Path) -> None: + items = [ + _captured("BTCUSDT", sequence=1, received_ns=START_NS + 100), + _captured("BTCUSDT", sequence=2, received_ns=START_NS + 200), + _captured("BTCUSDT", sequence=3, received_ns=END_NS), + ] + + result = _run( + tmp_path, + items, + limits=_limits(max_arrow_batch_bytes=8_192), + queue_capacity=10_000, + ) + + summary = read_json(tmp_path / "quality" / "capture.summary.json") + assert summary["receiver_queue_estimated_byte_budget"] == 8_192 + assert summary["max_receiver_queue_estimated_bytes"] <= 8_192 + assert result.max_arrow_batch_bytes_observed <= 8_192 # type: ignore[union-attr] + + +def test_permission_error_remains_nonterminal_system_failure(tmp_path: Path) -> None: + class PermissionClient(_FakeClient): + def fetch_exchange_info(self, *, symbol: str, raw_root: Path) -> SymbolMetadata: + raise PermissionError("injected local permission failure") + + adapter = BinanceM8L2Capture( + client_factory=PermissionClient, + collector_factory=_collector_factory([]), + clock_ns=lambda: START_NS, + ) + + with pytest.raises(PermissionError, match="injected local permission failure"): + asyncio.run( + adapter( + symbol="BTCUSDT", + scheduled_start_ns=START_NS, + scheduled_end_ns=END_NS, + stage_root=tmp_path, + limits=_limits(), + session_id=SESSION_ID, + ) + ) + + assert not (tmp_path / "INSUFFICIENT_DATA").exists() + assert (tmp_path / "quality" / "capture.summary.json").is_file() + + +def test_exhausted_websocket_transport_is_typed_session_data_failure(tmp_path: Path) -> None: + item = _captured("BTCUSDT", sequence=1, received_ns=START_NS + 100) + + class DisconnectCollector: + url = "wss://example.invalid/depth" + + def __init__(self, **kwargs: object) -> None: + self.callback = cast_callback(kwargs["on_raw_frame"]) + + async def stream(self, *, max_messages: int | None = None) -> AsyncIterator[CapturedDepth]: + received_ns = item.delta.received_ts_ns + capture_seq = item.delta.capture_seq + assert received_ns is not None and capture_seq is not None + self.callback( + RawDepthFrame( + payload=item.raw_payload.encode(), + was_text=True, + received_ts_ns=received_ns, + capture_seq=capture_seq, + continuity_id=item.delta.continuity_id, + ) + ) + yield item + raise OSError("websocket retry budget exhausted") + + adapter = BinanceM8L2Capture( + client_factory=lambda: _FakeClient(), + collector_factory=DisconnectCollector, + clock_ns=lambda: START_NS, + ) + + with pytest.raises(M8L2DataFailure) as raised: + asyncio.run( + adapter( + symbol="BTCUSDT", + scheduled_start_ns=START_NS, + scheduled_end_ns=END_NS, + stage_root=tmp_path, + limits=_limits(), + session_id=SESSION_ID, + ) + ) + + assert raised.value.reason_code == "PUBLIC_STREAM_UNAVAILABLE" + assert raised.value.partial_result is not None + assert raised.value.partial_result.messages == 1 + + +def test_exhausted_public_rest_transport_is_typed_session_data_failure( + tmp_path: Path, +) -> None: + class UnavailableClient(_FakeClient): + def fetch_exchange_info(self, *, symbol: str, raw_root: Path) -> SymbolMetadata: + raise BinanceHTTPError("public REST retry budget exhausted", retry_exhausted=True) + + adapter = BinanceM8L2Capture( + client_factory=UnavailableClient, + collector_factory=_collector_factory([]), + clock_ns=lambda: START_NS, + ) + + with pytest.raises(M8L2DataFailure) as raised: + asyncio.run( + adapter( + symbol="BTCUSDT", + scheduled_start_ns=START_NS, + scheduled_end_ns=END_NS, + stage_root=tmp_path, + limits=_limits(), + session_id=SESSION_ID, + ) + ) + + assert raised.value.reason_code == "PUBLIC_TRANSPORT_UNAVAILABLE" + assert raised.value.phase == "PUBLIC_METADATA" + + +def test_local_raw_journal_oserror_remains_system_failure( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + item = _captured("BTCUSDT", sequence=1, received_ns=START_NS + 100) + + def fail_local_write(*args: object, **kwargs: object) -> None: + raise OSError("local disk write failed") + + monkeypatch.setattr(adapter_module._RawJournal, "_write", fail_local_write) + adapter = BinanceM8L2Capture( + client_factory=lambda: _FakeClient(), + collector_factory=_collector_factory([item]), + clock_ns=lambda: START_NS, + ) + + with pytest.raises(RuntimeError, match="local raw-journal write failed") as raised: + asyncio.run( + adapter( + symbol="BTCUSDT", + scheduled_start_ns=START_NS, + scheduled_end_ns=END_NS, + stage_root=tmp_path, + limits=_limits(), + session_id=SESSION_ID, + ) + ) + + assert not isinstance(raised.value, M8L2DataFailure) + + +def test_cancellation_joins_rest_worker_before_returning(tmp_path: Path) -> None: + metadata_started = threading.Event() + release_metadata = threading.Event() + + def block_metadata() -> None: + metadata_started.set() + assert release_metadata.wait(timeout=5) + + adapter = BinanceM8L2Capture( + client_factory=lambda: _FakeClient(metadata_hook=block_metadata), + collector_factory=_collector_factory([]), + clock_ns=lambda: START_NS, + ) + + async def scenario() -> None: + task = asyncio.create_task( + adapter( + symbol="BTCUSDT", + scheduled_start_ns=START_NS, + scheduled_end_ns=END_NS, + stage_root=tmp_path, + limits=_limits(), + session_id=SESSION_ID, + ) + ) + assert await asyncio.to_thread(metadata_started.wait, 2) + task.cancel() + await asyncio.sleep(0.01) + assert not task.done() + release_metadata.set() + with pytest.raises(asyncio.CancelledError): + await task + + asyncio.run(scenario()) + before = sorted( + (path.relative_to(tmp_path).as_posix(), sha256_file(path)) + for path in tmp_path.rglob("*") + if path.is_file() + ) + assert before + # No detached REST worker remains to mutate the retained evidence afterward. + time.sleep(0.01) + after = sorted( + (path.relative_to(tmp_path).as_posix(), sha256_file(path)) + for path in tmp_path.rglob("*") + if path.is_file() + ) + assert after == before diff --git a/Microstructure/tests/test_m8_l2_capture.py b/Microstructure/tests/test_m8_l2_capture.py new file mode 100644 index 0000000000000000000000000000000000000000..0f8b97a723303a6266922abe835283f934e3a866 --- /dev/null +++ b/Microstructure/tests/test_m8_l2_capture.py @@ -0,0 +1,1844 @@ +from __future__ import annotations + +import asyncio +import base64 +import hashlib +import json +import os +import shutil +import stat +from concurrent.futures import ThreadPoolExecutor +from dataclasses import replace +from pathlib import Path + +import pyarrow as pa # type: ignore[import-untyped] +import pyarrow.parquet as pq # type: ignore[import-untyped] +import pytest + +import microstructure.m8_l2_binance as binance_module +import microstructure.m8_l2_capture as l2_module +from microstructure.data.schemas import SCHEMA_VERSION, get_schema +from microstructure.m8_l2_capture import ( + CapturedArtifact, + CaptureSourceIdentity, + M8L2CaptureSystemError, + M8L2DataFailure, + M8L2SessionBundle, + M8L2VerificationError, + ObservedInterval, + SymbolCaptureResult, + capture_m8_l2_session, + current_m8_l2_runtime_fingerprint_sha256, + merge_observed_intervals, + overlapping_observed_coverage_ns, + verify_m8_l2_session_bundle, +) +from microstructure.m8_l2_config import M8L2Session, M8L2StudyConfig, load_m8_l2_config +from microstructure.provenance import read_json, sha256_file, write_json + +PROJECT_ROOT = Path(__file__).parents[1] +CONFIG_PATH = PROJECT_ROOT / "configs" / "m8_l2_capture_study.toml" +PROTOCOL_PATH = PROJECT_ROOT / "docs" / "M8_L2_PROTOCOL.md" +SOURCE = CaptureSourceIdentity(commit="1" * 40, source_tree_sha256="2" * 64, dirty=False) + + +class FakeClock: + def __init__( + self, + now_ns: int, + *, + finish_ns: int | None = None, + finish_on_call: int = 3, + ) -> None: + self.now_ns = now_ns + self.finish_ns = finish_ns + self.finish_on_call = finish_on_call + self.time_calls = 0 + self.sleeps: list[float] = [] + + def time_ns(self) -> int: + self.time_calls += 1 + if self.finish_ns is not None and self.time_calls >= self.finish_on_call: + self.now_ns = max(self.now_ns, self.finish_ns) + return self.now_ns + + async def sleep(self, seconds: float) -> None: + self.sleeps.append(seconds) + self.now_ns += round(seconds * 1_000_000_000) + await asyncio.sleep(0) + + +def _artifact(root: Path, name: str = "raw.ndjson") -> CapturedArtifact: + path = root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text('{"raw":true}\n', encoding="utf-8") + return CapturedArtifact(path=path, kind="raw_journal", sha256=sha256_file(path)) + + +def _parquet(path: Path, dataset: str, rows: int) -> None: + schema = get_schema(dataset) + + def value_for(field: pa.Field) -> object: + if field.name == "schema_version": + return SCHEMA_VERSION + if pa.types.is_string(field.type): + return "fixture" + if pa.types.is_integer(field.type): + return 1 + if pa.types.is_floating(field.type): + return 1.0 + if pa.types.is_boolean(field.type): + return True + if pa.types.is_list(field.type): + return [] + raise AssertionError(f"unsupported fixture type: {field.type}") + + table = pa.Table.from_arrays( + [pa.array([value_for(field)] * rows, type=field.type) for field in schema], + schema=schema, + ) + path.parent.mkdir(parents=True, exist_ok=True) + pq.write_table(table, path) + + +def _complete_artifacts( + root: Path, + *, + symbol: str, + start_ns: int, + end_ns: int, + intervals: tuple[ObservedInterval, ...], + reconstructed_rows: int, + excluded_rows: int, +) -> tuple[CapturedArtifact, ...]: + continuity_id = f"{symbol}-epoch-1" + snapshot_path = root / "raw" / "snapshot.json" + snapshot_manifest_path = root / "raw" / "snapshot.manifest.json" + snapshot_path.parent.mkdir(parents=True, exist_ok=True) + write_json(snapshot_path, {"lastUpdateId": 1}) + write_json(snapshot_manifest_path, {"checksum": sha256_file(snapshot_path)}) + + raw_path = root / "raw" / "capture.ndjson" + first_payload = b"x" * 1024 + last_payload = b"y" + journal_entries = [ + { + "continuity_id": continuity_id, + "event_kind": "rest_snapshot_anchor", + "raw_manifest_path": snapshot_manifest_path.relative_to(root).as_posix(), + "raw_manifest_sha256": sha256_file(snapshot_manifest_path), + "raw_path": snapshot_path.relative_to(root).as_posix(), + "raw_sha256": sha256_file(snapshot_path), + "received_ts_ns": start_ns + 1, + "snapshot_id": f"{symbol}-snapshot", + }, + { + "event_kind": "websocket_frame", + "payload_base64": base64.b64encode(first_payload).decode("ascii"), + "payload_bytes": len(first_payload), + "payload_sha256": hashlib.sha256(first_payload).hexdigest(), + "received_ts_ns": start_ns + 10_000_000_000, + }, + { + "event_kind": "websocket_frame", + "payload_base64": base64.b64encode(last_payload).decode("ascii"), + "payload_bytes": len(last_payload), + "payload_sha256": hashlib.sha256(last_payload).hexdigest(), + "received_ts_ns": end_ns - 10_000_000_001, + }, + ] + raw_path.write_bytes( + b"".join( + json.dumps(item, sort_keys=True, separators=(",", ":")).encode() + b"\n" + for item in journal_entries + ) + ) + raw_manifest_path = root / "raw" / "capture.manifest.json" + write_json( + raw_manifest_path, + { + "artifact_kind": "raw_source", + "bytes": raw_path.stat().st_size, + "checksum": {"algorithm": "sha256", "value": sha256_file(raw_path)}, + "path": raw_path.name, + "requested_range_ns": {"start": start_ns, "end_exclusive": end_ns}, + "response_headers": { + "x-local-message-count": "2", + "x-local-snapshot-anchor-count": "1", + }, + }, + ) + + dataset_rows = { + "book_snapshots": 1, + "depth_deltas": 2, + "book_observations": reconstructed_rows, + "sequence_gaps": 0, + } + dataset_summaries: dict[str, dict[str, object]] = {} + artifact_coordinates: list[tuple[Path, str]] = [ + (raw_path, "raw_journal"), + (raw_manifest_path, "raw_journal_manifest"), + (snapshot_path, "raw_snapshot"), + (snapshot_manifest_path, "raw_snapshot_manifest"), + ] + for dataset, rows in dataset_rows.items(): + data_path = root / "normalized" / f"{dataset}.parquet" + if rows: + _parquet(data_path, dataset, rows) + artifact_coordinates.append((data_path, "normalized_data")) + manifest_path = root / "normalized" / f"{dataset}.manifest.json" + write_json( + manifest_path, + { + "dataset": dataset, + "requested_range_ns": {"start": start_ns, "end_exclusive": end_ns}, + "rows": rows, + "schema_version": SCHEMA_VERSION, + }, + ) + artifact_coordinates.append((manifest_path, "normalized_manifest")) + dataset_summaries[dataset] = { + "data_path": data_path.relative_to(root).as_posix() if rows else None, + "data_sha256": sha256_file(data_path) if rows else None, + "manifest_path": manifest_path.relative_to(root).as_posix(), + "manifest_sha256": sha256_file(manifest_path), + "rows": rows, + } + + quality_paths: dict[str, str] = {} + for dataset in ("depth_deltas", "book_observations"): + path = root / "quality" / f"{dataset}.validation.json" + write_json( + path, + { + "dataset": dataset, + "rows_checked": dataset_rows[dataset], + "summary": {"errors": 0, "warnings": 0}, + }, + ) + artifact_coordinates.append((path, "quality_report")) + quality_paths[dataset] = path.relative_to(root).as_posix() + + without_summary = tuple( + CapturedArtifact(path=path, kind=kind, sha256=sha256_file(path)) + for path, kind in artifact_coordinates + ) + summary_path = root / "quality" / "capture.summary.json" + write_json( + summary_path, + { + "schema_version": "m8-binance-l2-symbol-capture-v1", + "symbol": symbol, + "capture_id": f"{symbol.lower()}-capture", + "capture_status": "COMPLETE", + "completion_reason": "scheduled_end_reached", + "reconstruction_status": "LIVE", + "failure_reason_code": None, + "failure_phase": None, + "scheduled_range_ns": {"start": start_ns, "end_exclusive": end_ns}, + "messages": 2, + "normalized_rows": 2, + "reconstructed_rows": reconstructed_rows, + "excluded_rows": excluded_rows, + "continuity_epochs": 1, + "snapshot_anchors": 1, + "sequence_gaps": 0, + "quality_errors": 0, + "quality_warnings": 0, + "max_raw_frame_bytes_observed": 1024, + "max_arrow_batch_bytes_observed": 8192, + "first_raw_received_ns": start_ns + 10_000_000_000, + "last_raw_received_ns": end_ns - 10_000_000_001, + "valid_observed_intervals": [item.to_dict() for item in intervals], + "raw_journal": raw_path.relative_to(root).as_posix(), + "raw_journal_sha256": sha256_file(raw_path), + "raw_journal_manifest": raw_manifest_path.relative_to(root).as_posix(), + "raw_journal_manifest_sha256": sha256_file(raw_manifest_path), + "normalized_dataset_manifests": dataset_summaries, + "quality_reports": quality_paths, + "artifact_inventory_without_summary": [ + { + "path": item.path.relative_to(root).as_posix(), + "kind": item.kind, + "sha256": item.sha256, + "bytes": item.path.stat().st_size, + } + for item in sorted(without_summary, key=lambda value: value.path.as_posix()) + ], + }, + ) + return ( + *without_summary, + CapturedArtifact( + path=summary_path, + kind="capture_summary", + sha256=sha256_file(summary_path), + ), + ) + + +def _complete_result( + *, + symbol: str, + root: Path, + start_ns: int, + end_ns: int, + intervals: tuple[ObservedInterval, ...] | None = None, +) -> SymbolCaptureResult: + valid = ( + ( + ObservedInterval( + continuity_id=f"{symbol}-epoch-1", + start_received_ns=start_ns + 10_000_000_000, + end_received_ns_exclusive=end_ns - 10_000_000_000, + ), + ) + if intervals is None + else intervals + ) + reconstructed_rows = 2 if valid else 0 + excluded_rows = 2 - reconstructed_rows + return SymbolCaptureResult( + symbol=symbol, + capture_id=f"{symbol.lower()}-capture", + status="COMPLETE", + completion_reason="scheduled_end_reached", + reconstruction_status="LIVE", + messages=2, + normalized_rows=2, + reconstructed_rows=reconstructed_rows, + excluded_rows=excluded_rows, + continuity_epochs=1, + snapshot_anchors=1, + sequence_gaps=0, + quality_errors=0, + quality_warnings=0, + max_raw_frame_bytes_observed=1024, + max_arrow_batch_bytes_observed=8192, + first_raw_received_ns=start_ns + 10_000_000_000, + last_raw_received_ns=end_ns - 10_000_000_001, + valid_observed_intervals=valid, + artifacts=_complete_artifacts( + root, + symbol=symbol, + start_ns=start_ns, + end_ns=end_ns, + intervals=valid, + reconstructed_rows=reconstructed_rows, + excluded_rows=excluded_rows, + ), + ) + + +def _manifest(bundle_root: Path) -> dict[str, object]: + value = read_json(bundle_root / "session_manifest.json") + assert isinstance(value, dict) + return value + + +def _refresh_manifest_checksum(bundle_root: Path, *other_paths: str) -> None: + checksum_path = bundle_root / "CHECKSUMS.sha256" + refreshed = {"session_manifest.json", *other_paths} + entries: list[str] = [] + for line in checksum_path.read_text(encoding="ascii").splitlines(): + relative = line[66:] + digest = sha256_file(bundle_root / relative) if relative in refreshed else line[:64] + entries.append(f"{digest} {relative}\n") + checksum_path.write_text("".join(entries), encoding="ascii") + + +def _capture_complete_session( + output_root: Path, + *, + config: M8L2StudyConfig, + session: M8L2Session, + source: CaptureSourceIdentity = SOURCE, +) -> M8L2SessionBundle: + async def capture_one(**kwargs: object) -> SymbolCaptureResult: + return _complete_result( + symbol=str(kwargs["symbol"]), + root=Path(str(kwargs["stage_root"])), + start_ns=session.start_ns, + end_ns=session.end_ns, + ) + + return asyncio.run( + capture_m8_l2_session( + config, + session.date.isoformat(), + output_root, + capture_one, + protocol_path=PROTOCOL_PATH, + clock=FakeClock(session.start_ns, finish_ns=session.end_ns), + _test_source_identity=source, + ) + ) + + +def _complete_bundle(tmp_path: Path) -> tuple[M8L2SessionBundle, M8L2StudyConfig, M8L2Session]: + config = load_m8_l2_config(CONFIG_PATH) + session = config.sessions[0] + bundle = _capture_complete_session( + tmp_path, + config=config, + session=session, + ) + return bundle, config, session + + +def test_one_exact_campaign_authority_binds_all_four_frozen_sessions(tmp_path: Path) -> None: + config = load_m8_l2_config(CONFIG_PATH) + bundles = [ + _capture_complete_session( + tmp_path, + config=config, + session=session, + ) + for session in config.sessions + ] + + campaign_path = tmp_path / "campaign_authority.json" + campaign_raw = campaign_path.read_bytes() + campaign_sha256 = hashlib.sha256(campaign_raw).hexdigest() + campaign = read_json(campaign_path) + campaign_nonce = campaign.pop("campaign_nonce") + output_root = campaign.pop("output_root") + runtime_fingerprint = campaign.pop("runtime_fingerprint") + runtime_fingerprint_sha256 = campaign.pop("runtime_fingerprint_sha256") + assert campaign == { + "schema_version": "m8-live-l2-campaign-authority-v2", + "artifact_kind": "m8_prospective_live_l2_campaign_authority", + "config_sha256": config.hash, + "config_source_sha256": config.source_sha256, + "protocol_sha256": l2_module.M8_L2_PROTOCOL_SHA256, + "protocol_freeze_commit": l2_module.M8_L2_FREEZE_COMMIT, + "runtime_commit": SOURCE.commit, + "runtime_source_tree_sha256": SOURCE.source_tree_sha256, + "runtime_dirty": False, + } + assert isinstance(campaign_nonce, str) + assert len(campaign_nonce) == 64 + assert all(character in "0123456789abcdef" for character in campaign_nonce) + root_metadata = tmp_path.stat() + assert output_root == { + "canonical_path": str(tmp_path), + "device": root_metadata.st_dev, + "inode": root_metadata.st_ino, + } + runtime = l2_module._runtime_fingerprint() + assert runtime_fingerprint == runtime.payload() + assert runtime_fingerprint_sha256 == runtime.sha256 + assert len({bundle.session_id for bundle in bundles}) == 4 + for bundle in bundles: + payload = _manifest(bundle.root) + assert payload["schema_version"] == "m8-live-l2-session-v3" + authority = payload["authority"] + assert isinstance(authority, dict) + assert authority["campaign_authority_sha256"] == campaign_sha256 + bundled_campaign = bundle.root / "authority" / "campaign_authority.json" + assert bundled_campaign.read_bytes() == campaign_raw + assert verify_m8_l2_session_bundle(bundle.root, expected_config=config) == bundle + + +def test_public_runtime_fingerprint_helper_matches_canonical_campaign_digest() -> None: + observed = current_m8_l2_runtime_fingerprint_sha256() + + assert observed == l2_module._runtime_fingerprint().sha256 + assert len(observed) == 64 + assert all(character in "0123456789abcdef" for character in observed) + assert "current_m8_l2_runtime_fingerprint_sha256" in l2_module.__all__ + + +def test_changed_clean_source_cannot_replace_or_extend_campaign_before_capture( + tmp_path: Path, +) -> None: + first, config, _ = _complete_bundle(tmp_path) + changed = CaptureSourceIdentity( + commit="3" * 40, + source_tree_sha256="4" * 64, + dirty=False, + ) + calls = 0 + + async def never(**kwargs: object) -> SymbolCaptureResult: + nonlocal calls + calls += 1 + raise AssertionError(kwargs) + + for session in (config.sessions[0], config.sessions[1]): + with pytest.raises(M8L2CaptureSystemError, match="campaign authority differs"): + asyncio.run( + capture_m8_l2_session( + config, + session.date.isoformat(), + tmp_path, + never, + protocol_path=PROTOCOL_PATH, + clock=FakeClock(session.start_ns), + _test_source_identity=changed, + ) + ) + + assert calls == 0 + assert list((tmp_path / "sessions").iterdir()) == [first.root] + assert not list(tmp_path.glob(".m8-l2-*")) + + +def test_git_status_failure_with_empty_output_precedes_campaign_and_adapter( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + config = load_m8_l2_config(CONFIG_PATH) + session = config.sessions[0] + output_root = tmp_path / "capture-output" + calls = 0 + + def failed_status(arguments: list[str], **kwargs: object) -> object: + if arguments[1:] == ["rev-parse", "HEAD"]: + return l2_module.subprocess.CompletedProcess( + arguments, + 0, + stdout=f"{'1' * 40}\n", + stderr="", + ) + if arguments[1:] == ["status", "--porcelain=v1", "--untracked-files=normal"]: + return l2_module.subprocess.CompletedProcess( + arguments, + 7, + stdout="", + stderr="status unavailable", + ) + raise AssertionError((arguments, kwargs)) + + async def never(**kwargs: object) -> SymbolCaptureResult: + nonlocal calls + calls += 1 + raise AssertionError(kwargs) + + monkeypatch.setattr(l2_module.subprocess, "run", failed_status) + with pytest.raises(M8L2CaptureSystemError, match="status lookup failed with exit 7"): + asyncio.run( + capture_m8_l2_session( + config, + session.date.isoformat(), + output_root, + never, + protocol_path=PROTOCOL_PATH, + clock=FakeClock(session.start_ns), + _test_allow_injected_capture=True, + ) + ) + + assert calls == 0 + assert not output_root.exists() + + +def test_wrong_import_origin_precedes_git_campaign_and_adapter( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + config = load_m8_l2_config(CONFIG_PATH) + session = config.sessions[0] + foreign_module = tmp_path / "foreign" / "m8_l2_capture.py" + foreign_module.parent.mkdir() + foreign_module.write_text("# wrong checkout\n", encoding="utf-8") + output_root = tmp_path / "capture-output" + git_calls = 0 + adapter_calls = 0 + + def no_git(*args: object, **kwargs: object) -> object: + nonlocal git_calls + git_calls += 1 + raise AssertionError((args, kwargs)) + + async def never(**kwargs: object) -> SymbolCaptureResult: + nonlocal adapter_calls + adapter_calls += 1 + raise AssertionError(kwargs) + + monkeypatch.setattr(l2_module, "__file__", str(foreign_module)) + monkeypatch.setattr(l2_module.subprocess, "run", no_git) + with pytest.raises(M8L2CaptureSystemError, match="does not come from the hashed"): + asyncio.run( + capture_m8_l2_session( + config, + session.date.isoformat(), + output_root, + never, + protocol_path=PROTOCOL_PATH, + clock=FakeClock(session.start_ns), + _test_allow_injected_capture=True, + ) + ) + + assert git_calls == 0 + assert adapter_calls == 0 + assert not output_root.exists() + + +def test_foreign_production_adapter_origin_precedes_git_and_network( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + config = load_m8_l2_config(CONFIG_PATH) + session = config.sessions[0] + output_root = tmp_path / "capture-output" + foreign_module = tmp_path / "foreign" / "m8_l2_binance.py" + foreign_module.parent.mkdir() + foreign_module.write_text("# mixed editable checkout\n", encoding="utf-8") + git_calls = 0 + capture_calls = 0 + + def no_git(*args: object, **kwargs: object) -> object: + nonlocal git_calls + git_calls += 1 + raise AssertionError((args, kwargs)) + + async def no_capture(*args: object, **kwargs: object) -> SymbolCaptureResult: + nonlocal capture_calls + capture_calls += 1 + raise AssertionError((args, kwargs)) + + monkeypatch.setattr(binance_module, "__file__", str(foreign_module)) + monkeypatch.setattr(binance_module.BinanceM8L2Capture, "__call__", no_capture) + monkeypatch.setattr(l2_module.subprocess, "run", no_git) + with pytest.raises(M8L2CaptureSystemError, match="foreign or mixed import origin"): + asyncio.run( + capture_m8_l2_session( + config, + session.date.isoformat(), + output_root, + binance_module.BinanceM8L2Capture(), + protocol_path=PROTOCOL_PATH, + clock=FakeClock(session.start_ns), + ) + ) + + assert git_calls == 0 + assert capture_calls == 0 + assert not output_root.exists() + + +def test_campaign_tamper_and_symlink_fail_before_capture(tmp_path: Path) -> None: + tampered_root = tmp_path / "tampered" + _, config, _ = _complete_bundle(tampered_root) + campaign_path = tampered_root / "campaign_authority.json" + campaign = read_json(campaign_path) + assert isinstance(campaign, dict) + campaign["runtime_source_tree_sha256"] = "5" * 64 + write_json(campaign_path, campaign) + calls = 0 + + async def never(**kwargs: object) -> SymbolCaptureResult: + nonlocal calls + calls += 1 + raise AssertionError(kwargs) + + validation = config.sessions[1] + with pytest.raises(M8L2CaptureSystemError, match="campaign authority differs"): + asyncio.run( + capture_m8_l2_session( + config, + validation.date.isoformat(), + tampered_root, + never, + protocol_path=PROTOCOL_PATH, + clock=FakeClock(validation.start_ns), + _test_source_identity=SOURCE, + ) + ) + + symlink_root = tmp_path / "symlinked" + _complete_bundle(symlink_root) + authority_path = symlink_root / "campaign_authority.json" + preserved = tmp_path / "preserved-campaign-authority.json" + preserved.write_bytes(authority_path.read_bytes()) + authority_path.unlink() + authority_path.symlink_to(preserved) + with pytest.raises(M8L2CaptureSystemError, match="symlink"): + asyncio.run( + capture_m8_l2_session( + config, + validation.date.isoformat(), + symlink_root, + never, + protocol_path=PROTOCOL_PATH, + clock=FakeClock(validation.start_ns), + _test_source_identity=SOURCE, + ) + ) + assert calls == 0 + + +def test_runtime_drift_before_later_session_rejects_without_adapter( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + _, config, _ = _complete_bundle(tmp_path) + actual = l2_module._runtime_fingerprint() + drifted_payload = actual.payload() + python_payload = drifted_payload["python"] + assert isinstance(python_payload, dict) + python_payload["version"] = f"{python_payload['version']}-drift" + drifted = l2_module._runtime_from_recorded( + drifted_payload, l2_module._stable_sha256(drifted_payload) + ) + calls = 0 + + async def never(**kwargs: object) -> SymbolCaptureResult: + nonlocal calls + calls += 1 + raise AssertionError(kwargs) + + monkeypatch.setattr(l2_module, "_runtime_fingerprint", lambda: drifted) + validation = config.sessions[1] + with pytest.raises(M8L2CaptureSystemError, match="current production runtime"): + asyncio.run( + capture_m8_l2_session( + config, + validation.date.isoformat(), + tmp_path, + never, + protocol_path=PROTOCOL_PATH, + clock=FakeClock(validation.start_ns), + _test_source_identity=SOURCE, + ) + ) + + assert calls == 0 + assert len(list((tmp_path / "sessions").iterdir())) == 1 + + +def test_same_source_in_two_roots_has_distinct_campaign_and_session_identity( + tmp_path: Path, +) -> None: + config = load_m8_l2_config(CONFIG_PATH) + session = config.sessions[0] + first = _capture_complete_session(tmp_path / "first", config=config, session=session) + second = _capture_complete_session(tmp_path / "second", config=config, session=session) + + first_campaign = sha256_file(tmp_path / "first" / "campaign_authority.json") + second_campaign = sha256_file(tmp_path / "second" / "campaign_authority.json") + assert first_campaign != second_campaign + assert first.session_id != second.session_id + + +def test_copied_campaign_or_root_cannot_be_reused(tmp_path: Path) -> None: + first_root = tmp_path / "first" + _, config, _ = _complete_bundle(first_root) + copied_root = tmp_path / "copied" + shutil.copytree(first_root, copied_root) + validation = config.sessions[1] + calls = 0 + + async def never(**kwargs: object) -> SymbolCaptureResult: + nonlocal calls + calls += 1 + raise AssertionError(kwargs) + + with pytest.raises(M8L2CaptureSystemError, match="current output-root identity"): + asyncio.run( + capture_m8_l2_session( + config, + validation.date.isoformat(), + copied_root, + never, + protocol_path=PROTOCOL_PATH, + clock=FakeClock(validation.start_ns), + _test_source_identity=SOURCE, + ) + ) + + assert calls == 0 + + +def test_concurrent_campaign_creation_converges_on_one_exact_authority(tmp_path: Path) -> None: + config = load_m8_l2_config(CONFIG_PATH) + root, root_identity, _ = l2_module._prepare_output_root(tmp_path) + runtime = l2_module._runtime_fingerprint() + + def create() -> l2_module._CampaignAuthority: + return l2_module._ensure_campaign_authority( + root, + root_identity=root_identity, + config=config, + source=SOURCE, + runtime=runtime, + ) + + with ThreadPoolExecutor(max_workers=8) as pool: + futures = [pool.submit(create) for _ in range(8)] + authorities = [future.result() for future in futures] + + campaign = l2_module._verify_campaign_authority( + root, + root_identity=root_identity, + config=config, + source=SOURCE, + runtime=runtime, + ) + assert {authority.sha256 for authority in authorities} == {campaign.sha256} + assert {authority.nonce for authority in authorities} == {campaign.nonce} + assert campaign.sha256 == hashlib.sha256(campaign.raw).hexdigest() + assert not list(root.glob(".campaign-authority-*")) + + +def test_first_campaign_write_fsyncs_file_before_link_and_directory_after_link( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + config = load_m8_l2_config(CONFIG_PATH) + root, root_identity, _ = l2_module._prepare_output_root(tmp_path) + real_fsync = l2_module.os.fsync + real_link = l2_module.os.link + file_fsynced_before_link = False + linked = False + directory_fsynced_after_link = False + + def observed_fsync(descriptor: int) -> None: + nonlocal file_fsynced_before_link, directory_fsynced_after_link + metadata = os.fstat(descriptor) + if stat.S_ISREG(metadata.st_mode) and not linked: + file_fsynced_before_link = True + if stat.S_ISDIR(metadata.st_mode) and linked: + directory_fsynced_after_link = True + real_fsync(descriptor) + + def observed_link(source: object, destination: object, **kwargs: object) -> None: + nonlocal linked + assert file_fsynced_before_link + real_link(source, destination, **kwargs) + linked = True + + monkeypatch.setattr(l2_module.os, "fsync", observed_fsync) + monkeypatch.setattr(l2_module.os, "link", observed_link) + campaign = l2_module._ensure_campaign_authority( + root, + root_identity=root_identity, + config=config, + source=SOURCE, + runtime=l2_module._runtime_fingerprint(), + ) + + assert campaign.path == root / "campaign_authority.json" + assert linked + assert directory_fsynced_after_link + + +def test_bundle_verifier_rejects_rechecksummed_campaign_forgery(tmp_path: Path) -> None: + bundle, _, _ = _complete_bundle(tmp_path) + campaign_relative = "authority/campaign_authority.json" + campaign_path = bundle.root / campaign_relative + campaign = read_json(campaign_path) + assert isinstance(campaign, dict) + campaign["runtime_source_tree_sha256"] = "6" * 64 + write_json(campaign_path, campaign) + forged_sha256 = sha256_file(campaign_path) + payload = _manifest(bundle.root) + authority = payload["authority"] + assert isinstance(authority, dict) + authority["campaign_authority_sha256"] = forged_sha256 + write_json(bundle.manifest_path, payload) + _refresh_manifest_checksum(bundle.root, campaign_relative) + + with pytest.raises(M8L2VerificationError, match="bundled campaign authority"): + verify_m8_l2_session_bundle(bundle.root) + + +def test_bundle_verifier_rejects_runtime_tamper_and_coherent_rehash(tmp_path: Path) -> None: + plain_bundle, _, _ = _complete_bundle(tmp_path / "plain") + plain_payload = _manifest(plain_bundle.root) + plain_authority = plain_payload["authority"] + assert isinstance(plain_authority, dict) + plain_runtime = plain_authority["runtime_fingerprint"] + assert isinstance(plain_runtime, dict) + plain_dependencies = plain_runtime["dependencies"] + assert isinstance(plain_dependencies, dict) + plain_dependencies["polars"] = "forged" + write_json(plain_bundle.manifest_path, plain_payload) + _refresh_manifest_checksum(plain_bundle.root) + with pytest.raises(M8L2VerificationError, match="runtime fingerprint"): + verify_m8_l2_session_bundle(plain_bundle.root) + + forged_bundle, _, _ = _complete_bundle(tmp_path / "coherent") + campaign_relative = "authority/campaign_authority.json" + campaign_path = forged_bundle.root / campaign_relative + campaign = read_json(campaign_path) + assert isinstance(campaign, dict) + runtime_payload = campaign["runtime_fingerprint"] + assert isinstance(runtime_payload, dict) + dependencies = runtime_payload["dependencies"] + assert isinstance(dependencies, dict) + dependencies["polars"] = "forged" + runtime_sha256 = l2_module._stable_sha256(runtime_payload) + campaign["runtime_fingerprint_sha256"] = runtime_sha256 + write_json(campaign_path, campaign) + campaign_sha256 = sha256_file(campaign_path) + + payload = _manifest(forged_bundle.root) + authority = payload["authority"] + assert isinstance(authority, dict) + authority["runtime_fingerprint"] = runtime_payload + authority["runtime_fingerprint_sha256"] = runtime_sha256 + authority["campaign_authority_sha256"] = campaign_sha256 + inventory = payload["artifact_inventory"] + assert isinstance(inventory, list) + campaign_entry = next( + item + for item in inventory + if isinstance(item, dict) and item.get("path") == campaign_relative + ) + campaign_entry["sha256"] = campaign_sha256 + campaign_entry["bytes"] = campaign_path.stat().st_size + write_json(forged_bundle.manifest_path, payload) + _refresh_manifest_checksum(forged_bundle.root, campaign_relative) + + with pytest.raises(M8L2VerificationError, match="session_id"): + verify_m8_l2_session_bundle(forged_bundle.root) + + +def test_bundle_verifier_does_not_depend_on_current_runtime( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + bundle, config, _ = _complete_bundle(tmp_path) + + def forbidden() -> object: + raise AssertionError("offline verification must not inspect the current runtime") + + monkeypatch.setattr(l2_module, "_runtime_fingerprint", forbidden) + assert verify_m8_l2_session_bundle(bundle.root, expected_config=config) == bundle + + +def test_observed_interval_union_and_cross_symbol_intersection_do_not_bridge_gaps() -> None: + left = ( + ObservedInterval("left-a", 0, 100), + ObservedInterval("left-a", 80, 120), + ObservedInterval("left-b", 200, 400), + ) + right = ( + ObservedInterval("right-a", 50, 250), + ObservedInterval("right-b", 300, 500), + ) + + assert merge_observed_intervals(left) == ( + ObservedInterval("left-a", 0, 120), + ObservedInterval("left-b", 200, 400), + ) + assert overlapping_observed_coverage_ns(left, right) == 220 + + +def test_dual_capture_uses_one_absolute_barrier_and_publishes_verified_complete_bundle( + tmp_path: Path, +) -> None: + config = load_m8_l2_config(CONFIG_PATH) + session = config.sessions[0] + clock = FakeClock( + session.start_ns - 1_000_000_000, + finish_ns=session.end_ns, + finish_on_call=4, + ) + entered: set[str] = set() + both_entered = asyncio.Event() + requests: dict[str, tuple[int, int, str]] = {} + + async def capture_one(**kwargs: object) -> SymbolCaptureResult: + symbol = str(kwargs["symbol"]) + entered.add(symbol) + requests[symbol] = ( + int(kwargs["scheduled_start_ns"]), + int(kwargs["scheduled_end_ns"]), + str(kwargs["session_id"]), + ) + if len(entered) == 2: + both_entered.set() + await asyncio.wait_for(both_entered.wait(), timeout=1) + return _complete_result( + symbol=symbol, + root=Path(str(kwargs["stage_root"])), + start_ns=session.start_ns, + end_ns=session.end_ns, + ) + + bundle = asyncio.run( + capture_m8_l2_session( + config, + "2026-08-10", + tmp_path, + capture_one, + protocol_path=PROTOCOL_PATH, + clock=clock, + _test_source_identity=SOURCE, + ) + ) + + assert bundle.status == "COMPLETE" + assert bundle.marker_path.name == "_SUCCESS" + assert bundle.marker_path.read_bytes() == b"complete\n" + assert set(entered) == {"BTCUSDT", "ETHUSDT"} + assert clock.sleeps == [1.0] + assert {value[:2] for value in requests.values()} == {(session.start_ns, session.end_ns)} + assert len({value[2] for value in requests.values()}) == 1 + manifest = _manifest(bundle.root) + assert manifest["status"] == "COMPLETE" + assert manifest["reason_codes"] == [] + assert manifest["cross_symbol_observed_overlap_seconds"] == pytest.approx(3580.0) + symbols = manifest["symbols"] + assert isinstance(symbols, dict) + btc = symbols["BTCUSDT"] + assert btc["first_raw_received_ns"] == session.start_ns + 10_000_000_000 + assert btc["last_raw_received_ns"] == session.end_ns - 10_000_000_001 + assert btc["valid_observed_intervals"][0]["continuity_id"] == "BTCUSDT-epoch-1" + assert verify_m8_l2_session_bundle(bundle.root, expected_config=config) == bundle + + +def test_typed_failure_in_one_symbol_does_not_cancel_the_other_symbol(tmp_path: Path) -> None: + config = load_m8_l2_config(CONFIG_PATH) + session = config.sessions[0] + completed: set[str] = set() + + async def capture_one(**kwargs: object) -> SymbolCaptureResult: + symbol = str(kwargs["symbol"]) + root = Path(str(kwargs["stage_root"])) + if symbol == "BTCUSDT": + _artifact(root, "partial.ndjson") + await asyncio.sleep(0) + raise M8L2DataFailure( + "NETWORK_DISCONNECT", + phase="DUAL_CAPTURE", + message="declared feed disconnected", + ) + await asyncio.sleep(0.01) + completed.add(symbol) + return _complete_result( + symbol=symbol, + root=root, + start_ns=session.start_ns, + end_ns=session.end_ns, + ) + + bundle = asyncio.run( + capture_m8_l2_session( + config, + "2026-08-10", + tmp_path, + capture_one, + protocol_path=PROTOCOL_PATH, + clock=FakeClock(session.start_ns, finish_ns=session.end_ns), + _test_source_identity=SOURCE, + ) + ) + + assert completed == {"ETHUSDT"} + assert bundle.status == "INSUFFICIENT_DATA" + assert bundle.marker_path.name == "INSUFFICIENT_DATA" + assert bundle.marker_path.read_bytes() == b"terminal\n" + assert "NETWORK_DISCONNECT" in bundle.reason_codes + assert (bundle.root / "symbols" / "BTCUSDT" / "partial.ndjson").is_file() + assert not (bundle.root / "_SUCCESS").exists() + + +def test_only_observed_intervals_count_toward_epoch_and_overlap_gates(tmp_path: Path) -> None: + config = load_m8_l2_config(CONFIG_PATH) + session = config.sessions[0] + + async def capture_one(**kwargs: object) -> SymbolCaptureResult: + symbol = str(kwargs["symbol"]) + root = Path(str(kwargs["stage_root"])) + return _complete_result( + symbol=symbol, + root=root, + start_ns=session.start_ns, + end_ns=session.end_ns, + intervals=(), + ) + + bundle = asyncio.run( + capture_m8_l2_session( + config, + "2026-08-10", + tmp_path, + capture_one, + protocol_path=PROTOCOL_PATH, + clock=FakeClock(session.start_ns, finish_ns=session.end_ns), + _test_source_identity=SOURCE, + ) + ) + + assert bundle.status == "INSUFFICIENT_DATA" + assert "GATE_VALID_CONTINUITY_EPOCH_BTCUSDT" in bundle.reason_codes + assert "GATE_VALID_CONTINUITY_EPOCH_ETHUSDT" in bundle.reason_codes + assert "GATE_CROSS_SYMBOL_OBSERVED_OVERLAP" in bundle.reason_codes + + +def test_missed_absolute_window_is_terminal_insufficient_and_never_calls_capture( + tmp_path: Path, +) -> None: + config = load_m8_l2_config(CONFIG_PATH) + session = config.sessions[0] + called = False + + async def capture_one(**kwargs: object) -> SymbolCaptureResult: + nonlocal called + called = True + raise AssertionError(kwargs) + + bundle = asyncio.run( + capture_m8_l2_session( + config, + "2026-08-10", + tmp_path, + capture_one, + protocol_path=PROTOCOL_PATH, + clock=FakeClock(session.end_ns + 1), + _test_source_identity=SOURCE, + ) + ) + + assert not called + assert bundle.status == "INSUFFICIENT_DATA" + assert bundle.reason_codes == ("MISSED_WINDOW",) + assert bundle.marker_path.read_bytes() == b"terminal\n" + + +@pytest.mark.parametrize("error", [PermissionError("disk denied"), RuntimeError("bug")]) +def test_system_fault_is_nonterminal_and_preserves_raw_evidence( + tmp_path: Path, error: BaseException +) -> None: + config = load_m8_l2_config(CONFIG_PATH) + session = config.sessions[0] + other_finished = False + + async def capture_one(**kwargs: object) -> SymbolCaptureResult: + nonlocal other_finished + symbol = str(kwargs["symbol"]) + root = Path(str(kwargs["stage_root"])) + _artifact(root, "received-before-system-fault.ndjson") + if symbol == "BTCUSDT": + await asyncio.sleep(0) + raise error + await asyncio.sleep(0.01) + other_finished = True + return _complete_result( + symbol=symbol, + root=root, + start_ns=session.start_ns, + end_ns=session.end_ns, + ) + + with pytest.raises(M8L2CaptureSystemError) as raised: + asyncio.run( + capture_m8_l2_session( + config, + "2026-08-10", + tmp_path, + capture_one, + protocol_path=PROTOCOL_PATH, + clock=FakeClock(session.start_ns, finish_ns=session.end_ns), + _test_source_identity=SOURCE, + ) + ) + + assert other_finished + evidence_root = raised.value.evidence_root + assert evidence_root is not None and evidence_root.is_dir() + assert (evidence_root / "SYSTEM_FAILURE.json").is_file() + assert list(evidence_root.rglob("received-before-system-fault.ndjson")) + assert not list(evidence_root.rglob("_SUCCESS")) + assert not list(evidence_root.rglob("INSUFFICIENT_DATA")) + record = read_json(evidence_root / "SYSTEM_FAILURE.json") + assert record["terminal"] is False + assert record["research_result"] is False + assert not list((tmp_path / "sessions").glob("*")) + + +def test_system_failure_never_follows_preexisting_incomplete_symlink( + tmp_path: Path, +) -> None: + config = load_m8_l2_config(CONFIG_PATH) + session = config.sessions[0] + output_root = tmp_path / "evidence" + outside = tmp_path / "outside" + output_root.mkdir() + outside.mkdir() + (output_root / "incomplete").symlink_to(outside, target_is_directory=True) + + async def capture_one(**kwargs: object) -> SymbolCaptureResult: + root = Path(str(kwargs["stage_root"])) + _artifact(root, "received-before-system-fault.ndjson") + raise PermissionError("local storage denied") + + with pytest.raises(M8L2CaptureSystemError) as raised: + asyncio.run( + capture_m8_l2_session( + config, + session.date.isoformat(), + output_root, + capture_one, + protocol_path=PROTOCOL_PATH, + clock=FakeClock(session.start_ns, finish_ns=session.end_ns), + _test_source_identity=SOURCE, + ) + ) + + assert not list(outside.iterdir()) + evidence_root = raised.value.evidence_root + assert evidence_root is not None + assert evidence_root.parent == output_root + assert (evidence_root / "SYSTEM_FAILURE.json").is_file() + assert not list(output_root.rglob("_SUCCESS")) + assert not list(output_root.rglob("INSUFFICIENT_DATA")) + + +def test_active_cancellation_terminalizes_as_insufficient_and_preserves_partial_raw( + tmp_path: Path, +) -> None: + config = load_m8_l2_config(CONFIG_PATH) + session = config.sessions[0] + entered: set[str] = set() + both_entered = asyncio.Event() + + async def capture_one(**kwargs: object) -> SymbolCaptureResult: + symbol = str(kwargs["symbol"]) + root = Path(str(kwargs["stage_root"])) + _artifact(root, "partial.ndjson") + entered.add(symbol) + if len(entered) == 2: + both_entered.set() + await asyncio.Future() + raise AssertionError("unreachable") + + async def scenario() -> object: + task = asyncio.create_task( + capture_m8_l2_session( + config, + "2026-08-10", + tmp_path, + capture_one, + protocol_path=PROTOCOL_PATH, + clock=FakeClock(session.start_ns, finish_ns=session.end_ns), + _test_source_identity=SOURCE, + ) + ) + await asyncio.wait_for(both_entered.wait(), timeout=1) + task.cancel() + return await task + + bundle = asyncio.run(scenario()) + + assert bundle.status == "INSUFFICIENT_DATA" + assert "CAPTURE_CANCELED" in bundle.reason_codes + assert len(list(bundle.root.rglob("partial.ndjson"))) == 2 + + +def test_verifier_rejects_tamper_extra_files_and_bad_marker_and_reuse_is_verify_only( + tmp_path: Path, +) -> None: + config = load_m8_l2_config(CONFIG_PATH) + session = config.sessions[0] + calls = 0 + + async def capture_one(**kwargs: object) -> SymbolCaptureResult: + nonlocal calls + calls += 1 + return _complete_result( + symbol=str(kwargs["symbol"]), + root=Path(str(kwargs["stage_root"])), + start_ns=session.start_ns, + end_ns=session.end_ns, + ) + + first = asyncio.run( + capture_m8_l2_session( + config, + "2026-08-10", + tmp_path, + capture_one, + protocol_path=PROTOCOL_PATH, + clock=FakeClock(session.start_ns, finish_ns=session.end_ns), + _test_source_identity=SOURCE, + ) + ) + reused = asyncio.run( + capture_m8_l2_session( + config, + "2026-08-10", + tmp_path, + capture_one, + protocol_path=PROTOCOL_PATH, + clock=FakeClock(session.end_ns + 1), + _test_source_identity=SOURCE, + ) + ) + assert reused == first + assert calls == 2 + + extra = first.root / "unmanifested.txt" + extra.write_text("tamper", encoding="utf-8") + with pytest.raises(M8L2VerificationError, match="physical inventory"): + verify_m8_l2_session_bundle(first.root) + extra.unlink() + + first.marker_path.write_bytes(b"COMPLETE\n") + with pytest.raises(M8L2VerificationError, match="marker bytes"): + verify_m8_l2_session_bundle(first.root) + + +def test_capture_result_with_undeclared_file_is_program_fault_not_data_failure( + tmp_path: Path, +) -> None: + config = load_m8_l2_config(CONFIG_PATH) + session = config.sessions[0] + + async def capture_one(**kwargs: object) -> SymbolCaptureResult: + root = Path(str(kwargs["stage_root"])) + result = _complete_result( + symbol=str(kwargs["symbol"]), + root=root, + start_ns=session.start_ns, + end_ns=session.end_ns, + ) + (root / "undeclared.bin").write_bytes(b"raw") + return result + + with pytest.raises(M8L2CaptureSystemError) as raised: + asyncio.run( + capture_m8_l2_session( + config, + "2026-08-10", + tmp_path, + capture_one, + protocol_path=PROTOCOL_PATH, + clock=FakeClock(session.start_ns, finish_ns=session.end_ns), + _test_source_identity=SOURCE, + ) + ) + assert raised.value.evidence_root is not None + assert list(raised.value.evidence_root.rglob("undeclared.bin")) + + +def test_terminal_publication_io_fault_is_demoted_and_raw_is_preserved( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + config = load_m8_l2_config(CONFIG_PATH) + session = config.sessions[0] + + async def capture_one(**kwargs: object) -> SymbolCaptureResult: + return _complete_result( + symbol=str(kwargs["symbol"]), + root=Path(str(kwargs["stage_root"])), + start_ns=session.start_ns, + end_ns=session.end_ns, + ) + + real_write = l2_module._write_bytes_durable + + def fail_terminal_marker(path: Path, payload: bytes) -> None: + if path.name == "_SUCCESS": + raise PermissionError("injected terminal permission failure") + real_write(path, payload) + + monkeypatch.setattr(l2_module, "_write_bytes_durable", fail_terminal_marker) + + with pytest.raises(M8L2CaptureSystemError) as raised: + asyncio.run( + capture_m8_l2_session( + config, + "2026-08-10", + tmp_path, + capture_one, + protocol_path=PROTOCOL_PATH, + clock=FakeClock(session.start_ns, finish_ns=session.end_ns), + _test_source_identity=SOURCE, + ) + ) + + evidence_root = raised.value.evidence_root + assert evidence_root is not None + assert (evidence_root / "SYSTEM_FAILURE.json").is_file() + assert len(list(evidence_root.rglob("capture.ndjson"))) == 2 + assert not (evidence_root / "_SUCCESS").exists() + assert not (evidence_root / "INSUFFICIENT_DATA").exists() + + +def test_protocol_drift_during_capture_is_system_failure_and_preserves_raw( + tmp_path: Path, +) -> None: + project = tmp_path / "relocated-project" + config_path = project / "configs" / "m8_l2_capture_study.toml" + protocol_path = project / "docs" / "M8_L2_PROTOCOL.md" + config_path.parent.mkdir(parents=True) + protocol_path.parent.mkdir(parents=True) + config_path.write_bytes(CONFIG_PATH.read_bytes()) + protocol_path.write_bytes(PROTOCOL_PATH.read_bytes()) + config = load_m8_l2_config(config_path) + session = config.sessions[0] + both_finished = 0 + + async def capture_one(**kwargs: object) -> SymbolCaptureResult: + nonlocal both_finished + result = _complete_result( + symbol=str(kwargs["symbol"]), + root=Path(str(kwargs["stage_root"])), + start_ns=session.start_ns, + end_ns=session.end_ns, + ) + both_finished += 1 + if both_finished == 2: + protocol_path.write_bytes(b"protocol drift\n") + await asyncio.sleep(0) + return result + + with pytest.raises(M8L2CaptureSystemError, match="authority/gate") as raised: + asyncio.run( + capture_m8_l2_session( + config, + "2026-08-10", + tmp_path / "evidence", + capture_one, + protocol_path=protocol_path, + clock=FakeClock(session.start_ns, finish_ns=session.end_ns), + _test_source_identity=SOURCE, + ) + ) + + evidence_root = raised.value.evidence_root + assert evidence_root is not None + assert (evidence_root / "SYSTEM_FAILURE.json").is_file() + assert len(list(evidence_root.rglob("capture.ndjson"))) == 2 + assert not (evidence_root / "_SUCCESS").exists() + assert not (evidence_root / "INSUFFICIENT_DATA").exists() + + +@pytest.mark.parametrize("drift_after", ["checksums", "marker"]) +def test_full_authority_drift_during_terminal_materialization_is_nonterminal( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + drift_after: str, +) -> None: + project = tmp_path / "relocated-project" + config_path = project / "configs" / "m8_l2_capture_study.toml" + protocol_path = project / "docs" / "M8_L2_PROTOCOL.md" + config_path.parent.mkdir(parents=True) + protocol_path.parent.mkdir(parents=True) + config_path.write_bytes(CONFIG_PATH.read_bytes()) + protocol_path.write_bytes(PROTOCOL_PATH.read_bytes()) + config = load_m8_l2_config(config_path) + session = config.sessions[0] + output_root = tmp_path / "evidence" + drifted = False + + async def capture_one(**kwargs: object) -> SymbolCaptureResult: + return _complete_result( + symbol=str(kwargs["symbol"]), + root=Path(str(kwargs["stage_root"])), + start_ns=session.start_ns, + end_ns=session.end_ns, + ) + + def drift_protocol() -> None: + nonlocal drifted + if not drifted: + protocol_path.write_bytes(b"terminal materialization drift\n") + drifted = True + + if drift_after == "checksums": + real_write_checksums = l2_module._write_checksums + + def write_checksums_then_drift(stage: Path) -> Path: + result = real_write_checksums(stage) + drift_protocol() + return result + + monkeypatch.setattr(l2_module, "_write_checksums", write_checksums_then_drift) + else: + real_write_bytes = l2_module._write_bytes_durable + + def write_marker_then_drift(path: Path, payload: bytes) -> None: + real_write_bytes(path, payload) + if path.name in {"_SUCCESS", "INSUFFICIENT_DATA"}: + drift_protocol() + + monkeypatch.setattr(l2_module, "_write_bytes_durable", write_marker_then_drift) + + with pytest.raises(M8L2CaptureSystemError, match="terminal publication failed") as raised: + asyncio.run( + capture_m8_l2_session( + config, + session.date.isoformat(), + output_root, + capture_one, + protocol_path=protocol_path, + clock=FakeClock(session.start_ns, finish_ns=session.end_ns), + _test_source_identity=SOURCE, + ) + ) + + assert drifted + evidence_root = raised.value.evidence_root + assert evidence_root is not None + assert (evidence_root / "SYSTEM_FAILURE.json").is_file() + assert len(list(evidence_root.rglob("capture.ndjson"))) == 2 + assert not list(output_root.rglob("_SUCCESS")) + assert not list(output_root.rglob("INSUFFICIENT_DATA")) + assert not list((output_root / "sessions").iterdir()) + + +def test_success_revalidates_full_authority_before_marker_and_rename( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + events: list[str] = [] + real_revalidate = l2_module._revalidate_runtime_authority + real_verify_campaign = l2_module._verify_campaign_authority + real_write = l2_module._write_bytes_durable + real_rename = l2_module.os.rename + + def observed_revalidate(**kwargs: object) -> None: + events.append("full") + real_revalidate(**kwargs) + + def observed_verify_campaign(*args: object, **kwargs: object) -> object: + events.append("campaign") + return real_verify_campaign(*args, **kwargs) + + def observed_write(path: Path, payload: bytes) -> None: + if path.name in {"_SUCCESS", "INSUFFICIENT_DATA"}: + events.append("marker") + real_write(path, payload) + + def observed_rename(source: object, target: object, **kwargs: object) -> None: + events.append("rename") + real_rename(source, target, **kwargs) + + monkeypatch.setattr(l2_module, "_revalidate_runtime_authority", observed_revalidate) + monkeypatch.setattr(l2_module, "_verify_campaign_authority", observed_verify_campaign) + monkeypatch.setattr(l2_module, "_write_bytes_durable", observed_write) + monkeypatch.setattr(l2_module.os, "rename", observed_rename) + + bundle, _, _ = _complete_bundle(tmp_path) + marker_index = events.index("marker") + rename_index = events.index("rename") + + assert bundle.status == "COMPLETE" + assert events[marker_index - 2 : marker_index + 1] == ["full", "campaign", "marker"] + assert events[rename_index - 2 : rename_index + 1] == ["full", "campaign", "rename"] + + +def test_manifest_is_machine_readable_and_contains_exact_checksum_inventory(tmp_path: Path) -> None: + config = load_m8_l2_config(CONFIG_PATH) + session = config.sessions[0] + + async def capture_one(**kwargs: object) -> SymbolCaptureResult: + return _complete_result( + symbol=str(kwargs["symbol"]), + root=Path(str(kwargs["stage_root"])), + start_ns=session.start_ns, + end_ns=session.end_ns, + ) + + bundle = asyncio.run( + capture_m8_l2_session( + config, + "2026-08-10", + tmp_path, + capture_one, + protocol_path=PROTOCOL_PATH, + clock=FakeClock(session.start_ns, finish_ns=session.end_ns), + _test_source_identity=SOURCE, + ) + ) + + payload = json.loads(bundle.manifest_path.read_text()) + checksummed = { + line[66:] for line in bundle.checksum_path.read_text(encoding="ascii").splitlines() + } + inventoried = {item["path"] for item in payload["artifact_inventory"]} + assert inventoried == checksummed - {"session_manifest.json"} + + +def test_complete_result_returned_before_scheduled_end_is_nonterminal(tmp_path: Path) -> None: + config = load_m8_l2_config(CONFIG_PATH) + session = config.sessions[0] + + async def capture_one(**kwargs: object) -> SymbolCaptureResult: + return _complete_result( + symbol=str(kwargs["symbol"]), + root=Path(str(kwargs["stage_root"])), + start_ns=session.start_ns, + end_ns=session.end_ns, + ) + + with pytest.raises(M8L2CaptureSystemError, match="before the frozen scheduled end") as raised: + asyncio.run( + capture_m8_l2_session( + config, + session.date.isoformat(), + tmp_path, + capture_one, + protocol_path=PROTOCOL_PATH, + clock=FakeClock(session.start_ns), + _test_source_identity=SOURCE, + ) + ) + assert raised.value.evidence_root is not None + assert not list((tmp_path / "sessions").glob("*")) + + +def test_co_lied_text_normalized_artifact_is_rejected_as_system_fault(tmp_path: Path) -> None: + config = load_m8_l2_config(CONFIG_PATH) + session = config.sessions[0] + + async def capture_one(**kwargs: object) -> SymbolCaptureResult: + root = Path(str(kwargs["stage_root"])) + result = _complete_result( + symbol=str(kwargs["symbol"]), + root=root, + start_ns=session.start_ns, + end_ns=session.end_ns, + ) + target = next( + item + for item in result.artifacts + if item.kind == "normalized_data" and item.path.name == "depth_deltas.parquet" + ) + target.path.write_text("not parquet but every self-report agrees\n", encoding="utf-8") + digest = sha256_file(target.path) + summary_artifact = next(item for item in result.artifacts if item.kind == "capture_summary") + summary = read_json(summary_artifact.path) + summary["normalized_dataset_manifests"]["depth_deltas"]["data_sha256"] = digest + for entry in summary["artifact_inventory_without_summary"]: + if entry["path"] == target.path.relative_to(root).as_posix(): + entry["sha256"] = digest + entry["bytes"] = target.path.stat().st_size + write_json(summary_artifact.path, summary) + artifacts = tuple( + CapturedArtifact( + path=item.path, + kind=item.kind, + sha256=( + digest + if item.path == target.path + else sha256_file(item.path) + if item.kind == "capture_summary" + else item.sha256 + ), + ) + for item in result.artifacts + ) + return replace(result, artifacts=artifacts) + + with pytest.raises(M8L2CaptureSystemError, match="Parquet"): + asyncio.run( + capture_m8_l2_session( + config, + session.date.isoformat(), + tmp_path, + capture_one, + protocol_path=PROTOCOL_PATH, + clock=FakeClock(session.start_ns, finish_ns=session.end_ns), + _test_source_identity=SOURCE, + ) + ) + + +@pytest.mark.parametrize("case", ["summary_claim", "epoch_anchor"]) +def test_capture_summary_and_epoch_claim_mismatches_are_nonterminal( + tmp_path: Path, case: str +) -> None: + config = load_m8_l2_config(CONFIG_PATH) + session = config.sessions[0] + + async def capture_one(**kwargs: object) -> SymbolCaptureResult: + root = Path(str(kwargs["stage_root"])) + result = _complete_result( + symbol=str(kwargs["symbol"]), + root=root, + start_ns=session.start_ns, + end_ns=session.end_ns, + ) + if case == "summary_claim": + return replace(result, messages=3, normalized_rows=3, reconstructed_rows=3) + summary_artifact = next(item for item in result.artifacts if item.kind == "capture_summary") + summary = read_json(summary_artifact.path) + summary["continuity_epochs"] = 2 + summary["snapshot_anchors"] = 2 + write_json(summary_artifact.path, summary) + artifacts = tuple( + replace(item, sha256=sha256_file(item.path)) if item.kind == "capture_summary" else item + for item in result.artifacts + ) + return replace(result, continuity_epochs=2, snapshot_anchors=2, artifacts=artifacts) + + with pytest.raises(M8L2CaptureSystemError): + asyncio.run( + capture_m8_l2_session( + config, + session.date.isoformat(), + tmp_path, + capture_one, + protocol_path=PROTOCOL_PATH, + clock=FakeClock(session.start_ns, finish_ns=session.end_ns), + _test_source_identity=SOURCE, + ) + ) + + +@pytest.mark.parametrize("spoof", ["session", "gate", "source"]) +def test_verifier_recomputes_rechecksummed_session_gate_and_source_claims( + tmp_path: Path, spoof: str +) -> None: + bundle, _, _ = _complete_bundle(tmp_path) + payload = _manifest(bundle.root) + if spoof == "session": + payload["session"]["scheduled_start_ns"] += 1 + elif spoof == "gate": + payload["gates"][0]["observed"] = "attacker-controlled" + else: + payload["authority"]["runtime_source_tree_sha256"] = "3" * 64 + write_json(bundle.manifest_path, payload) + _refresh_manifest_checksum(bundle.root) + + with pytest.raises(M8L2VerificationError): + verify_m8_l2_session_bundle(bundle.root) + + +def test_output_root_and_sessions_symlinks_are_rejected_before_capture(tmp_path: Path) -> None: + config = load_m8_l2_config(CONFIG_PATH) + session = config.sessions[0] + outside = tmp_path / "outside" + outside.mkdir() + root_link = tmp_path / "root-link" + root_link.symlink_to(outside, target_is_directory=True) + + async def never(**kwargs: object) -> SymbolCaptureResult: + raise AssertionError(kwargs) + + with pytest.raises(M8L2CaptureSystemError, match="traverses a symlink"): + asyncio.run( + capture_m8_l2_session( + config, + session.date.isoformat(), + root_link, + never, + protocol_path=PROTOCOL_PATH, + clock=FakeClock(session.end_ns + 1), + _test_source_identity=SOURCE, + ) + ) + + root = tmp_path / "root" + root.mkdir() + (root / "sessions").symlink_to(outside, target_is_directory=True) + with pytest.raises(M8L2CaptureSystemError, match="sessions directory"): + asyncio.run( + capture_m8_l2_session( + config, + session.date.isoformat(), + root, + never, + protocol_path=PROTOCOL_PATH, + clock=FakeClock(session.end_ns + 1), + _test_source_identity=SOURCE, + ) + ) + + +def test_fifo_is_rejected_by_producer_and_verifier_without_opening_it(tmp_path: Path) -> None: + config = load_m8_l2_config(CONFIG_PATH) + session = config.sessions[0] + + async def capture_one(**kwargs: object) -> SymbolCaptureResult: + root = Path(str(kwargs["stage_root"])) + result = _complete_result( + symbol=str(kwargs["symbol"]), + root=root, + start_ns=session.start_ns, + end_ns=session.end_ns, + ) + os.mkfifo(root / "attacker.fifo") + return result + + with pytest.raises(M8L2CaptureSystemError, match="non-regular filesystem entry"): + asyncio.run( + capture_m8_l2_session( + config, + session.date.isoformat(), + tmp_path / "producer", + capture_one, + protocol_path=PROTOCOL_PATH, + clock=FakeClock(session.start_ns, finish_ns=session.end_ns), + _test_source_identity=SOURCE, + ) + ) + + bundle, _, _ = _complete_bundle(tmp_path / "verifier") + os.mkfifo(bundle.root / "attacker.fifo") + with pytest.raises(M8L2VerificationError, match="non-regular filesystem entry"): + verify_m8_l2_session_bundle(bundle.root) + + +def test_in_memory_config_forgery_and_production_identity_injection_are_rejected( + tmp_path: Path, +) -> None: + config = load_m8_l2_config(CONFIG_PATH) + session = config.sessions[0] + forged = replace( + config, + capture=replace( + config.capture, + max_messages_per_symbol=config.capture.max_messages_per_symbol - 1, + ), + ) + + async def never(**kwargs: object) -> SymbolCaptureResult: + raise AssertionError(kwargs) + + with pytest.raises(M8L2CaptureSystemError, match="in-memory configuration"): + asyncio.run( + capture_m8_l2_session( + forged, + session.date.isoformat(), + tmp_path / "forged", + never, + protocol_path=PROTOCOL_PATH, + clock=FakeClock(session.start_ns), + _test_source_identity=SOURCE, + ) + ) + with pytest.raises(M8L2CaptureSystemError, match="test source identity injection"): + asyncio.run( + capture_m8_l2_session( + config, + session.date.isoformat(), + tmp_path / "production", + never, + protocol_path=PROTOCOL_PATH, + _test_source_identity=SOURCE, + ) + ) + + +def test_terminal_rename_fsyncs_both_old_and_new_parent_directories( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + renamed = False + fsynced_after_rename: set[tuple[int, int]] = set() + real_rename = l2_module.os.rename + real_fsync = l2_module.os.fsync + + def observed_rename(source: object, target: object, **kwargs: object) -> None: + nonlocal renamed + real_rename(source, target, **kwargs) + renamed = True + + def observed_fsync(descriptor: int) -> None: + if renamed: + metadata = os.fstat(descriptor) + if stat.S_ISDIR(metadata.st_mode): + fsynced_after_rename.add((metadata.st_dev, metadata.st_ino)) + real_fsync(descriptor) + + monkeypatch.setattr(l2_module.os, "rename", observed_rename) + monkeypatch.setattr(l2_module.os, "fsync", observed_fsync) + bundle, _, _ = _complete_bundle(tmp_path) + + root_metadata = tmp_path.stat() + sessions_metadata = (tmp_path / "sessions").stat() + assert bundle.status == "COMPLETE" + assert (root_metadata.st_dev, root_metadata.st_ino) in fsynced_after_rename + assert (sessions_metadata.st_dev, sessions_metadata.st_ino) in fsynced_after_rename diff --git a/Microstructure/tests/test_m8_l2_config.py b/Microstructure/tests/test_m8_l2_config.py new file mode 100644 index 0000000000000000000000000000000000000000..86cfda119a78a4f28259eb31f33b91629e5a4495 --- /dev/null +++ b/Microstructure/tests/test_m8_l2_config.py @@ -0,0 +1,124 @@ +from __future__ import annotations + +import hashlib +from dataclasses import FrozenInstanceError +from pathlib import Path + +import pytest + +from microstructure.m8_l2_config import ( + M8_L2_CONFIG_SOURCE_SHA256, + M8_L2_FREEZE_COMMIT, + M8_L2_PROTOCOL_SHA256, + M8L2ConfigError, + load_m8_l2_config, +) + +PROJECT_ROOT = Path(__file__).parents[1] +CONFIG_PATH = PROJECT_ROOT / "configs" / "m8_l2_capture_study.toml" +PROTOCOL_PATH = PROJECT_ROOT / "docs" / "M8_L2_PROTOCOL.md" + + +def _mutated(tmp_path: Path, old: str, new: str) -> Path: + source = CONFIG_PATH.read_text(encoding="utf-8") + assert old in source + path = tmp_path / "mutated.toml" + path.write_text(source.replace(old, new, 1), encoding="utf-8") + return path + + +def test_frozen_live_l2_config_is_typed_and_bound_to_exact_bytes(tmp_path: Path) -> None: + config = load_m8_l2_config(CONFIG_PATH) + + assert config.source_sha256 == M8_L2_CONFIG_SOURCE_SHA256 + assert hashlib.sha256(CONFIG_PATH.read_bytes()).hexdigest() == M8_L2_CONFIG_SOURCE_SHA256 + assert hashlib.sha256(PROTOCOL_PATH.read_bytes()).hexdigest() == M8_L2_PROTOCOL_SHA256 + assert M8_L2_FREEZE_COMMIT == "6db6c8cf81b726069d1833672864e0554976b985" + assert config.study.symbols == ("BTCUSDT", "ETHUSDT") + assert config.study.stream_interval_ms == 100 + assert config.capture.duration_seconds == 3600 + assert config.capture.max_messages_per_symbol == 60_000 + assert config.sessions[0].start_ns == 1_786_370_400_000_000_000 + assert config.sessions[0].end_ns - config.sessions[0].start_ns == 3_600_000_000_000 + assert [item.role for item in config.sessions] == [ + "train", + "validation", + "primary_test", + "replication_test", + ] + assert len(config.hash) == 64 + assert config.public_dict()["source_sha256"] == M8_L2_CONFIG_SOURCE_SHA256 + + relocated = tmp_path / "same-bytes.toml" + relocated.write_bytes(CONFIG_PATH.read_bytes()) + assert load_m8_l2_config(relocated).hash == config.hash + + +def test_live_l2_config_objects_are_immutable() -> None: + config = load_m8_l2_config(CONFIG_PATH) + + with pytest.raises(FrozenInstanceError): + config.capture.duration_seconds = 1 # type: ignore[misc] + + +@pytest.mark.parametrize( + ("old", "new", "message"), + [ + ( + 'symbols = ["BTCUSDT", "ETHUSDT"]', + 'symbols = ["ETHUSDT", "BTCUSDT"]', + r"study\.symbols is frozen", + ), + ("stream_interval_ms = 100", "stream_interval_ms = 1000", "stream_interval_ms is frozen"), + ('date = "2026-08-10"', 'date = "2026-08-14"', "session calendar/order is frozen"), + ('start_utc = "14:00:00"', 'start_utc = "14:00:01"', "session calendar/order is frozen"), + ("duration_seconds = 3600", "duration_seconds = 3599", "capture contract is frozen"), + ( + "min_overlapping_coverage_seconds = 3300", + "min_overlapping_coverage_seconds = 1", + "capture contract is frozen", + ), + ("max_quality_warnings = 0", "max_quality_warnings = 1", "capture contract is frozen"), + ("depth_levels = [1, 5, 10]", "depth_levels = [1, 5]", "features contract is frozen"), + ("bootstrap_samples = 2000", "bootstrap_samples = 1999", "models contract is frozen"), + ("market_orders_only = true", "market_orders_only = false", "execution contract is frozen"), + ("allow_p_values = false", "allow_p_values = true", "claims contract is frozen"), + ], +) +def test_every_frozen_dimension_fails_closed( + tmp_path: Path, old: str, new: str, message: str +) -> None: + path = _mutated(tmp_path, old, new) + + with pytest.raises(M8L2ConfigError, match=message): + load_m8_l2_config(path) + + +def test_formatting_only_byte_drift_is_rejected(tmp_path: Path) -> None: + path = tmp_path / "commented.toml" + path.write_text("# outcome-blind but different bytes\n" + CONFIG_PATH.read_text()) + + with pytest.raises(M8L2ConfigError, match="configuration bytes do not match"): + load_m8_l2_config(path) + + +def test_unknown_key_and_bool_as_integer_fail_before_byte_authority(tmp_path: Path) -> None: + unknown = _mutated( + tmp_path, + 'name = "binance-m8-live-l2-study-v2"', + 'name = "binance-m8-live-l2-study-v2"\nunreviewed = true', + ) + with pytest.raises(M8L2ConfigError, match=r"unknown=.*unreviewed"): + load_m8_l2_config(unknown) + + invalid_type = _mutated(tmp_path, "duration_seconds = 3600", "duration_seconds = true") + with pytest.raises(M8L2ConfigError, match="duration_seconds must be an integer"): + load_m8_l2_config(invalid_type) + + +def test_only_frozen_dates_can_be_resolved() -> None: + config = load_m8_l2_config(CONFIG_PATH) + + assert config.session_for_date("2026-08-12").role == "primary_test" + with pytest.raises(M8L2ConfigError, match="not a frozen"): + config.session_for_date("2026-08-14") diff --git a/Microstructure/tests/test_m8_l2_development.py b/Microstructure/tests/test_m8_l2_development.py new file mode 100644 index 0000000000000000000000000000000000000000..db7c39d9f569e5f8362b3caeac4b453b6ba3a3af --- /dev/null +++ b/Microstructure/tests/test_m8_l2_development.py @@ -0,0 +1,1008 @@ +from __future__ import annotations + +import inspect +import json +import math +import shutil +from collections.abc import Iterator +from dataclasses import dataclass +from datetime import UTC, datetime +from pathlib import Path +from types import MappingProxyType +from typing import Any, cast + +import polars as pl +import pytest + +import microstructure.m8_l2_development as development +import microstructure.research.l2_multidate as l2_multidate_module +from microstructure.m8_l2_analysis_config import load_m8_l2_analysis_config +from microstructure.m8_l2_capture import M8L2SessionBundle +from microstructure.m8_l2_config import load_m8_l2_config +from microstructure.m8_l2_development import ( + M8L2DevelopmentError, + ProducerSourceIdentity, + lock_m8_l2_development, + verify_m8_l2_development_lock, +) +from microstructure.m8_l2_inputs import ( + L2CampaignRuntimeIdentity, + L2SessionFileAuthority, +) +from microstructure.research.l2_multidate import L2ObservedInterval + +SECOND = 1_000_000_000 +MILLISECOND = 1_000_000 +COMMIT = "a" * 40 +SOURCE_TREE = "b" * 64 +CAMPAIGN_SHA = "c" * 64 +RUNTIME_SHA = "d" * 64 + + +@dataclass(frozen=True) +class _Loaded: + book_observations: pl.DataFrame + depth_deltas: pl.DataFrame + intervals: tuple[L2ObservedInterval, ...] + + +@dataclass +class _FakeInput: + root: Path + session_id: str + session_date: str + role: str + config_sha256: str + config_source_sha256: str + file_authority: L2SessionFileAuthority + campaign_identity: L2CampaignRuntimeIdentity + symbols: MappingProxyType[str, object] + frames: dict[str, _Loaded] + events: list[str] + access_phase: str = "development" + development_lock_sha256: str | None = None + + def load_symbol_frames(self, symbol: str) -> _Loaded: + self.events.append(f"load:{self.session_date}:{symbol}") + return self.frames[symbol] + + +@dataclass +class _Environment: + capture: Any + analysis: Any + train_path: Path + validation_path: Path + train_input: _FakeInput + validation_input: _FakeInput + events: list[str] + result: Any | None = None + + +def _source() -> ProducerSourceIdentity: + return ProducerSourceIdentity(COMMIT, SOURCE_TREE, False) + + +def _frames(symbol: str, study_date: str) -> _Loaded: + start = int(datetime.fromisoformat(f"{study_date}T14:00:00+00:00").timestamp()) * SECOND + count = 280 + times = [start + index * 100 * MILLISECOND for index in range(count)] + sequence = list(range(1, count + 1)) + mids = [ + 100.0 + 0.025 * math.sin(index / 5.0) + 0.008 * math.sin(index / 17.0) for index in sequence + ] + bid_quantity = [3.0 + (index % 13) * 0.05 for index in sequence] + ask_quantity = [2.5 + (index % 11) * 0.05 for index in sequence] + continuity = f"capture:{symbol}:{study_date}" + books = pl.DataFrame( + { + "venue": ["binance_spot"] * count, + "symbol": [symbol] * count, + "event_ts_ns": times, + "available_ts_ns": times, + "continuity_id": [continuity] * count, + "sequence_end": sequence, + "is_valid": [True] * count, + "best_bid": [value - 0.01 for value in mids], + "best_ask": [value + 0.01 for value in mids], + "bid_quantity": bid_quantity, + "ask_quantity": ask_quantity, + "depth_bid_5": [value + 8.0 for value in bid_quantity], + "depth_ask_5": [value + 7.0 for value in ask_quantity], + "depth_bid_10": [value + 18.0 for value in bid_quantity], + "depth_ask_10": [value + 17.0 for value in ask_quantity], + "tick_size": [0.01] * count, + "lot_size": [0.00001] * count, + } + ) + deltas = pl.DataFrame( + { + "venue": ["binance_spot"] * count, + "symbol": [symbol] * count, + "event_ts_ns": times, + "available_ts_ns": times, + "continuity_id": [continuity] * count, + "first_update_id": sequence, + "last_update_id": sequence, + "bids": [ + [ + { + "price_ticks": 10_000 + index, + "quantity_lots": 0 if index % 13 == 0 else 10, + } + ] + for index in sequence + ], + "asks": [[{"price_ticks": 10_002 + index, "quantity_lots": 10}] for index in sequence], + } + ) + return _Loaded( + books, + deltas, + (L2ObservedInterval(continuity, start, start + 30 * SECOND),), + ) + + +def _bundle(root: Path, *, date: str, role: str, manifest_sha: str) -> M8L2SessionBundle: + return M8L2SessionBundle( + root=root, + status="COMPLETE", + session_id=hashlib_sha(date), + session_date=date, + role=role, + manifest_path=root / "session_manifest.json", + manifest_sha256=manifest_sha, + checksum_path=root / "CHECKSUMS.sha256", + marker_path=root / "_SUCCESS", + reason_codes=(), + ) + + +def _terminal_bundle( + root: Path, + *, + date: str, + role: str, + status: str, + reasons: tuple[str, ...], +) -> M8L2SessionBundle: + campaign = { + "campaign_authority_sha256": CAMPAIGN_SHA, + "runtime_commit": COMMIT, + "runtime_source_tree_sha256": SOURCE_TREE, + "runtime_fingerprint_sha256": RUNTIME_SHA, + "runtime_dirty": False, + } + manifest = root / "session_manifest.json" + manifest.write_bytes(_canonical({"authority": campaign})) + checksum = root / "CHECKSUMS.sha256" + checksum.write_text("session authority\n", encoding="ascii") + return M8L2SessionBundle( + root=root, + status=cast(Any, status), + session_id=hashlib_sha(date), + session_date=date, + role=role, + manifest_path=manifest, + manifest_sha256=hashlib_sha_bytes(manifest.read_bytes()), + checksum_path=checksum, + marker_path=root / ("_SUCCESS" if status == "COMPLETE" else "INSUFFICIENT_DATA"), + reason_codes=reasons, + ) + + +def hashlib_sha(value: str) -> str: + import hashlib + + return hashlib.sha256(value.encode()).hexdigest() + + +def _environment(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> _Environment: + capture = load_m8_l2_config("configs/m8_l2_capture_study.toml") + analysis = load_m8_l2_analysis_config("configs/m8_l2_analysis.toml") + sessions = tmp_path / "sessions" + train_path = sessions / f"2026-08-10-train-{hashlib_sha('train')[:20]}" + validation_path = sessions / f"2026-08-11-validation-{hashlib_sha('validation')[:20]}" + train_path.mkdir(parents=True) + validation_path.mkdir() + train_manifest = "1" * 64 + validation_manifest = "2" * 64 + campaign = L2CampaignRuntimeIdentity(CAMPAIGN_SHA, COMMIT, SOURCE_TREE, RUNTIME_SHA, False) + events: list[str] = [] + symbols = MappingProxyType({symbol: object() for symbol in capture.study.symbols}) + train_input = _FakeInput( + root=train_path.absolute(), + session_id=hashlib_sha("2026-08-10"), + session_date="2026-08-10", + role="train", + config_sha256=capture.hash, + config_source_sha256=capture.source_sha256, + file_authority=L2SessionFileAuthority(train_manifest, "3" * 64), + campaign_identity=campaign, + symbols=symbols, + frames={symbol: _frames(symbol, "2026-08-10") for symbol in capture.study.symbols}, + events=events, + ) + validation_input = _FakeInput( + root=validation_path.absolute(), + session_id=hashlib_sha("2026-08-11"), + session_date="2026-08-11", + role="validation", + config_sha256=capture.hash, + config_source_sha256=capture.source_sha256, + file_authority=L2SessionFileAuthority(validation_manifest, "4" * 64), + campaign_identity=campaign, + symbols=symbols, + frames={symbol: _frames(symbol, "2026-08-11") for symbol in capture.study.symbols}, + events=events, + ) + bundles = { + train_path.absolute(): _bundle( + train_path.absolute(), date="2026-08-10", role="train", manifest_sha=train_manifest + ), + validation_path.absolute(): _bundle( + validation_path.absolute(), + date="2026-08-11", + role="validation", + manifest_sha=validation_manifest, + ), + } + + def fake_capture_verify(path: str | Path, *, expected_config: Any) -> M8L2SessionBundle: + assert expected_config == capture + return bundles[Path(path).absolute()] + + def fake_input_verify( + path: str | Path, + *, + expected_config: Any, + expected_date: str, + expected_role: str, + expected_file_authority: Any = None, + expected_campaign: Any = None, + ) -> _FakeInput: + assert expected_config == capture + events.append(f"authority:{expected_date}") + value = train_input if expected_date == "2026-08-10" else validation_input + assert Path(path).absolute() == value.root + assert expected_role == value.role + if expected_file_authority is not None: + assert expected_file_authority == value.file_authority + if expected_campaign is not None: + assert expected_campaign == campaign + return value + + monkeypatch.setattr(development, "verify_m8_l2_session_bundle", fake_capture_verify) + monkeypatch.setattr(development, "_load_input_verifier", lambda: fake_input_verify) + monkeypatch.setattr(development, "_producer_source_identity", lambda _root: _source()) + monkeypatch.setattr( + development, + "current_m8_l2_runtime_fingerprint_sha256", + lambda: RUNTIME_SHA, + ) + monkeypatch.setattr(development, "_utc_now", lambda: datetime(2026, 8, 11, 16, 0, tzinfo=UTC)) + return _Environment( + capture, + analysis, + train_path, + validation_path, + train_input, + validation_input, + events, + ) + + +def test_foreign_import_origin_fails_before_bundle_or_economic_load( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + environment = _environment(tmp_path, monkeypatch) + foreign = tmp_path / "foreign" / "research" / "l2_multidate.py" + foreign.parent.mkdir(parents=True) + foreign.write_text("# foreign checkout\n", encoding="utf-8") + bundle_calls = 0 + + def forbidden_bundle(*args: object, **kwargs: object) -> M8L2SessionBundle: + nonlocal bundle_calls + bundle_calls += 1 + raise AssertionError((args, kwargs)) + + monkeypatch.setattr(l2_multidate_module, "__file__", str(foreign)) + monkeypatch.setattr(development, "verify_m8_l2_session_bundle", forbidden_bundle) + target = tmp_path / "development-lock" + with pytest.raises(M8L2DevelopmentError, match="foreign or mixed import origin"): + lock_m8_l2_development( + environment.capture, + environment.analysis, + environment.train_path, + environment.validation_path, + target, + ) + + assert bundle_calls == 0 + assert environment.events == [] + assert not target.exists() + + +def test_import_origin_drift_before_marker_is_not_terminal( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + environment = _environment(tmp_path, monkeypatch) + foreign = tmp_path / "foreign" / "research" / "l2_multidate.py" + foreign.parent.mkdir(parents=True) + foreign.write_text("# drifted checkout\n", encoding="utf-8") + original_publish_inventory = development._publish_inventory + + def publish_then_drift(root: Path) -> None: + original_publish_inventory(root) + monkeypatch.setattr(l2_multidate_module, "__file__", str(foreign)) + + monkeypatch.setattr(development, "_publish_inventory", publish_then_drift) + target = tmp_path / "development-lock" + with pytest.raises(M8L2DevelopmentError, match="foreign or mixed import origin"): + lock_m8_l2_development( + environment.capture, + environment.analysis, + environment.train_path, + environment.validation_path, + target, + ) + + assert environment.events + assert not target.exists() + + +def test_development_memory_budget_boundary_and_selection_estimate() -> None: + frame = pl.DataFrame( + { + "feature_a": [1.0, 2.0, 3.0], + "feature_b": [4.0, 5.0, 6.0], + "future_mid_up": [0, 1, 0], + } + ) + observed = development._selection_workspace_upper_bytes(frame, frame, feature_count=2) + assert observed > 2 * (frame.estimated_size("b") * 2) + development._require_memory_budget(observed, observed, "selection boundary") + with pytest.raises(M8L2DevelopmentError, match="memory budget"): + development._require_memory_budget(observed + 1, observed, "selection overflow") + assert development._causal_build_upper_bytes(60_000, 4) == ( + 60_000 * 4 * development._CAUSAL_ENDPOINT_ROW_UPPER_BYTES + ) + + +def test_development_raw_overflow_is_system_failure_without_terminal( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + environment = _environment(tmp_path, monkeypatch) + monkeypatch.setattr(development, "_MAX_DEVELOPMENT_RAW_BYTES", 1) + target = tmp_path / "development-lock" + with pytest.raises(M8L2DevelopmentError, match=r"raw materialization.*memory budget"): + lock_m8_l2_development( + environment.capture, + environment.analysis, + environment.train_path, + environment.validation_path, + target, + ) + assert not target.exists() + assert not (target / "_LOCKED").exists() + + +def test_insufficient_development_publishes_verified_not_created_without_economic_load( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + environment = _environment(tmp_path, monkeypatch) + train = _terminal_bundle( + environment.train_path, + date="2026-08-10", + role="train", + status="INSUFFICIENT_DATA", + reasons=("GATE_COVERAGE",), + ) + validation = _terminal_bundle( + environment.validation_path, + date="2026-08-11", + role="validation", + status="COMPLETE", + reasons=(), + ) + bundles = {train.root: train, validation.root: validation} + monkeypatch.setattr( + development, + "verify_m8_l2_session_bundle", + lambda path, *, expected_config: bundles[Path(path).absolute()], + ) + + def forbidden_loader() -> object: + raise AssertionError("NOT_CREATED publication opened an economic input loader") + + monkeypatch.setattr(development, "_load_input_verifier", forbidden_loader) + target = tmp_path / "development-not-created" + result = lock_m8_l2_development( + environment.capture, + environment.analysis, + train.root, + validation.root, + target, + ) + + assert result.status == "NOT_CREATED" + assert result.children == () + assert result.reason_codes == ("DEVELOPMENT_SESSION_INSUFFICIENT::train::GATE_COVERAGE",) + assert result.marker_path.read_bytes() == b"not-created\n" + assert not list(result.root.rglob("*.parquet")) + payload = json.loads(result.aggregate_path.read_text(encoding="ascii")) + assert payload["status"] == "NOT_CREATED" + assert payload["children"] == [] + assert payload["heldout_access"]["economic_rows_opened"] is False + + restored = verify_m8_l2_development_lock( + environment.capture, + environment.analysis, + train.root, + validation.root, + result.root, + expected_lock_sha256=result.aggregate_sha256, + ) + assert restored == result + assert environment.events == [] + + +def test_not_created_rejects_caller_authority_swap_before_producer_entry( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + environment = _environment(tmp_path, monkeypatch) + train = _terminal_bundle( + environment.train_path, + date="2026-08-10", + role="train", + status="INSUFFICIENT_DATA", + reasons=("GATE_COVERAGE",), + ) + validation = _terminal_bundle( + environment.validation_path, + date="2026-08-11", + role="validation", + status="COMPLETE", + reasons=(), + ) + authorities = { + train.session_date: L2SessionFileAuthority( + train.manifest_sha256, + hashlib_sha_bytes(train.checksum_path.read_bytes()), + ), + validation.session_date: L2SessionFileAuthority( + validation.manifest_sha256, + hashlib_sha_bytes(validation.checksum_path.read_bytes()), + ), + } + train.checksum_path.write_bytes(b"self-consistent replacement authority\n") + bundles = {train.root: train, validation.root: validation} + monkeypatch.setattr( + development, + "verify_m8_l2_session_bundle", + lambda path, *, expected_config: bundles[Path(path).absolute()], + ) + monkeypatch.setattr( + development, + "_load_input_verifier", + lambda: pytest.fail("NOT_CREATED swap check opened an economic loader"), + ) + target = tmp_path / "development-not-created" + + with pytest.raises(M8L2DevelopmentError, match="caller-held train session"): + lock_m8_l2_development( + environment.capture, + environment.analysis, + train.root, + validation.root, + target, + expected_session_file_authorities=authorities, + ) + + assert not target.exists() + assert environment.events == [] + + +def test_not_created_rechecks_caller_authority_at_marker_boundary( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + environment = _environment(tmp_path, monkeypatch) + train = _terminal_bundle( + environment.train_path, + date="2026-08-10", + role="train", + status="INSUFFICIENT_DATA", + reasons=("GATE_COVERAGE",), + ) + validation = _terminal_bundle( + environment.validation_path, + date="2026-08-11", + role="validation", + status="COMPLETE", + reasons=(), + ) + bundles = {train.root: train, validation.root: validation} + monkeypatch.setattr( + development, + "verify_m8_l2_session_bundle", + lambda path, *, expected_config: bundles[Path(path).absolute()], + ) + authorities = { + bundle.session_date: L2SessionFileAuthority( + bundle.manifest_sha256, + hashlib_sha_bytes(bundle.checksum_path.read_bytes()), + ) + for bundle in bundles.values() + } + original_publish_inventory = development._publish_inventory + + def publish_then_tamper(root: Path, **kwargs: object) -> None: + original_publish_inventory(root, **kwargs) + train.checksum_path.write_bytes(b"tampered before terminal marker\n") + + monkeypatch.setattr(development, "_publish_inventory", publish_then_tamper) + monkeypatch.setattr( + development, + "_load_input_verifier", + lambda: pytest.fail("NOT_CREATED marker check opened an economic loader"), + ) + target = tmp_path / "development-not-created" + + with pytest.raises(M8L2DevelopmentError, match="caller-held train session"): + lock_m8_l2_development( + environment.capture, + environment.analysis, + train.root, + validation.root, + target, + expected_session_file_authorities=authorities, + ) + + assert not target.exists() + assert environment.events == [] + + +@pytest.fixture(scope="module") +def locked_environment(tmp_path_factory: pytest.TempPathFactory) -> Iterator[_Environment]: + monkeypatch = pytest.MonkeyPatch() + environment = _environment(tmp_path_factory.mktemp("l2-development"), monkeypatch) + original_select = cast(Any, development.__dict__["select_multidate_model"]) + fit_observations: list[bool] = [] + destination = environment.train_path.parent.parent / "development-lock" + + def observed_select(*args: Any, **kwargs: Any) -> Any: + fit_observations.append((destination / "_LOCKED").exists()) + return original_select(*args, **kwargs) + + monkeypatch.setattr(development, "select_multidate_model", observed_select) + environment.result = lock_m8_l2_development( + environment.capture, + environment.analysis, + environment.train_path, + environment.validation_path, + destination, + ) + assert fit_observations == [False] * 8 + try: + yield environment + finally: + monkeypatch.undo() + + +def _canonical(payload: dict[str, Any]) -> bytes: + return ( + json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=True) + "\n" + ).encode("ascii") + + +def _rebuild_publication(root: Path) -> None: + import hashlib + + aggregate_raw = (root / "development_lock.json").read_bytes() + aggregate_sha = hashlib.sha256(aggregate_raw).hexdigest() + (root / "development_lock.sha256").write_text( + f"{aggregate_sha} development_lock.json\n", encoding="ascii" + ) + payload_files = sorted( + path + for path in root.rglob("*") + if path.is_file() and path.name not in {"_LOCKED", "CHECKSUMS.sha256", "inventory.json"} + ) + entries = [ + { + "path": path.relative_to(root).as_posix(), + "sha256": hashlib.sha256(path.read_bytes()).hexdigest(), + "bytes": path.stat().st_size, + } + for path in payload_files + ] + inventory = { + "schema_version": "m8-l2-development-inventory-v1", + "artifact_kind": "m8_l2_development_lock_inventory", + "files": entries, + } + (root / "inventory.json").write_bytes(_canonical(inventory)) + checksum_files = sorted( + path + for path in root.rglob("*") + if path.is_file() and path.name not in {"_LOCKED", "CHECKSUMS.sha256"} + ) + (root / "CHECKSUMS.sha256").write_text( + "".join( + f"{hashlib.sha256(path.read_bytes()).hexdigest()} " + f"{path.relative_to(root).as_posix()}\n" + for path in checksum_files + ), + encoding="ascii", + ) + + +def test_development_lock_is_complete_outcome_blind_and_roundtrips( + locked_environment: _Environment, +) -> None: + result = locked_environment.result + assert result is not None + assert result.marker_path.read_bytes() == b"locked\n" + assert len(result.children) == 8 + assert locked_environment.events[:2] == ["authority:2026-08-10", "authority:2026-08-11"] + assert all(event.startswith("authority:") for event in locked_environment.events[:2]) + aggregate = json.loads(result.aggregate_path.read_text(encoding="ascii")) + assert aggregate["heldout_access"] == { + "paths_received": False, + "file_hashes_received": False, + "row_counts_received": False, + "economic_rows_opened": False, + "model_fit_or_update_after_lock": False, + } + assert aggregate["heldout_declarations"] == [ + {"date": "2026-08-12", "role": "primary_test"}, + {"date": "2026-08-13", "role": "replication_test"}, + ] + restored = verify_m8_l2_development_lock( + locked_environment.capture, + locked_environment.analysis, + locked_environment.train_path, + locked_environment.validation_path, + result.root, + expected_lock_sha256=result.aggregate_sha256, + ) + assert restored.aggregate_sha256 == result.aggregate_sha256 + assert [(item.symbol, item.endpoint) for item in restored.children] == [ + (symbol, endpoint.name) + for symbol in locked_environment.capture.study.symbols + for endpoint in locked_environment.analysis.endpoints + ] + + +def test_execution_reference_is_train_only_and_matches_frozen_formula( + locked_environment: _Environment, +) -> None: + result = locked_environment.result + assert result is not None + aggregate = json.loads(result.aggregate_path.read_text(encoding="ascii")) + for claim in aggregate["execution_references"]: + payload = json.loads((result.root / claim["path"]).read_text(encoding="ascii")) + assert payload["fit_date"] == "2026-08-10" + assert payload["reference_price_statistic"] == "train_median_mid_price" + assert payload["reference_depth_statistic"] == "train_q05_min_bid_ask_l1_depth" + unrounded = min( + 100.0 / payload["reference_mid_price"], + 0.10 * payload["reference_l1_depth_q05"], + ) + assert payload["unrounded_reference_quantity"] == pytest.approx(unrounded) + assert payload["reference_quantity_lots"] == math.floor( + unrounded / payload["lot_size"] + 1e-12 + ) + assert payload["reference_quantity"] == pytest.approx( + payload["reference_quantity_lots"] * payload["lot_size"] + ) + + +def test_public_api_has_no_heldout_or_test_path_and_refuses_overwrite( + locked_environment: _Environment, +) -> None: + parameters = inspect.signature(lock_m8_l2_development).parameters + assert "test_bundle_path" not in parameters + assert "primary_bundle_path" not in parameters + assert "replication_bundle_path" not in parameters + result = locked_environment.result + assert result is not None + loads_before = sum(event.startswith("load:") for event in locked_environment.events) + with pytest.raises(M8L2DevelopmentError, match="overwrite is forbidden"): + lock_m8_l2_development( + locked_environment.capture, + locked_environment.analysis, + locked_environment.train_path, + locked_environment.validation_path, + result.root, + ) + assert sum(event.startswith("load:") for event in locked_environment.events) == loads_before + + +def test_rechecksummed_semantic_tamper_is_rejected( + locked_environment: _Environment, tmp_path: Path +) -> None: + result = locked_environment.result + assert result is not None + target = tmp_path / "tampered" + shutil.copytree(result.root, target) + aggregate_path = target / "development_lock.json" + aggregate = json.loads(aggregate_path.read_text(encoding="ascii")) + claim = aggregate["children"][0] + child_path = target / claim["path"] + child = json.loads(child_path.read_text(encoding="ascii")) + child["selected_model"] = "tree_depth_999" + child_path.write_bytes(_canonical(child)) + claim["sha256"] = hashlib_sha_bytes(child_path.read_bytes()) + aggregate_path.write_bytes(_canonical(aggregate)) + _rebuild_publication(target) + with pytest.raises(M8L2DevelopmentError, match=r"contract changed|authorities disagree"): + verify_m8_l2_development_lock( + locked_environment.capture, + locked_environment.analysis, + locked_environment.train_path, + locked_environment.validation_path, + target, + ) + + +def hashlib_sha_bytes(raw: bytes) -> str: + import hashlib + + return hashlib.sha256(raw).hexdigest() + + +def test_missing_terminal_marker_is_rejected( + locked_environment: _Environment, tmp_path: Path +) -> None: + result = locked_environment.result + assert result is not None + target = tmp_path / "no-marker" + shutil.copytree(result.root, target) + (target / "_LOCKED").unlink() + with pytest.raises(M8L2DevelopmentError, match="terminal marker"): + verify_m8_l2_development_lock( + locked_environment.capture, + locked_environment.analysis, + locked_environment.train_path, + locked_environment.validation_path, + target, + ) + + +def test_late_lock_and_dirty_source_fail_before_economic_rows_open( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + environment = _environment(tmp_path / "late", monkeypatch) + monkeypatch.setattr(development, "_utc_now", lambda: datetime(2026, 8, 12, 14, 0, tzinfo=UTC)) + target = tmp_path / "late-lock" + with pytest.raises(M8L2DevelopmentError, match="deadline"): + lock_m8_l2_development( + environment.capture, + environment.analysis, + environment.train_path, + environment.validation_path, + target, + ) + assert not any(event.startswith("load:") for event in environment.events) + assert not target.exists() + + environment.events.clear() + monkeypatch.setattr( + development, + "_producer_source_identity", + lambda _root: ProducerSourceIdentity(COMMIT, SOURCE_TREE, True), + ) + monkeypatch.setattr(development, "_utc_now", lambda: datetime(2026, 8, 11, 16, 0, tzinfo=UTC)) + with pytest.raises(M8L2DevelopmentError, match="clean Git"): + lock_m8_l2_development( + environment.capture, + environment.analysis, + environment.train_path, + environment.validation_path, + tmp_path / "dirty-lock", + ) + assert environment.events == [] + + +def test_lock_crossing_deadline_during_fit_is_not_published( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + environment = _environment(tmp_path / "crossing-deadline", monkeypatch) + observed_times = iter( + ( + datetime(2026, 8, 11, 16, 0, tzinfo=UTC), + datetime(2026, 8, 12, 14, 0, tzinfo=UTC), + ) + ) + monkeypatch.setattr(development, "_utc_now", lambda: next(observed_times)) + target = tmp_path / "crossing-deadline-lock" + + with pytest.raises(M8L2DevelopmentError, match="deadline"): + lock_m8_l2_development( + environment.capture, + environment.analysis, + environment.train_path, + environment.validation_path, + target, + ) + + assert any(event.startswith("load:") for event in environment.events) + assert not target.exists() + + +def test_lock_crossing_deadline_during_publication_is_not_terminal( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + environment = _environment(tmp_path / "crossing-publication", monkeypatch) + observed_times = iter( + ( + datetime(2026, 8, 11, 16, 0, tzinfo=UTC), + datetime(2026, 8, 12, 13, 59, 59, tzinfo=UTC), + datetime(2026, 8, 12, 14, 0, tzinfo=UTC), + ) + ) + monkeypatch.setattr(development, "_utc_now", lambda: next(observed_times)) + target = tmp_path / "crossing-publication-lock" + + with pytest.raises(M8L2DevelopmentError, match="deadline"): + lock_m8_l2_development( + environment.capture, + environment.analysis, + environment.train_path, + environment.validation_path, + target, + ) + + assert any(event.startswith("load:") for event in environment.events) + assert not target.exists() + + +def test_lock_crossing_deadline_during_final_authority_recheck_is_not_terminal( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + environment = _environment(tmp_path / "crossing-final-authority", monkeypatch) + observed_times = iter( + ( + datetime(2026, 8, 11, 16, 0, tzinfo=UTC), + datetime(2026, 8, 12, 13, 59, 58, tzinfo=UTC), + datetime(2026, 8, 12, 13, 59, 59, tzinfo=UTC), + datetime(2026, 8, 12, 14, 0, tzinfo=UTC), + ) + ) + monkeypatch.setattr(development, "_utc_now", lambda: next(observed_times)) + target = tmp_path / "crossing-final-authority-lock" + + with pytest.raises(M8L2DevelopmentError, match="deadline"): + lock_m8_l2_development( + environment.capture, + environment.analysis, + environment.train_path, + environment.validation_path, + target, + ) + + assert any(event.startswith("load:") for event in environment.events) + assert not target.exists() + + +def test_source_drift_during_fitting_is_not_published( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + environment = _environment(tmp_path / "source-drift", monkeypatch) + identities = iter( + ( + _source(), + ProducerSourceIdentity("3" * 40, "4" * 64, False), + ) + ) + monkeypatch.setattr( + development, + "_producer_source_identity", + lambda _root: next(identities), + ) + target = tmp_path / "source-drift-lock" + + with pytest.raises(M8L2DevelopmentError, match="changed before lock publication"): + lock_m8_l2_development( + environment.capture, + environment.analysis, + environment.train_path, + environment.validation_path, + target, + ) + + assert any(event.startswith("load:") for event in environment.events) + assert not target.exists() + + +def test_runtime_drift_fails_before_rows_and_before_terminal_publication( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + early = _environment(tmp_path / "runtime-early", monkeypatch) + monkeypatch.setattr( + development, + "current_m8_l2_runtime_fingerprint_sha256", + lambda: "e" * 64, + ) + with pytest.raises(M8L2DevelopmentError, match="runtime differs"): + lock_m8_l2_development( + early.capture, + early.analysis, + early.train_path, + early.validation_path, + tmp_path / "runtime-early-lock", + ) + assert not any(event.startswith("load:") for event in early.events) + + late = _environment(tmp_path / "runtime-late", monkeypatch) + observed = iter((RUNTIME_SHA, "f" * 64)) + monkeypatch.setattr( + development, + "current_m8_l2_runtime_fingerprint_sha256", + lambda: next(observed), + ) + target = tmp_path / "runtime-late-lock" + with pytest.raises(M8L2DevelopmentError, match="runtime changed"): + lock_m8_l2_development( + late.capture, + late.analysis, + late.train_path, + late.validation_path, + target, + ) + assert any(event.startswith("load:") for event in late.events) + assert not target.exists() + + +def test_system_fault_removes_unlocked_reservation( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + environment = _environment(tmp_path / "fault", monkeypatch) + original_write_json = development._write_json + + def fail_regime(path: Path, payload: Any) -> str: + if path.name == "regime_thresholds.json": + raise OSError("injected durable-write failure") + return original_write_json(path, payload) + + monkeypatch.setattr(development, "_write_json", fail_regime) + target = tmp_path / "fault-lock" + with pytest.raises(OSError, match="injected"): + lock_m8_l2_development( + environment.capture, + environment.analysis, + environment.train_path, + environment.validation_path, + target, + ) + assert not target.exists() + assert all(not event.startswith("load:2026-08-12") for event in environment.events) + + +def test_wrong_development_coordinates_and_campaign_fail_closed( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + environment = _environment(tmp_path / "wrong", monkeypatch) + with pytest.raises(M8L2DevelopmentError, match="COMPLETE 2026-08-10 train"): + lock_m8_l2_development( + environment.capture, + environment.analysis, + environment.validation_path, + environment.train_path, + tmp_path / "reversed", + ) + assert environment.events == [] + + environment.validation_input.campaign_identity = L2CampaignRuntimeIdentity( + "e" * 64, COMMIT, SOURCE_TREE, RUNTIME_SHA, False + ) + with pytest.raises(M8L2DevelopmentError, match="campaign"): + lock_m8_l2_development( + environment.capture, + environment.analysis, + environment.train_path, + environment.validation_path, + tmp_path / "campaign-mismatch", + ) + assert not any(event.startswith("load:") for event in environment.events) diff --git a/Microstructure/tests/test_m8_l2_inputs.py b/Microstructure/tests/test_m8_l2_inputs.py new file mode 100644 index 0000000000000000000000000000000000000000..291ed51c9ed652f9aa9c348f9eec24e7a0d2a6c7 --- /dev/null +++ b/Microstructure/tests/test_m8_l2_inputs.py @@ -0,0 +1,484 @@ +from __future__ import annotations + +import os +import shutil +from dataclasses import replace +from pathlib import Path +from typing import cast + +import pyarrow as pa # type: ignore[import-untyped] +import pyarrow.parquet as pq # type: ignore[import-untyped] +import pytest + +import microstructure.m8_l2_inputs as input_module +import test_m8_l2_capture as capture_fixtures +from microstructure.data.schemas import SCHEMA_VERSION, get_schema +from microstructure.m8_l2_config import M8L2Session, M8L2StudyConfig, load_m8_l2_config +from microstructure.m8_l2_inputs import ( + L2CampaignRuntimeIdentity, + L2SessionFileAuthority, + M8L2InputError, + verify_m8_l2_development_input, + verify_m8_l2_heldout_input, +) + +PROJECT_ROOT = Path(__file__).parents[1] +CONFIG_PATH = PROJECT_ROOT / "configs" / "m8_l2_capture_study.toml" + + +def _base_record(field: pa.Field) -> object: + if field.name == "schema_version": + return SCHEMA_VERSION + if pa.types.is_string(field.type): + return "fixture" + if pa.types.is_integer(field.type): + return 1 + if pa.types.is_floating(field.type): + return 1.0 + if pa.types.is_boolean(field.type): + return True + if pa.types.is_list(field.type): + return [] + raise AssertionError(f"unsupported fixture field: {field}") + + +def _valid_parquet( + path: Path, + dataset: str, + rows: int, + *, + session: M8L2Session, + corrupt_continuity: bool = False, +) -> None: + schema = get_schema(dataset) + symbol = next(part for part in path.parts if part in {"BTCUSDT", "ETHUSDT"}) + continuity = f"{symbol}-epoch-1" + times = [session.start_ns + 10_000_000_000, session.end_ns - 10_000_000_001] + records: list[dict[str, object]] = [] + for index in range(rows): + record = {field.name: _base_record(field) for field in schema} + available = times[min(index, len(times) - 1)] + record.update( + { + "venue": "binance_spot", + "symbol": symbol, + "event_ts_ns": available, + "received_ts_ns": available, + "available_ts_ns": available, + "availability_basis": "local_receipt", + "capture_seq": index + 1, + "continuity_id": continuity, + "source_artifact_id": "a" * 64, + "tick_size": 0.01, + "lot_size": 0.001, + } + ) + if dataset == "depth_deltas": + record.update( + { + "first_update_id": index + 1, + "last_update_id": index + 1, + "previous_update_id": index if index else None, + "bids": [], + "asks": [], + } + ) + elif dataset == "book_observations": + record.update( + { + "continuity_id": "wrong-epoch" if corrupt_continuity else continuity, + "sequence_start": index + 1, + "sequence_end": index + 1, + "is_valid": True, + "best_bid_ticks": 10_000, + "best_ask_ticks": 10_001, + "bid_quantity_lots": 2_000, + "ask_quantity_lots": 2_000, + "best_bid": 100.0, + "best_ask": 100.01, + "bid_quantity": 2.0, + "ask_quantity": 2.0, + "spread": 0.01, + "mid_price": 100.005, + "microprice": 100.005, + "depth_bid_1": 2.0, + "depth_ask_1": 2.0, + "depth_bid_5": 2.0, + "depth_ask_5": 2.0, + "depth_bid_10": 2.0, + "depth_ask_10": 2.0, + "queue_imbalance_1": 0.0, + "queue_imbalance_5": 0.0, + "queue_imbalance_10": 0.0, + } + ) + elif dataset == "book_snapshots": + record.update( + { + "snapshot_id": f"{symbol}-snapshot", + "request_ts_ns": session.start_ns, + "received_ts_ns": session.start_ns + 1, + "available_ts_ns": session.start_ns + 1, + "last_update_id": 0, + "depth_limit": 100, + "bids": [], + "asks": [], + } + ) + records.append(record) + path.parent.mkdir(parents=True, exist_ok=True) + pq.write_table(pa.Table.from_pylist(records, schema=schema), path) + + +class _CaptureFactory: + def __init__( + self, + monkeypatch: pytest.MonkeyPatch, + config: M8L2StudyConfig, + *, + corrupt_continuity: bool = False, + ) -> None: + self.config = config + self.session = config.sessions[0] + + def write(path: Path, dataset: str, rows: int) -> None: + _valid_parquet( + path, + dataset, + rows, + session=self.session, + corrupt_continuity=corrupt_continuity, + ) + + monkeypatch.setattr(capture_fixtures, "_parquet", write) + + def capture(self, output_root: Path, session_index: int): + self.session = self.config.sessions[session_index] + return capture_fixtures._capture_complete_session( + output_root, + config=self.config, + session=self.session, + ) + + +@pytest.fixture +def config() -> M8L2StudyConfig: + return load_m8_l2_config(CONFIG_PATH) + + +def test_development_input_binds_authority_and_loads_only_requested_symbol( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + config: M8L2StudyConfig, +) -> None: + factory = _CaptureFactory(monkeypatch, config) + bundle = factory.capture(tmp_path, 0) + verified = verify_m8_l2_development_input( + bundle.root, + expected_config=config, + expected_date="2026-08-10", + expected_role="train", + ) + + assert verified.root == bundle.root + assert verified.access_phase == "development" + assert verified.development_lock_sha256 is None + assert verified.file_authority.manifest_sha256 == bundle.manifest_sha256 + assert verified.file_authority.to_dict() == { + "manifest_sha256": bundle.manifest_sha256, + "checksums_sha256": verified.file_authority.checksums_sha256, + } + assert verified.campaign_identity.to_dict()["runtime_dirty"] is False + assert set(verified.symbols) == {"BTCUSDT", "ETHUSDT"} + assert verified.symbols["BTCUSDT"].depth_deltas.rows == 2 + assert verified.symbols["BTCUSDT"].book_observations.rows == 2 + + opened: list[str] = [] + original = input_module._load_verified_parquet + original_lineage = input_module._verify_artifact_hash + + def recording_loader(*args: object, **kwargs: object): + artifact = kwargs["artifact"] + assert isinstance(artifact, input_module.VerifiedL2Artifact) + opened.append(artifact.relative_path) + return original(*args, **kwargs) + + def recording_lineage(*args: object, **kwargs: object) -> None: + artifact = kwargs["artifact"] + assert isinstance(artifact, input_module.VerifiedL2Artifact) + opened.append(artifact.relative_path) + original_lineage(*args, **kwargs) + + monkeypatch.setattr(input_module, "_load_verified_parquet", recording_loader) + monkeypatch.setattr(input_module, "_verify_artifact_hash", recording_lineage) + loaded = verified.load_symbol_frames("BTCUSDT") + assert loaded.book_observations.height == 2 + assert loaded.depth_deltas.height == 2 + assert loaded.intervals == verified.symbols["BTCUSDT"].valid_observed_intervals + assert len(opened) == 4 + assert all(path.startswith("symbols/BTCUSDT/") for path in opened) + assert not any("ETHUSDT" in path for path in opened) + + rebound = verify_m8_l2_development_input( + bundle.root, + expected_config=config, + expected_date="2026-08-10", + expected_role="train", + expected_file_authority=verified.file_authority, + expected_campaign=verified.campaign_identity, + ) + assert rebound.file_authority == verified.file_authority + + +def test_development_coordinates_are_hard_separated_before_bundle_open( + tmp_path: Path, + config: M8L2StudyConfig, + monkeypatch: pytest.MonkeyPatch, +) -> None: + called = False + + def forbidden(*args: object, **kwargs: object): + nonlocal called + called = True + raise AssertionError("verifier must not open a held-out coordinate through dev API") + + monkeypatch.setattr(input_module, "verify_m8_l2_session_bundle", forbidden) + with pytest.raises(M8L2InputError, match="development input"): + verify_m8_l2_development_input( + tmp_path, + expected_config=config, + expected_date="2026-08-12", + expected_role=cast(input_module.DevelopmentRole, "primary_test"), + ) + assert called is False + + +def test_heldout_input_requires_and_binds_development_lock( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + config: M8L2StudyConfig, +) -> None: + with pytest.raises(M8L2InputError, match="development lock authority"): + verify_m8_l2_heldout_input( + tmp_path, + expected_config=config, + expected_date="2026-08-12", + expected_role="primary_test", + development_lock_sha256="not-a-digest", + ) + + factory = _CaptureFactory(monkeypatch, config) + bundle = factory.capture(tmp_path, 2) + lock_sha256 = "d" * 64 + verified = verify_m8_l2_heldout_input( + bundle.root, + expected_config=config, + expected_date="2026-08-12", + expected_role="primary_test", + development_lock_sha256=lock_sha256, + ) + assert verified.access_phase == "heldout_after_lock" + assert verified.development_lock_sha256 == lock_sha256 + assert verified.load_symbol_frames("ETHUSDT").book_observations.height == 2 + + +def test_cross_session_campaign_identity_must_match( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + config: M8L2StudyConfig, +) -> None: + factory = _CaptureFactory(monkeypatch, config) + train = factory.capture(tmp_path, 0) + train_input = verify_m8_l2_development_input( + train.root, + expected_config=config, + expected_date="2026-08-10", + expected_role="train", + ) + validation = factory.capture(tmp_path, 1) + matching = verify_m8_l2_development_input( + validation.root, + expected_config=config, + expected_date="2026-08-11", + expected_role="validation", + expected_campaign=train_input.campaign_identity, + ) + assert matching.campaign_identity == train_input.campaign_identity + + wrong = replace( + train_input.campaign_identity, + runtime_source_tree_sha256="3" * 64, + ) + with pytest.raises(M8L2InputError, match="campaign/runtime identity"): + verify_m8_l2_development_input( + validation.root, + expected_config=config, + expected_date="2026-08-11", + expected_role="validation", + expected_campaign=wrong, + ) + + +def test_external_file_authority_mismatch_fails_closed( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + config: M8L2StudyConfig, +) -> None: + factory = _CaptureFactory(monkeypatch, config) + bundle = factory.capture(tmp_path, 0) + wrong = L2SessionFileAuthority("0" * 64, "1" * 64) + with pytest.raises(M8L2InputError, match="external digest authority"): + verify_m8_l2_development_input( + bundle.root, + expected_config=config, + expected_date="2026-08-10", + expected_role="train", + expected_file_authority=wrong, + ) + + +def test_insufficient_extra_file_and_symlink_roots_are_rejected( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + config: M8L2StudyConfig, +) -> None: + factory = _CaptureFactory(monkeypatch, config) + bundle = factory.capture(tmp_path, 0) + + original_verifier = input_module.verify_m8_l2_session_bundle + monkeypatch.setattr( + input_module, + "verify_m8_l2_session_bundle", + lambda *args, **kwargs: replace( + bundle, status="INSUFFICIENT_DATA", reason_codes=("NO_MESSAGES",) + ), + ) + with pytest.raises(M8L2InputError, match="gate-complete"): + verify_m8_l2_development_input( + bundle.root, + expected_config=config, + expected_date="2026-08-10", + expected_role="train", + ) + monkeypatch.setattr(input_module, "verify_m8_l2_session_bundle", original_verifier) + + extra = bundle.root / "unmanifested.txt" + extra.write_text("unexpected", encoding="utf-8") + with pytest.raises(M8L2InputError, match="capture authority failed verification"): + verify_m8_l2_development_input( + bundle.root, + expected_config=config, + expected_date="2026-08-10", + expected_role="train", + ) + extra.unlink() + + alias = tmp_path / "session-alias" + alias.symlink_to(bundle.root, target_is_directory=True) + with pytest.raises(M8L2InputError, match="capture authority failed verification"): + verify_m8_l2_development_input( + alias, + expected_config=config, + expected_date="2026-08-10", + expected_role="train", + ) + + +def test_payload_tamper_after_verification_is_detected_before_rows_return( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + config: M8L2StudyConfig, +) -> None: + factory = _CaptureFactory(monkeypatch, config) + bundle = factory.capture(tmp_path, 0) + verified = verify_m8_l2_development_input( + bundle.root, + expected_config=config, + expected_date="2026-08-10", + expected_role="train", + ) + target = bundle.root / verified.symbols["BTCUSDT"].book_observations.relative_path + target.write_bytes(target.read_bytes() + b"tamper") + with pytest.raises(M8L2InputError, match=r"Parquet|changed|claimed"): + verified.load_symbol_frames("BTCUSDT") + + +def test_loader_rejects_an_object_not_created_by_verifier( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + config: M8L2StudyConfig, +) -> None: + factory = _CaptureFactory(monkeypatch, config) + bundle = factory.capture(tmp_path, 0) + verified = verify_m8_l2_development_input( + bundle.root, + expected_config=config, + expected_date="2026-08-10", + expected_role="train", + ) + forged = replace(verified, _verification_token=object()) + with pytest.raises(M8L2InputError, match="verifier-created"): + forged.load_symbol_frames("BTCUSDT") + + +def test_descriptor_snapshot_detects_atomic_path_replacement_toctou( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + config: M8L2StudyConfig, +) -> None: + factory = _CaptureFactory(monkeypatch, config) + bundle = factory.capture(tmp_path, 0) + verified = verify_m8_l2_development_input( + bundle.root, + expected_config=config, + expected_date="2026-08-10", + expected_role="train", + ) + target = bundle.root / verified.symbols["BTCUSDT"].book_observations.relative_path + replacement = tmp_path / "replacement.parquet" + shutil.copy2(target, replacement) + original_hash = input_module._hash_descriptor + replaced = False + + target_inode = target.stat().st_ino + + def replace_after_hash(descriptor: int, maximum_bytes: int) -> tuple[str, int]: + nonlocal replaced + result = original_hash(descriptor, maximum_bytes) + if not replaced and os.fstat(descriptor).st_ino == target_inode: + os.replace(replacement, target) + replaced = True + return result + + monkeypatch.setattr(input_module, "_hash_descriptor", replace_after_hash) + with pytest.raises(M8L2InputError, match="path changed"): + verified.load_symbol_frames("BTCUSDT") + assert replaced is True + + +def test_loaded_row_continuity_must_reconcile_to_verified_intervals( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + config: M8L2StudyConfig, +) -> None: + factory = _CaptureFactory(monkeypatch, config, corrupt_continuity=True) + bundle = factory.capture(tmp_path, 0) + verified = verify_m8_l2_development_input( + bundle.root, + expected_config=config, + expected_date="2026-08-10", + expected_role="train", + ) + with pytest.raises(M8L2InputError, match=r"reconcile|OBSERVED interval"): + verified.load_symbol_frames("BTCUSDT") + + +def test_campaign_identity_constructor_rejects_dirty_runtime() -> None: + with pytest.raises(M8L2InputError, match="must be clean"): + L2CampaignRuntimeIdentity( + campaign_authority_sha256="a" * 64, + runtime_commit="b" * 40, + runtime_source_tree_sha256="c" * 64, + runtime_fingerprint_sha256="d" * 64, + runtime_dirty=True, + ) diff --git a/Microstructure/tests/test_m8_l2_pipeline.py b/Microstructure/tests/test_m8_l2_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..6c241e52f06849ccb42cc548117060f63be87713 --- /dev/null +++ b/Microstructure/tests/test_m8_l2_pipeline.py @@ -0,0 +1,992 @@ +from __future__ import annotations + +import gc +import hashlib +import json +import shutil +import weakref +from pathlib import Path +from types import MappingProxyType, SimpleNamespace +from typing import Any, cast + +import polars as pl +import pytest + +import microstructure.m8_l2_pipeline as pipeline +import microstructure.research.l2_evaluation as l2_evaluation_module +import test_m8_l2_development as development_fixture +from microstructure.m8_l2_analysis_config import load_m8_l2_analysis_config +from microstructure.m8_l2_capture import M8L2SessionBundle +from microstructure.m8_l2_config import load_m8_l2_config +from microstructure.m8_l2_development import lock_m8_l2_development +from microstructure.m8_l2_inputs import L2CampaignRuntimeIdentity +from microstructure.reporting.l2 import L2ReportData + +PROJECT_ROOT = Path(__file__).parents[1] +CAPTURE_CONFIG = PROJECT_ROOT / "configs" / "m8_l2_capture_study.toml" +ANALYSIS_CONFIG = PROJECT_ROOT / "configs" / "m8_l2_analysis.toml" + + +def _sha(value: str) -> str: + return hashlib.sha256(value.encode()).hexdigest() + + +def _authority(tmp_path: Path, name: str) -> pipeline.L2StudySessionAuthority: + return pipeline.L2StudySessionAuthority( + tmp_path / name, + _sha(f"manifest:{name}"), + _sha(f"checksums:{name}"), + ) + + +def _bundle( + authority: pipeline.L2StudySessionAuthority, + *, + date: str, + role: str, + status: str = "COMPLETE", + reasons: tuple[str, ...] = (), +) -> M8L2SessionBundle: + return M8L2SessionBundle( + root=authority.bundle_path, + status=status, # type: ignore[arg-type] + session_id=_sha(f"session:{date}"), + session_date=date, + role=role, + manifest_path=authority.bundle_path / "session_manifest.json", + manifest_sha256=authority.manifest_sha256, + checksum_path=authority.bundle_path / "CHECKSUMS.sha256", + marker_path=authority.bundle_path + / ("_SUCCESS" if status == "COMPLETE" else "INSUFFICIENT_DATA"), + reason_codes=reasons, + ) + + +def test_session_authority_requires_both_independent_digests(tmp_path: Path) -> None: + value = _authority(tmp_path, "train") + assert value.bundle_path.is_absolute() + assert value.file_authority.manifest_sha256 == value.manifest_sha256 + assert value.to_dict()["checksums_sha256"] == value.checksums_sha256 + + with pytest.raises(pipeline.M8L2StudyPipelineError, match="lowercase SHA-256"): + pipeline.L2StudySessionAuthority(tmp_path / "bad", "not-a-sha", "0" * 64) + + +def test_atomic_stage_is_hidden_and_published_without_overwrite(tmp_path: Path) -> None: + target = tmp_path / "run" + stage, parent = pipeline._reserve_stage(target) + pipeline._write_bytes(stage / "payload", b"evidence\n") + pipeline._write_bytes(stage / "_SUCCESS", b"complete\n") + assert not target.exists() + + pipeline._publish_stage_no_overwrite(stage, target, parent) + assert (target / "payload").read_bytes() == b"evidence\n" + assert (target / "_SUCCESS").read_bytes() == b"complete\n" + + with pytest.raises(pipeline.M8L2StudyPipelineError, match="already exists"): + pipeline._reserve_stage(target) + + +def test_atomic_rename_exclusively_rejects_racing_target( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + target = tmp_path / "run" + stage, parent = pipeline._reserve_stage(target) + pipeline._write_bytes(stage / "payload", b"candidate\n") + original = pipeline._atomic_rename_no_replace + + def racing_rename(source: Path, destination: Path) -> None: + destination.mkdir() + (destination / "owner").write_text("other\n", encoding="utf-8") + original(source, destination) + + monkeypatch.setattr(pipeline, "_atomic_rename_no_replace", racing_rename) + with pytest.raises(pipeline.M8L2StudyPipelineError, match="appeared"): + pipeline._publish_stage_no_overwrite(stage, target, parent) + assert (target / "owner").read_text(encoding="utf-8") == "other\n" + assert (stage / "payload").read_bytes() == b"candidate\n" + shutil.rmtree(stage) + + +def test_stage_rejects_symlinked_publication_parent(tmp_path: Path) -> None: + real = tmp_path / "real" + real.mkdir() + linked = tmp_path / "linked" + linked.symlink_to(real, target_is_directory=True) + with pytest.raises(pipeline.M8L2StudyPipelineError, match="symlink component"): + pipeline._reserve_stage(linked / "run") + + +def test_report_snapshot_round_trip_and_tamper_detection(tmp_path: Path) -> None: + manifest = { + "evidence_tier": "FULL_DATA", + "effective_evidence_tier": "INSUFFICIENT_DATA", + "status": "INSUFFICIENT_DATA", + "live_trading": False, + "research": { + "question": "Does the frozen model improve direction log loss?", + "period_start_utc": "2026-08-10T14:00:00Z", + "period_end_utc": "2026-08-13T15:00:00Z", + }, + } + provenance = { + "git": {"commit": "a" * 40, "source_tree_sha256": "b" * 64, "dirty": False}, + "inputs": { + "capture_config_sha256": "c" * 64, + "capture_protocol_sha256": "d" * 64, + "analysis_config_sha256": "e" * 64, + "development_lock_sha256": "f" * 64, + }, + } + data = L2ReportData( + manifest=manifest, + provenance=provenance, + session_gates=(), + hypothesis={ + "conclusion": "Insufficient evidence for deployment.", + "directionally_replicated_pairs": 0, + }, + predictive_metrics=(), + paired_metrics=(), + equal_session_metrics=(), + execution_metrics=(), + ) + pipeline._write_report_artifacts(tmp_path, data) + restored = pipeline._load_report_data_snapshot(tmp_path) + assert restored.manifest == manifest + assert restored.hypothesis == data.hypothesis + + sidecar = tmp_path / "report_inputs.sha256" + sidecar.write_text(f"{'0' * 64} report_inputs.json\n", encoding="ascii") + with pytest.raises(pipeline.M8L2StudyRunVerificationError, match="sidecar differs"): + pipeline._load_report_data_snapshot(tmp_path) + + +def test_pipeline_memory_boundary_and_execution_projection() -> None: + payload: dict[str, list[object]] = { + name: [1, 2, 3] for name in pipeline._EXECUTION_PREDICTION_COLUMNS + } + for name in ( + "sample_id", + "symbol", + "study_date", + "study_role", + "endpoint_name", + "split", + "child_lock_sha256", + "aggregate_lock_sha256", + ): + payload[name] = [f"{name}-{index}" for index in range(3)] + payload["selected_probability"] = [0.1, 0.5, 0.9] + payload["is_oos"] = [True, True, True] + payload["unused_wide_payload"] = ["x" * 10_000] * 3 + frame = pl.DataFrame(payload) + projected = pipeline._project_frame( + frame, + pipeline._EXECUTION_PREDICTION_COLUMNS, + "test execution predictions", + ) + assert projected.columns == list(pipeline._EXECUTION_PREDICTION_COLUMNS) + assert projected.estimated_size("b") < frame.estimated_size("b") + observed = int(projected.estimated_size("b")) + pipeline._require_memory_budget(observed, observed, "inclusive boundary") + with pytest.raises(pipeline.M8L2StudyPipelineError, match="memory budget"): + pipeline._require_memory_budget(observed + 1, observed, "overflow") + + event_payload: dict[str, list[object]] = { + name: [1, 2, 3] for name in pipeline._EXECUTION_EVENT_COLUMNS + } + events = pl.DataFrame(event_payload) + execution_upper = pipeline._execution_workspace_upper_bytes(events, projected) + signal_rows = 2 + ledger_rows = signal_rows + 1 + projected_inputs = pipeline._projected_frame_bytes( + events, pipeline._EXECUTION_EVENT_COLUMNS, "events" + ) + pipeline._projected_frame_bytes( + projected, pipeline._EXECUTION_PREDICTION_COLUMNS, "predictions" + ) + python_inputs = pipeline._python_projected_rows_upper_bytes( + events, pipeline._EXECUTION_EVENT_COLUMNS + ) + pipeline._python_projected_rows_upper_bytes( + projected, pipeline._EXECUTION_PREDICTION_COLUMNS + ) + assert execution_upper == ( + 3 * projected_inputs + + python_inputs + + (4 * ledger_rows + events.height) * pipeline._PYTHON_LEDGER_ROW_UPPER_BYTES + + 3 * ledger_rows * 9 * pipeline._POLARS_LEDGER_ROW_UPPER_BYTES + ) + + +def test_execution_ratio_verifier_requires_nullable_finite_unit_interval() -> None: + valid = pl.DataFrame( + { + "fill_ratio": [0.0, 1.0, None], + "fill_ratio_requested": [0.25, None, 0.75], + "partial_fill_order_ratio": [None, 0.5, 1.0], + } + ) + pipeline._require_nullable_unit_interval_columns( + valid, + ("fill_ratio", "fill_ratio_requested", "partial_fill_order_ratio"), + "execution metrics", + ) + with pytest.raises(pipeline.M8L2StudyRunVerificationError, match="lacks ratio columns"): + pipeline._require_nullable_unit_interval_columns( + valid.drop("fill_ratio_requested"), + ("fill_ratio", "fill_ratio_requested", "partial_fill_order_ratio"), + "execution metrics", + ) + for invalid in (float("nan"), float("inf"), -0.01, 1.01): + tampered = valid.with_columns(pl.lit(invalid).alias("fill_ratio")) + with pytest.raises( + pipeline.M8L2StudyRunVerificationError, + match=r"null or finite in \[0, 1\]", + ): + pipeline._require_nullable_unit_interval_columns( + tampered, + ("fill_ratio", "fill_ratio_requested", "partial_fill_order_ratio"), + "execution metrics", + ) + + +def test_streaming_verifier_does_not_accumulate_partition_frames( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + capture = load_m8_l2_config(CAPTURE_CONFIG) + analysis = load_m8_l2_analysis_config(ANALYSIS_CONFIG) + causal_keys = tuple( + (session.date.isoformat(), session.role, symbol, endpoint.name) + for session in capture.sessions + for symbol in capture.study.symbols + for endpoint in analysis.endpoints + ) + claims: dict[str, dict[str, object]] = { + pipeline._causal_relative(key): {} for key in causal_keys + } + for date, role in pipeline._EXPECTED_COORDINATES[2:]: + for symbol in capture.study.symbols: + for endpoint in analysis.endpoints: + for family in ("orders", "fills", "positions"): + relative = ( + f"execution/partitions/{date}-{role}/{symbol.lower()}/" + f"{endpoint.name}/{family}.parquet" + ) + claims[relative] = {} + + references: list[weakref.ReferenceType[pl.DataFrame]] = [] + maximum_live = 0 + + def fake_read(root: Path, relative: str, claim: Any) -> pl.DataFrame: + nonlocal maximum_live + del root, claim + gc.collect() + maximum_live = max(maximum_live, sum(reference() is not None for reference in references)) + if relative.startswith("causal_frames/"): + frame = pl.DataFrame( + {"feature_ready": [True], "right_censored": [False], "future_mid_up": [1]} + ) + else: + frame = pl.DataFrame({"partition": [relative]}) + references.append(weakref.ref(frame)) + return frame + + monkeypatch.setattr(pipeline, "_read_claimed_parquet", fake_read) + monkeypatch.setattr(pipeline, "_verify_one_causal_output", lambda *args, **kwargs: None) + monkeypatch.setattr(pipeline, "_verify_partition_frame", lambda *args, **kwargs: None) + monkeypatch.setattr(pipeline, "_frame_sha256", lambda frame: "1" * 64) + material = SimpleNamespace( + development_frame_sha256={ + (symbol, endpoint.name): "1" * 64 + for symbol in capture.study.symbols + for endpoint in analysis.endpoints + }, + result=SimpleNamespace(aggregate_sha256="2" * 64), + ) + retained = pipeline._verify_tabular_outputs_streaming( + tmp_path, + claims, + capture=capture, + analysis=analysis, + material=material, + status="COMPLETE", + reasons=(), + ) + assert retained == {} + assert maximum_live <= 2 + + +def test_verified_heldout_failure_never_opens_economic_frames( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + capture = load_m8_l2_config(CAPTURE_CONFIG) + analysis = load_m8_l2_analysis_config(ANALYSIS_CONFIG) + authorities = tuple(_authority(tmp_path, role) for _, role in pipeline._EXPECTED_COORDINATES) + campaign = L2CampaignRuntimeIdentity("a" * 64, "b" * 40, "c" * 64, "d" * 64, False) + snapshots = tuple( + pipeline._SessionSnapshot( + authority, + _bundle( + authority, + date=date, + role=role, + status="INSUFFICIENT_DATA" if role == "primary_test" else "COMPLETE", + reasons=("COVERAGE_GATE",) if role == "primary_test" else (), + ), + {"symbols": {}, "cross_symbol_observed_overlap_seconds": 0.0}, + campaign, + ) + for authority, (date, role) in zip(authorities, pipeline._EXPECTED_COORDINATES, strict=True) + ) + material = object() + monkeypatch.setattr( + pipeline, + "_verify_lock_context", + lambda *args, **kwargs: (object(), {}, campaign, object()), + ) + monkeypatch.setattr(pipeline, "_load_lock_material", lambda *args, **kwargs: material) + monkeypatch.setattr(pipeline, "_verify_all_sessions", lambda *args, **kwargs: snapshots) + monkeypatch.setattr( + pipeline, + "current_m8_l2_runtime_fingerprint_sha256", + lambda: "d" * 64, + ) + + def forbidden(*args: object, **kwargs: object) -> None: + raise AssertionError("held-out economic frames were opened after a gate failure") + + monkeypatch.setattr(pipeline, "_build_causal_frames", forbidden) + expected = pipeline.M8L2StudyRunResult( + root=tmp_path / "run", + status="INSUFFICIENT_DATA", + manifest_path=tmp_path / "run" / "run_manifest.json", + manifest_sha256="d" * 64, + checksum_path=tmp_path / "run" / "CHECKSUMS.sha256", + checksum_sha256="e" * 64, + marker_path=tmp_path / "run" / "INSUFFICIENT_DATA", + reason_codes=("primary_test::COVERAGE_GATE",), + ) + + def fake_publish(**kwargs: Any) -> pipeline.M8L2StudyRunResult: + assert kwargs["status"] == "INSUFFICIENT_DATA" + assert kwargs["reason_codes"] == ("primary_test::COVERAGE_GATE",) + assert kwargs["causal"] == {} + assert kwargs["heldout"] == () + return expected + + monkeypatch.setattr(pipeline, "_publish_run", fake_publish) + result = pipeline.reproduce_m8_l2_study( + capture, + analysis, + authorities[0], + authorities[1], + tmp_path / "lock", + "f" * 64, + authorities[2], + authorities[3], + tmp_path / "run", + ) + assert result == expected + + +def test_not_created_development_publishes_and_verifies_four_session_terminal_without_frames( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + environment = development_fixture._environment(tmp_path, monkeypatch) + campaign_raw = b'{"artifact_kind":"test-campaign-authority"}\n' + campaign_sha = hashlib.sha256(campaign_raw).hexdigest() + + def session_bundle( + path: Path, + *, + date: str, + role: str, + status: str, + reasons: tuple[str, ...] = (), + ) -> M8L2SessionBundle: + authority_dir = path / "authority" + authority_dir.mkdir(exist_ok=True) + (authority_dir / "campaign_authority.json").write_bytes(campaign_raw) + manifest_payload = { + "authority": { + "campaign_authority_sha256": campaign_sha, + "runtime_commit": development_fixture.COMMIT, + "runtime_source_tree_sha256": development_fixture.SOURCE_TREE, + "runtime_fingerprint_sha256": development_fixture.RUNTIME_SHA, + "runtime_dirty": False, + }, + "symbols": {}, + "cross_symbol_observed_overlap_seconds": 0.0, + } + manifest = path / "session_manifest.json" + manifest.write_text( + json.dumps(manifest_payload, sort_keys=True, separators=(",", ":")) + "\n", + encoding="ascii", + ) + checksums = path / "CHECKSUMS.sha256" + checksums.write_text("session control authority\n", encoding="ascii") + return M8L2SessionBundle( + root=path.absolute(), + status=cast(Any, status), + session_id=_sha(f"session:{date}"), + session_date=date, + role=role, + manifest_path=manifest, + manifest_sha256=hashlib.sha256(manifest.read_bytes()).hexdigest(), + checksum_path=checksums, + marker_path=path / ("_SUCCESS" if status == "COMPLETE" else "INSUFFICIENT_DATA"), + reason_codes=reasons, + ) + + train = session_bundle( + environment.train_path, + date="2026-08-10", + role="train", + status="INSUFFICIENT_DATA", + reasons=("GATE_COVERAGE",), + ) + validation = session_bundle( + environment.validation_path, + date="2026-08-11", + role="validation", + status="COMPLETE", + ) + primary_path = train.root.parent / "2026-08-12-primary" + replication_path = train.root.parent / "2026-08-13-replication" + primary_path.mkdir() + replication_path.mkdir() + primary = session_bundle( + primary_path, + date="2026-08-12", + role="primary_test", + status="COMPLETE", + ) + replication = session_bundle( + replication_path, + date="2026-08-13", + role="replication_test", + status="COMPLETE", + ) + bundles = {item.root: item for item in (train, validation, primary, replication)} + + def fake_session_verify(path: str | Path, *, expected_config: Any) -> M8L2SessionBundle: + assert expected_config == environment.capture + return bundles[Path(path).absolute()] + + monkeypatch.setattr( + development_fixture.development, + "verify_m8_l2_session_bundle", + fake_session_verify, + ) + monkeypatch.setattr(pipeline, "verify_m8_l2_session_bundle", fake_session_verify) + monkeypatch.setattr( + pipeline, + "_current_source_identity", + lambda capture: pipeline._SourceIdentity( + development_fixture.COMMIT, + development_fixture.SOURCE_TREE, + False, + ), + ) + monkeypatch.setattr( + pipeline, + "current_m8_l2_runtime_fingerprint_sha256", + lambda: development_fixture.RUNTIME_SHA, + ) + + def forbidden(*args: object, **kwargs: object) -> None: + raise AssertionError("NOT_CREATED finalization opened economic rows") + + monkeypatch.setattr(pipeline, "_development_input", forbidden) + monkeypatch.setattr(pipeline, "_heldout_input", forbidden) + monkeypatch.setattr(pipeline, "_build_causal_frames", forbidden) + development_authority = lock_m8_l2_development( + environment.capture, + environment.analysis, + train.root, + validation.root, + tmp_path / "development-authority", + ) + assert development_authority.status == "NOT_CREATED" + authorities = tuple( + pipeline.L2StudySessionAuthority( + bundle.root, + bundle.manifest_sha256, + hashlib.sha256(bundle.checksum_path.read_bytes()).hexdigest(), + ) + for bundle in (train, validation, primary, replication) + ) + run_dir = tmp_path / "final-run" + result = pipeline.reproduce_m8_l2_study( + environment.capture, + environment.analysis, + authorities[0], + authorities[1], + development_authority.root, + development_authority.aggregate_sha256, + authorities[2], + authorities[3], + run_dir, + ) + assert result.status == "INSUFFICIENT_DATA" + assert result.reason_codes == ("DEVELOPMENT_SESSION_INSUFFICIENT::train::GATE_COVERAGE",) + assert not list(run_dir.rglob("*.parquet")) + manifest = json.loads(result.manifest_path.read_text(encoding="ascii")) + assert manifest["authority"]["development_authority"] == { + "status": "NOT_CREATED", + "authority_sha256": development_authority.aggregate_sha256, + "reason_codes": list(development_authority.reason_codes), + } + assert manifest["tabular_outputs"] == [] + + verified = pipeline.verify_m8_l2_study_run( + environment.capture, + environment.analysis, + authorities[0], + authorities[1], + development_authority.root, + development_authority.aggregate_sha256, + authorities[2], + authorities[3], + run_dir, + expected_manifest_sha256=result.manifest_sha256, + expected_checksums_sha256=result.checksum_sha256, + ) + assert verified == result + + +def test_final_producer_rejects_runtime_drift_before_material_or_rows( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + capture = load_m8_l2_config(CAPTURE_CONFIG) + analysis = load_m8_l2_analysis_config(ANALYSIS_CONFIG) + authorities = tuple(_authority(tmp_path, role) for _, role in pipeline._EXPECTED_COORDINATES) + campaign = L2CampaignRuntimeIdentity("a" * 64, "b" * 40, "c" * 64, "d" * 64, False) + monkeypatch.setattr( + pipeline, + "_verify_lock_context", + lambda *args, **kwargs: (object(), {}, campaign, object()), + ) + monkeypatch.setattr( + pipeline, + "current_m8_l2_runtime_fingerprint_sha256", + lambda: "e" * 64, + ) + + def forbidden(*args: object, **kwargs: object) -> None: + raise AssertionError("runtime drift reached lock material or session rows") + + monkeypatch.setattr(pipeline, "_load_lock_material", forbidden) + monkeypatch.setattr(pipeline, "_verify_all_sessions", forbidden) + with pytest.raises(pipeline.M8L2StudyPipelineError, match="runtime differs"): + pipeline.reproduce_m8_l2_study( + capture, + analysis, + authorities[0], + authorities[1], + tmp_path / "lock", + "f" * 64, + authorities[2], + authorities[3], + tmp_path / "run", + ) + assert not (tmp_path / "run").exists() + + +def test_final_producer_rejects_foreign_origin_before_lock_or_rows( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + capture = load_m8_l2_config(CAPTURE_CONFIG) + analysis = load_m8_l2_analysis_config(ANALYSIS_CONFIG) + authorities = tuple(_authority(tmp_path, role) for _, role in pipeline._EXPECTED_COORDINATES) + foreign = tmp_path / "foreign" / "research" / "l2_evaluation.py" + foreign.parent.mkdir(parents=True) + foreign.write_text("# foreign checkout\n", encoding="utf-8") + lock_calls = 0 + + def forbidden(*args: object, **kwargs: object) -> object: + nonlocal lock_calls + lock_calls += 1 + raise AssertionError((args, kwargs)) + + monkeypatch.setattr(l2_evaluation_module, "__file__", str(foreign)) + monkeypatch.setattr(pipeline, "_verify_lock_context", forbidden) + with pytest.raises(pipeline.M8L2StudyPipelineError, match="foreign or mixed import origin"): + pipeline.reproduce_m8_l2_study( + capture, + analysis, + authorities[0], + authorities[1], + tmp_path / "lock", + "f" * 64, + authorities[2], + authorities[3], + tmp_path / "run", + ) + + assert lock_calls == 0 + assert not (tmp_path / "run").exists() + + +def test_complete_producer_verifier_reuse_and_report_round_trip( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + environment = development_fixture._environment(tmp_path, monkeypatch) + lock = lock_m8_l2_development( + environment.capture, + environment.analysis, + environment.train_path, + environment.validation_path, + tmp_path / "development-lock", + ) + environment.result = lock + campaign = environment.train_input.campaign_identity + authorities = ( + pipeline.L2StudySessionAuthority( + environment.train_path, + environment.train_input.file_authority.manifest_sha256, + environment.train_input.file_authority.checksums_sha256, + ), + pipeline.L2StudySessionAuthority( + environment.validation_path, + environment.validation_input.file_authority.manifest_sha256, + environment.validation_input.file_authority.checksums_sha256, + ), + _authority(tmp_path, "primary_test"), + _authority(tmp_path, "replication_test"), + ) + symbols = MappingProxyType({symbol: object() for symbol in environment.capture.study.symbols}) + primary_input = development_fixture._FakeInput( + root=authorities[2].bundle_path, + session_id=_sha("2026-08-12"), + session_date="2026-08-12", + role="primary_test", + config_sha256=environment.capture.hash, + config_source_sha256=environment.capture.source_sha256, + file_authority=authorities[2].file_authority, + campaign_identity=campaign, + symbols=symbols, + frames={ + symbol: development_fixture._frames(symbol, "2026-08-12") + for symbol in environment.capture.study.symbols + }, + events=environment.events, + access_phase="heldout_after_lock", + development_lock_sha256=lock.aggregate_sha256, + ) + replication_input = development_fixture._FakeInput( + root=authorities[3].bundle_path, + session_id=_sha("2026-08-13"), + session_date="2026-08-13", + role="replication_test", + config_sha256=environment.capture.hash, + config_source_sha256=environment.capture.source_sha256, + file_authority=authorities[3].file_authority, + campaign_identity=campaign, + symbols=symbols, + frames={ + symbol: development_fixture._frames(symbol, "2026-08-13") + for symbol in environment.capture.study.symbols + }, + events=environment.events, + access_phase="heldout_after_lock", + development_lock_sha256=lock.aggregate_sha256, + ) + verified_inputs = { + "train": environment.train_input, + "validation": environment.validation_input, + "primary_test": primary_input, + "replication_test": replication_input, + } + snapshots = tuple( + pipeline._SessionSnapshot( + authority, + _bundle(authority, date=date, role=role), + { + "symbols": { + symbol: {"status": "COMPLETE"} for symbol in environment.capture.study.symbols + }, + "cross_symbol_observed_overlap_seconds": 30.0, + }, + campaign, + ) + for authority, (date, role) in zip(authorities, pipeline._EXPECTED_COORDINATES, strict=True) + ) + + monkeypatch.setattr( + pipeline, + "_current_source_identity", + lambda capture: pipeline._SourceIdentity( + development_fixture.COMMIT, + development_fixture.SOURCE_TREE, + False, + ), + ) + monkeypatch.setattr( + pipeline, + "current_m8_l2_runtime_fingerprint_sha256", + lambda: development_fixture.RUNTIME_SHA, + ) + monkeypatch.setattr( + pipeline, + "_verify_all_sessions", + lambda capture, material, supplied: snapshots, + ) + monkeypatch.setattr( + pipeline, + "_development_input", + lambda snapshot, **kwargs: verified_inputs[snapshot.bundle.role], + ) + monkeypatch.setattr( + pipeline, + "_heldout_input", + lambda snapshot, **kwargs: verified_inputs[snapshot.bundle.role], + ) + + def authority_sources( + capture: Any, analysis: Any, supplied: Any, material: Any + ) -> dict[str, tuple[Path, str]]: + del supplied + protocol = PROJECT_ROOT / "docs" / "M8_L2_PROTOCOL.md" + sources = { + "authority/m8_l2_capture_study.toml": (capture.path, capture.source_sha256), + "authority/m8_l2_analysis.toml": (analysis.path, analysis.source_sha256), + "authority/M8_L2_PROTOCOL.md": ( + protocol, + pipeline.M8_L2_PROTOCOL_SHA256, + ), + } + for source in material.snapshot_files: + relative = source.relative_to(material.result.root).as_posix() + sources[f"authority/development_lock/{relative}"] = ( + source, + hashlib.sha256(source.read_bytes()).hexdigest(), + ) + return dict(sorted(sources.items())) + + monkeypatch.setattr(pipeline, "_authority_sources", authority_sources) + publication_events: list[str] = [] + producer_terminal_revalidations = 0 + original_terminal_revalidation = pipeline._terminal_revalidation + original_publish_stage = pipeline._publish_stage_no_overwrite + + def observed_terminal_revalidation(**kwargs: Any) -> None: + nonlocal producer_terminal_revalidations + if kwargs.get("require_current_runtime") is True: + producer_terminal_revalidations += 1 + publication_events.append("revalidate") + original_terminal_revalidation(**kwargs) + + def observed_publish_stage(stage: Path, target: Path, parent: pipeline._ParentIdentity) -> None: + assert publication_events[-2:] == ["revalidate", "revalidate"] + publication_events.append("publish") + original_publish_stage(stage, target, parent) + + monkeypatch.setattr(pipeline, "_terminal_revalidation", observed_terminal_revalidation) + monkeypatch.setattr(pipeline, "_publish_stage_no_overwrite", observed_publish_stage) + run_dir = tmp_path / "final-run" + result = pipeline.reproduce_m8_l2_study( + environment.capture, + environment.analysis, + authorities[0], + authorities[1], + lock.root, + lock.aggregate_sha256, + authorities[2], + authorities[3], + run_dir, + ) + assert result.status == "COMPLETE" + assert result.marker_path.read_bytes() == b"complete\n" + assert len(list((run_dir / "causal_frames").rglob("*.parquet"))) == 32 + assert len(list((run_dir / "execution" / "partitions").rglob("*.parquet"))) == 48 + manifest = json.loads(result.manifest_path.read_text(encoding="ascii")) + assert manifest["evaluation"]["model_refit_after_development_lock"] is False + assert manifest["execution"]["realized_execution"] is False + assert producer_terminal_revalidations == 2 + + memory_failure_dir = tmp_path / "memory-failure-run" + with monkeypatch.context() as bounded: + bounded.setattr(pipeline, "_MAX_FINAL_RAW_BYTES", 1) + with pytest.raises( + pipeline.M8L2StudyPipelineError, + match=r"raw materialization.*memory budget", + ): + pipeline.reproduce_m8_l2_study( + environment.capture, + environment.analysis, + authorities[0], + authorities[1], + lock.root, + lock.aggregate_sha256, + authorities[2], + authorities[3], + memory_failure_dir, + ) + assert not memory_failure_dir.exists() + assert not (memory_failure_dir / "_SUCCESS").exists() + assert not (memory_failure_dir / "INSUFFICIENT_DATA").exists() + + with pytest.raises( + pipeline.M8L2StudyPipelineError, + match="requires caller-held manifest and checksum authorities", + ): + pipeline.reproduce_m8_l2_study( + environment.capture, + environment.analysis, + authorities[0], + authorities[1], + lock.root, + lock.aggregate_sha256, + authorities[2], + authorities[3], + run_dir, + ) + reused = pipeline.reproduce_m8_l2_study( + environment.capture, + environment.analysis, + authorities[0], + authorities[1], + lock.root, + lock.aggregate_sha256, + authorities[2], + authorities[3], + run_dir, + expected_existing_manifest_sha256=result.manifest_sha256, + expected_existing_checksums_sha256=result.checksum_sha256, + ) + assert reused == result + + def forbidden_current_origin(*args: object, **kwargs: object) -> None: + raise AssertionError((args, kwargs, "offline verifier inspected current import origin")) + + current_origin = pipeline._assert_final_producer_import_origins + monkeypatch.setattr(pipeline, "_assert_final_producer_import_origins", forbidden_current_origin) + report_data = pipeline.load_m8_l2_report_data( + environment.capture, + environment.analysis, + authorities[0], + authorities[1], + lock.root, + lock.aggregate_sha256, + authorities[2], + authorities[3], + run_dir, + expected_manifest_sha256=result.manifest_sha256, + expected_checksums_sha256=result.checksum_sha256, + ) + assert report_data.manifest["status"] == "COMPLETE" + assert len(report_data.execution_metrics) == 144 + monkeypatch.setattr(pipeline, "_assert_final_producer_import_origins", current_origin) + + original_report = result.technical_report_path.read_bytes() + mutated_at_return_boundary = False + + def mutate_report_after_semantic_verification(**kwargs: Any) -> None: + nonlocal mutated_at_return_boundary + original_terminal_revalidation(**kwargs) + if kwargs.get("require_current_runtime") is not True: + result.technical_report_path.write_text("return-boundary drift\n", encoding="utf-8") + mutated_at_return_boundary = True + + with monkeypatch.context() as return_boundary: + return_boundary.setattr( + pipeline, + "_terminal_revalidation", + mutate_report_after_semantic_verification, + ) + with pytest.raises( + pipeline.M8L2StudyRunVerificationError, + match="changed after semantic verification", + ): + pipeline.verify_m8_l2_study_run( + environment.capture, + environment.analysis, + authorities[0], + authorities[1], + lock.root, + lock.aggregate_sha256, + authorities[2], + authorities[3], + run_dir, + expected_manifest_sha256=result.manifest_sha256, + expected_checksums_sha256=result.checksum_sha256, + ) + assert mutated_at_return_boundary + result.technical_report_path.write_bytes(original_report) + + result.technical_report_path.write_text("tampered\n", encoding="utf-8") + with pytest.raises(pipeline.M8L2StudyPipelineError, match="checksum mismatch"): + pipeline.verify_m8_l2_study_run( + environment.capture, + environment.analysis, + authorities[0], + authorities[1], + lock.root, + lock.aggregate_sha256, + authorities[2], + authorities[3], + run_dir, + expected_manifest_sha256=result.manifest_sha256, + expected_checksums_sha256=result.checksum_sha256, + ) + + insufficient_snapshots = ( + snapshots[0], + snapshots[1], + pipeline._SessionSnapshot( + authorities[2], + _bundle( + authorities[2], + date="2026-08-12", + role="primary_test", + status="INSUFFICIENT_DATA", + reasons=("COVERAGE_GATE",), + ), + { + "symbols": { + symbol: {"status": "FAILED"} for symbol in environment.capture.study.symbols + }, + "cross_symbol_observed_overlap_seconds": 10.0, + }, + campaign, + ), + snapshots[3], + ) + monkeypatch.setattr( + pipeline, + "_verify_all_sessions", + lambda capture, material, supplied: insufficient_snapshots, + ) + insufficient_dir = tmp_path / "insufficient-run" + insufficient = pipeline.reproduce_m8_l2_study( + environment.capture, + environment.analysis, + authorities[0], + authorities[1], + lock.root, + lock.aggregate_sha256, + authorities[2], + authorities[3], + insufficient_dir, + ) + assert insufficient.status == "INSUFFICIENT_DATA" + assert insufficient.marker_path.read_bytes() == b"terminal\n" + assert insufficient.reason_codes == ("primary_test::COVERAGE_GATE",) + assert not (insufficient_dir / "causal_frames").exists() + assert not (insufficient_dir / "evaluation").exists() + insufficient_reports = pipeline.load_m8_l2_report_data( + environment.capture, + environment.analysis, + authorities[0], + authorities[1], + lock.root, + lock.aggregate_sha256, + authorities[2], + authorities[3], + insufficient_dir, + expected_manifest_sha256=insufficient.manifest_sha256, + expected_checksums_sha256=insufficient.checksum_sha256, + ) + assert insufficient_reports.manifest["status"] == "INSUFFICIENT_DATA" + assert insufficient_reports.execution_metrics == () diff --git a/Microstructure/tests/test_m8_manifest.py b/Microstructure/tests/test_m8_manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..c99e4c0b08ec0fc37f3775b70ae9bc960f3264ea --- /dev/null +++ b/Microstructure/tests/test_m8_manifest.py @@ -0,0 +1,1186 @@ +from __future__ import annotations + +import hashlib +import json +import struct +from dataclasses import dataclass, replace +from datetime import UTC, date, datetime +from decimal import Decimal +from pathlib import Path +from typing import Any +from zipfile import ZIP_DEFLATED, ZipFile + +import pyarrow as pa # type: ignore[import-untyped] +import pyarrow.parquet as pq # type: ignore[import-untyped] +import pytest + +from microstructure.data.storage import write_partitioned_parquet, write_source_manifest +from microstructure.data.synthetic import generate_synthetic_market +from microstructure.m8_config import M8StudyConfig, load_m8_config +from microstructure.m8_manifest import ( + M8ArchiveEntry, + M8InputManifest, + M8ManifestError, + M8NormalizedPart, + M8SymbolMetadata, + read_m8_input_manifest, + verify_m8_input_manifest, + write_m8_input_manifest, +) +from microstructure.provenance import sha256_file, write_json + +PROJECT_ROOT = Path(__file__).parents[1] +CONFIG_PATH = PROJECT_ROOT / "configs" / "m8_multidate_trade_study.toml" +_NS_PER_DAY = 86_400 * 1_000_000_000 + + +@dataclass(slots=True) +class _Fixture: + config: M8StudyConfig + root: Path + symbol_metadata: tuple[M8SymbolMetadata, ...] + entries: tuple[M8ArchiveEntry, ...] + manifest: M8InputManifest + + +def _day_start_ns(day: date) -> int: + epoch = datetime(1970, 1, 1, tzinfo=UTC) + start = datetime(day.year, day.month, day.day, tzinfo=UTC) + return (start - epoch).days * _NS_PER_DAY + + +def _replace_column(table: pa.Table, name: str, values: list[str]) -> pa.Table: + index = table.schema.get_field_index(name) + field = table.schema.field(index) + return table.set_column(index, field, pa.array(values, type=field.type)) + + +def _entry_artifacts( + root: Path, + config: M8StudyConfig, + *, + symbol: str, + day: date, + role: str, + seed: int, + tick_size: Decimal, + lot_size: Decimal, +) -> M8ArchiveEntry: + day_text = day.isoformat() + start_ns = _day_start_ns(day) + end_ns = start_ns + _NS_PER_DAY + raw_dir = root / "raw" / symbol / day_text + raw_dir.mkdir(parents=True, exist_ok=True) + zip_path = raw_dir / f"{symbol}-aggTrades-{day_text}.zip" + csv_bytes = ( + "aggregate_trade_id,price,quantity,first_trade_id,last_trade_id,transact_time," + "buyer_is_maker,best_match\n" + f"1,100.00,1.0,1,1,{start_ns // 1_000_000 + 1},false,true\n" + f"2,100.01,2.0,2,2,{start_ns // 1_000_000 + 2},true,true\n" + f"3,100.02,1.5,3,3,{start_ns // 1_000_000 + 3},false,true\n" + ).encode() + with ZipFile(zip_path, "w", compression=ZIP_DEFLATED) as archive: + archive.writestr(f"{symbol}-aggTrades-{day_text}.csv", csv_bytes) + zip_sha = sha256_file(zip_path) + source_uri = ( + "https://data.binance.vision/data/spot/daily/aggTrades/" + f"{symbol}/{symbol}-aggTrades-{day_text}.zip" + ) + raw_sidecar_path, raw_sidecar_sha = write_source_manifest( + zip_path, + source=config.study.source, + source_uri=source_uri, + downloaded_at_utc="2026-08-07T12:00:00Z", + requested_start_ns=start_ns, + requested_end_ns=end_ns, + upstream_checksum_sha256=zip_sha, + ) + checksum_dir = root / "raw" / "checksums" / symbol / day_text + checksum_dir.mkdir(parents=True, exist_ok=True) + checksum_path = checksum_dir / f"{zip_path.name}.CHECKSUM" + checksum_path.write_bytes(f"{zip_sha} {zip_path.name}\n".encode("ascii")) + checksum_sha = sha256_file(checksum_path) + checksum_source_uri = f"{source_uri}.CHECKSUM" + checksum_sidecar_path, checksum_sidecar_sha = write_source_manifest( + checksum_path, + source="binance_spot_daily_aggtrades_archive_checksum", + source_uri=checksum_source_uri, + downloaded_at_utc="2026-08-07T11:59:59.123456789Z", + requested_start_ns=start_ns, + requested_end_ns=end_ns, + ) + + generated = generate_synthetic_market( + symbols=(symbol,), + events_per_symbol=3, + start_ts_ns=start_ns + 1_000_000, + seed=seed, + ) + trades = _replace_column(generated.trades, "venue", ["binance_spot"] * 3) + trades = _replace_column(trades, "source_artifact_id", [zip_sha] * 3) + normalized_root = root / "normalized" / symbol / day_text + dataset = write_partitioned_parquet( + [trades], + root=normalized_root, + dataset="trades", + schema_name="trades", + source=config.study.source, + source_uri=source_uri, + downloaded_at_utc="2026-08-07T12:00:00Z", + source_checksum_sha256=zip_sha, + requested_start_ns=start_ns, + requested_end_ns=end_ns, + ) + parts = tuple( + M8NormalizedPart( + data_path=artifact.data_path, + data_sha256=artifact.data_sha256, + data_bytes=artifact.data_path.stat().st_size, + sidecar_path=artifact.manifest_path, + sidecar_sha256=artifact.manifest_sha256, + sidecar_bytes=artifact.manifest_path.stat().st_size, + rows=artifact.rows, + write_ordinal=artifact.write_ordinal, + observed_start_ns=artifact.observed_start_ns, + observed_end_inclusive_ns=artifact.observed_end_inclusive_ns, + ) + for artifact in dataset.artifacts + ) + + quality_dir = root / "quality" / symbol / day_text + quality_dir.mkdir(parents=True, exist_ok=True) + findings_path = quality_dir / "findings.jsonl" + findings_path.write_bytes(b"") + report_path = quality_dir / "validation.json" + write_json( + report_path, + { + "generated_at_utc": "2026-08-07T12:00:00Z", + "dataset": "trades", + "rows_checked": 3, + "summary": {"errors": 0, "warnings": 0}, + "findings": [], + "mutation_policy": "observations were not changed or repaired", + "findings_jsonl_path": str(findings_path.relative_to(root)), + }, + ) + observed_start = min(part.observed_start_ns for part in parts) + observed_end = max(part.observed_end_inclusive_ns for part in parts) + return M8ArchiveEntry( + symbol=symbol, + date=day, + role=role, # type: ignore[arg-type] + complete=True, + rows=3, + first_trade_id=1, + last_trade_id=3, + observed_start_ns=observed_start, + observed_end_inclusive_ns=observed_end, + tick_size=tick_size, + lot_size=lot_size, + raw_zip_path=zip_path, + raw_zip_sha256=zip_sha, + raw_zip_bytes=zip_path.stat().st_size, + raw_uncompressed_bytes=len(csv_bytes), + raw_source_uri=source_uri, + raw_source_manifest_path=raw_sidecar_path, + raw_source_manifest_sha256=raw_sidecar_sha, + raw_source_manifest_bytes=raw_sidecar_path.stat().st_size, + raw_checksum_path=checksum_path, + raw_checksum_sha256=checksum_sha, + raw_checksum_bytes=checksum_path.stat().st_size, + raw_checksum_source_uri=checksum_source_uri, + raw_checksum_source_manifest_path=checksum_sidecar_path, + raw_checksum_source_manifest_sha256=checksum_sidecar_sha, + raw_checksum_source_manifest_bytes=checksum_sidecar_path.stat().st_size, + normalized_dataset_manifest_path=dataset.manifest_path, + normalized_dataset_manifest_sha256=dataset.manifest_sha256, + normalized_dataset_manifest_bytes=dataset.manifest_path.stat().st_size, + normalized_parts=parts, + quality_report_path=report_path, + quality_report_sha256=sha256_file(report_path), + quality_report_bytes=report_path.stat().st_size, + quality_findings_path=findings_path, + quality_findings_sha256=sha256_file(findings_path), + quality_findings_bytes=0, + quality_errors=0, + quality_warnings=0, + ) + + +def _build_symbol_metadata(root: Path, config: M8StudyConfig) -> tuple[M8SymbolMetadata, ...]: + scales = { + "BTCUSDT": (Decimal("0.01000000"), Decimal("0.00001000")), + "ETHUSDT": (Decimal("0.01000000"), Decimal("0.00010000")), + } + observed_ts_ns = _day_start_ns(date(2026, 8, 7)) + 43_200_123_456_789 + metadata: list[M8SymbolMetadata] = [] + for symbol in config.study.symbols: + tick_size, lot_size = scales[symbol] + raw_payload = { + "timezone": "UTC", + "serverTime": 1_786_104_000_123, + "symbols": [ + { + "symbol": symbol, + "status": "TRADING", + "filters": [ + { + "filterType": "PRICE_FILTER", + "minPrice": "0.00000001", + "maxPrice": "1000000.00000000", + "tickSize": format(tick_size, "f"), + }, + { + "filterType": "LOT_SIZE", + "minQty": format(lot_size, "f"), + "maxQty": "100000.00000000", + "stepSize": format(lot_size, "f"), + }, + ], + } + ], + } + raw_bytes = json.dumps( + raw_payload, + sort_keys=True, + separators=(",", ":"), + allow_nan=False, + ).encode() + raw_sha = hashlib.sha256(raw_bytes).hexdigest() + raw_dir = root / "raw" / "binance_spot" / "exchange_info" / symbol + raw_dir.mkdir(parents=True, exist_ok=True) + raw_path = raw_dir / f"{raw_sha}.json" + raw_path.write_bytes(raw_bytes) + source_uri = f"https://data-api.binance.vision/api/v3/exchangeInfo?symbol={symbol}" + source_manifest_path, source_manifest_sha = write_source_manifest( + raw_path, + source="binance_spot_public_api", + source_uri=source_uri, + downloaded_at_utc="2026-08-07T12:00:00.123456789Z", + requested_start_ns=None, + requested_end_ns=None, + response_headers={"content-type": "application/json"}, + ) + metadata.append( + M8SymbolMetadata( + symbol=symbol, + status="TRADING", + tick_size=tick_size, + lot_size=lot_size, + observed_ts_ns=observed_ts_ns, + raw_path=raw_path, + raw_sha256=raw_sha, + raw_bytes=len(raw_bytes), + source_uri=source_uri, + source_manifest_path=source_manifest_path, + source_manifest_sha256=source_manifest_sha, + source_manifest_bytes=source_manifest_path.stat().st_size, + ) + ) + return tuple(metadata) + + +def _build_entries( + root: Path, + config: M8StudyConfig, + symbol_metadata: tuple[M8SymbolMetadata, ...], +) -> tuple[M8ArchiveEntry, ...]: + metadata_by_symbol = {metadata.symbol: metadata for metadata in symbol_metadata} + entries: list[M8ArchiveEntry] = [] + seed = 100 + for period in config.periods: + for symbol in config.study.symbols: + scale = metadata_by_symbol[symbol] + entries.append( + _entry_artifacts( + root, + config, + symbol=symbol, + day=period.date, + role=period.role, + seed=seed, + tick_size=scale.tick_size, + lot_size=scale.lot_size, + ) + ) + seed += 1 + return tuple(entries) + + +@pytest.fixture +def manifest_fixture(tmp_path: Path) -> _Fixture: + config = load_m8_config(CONFIG_PATH) + root = tmp_path / "m8-input" + root.mkdir() + symbol_metadata = _build_symbol_metadata(root, config) + entries = _build_entries(root, config, symbol_metadata) + manifest = write_m8_input_manifest( + config, + root, + tuple(reversed(entries)), + tuple(reversed(symbol_metadata)), + ) + return _Fixture( + config=config, + root=root, + symbol_metadata=symbol_metadata, + entries=entries, + manifest=manifest, + ) + + +def _write_readdressed_manifest(root: Path, payload: dict[str, Any]) -> tuple[Path, str]: + encoded = ( + json.dumps(payload, indent=2, sort_keys=True, allow_nan=False, ensure_ascii=False) + "\n" + ).encode() + digest = hashlib.sha256(encoded).hexdigest() + path = root / "_manifests" / f"m8-input.manifest-{digest[:20]}.json" + path.write_bytes(encoded) + return path, digest + + +def _top_payload(fixture: _Fixture) -> dict[str, Any]: + value = json.loads(fixture.manifest.path.read_text(encoding="utf-8")) + assert isinstance(value, dict) + return value + + +def _rebind_symbol_metadata_artifacts( + fixture: _Fixture, + payload: dict[str, Any], + *, + index: int = 0, + raw_payload: dict[str, Any] | None = None, + sidecar_payload: dict[str, Any] | None = None, +) -> tuple[Path, str]: + metadata = payload["symbol_metadata"][index] + raw_path = fixture.root / metadata["raw_path"] + if raw_payload is not None: + write_json(raw_path, raw_payload) + metadata["raw_sha256"] = sha256_file(raw_path) + metadata["raw_bytes"] = raw_path.stat().st_size + + sidecar_path = fixture.root / metadata["source_manifest_path"] + if sidecar_payload is None: + loaded = json.loads(sidecar_path.read_text(encoding="utf-8")) + assert isinstance(loaded, dict) + sidecar_payload = loaded + if raw_payload is not None: + sidecar_payload["checksum"]["value"] = metadata["raw_sha256"] + sidecar_payload["bytes"] = metadata["raw_bytes"] + write_json(sidecar_path, sidecar_payload) + metadata["source_manifest_sha256"] = sha256_file(sidecar_path) + metadata["source_manifest_bytes"] = sidecar_path.stat().st_size + payload["total_symbol_metadata_bytes"] = sum( + item["raw_bytes"] for item in payload["symbol_metadata"] + ) + return _write_readdressed_manifest(fixture.root, payload) + + +def _rebind_archive_checksum_artifacts( + fixture: _Fixture, + payload: dict[str, Any], + *, + index: int = 0, + checksum_body: bytes | None = None, + sidecar_payload: dict[str, Any] | None = None, +) -> tuple[Path, str]: + checksum = payload["entries"][index]["raw"]["checksum"] + checksum_path = fixture.root / checksum["path"] + if checksum_body is not None: + checksum_path.write_bytes(checksum_body) + checksum["sha256"] = sha256_file(checksum_path) + checksum["bytes"] = checksum_path.stat().st_size + + sidecar_path = fixture.root / checksum["source_manifest_path"] + if sidecar_payload is None: + loaded = json.loads(sidecar_path.read_text(encoding="utf-8")) + assert isinstance(loaded, dict) + sidecar_payload = loaded + if checksum_body is not None: + sidecar_payload["checksum"]["value"] = checksum["sha256"] + sidecar_payload["bytes"] = checksum["bytes"] + write_json(sidecar_path, sidecar_payload) + checksum["source_manifest_sha256"] = sha256_file(sidecar_path) + checksum["source_manifest_bytes"] = sidecar_path.stat().st_size + return _write_readdressed_manifest(fixture.root, payload) + + +def _rebind_raw_zip_bytes_for_preflight( + fixture: _Fixture, + payload: dict[str, Any], + content: bytes, + *, + index: int = 0, +) -> tuple[Path, str]: + raw = payload["entries"][index]["raw"] + zip_path = fixture.root / raw["zip_path"] + zip_path.write_bytes(content) + raw["zip_sha256"] = sha256_file(zip_path) + raw["zip_bytes"] = zip_path.stat().st_size + payload["total_raw_zip_bytes"] = sum(entry["raw"]["zip_bytes"] for entry in payload["entries"]) + return _write_readdressed_manifest(fixture.root, payload) + + +def test_manifest_round_trip_is_deterministic_complete_and_ordered( + manifest_fixture: _Fixture, +) -> None: + fixture = manifest_fixture + manifest = fixture.manifest + + assert manifest.path.name == f"m8-input.manifest-{manifest.sha256[:20]}.json" + assert sha256_file(manifest.path) == manifest.sha256 + assert manifest.config_sha256 == fixture.config.hash + assert manifest.config_source_sha256 == fixture.config.source_sha256 + assert manifest.protocol_version == "1.0.2" + assert [metadata.symbol for metadata in manifest.symbol_metadata] == [ + "BTCUSDT", + "ETHUSDT", + ] + assert manifest.metadata_for("BTCUSDT").tick_size == Decimal("0.01000000") + assert len(manifest.entries) == 8 + assert [(entry.date.isoformat(), entry.symbol, entry.role) for entry in manifest.entries] == [ + (period.date.isoformat(), symbol, period.role) + for period in fixture.config.periods + for symbol in fixture.config.study.symbols + ] + first = manifest.entries[0] + assert first.raw_checksum_source_uri == f"{first.raw_source_uri}.CHECKSUM" + assert first.raw_checksum_path.read_bytes() == ( + f"{first.raw_zip_sha256} {first.raw_zip_path.name}\n".encode("ascii") + ) + assert manifest.part_paths_for(first.symbol, first.date) == tuple( + part.data_path for part in first.normalized_parts + ) + assert next(iter(manifest.ordered_part_paths)) == ("BTCUSDT", "2024-01-03") + + repeated = write_m8_input_manifest( + fixture.config, + fixture.root, + fixture.entries, + fixture.symbol_metadata, + ) + assert repeated.path == manifest.path + assert repeated.sha256 == manifest.sha256 + assert len(list((fixture.root / "_manifests").glob("m8-input.manifest-*.json"))) == 1 + + +def test_reader_verifies_only_parquet_footer_not_trade_rows( + manifest_fixture: _Fixture, monkeypatch: pytest.MonkeyPatch +) -> None: + def fail_if_rows_are_read(*_args: object, **_kwargs: object) -> None: + raise AssertionError("manifest verification must not read Parquet rows") + + monkeypatch.setattr(pq, "read_table", fail_if_rows_are_read) + + verified = verify_m8_input_manifest( + manifest_fixture.config, + manifest_fixture.root, + manifest_fixture.manifest.path, + manifest_sha256=manifest_fixture.manifest.sha256, + ) + + assert len(verified.entries) == 8 + + +@pytest.mark.parametrize( + "case", + [ + "multiple_members", + "zip64_eocd", + "zip64_entry", + "oversized_directory", + "malformed_directory_bounds", + ], +) +def test_reader_rejects_unsafe_zip_directory_before_zipfile_parser( + manifest_fixture: _Fixture, + monkeypatch: pytest.MonkeyPatch, + case: str, +) -> None: + payload = _top_payload(manifest_fixture) + entry = manifest_fixture.manifest.entries[0] + content = bytearray(entry.raw_zip_path.read_bytes()) + eocd = content.rfind(b"PK\x05\x06") + assert eocd >= 0 + central_offset = struct.unpack_from(" None: + nonlocal parser_called + parser_called = True + raise AssertionError("unsafe ZIP metadata reached ZipFile") + + import microstructure.m8_manifest as manifest_module + + monkeypatch.setattr(manifest_module, "ZipFile", unexpected_zipfile_parser) + with pytest.raises(M8ManifestError, match=r"ZIP64|central|directory"): + read_m8_input_manifest( + manifest_fixture.config, + manifest_fixture.root, + path, + manifest_sha256=manifest_sha, + ) + assert parser_called is False + + +@pytest.mark.parametrize("case", ["missing", "duplicate", "extra", "misrole"]) +def test_writer_rejects_missing_duplicate_extra_and_misrole(tmp_path: Path, case: str) -> None: + config = load_m8_config(CONFIG_PATH) + root = tmp_path / "m8-input" + root.mkdir() + symbol_metadata = _build_symbol_metadata(root, config) + entries = list(_build_entries(root, config, symbol_metadata)) + if case == "missing": + entries.pop() + message = "missing M8 archive entries" + elif case == "duplicate": + entries[1] = entries[0] + message = "duplicate M8 archive entry" + elif case == "extra": + entries.append(replace(entries[0], date=date(2024, 1, 7))) + message = "extra M8 archive entry" + else: + entries[0] = replace(entries[0], role="validation") + message = "role mismatch" + + with pytest.raises(M8ManifestError, match=message): + write_m8_input_manifest(config, root, entries, symbol_metadata) + + +@pytest.mark.parametrize( + ("case", "message"), + [ + ("incomplete", "not a complete full-day archive"), + ("zero_rows", "rows must be at least 1"), + ("id_gap", "IDs are not a contiguous row count"), + ("zero_tick", "tick_size must be finite and positive"), + ("negative_lot", "lot_size must be finite and positive"), + ], +) +def test_writer_rejects_invalid_complete_id_and_scale_claims( + tmp_path: Path, case: str, message: str +) -> None: + config = load_m8_config(CONFIG_PATH) + root = tmp_path / "m8-input" + root.mkdir() + symbol_metadata = _build_symbol_metadata(root, config) + entries = list(_build_entries(root, config, symbol_metadata)) + if case == "incomplete": + entries[0] = replace(entries[0], complete=False) + elif case == "zero_rows": + entries[0] = replace(entries[0], rows=0) + elif case == "id_gap": + entries[0] = replace(entries[0], last_trade_id=4) + elif case == "zero_tick": + entries[0] = replace(entries[0], tick_size=Decimal("0")) + else: + entries[0] = replace(entries[0], lot_size=Decimal("-0.1")) + + with pytest.raises(M8ManifestError, match=message): + write_m8_input_manifest(config, root, entries, symbol_metadata) + + +def test_writer_rejects_event_bounds_outside_declared_day(tmp_path: Path) -> None: + config = load_m8_config(CONFIG_PATH) + root = tmp_path / "m8-input" + root.mkdir() + symbol_metadata = _build_symbol_metadata(root, config) + entries = list(_build_entries(root, config, symbol_metadata)) + entries[0] = replace(entries[0], observed_start_ns=_day_start_ns(entries[0].date) - 1) + + with pytest.raises(M8ManifestError, match="outside its declared UTC day"): + write_m8_input_manifest(config, root, entries, symbol_metadata) + + +@pytest.mark.parametrize("case", ["missing", "duplicate", "extra"]) +def test_writer_rejects_incomplete_or_ambiguous_symbol_metadata(tmp_path: Path, case: str) -> None: + config = load_m8_config(CONFIG_PATH) + root = tmp_path / "m8-input" + root.mkdir() + symbol_metadata = list(_build_symbol_metadata(root, config)) + entries = _build_entries(root, config, tuple(symbol_metadata)) + if case == "missing": + symbol_metadata.pop() + message = "missing M8 symbol metadata" + elif case == "duplicate": + symbol_metadata[1] = symbol_metadata[0] + message = "duplicate M8 symbol metadata" + else: + symbol_metadata.append(replace(symbol_metadata[0], symbol="SOLUSDT")) + message = "extra M8 symbol metadata" + + with pytest.raises(M8ManifestError, match=message): + write_m8_input_manifest(config, root, entries, symbol_metadata) + + +def test_writer_binds_every_entry_scale_to_exchange_info(tmp_path: Path) -> None: + config = load_m8_config(CONFIG_PATH) + root = tmp_path / "m8-input" + root.mkdir() + symbol_metadata = _build_symbol_metadata(root, config) + entries = list(_build_entries(root, config, symbol_metadata)) + entries[0] = replace(entries[0], tick_size=Decimal("0.02")) + + with pytest.raises(M8ManifestError, match="scales do not match verified exchangeInfo"): + write_m8_input_manifest(config, root, entries, symbol_metadata) + + +@pytest.mark.parametrize( + "source_uri", + [ + "http://data-api.binance.vision/api/v3/exchangeInfo?symbol=BTCUSDT", + "https://evil.example/api/v3/exchangeInfo?symbol=BTCUSDT", + ("https://data-api.binance.vision/api/v3/exchangeInfo?symbol=BTCUSDT&symbol=BTCUSDT"), + ("https://data-api.binance.vision/api/v3/exchangeInfo?symbol=BTCUSDT&limit=1"), + "https://\ndata-api.binance.vision/api/v3/exchangeInfo?symbol=BTCUSDT", + "https://data-api.binance.vision:/api/v3/exchangeInfo?symbol=BTCUSDT", + "https://[data-api.binance.vision/api/v3/exchangeInfo?symbol=BTCUSDT", + ], +) +def test_writer_rejects_nonexact_exchange_info_uri( + manifest_fixture: _Fixture, source_uri: str +) -> None: + symbol_metadata = list(manifest_fixture.symbol_metadata) + symbol_metadata[0] = replace(symbol_metadata[0], source_uri=source_uri) + + with pytest.raises( + M8ManifestError, + match=r"exact official exchangeInfo request|invalid network location", + ): + write_m8_input_manifest( + manifest_fixture.config, + manifest_fixture.root, + manifest_fixture.entries, + symbol_metadata, + ) + + +@pytest.mark.parametrize( + "artifact", + [ + "raw_zip", + "raw_sidecar", + "raw_checksum", + "raw_checksum_sidecar", + "dataset_manifest", + "part", + "part_sidecar", + "quality_report", + "quality_findings", + ], +) +def test_reader_rejects_any_artifact_tamper(manifest_fixture: _Fixture, artifact: str) -> None: + entry = manifest_fixture.manifest.entries[0] + paths = { + "raw_zip": entry.raw_zip_path, + "raw_sidecar": entry.raw_source_manifest_path, + "raw_checksum": entry.raw_checksum_path, + "raw_checksum_sidecar": entry.raw_checksum_source_manifest_path, + "dataset_manifest": entry.normalized_dataset_manifest_path, + "part": entry.normalized_parts[0].data_path, + "part_sidecar": entry.normalized_parts[0].sidecar_path, + "quality_report": entry.quality_report_path, + "quality_findings": entry.quality_findings_path, + } + with paths[artifact].open("ab") as handle: + handle.write(b"tamper") + + with pytest.raises(M8ManifestError, match=r"byte count does not match|SHA-256 mismatch"): + read_m8_input_manifest( + manifest_fixture.config, + manifest_fixture.root, + manifest_fixture.manifest.path, + manifest_sha256=manifest_fixture.manifest.sha256, + ) + + +@pytest.mark.parametrize( + "body_kind", + [ + "wrong_digest", + "uppercase_digest", + "wrong_basename", + "carriage_return_only", + "extra_line", + ], +) +def test_reader_rejects_rebound_official_checksum_body_forgery( + manifest_fixture: _Fixture, body_kind: str +) -> None: + payload = _top_payload(manifest_fixture) + entry = manifest_fixture.manifest.entries[0] + digest = entry.raw_zip_sha256 + basename = entry.raw_zip_path.name + if body_kind == "wrong_digest": + body = f"{'0' * 64} {basename}\n".encode("ascii") + elif body_kind == "uppercase_digest": + body = f"{digest.upper()} {basename}\n".encode("ascii") + elif body_kind == "wrong_basename": + body = f"{digest} ETHUSDT-aggTrades-2024-01-03.zip\n".encode("ascii") + elif body_kind == "carriage_return_only": + body = f"{digest} {basename}\r".encode("ascii") + else: + body = f"{digest} {basename}\nextra\n".encode("ascii") + path, manifest_sha = _rebind_archive_checksum_artifacts( + manifest_fixture, + payload, + checksum_body=body, + ) + + with pytest.raises(M8ManifestError, match="body must be exactly one ZIP SHA-256"): + read_m8_input_manifest( + manifest_fixture.config, + manifest_fixture.root, + path, + manifest_sha256=manifest_sha, + ) + + +@pytest.mark.parametrize("line_ending", [b"", b"\n", b"\r\n"]) +def test_reader_preserves_and_accepts_official_single_line_checksum_endings( + manifest_fixture: _Fixture, line_ending: bytes +) -> None: + payload = _top_payload(manifest_fixture) + entry = manifest_fixture.manifest.entries[0] + checksum_body = ( + f"{entry.raw_zip_sha256} {entry.raw_zip_path.name}".encode("ascii") + line_ending + ) + path, manifest_sha = _rebind_archive_checksum_artifacts( + manifest_fixture, + payload, + checksum_body=checksum_body, + ) + + verified = read_m8_input_manifest( + manifest_fixture.config, + manifest_fixture.root, + path, + manifest_sha256=manifest_sha, + ) + + assert verified.entries[0].raw_checksum_path.read_bytes() == checksum_body + + +@pytest.mark.parametrize( + ("case", "message"), + [ + ("source", "source sidecar source claim does not match"), + ("uri", "source sidecar source_uri claim does not match"), + ("range", "does not claim the full UTC day"), + ("checksum", "source sidecar checksum claim does not match"), + ("upstream", "must not claim an upstream checksum"), + ("path", "source sidecar path claim does not match"), + ], +) +def test_reader_rejects_rebound_official_checksum_sidecar_forgery( + manifest_fixture: _Fixture, case: str, message: str +) -> None: + payload = _top_payload(manifest_fixture) + entry = manifest_fixture.manifest.entries[0] + sidecar = json.loads(entry.raw_checksum_source_manifest_path.read_text(encoding="utf-8")) + if case == "source": + sidecar["source"] = "untrusted_source" + elif case == "uri": + sidecar["source_uri"] = entry.raw_source_uri + elif case == "range": + sidecar["requested_range_ns"]["end_exclusive"] -= 1 + elif case == "checksum": + sidecar["checksum"]["value"] = "0" * 64 + elif case == "upstream": + sidecar["upstream_checksum_sha256"] = entry.raw_zip_sha256 + else: + sidecar["path"] = entry.raw_zip_path.name + path, manifest_sha = _rebind_archive_checksum_artifacts( + manifest_fixture, + payload, + sidecar_payload=sidecar, + ) + + with pytest.raises(M8ManifestError, match=message): + read_m8_input_manifest( + manifest_fixture.config, + manifest_fixture.root, + path, + manifest_sha256=manifest_sha, + ) + + +def test_writer_rejects_checksum_uri_not_bound_to_zip(manifest_fixture: _Fixture) -> None: + entries = list(manifest_fixture.entries) + entries[0] = replace( + entries[0], + raw_checksum_source_uri=( + "https://data.binance.vision/data/spot/daily/aggTrades/BTCUSDT/" + "BTCUSDT-aggTrades-2024-01-04.zip.CHECKSUM" + ), + ) + + with pytest.raises(M8ManifestError, match="URI is not bound to its ZIP URI"): + write_m8_input_manifest( + manifest_fixture.config, + manifest_fixture.root, + entries, + manifest_fixture.symbol_metadata, + ) + + +@pytest.mark.parametrize( + "source_uri", + [ + ( + "https://\ndata.binance.vision/data/spot/daily/aggTrades/BTCUSDT/" + "BTCUSDT-aggTrades-2024-01-03.zip" + ), + ( + "https://data.binance.vision:/data/spot/daily/aggTrades/BTCUSDT/" + "BTCUSDT-aggTrades-2024-01-03.zip" + ), + ( + "https://[data.binance.vision/data/spot/daily/aggTrades/BTCUSDT/" + "BTCUSDT-aggTrades-2024-01-03.zip" + ), + ], +) +def test_writer_rejects_noncanonical_archive_uri( + manifest_fixture: _Fixture, source_uri: str +) -> None: + entries = list(manifest_fixture.entries) + entries[0] = replace(entries[0], raw_source_uri=source_uri) + + with pytest.raises( + M8ManifestError, + match=r"exact official daily archive URI|invalid network location", + ): + write_m8_input_manifest( + manifest_fixture.config, + manifest_fixture.root, + entries, + manifest_fixture.symbol_metadata, + ) + + +def test_writer_enforces_official_checksum_byte_ceiling(manifest_fixture: _Fixture) -> None: + entries = list(manifest_fixture.entries) + entries[0] = replace(entries[0], raw_checksum_bytes=4_097) + + with pytest.raises(M8ManifestError, match="4096-byte checksum limit"): + write_m8_input_manifest( + manifest_fixture.config, + manifest_fixture.root, + entries, + manifest_fixture.symbol_metadata, + ) + + +@pytest.mark.parametrize("artifact", ["raw", "source_sidecar"]) +def test_reader_rejects_exchange_info_artifact_tamper( + manifest_fixture: _Fixture, artifact: str +) -> None: + metadata = manifest_fixture.manifest.symbol_metadata[0] + path = metadata.raw_path if artifact == "raw" else metadata.source_manifest_path + with path.open("ab") as handle: + handle.write(b"tamper") + + with pytest.raises(M8ManifestError, match=r"byte count does not match|SHA-256 mismatch"): + read_m8_input_manifest( + manifest_fixture.config, + manifest_fixture.root, + manifest_fixture.manifest.path, + manifest_sha256=manifest_fixture.manifest.sha256, + ) + + +@pytest.mark.parametrize( + ("case", "message"), + [ + ("symbol", "returned a different symbol"), + ("status", "raw body status does not match"), + ("tick", "declared scales do not match"), + ("missing_lot", "lacks PRICE_FILTER or LOT_SIZE provenance"), + ], +) +def test_reader_rejects_rebound_exchange_info_semantic_forgery( + manifest_fixture: _Fixture, case: str, message: str +) -> None: + payload = _top_payload(manifest_fixture) + raw_path = manifest_fixture.manifest.symbol_metadata[0].raw_path + raw_payload = json.loads(raw_path.read_text(encoding="utf-8")) + symbol = raw_payload["symbols"][0] + if case == "symbol": + symbol["symbol"] = "ETHUSDT" + elif case == "status": + symbol["status"] = "BREAK" + elif case == "tick": + symbol["filters"][0]["tickSize"] = "0.02000000" + else: + symbol["filters"] = [symbol["filters"][0]] + path, digest = _rebind_symbol_metadata_artifacts( + manifest_fixture, + payload, + raw_payload=raw_payload, + ) + + with pytest.raises(M8ManifestError, match=message): + read_m8_input_manifest( + manifest_fixture.config, + manifest_fixture.root, + path, + manifest_sha256=digest, + ) + + +@pytest.mark.parametrize( + ("case", "message"), + [ + ("timestamp", "observed timestamp does not match"), + ("range", "must have null API range bounds"), + ("checksum", "source sidecar checksum does not match"), + ("source", "source sidecar source claim does not match"), + ], +) +def test_reader_rejects_rebound_exchange_info_sidecar_forgery( + manifest_fixture: _Fixture, case: str, message: str +) -> None: + payload = _top_payload(manifest_fixture) + sidecar_path = manifest_fixture.manifest.symbol_metadata[0].source_manifest_path + sidecar = json.loads(sidecar_path.read_text(encoding="utf-8")) + if case == "timestamp": + sidecar["downloaded_at_utc"] = "2026-08-07T12:00:00.123456788Z" + elif case == "range": + sidecar["requested_range_ns"]["start"] = 1 + elif case == "checksum": + sidecar["checksum"]["value"] = "0" * 64 + else: + sidecar["source"] = "untrusted_source" + path, digest = _rebind_symbol_metadata_artifacts( + manifest_fixture, + payload, + sidecar_payload=sidecar, + ) + + with pytest.raises(M8ManifestError, match=message): + read_m8_input_manifest( + manifest_fixture.config, + manifest_fixture.root, + path, + manifest_sha256=digest, + ) + + +def test_reader_rejects_manifest_path_traversal_even_when_readdressed( + manifest_fixture: _Fixture, tmp_path: Path +) -> None: + outside = tmp_path / "outside.zip" + outside.write_bytes(b"outside") + payload = _top_payload(manifest_fixture) + payload["entries"][0]["raw"]["zip_path"] = "../../outside.zip" + path, digest = _write_readdressed_manifest(manifest_fixture.root, payload) + + with pytest.raises(M8ManifestError, match="escapes the M8 input root"): + read_m8_input_manifest( + manifest_fixture.config, + manifest_fixture.root, + path, + manifest_sha256=digest, + ) + + +def test_reader_rejects_exchange_info_path_traversal_even_when_readdressed( + manifest_fixture: _Fixture, tmp_path: Path +) -> None: + outside = tmp_path / "outside.json" + outside.write_text('{"symbols": []}', encoding="utf-8") + payload = _top_payload(manifest_fixture) + payload["symbol_metadata"][0]["raw_path"] = "../outside.json" + path, digest = _write_readdressed_manifest(manifest_fixture.root, payload) + + with pytest.raises(M8ManifestError, match="escapes the M8 input root"): + read_m8_input_manifest( + manifest_fixture.config, + manifest_fixture.root, + path, + manifest_sha256=digest, + ) + + +@pytest.mark.parametrize("field", ["path", "source_manifest_path"]) +def test_reader_rejects_official_checksum_path_traversal_even_when_readdressed( + manifest_fixture: _Fixture, tmp_path: Path, field: str +) -> None: + outside = tmp_path / "outside.CHECKSUM" + outside.write_text("0" * 64 + " outside.zip\n", encoding="ascii") + payload = _top_payload(manifest_fixture) + payload["entries"][0]["raw"]["checksum"][field] = "../outside.CHECKSUM" + path, digest = _write_readdressed_manifest(manifest_fixture.root, payload) + + with pytest.raises(M8ManifestError, match="escapes the M8 input root"): + read_m8_input_manifest( + manifest_fixture.config, + manifest_fixture.root, + path, + manifest_sha256=digest, + ) + + +@pytest.mark.parametrize("case", ["missing", "extra"]) +def test_reader_requires_exact_official_checksum_descriptor_keys( + manifest_fixture: _Fixture, case: str +) -> None: + payload = _top_payload(manifest_fixture) + checksum = payload["entries"][0]["raw"]["checksum"] + if case == "missing": + checksum.pop("source_manifest_sha256") + else: + checksum["unbound_claim"] = True + path, digest = _write_readdressed_manifest(manifest_fixture.root, payload) + + with pytest.raises(M8ManifestError, match="official CHECKSUM keys are invalid"): + read_m8_input_manifest( + manifest_fixture.config, + manifest_fixture.root, + path, + manifest_sha256=digest, + ) + + +def test_reader_rejects_pre_checksum_manifest_shape(manifest_fixture: _Fixture) -> None: + payload = _top_payload(manifest_fixture) + payload["manifest_version"] = "1.1.0" + payload["entries"][0]["raw"].pop("checksum") + path, digest = _write_readdressed_manifest(manifest_fixture.root, payload) + + with pytest.raises(M8ManifestError, match="unsupported M8 input manifest version"): + read_m8_input_manifest( + manifest_fixture.config, + manifest_fixture.root, + path, + manifest_sha256=digest, + ) + + +@pytest.mark.parametrize("case", ["order", "total", "version", "extra_key"]) +def test_reader_rejects_symbol_metadata_schema_and_aggregate_tamper( + manifest_fixture: _Fixture, case: str +) -> None: + payload = _top_payload(manifest_fixture) + if case == "order": + payload["symbol_metadata"].reverse() + message = "out of frozen symbol order" + elif case == "total": + payload["total_symbol_metadata_bytes"] += 1 + message = "total symbol metadata byte claim does not match" + elif case == "version": + payload["manifest_version"] = "1.0.0" + message = "unsupported M8 input manifest version" + else: + payload["symbol_metadata"][0]["unbound_claim"] = True + message = r"symbol_metadata\[0\] keys are invalid" + path, digest = _write_readdressed_manifest(manifest_fixture.root, payload) + + with pytest.raises(M8ManifestError, match=message): + read_m8_input_manifest( + manifest_fixture.config, + manifest_fixture.root, + path, + manifest_sha256=digest, + ) + + +def test_reader_rejects_rebound_dataset_row_and_ordinal_forgery( + manifest_fixture: _Fixture, +) -> None: + payload = _top_payload(manifest_fixture) + normalized = payload["entries"][0]["normalized"] + dataset_path = manifest_fixture.root / normalized["dataset_manifest_path"] + dataset = json.loads(dataset_path.read_text(encoding="utf-8")) + dataset["artifacts"][0]["write_ordinal"] = 1 + write_json(dataset_path, dataset) + normalized["dataset_manifest_sha256"] = sha256_file(dataset_path) + normalized["dataset_manifest_bytes"] = dataset_path.stat().st_size + path, digest = _write_readdressed_manifest(manifest_fixture.root, payload) + + with pytest.raises(M8ManifestError, match="write ordinals are not contiguous"): + read_m8_input_manifest( + manifest_fixture.config, + manifest_fixture.root, + path, + manifest_sha256=digest, + ) + + +def test_reader_rejects_rebound_part_sidecar_semantic_forgery( + manifest_fixture: _Fixture, +) -> None: + payload = _top_payload(manifest_fixture) + normalized = payload["entries"][0]["normalized"] + part = normalized["parts"][0] + sidecar_path = manifest_fixture.root / part["sidecar_path"] + sidecar = json.loads(sidecar_path.read_text(encoding="utf-8")) + sidecar["symbol"] = "ETHUSDT" + write_json(sidecar_path, sidecar) + rebound_sidecar_sha = sha256_file(sidecar_path) + part["sidecar_sha256"] = rebound_sidecar_sha + part["sidecar_bytes"] = sidecar_path.stat().st_size + + dataset_path = manifest_fixture.root / normalized["dataset_manifest_path"] + dataset = json.loads(dataset_path.read_text(encoding="utf-8")) + dataset["artifacts"][0]["manifest_sha256"] = rebound_sidecar_sha + write_json(dataset_path, dataset) + normalized["dataset_manifest_sha256"] = sha256_file(dataset_path) + normalized["dataset_manifest_bytes"] = dataset_path.stat().st_size + path, digest = _write_readdressed_manifest(manifest_fixture.root, payload) + + with pytest.raises(M8ManifestError, match="sidecar symbol claim does not match"): + read_m8_input_manifest( + manifest_fixture.config, + manifest_fixture.root, + path, + manifest_sha256=digest, + ) + + +def test_reader_rejects_config_binding_and_content_address_tamper( + manifest_fixture: _Fixture, +) -> None: + payload = _top_payload(manifest_fixture) + payload["config"]["semantic_sha256"] = "0" * 64 + path, digest = _write_readdressed_manifest(manifest_fixture.root, payload) + + with pytest.raises(M8ManifestError, match="different frozen configuration"): + read_m8_input_manifest( + manifest_fixture.config, + manifest_fixture.root, + path, + manifest_sha256=digest, + ) + + copied = manifest_fixture.root / "_manifests" / "not-content-addressed.json" + copied.write_bytes(manifest_fixture.manifest.path.read_bytes()) + with pytest.raises(M8ManifestError, match="filename is not content-addressed"): + read_m8_input_manifest( + manifest_fixture.config, + manifest_fixture.root, + copied, + manifest_sha256=manifest_fixture.manifest.sha256, + ) diff --git a/Microstructure/tests/test_m8_normalization.py b/Microstructure/tests/test_m8_normalization.py new file mode 100644 index 0000000000000000000000000000000000000000..54752fe06028886e82583a6444d4e8965d38d863 --- /dev/null +++ b/Microstructure/tests/test_m8_normalization.py @@ -0,0 +1,346 @@ +from __future__ import annotations + +import hashlib +import json +import zipfile +from datetime import UTC, date, datetime +from decimal import Decimal +from pathlib import Path +from typing import Any, cast + +import pytest + +from microstructure.data.binance_archive import ( + AcquiredDailyArchive, + ArchiveDownloadLimits, + DailyArchiveRequest, + RawArchiveArtifact, +) +from microstructure.data.quality import ValidationReport +from microstructure.m8_config import M8Period, load_m8_config +from microstructure.m8_manifest import M8SymbolMetadata +from microstructure.m8_normalization import ( + M8InsufficientDataError, + M8NormalizationError, + normalize_m8_archive, +) + + +def _sha(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def _fixture( + tmp_path: Path, + *, + role: str, + gap_at: int | None = None, +) -> tuple[object, M8Period, M8SymbolMetadata, AcquiredDailyArchive, Path]: + project_root = Path(__file__).resolve().parents[1] + config = load_m8_config(project_root / "configs" / "m8_multidate_trade_study.toml") + study_date = date(2024, 1, 5) if role == "primary_test" else date(2024, 1, 3) + period = M8Period(date=study_date, role=role) # type: ignore[arg-type] + root = tmp_path / "input" + raw = root / "raw" + raw.mkdir(parents=True) + request = DailyArchiveRequest( + symbol="BTCUSDT", + date=study_date, + tick_size=Decimal("0.01"), + lot_size=Decimal("0.0001"), + ) + start_ms = ( + int(datetime(study_date.year, study_date.month, study_date.day, tzinfo=UTC).timestamp()) + * 1_000 + ) + rows: list[str] = [] + for index in range(180): + aggregate_id = 1000 + index + (1 if gap_at is not None and index >= gap_at else 0) + price = Decimal("100") + Decimal(index % 17) / Decimal("100") + rows.append( + f"{aggregate_id},{price:.2f},0.5000,{2000 + index},{2000 + index}," + f"{start_ms + index},{'true' if index % 2 else 'false'},true\n" + ) + archive_path = raw / request.archive_name + with zipfile.ZipFile(archive_path, "w", compression=zipfile.ZIP_DEFLATED) as archive: + archive.writestr(request.member_name, "".join(rows).encode("ascii")) + archive_sha = _sha(archive_path) + archive_sidecar = raw / "archive.source.json" + archive_sidecar.write_text( + json.dumps({"downloaded_at_utc": "2026-08-07T00:00:00Z"}) + "\n", + encoding="utf-8", + ) + checksum_path = raw / f"{request.archive_name}.CHECKSUM" + checksum_path.write_text(f"{archive_sha} {request.archive_name}\n", encoding="ascii") + checksum_sidecar = raw / "checksum.source.json" + checksum_sidecar.write_text("{}\n", encoding="utf-8") + archive_artifact = RawArchiveArtifact( + kind="archive_zip", + path=archive_path, + manifest_path=archive_sidecar, + sha256=archive_sha, + manifest_sha256=_sha(archive_sidecar), + bytes=archive_path.stat().st_size, + source_uri=( + f"https://data.binance.vision/data/spot/daily/aggTrades/BTCUSDT/{request.archive_name}" + ), + ) + checksum_artifact = RawArchiveArtifact( + kind="archive_checksum", + path=checksum_path, + manifest_path=checksum_sidecar, + sha256=_sha(checksum_path), + manifest_sha256=_sha(checksum_sidecar), + bytes=checksum_path.stat().st_size, + source_uri=f"{archive_artifact.source_uri}.CHECKSUM", + ) + with zipfile.ZipFile(archive_path) as archive: + expanded = archive.getinfo(request.member_name).file_size + acquired = AcquiredDailyArchive( + request=request, + archive_artifact=archive_artifact, + checksum_artifact=checksum_artifact, + upstream_sha256=archive_sha, + declared_uncompressed_bytes=expanded, + limits=ArchiveDownloadLimits( + max_compressed_bytes=10_000_000, + max_uncompressed_bytes=10_000_000, + ), + ) + metadata = M8SymbolMetadata( + symbol="BTCUSDT", + status="TRADING", + tick_size=Decimal("0.01"), + lot_size=Decimal("0.0001"), + observed_ts_ns=1, + raw_path=raw / "unused-metadata.json", + raw_sha256="0" * 64, + raw_bytes=1, + source_uri="https://api.binance.com/api/v3/exchangeInfo?symbol=BTCUSDT", + source_manifest_path=raw / "unused-metadata-sidecar.json", + source_manifest_sha256="1" * 64, + source_manifest_bytes=1, + ) + return config, period, metadata, acquired, root + + +def test_held_out_archive_requires_guard_before_stream_creation( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + config, period, metadata, acquired, root = _fixture(tmp_path, role="primary_test") + opened = 0 + original = cast(Any, zipfile.ZipFile.open) + + def spy(self: zipfile.ZipFile, *args: object, **kwargs: object) -> Any: + nonlocal opened + opened += 1 + return original(self, *args, **kwargs) + + monkeypatch.setattr(zipfile.ZipFile, "open", spy) + with pytest.raises(M8NormalizationError, match="lock-revalidation callback"): + normalize_m8_archive(config, period, metadata, acquired, root) # type: ignore[arg-type] + assert opened == 0 + + +def test_primary_test_cannot_be_spoofed_as_train_to_bypass_guard( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + config, frozen_period, metadata, acquired, root = _fixture( + tmp_path, + role="primary_test", + ) + spoofed_period = M8Period(date=frozen_period.date, role="train") + opened = 0 + original = cast(Any, zipfile.ZipFile.open) + + def spy(self: zipfile.ZipFile, *args: object, **kwargs: object) -> Any: + nonlocal opened + opened += 1 + return original(self, *args, **kwargs) + + monkeypatch.setattr(zipfile.ZipFile, "open", spy) + with pytest.raises(M8NormalizationError, match="exact frozen configuration entry"): + normalize_m8_archive( + config, # type: ignore[arg-type] + spoofed_period, + metadata, + acquired, + root, + ) + assert opened == 0 + + +def test_guard_runs_immediately_before_held_out_member_open( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + config, period, metadata, acquired, root = _fixture(tmp_path, role="primary_test") + events: list[str] = [] + original = cast(Any, zipfile.ZipFile.open) + + def spy(self: zipfile.ZipFile, *args: object, **kwargs: object) -> Any: + events.append("open") + return original(self, *args, **kwargs) + + monkeypatch.setattr(zipfile.ZipFile, "open", spy) + result = normalize_m8_archive( + config, # type: ignore[arg-type] + period, + metadata, + acquired, + root, + before_member_open=lambda: events.append("guard"), + batch_rows=32, + ) + assert events == ["guard", "open"] + assert result.entry.rows == 180 + assert len(result.entry.normalized_parts) >= 1 + + +def test_output_root_isolates_derived_evidence_from_raw_authority(tmp_path: Path) -> None: + config, period, metadata, acquired, raw_root = _fixture(tmp_path, role="train") + raw_before = { + path.relative_to(raw_root).as_posix(): _sha(path) + for path in raw_root.rglob("*") + if path.is_file() + } + derived_root = tmp_path / "normalized_input" + + result = normalize_m8_archive( + config, # type: ignore[arg-type] + period, + metadata, + acquired, + raw_root, + output_root=derived_root, + batch_rows=32, + ) + + assert result.output_root == derived_root.resolve() + assert result.entry.normalized_dataset_manifest_path.is_relative_to(derived_root.resolve()) + assert result.entry.quality_report_path.is_relative_to(derived_root.resolve()) + assert all( + part.data_path.is_relative_to(derived_root.resolve()) + and part.sidecar_path.is_relative_to(derived_root.resolve()) + for part in result.entry.normalized_parts + ) + assert raw_before == { + path.relative_to(raw_root).as_posix(): _sha(path) + for path in raw_root.rglob("*") + if path.is_file() + } + assert not (raw_root / "normalized").exists() + assert not (raw_root / "quality").exists() + + +def test_guard_failure_propagates_without_open_or_data_reclassification( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + config, period, metadata, acquired, root = _fixture(tmp_path, role="primary_test") + opened = 0 + original = cast(Any, zipfile.ZipFile.open) + + def spy(self: zipfile.ZipFile, *args: object, **kwargs: object) -> Any: + nonlocal opened + opened += 1 + return original(self, *args, **kwargs) + + class GuardFailure(RuntimeError): + pass + + def rejected() -> None: + raise GuardFailure("lock changed") + + monkeypatch.setattr(zipfile.ZipFile, "open", spy) + with pytest.raises(GuardFailure, match="lock changed"): + normalize_m8_archive( + config, # type: ignore[arg-type] + period, + metadata, + acquired, + root, + before_member_open=rejected, + ) + assert opened == 0 + + +def test_gap_after_lock_is_typed_insufficient_data(tmp_path: Path) -> None: + config, period, metadata, acquired, root = _fixture( + tmp_path, + role="primary_test", + gap_at=17, + ) + guarded = False + + def guard() -> None: + nonlocal guarded + guarded = True + + with pytest.raises(M8InsufficientDataError, match="noncontiguous") as raised: + normalize_m8_archive( + config, # type: ignore[arg-type] + period, + metadata, + acquired, + root, + before_member_open=guard, + batch_rows=8, + ) + assert guarded is True + assert raised.value.failure_kind == "PAYLOAD_OR_CONTINUITY" + assert raised.value.evidence_completion == "PARTIAL_STREAM" + assert raised.value.completed_evidence is None + + +@pytest.mark.parametrize( + "failure", + [OSError("disk full"), ValueError("writer implementation failure")], +) +def test_parquet_system_failures_are_not_reclassified_as_insufficient_data( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + failure: Exception, +) -> None: + config, period, metadata, acquired, root = _fixture(tmp_path, role="train") + + def fail_write(*_args: object, **_kwargs: object) -> Any: + raise failure + + import microstructure.m8_normalization as normalization_module + + monkeypatch.setattr(normalization_module, "write_partitioned_parquet", fail_write) + with pytest.raises(type(failure), match=str(failure)) as raised: + normalize_m8_archive( + config, # type: ignore[arg-type] + period, + metadata, + acquired, + root, + ) + assert not isinstance(raised.value, M8InsufficientDataError) + + +def test_quality_report_permission_failure_is_not_insufficient_data( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + config, period, metadata, acquired, root = _fixture(tmp_path, role="train") + + def fail_report_write(self: ValidationReport, path: str | Path) -> None: + del self, path + raise PermissionError("quality report is read-only") + + monkeypatch.setattr(ValidationReport, "write_json", fail_report_write) + with pytest.raises(PermissionError, match="quality report is read-only") as raised: + normalize_m8_archive( + config, # type: ignore[arg-type] + period, + metadata, + acquired, + root, + batch_rows=32, + ) + assert not isinstance(raised.value, M8InsufficientDataError) diff --git a/Microstructure/tests/test_m8_pipeline.py b/Microstructure/tests/test_m8_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..caa5ecf009912c6f72e7b216c6826fc59fa6ddfe --- /dev/null +++ b/Microstructure/tests/test_m8_pipeline.py @@ -0,0 +1,2082 @@ +from __future__ import annotations + +import hashlib +import json +import math +import shutil +import zipfile +from collections.abc import Iterator +from dataclasses import dataclass, replace +from datetime import UTC, date, datetime +from decimal import Decimal +from pathlib import Path +from typing import Any, cast + +import pytest + +import microstructure.m8_pipeline as m8_pipeline +import microstructure.research.multidate as multidate +from microstructure.data.storage import write_source_manifest +from microstructure.m8_acquisition import ( + M8AcquisitionError, + M8AcquisitionManifest, + M8RawArchiveDescriptor, + M8RawArchiveEntry, + M8RawSymbolMetadata, + M8RetainedArtifact, +) +from microstructure.m8_config import M8StudyConfig, load_m8_config +from microstructure.provenance import sha256_file +from microstructure.reporting import load_run_bundle, verify_checksums, write_checksum_manifest +from microstructure.research.multidate import ( + AnalysisLock, + FinalFittedState, + MultiDateEvaluationError, +) + + +@dataclass(frozen=True) +class _Harness: + config: M8StudyConfig + authority: M8AcquisitionManifest + run_dir: Path + source_identity: m8_pipeline._SourceIdentity + member_opens: list[tuple[str, str]] + stage_manifests: list[M8AcquisitionManifest] + + +def _write_bytes(path: Path, content: bytes) -> tuple[str, int]: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(content) + return sha256_file(path), path.stat().st_size + + +def _observed_ns(timestamp: str) -> int: + return int(datetime.fromisoformat(timestamp.replace("Z", "+00:00")).timestamp() * 1e9) + + +@pytest.mark.parametrize( + "content", + [ + b'{"key":1,"key":2}', + b'{"key":NaN}', + b'{ "key":1}', + b"\xff", + ], + ids=["duplicate-key", "nan", "noncanonical", "invalid-utf8"], +) +def test_bounded_json_snapshot_rejects_ambiguous_or_noncanonical_input( + tmp_path: Path, + content: bytes, +) -> None: + path = tmp_path / "lock.json" + path.write_bytes(content) + with pytest.raises(m8_pipeline.M8PipelineError): + m8_pipeline._read_bounded_json_snapshot( + path, + label="fixture lock", + expected_sha256=hashlib.sha256(content).hexdigest(), + ensure_ascii=False, + ) + + +def _metadata(root: Path, symbol: str) -> M8RawSymbolMetadata: + downloaded = "2026-08-07T12:00:00.000000000Z" + uri = f"https://data-api.binance.vision/api/v3/exchangeInfo?symbol={symbol}" + payload = { + "symbols": [ + { + "symbol": symbol, + "status": "TRADING", + "baseAsset": symbol.removesuffix("USDT"), + "quoteAsset": "USDT", + "filters": [ + { + "filterType": "PRICE_FILTER", + "minPrice": "0.01", + "maxPrice": "1000000.00", + "tickSize": "0.01", + }, + { + "filterType": "LOT_SIZE", + "minQty": "0.0001", + "maxQty": "100000.0000", + "stepSize": "0.0001", + }, + ], + } + ] + } + raw_body = (json.dumps(payload, sort_keys=True) + "\n").encode() + raw_digest = hashlib.sha256(raw_body).hexdigest() + raw_path = root / "raw" / "binance_spot" / "exchange_info" / symbol / f"{raw_digest}.json" + raw_sha, raw_bytes = _write_bytes( + raw_path, + raw_body, + ) + sidecar_path, sidecar_sha = write_source_manifest( + raw_path, + source="binance_spot_public_api", + source_uri=uri, + downloaded_at_utc=downloaded, + requested_start_ns=None, + requested_end_ns=None, + response_headers={"content-type": "application/json"}, + ) + return M8RawSymbolMetadata( + venue="binance_spot", + symbol=symbol, + status="TRADING", + base_asset=symbol.removesuffix("USDT"), + quote_asset="USDT", + tick_size=Decimal("0.01"), + lot_size=Decimal("0.0001"), + min_price=Decimal("0.01"), + max_price=Decimal("1000000.00"), + min_quantity=Decimal("0.0001"), + max_quantity=Decimal("100000.0000"), + observed_ts_ns=_observed_ns(downloaded), + raw_path=raw_path.resolve(), + raw_sha256=raw_sha, + raw_bytes=raw_bytes, + source_uri=uri, + source_manifest_path=sidecar_path.resolve(), + source_manifest_sha256=sidecar_sha, + source_manifest_bytes=sidecar_path.stat().st_size, + ) + + +def _archive( + root: Path, + config: M8StudyConfig, + *, + symbol: str, + study_date: date, + role: str, + period_index: int, + symbol_index: int, + gap_at: int | None, + silence_at: int | None, +) -> M8RawArchiveEntry: + archive_name = f"{symbol}-aggTrades-{study_date.isoformat()}.zip" + member_name = archive_name.removesuffix(".zip") + ".csv" + archive_uri = f"https://data.binance.vision/data/spot/daily/aggTrades/{symbol}/{archive_name}" + archive_path = ( + root + / "raw" + / "binance_spot" + / "daily_agg_trades_archive" + / symbol + / study_date.isoformat() + / archive_name + ) + start_ms = int( + datetime(study_date.year, study_date.month, study_date.day, tzinfo=UTC).timestamp() * 1_000 + ) + lines: list[str] = [] + first_id = 10_000_000 * (symbol_index + 1) + period_index * 1_000 + for index in range(180): + aggregate_id = first_id + index + (1 if gap_at is not None and index >= gap_at else 0) + price = 100.0 + math.sin(index / 6.0 + period_index * 0.4 + symbol_index * 0.7) + price += 0.12 * math.sin(index / 17.0 + period_index * 0.4) + event_offset_ms = index // 3 + ( + 6_000 if silence_at is not None and index >= silence_at else 0 + ) + lines.append( + f"{aggregate_id},{price:.2f},{0.5 + (index % 11) * 0.03:.4f}," + f"{aggregate_id},{aggregate_id},{start_ms + event_offset_ms}," + f"{'true' if index % 3 else 'false'},true\n" + ) + archive_path.parent.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(archive_path, "w", compression=zipfile.ZIP_DEFLATED) as archive: + archive.writestr(member_name, "".join(lines).encode("ascii")) + archive_sha = sha256_file(archive_path) + checksum_path = ( + root + / "raw" + / "binance_spot" + / "daily_agg_trades_archive_checksums" + / symbol + / study_date.isoformat() + / f"{archive_name}.CHECKSUM" + ) + checksum_sha, checksum_bytes = _write_bytes( + checksum_path, + f"{archive_sha} {archive_name}\n".encode("ascii"), + ) + start_ns = start_ms * 1_000_000 + end_ns = start_ns + 86_400 * 1_000_000_000 + archive_sidecar, archive_sidecar_sha = write_source_manifest( + archive_path, + source=config.study.source, + source_uri=archive_uri, + downloaded_at_utc="2026-08-07T12:00:00Z", + requested_start_ns=start_ns, + requested_end_ns=end_ns, + upstream_checksum_sha256=archive_sha, + response_headers={"content-type": "application/zip"}, + ) + checksum_sidecar, checksum_sidecar_sha = write_source_manifest( + checksum_path, + source="binance_spot_daily_aggtrades_archive_checksum", + source_uri=f"{archive_uri}.CHECKSUM", + downloaded_at_utc="2026-08-07T12:00:00Z", + requested_start_ns=start_ns, + requested_end_ns=end_ns, + response_headers={"content-type": "text/plain"}, + ) + with zipfile.ZipFile(archive_path) as archive: + expanded = archive.getinfo(member_name).file_size + return M8RawArchiveEntry( + root=root.resolve(), + symbol=symbol, + date=study_date, + role=cast(Any, role), + tick_size=Decimal("0.01"), + lot_size=Decimal("0.0001"), + archive_path=archive_path.resolve(), + archive_sha256=archive_sha, + archive_bytes=archive_path.stat().st_size, + archive_source_uri=archive_uri, + archive_source_manifest_path=archive_sidecar.resolve(), + archive_source_manifest_sha256=archive_sidecar_sha, + archive_source_manifest_bytes=archive_sidecar.stat().st_size, + checksum_path=checksum_path.resolve(), + checksum_sha256=checksum_sha, + checksum_bytes=checksum_bytes, + checksum_source_uri=f"{archive_uri}.CHECKSUM", + checksum_source_manifest_path=checksum_sidecar.resolve(), + checksum_source_manifest_sha256=checksum_sidecar_sha, + checksum_source_manifest_bytes=checksum_sidecar.stat().st_size, + upstream_sha256=archive_sha, + member_name=member_name, + declared_uncompressed_bytes=expanded, + max_compressed_bytes=config.study.max_archive_compressed_bytes, + max_uncompressed_bytes=config.study.max_archive_uncompressed_bytes, + max_checksum_bytes=4_096, + transfer_chunk_bytes=64 * 1_024, + max_csv_line_bytes=16 * 1_024, + ) + + +def _retained( + root: Path, metadata: tuple[M8RawSymbolMetadata, ...], archives: tuple[M8RawArchiveEntry, ...] +) -> tuple[M8RetainedArtifact, ...]: + rows: list[M8RetainedArtifact] = [] + + def add(path: Path, kind: str, uri: str, paired: Path | None = None) -> None: + rows.append( + M8RetainedArtifact( + path=path.resolve().relative_to(root.resolve()).as_posix(), + sha256=sha256_file(path), + bytes=path.stat().st_size, + kind=cast(Any, kind), + source_uri=uri, + paired_body_path=( + None + if paired is None + else paired.resolve().relative_to(root.resolve()).as_posix() + ), + ) + ) + + for metadata_item in metadata: + add(metadata_item.raw_path, "metadata_body", metadata_item.source_uri) + add( + metadata_item.source_manifest_path, + "source_manifest", + metadata_item.source_uri, + metadata_item.raw_path, + ) + for archive_item in archives: + add(archive_item.archive_path, "archive_zip", archive_item.archive_source_uri) + add( + archive_item.archive_source_manifest_path, + "source_manifest", + archive_item.archive_source_uri, + archive_item.archive_path, + ) + add( + archive_item.checksum_path, + "archive_checksum", + archive_item.checksum_source_uri, + ) + add( + archive_item.checksum_source_manifest_path, + "source_manifest", + archive_item.checksum_source_uri, + archive_item.checksum_path, + ) + return tuple(sorted(rows, key=lambda item: item.path)) + + +def _authority( + tmp_path: Path, + config: M8StudyConfig, + *, + gaps: set[tuple[str, str]] | None = None, + silences: set[tuple[str, str]] | None = None, +) -> M8AcquisitionManifest: + root = (tmp_path / "authority").resolve() + root.mkdir(parents=True) + metadata = tuple(_metadata(root, symbol) for symbol in config.study.symbols) + archives = tuple( + _archive( + root, + config, + symbol=symbol, + study_date=period.date, + role=period.role, + period_index=period_index, + symbol_index=symbol_index, + gap_at=(17 if gaps and (symbol, period.date.isoformat()) in gaps else None), + silence_at=(90 if silences and (symbol, period.date.isoformat()) in silences else None), + ) + for period_index, period in enumerate(config.periods) + for symbol_index, symbol in enumerate(config.study.symbols) + ) + retained = _retained(root, metadata, archives) + identity = hashlib.sha256( + "".join(f"{item.path}:{item.sha256}:{item.bytes}\n" for item in retained).encode() + ).hexdigest() + body = (json.dumps({"fixture": identity}, sort_keys=True) + "\n").encode() + digest = hashlib.sha256(body).hexdigest() + manifest_path = root / "_manifests" / f"m8-acquisition.manifest-{digest[:20]}.json" + _write_bytes(manifest_path, body) + protocol_path = Path(__file__).resolve().parents[1] / "docs" / "M8_MULTIDATE_TRADE_PROTOCOL.md" + return M8AcquisitionManifest( + root=root, + path=manifest_path.resolve(), + sha256=digest, + config_sha256=config.hash, + config_source_sha256=config.source_sha256, + protocol_version=config.study.protocol_version, + protocol_document_sha256=sha256_file(protocol_path), + copied_from_manifest_sha256=None, + evidence_set_sha256=identity, + symbol_metadata=metadata, + archives=archives, + retained_artifacts=retained, + total_raw_evidence_bytes=sum(item.bytes for item in retained), + total_accepted_zip_bytes=sum(item.archive_bytes for item in archives), + config=config, + ) + + +def _install_boundaries( + monkeypatch: pytest.MonkeyPatch, + authority: M8AcquisitionManifest, + source_identity: m8_pipeline._SourceIdentity, + member_opens: list[tuple[str, str]], + stage_manifests: list[M8AcquisitionManifest], +) -> None: + by_path: dict[Path, M8AcquisitionManifest] = {authority.path.resolve(): authority} + + def read_manifest( + path: str | Path, + *, + expected_sha256: str, + config: M8StudyConfig, + ) -> M8AcquisitionManifest: + resolved = Path(path).resolve() + observed = by_path.get(resolved) + if observed is None: + for staged in stage_manifests: + if staged.sha256 != expected_sha256: + continue + destination = resolved.parent.parent + + def move( + staged_path: Path, + source_root: Path = staged.root, + target_root: Path = destination, + ) -> Path: + relative = staged_path.resolve().relative_to(source_root.resolve()) + return (target_root / relative).resolve() + + observed = replace( + staged, + root=destination, + path=resolved, + symbol_metadata=tuple( + replace( + item, + raw_path=move(item.raw_path), + source_manifest_path=move(item.source_manifest_path), + ) + for item in staged.symbol_metadata + ), + archives=tuple( + replace( + item, + root=destination, + archive_path=move(item.archive_path), + archive_source_manifest_path=move(item.archive_source_manifest_path), + checksum_path=move(item.checksum_path), + checksum_source_manifest_path=move(item.checksum_source_manifest_path), + ) + for item in staged.archives + ), + ) + by_path[resolved] = observed + break + if observed is None: + raise AssertionError(f"unexpected acquisition manifest path: {resolved}") + assert observed.sha256 == expected_sha256 + assert observed.config_sha256 == config.hash + if observed.copied_from_manifest_sha256 is not None: + expected_files = {item.path for item in observed.retained_artifacts} | { + observed.path.relative_to(observed.root).as_posix() + } + actual_files = { + item.relative_to(observed.root).as_posix() + for item in observed.root.rglob("*") + if item.is_file() + } + if actual_files != expected_files: + raise M8AcquisitionError("unexpected acquisition-root artifact") + return observed + + def rebase(path: Path, destination: Path) -> Path: + return (destination / path.resolve().relative_to(authority.root.resolve())).resolve() + + def copy_manifest( + observed: M8AcquisitionManifest, + destination_root: str | Path, + ) -> M8AcquisitionManifest: + assert observed is authority + destination = Path(destination_root).resolve() + shutil.copytree(authority.root, destination) + copied_authority_path = rebase(authority.path, destination) + copied_authority_path.unlink() + copied_body = ( + json.dumps( + {"fixture": authority.content_identity_sha256, "copied_from": authority.sha256}, + sort_keys=True, + ) + + "\n" + ).encode() + copied_sha = hashlib.sha256(copied_body).hexdigest() + copied_path = ( + destination / "_manifests" / (f"m8-acquisition.manifest-{copied_sha[:20]}.json") + ) + _write_bytes(copied_path, copied_body) + copied_metadata = tuple( + replace( + item, + raw_path=rebase(item.raw_path, destination), + source_manifest_path=rebase(item.source_manifest_path, destination), + ) + for item in authority.symbol_metadata + ) + copied_archives = tuple( + replace( + item, + root=destination, + archive_path=rebase(item.archive_path, destination), + archive_source_manifest_path=rebase(item.archive_source_manifest_path, destination), + checksum_path=rebase(item.checksum_path, destination), + checksum_source_manifest_path=rebase( + item.checksum_source_manifest_path, destination + ), + ) + for item in authority.archives + ) + copied = replace( + authority, + root=destination, + path=copied_path, + sha256=copied_sha, + copied_from_manifest_sha256=authority.sha256, + symbol_metadata=copied_metadata, + archives=copied_archives, + ) + by_path[copied.path.resolve()] = copied + stage_manifests.append(copied) + return copied + + original_open = cast(Any, zipfile.ZipFile.open) + + def open_spy(self: zipfile.ZipFile, name: object, *args: object, **kwargs: object) -> Any: + member_name = name.filename if isinstance(name, zipfile.ZipInfo) else str(name) + filename = Path(member_name).name + if filename.endswith(".csv"): + symbol, _, study_date = filename.removesuffix(".csv").partition("-aggTrades-") + member_opens.append((symbol, study_date)) + return original_open(self, name, *args, **kwargs) + + monkeypatch.setattr(m8_pipeline, "read_m8_acquisition_manifest", read_manifest) + monkeypatch.setattr(m8_pipeline, "copy_m8_acquisition_into", copy_manifest) + monkeypatch.setattr(m8_pipeline, "_capture_source_identity", lambda _root: source_identity) + monkeypatch.setattr(zipfile.ZipFile, "open", open_spy) + + +def _harness( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + *, + gaps: set[tuple[str, str]] | None = None, + silences: set[tuple[str, str]] | None = None, +) -> _Harness: + project_root = Path(__file__).resolve().parents[1] + config = load_m8_config(project_root / "configs" / "m8_multidate_trade_study.toml") + authority = _authority(tmp_path, config, gaps=gaps, silences=silences) + source = m8_pipeline._SourceIdentity( + commit="0" * 40, + dirty=False, + source_tree_sha256="1" * 64, + ) + opens: list[tuple[str, str]] = [] + staged: list[M8AcquisitionManifest] = [] + _install_boundaries(monkeypatch, authority, source, opens, staged) + return _Harness( + config=config, + authority=authority, + run_dir=(tmp_path / "run").resolve(), + source_identity=source, + member_opens=opens, + stage_manifests=staged, + ) + + +def _refresh_failure_inventory(run_dir: Path, *changed_paths: Path) -> None: + inventory_path = run_dir / "data" / "failure_evidence_inventory.json" + inventory = json.loads(inventory_path.read_text(encoding="utf-8")) + by_path = {item["path"]: item for item in inventory} + for path in changed_paths: + relative = path.relative_to(run_dir).as_posix() + by_path[relative]["sha256"] = sha256_file(path) + by_path[relative]["bytes"] = path.stat().st_size + m8_pipeline._write_json(inventory_path, inventory) + write_checksum_manifest(run_dir) + + +@pytest.fixture(scope="module") +def completed(tmp_path_factory: pytest.TempPathFactory) -> Iterator[_Harness]: + tmp_path = tmp_path_factory.mktemp("m8-pipeline-v2") + patcher = pytest.MonkeyPatch() + harness = _harness(tmp_path, patcher) + result = m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + assert result.status == "COMPLETE" + assert result.path == harness.run_dir + try: + yield harness + finally: + patcher.undo() + + +def test_first_held_out_member_opens_only_after_both_durable_locks( + completed: _Harness, +) -> None: + assert completed.member_opens == [ + ("BTCUSDT", "2024-01-03"), + ("ETHUSDT", "2024-01-03"), + ("BTCUSDT", "2024-01-04"), + ("ETHUSDT", "2024-01-04"), + ("BTCUSDT", "2024-01-05"), + ("ETHUSDT", "2024-01-05"), + ("BTCUSDT", "2024-01-06"), + ("ETHUSDT", "2024-01-06"), + ] + aggregate_path = completed.run_dir / "analysis" / "analysis_lock.json" + aggregate = json.loads(aggregate_path.read_text(encoding="utf-8")) + assert aggregate["source_identity"] == completed.source_identity.public_dict() + assert aggregate["raw_acquisition_manifest_sha256"] == completed.authority.sha256 + assert aggregate["development_manifest_sha256"] == sha256_file( + completed.run_dir / aggregate["development_manifest_path"] + ) + assert (completed.run_dir / "analysis" / "analysis_lock.sha256").read_text() == ( + f"{sha256_file(aggregate_path)} analysis_lock.json\n" + ) + for symbol in completed.config.study.symbols: + assert ( + completed.run_dir / "analysis" / "locks" / f"{symbol.lower()}.selection_lock.json" + ).is_file() + + +def test_final_fitted_state_is_bound_across_complete_bundle_authorities( + completed: _Harness, +) -> None: + aggregate = json.loads( + (completed.run_dir / "analysis" / "analysis_lock.json").read_text(encoding="utf-8") + ) + claims = [ + { + "symbol": item["symbol"], + "path": item["final_fitted_state_path"], + "sha256": item["final_fitted_state_sha256"], + } + for item in aggregate["symbols"] + ] + primary_start_ns = int(datetime(2024, 1, 5, tzinfo=UTC).timestamp() * 1_000_000_000) + for aggregate_symbol, claim in zip( + aggregate["symbols"], + claims, + strict=True, + ): + state_path = completed.run_dir / claim["path"] + state = FinalFittedState.restore( + state_path.read_text(encoding="utf-8"), + claim["sha256"], + ) + child_path = completed.run_dir / aggregate_symbol["selection_lock_path"] + child = AnalysisLock.restore( + child_path.read_text(encoding="utf-8"), + aggregate_symbol["selection_lock_sha256"], + ).payload() + assert sha256_file(state_path) == claim["sha256"] + assert child["final_fitted_state_sha256"] == claim["sha256"] + assert child["final_fitted_state"] == state.payload() + assert state.payload()["fit_cutoff_ts_ns"] < primary_start_ns + + provenance = json.loads((completed.run_dir / "provenance.json").read_text()) + research_manifest = json.loads((completed.run_dir / "research" / "manifest.json").read_text()) + run_manifest = json.loads((completed.run_dir / "run_manifest.json").read_text()) + expected_sha_by_symbol = {claim["symbol"]: claim["sha256"] for claim in claims} + assert provenance["final_fitted_states"] == claims + assert research_manifest["final_fitted_states"] == claims + assert run_manifest["research"]["final_fitted_states"] == claims + assert provenance["run_key_inputs"]["final_fitted_state_sha256_by_symbol"] == ( + expected_sha_by_symbol + ) + + +def test_no_model_or_calibrator_fit_occurs_after_held_out_authority_boundary( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + harness = _harness(tmp_path, monkeypatch) + fit_counts = {"classifier": 0, "calibrator": 0} + boundary_snapshots: list[tuple[int, int]] = [] + original_classifier = multidate.make_classifier + original_calibrator_fit = multidate.SigmoidCalibrator.fit + original_boundary = m8_pipeline._assert_test_open_authority + + def classifier_spy(*args: Any, **kwargs: Any) -> Any: + fit_counts["classifier"] += 1 + return original_classifier(*args, **kwargs) + + def calibrator_fit_spy(*args: Any, **kwargs: Any) -> Any: + fit_counts["calibrator"] += 1 + return original_calibrator_fit(*args, **kwargs) + + def boundary_spy(**kwargs: Any) -> None: + original_boundary(**kwargs) + for selection in kwargs["selections"]: + assert sha256_file(selection.fitted_state_path) == ( + selection.selection.fitted_state.sha256 + ) + boundary_snapshots.append((fit_counts["classifier"], fit_counts["calibrator"])) + + monkeypatch.setattr(multidate, "make_classifier", classifier_spy) + monkeypatch.setattr(multidate.SigmoidCalibrator, "fit", calibrator_fit_spy) + monkeypatch.setattr(m8_pipeline, "_assert_test_open_authority", boundary_spy) + + result = m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + assert result.status == "COMPLETE" + assert boundary_snapshots + assert boundary_snapshots[0][0] > 0 + assert boundary_snapshots[0][1] > 0 + assert all(snapshot == boundary_snapshots[0] for snapshot in boundary_snapshots) + assert (fit_counts["classifier"], fit_counts["calibrator"]) == boundary_snapshots[0] + + +def test_complete_bundle_has_final_manifest_then_endpoints_and_narrow_claims( + completed: _Harness, +) -> None: + bundle = load_run_bundle(completed.run_dir) + assert bundle.evidence_tier == "FULL_DATA" + assert bundle.data["all_requested_ranges_complete"] is True + assert len(bundle.hypothesis_evaluation["per_date"]) == 4 + assert len(bundle.hypothesis_evaluation["per_symbol"]) == 2 + assert bundle.manifest["execution_assumptions"]["status"] == "NOT_RUN" + assert bundle.hypothesis_evaluation["p_values_computed"] is False + assert bundle.hypothesis_evaluation["cross_instrument_conclusion"]["pooling_performed"] is False + final_path = completed.run_dir / bundle.provenance["m8_input_manifest_path"] + assert final_path.is_file() + research = json.loads((completed.run_dir / "research" / "manifest.json").read_text()) + assert research["final_all_date_manifest_committed_before_endpoint_evaluation"] is True + assert len(research["entries"]) == 8 + predictions = completed.run_dir / "models" / "predictions.parquet" + assert predictions.is_file() + + +def test_self_contained_snapshot_has_no_duplicate_raw_evidence(completed: _Harness) -> None: + snapshot = json.loads( + (completed.run_dir / "data" / "manifest_snapshot.json").read_text(encoding="utf-8") + ) + assert snapshot["self_contained_bundle_input"] is True + assert snapshot["snapshot_created_additional_raw_evidence_copies"] is False + assert "external" not in json.dumps(snapshot).lower() + provenance = json.loads((completed.run_dir / "provenance.json").read_text()) + budget = provenance["raw_evidence_byte_budget"] + assert budget["external_total"] == completed.authority.total_raw_evidence_bytes + assert budget["bundle_copy_total"] == completed.authority.total_raw_evidence_bytes + assert budget["combined_total"] == 2 * completed.authority.total_raw_evidence_bytes + staged = completed.stage_manifests[0] + physical = sum( + (completed.run_dir / "data" / "input" / item.path).stat().st_size + for item in staged.retained_artifacts + ) + assert physical == staged.total_raw_evidence_bytes + assert len({item.path for item in staged.retained_artifacts}) == len(staged.retained_artifacts) + + +def test_complete_reuse_changes_no_bytes_or_member_opens(completed: _Harness) -> None: + before = { + path.relative_to(completed.run_dir).as_posix(): sha256_file(path) + for path in completed.run_dir.rglob("*") + if path.is_file() + } + open_count = len(completed.member_opens) + result = m8_pipeline.reproduce_m8( + completed.config, + completed.run_dir, + raw_manifest_path=completed.authority.path, + raw_manifest_sha256=completed.authority.sha256, + ) + assert result.status == "COMPLETE" + assert len(completed.member_opens) == open_count + assert before == { + path.relative_to(completed.run_dir).as_posix(): sha256_file(path) + for path in completed.run_dir.rglob("*") + if path.is_file() + } + + +def test_complete_reuse_rejects_mutated_success_marker( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + harness = _harness(tmp_path, monkeypatch) + result = m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + (result.path / "_SUCCESS").write_bytes(b"tampered terminal bytes\n") + with pytest.raises(m8_pipeline.M8PipelineError, match="terminal marker bytes"): + m8_pipeline.verify_m8_result( + result.path, + harness.config, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + + +@pytest.mark.parametrize( + "artifact", + ["aggregate", "digest_sidecar", "child_lock", "fitted_state", "development_manifest"], +) +def test_complete_reuse_rejects_rechecksummed_lock_chain_tampering( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + artifact: str, +) -> None: + harness = _harness(tmp_path, monkeypatch) + result = m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + aggregate_path = result.path / "analysis" / "analysis_lock.json" + aggregate = json.loads(aggregate_path.read_text(encoding="utf-8")) + if artifact == "aggregate": + aggregate["source_identity"] = { + "commit": "f" * 40, + "dirty": False, + "source_tree_sha256": "e" * 64, + } + aggregate_path.write_text( + json.dumps(aggregate, sort_keys=True, separators=(",", ":")), + encoding="utf-8", + ) + elif artifact == "digest_sidecar": + (result.path / "analysis" / "analysis_lock.sha256").write_text( + f"{'0' * 64} analysis_lock.json\n", + encoding="utf-8", + ) + elif artifact == "child_lock": + child = result.path / aggregate["symbols"][0]["selection_lock_path"] + child.write_bytes(child.read_bytes() + b"\n") + elif artifact == "fitted_state": + state = result.path / aggregate["symbols"][0]["final_fitted_state_path"] + state.write_bytes(state.read_bytes() + b"\n") + else: + development = result.path / aggregate["development_manifest_path"] + development.write_bytes(development.read_bytes() + b"\n") + + (result.path / "_SUCCESS").unlink() + write_checksum_manifest(result.path) + (result.path / "_SUCCESS").write_bytes(b"complete\n") + with pytest.raises(m8_pipeline.M8PipelineError, match="completed"): + m8_pipeline.verify_m8_result( + result.path, + harness.config, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + + +def test_complete_verifier_bounds_fitted_state_reads( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + harness = _harness(tmp_path, monkeypatch) + result = m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + aggregate = json.loads( + (result.path / "analysis" / "analysis_lock.json").read_text(encoding="utf-8") + ) + state = result.path / aggregate["symbols"][0]["final_fitted_state_path"] + state.write_bytes(b"x" * (m8_pipeline._MAX_LOCK_JSON_BYTES + 1)) + (result.path / "_SUCCESS").unlink() + write_checksum_manifest(result.path) + (result.path / "_SUCCESS").write_bytes(b"complete\n") + with pytest.raises(m8_pipeline.M8PipelineError, match="hard limit"): + m8_pipeline.verify_m8_result( + result.path, + harness.config, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + + +def test_postlock_inventory_binding_rejects_temporary_rechecksummed_lock_swap( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + harness = _harness(tmp_path, monkeypatch, gaps={("BTCUSDT", "2024-01-05")}) + result = m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + failure_path = result.path / "failure.json" + provenance_path = result.path / "provenance.json" + run_manifest_path = result.path / "run_manifest.json" + failure = json.loads(failure_path.read_text(encoding="utf-8")) + provenance = json.loads(provenance_path.read_text(encoding="utf-8")) + run_manifest = json.loads(run_manifest_path.read_text(encoding="utf-8")) + aggregate_path = result.path / failure["analysis_lock_path"] + sidecar_path = aggregate_path.with_name("analysis_lock.sha256") + aggregate = json.loads(aggregate_path.read_text(encoding="utf-8")) + aggregate["unclaimed_rechecksummed_extension"] = True + replacement_bytes = json.dumps( + aggregate, + sort_keys=True, + separators=(",", ":"), + ).encode("utf-8") + replacement_sha = hashlib.sha256(replacement_bytes).hexdigest() + failure["analysis_lock_sha256"] = replacement_sha + provenance["selection_lock_sha256"] = replacement_sha + run_manifest["research"]["analysis_lock"]["sha256"] = replacement_sha + m8_pipeline._write_json(failure_path, failure) + m8_pipeline._write_json(provenance_path, provenance) + m8_pipeline._write_json(run_manifest_path, run_manifest) + _refresh_failure_inventory(result.path, failure_path, provenance_path, run_manifest_path) + + saved_aggregate = tmp_path / "saved-analysis-lock.json" + saved_sidecar = tmp_path / "saved-analysis-lock.sha256" + replacement_aggregate = tmp_path / "replacement-analysis-lock.json" + replacement_sidecar = tmp_path / "replacement-analysis-lock.sha256" + shutil.copy2(aggregate_path, saved_aggregate) + shutil.copy2(sidecar_path, saved_sidecar) + replacement_aggregate.write_bytes(replacement_bytes) + replacement_sidecar.write_text( + f"{replacement_sha} analysis_lock.json\n", + encoding="utf-8", + ) + original_verify_chain = m8_pipeline._verify_insufficient_lock_chain + swapped = False + + def swap_during_semantic_verification(*args: Any, **kwargs: Any) -> None: + nonlocal swapped + replacement_aggregate.replace(aggregate_path) + replacement_sidecar.replace(sidecar_path) + swapped = True + try: + original_verify_chain(*args, **kwargs) + finally: + saved_aggregate.replace(aggregate_path) + saved_sidecar.replace(sidecar_path) + + monkeypatch.setattr( + m8_pipeline, + "_verify_insufficient_lock_chain", + swap_during_semantic_verification, + ) + with pytest.raises(m8_pipeline.M8PipelineError, match="failure evidence inventory"): + m8_pipeline.verify_m8_result( + result.path, + harness.config, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + assert swapped is True + + +def test_descriptor_integrity_error_is_terminal_insufficient_data( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + harness = _harness(tmp_path, monkeypatch) + + def fail_integrity(_descriptor: M8RawArchiveDescriptor) -> Any: + raise M8AcquisitionError("fixture raw integrity failure") + + monkeypatch.setattr(M8RawArchiveDescriptor, "reconstruct", fail_integrity) + result = m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + assert result.status == "INSUFFICIENT_DATA" + assert (result.path / "INSUFFICIENT_DATA").read_bytes() == b"terminal\n" + assert harness.member_opens == [] + + +@pytest.mark.parametrize("fault", ["permission", "wrapped_permission", "assertion"]) +def test_descriptor_system_fault_does_not_publish_terminal_result( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + fault: str, +) -> None: + harness = _harness(tmp_path, monkeypatch) + + def fail_system(_descriptor: M8RawArchiveDescriptor) -> Any: + if fault == "assertion": + raise AssertionError("fixture programmer fault") + if fault == "permission": + raise PermissionError("fixture permission fault") + try: + raise PermissionError("fixture wrapped permission fault") + except PermissionError as exc: + raise M8AcquisitionError("cannot verify fixture raw evidence") from exc + + monkeypatch.setattr(M8RawArchiveDescriptor, "reconstruct", fail_system) + with pytest.raises(m8_pipeline.M8PipelineError, match="failed closed"): + m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + assert not harness.run_dir.exists() + assert not tuple(tmp_path.glob(".run.staging-*")) + assert harness.member_opens == [] + + +@pytest.mark.parametrize("commit,dirty", [("UNBORN", False), ("0" * 40, True)]) +def test_dirty_or_unborn_source_opens_zero_members( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + commit: str, + dirty: bool, +) -> None: + harness = _harness(tmp_path, monkeypatch) + bad_source = replace(harness.source_identity, commit=commit, dirty=dirty) + monkeypatch.setattr(m8_pipeline, "_capture_source_identity", lambda _root: bad_source) + with pytest.raises(m8_pipeline.M8PipelineError): + m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + assert harness.member_opens == [] + + +def test_missing_lock_opens_zero_held_out_members( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + harness = _harness(tmp_path, monkeypatch) + original = m8_pipeline._commit_aggregate_lock + + def commit_then_remove(*args: Any, **kwargs: Any) -> tuple[Path, str]: + path, digest = original(*args, **kwargs) + path.unlink() + return path, digest + + monkeypatch.setattr(m8_pipeline, "_commit_aggregate_lock", commit_then_remove) + with pytest.raises(m8_pipeline.M8PipelineError, match="aggregate lock"): + m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + assert all(study_date in {"2024-01-03", "2024-01-04"} for _, study_date in harness.member_opens) + + +def test_aggregate_path_replacement_during_same_fd_snapshot_opens_zero_held_out_members( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + harness = _harness(tmp_path, monkeypatch) + original_commit = m8_pipeline._commit_aggregate_lock + original_read = m8_pipeline.os.read + armed: dict[str, Any] = {} + + def commit_then_arm(*args: Any, **kwargs: Any) -> tuple[Path, str]: + path, digest = original_commit(*args, **kwargs) + replacement = path.with_name(".analysis_lock.replacement.json") + shutil.copy2(path, replacement) + armed.update( + { + "path": path, + "replacement": replacement, + "inode": path.stat().st_ino, + "swapped": False, + } + ) + return path, digest + + def replace_after_first_read(descriptor: int, count: int) -> bytes: + chunk = original_read(descriptor, count) + if ( + armed + and not armed["swapped"] + and m8_pipeline.os.fstat(descriptor).st_ino == armed["inode"] + ): + path = cast(Path, armed["path"]) + original = path.with_name(".analysis_lock.original.json") + path.rename(original) + cast(Path, armed["replacement"]).rename(path) + armed["swapped"] = True + return chunk + + monkeypatch.setattr(m8_pipeline, "_commit_aggregate_lock", commit_then_arm) + monkeypatch.setattr(m8_pipeline.os, "read", replace_after_first_read) + with pytest.raises(m8_pipeline.M8PipelineError, match="changed"): + m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + assert armed["swapped"] is True + assert all(study_date in {"2024-01-03", "2024-01-04"} for _, study_date in harness.member_opens) + assert not harness.run_dir.exists() + + +@pytest.mark.parametrize( + "artifact", + ["aggregate", "digest_sidecar", "child_lock", "fitted_state", "development_manifest"], +) +def test_lock_boundary_rejects_symlink_artifacts_before_held_out_open( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + artifact: str, +) -> None: + harness = _harness(tmp_path, monkeypatch) + original = m8_pipeline._commit_aggregate_lock + + def commit_then_symlink(*args: Any, **kwargs: Any) -> tuple[Path, str]: + path, digest = original(*args, **kwargs) + aggregate = json.loads(path.read_text(encoding="utf-8")) + stage = path.parent.parent + targets = { + "aggregate": path, + "digest_sidecar": path.with_name("analysis_lock.sha256"), + "child_lock": stage / aggregate["symbols"][0]["selection_lock_path"], + "fitted_state": stage / aggregate["symbols"][0]["final_fitted_state_path"], + "development_manifest": stage / aggregate["development_manifest_path"], + } + target = targets[artifact] + real = target.with_name(f".{target.name}.real") + target.rename(real) + target.symlink_to(real.name) + return path, digest + + monkeypatch.setattr(m8_pipeline, "_commit_aggregate_lock", commit_then_symlink) + with pytest.raises(m8_pipeline.M8PipelineError): + m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + assert all(study_date in {"2024-01-03", "2024-01-04"} for _, study_date in harness.member_opens) + assert not harness.run_dir.exists() + + +@pytest.mark.parametrize( + "artifact", + ["aggregate", "digest_sidecar", "child_lock", "fitted_state", "development_manifest"], +) +def test_lock_boundary_rejects_oversized_artifacts_before_held_out_open( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + artifact: str, +) -> None: + harness = _harness(tmp_path, monkeypatch) + original = m8_pipeline._commit_aggregate_lock + + def commit_then_oversize(*args: Any, **kwargs: Any) -> tuple[Path, str]: + path, digest = original(*args, **kwargs) + aggregate = json.loads(path.read_text(encoding="utf-8")) + stage = path.parent.parent + targets = { + "aggregate": path, + "digest_sidecar": path.with_name("analysis_lock.sha256"), + "child_lock": stage / aggregate["symbols"][0]["selection_lock_path"], + "fitted_state": stage / aggregate["symbols"][0]["final_fitted_state_path"], + "development_manifest": stage / aggregate["development_manifest_path"], + } + target = targets[artifact] + limit = ( + m8_pipeline._MAX_LOCK_DIGEST_BYTES + if artifact == "digest_sidecar" + else m8_pipeline._MAX_LOCK_JSON_BYTES + ) + target.write_bytes(b"x" * (limit + 1)) + return path, digest + + monkeypatch.setattr(m8_pipeline, "_commit_aggregate_lock", commit_then_oversize) + with pytest.raises(m8_pipeline.M8PipelineError, match="hard limit"): + m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + assert all(study_date in {"2024-01-03", "2024-01-04"} for _, study_date in harness.member_opens) + assert not harness.run_dir.exists() + + +def test_same_size_different_stage_authority_opens_zero_held_out_members( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + harness = _harness(tmp_path, monkeypatch) + original = m8_pipeline._commit_aggregate_lock + + def commit_then_tamper(*args: Any, **kwargs: Any) -> tuple[Path, str]: + result = original(*args, **kwargs) + staged = harness.stage_manifests[0] + harness.stage_manifests[0] = replace(staged, evidence_set_sha256="f" * 64) + # The reader closure resolves by path. Replace its visible object through + # the pipeline argument as well; exact totals remain unchanged. + monkeypatch.setattr( + m8_pipeline, + "read_m8_acquisition_manifest", + lambda path, *, expected_sha256, config: ( + harness.stage_manifests[0] + if Path(path).resolve() == staged.path.resolve() + else harness.authority + ), + ) + return result + + monkeypatch.setattr(m8_pipeline, "_commit_aggregate_lock", commit_then_tamper) + with pytest.raises(m8_pipeline.M8PipelineError, match="differs"): + m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + assert all(study_date in {"2024-01-03", "2024-01-04"} for _, study_date in harness.member_opens) + + +def test_prelock_gap_publishes_terminal_insufficient_without_held_out_open( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + harness = _harness(tmp_path, monkeypatch, gaps={("BTCUSDT", "2024-01-03")}) + result = m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + assert result.status == "INSUFFICIENT_DATA" + assert result.normalized_manifest_sha256 is None + failure = json.loads((result.path / "failure.json").read_text()) + assert failure["failed_after_analysis_lock"] is False + assert failure["reason_code"] == "ARCHIVE_PAYLOAD_OR_CONTINUITY" + assert failure["failure_stage"] == "development_normalization" + assert failure["failed_role"] == "train" + assert failure["failed_normalization_evidence"] == { + "schema_version": "m8-failed-normalization-evidence-v1", + "failure_kind": "PAYLOAD_OR_CONTINUITY", + "evidence_completion": "PARTIAL_STREAM", + "normalized_prefix": "data/normalized_input/normalized/BTCUSDT/2024-01-03", + "quality_prefix": "data/normalized_input/quality/BTCUSDT/2024-01-03", + "artifacts": [], + "complete_normalization": None, + } + assert failure["analysis_lock"] is None + assert failure["analysis_lock_path"] is None + assert failure["analysis_lock_sha256"] is None + assert failure["aggregate_lock_committed"] is False + assert failure["selection_started"] is False + assert failure["selection_completed_symbols"] == [] + assert failure["endpoint_evaluation_started"] is False + assert failure["endpoint_evaluation_completed"] is False + assert failure["endpoint_artifacts_published"] is False + assert failure["held_out_member_opened"] is False + assert not (result.path / "analysis" / "analysis_lock.json").exists() + assert not tuple(result.path.rglob("*prediction*")) + assert harness.member_opens == [("BTCUSDT", "2024-01-03")] + assert verify_checksums(result.path) > 0 + + +def test_early_payload_failure_preserves_canonical_partial_parts( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + harness = _harness(tmp_path, monkeypatch, gaps={("BTCUSDT", "2024-01-03")}) + original_normalize = m8_pipeline.normalize_m8_archive + + def normalize_in_small_batches(*args: Any, **kwargs: Any) -> Any: + kwargs["batch_rows"] = 8 + return original_normalize(*args, **kwargs) + + monkeypatch.setattr(m8_pipeline, "normalize_m8_archive", normalize_in_small_batches) + result = m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + + failure = json.loads((result.path / "failure.json").read_text(encoding="utf-8")) + evidence = failure["failed_normalization_evidence"] + assert evidence["evidence_completion"] == "PARTIAL_STREAM" + assert evidence["artifacts"] + assert all( + item["path"].endswith(".parquet") or ".manifest-" in item["path"] + for item in evidence["artifacts"] + ) + assert not tuple((result.path / evidence["normalized_prefix"] / "_manifests").glob("*.json")) + assert not (result.path / evidence["quality_prefix"] / "report.json").exists() + assert ( + m8_pipeline.verify_m8_result( + result.path, + harness.config, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ).status + == "INSUFFICIENT_DATA" + ) + + +def test_second_symbol_warning_preserves_separated_evidence_and_verifies( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + harness = _harness( + tmp_path, + monkeypatch, + silences={("ETHUSDT", "2024-01-03")}, + ) + result = m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + + assert result.status == "INSUFFICIENT_DATA" + assert result.normalized_manifest_sha256 is None + failure = json.loads((result.path / "failure.json").read_text(encoding="utf-8")) + assert failure["failure_stage"] == "development_normalization" + assert failure["failed_symbol"] == "ETHUSDT" + assert failure["failed_date"] == "2024-01-03" + assert failure["failed_role"] == "train" + assert failure["reason_code"] == "ARCHIVE_QUALITY_GATE" + assert failure["held_out_member_opened"] is False + failed_evidence = failure["failed_normalization_evidence"] + assert failed_evidence["failure_kind"] == "QUALITY_GATE" + assert failed_evidence["evidence_completion"] == "COMPLETE_DATASET_AND_QUALITY" + assert failed_evidence["complete_normalization"]["quality_warnings"] == 1 + assert [ + (item["symbol"], item["date"], item["role"]) for item in failure["completed_normalizations"] + ] == [("BTCUSDT", "2024-01-03", "train")] + assert harness.member_opens == [ + ("BTCUSDT", "2024-01-03"), + ("ETHUSDT", "2024-01-03"), + ] + + raw_root = result.path / "data" / "input" + staged = harness.stage_manifests[0] + expected_raw_files = {item.path for item in staged.retained_artifacts} | { + staged.path.relative_to(staged.root).as_posix() + } + assert { + path.relative_to(raw_root).as_posix() for path in raw_root.rglob("*") if path.is_file() + } == expected_raw_files + assert {path.name for path in raw_root.iterdir()} == {"_manifests", "raw"} + assert not (raw_root / "normalized").exists() + assert not (raw_root / "quality").exists() + + derived_root = result.path / "data" / "normalized_input" + btc_reports = tuple((derived_root / "quality" / "BTCUSDT").rglob("report.json")) + eth_reports = tuple((derived_root / "quality" / "ETHUSDT").rglob("report.json")) + assert len(btc_reports) == len(eth_reports) == 1 + assert json.loads(btc_reports[0].read_text(encoding="utf-8"))["summary"] == { + "errors": 0, + "warnings": 0, + } + assert json.loads(eth_reports[0].read_text(encoding="utf-8"))["summary"] == { + "errors": 0, + "warnings": 1, + } + assert tuple((derived_root / "normalized" / "BTCUSDT").rglob("*.parquet")) + assert tuple((derived_root / "normalized" / "ETHUSDT").rglob("*.parquet")) + inventory = json.loads( + (result.path / "data" / "failure_evidence_inventory.json").read_text(encoding="utf-8") + ) + assert any( + item["path"].startswith("data/normalized_input/quality/ETHUSDT/") for item in inventory + ) + + verified = m8_pipeline.verify_m8_result( + result.path, + harness.config, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + assert verified.status == "INSUFFICIENT_DATA" + member_opens_before_reuse = len(harness.member_opens) + reused = m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + assert reused == verified + assert len(harness.member_opens) == member_opens_before_reuse + + +def test_quality_failure_cannot_drop_failed_evidence_and_rechecksum( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + harness = _harness( + tmp_path, + monkeypatch, + silences={("ETHUSDT", "2024-01-03")}, + ) + result = m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + shutil.rmtree( + result.path / "data" / "normalized_input" / "normalized" / "ETHUSDT" / "2024-01-03" + ) + shutil.rmtree(result.path / "data" / "normalized_input" / "quality" / "ETHUSDT" / "2024-01-03") + terminal_exclusions = { + "data/failure_evidence_inventory.json", + "checksums.sha256", + "INSUFFICIENT_DATA", + } + rebuilt_inventory = [ + { + "path": path.relative_to(result.path).as_posix(), + "sha256": sha256_file(path), + "bytes": path.stat().st_size, + } + for path in sorted(result.path.rglob("*")) + if path.is_file() and path.relative_to(result.path).as_posix() not in terminal_exclusions + ] + m8_pipeline._write_json( + result.path / "data" / "failure_evidence_inventory.json", + rebuilt_inventory, + ) + write_checksum_manifest(result.path) + + with pytest.raises(m8_pipeline.M8PipelineError, match=r"failed normalization|quality-gate"): + m8_pipeline.verify_m8_result( + result.path, + harness.config, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + + +def test_inventory_semantic_read_rejects_post_hash_swap( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + harness = _harness( + tmp_path, + monkeypatch, + silences={("ETHUSDT", "2024-01-03")}, + ) + result = m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + report_relative = "data/normalized_input/quality/BTCUSDT/2024-01-03/report.json" + original_verify = m8_pipeline._verify_inventory_file + swapped = False + + def verify_then_swap(root: Path, item: m8_pipeline._FailureEvidenceItem) -> None: + nonlocal swapped + original_verify(root, item) + if item.path == report_relative and not swapped: + report_path = root / report_relative + report_path.write_bytes(report_path.read_bytes() + b" ") + swapped = True + + monkeypatch.setattr(m8_pipeline, "_verify_inventory_file", verify_then_swap) + with pytest.raises(m8_pipeline.M8PipelineError, match=r"SHA-256|inventory|canonical"): + m8_pipeline.verify_m8_result( + result.path, + harness.config, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + assert swapped is True + + +def test_bundled_raw_retained_artifact_rejects_rechecksummed_inventory_mismatch( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + harness = _harness(tmp_path, monkeypatch, gaps={("BTCUSDT", "2024-01-03")}) + result = m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + staged = harness.stage_manifests[0] + retained = staged.retained_artifacts[0] + retained_path = result.path / "data" / "input" / retained.path + retained_path.write_bytes(retained_path.read_bytes() + b"\n") + _refresh_failure_inventory(result.path, retained_path) + + with pytest.raises(m8_pipeline.M8PipelineError, match="failure evidence inventory"): + m8_pipeline.verify_m8_result( + result.path, + harness.config, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + + +def test_final_manifest_part_claim_must_match_failure_inventory( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + harness = _harness(tmp_path, monkeypatch) + original_evaluate = m8_pipeline._evaluate_symbol + + def fail_second(symbol: str, *args: Any, **kwargs: Any) -> Any: + if symbol == "ETHUSDT": + raise MultiDateEvaluationError("fixture evaluation insufficiency") + return original_evaluate(symbol, *args, **kwargs) + + monkeypatch.setattr(m8_pipeline, "_evaluate_symbol", fail_second) + result = m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + original_load = m8_pipeline._load_final_input_manifest + + def load_with_forged_part_claim(*args: Any, **kwargs: Any) -> Any: + manifest = original_load(*args, **kwargs) + first_entry = manifest.entries[0] + forged_part = replace(first_entry.normalized_parts[0], data_sha256="f" * 64) + forged_entry = replace( + first_entry, + normalized_parts=(forged_part, *first_entry.normalized_parts[1:]), + ) + return replace(manifest, entries=(forged_entry, *manifest.entries[1:])) + + monkeypatch.setattr(m8_pipeline, "_load_final_input_manifest", load_with_forged_part_claim) + with pytest.raises(m8_pipeline.M8PipelineError, match="failure evidence inventory"): + m8_pipeline.verify_m8_result( + result.path, + harness.config, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + + +@pytest.mark.parametrize( + "mutation", + [ + "missing_entry", + "extra_entry", + "undeclared_file", + "path_escape", + "wrong_sha", + "wrong_bytes", + "duplicate_path", + ], +) +def test_failure_inventory_rejects_rechecksummed_physical_or_schema_tampering( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + mutation: str, +) -> None: + harness = _harness( + tmp_path, + monkeypatch, + gaps={("ETHUSDT", "2024-01-03")}, + ) + result = m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + inventory_path = result.path / "data" / "failure_evidence_inventory.json" + inventory = json.loads(inventory_path.read_text(encoding="utf-8")) + assert isinstance(inventory, list) and inventory + + if mutation == "missing_entry": + inventory.pop(0) + elif mutation == "extra_entry": + inventory.append( + { + "path": "zzzz-missing-evidence.bin", + "sha256": "0" * 64, + "bytes": 1, + } + ) + elif mutation == "undeclared_file": + (result.path / "undeclared-evidence.bin").write_bytes(b"undeclared\n") + elif mutation == "path_escape": + inventory[0]["path"] = "../escaped-evidence.bin" + elif mutation == "wrong_sha": + inventory[0]["sha256"] = "0" * 64 + elif mutation == "wrong_bytes": + inventory[0]["bytes"] += 1 + else: + inventory.append(dict(inventory[0])) + inventory.sort(key=lambda item: item["path"]) + inventory_path.write_text( + json.dumps(inventory, indent=2, sort_keys=True) + "\n", + encoding="utf-8", + ) + write_checksum_manifest(result.path) + + with pytest.raises(m8_pipeline.M8PipelineError, match="inventory"): + m8_pipeline.verify_m8_result( + result.path, + harness.config, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + + +def test_failure_inventory_rejects_rechecksummed_completed_evidence_mismatch( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + harness = _harness( + tmp_path, + monkeypatch, + gaps={("ETHUSDT", "2024-01-03")}, + ) + result = m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + failure_path = result.path / "failure.json" + failure = json.loads(failure_path.read_text(encoding="utf-8")) + assert len(failure["completed_normalizations"]) == 1 + failure["completed_normalizations"][0]["normalized_dataset_manifest_sha256"] = "0" * 64 + failure_path.write_text( + json.dumps(failure, indent=2, sort_keys=True) + "\n", + encoding="utf-8", + ) + + inventory_path = result.path / "data" / "failure_evidence_inventory.json" + inventory = json.loads(inventory_path.read_text(encoding="utf-8")) + failure_entry = next(item for item in inventory if item["path"] == "failure.json") + failure_entry["sha256"] = sha256_file(failure_path) + failure_entry["bytes"] = failure_path.stat().st_size + inventory_path.write_text( + json.dumps(inventory, indent=2, sort_keys=True) + "\n", + encoding="utf-8", + ) + write_checksum_manifest(result.path) + + with pytest.raises(m8_pipeline.M8PipelineError, match=r"completed|normalized"): + m8_pipeline.verify_m8_result( + result.path, + harness.config, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + + +def test_producer_rejects_invalid_terminal_before_publish( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + harness = _harness(tmp_path, monkeypatch, gaps={("BTCUSDT", "2024-01-03")}) + original_publish = m8_pipeline._publish_prelock_insufficient_data + + def publish_then_tamper(*args: Any, **kwargs: Any) -> None: + original_publish(*args, **kwargs) + stage = cast(Path, kwargs["stage"]) + inventory_path = stage / "data" / "failure_evidence_inventory.json" + inventory = json.loads(inventory_path.read_text(encoding="utf-8")) + inventory[0]["sha256"] = "0" * 64 + inventory_path.write_text( + json.dumps(inventory, indent=2, sort_keys=True) + "\n", + encoding="utf-8", + ) + write_checksum_manifest(stage) + + monkeypatch.setattr( + m8_pipeline, + "_publish_prelock_insufficient_data", + publish_then_tamper, + ) + with pytest.raises(m8_pipeline.M8PipelineError, match="inventory"): + m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + assert not harness.run_dir.exists() + assert not tuple(harness.run_dir.parent.glob(f".{harness.run_dir.name}.staging-*")) + + +@pytest.mark.parametrize("complete", [False, True]) +def test_producer_self_verifies_stage_and_published_terminal( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + complete: bool, +) -> None: + harness = _harness( + tmp_path, + monkeypatch, + gaps=None if complete else {("BTCUSDT", "2024-01-03")}, + ) + function_name = "_reuse_completed" if complete else "_reuse_insufficient" + original_reuse = cast(Any, getattr(m8_pipeline, function_name)) + verified_paths: list[Path] = [] + + def reuse_spy(target: Path, *args: Any, **kwargs: Any) -> Any: + verified_paths.append(target.resolve()) + return original_reuse(target, *args, **kwargs) + + monkeypatch.setattr(m8_pipeline, function_name, reuse_spy) + result = m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + + assert result.status == ("COMPLETE" if complete else "INSUFFICIENT_DATA") + assert len(verified_paths) == 2 + assert verified_paths[0] != harness.run_dir + assert verified_paths[0].parent == harness.run_dir.parent + assert verified_paths[1] == harness.run_dir + + +def test_postlock_gap_preserves_lock_and_stops_before_later_dates( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + harness = _harness(tmp_path, monkeypatch, gaps={("BTCUSDT", "2024-01-05")}) + result = m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + assert result.status == "INSUFFICIENT_DATA" + failure = json.loads((result.path / "failure.json").read_text()) + assert failure["failed_after_analysis_lock"] is True + assert failure["reason_code"] == "ARCHIVE_PAYLOAD_OR_CONTINUITY" + assert failure["failure_stage"] == "held_out_normalization" + assert failure["failed_role"] == "primary_test" + assert failure["aggregate_lock_committed"] is True + assert failure["selection_completed_symbols"] == list(harness.config.study.symbols) + assert failure["endpoint_evaluation_started"] is False + assert failure["endpoint_evaluation_completed"] is False + assert failure["endpoint_artifacts_published"] is False + assert (result.path / failure["analysis_lock_path"]).is_file() + assert failure["final_all_date_normalized_manifest"] is None + assert ("ETHUSDT", "2024-01-05") not in harness.member_opens + assert not tuple(result.path.rglob("*prediction*")) + before = len(harness.member_opens) + reused = m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + assert reused.status == "INSUFFICIENT_DATA" + assert len(harness.member_opens) == before + + +def test_second_symbol_evaluation_failure_publishes_no_endpoint( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + harness = _harness(tmp_path, monkeypatch) + original = m8_pipeline._evaluate_symbol + + def fail_second(symbol: str, *args: Any, **kwargs: Any) -> Any: + if symbol == "ETHUSDT": + raise MultiDateEvaluationError("fixture evaluation insufficiency") + return original(symbol, *args, **kwargs) + + monkeypatch.setattr(m8_pipeline, "_evaluate_symbol", fail_second) + result = m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + assert result.status == "INSUFFICIENT_DATA" + assert result.normalized_manifest_sha256 is not None + assert not tuple(result.path.rglob("*prediction*")) + assert not (result.path / ".endpoint-staging").exists() + failure = json.loads((result.path / "failure.json").read_text()) + assert failure["final_all_date_normalized_manifest"]["sha256"] == ( + result.normalized_manifest_sha256 + ) + assert failure["reason_code"] == "LOCKED_EVALUATION_INSUFFICIENT" + assert failure["failure_stage"] == "locked_evaluation" + assert failure["failed_role"] == "all_test_dates" + assert failure["endpoint_evaluation_started"] is True + assert failure["endpoint_evaluation_completed"] is False + assert failure["endpoint_artifacts_published"] is False + assert failure["endpoint_evaluation_completed_symbols"] == ["BTCUSDT"] + assert failure["endpoint_evaluation_completed_symbol_count"] == 1 + + +@pytest.mark.parametrize( + "artifact", + [ + "aggregate", + "digest_sidecar", + "child_lock", + "fitted_state", + "development_manifest", + "failure_claim", + "provenance_claim", + ], +) +def test_postlock_failure_rejects_rechecksummed_lock_chain_tampering( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + artifact: str, +) -> None: + harness = _harness(tmp_path, monkeypatch, gaps={("BTCUSDT", "2024-01-05")}) + result = m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + failure_path = result.path / "failure.json" + failure = json.loads(failure_path.read_text(encoding="utf-8")) + aggregate_path = result.path / failure["analysis_lock_path"] + aggregate = json.loads(aggregate_path.read_text(encoding="utf-8")) + if artifact == "aggregate": + aggregate_path.write_bytes(aggregate_path.read_bytes() + b"\n") + elif artifact == "digest_sidecar": + (result.path / "analysis" / "analysis_lock.sha256").write_text( + f"{'0' * 64} analysis_lock.json\n", + encoding="utf-8", + ) + elif artifact == "child_lock": + child = result.path / aggregate["symbols"][0]["selection_lock_path"] + child.write_bytes(child.read_bytes() + b"\n") + elif artifact == "fitted_state": + state = result.path / aggregate["symbols"][0]["final_fitted_state_path"] + state.write_bytes(state.read_bytes() + b"\n") + elif artifact == "development_manifest": + development = result.path / aggregate["development_manifest_path"] + development.write_bytes(development.read_bytes() + b"\n") + elif artifact == "failure_claim": + failure["analysis_lock_sha256"] = "0" * 64 + failure_path.write_text( + json.dumps(failure, sort_keys=True, indent=2) + "\n", + encoding="utf-8", + ) + else: + provenance_path = result.path / "provenance.json" + provenance = json.loads(provenance_path.read_text(encoding="utf-8")) + provenance["selection_lock_sha256"] = "0" * 64 + provenance_path.write_text( + json.dumps(provenance, sort_keys=True, indent=2) + "\n", + encoding="utf-8", + ) + write_checksum_manifest(result.path) + with pytest.raises(m8_pipeline.M8PipelineError): + m8_pipeline.verify_m8_result( + result.path, + harness.config, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + assert not tuple(result.path.rglob("*prediction*")) + + +def test_insufficient_verifier_bounds_child_lock_reads( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + harness = _harness(tmp_path, monkeypatch, gaps={("BTCUSDT", "2024-01-05")}) + result = m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + failure = json.loads((result.path / "failure.json").read_text(encoding="utf-8")) + aggregate = json.loads( + (result.path / failure["analysis_lock_path"]).read_text(encoding="utf-8") + ) + child = result.path / aggregate["symbols"][0]["selection_lock_path"] + child.write_bytes(b"x" * (m8_pipeline._MAX_LOCK_JSON_BYTES + 1)) + _refresh_failure_inventory(result.path, child) + with pytest.raises(m8_pipeline.M8PipelineError, match=r"hard limit|failure evidence inventory"): + m8_pipeline.verify_m8_result( + result.path, + harness.config, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + + +@pytest.mark.parametrize( + ("field", "value"), + [ + ("reason_code", "UNRECOGNIZED"), + ("failure_stage", "model_selection"), + ("failed_role", "replication_test"), + ], +) +def test_failure_rejects_rechecksummed_typed_identity_tampering( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + field: str, + value: str, +) -> None: + harness = _harness(tmp_path, monkeypatch, gaps={("BTCUSDT", "2024-01-05")}) + result = m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + failure_path = result.path / "failure.json" + failure = json.loads(failure_path.read_text(encoding="utf-8")) + failure[field] = value + failure_path.write_text( + json.dumps(failure, sort_keys=True, indent=2) + "\n", + encoding="utf-8", + ) + _refresh_failure_inventory(result.path, failure_path) + with pytest.raises(m8_pipeline.M8PipelineError, match=r"failure|reason|stage|role"): + m8_pipeline.verify_m8_result( + result.path, + harness.config, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + + +def test_prelock_failure_rejects_rechecksummed_aggregate_lock_claim( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + harness = _harness(tmp_path, monkeypatch, gaps={("BTCUSDT", "2024-01-03")}) + result = m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + failure_path = result.path / "failure.json" + failure = json.loads(failure_path.read_text(encoding="utf-8")) + failure["analysis_lock_sha256"] = "0" * 64 + failure_path.write_text( + json.dumps(failure, sort_keys=True, indent=2) + "\n", + encoding="utf-8", + ) + _refresh_failure_inventory(result.path, failure_path) + with pytest.raises(m8_pipeline.M8PipelineError, match=r"pre-lock.*lock claim"): + m8_pipeline.verify_m8_result( + result.path, + harness.config, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + + +@pytest.mark.parametrize("artifact", ["child_lock", "fitted_state"]) +def test_partial_selection_failure_preserves_and_verifies_completed_child_lock( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + artifact: str, +) -> None: + harness = _harness(tmp_path, monkeypatch) + original = m8_pipeline._select_symbol + + def fail_second(symbol: str, *args: Any, **kwargs: Any) -> Any: + if symbol == "ETHUSDT": + raise MultiDateEvaluationError("fixture second-symbol selection insufficiency") + return original(symbol, *args, **kwargs) + + monkeypatch.setattr(m8_pipeline, "_select_symbol", fail_second) + result = m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + failure = json.loads((result.path / "failure.json").read_text(encoding="utf-8")) + assert failure["failure_stage"] == "model_selection" + assert failure["selection_started"] is True + assert failure["selection_completed_symbols"] == ["BTCUSDT"] + assert failure["selection_completed_symbol_count"] == 1 + assert failure["aggregate_lock_committed"] is False + assert failure["held_out_member_opened"] is False + assert len(failure["selection_locks"]) == 1 + child_path = result.path / failure["selection_locks"][0]["path"] + assert child_path.is_file() + assert not (result.path / "analysis" / "analysis_lock.json").exists() + assert not tuple(result.path.rglob("*prediction*")) + assert ( + m8_pipeline.verify_m8_result( + result.path, + harness.config, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ).status + == "INSUFFICIENT_DATA" + ) + + if artifact == "child_lock": + child_path.write_bytes(child_path.read_bytes() + b"\n") + changed_path = child_path + else: + state_path = result.path / failure["final_fitted_states"][0]["path"] + state_path.write_bytes(state_path.read_bytes() + b"\n") + changed_path = state_path + _refresh_failure_inventory(result.path, changed_path) + with pytest.raises(m8_pipeline.M8PipelineError, match="partial BTCUSDT"): + m8_pipeline.verify_m8_result( + result.path, + harness.config, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + + +@pytest.mark.parametrize("complete", [False, True]) +def test_terminal_publication_flushes_tree_before_checksums_and_marker( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + complete: bool, +) -> None: + gaps = None if complete else {("BTCUSDT", "2024-01-03")} + harness = _harness(tmp_path, monkeypatch, gaps=gaps) + events: list[str] = [] + original_tree = m8_pipeline._fsync_tree + original_checksums = cast(Any, m8_pipeline).write_checksum_manifest + original_marker = m8_pipeline._create_terminal_marker + + def flush_tree(path: Path) -> None: + events.append("tree") + original_tree(path) + + def checksums(path: str | Path) -> Path: + assert events[-1] == "tree" + events.append("checksums") + return cast(Path, original_checksums(path)) + + def marker(path: Path, content: str) -> None: + assert events[-1] == "checksums" + events.append("marker") + original_marker(path, content) + + monkeypatch.setattr(m8_pipeline, "_fsync_tree", flush_tree) + monkeypatch.setattr(m8_pipeline, "write_checksum_manifest", checksums) + monkeypatch.setattr(m8_pipeline, "_create_terminal_marker", marker) + result = m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + assert result.status == ("COMPLETE" if complete else "INSUFFICIENT_DATA") + assert events == ["tree", "checksums", "marker"] + + +def test_failure_marker_is_exact_and_mutually_exclusive( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + harness = _harness(tmp_path, monkeypatch, gaps={("BTCUSDT", "2024-01-03")}) + result = m8_pipeline.reproduce_m8( + harness.config, + harness.run_dir, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + marker = result.path / "INSUFFICIENT_DATA" + assert marker.read_bytes() == b"terminal\n" + marker.write_text("changed\n", encoding="utf-8") + with pytest.raises(m8_pipeline.M8PipelineError, match="marker bytes"): + m8_pipeline.verify_m8_result( + result.path, + harness.config, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + marker.write_bytes(b"terminal\n") + (result.path / "_SUCCESS").write_text("complete\n", encoding="utf-8") + with pytest.raises(m8_pipeline.M8PipelineError, match="conflicting"): + m8_pipeline.verify_m8_result( + result.path, + harness.config, + raw_manifest_path=harness.authority.path, + raw_manifest_sha256=harness.authority.sha256, + ) + + +def test_every_complete_bundle_byte_is_checksum_protected(completed: _Harness) -> None: + protected = verify_checksums(completed.run_dir) + actual = [ + path + for path in completed.run_dir.rglob("*") + if path.is_file() and path.name not in {"checksums.sha256", "_SUCCESS"} + ] + assert protected == len(actual) diff --git a/Microstructure/tests/test_models.py b/Microstructure/tests/test_models.py new file mode 100644 index 0000000000000000000000000000000000000000..964200f0bd03620b06421aea2077a78c2696734d --- /dev/null +++ b/Microstructure/tests/test_models.py @@ -0,0 +1,213 @@ +from __future__ import annotations + +import numpy as np +import polars as pl +import pytest + +from microstructure.config import EvaluationConfig, ModelConfig +from microstructure.research.models import ( + ModelEvaluationError, + SigmoidCalibrator, + block_bootstrap_metric, + build_model_candidates, + classification_metrics, + evaluate_model_ladder, + paired_block_bootstrap_difference, +) +from microstructure.research.splits import expanding_walk_forward_splits + + +def _evaluation_config() -> EvaluationConfig: + return EvaluationConfig( + min_train_events=20, + validation_events=8, + test_events=8, + step_events=8, + embargo_events=1, + bootstrap_samples=40, + calibration_bins=5, + ) + + +def _model_config() -> ModelConfig: + return ModelConfig( + selection_metric="log_loss", + logistic_c_values=(1.0,), + tree_max_depth_values=(2,), + tree_min_samples_leaf=1, + ) + + +def _model_frame() -> pl.DataFrame: + rows: list[dict[str, object]] = [] + for decision in range(48): + positive = decision % 2 + for symbol_offset, symbol in enumerate(("BTCUSDT", "ETHUSDT")): + censored = decision == 47 + rows.append( + { + "symbol": symbol, + "decision_ts_ns": decision, + "label_information_end_ts_ns": None if censored else decision + 1, + "right_censored": censored, + "future_mid_up": None if censored else positive, + "future_mid_return": None if censored else (0.001 if positive else -0.001), + "feature_ready": True, + "spread_bps": 2.0 + 0.1 * symbol_offset, + "depth_total_l1": 20.0, + "queue_imbalance_l1": 0.8 if positive else -0.8, + "microprice_deviation_bps": 0.5 if positive else -0.5, + "ofi_l1": 2.0 if positive else -2.0, + "log_mid_return_1": 0.0001 if positive else -0.0001, + "ofi_w2": 3.0 if positive else -3.0, + "signed_trade_volume_w2": 4.0 if positive else -4.0, + "trade_volume_w2": 4.0, + "trade_count_w2": 1.0, + "trade_intensity_w2": 2.0, + "realized_volatility_w2": 0.001, + } + ) + return pl.DataFrame(rows).sort(["decision_ts_ns", "symbol"]) + + +def test_model_ladder_contains_required_transparent_families() -> None: + candidates = build_model_candidates(_model_config()) + assert [candidate.family for candidate in candidates] == [ + "baseline", + "logistic", + "logistic_l2", + "shallow_tree", + ] + + +def test_out_of_time_ladder_is_deterministic_and_test_is_not_selected_on() -> None: + frame = _model_frame() + plan = expanding_walk_forward_splits(frame, _evaluation_config()) + first = evaluate_model_ladder( + frame, + plan, + _model_config(), + seed=7, + calibration_bins=5, + ) + second = evaluate_model_ladder( + frame, + plan, + _model_config(), + seed=7, + calibration_bins=5, + ) + + assert first.selected_model == second.selected_model + assert first.comparison.equals(second.comparison) + assert first.predictions.equals(second.predictions) + assert first.predictions.get_column("is_oos").all() + assert first.predictions.filter( + pl.col("fit_cutoff_ts_ns") >= pl.col("decision_ts_ns") + ).is_empty() + assert set(first.comparison.get_column("split")) == {"validation", "test"} + assert first.comparison.get_column("instrument_scope").unique().to_list() == ["POOLED"] + assert first.comparison.filter(pl.col("split") == "test").get_column( + "period_start_ts_ns" + ).unique().to_list() == [40] + assert {"sample_id", "decision_sequence"}.issubset(first.predictions.columns) + selected = first.comparison.filter(pl.col("selected_on_validation")) + assert selected.get_column("model").unique().to_list() == [first.selected_model] + + +def test_single_class_fallback_is_labeled_as_prior_and_cannot_win_selection() -> None: + frame = _model_frame().with_columns( + pl.when(pl.col("right_censored")) + .then(None) + .otherwise(1) + .cast(pl.Int8) + .alias("future_mid_up") + ) + plan = expanding_walk_forward_splits(frame, _evaluation_config()) + result = evaluate_model_ladder( + frame, + plan, + _model_config(), + seed=7, + calibration_bins=5, + ) + + fallback = result.comparison.filter(pl.col("requested_family") != "baseline") + assert fallback.get_column("family").unique().to_list() == ["baseline"] + assert fallback.get_column("model").str.ends_with("__prior_fallback").all() + assert fallback.get_column("fit_status").str.contains("single_class_prior_fallback").all() + assert result.selected_model == "historical_prior" + + +def test_label_columns_are_rejected_from_feature_allowlist() -> None: + frame = _model_frame() + plan = expanding_walk_forward_splits(frame, _evaluation_config()) + with pytest.raises(ModelEvaluationError, match="cannot be model features"): + evaluate_model_ladder( + frame, + plan, + _model_config(), + seed=7, + calibration_bins=5, + features=("queue_imbalance_l1", "future_mid_return"), + ) + + +def test_calibration_and_metrics_have_exact_small_values() -> None: + y_true = np.asarray([0, 1], dtype=np.int64) + probability = np.asarray([0.1, 0.9], dtype=np.float64) + metrics = classification_metrics(y_true, probability, calibration_bins=2) + assert metrics["accuracy"] == 1.0 + assert metrics["brier_score"] == pytest.approx(0.01) + assert metrics["log_loss"] == pytest.approx(-np.log(0.9)) + assert metrics["expected_calibration_error"] == pytest.approx(0.1) + + calibrator = SigmoidCalibrator() + calibration_y = np.asarray([0, 0, 0, 0, 0, 1, 1, 1, 1, 1], dtype=np.int64) + raw = np.linspace(0.2, 0.8, 10, dtype=np.float64) + calibrator.fit(calibration_y, raw) + transformed = calibrator.transform(raw) + assert calibrator.status == "sigmoid" + assert np.all((transformed >= 0.0) & (transformed <= 1.0)) + assert np.all(np.diff(transformed) > 0) + + +def test_block_bootstrap_is_seeded_and_paired_identity_is_zero() -> None: + predictions = pl.DataFrame( + { + "row_id": list(range(8)), + "y_true": [0, 1, 0, 1, 1, 0, 1, 0], + "probability": [0.1, 0.8, 0.2, 0.7, 0.9, 0.3, 0.6, 0.4], + "block": ["a", "a", "a", "a", "b", "b", "b", "b"], + } + ) + first = block_bootstrap_metric( + predictions, + metric="brier_score", + block_column="block", + n_bootstrap=40, + seed=11, + ) + second = block_bootstrap_metric( + predictions, + metric="brier_score", + block_column="block", + n_bootstrap=40, + seed=11, + ) + assert first == second + assert first.status == "ok" + assert first.n_blocks == 2 + + paired = paired_block_bootstrap_difference( + predictions, + predictions, + metric="brier_score", + block_column="block", + n_bootstrap=40, + seed=11, + ) + assert paired.point_estimate == 0.0 + assert paired.lower == 0.0 + assert paired.upper == 0.0 + assert set(paired.draws) == {0.0} diff --git a/Microstructure/tests/test_multidate.py b/Microstructure/tests/test_multidate.py new file mode 100644 index 0000000000000000000000000000000000000000..6a2b9d14848ce31a6b06c2a33d68bb894705780b --- /dev/null +++ b/Microstructure/tests/test_multidate.py @@ -0,0 +1,607 @@ +from __future__ import annotations + +import json +from datetime import UTC, datetime + +import numpy as np +import polars as pl +import pytest + +import microstructure.research.multidate as multidate +from microstructure.config import FeatureConfig, ModelConfig +from microstructure.research.models import ModelCandidate, build_model_candidates +from microstructure.research.multidate import ( + DATE_BOOTSTRAP_BLOCK_EVENTS, + DATE_BOOTSTRAP_DRAWS, + AnalysisLock, + FinalFittedState, + MultiDateEvaluationError, + build_multidate_walk_forward_plan, + evaluate_locked_multidate_tests, + paired_date_log_loss, + select_multidate_model, +) +from microstructure.research.trade_only import build_trade_only_research_frame + + +def _model_config() -> ModelConfig: + return ModelConfig( + selection_metric="log_loss", + logistic_c_values=(1.0,), + tree_max_depth_values=(2,), + tree_min_samples_leaf=5, + ) + + +def _date_frame( + study_date: str, + study_role: str, + *, + invert_target: bool = False, + rows: int = 121, +) -> pl.DataFrame: + midnight = datetime.fromisoformat(f"{study_date}T00:00:00+00:00") + start_ns = int(midnight.timestamp() * 1_000_000_000) + continuity = f"BTCUSDT:{study_date}" + records: list[dict[str, object]] = [] + for sequence in range(rows): + decision_ts_ns = start_ns + sequence * 1_000_000_000 + decision_trade_id = 10_000 + sequence + censored = sequence == rows - 1 + positive = sequence % 2 + if invert_target: + positive = 1 - positive + records.append( + { + "study_date": study_date, + "study_role": study_role, + "symbol": "BTCUSDT", + "decision_ts_ns": decision_ts_ns, + "decision_trade_id": decision_trade_id, + "decision_sequence": sequence, + "continuity_id": continuity, + "feature_continuity_id": continuity, + "label_continuity_id": None if censored else continuity, + "max_feature_source_ts_ns": decision_ts_ns, + "max_feature_source_trade_id": decision_trade_id, + "label_start_ts_ns": decision_ts_ns, + "label_start_trade_id": decision_trade_id, + "label_information_end_ts_ns": (None if censored else decision_ts_ns + 750_000_000), + "label_information_end_trade_id": (None if censored else decision_trade_id + 1), + "feature_ready": True, + "right_censored": censored, + "future_trade_up": None if censored else positive, + "signal": 1.0 if sequence % 2 else -1.0, + "slow_feature": float(sequence) / rows, + "sample_id": f"BTCUSDT:{study_date}:{sequence}", + } + ) + return pl.DataFrame(records).with_columns( + pl.col("future_trade_up").cast(pl.Int8), + pl.col("label_start_ts_ns").cast(pl.Int64), + pl.col("label_start_trade_id").cast(pl.Int64), + pl.col("label_information_end_ts_ns").cast(pl.Int64), + pl.col("label_information_end_trade_id").cast(pl.Int64), + ) + + +def _study_frames() -> tuple[list[pl.DataFrame], list[pl.DataFrame]]: + development = [ + _date_frame("2024-01-03", "train"), + _date_frame("2024-01-04", "validation"), + ] + tests = [ + _date_frame("2024-01-05", "primary_test"), + _date_frame("2024-01-06", "replication_test"), + ] + return development, tests + + +def _tied_millisecond_trade_frame(study_date: str, study_role: str) -> pl.DataFrame: + timestamp_ns = int( + datetime.fromisoformat(f"{study_date}T00:00:00.123+00:00").timestamp() * 1_000_000_000 + ) + continuity = f"tied-millisecond:{study_date}" + trades = pl.DataFrame( + { + "symbol": ["BTCUSDT"] * 6, + "continuity_id": [continuity] * 6, + "trade_id": list(range(100, 106)), + "event_ts_ns": [timestamp_ns] * 6, + "available_ts_ns": [timestamp_ns] * 6, + "price": [100.0, 101.0, 100.0, 102.0, 101.0, 103.0], + "quantity": [1.0] * 6, + "aggressor_side": ["buy", "sell", "buy", "sell", "buy", "sell"], + } + ) + config = FeatureConfig( + trade_windows=(1,), + volatility_window=1, + intensity_window=1, + label_horizon_events=1, + large_trade_quantile=0.9, + ) + return build_trade_only_research_frame(trades, config).with_columns( + pl.lit(study_date).alias("study_date"), + pl.lit(study_role).alias("study_role"), + ) + + +def test_two_phase_lock_never_reads_test_rows_and_builds_exact_date_plan() -> None: + development, tests = _study_frames() + selection = select_multidate_model( + development, + _model_config(), + feature_columns=("signal", "slow_feature"), + declared_test_dates=("2024-01-05", "2024-01-06"), + seed=17, + calibration_bins=5, + ) + + assert selection.train_dates == ("2024-01-03",) + assert selection.validation_date == "2024-01-04" + assert selection.declared_test_dates == ("2024-01-05", "2024-01-06") + assert selection.validation_comparison.height == 4 + assert selection.validation_comparison.get_column("test_rows_accessed").not_().all() + assert selection.validation_comparison.filter(pl.col("selected_on_validation")).height == 1 + payload = selection.lock.payload() + assert payload["test_rows_accessed_during_selection"] is False + assert payload["test_update_policy"] == ( + "fit_once_before_primary_test; no updates through replication" + ) + + # Deliberately changing every test target cannot change a phase-one selection lock: + # the API accepts only development frames and declared date identities. + mutated_tests = [ + _date_frame("2024-01-05", "primary_test", invert_target=True), + _date_frame("2024-01-06", "replication_test", invert_target=True), + ] + repeated = select_multidate_model( + development, + _model_config(), + feature_columns=("signal", "slow_feature"), + declared_test_dates=("2024-01-05", "2024-01-06"), + seed=17, + calibration_bins=5, + ) + assert repeated.lock == selection.lock + assert repeated.selected_model == selection.selected_model + assert ( + not tests[0] + .get_column("future_trade_up") + .equals(mutated_tests[0].get_column("future_trade_up")) + ) + + result = evaluate_locked_multidate_tests(development, tests, selection) + fold = result.plan.folds[0] + assert fold.train_indices.size == 120 + assert fold.validation_indices.size == 120 + assert result.plan.final_train_indices.size == 240 + assert result.plan.test_indices.size == 240 + assert result.predictions.height == 240 + assert result.predictions.get_column("study_date").unique().sort().to_list() == [ + "2024-01-05", + "2024-01-06", + ] + assert result.predictions.get_column("is_oos").all() + assert result.predictions.get_column("model_updated_between_test_dates").not_().all() + assert result.predictions.get_column("selected_fit_cutoff_ts_ns").n_unique() == 1 + assert result.predictions.get_column("prior_fit_cutoff_ts_ns").n_unique() == 1 + assert result.predictions.filter( + pl.col("selected_fit_cutoff_ts_ns") >= pl.col("decision_ts_ns") + ).is_empty() + + paired = result.paired_log_loss + assert paired.per_date.height == 2 + assert paired.per_date.get_column("n_blocks").to_list() == [3, 3] + assert paired.per_date.get_column("date_weight").to_list() == [0.5, 0.5] + assert paired.aggregate.status == "ok" + assert paired.aggregate.n_bootstrap == DATE_BOOTSTRAP_DRAWS + assert len(paired.aggregate.draws) == DATE_BOOTSTRAP_DRAWS + assert paired.replication_status == "replicated" + assert result.feature_stability.height == 4 + assert result.feature_stability.get_column("bin_source").unique().to_list() == [ + "reference_period_only" + ] + assert result.feature_stability.get_column("reference_dates").unique().to_list() == [ + "2024-01-03,2024-01-04" + ] + assert result.feature_stability.get_column("reference_only").all() + + +def test_lock_can_be_persisted_and_tampering_is_rejected() -> None: + development, tests = _study_frames() + selected = select_multidate_model( + development, + _model_config(), + feature_columns=("signal", "slow_feature"), + declared_test_dates=("2024-01-05", "2024-01-06"), + seed=5, + calibration_bins=5, + ) + restored = AnalysisLock.restore(selected.lock.payload_json, selected.lock.sha256) + result = evaluate_locked_multidate_tests(development, tests, restored) + assert result.lock_sha256 == selected.lock.sha256 + mislabeled = [ + tests[0].with_columns(pl.lit("replication_test").alias("study_role")), + tests[1].with_columns(pl.lit("primary_test").alias("study_role")), + ] + with pytest.raises(MultiDateEvaluationError, match="first declared test date"): + evaluate_locked_multidate_tests(development, mislabeled, restored) + with pytest.raises(MultiDateEvaluationError, match="does not match"): + AnalysisLock.restore(selected.lock.payload_json + " ", selected.lock.sha256) + + +def test_final_fitted_state_is_development_only_canonical_and_hash_bound() -> None: + development, _ = _study_frames() + selection = select_multidate_model( + development, + _model_config(), + feature_columns=("signal", "slow_feature"), + declared_test_dates=("2024-01-05", "2024-01-06"), + seed=17, + calibration_bins=5, + ) + + state = selection.fitted_state + restored = FinalFittedState.restore(state.payload_json, state.sha256) + payload = restored.payload() + primary_start_ns = int(datetime(2024, 1, 5, tzinfo=UTC).timestamp() * 1_000_000_000) + assert restored == state + assert json.dumps(payload, sort_keys=True, separators=(",", ":")) == state.payload_json + assert payload["serialization_format"] == "canonical-json-numeric-v1" + assert set(payload["library_versions"]) == {"numpy", "scikit_learn"} + assert payload["development_frame_sha256"] == selection.development_frame_sha256 + assert payload["fit_cutoff_ts_ns"] < primary_start_ns + assert selection.lock.payload()["final_fitted_state_sha256"] == state.sha256 + + changed = json.loads(state.payload_json) + changed["library_versions"]["numpy"] = "tampered" + changed_json = json.dumps(changed, sort_keys=True, separators=(",", ":")) + with pytest.raises(MultiDateEvaluationError, match="does not match"): + FinalFittedState.restore(changed_json, state.sha256) + + changed_lock = json.loads(selection.lock.payload_json) + changed_lock["final_fitted_state"]["library_versions"]["numpy"] = "tampered" + rewritten = AnalysisLock.create(changed_lock) + with pytest.raises(MultiDateEvaluationError, match="hash does not match"): + evaluate_locked_multidate_tests(development, _study_frames()[1], rewritten) + + +def test_locked_test_evaluation_invokes_no_fit_api( + monkeypatch: pytest.MonkeyPatch, +) -> None: + development, tests = _study_frames() + selection = select_multidate_model( + development, + _model_config(), + feature_columns=("signal", "slow_feature"), + declared_test_dates=("2024-01-05", "2024-01-06"), + seed=17, + calibration_bins=5, + ) + restored = AnalysisLock.restore(selection.lock.payload_json, selection.lock.sha256) + + def forbidden_fit(*args: object, **kwargs: object) -> None: + del args, kwargs + raise AssertionError("test evaluation must not fit or recalibrate") + + monkeypatch.setattr(multidate, "make_classifier", forbidden_fit) + monkeypatch.setattr(multidate.SigmoidCalibrator, "fit", forbidden_fit) + + result = evaluate_locked_multidate_tests(development, tests, restored) + assert result.predictions.height == 240 + + +def test_every_candidate_numeric_state_matches_original_sklearn_predictions() -> None: + development, _ = _study_frames() + combined = multidate._combine_date_frames( + development, + allowed_roles=multidate._DEVELOPMENT_ROLES, + label="development fixture", + ) + eligible = combined.filter(multidate._eligible() & pl.col("future_trade_up").is_not_null()) + matrices = multidate._fit_matrices( + eligible, + eligible.head(37), + features=("signal", "slow_feature"), + target="future_trade_up", + calibration_fraction=0.2, + ) + candidates = build_model_candidates(_model_config()) + assert {candidate.family for candidate in candidates} == { + "baseline", + "logistic", + "logistic_l2", + "shallow_tree", + } + for candidate in candidates: + outcome = multidate._fit_candidate( + candidate, + matrices, + seed=31, + state_role="selected", + ) + assert outcome.fitted_state is not None + raw, calibrated = multidate._predict_serialized_model( + outcome.fitted_state, + matrices.x_evaluate, + ) + assert raw == pytest.approx(outcome.raw_probability, abs=1e-12) + assert calibrated == pytest.approx(outcome.probability, abs=1e-12) + + +def test_single_class_fallback_state_preserves_one_class_prior() -> None: + development, _ = _study_frames() + development = [ + frame.with_columns( + pl.when(pl.col("right_censored")) + .then(None) + .otherwise(1) + .cast(pl.Int8) + .alias("future_trade_up") + ) + for frame in development + ] + combined = multidate._combine_date_frames( + development, + allowed_roles=multidate._DEVELOPMENT_ROLES, + label="single-class development fixture", + ) + eligible = combined.filter(multidate._eligible() & pl.col("future_trade_up").is_not_null()) + matrices = multidate._fit_matrices( + eligible, + eligible.head(11), + features=("signal", "slow_feature"), + target="future_trade_up", + calibration_fraction=0.2, + ) + outcome = multidate._fit_candidate( + ModelCandidate("logistic_l2_fixture", "logistic_l2", c=1.0), + matrices, + seed=9, + state_role="selected", + ) + assert outcome.fitted_state is not None + classifier = outcome.fitted_state["classifier"] + assert classifier == { + "kind": "prior", + "classes": [1], + "class_probabilities": [1.0], + } + raw, calibrated = multidate._predict_serialized_model( + outcome.fitted_state, + matrices.x_evaluate, + ) + assert raw == pytest.approx(np.ones(matrices.x_evaluate.shape[0])) + assert calibrated == pytest.approx(np.full(matrices.x_evaluate.shape[0], 1.0 - 1e-12)) + + +@pytest.mark.parametrize("kind", ["label", "continuity"]) +def test_date_local_label_and_lookback_lineage_fail_closed(kind: str) -> None: + development, _ = _study_frames() + if kind == "label": + next_date_ns = int(datetime(2024, 1, 4, tzinfo=UTC).timestamp() * 1_000_000_000) + development[0] = development[0].with_columns( + pl.when(pl.col("decision_sequence") == 0) + .then(next_date_ns) + .otherwise(pl.col("label_information_end_ts_ns")) + .alias("label_information_end_ts_ns") + ) + message = "label endpoints" + else: + reused = "BTCUSDT:2024-01-03" + development[1] = development[1].with_columns( + pl.lit(reused).alias("continuity_id"), + pl.lit(reused).alias("feature_continuity_id"), + pl.when(pl.col("right_censored")) + .then(None) + .otherwise(pl.lit(reused)) + .alias("label_continuity_id"), + ) + message = "cannot span study dates" + with pytest.raises(MultiDateEvaluationError, match=message): + select_multidate_model( + development, + _model_config(), + feature_columns=("signal", "slow_feature"), + declared_test_dates=("2024-01-05", "2024-01-06"), + seed=17, + calibration_bins=5, + ) + + +def _tied_millisecond_study() -> pl.DataFrame: + return pl.concat( + [ + _tied_millisecond_trade_frame("2024-01-03", "train"), + _tied_millisecond_trade_frame("2024-01-04", "validation"), + _tied_millisecond_trade_frame("2024-01-05", "primary_test"), + _tied_millisecond_trade_frame("2024-01-06", "replication_test"), + ], + how="vertical", + ) + + +def test_real_tied_millisecond_trade_labels_use_trade_id_boundary() -> None: + study = _tied_millisecond_study() + tied = study.filter( + (pl.col("study_date") == "2024-01-05") & (pl.col("decision_trade_id") == 100) + ).row(0, named=True) + + assert tied["label_start_ts_ns"] == tied["decision_ts_ns"] + assert tied["label_start_trade_id"] == tied["decision_trade_id"] + assert tied["label_information_end_ts_ns"] == tied["decision_ts_ns"] + assert tied["label_information_end_trade_id"] > tied["decision_trade_id"] + plan = build_multidate_walk_forward_plan(study) + assert plan.folds[0].train_indices.size == 5 + assert plan.folds[0].validation_indices.size == 5 + assert plan.final_train_indices.size == 10 + assert plan.test_indices.size == 10 + + +@pytest.mark.parametrize("invalid_end_trade_id", [100, 99]) +def test_tied_millisecond_same_or_lower_label_end_trade_id_fails( + invalid_end_trade_id: int, +) -> None: + invalid = _tied_millisecond_study().with_columns( + pl.when((pl.col("study_date") == "2024-01-05") & (pl.col("decision_trade_id") == 100)) + .then(invalid_end_trade_id) + .otherwise(pl.col("label_information_end_trade_id")) + .alias("label_information_end_trade_id") + ) + with pytest.raises(MultiDateEvaluationError, match="strictly later"): + build_multidate_walk_forward_plan(invalid) + + +def test_tied_millisecond_cross_date_endpoint_and_changed_start_fail() -> None: + next_date_ns = int( + datetime.fromisoformat("2024-01-06T00:00:00+00:00").timestamp() * 1_000_000_000 + ) + cross_date = _tied_millisecond_study().with_columns( + pl.when((pl.col("study_date") == "2024-01-05") & (pl.col("decision_trade_id") == 100)) + .then(next_date_ns) + .otherwise(pl.col("label_information_end_ts_ns")) + .alias("label_information_end_ts_ns") + ) + with pytest.raises(MultiDateEvaluationError, match="label endpoints"): + build_multidate_walk_forward_plan(cross_date) + + changed_start = _tied_millisecond_study().with_columns( + pl.when((pl.col("study_date") == "2024-01-05") & (pl.col("decision_trade_id") == 100)) + .then(pl.col("decision_trade_id") + 1) + .otherwise(pl.col("label_start_trade_id")) + .alias("label_start_trade_id") + ) + with pytest.raises(MultiDateEvaluationError, match="label start boundary"): + build_multidate_walk_forward_plan(changed_start) + + +def test_later_clock_boundary_may_reuse_the_last_observed_sequence() -> None: + """Exact clock labels can carry a state forward to t+h without a new update.""" + + development, tests = _study_frames() + frames = [*development, *tests] + carried = [ + frame.with_columns( + pl.when(pl.col("right_censored")) + .then(None) + .otherwise(pl.col("decision_trade_id")) + .cast(pl.Int64) + .alias("label_information_end_trade_id") + ) + for frame in frames + ] + + plan = build_multidate_walk_forward_plan(pl.concat(carried, how="vertical")) + + assert plan.final_train_indices.size == 240 + assert plan.test_indices.size == 240 + + +def test_custom_bootstrap_contract_is_persisted_and_used() -> None: + development, tests = _study_frames() + selection = select_multidate_model( + development, + _model_config(), + feature_columns=("signal", "slow_feature"), + declared_test_dates=("2024-01-05", "2024-01-06"), + seed=17, + calibration_bins=5, + bootstrap_draws=37, + block_width_events=7, + ) + + bootstrap = selection.lock.payload()["bootstrap"] + assert bootstrap == { + "block_width_events": 7, + "date_weighting": "equal", + "draws": 37, + "metric": "selected_minus_historical_prior_log_loss", + } + result = evaluate_locked_multidate_tests(development, tests, selection) + assert result.paired_log_loss.aggregate.n_bootstrap == 37 + assert result.paired_log_loss.per_date.get_column("n_blocks").to_list() == [18, 18] + assert result.predictions.get_column("date_block_width_events").unique().to_list() == [7] + + +def _paired_prediction_fixture() -> pl.DataFrame: + rows: list[dict[str, object]] = [] + for date_index, (study_date, count) in enumerate((("2024-01-05", 85), ("2024-01-06", 125))): + start_ns = int( + datetime.fromisoformat(f"{study_date}T00:00:00+00:00").timestamp() * 1_000_000_000 + ) + for sequence in range(count): + y_true = sequence % 2 + selected = 0.75 if y_true else 0.25 + if date_index: + selected = 0.65 if y_true else 0.35 + rows.append( + { + "row_id": len(rows), + "study_date": study_date, + "study_role": "primary_test" if date_index == 0 else "replication_test", + "test_phase": "primary" if date_index == 0 else "replication", + "decision_ts_ns": start_ns + sequence, + "decision_sequence": sequence, + "y_true": y_true, + "selected_probability": selected, + "prior_probability": 0.5, + } + ) + return pl.DataFrame(rows) + + +def _naive_equal_date_draws(predictions: pl.DataFrame, *, seed: int, draws: int) -> np.ndarray: + random = np.random.default_rng(seed) + per_date: list[np.ndarray] = [] + for study_date in sorted(predictions.get_column("study_date").unique().to_list()): + current = predictions.filter(pl.col("study_date") == study_date).sort( + "decision_ts_ns", "decision_sequence", "row_id" + ) + y_true = current.get_column("y_true").to_numpy().astype(np.int64) + selected = current.get_column("selected_probability").to_numpy() + prior = current.get_column("prior_probability").to_numpy() + selected_loss = -(y_true * np.log(selected) + (1 - y_true) * np.log(1 - selected)) + prior_loss = -(y_true * np.log(prior) + (1 - y_true) * np.log(1 - prior)) + differences = selected_loss - prior_loss + block_index = np.arange(current.height) // DATE_BOOTSTRAP_BLOCK_EVENTS + block_count = int(block_index.max()) + 1 + sums = np.asarray([differences[block_index == index].sum() for index in range(block_count)]) + counts = np.asarray( + [(block_index == index).sum() for index in range(block_count)], dtype=np.int64 + ) + date_draws = np.empty(draws) + for draw in range(draws): + sampled = random.integers(0, block_count, size=block_count) + date_draws[draw] = sums[sampled].sum() / counts[sampled].sum() + per_date.append(date_draws) + return np.mean(np.vstack(per_date), axis=0) + + +def test_block_sufficient_statistic_bootstrap_matches_naive_rows_exactly() -> None: + predictions = _paired_prediction_fixture() + seed = 91 + result = paired_date_log_loss( + predictions, + seed=seed, + draw_chunk_size=7, + ) + naive = _naive_equal_date_draws( + predictions, + seed=seed, + draws=DATE_BOOTSTRAP_DRAWS, + ) + + assert result.aggregate.status == "ok" + assert result.aggregate.n_bootstrap == 2_000 + assert result.aggregate.n_blocks == 7 + assert np.asarray(result.aggregate.draws) == pytest.approx(naive, abs=1e-15) + assert result.aggregate.point_estimate == pytest.approx( + result.per_date.get_column("point_delta").mean() + ) + pooled = ( + result.per_date.get_column("point_delta") * result.per_date.get_column("n_obs") + ).sum() / result.per_date.get_column("n_obs").sum() + assert result.aggregate.point_estimate != pytest.approx(pooled) + assert result.predictions.get_column("date_block_width_events").unique().to_list() == [40] diff --git a/Microstructure/tests/test_pipeline.py b/Microstructure/tests/test_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..49bc57c5772f5c93fc6457b48feaa950587ad9da --- /dev/null +++ b/Microstructure/tests/test_pipeline.py @@ -0,0 +1,329 @@ +from __future__ import annotations + +import json +import shutil +from pathlib import Path + +import polars as pl +import pytest + +from microstructure.config import ProjectConfig, load_config +from microstructure.pipeline import PipelineError, reproduce +from microstructure.reporting import ChecksumMismatchError, load_run_bundle + + +def _config(project_root: Path) -> ProjectConfig: + config_path = project_root / "configs" / "pipeline-smoke.toml" + config_path.parent.mkdir(parents=True, exist_ok=True) + config_path.write_text( + """ +[run] +name = "pipeline-smoke" +evidence_tier = "SYNTHETIC_SMOKE" +seed = 20260807 + +[data] +mode = "synthetic" +source = "synthetic_pipeline_fixture_v1" +symbols = ["BTCUSDT", "ETHUSDT"] +start = "2024-01-02T00:00:00Z" +events_per_symbol = 72 +partition_root = "data/normalized" +schema_version = "1.0.0" + +[quality] +max_spread_bps = 100.0 +max_silence_ms = 5000 +fail_on_error = true + +[features] +trade_windows = [2, 4] +volatility_window = 4 +intensity_window = 3 +label_horizon_events = 2 +large_trade_quantile = 0.95 + +[evaluation] +min_train_events = 24 +validation_events = 12 +test_events = 12 +step_events = 12 +embargo_events = 2 +bootstrap_samples = 8 +calibration_bins = 5 + +[models] +selection_metric = "log_loss" +logistic_c_values = [1.0] +tree_max_depth_values = [2] +tree_min_samples_leaf = 2 + +[execution] +decision_latency_events = 1 +order_latency_events = 1 +maker_fee_bps = 1.0 +taker_fee_bps = 4.0 +half_spread_bps = 1.0 +slippage_bps_per_unit = 0.20 +signal_threshold = 0.52 +max_position_units = 0.01 +order_size_units = 0.002 +limit_fill_base_probability = 0.55 +queue_ahead_units = 0.001 +limit_max_age_events = 5 +cancel_latency_events = 1 +liquidate_at_end = true +capacity_multipliers = [0.5, 1.0] +""".strip() + + "\n", + encoding="utf-8", + ) + return load_config(config_path) + + +@pytest.fixture(scope="module") +def completed_bundle( + tmp_path_factory: pytest.TempPathFactory, +) -> tuple[ProjectConfig, Path]: + project_root = tmp_path_factory.mktemp("pipeline-project") + config = _config(project_root) + run_dir = project_root / "artifacts" / "runs" / "pipeline-smoke" + return config, reproduce(config, run_dir) + + +def _read_json(path: Path) -> object: + return json.loads(path.read_text(encoding="utf-8")) + + +def test_reproduce_builds_verified_honestly_labeled_vertical_slice( + completed_bundle: tuple[ProjectConfig, Path], +) -> None: + config, run_dir = completed_bundle + bundle = load_run_bundle(run_dir) + + assert bundle.evidence_tier == "SYNTHETIC_SMOKE" + assert bundle.manifest["data"]["mode"] == "synthetic" + assert bundle.provenance["requested_evidence_tier"] == "SYNTHETIC_SMOKE" + assert bundle.provenance["effective_evidence_tier"] == "SYNTHETIC_SMOKE" + assert bundle.manifest["run_key"] == bundle.provenance["run_key"] + assert len(str(bundle.manifest["run_key"])) == 64 + assert len(bundle.provenance["input_manifest_sha256"]) == 2 + assert bundle.observed_start_utc < bundle.observed_end_utc + assert bundle.quality["summary"]["errors"] == 0 + assert bundle.manifest["research"]["feature_ready_rows"] > 0 + + normalized_parts = sorted((run_dir / "data" / "normalized").rglob("*.parquet")) + normalized_manifests = sorted((run_dir / "data" / "normalized").rglob("*.json")) + assert normalized_parts + assert normalized_manifests + assert (run_dir / "research" / "research_frame.parquet").is_file() + evaluation = pl.read_parquet(run_dir / "research" / "evaluation_frame.parquet") + assert evaluation.get_column("feature_ready").all() + assert evaluation.height == bundle.manifest["research"]["evaluation_rows"] + folds = _read_json(run_dir / "research" / "folds.json") + assert isinstance(folds, dict) + assert folds["index_basis"].startswith("zero-based row positions") + recorded_indices = [ + int(index) + for fold in folds["folds"] + for key in ("train_indices", "validation_indices") + for index in fold[key] + ] + recorded_indices.extend(int(index) for index in folds["final_train_indices"]) + recorded_indices.extend(int(index) for index in folds["test_indices"]) + assert recorded_indices + assert min(recorded_indices) >= 0 + assert max(recorded_indices) < evaluation.height + assert (run_dir / "research" / "folds.json").is_file() + analysis_manifest = _read_json(run_dir / "analysis" / "manifest.json") + assert isinstance(analysis_manifest, dict) + assert analysis_manifest["descriptive_only"] is True + assert analysis_manifest["economic_claim_authorized"] is False + assert analysis_manifest["threshold_source"] == "final_training_period_only" + expected_analysis = { + "intraday_liquidity", + "ofi_future_return", + "signal_decay_curve", + "signal_half_life", + "event_time_impact_labels", + "large_trade_price_impact", + "liquidity_recovery", + "market_regimes", + "regime_outcomes", + "regime_model_performance", + "cross_instrument_stability", + "feature_stability", + } + assert set(analysis_manifest["artifacts"]) == expected_analysis + assert all((run_dir / "analysis" / f"{name}.parquet").is_file() for name in expected_analysis) + regime_performance = pl.read_parquet(run_dir / "analysis/regime_model_performance.parquet") + assert regime_performance.get_column("split").unique().to_list() == ["test"] + assert set(regime_performance.get_column("threshold_source")) == { + "caller_supplied_final_training_period" + } + + families = {str(row["family"]) for row in bundle.predictive_metrics} + assert families == {"baseline", "logistic", "logistic_l2", "shallow_tree"} + assert {str(row["split"]) for row in bundle.predictive_metrics} == { + "validation", + "test", + } + test_metric_rows = [row for row in bundle.predictive_metrics if row["split"] == "test"] + assert {int(row["bootstrap_block_width_events"]) for row in test_metric_rows} == {4} + assert {str(row["bootstrap_block_policy"]) for row in test_metric_rows} == { + "pooled_dense_decision_time_clusters_2x_label_horizon" + } + all_predictions = pl.read_parquet(run_dir / "models" / "predictions.parquet") + assert ( + all_predictions.group_by("decision_ts_ns") + .agg(pl.col("bootstrap_block").n_unique().alias("block_count")) + .filter(pl.col("block_count") != 1) + .is_empty() + ) + selected = pl.read_parquet(run_dir / "models" / "selected_test_predictions.parquet") + assert selected.get_column("model").n_unique() == 1 + assert selected.get_column("split").unique().to_list() == ["test"] + assert selected.get_column("is_oos").all() + assert selected.get_column("continuity_id").null_count() == 0 + + execution_events = pl.read_parquet(run_dir / "execution" / "events.parquet") + assert execution_events.filter(pl.col("event_ts_ns") != pl.col("decision_ts_ns")).is_empty() + assert {str(row["order_type"]) for row in bundle.execution_metrics} == { + "market", + "limit", + } + sensitivity = _read_json(run_dir / "metrics" / "execution_sensitivity.json") + assert isinstance(sensitivity, list) + assert {str(row["order_type"]) for row in sensitivity} == {"market", "limit"} + assert {float(row["size_multiplier"]) for row in sensitivity} == {0.5, 1.0} + + technical = (run_dir / "reports" / "technical_report.md").read_text(encoding="utf-8") + memo = (run_dir / "reports" / "executive_memo.md").read_text(encoding="utf-8") + table = (run_dir / "reports" / "model_comparison.md").read_text(encoding="utf-8") + for rendered in (technical, memo, table): + assert "SYNTHETIC SMOKE" in rendered + assert "NOT EMPIRICAL OR INVESTMENT EVIDENCE" in technical + assert "authorize no capital deployment" in memo + assert "No capital recommendation is made" in technical + + checksums_before = (run_dir / "checksums.sha256").read_bytes() + success_mtime = (run_dir / "_SUCCESS").stat().st_mtime_ns + assert reproduce(config, run_dir) == run_dir + assert (run_dir / "checksums.sha256").read_bytes() == checksums_before + assert (run_dir / "_SUCCESS").stat().st_mtime_ns == success_mtime + assert not list(run_dir.parent.glob(".pipeline-smoke.staging-*")) + + +def test_checksum_corruption_is_rejected_without_overwrite( + completed_bundle: tuple[ProjectConfig, Path], tmp_path: Path +) -> None: + config, source = completed_bundle + corrupted = tmp_path / "corrupted-run" + shutil.copytree(source, corrupted) + metrics_path = corrupted / "metrics" / "execution_metrics.json" + original = metrics_path.read_bytes() + metrics_path.write_bytes(original + b"\n") + + with pytest.raises(ChecksumMismatchError, match="checksum mismatch"): + reproduce(config, corrupted) + assert metrics_path.read_bytes() == original + b"\n" + + +def test_independent_runs_have_deterministic_semantic_metrics( + completed_bundle: tuple[ProjectConfig, Path], +) -> None: + config, first = completed_bundle + second = reproduce(config, first.parent / "pipeline-smoke-repeat") + + assert ( + _read_json(first / "run_manifest.json")["run_key"] + == _read_json(second / "run_manifest.json")["run_key"] + ) + assert ( + _read_json(first / "provenance.json")["run_key_inputs"] + == _read_json(second / "provenance.json")["run_key_inputs"] + ) + + for relative in ( + "metrics/predictive_metrics.json", + "metrics/execution_metrics.json", + "metrics/execution_sensitivity.json", + ): + assert _read_json(first / relative) == _read_json(second / relative) + + +def test_existing_incomplete_target_is_not_repaired_or_overwritten( + completed_bundle: tuple[ProjectConfig, Path], tmp_path: Path +) -> None: + config, _ = completed_bundle + target = tmp_path / "incomplete" + target.mkdir() + marker = target / "producer-failed.txt" + marker.write_text("preserve me\n", encoding="utf-8") + + with pytest.raises(PipelineError, match="not a verified completed bundle"): + reproduce(config, target) + assert marker.read_text(encoding="utf-8") == "preserve me\n" + + +def test_completed_target_from_different_config_is_not_reused( + completed_bundle: tuple[ProjectConfig, Path], tmp_path: Path +) -> None: + config, target = completed_bundle + alternate_path = tmp_path / "alternate.toml" + alternate_path.write_text( + config.path.read_text(encoding="utf-8").replace("seed = 20260807", "seed = 20260808"), + encoding="utf-8", + ) + alternate = load_config(alternate_path) + + with pytest.raises(PipelineError, match="different configuration"): + reproduce(alternate, target) + + +def test_completed_target_from_different_source_tree_is_not_reused( + completed_bundle: tuple[ProjectConfig, Path], + monkeypatch: pytest.MonkeyPatch, +) -> None: + config, target = completed_bundle + monkeypatch.setattr( + "microstructure.pipeline.git_source_tree_sha256", + lambda project_root: "f" * 64, + ) + + with pytest.raises(PipelineError, match="different Git/source-tree state"): + reproduce(config, target) + + +def test_synthetic_reproduction_rejects_public_manifest_anchor( + completed_bundle: tuple[ProjectConfig, Path], tmp_path: Path +) -> None: + config, _ = completed_bundle + + with pytest.raises(PipelineError, match="does not accept a public input manifest"): + reproduce( + config, + tmp_path / "wrongly-anchored", + ingestion_manifest_path=tmp_path / "ingestion.json", + ingestion_manifest_sha256="a" * 64, + ) + + +def test_public_reproduction_requires_and_hashes_explicit_manifest_anchor( + tmp_path: Path, +) -> None: + config = load_config(Path(__file__).parents[1] / "configs" / "public_sample.toml") + target = tmp_path / "public-run" + + with pytest.raises(PipelineError, match="requires an explicit ingestion manifest"): + reproduce(config, target) + + manifest = tmp_path / "ingestion.json" + manifest.write_text("{}\n", encoding="utf-8") + with pytest.raises(PipelineError, match="bytes do not match"): + reproduce( + config, + target, + ingestion_manifest_path=manifest, + ingestion_manifest_sha256="a" * 64, + ) diff --git a/Microstructure/tests/test_provenance.py b/Microstructure/tests/test_provenance.py new file mode 100644 index 0000000000000000000000000000000000000000..60376d8f86dd8a093ac78e6a9c3717191776652e --- /dev/null +++ b/Microstructure/tests/test_provenance.py @@ -0,0 +1,116 @@ +from __future__ import annotations + +import subprocess +from pathlib import Path + +import pytest + +import microstructure +import microstructure.provenance as provenance_module +from microstructure.provenance import ( + ImportOriginError, + assert_project_module_origins, + git_source_tree_sha256, + git_state, + read_json, + sha256_file, + strict_git_state, + write_json, +) + +PROJECT_ROOT = Path(__file__).parents[1] + + +def test_sha256_and_atomic_json_round_trip(tmp_path: Path) -> None: + target = tmp_path / "artifact.json" + write_json(target, {"b": 2, "a": [1, 3]}) + + assert read_json(target) == {"a": [1, 3], "b": 2} + assert sha256_file(target) == sha256_file(target) + assert not list(tmp_path.glob("*.tmp")) + + +def test_git_state_handles_unborn_clean_and_dirty_repositories(tmp_path: Path) -> None: + repository = tmp_path / "repository" + repository.mkdir() + subprocess.run(["git", "init", "--quiet"], cwd=repository, check=True) + tracked = repository / "tracked.txt" + tracked.write_text("first\n", encoding="utf-8") + + unborn = git_state(repository) + unborn_source = git_source_tree_sha256(repository) + assert unborn.commit == "UNBORN" + assert unborn.dirty is True + + subprocess.run(["git", "add", "tracked.txt"], cwd=repository, check=True) + subprocess.run( + [ + "git", + "-c", + "user.name=Provenance Test", + "-c", + "user.email=provenance@example.invalid", + "commit", + "--quiet", + "-m", + "fixture", + ], + cwd=repository, + check=True, + ) + clean = git_state(repository) + clean_source = git_source_tree_sha256(repository) + assert len(clean.commit) == 40 + assert clean.dirty is False + assert clean_source == unborn_source + + tracked.write_text("modified\n", encoding="utf-8") + dirty = git_state(repository) + dirty_source = git_source_tree_sha256(repository) + assert dirty.commit == clean.commit + assert dirty.dirty is True + assert dirty_source != clean_source + + (repository / "untracked.txt").write_text("new source\n", encoding="utf-8") + assert git_source_tree_sha256(repository) != dirty_source + + +def test_git_state_fails_closed_when_status_cannot_run( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + calls = 0 + + def failed_status(*args: object, **kwargs: object) -> subprocess.CompletedProcess[str]: + nonlocal calls + calls += 1 + if calls == 1: + return subprocess.CompletedProcess(args=[], returncode=0, stdout="a" * 40 + "\n") + return subprocess.CompletedProcess(args=[], returncode=128, stdout="", stderr="fatal\n") + + monkeypatch.setattr(subprocess, "run", failed_status) + + with pytest.raises(RuntimeError, match="strict Git working-tree identity"): + strict_git_state(tmp_path) + + +def test_loaded_module_origin_rejects_foreign_file_and_mixed_namespace( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + assert_project_module_origins(PROJECT_ROOT, provenance_module) + + foreign = tmp_path / "checkout" / "src" / "microstructure" / "provenance.py" + foreign.parent.mkdir(parents=True) + foreign.write_text("# foreign checkout\n", encoding="utf-8") + with monkeypatch.context() as scoped: + scoped.setattr(provenance_module, "__file__", str(foreign)) + with pytest.raises(ImportOriginError, match="foreign source root"): + assert_project_module_origins(PROJECT_ROOT, provenance_module) + + with monkeypatch.context() as scoped: + scoped.setattr( + microstructure, + "__path__", + [str(PROJECT_ROOT / "src" / "microstructure"), str(foreign.parent)], + ) + with pytest.raises(ImportOriginError, match="mixed namespace"): + assert_project_module_origins(PROJECT_ROOT, provenance_module) diff --git a/Microstructure/tests/test_public_data.py b/Microstructure/tests/test_public_data.py new file mode 100644 index 0000000000000000000000000000000000000000..5746e48a9eb38d6aa728a7ecafe75f1a09f696b5 --- /dev/null +++ b/Microstructure/tests/test_public_data.py @@ -0,0 +1,1181 @@ +from __future__ import annotations + +from dataclasses import dataclass, replace +from datetime import UTC, datetime +from decimal import Decimal +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pyarrow.parquet as pq +import pytest + +import microstructure.public_data as public_data +from microstructure.config import ProjectConfig, load_config +from microstructure.data.schemas import table_from_records +from microstructure.data.storage import ( + DatasetWriteResult, + write_partitioned_parquet, + write_source_manifest, +) +from microstructure.data.synthetic import generate_synthetic_market +from microstructure.provenance import read_json, sha256_file, write_json +from microstructure.public_data import ( + PublicDataError, + read_public_trades, + verify_public_trade_dataset, +) + +START_NS = 1_704_153_600_000_000_000 +END_NS = START_NS + 1_000_000_000 +PROJECT_ROOT = Path(__file__).parents[1] + + +@dataclass(frozen=True, slots=True) +class ManifestedFixture: + config: ProjectConfig + ingestion_path: Path + ingestion_sha256: str + dataset: DatasetWriteResult + table: pa.Table + aggregate_paths: dict[str, Path] + exchange_info_paths: dict[str, Path] + raw_manifest_paths: dict[Path, Path] + + +def _config(root: Path, evidence_tier: str) -> ProjectConfig: + base = load_config(PROJECT_ROOT / "configs" / "public_sample.toml") + return replace( + base, + run=replace(base.run, evidence_tier=evidence_tier), + data=replace( + base.data, + start=datetime.fromtimestamp(START_NS / 1_000_000_000, tz=UTC), + end=datetime.fromtimestamp(END_NS / 1_000_000_000, tz=UTC), + max_events_per_symbol=3, + partition_root=root / "normalized", + raw_root=root / "raw", + ), + ) + + +def _as_public_trades( + table: pa.Table, + source_artifact_ids: dict[str, str], + *, + invalid_quality: bool, + cross_symbol_lineage: bool, + normalized_scale_mismatch: bool, +) -> pa.Table: + records = table.to_pylist() + for record in records: + symbol = str(record["symbol"]) + lineage_symbol = "ETHUSDT" if cross_symbol_lineage and symbol == "BTCUSDT" else symbol + price = float(Decimal(int(record["price_ticks"])) * Decimal("0.01")) + quantity = float(Decimal(int(record["quantity_lots"])) * Decimal("0.001")) + event_ts_ns = int(record["event_ts_ns"]) // 1_000_000 * 1_000_000 + record.update( + { + "venue": "binance_spot", + "event_ts_ns": event_ts_ns, + "received_ts_ns": None, + "available_ts_ns": event_ts_ns, + "availability_basis": "exchange_event_time_proxy", + "capture_seq": None, + "continuity_id": None, + "source_artifact_id": source_artifact_ids[lineage_symbol], + "price": price, + "quantity": quantity, + "quote_quantity": price * quantity, + } + ) + if invalid_quality: + records[1] = dict(records[0]) + if normalized_scale_mismatch: + records[1]["tick_size"] = 0.02 + return table_from_records("trades", records) + + +def _fixture( + root: Path, + *, + stored_schema: str = "trades", + requested_tier: str = "PUBLIC_SAMPLE_PARTIAL", + effective_tier: str = "PUBLIC_SAMPLE_PARTIAL", + complete: bool = False, + invalid_quality: bool = False, + cross_symbol_lineage: bool = False, + raw_trade_id_offset: bool = False, + raw_price_mismatch: bool = False, + normalized_scale_mismatch: bool = False, + physical_clock_reversal: bool = False, + raw_terminal_sentinel: bool = False, + drop_last_normalized_per_symbol: bool = False, +) -> ManifestedFixture: + config = _config(root, requested_tier) + generated = generate_synthetic_market( + symbols=("BTCUSDT", "ETHUSDT"), + events_per_symbol=3, + start_ts_ns=START_NS, + seed=17, + ) + raw_entries: list[dict[str, object]] = [] + aggregate_paths: dict[str, Path] = {} + exchange_info_paths: dict[str, Path] = {} + raw_manifest_paths: dict[Path, Path] = {} + aggregate_digests: dict[str, str] = {} + generated_records = generated.trades.to_pylist() + for symbol in config.data.symbols: + exchange_info_path = ( + root / "raw" / "binance_spot" / "exchange_info" / symbol / "fixture.json" + ) + write_json( + exchange_info_path, + { + "symbols": [ + { + "symbol": symbol, + "status": "TRADING", + "baseAsset": symbol.removesuffix("USDT"), + "quoteAsset": "USDT", + "filters": [ + {"filterType": "PRICE_FILTER", "tickSize": "0.01000000"}, + {"filterType": "LOT_SIZE", "stepSize": "0.00100000"}, + ], + } + ] + }, + ) + exchange_manifest_path, exchange_manifest_sha = write_source_manifest( + exchange_info_path, + source="binance_spot_public_api", + source_uri=f"{config.data.base_url}/api/v3/exchangeInfo?symbol={symbol}", + downloaded_at_utc="2026-08-07T12:00:00Z", + requested_start_ns=None, + requested_end_ns=None, + ) + exchange_info_paths[symbol] = exchange_info_path + raw_manifest_paths[exchange_info_path] = exchange_manifest_path + raw_entries.append( + { + "path": str(exchange_info_path.relative_to(root)), + "sha256": sha256_file(exchange_info_path), + "manifest_path": str(exchange_manifest_path.relative_to(root)), + "manifest_sha256": exchange_manifest_sha, + } + ) + + symbol_records = [record for record in generated_records if str(record["symbol"]) == symbol] + aggregate_path = root / "raw" / "binance_spot" / "agg_trades" / symbol / "fixture.json" + raw_payload = [ + { + "a": int(record["trade_id"]) + + (1_000_000 if raw_trade_id_offset and symbol == "BTCUSDT" else 0), + "f": record["first_trade_id"], + "l": record["last_trade_id"], + "p": str( + Decimal(int(record["price_ticks"])) * Decimal("0.01") + + ( + Decimal("0.01") + if raw_price_mismatch + and symbol == "BTCUSDT" + and record["trade_id"] == symbol_records[1]["trade_id"] + else Decimal(0) + ) + ), + "q": str(Decimal(int(record["quantity_lots"])) * Decimal("0.001")), + "T": int(record["event_ts_ns"]) // 1_000_000, + "m": record["buyer_is_maker"], + } + for record in symbol_records + ] + if raw_terminal_sentinel and symbol == "BTCUSDT": + final = dict(raw_payload[-1]) + final["a"] = int(final["a"]) + 1 + final["f"] = int(final["l"]) + 1 + final["l"] = int(final["l"]) + 1 + final["T"] = END_NS // 1_000_000 + raw_payload.append(final) + write_json(aggregate_path, raw_payload) + aggregate_manifest_path, aggregate_manifest_sha = write_source_manifest( + aggregate_path, + source="binance_spot_public_api", + source_uri=( + f"{config.data.base_url}/api/v3/aggTrades?symbol={symbol}" + f"&startTime={START_NS // 1_000_000}" + f"&endTime={(END_NS - 1) // 1_000_000}" + f"&limit={config.data.request_limit}" + ), + downloaded_at_utc="2026-08-07T12:00:00Z", + requested_start_ns=START_NS, + requested_end_ns=END_NS, + ) + aggregate_paths[symbol] = aggregate_path + raw_manifest_paths[aggregate_path] = aggregate_manifest_path + aggregate_digest = sha256_file(aggregate_path) + aggregate_digests[symbol] = aggregate_digest + raw_entries.append( + { + "path": str(aggregate_path.relative_to(root)), + "sha256": aggregate_digest, + "manifest_path": str(aggregate_manifest_path.relative_to(root)), + "manifest_sha256": aggregate_manifest_sha, + } + ) + + table = ( + _as_public_trades( + generated.trades, + aggregate_digests, + invalid_quality=invalid_quality, + cross_symbol_lineage=cross_symbol_lineage, + normalized_scale_mismatch=normalized_scale_mismatch, + ) + if stored_schema == "trades" + else generated.book_observations + ) + if physical_clock_reversal: + records = table.to_pylist() + records[1], records[2] = records[2], records[1] + table = table_from_records("trades", records) + if drop_last_normalized_per_symbol: + records = table.to_pylist() + retained: list[dict[str, Any]] = [] + for symbol in config.data.symbols: + symbol_records = [record for record in records if str(record["symbol"]) == symbol] + retained.extend(symbol_records[:-1]) + table = table_from_records("trades", retained) + dataset = write_partitioned_parquet( + table.to_batches(max_chunksize=3), + root=root / "normalized", + dataset="trades", + schema_name=stored_schema, + source="binance_spot_rest", + source_uri="https://data-api.binance.vision/api/v3/aggTrades", + downloaded_at_utc="2026-08-07T12:00:00Z", + requested_start_ns=START_NS, + requested_end_ns=END_NS, + max_rows_per_file=2, + ) + counts: dict[str, int] = {} + for symbol in table.column("symbol").to_pylist(): + counts[str(symbol)] = counts.get(str(symbol), 0) + 1 + payload: dict[str, Any] = { + "manifest_version": "1.0.0", + "artifact_kind": "ingestion_run", + "created_at_utc": "2026-08-07T12:00:00Z", + "mode": "binance_rest", + "evidence_tier": effective_tier, + "requested_evidence_tier": requested_tier, + "source": config.data.source, + "schema_version": "1.0.0", + "requested_range_ns": {"start": START_NS, "end_exclusive": END_NS}, + "row_cap_per_symbol": config.data.max_events_per_symbol, + "all_requested_ranges_complete": complete, + "symbols": [ + { + "symbol": symbol, + "rows": rows, + "complete_range": complete, + "tick_size": "0.01", + "lot_size": "0.001", + **( + { + "raw_page_count": 1, + "stop_reason": "short_page", + "last_raw_page_sha256": aggregate_digests[symbol], + "stream_summary": { + "requested_start_ns": START_NS, + "requested_end_ns": END_NS, + "rows_yielded": rows, + "raw_page_count": 1, + "stop_reason": "short_page", + "complete_range": complete, + "last_raw_page": { + "path": str(aggregate_paths[symbol].relative_to(root)), + "manifest_path": str( + raw_manifest_paths[aggregate_paths[symbol]].relative_to(root) + ), + "sha256": aggregate_digests[symbol], + "request_uri": read_json( + raw_manifest_paths[aggregate_paths[symbol]] + )["source_uri"], + "row_count": 3, + }, + }, + } + if drop_last_normalized_per_symbol + else {} + ), + } + for symbol, rows in sorted(counts.items()) + ], + "normalized_datasets": [ + { + "schema_name": "trades", + "rows": table.num_rows, + "manifest_path": str(dataset.manifest_path.relative_to(root)), + "manifest_sha256": dataset.manifest_sha256, + } + ], + "raw_artifacts": raw_entries, + } + ingestion_path = root / "_ingestion_manifests" / "ingestion.manifest-fixture.json" + write_json(ingestion_path, payload) + return ManifestedFixture( + config=config, + ingestion_path=ingestion_path, + ingestion_sha256=sha256_file(ingestion_path), + dataset=dataset, + table=table, + aggregate_paths=aggregate_paths, + exchange_info_paths=exchange_info_paths, + raw_manifest_paths=raw_manifest_paths, + ) + + +def _rewrite_ingestion(fixture: ManifestedFixture, payload: dict[str, Any]) -> str: + write_json(fixture.ingestion_path, payload) + return sha256_file(fixture.ingestion_path) + + +def _raw_entry(payload: dict[str, Any], fixture: ManifestedFixture, path: Path) -> dict[str, Any]: + relative_path = str(path.relative_to(fixture.ingestion_path.parent.parent)) + for raw_entry in payload["raw_artifacts"]: + if raw_entry["path"] == relative_path: + return raw_entry + raise AssertionError(f"fixture raw artifact is not manifested: {path}") + + +def _rewrite_raw_sidecar_uri( + fixture: ManifestedFixture, + path: Path, + source_uri: str, +) -> str: + sidecar_path = fixture.raw_manifest_paths[path] + sidecar = read_json(sidecar_path) + sidecar["source_uri"] = source_uri + write_json(sidecar_path, sidecar) + ingestion = read_json(fixture.ingestion_path) + entry = _raw_entry(ingestion, fixture, path) + entry["manifest_sha256"] = sha256_file(sidecar_path) + return _rewrite_ingestion(fixture, ingestion) + + +def _rewrite_raw_payload( + fixture: ManifestedFixture, + path: Path, + payload: dict[str, Any] | list[Any], +) -> str: + write_json(path, payload) + raw_sha = sha256_file(path) + sidecar_path = fixture.raw_manifest_paths[path] + sidecar = read_json(sidecar_path) + sidecar["bytes"] = path.stat().st_size + sidecar["checksum"]["value"] = raw_sha + write_json(sidecar_path, sidecar) + ingestion = read_json(fixture.ingestion_path) + entry = _raw_entry(ingestion, fixture, path) + entry["sha256"] = raw_sha + entry["manifest_sha256"] = sha256_file(sidecar_path) + return _rewrite_ingestion(fixture, ingestion) + + +def test_reads_only_manifested_parts_and_returns_arrow_polars_utc_coverage( + tmp_path: Path, +) -> None: + fixture = _fixture(tmp_path) + undeclared = tmp_path / "normalized" / "undeclared.parquet" + undeclared.write_bytes(b"this file must never be discovered") + + result = read_public_trades( + fixture.config, + fixture.ingestion_path, + ingestion_manifest_sha256=fixture.ingestion_sha256, + ) + + assert result.rows == 6 + assert result.arrow_trades.equals(fixture.table) + assert result.polars_trades.height == 6 + assert result.validation.error_count == 0 + assert result.row_bound == 6 + assert result.evidence_tier == "PUBLIC_SAMPLE_PARTIAL" + assert not result.all_requested_ranges_complete + assert result.observed.start_ns == START_NS + assert result.observed.end_inclusive_ns == START_NS + 200_000_000 + assert result.observed.start_utc == "2024-01-02T00:00:00.000000000Z" + assert result.observed.end_inclusive_utc == "2024-01-02T00:00:00.200000000Z" + assert {item.symbol: item.rows for item in result.symbols} == { + "BTCUSDT": 3, + "ETHUSDT": 3, + } + assert set(result.part_paths) == {item.data_path for item in fixture.dataset.artifacts} + expected_raw_paths = set(fixture.aggregate_paths.values()) | set( + fixture.exchange_info_paths.values() + ) + assert set(result.raw_artifact_paths) == expected_raw_paths + assert set(result.raw_manifest_paths) == set(fixture.raw_manifest_paths.values()) + assert set(result.raw_artifact_sha256s) == {sha256_file(path) for path in expected_raw_paths} + assert result.canonical_order == ( + "venue", + "symbol", + "available_ts_ns", + "event_ts_ns", + "trade_id", + ) + assert undeclared not in result.part_paths + + +def test_requires_matching_ingestion_and_normalized_manifest_hashes(tmp_path: Path) -> None: + fixture = _fixture(tmp_path) + with pytest.raises(PublicDataError, match="ingestion manifest SHA-256 mismatch"): + read_public_trades( + fixture.config, + fixture.ingestion_path, + ingestion_manifest_sha256="0" * 64, + ) + + payload = read_json(fixture.ingestion_path) + payload["normalized_datasets"][0]["manifest_sha256"] = "0" * 64 + rewritten_sha = _rewrite_ingestion(fixture, payload) + with pytest.raises(PublicDataError, match="normalized dataset manifest SHA-256 mismatch"): + read_public_trades( + fixture.config, + fixture.ingestion_path, + ingestion_manifest_sha256=rewritten_sha, + ) + + +@pytest.mark.parametrize( + ("requested_tier", "complete"), + [("PUBLIC_SAMPLE_PARTIAL", True), ("FULL_DATA", False)], +) +def test_rejects_partial_manifest_promoted_to_full_data( + tmp_path: Path, requested_tier: str, complete: bool +) -> None: + fixture = _fixture( + tmp_path, + requested_tier=requested_tier, + effective_tier="FULL_DATA", + complete=complete, + ) + + with pytest.raises(PublicDataError, match="cannot be promoted to FULL_DATA"): + read_public_trades( + fixture.config, + fixture.ingestion_path, + ingestion_manifest_sha256=fixture.ingestion_sha256, + ) + + +def test_rejects_missing_or_tampered_declared_parts(tmp_path: Path) -> None: + missing_fixture = _fixture(tmp_path / "missing") + missing_fixture.dataset.artifacts[0].data_path.unlink() + with pytest.raises(PublicDataError, match=r"missing normalized dataset\.artifacts"): + read_public_trades( + missing_fixture.config, + missing_fixture.ingestion_path, + ingestion_manifest_sha256=missing_fixture.ingestion_sha256, + ) + + tampered_fixture = _fixture(tmp_path / "tampered") + part = tampered_fixture.dataset.artifacts[0].data_path + part.write_bytes(part.read_bytes() + b"tampered") + with pytest.raises(PublicDataError, match=r"Parquet part \d+ SHA-256 mismatch"): + read_public_trades( + tampered_fixture.config, + tampered_fixture.ingestion_path, + ingestion_manifest_sha256=tampered_fixture.ingestion_sha256, + ) + + +def test_rejects_unexpected_normalized_schema(tmp_path: Path) -> None: + fixture = _fixture(tmp_path, stored_schema="book_observations") + + with pytest.raises(PublicDataError, match="declares an unexpected schema"): + read_public_trades( + fixture.config, + fixture.ingestion_path, + ingestion_manifest_sha256=fixture.ingestion_sha256, + ) + + +def test_enforces_required_row_bound_before_part_loading(tmp_path: Path) -> None: + fixture = _fixture(tmp_path) + dataset_payload = read_json(fixture.dataset.manifest_path) + dataset_payload["rows"] = 7 + write_json(fixture.dataset.manifest_path, dataset_payload) + ingestion_payload = read_json(fixture.ingestion_path) + ingestion_payload["normalized_datasets"][0]["rows"] = 7 + ingestion_payload["normalized_datasets"][0]["manifest_sha256"] = sha256_file( + fixture.dataset.manifest_path + ) + ingestion_sha = _rewrite_ingestion(fixture, ingestion_payload) + fixture.dataset.artifacts[0].data_path.write_bytes(b"also tampered") + + with pytest.raises(PublicDataError, match="above required bound 6"): + read_public_trades( + fixture.config, + fixture.ingestion_path, + ingestion_manifest_sha256=ingestion_sha, + ) + + +def test_rejects_cross_manifest_coverage_disagreement(tmp_path: Path) -> None: + fixture = _fixture(tmp_path) + payload = read_json(fixture.ingestion_path) + payload["requested_range_ns"]["start"] = START_NS + 1 + rewritten_sha = _rewrite_ingestion(fixture, payload) + + with pytest.raises(PublicDataError, match="requested range does not match configuration"): + read_public_trades( + fixture.config, + fixture.ingestion_path, + ingestion_manifest_sha256=rewritten_sha, + ) + + +@pytest.mark.parametrize("mismatch", ["source", "symbols", "range"]) +def test_rejects_manifest_that_does_not_match_config(tmp_path: Path, mismatch: str) -> None: + fixture = _fixture(tmp_path) + config = fixture.config + if mismatch == "source": + config = replace(config, data=replace(config.data, source="different_public_source")) + elif mismatch == "symbols": + config = replace(config, data=replace(config.data, symbols=("BTCUSDT",))) + else: + config = replace( + config, + data=replace( + config.data, + start=datetime.fromtimestamp((START_NS - 1_000_000_000) / 1e9, tz=UTC), + ), + ) + + with pytest.raises(PublicDataError, match=r"do(?:es)? not match"): + read_public_trades( + config, + fixture.ingestion_path, + ingestion_manifest_sha256=fixture.ingestion_sha256, + ) + + +def test_rejects_tampered_raw_bytes_and_undeclared_row_lineage(tmp_path: Path) -> None: + tampered = _fixture(tmp_path / "tampered-raw") + tampered_path = tampered.aggregate_paths["BTCUSDT"] + tampered_path.write_bytes(tampered_path.read_bytes() + b"tampered") + with pytest.raises(PublicDataError, match=r"raw artifact \d+ SHA-256 mismatch"): + read_public_trades( + tampered.config, + tampered.ingestion_path, + ingestion_manifest_sha256=tampered.ingestion_sha256, + ) + + lineage = _fixture(tmp_path / "lineage") + replacement_raw = lineage.ingestion_path.parent.parent / "raw" / "replacement.json" + original_payload = read_json(lineage.aggregate_paths["BTCUSDT"]) + for record in original_payload: + record["a"] += 1_000_000 + write_json(replacement_raw, original_payload) + replacement_manifest, replacement_manifest_sha = write_source_manifest( + replacement_raw, + source="binance_spot_public_api", + source_uri=( + f"{lineage.config.data.base_url}/api/v3/aggTrades?symbol=BTCUSDT" + f"&startTime={START_NS // 1_000_000}" + f"&endTime={(END_NS - 1) // 1_000_000}" + f"&limit={lineage.config.data.request_limit}" + ), + downloaded_at_utc="2026-08-07T12:00:00Z", + requested_start_ns=START_NS, + requested_end_ns=END_NS, + ) + payload = read_json(lineage.ingestion_path) + entry = _raw_entry(payload, lineage, lineage.aggregate_paths["BTCUSDT"]) + entry.update( + { + "path": str(replacement_raw.relative_to(tmp_path / "lineage")), + "sha256": sha256_file(replacement_raw), + "manifest_path": str(replacement_manifest.relative_to(tmp_path / "lineage")), + "manifest_sha256": replacement_manifest_sha, + } + ) + ingestion_sha = _rewrite_ingestion(lineage, payload) + with pytest.raises(PublicDataError, match="references an undeclared or empty raw artifact"): + read_public_trades( + lineage.config, + lineage.ingestion_path, + ingestion_manifest_sha256=ingestion_sha, + ) + + +@pytest.mark.parametrize( + ("case", "expected"), + [ + ("wrong_scheme", "not bound to configured data.base_url"), + ("wrong_host", "not bound to configured data.base_url"), + ("wrong_path", "does not use an allowed Binance public endpoint"), + ("extra_query", "initial-time or fromId query parameters"), + ("missing_time", "initial-time or fromId query parameters"), + ("wrong_symbol", "exactly one initial-time aggTrades page"), + ], +) +def test_rejects_unbound_or_malformed_aggregate_trade_uri( + tmp_path: Path, + case: str, + expected: str, +) -> None: + fixture = _fixture(tmp_path) + base = fixture.config.data.base_url + query = ( + f"symbol=BTCUSDT&startTime={START_NS // 1_000_000}" + f"&endTime={(END_NS - 1) // 1_000_000}" + f"&limit={fixture.config.data.request_limit}" + ) + uris = { + "wrong_scheme": f"http://data-api.binance.vision/api/v3/aggTrades?{query}", + "wrong_host": f"https://evil.example/api/v3/aggTrades?{query}", + "wrong_path": f"{base}/api/v3/aggTrades/extra?{query}", + "extra_query": f"{base}/api/v3/aggTrades?{query}&unexpected=1", + "missing_time": ( + f"{base}/api/v3/aggTrades?symbol=BTCUSDT" + f"&startTime={START_NS // 1_000_000}" + f"&limit={fixture.config.data.request_limit}" + ), + "wrong_symbol": f"{base}/api/v3/aggTrades?{query.replace('BTCUSDT', 'ETHUSDT')}", + } + ingestion_sha = _rewrite_raw_sidecar_uri( + fixture, + fixture.aggregate_paths["BTCUSDT"], + uris[case], + ) + + with pytest.raises(PublicDataError, match=expected): + read_public_trades( + fixture.config, + fixture.ingestion_path, + ingestion_manifest_sha256=ingestion_sha, + ) + + +def test_rejects_exchange_info_query_and_requires_every_configured_symbol( + tmp_path: Path, +) -> None: + malformed = _fixture(tmp_path / "query") + malformed_sha = _rewrite_raw_sidecar_uri( + malformed, + malformed.exchange_info_paths["BTCUSDT"], + (f"{malformed.config.data.base_url}/api/v3/exchangeInfo?symbol=BTCUSDT&unexpected=1"), + ) + with pytest.raises(PublicDataError, match="exactly the symbol parameter"): + read_public_trades( + malformed.config, + malformed.ingestion_path, + ingestion_manifest_sha256=malformed_sha, + ) + + missing = _fixture(tmp_path / "missing") + ingestion = read_json(missing.ingestion_path) + missing_relative = str( + missing.exchange_info_paths["BTCUSDT"].relative_to(missing.ingestion_path.parent.parent) + ) + ingestion["raw_artifacts"] = [ + entry for entry in ingestion["raw_artifacts"] if entry["path"] != missing_relative + ] + missing_sha = _rewrite_ingestion(missing, ingestion) + with pytest.raises(PublicDataError, match=r"lacks exchangeInfo.*BTCUSDT"): + read_public_trades( + missing.config, + missing.ingestion_path, + ingestion_manifest_sha256=missing_sha, + ) + + +@pytest.mark.parametrize( + ("fixture_kwargs", "expected"), + [ + ({"cross_symbol_lineage": True}, "raw page for ETHUSDT, not BTCUSDT"), + ({"raw_trade_id_offset": True}, "trade_id is absent from its exact raw"), + ({"raw_price_mismatch": True}, "exact raw aggregate-trade record: price"), + ], +) +def test_rejects_cross_symbol_and_exact_raw_record_mismatches( + tmp_path: Path, + fixture_kwargs: dict[str, bool], + expected: str, +) -> None: + fixture = _fixture(tmp_path, **fixture_kwargs) + with pytest.raises(PublicDataError, match=expected): + read_public_trades( + fixture.config, + fixture.ingestion_path, + ingestion_manifest_sha256=fixture.ingestion_sha256, + ) + + +@pytest.mark.parametrize( + ("field", "value", "expected"), + [ + ("tick_size", "0.02", "payload scales do not match ingestion claim"), + ("status", "BREAK", "payload status is not TRADING"), + ("symbol", "ETHUSDT", "payload symbol does not match its request URI"), + ], +) +def test_rejects_semantically_tampered_exchange_info_payload( + tmp_path: Path, + field: str, + value: str, + expected: str, +) -> None: + fixture = _fixture(tmp_path) + metadata_path = fixture.exchange_info_paths["BTCUSDT"] + payload = read_json(metadata_path) + item = payload["symbols"][0] + if field == "tick_size": + price_filter = next( + raw_filter + for raw_filter in item["filters"] + if raw_filter["filterType"] == "PRICE_FILTER" + ) + price_filter["tickSize"] = value + else: + item[field] = value + ingestion_sha = _rewrite_raw_payload(fixture, metadata_path, payload) + + with pytest.raises(PublicDataError, match=expected): + read_public_trades( + fixture.config, + fixture.ingestion_path, + ingestion_manifest_sha256=ingestion_sha, + ) + + +def test_rejects_raw_aggregate_event_time_reversal(tmp_path: Path) -> None: + fixture = _fixture(tmp_path) + aggregate_path = fixture.aggregate_paths["BTCUSDT"] + payload = read_json(aggregate_path) + payload[0]["T"] = int(payload[1]["T"]) + 1 + ingestion_sha = _rewrite_raw_payload(fixture, aggregate_path, payload) + + with pytest.raises(PublicDataError, match="event times are not nondecreasing"): + verify_public_trade_dataset( + fixture.config, + fixture.ingestion_path, + ingestion_manifest_sha256=ingestion_sha, + ) + + +def test_allows_shared_empty_terminal_page_with_distinct_symbol_sidecars( + tmp_path: Path, +) -> None: + fixture = _fixture(tmp_path) + bundle_root = fixture.ingestion_path.parent.parent + empty_path = bundle_root / "raw" / "binance_spot" / "agg_trades" / "shared-empty.json" + write_json(empty_path, []) + empty_sha = sha256_file(empty_path) + ingestion = read_json(fixture.ingestion_path) + for symbol in fixture.config.data.symbols: + symbol_rows = [row for row in fixture.table.to_pylist() if str(row["symbol"]) == symbol] + from_id = max(int(row["trade_id"]) for row in symbol_rows) + 1 + sidecar_path, sidecar_sha = write_source_manifest( + empty_path, + source="binance_spot_public_api", + source_uri=( + f"{fixture.config.data.base_url}/api/v3/aggTrades?symbol={symbol}" + f"&fromId={from_id}&limit={fixture.config.data.request_limit}" + ), + downloaded_at_utc="2026-08-07T12:00:01Z", + requested_start_ns=START_NS, + requested_end_ns=END_NS, + ) + ingestion["raw_artifacts"].append( + { + "path": str(empty_path.relative_to(bundle_root)), + "sha256": empty_sha, + "manifest_path": str(sidecar_path.relative_to(bundle_root)), + "manifest_sha256": sidecar_sha, + } + ) + ingestion_sha = _rewrite_ingestion(fixture, ingestion) + + result = read_public_trades( + fixture.config, + fixture.ingestion_path, + ingestion_manifest_sha256=ingestion_sha, + ) + + assert result.rows == fixture.table.num_rows + assert empty_path in result.raw_artifact_paths + + +def test_rejects_manifest_scale_mismatch_and_fresh_quality_errors(tmp_path: Path) -> None: + scale = _fixture(tmp_path / "scale") + payload = read_json(scale.ingestion_path) + payload["symbols"][0]["tick_size"] = "0.02" + ingestion_sha = _rewrite_ingestion(scale, payload) + with pytest.raises(PublicDataError, match="payload scales do not match ingestion claim"): + read_public_trades( + scale.config, + scale.ingestion_path, + ingestion_manifest_sha256=ingestion_sha, + ) + + invalid = _fixture(tmp_path / "quality", invalid_quality=True) + with pytest.raises(PublicDataError, match="failed quality validation"): + read_public_trades( + invalid.config, + invalid.ingestion_path, + ingestion_manifest_sha256=invalid.ingestion_sha256, + ) + + +def test_canonical_order_is_independent_of_manifest_part_order(tmp_path: Path) -> None: + fixture = _fixture(tmp_path) + dataset_payload = read_json(fixture.dataset.manifest_path) + dataset_payload["artifacts"] = list(reversed(dataset_payload["artifacts"])) + write_json(fixture.dataset.manifest_path, dataset_payload) + ingestion_payload = read_json(fixture.ingestion_path) + ingestion_payload["normalized_datasets"][0]["manifest_sha256"] = sha256_file( + fixture.dataset.manifest_path + ) + ingestion_sha = _rewrite_ingestion(fixture, ingestion_payload) + + result = read_public_trades( + fixture.config, + fixture.ingestion_path, + ingestion_manifest_sha256=ingestion_sha, + ) + + assert result.arrow_trades.equals(fixture.table) + + +def test_verify_only_never_reads_normalized_parquet_rows( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + fixture = _fixture(tmp_path) + + def _forbidden_read(*args: object, **kwargs: object) -> pa.Table: + del args, kwargs + raise AssertionError("verify-only must not read normalized rows") + + monkeypatch.setattr(pq.ParquetFile, "read", _forbidden_read) + dataset = verify_public_trade_dataset( + fixture.config, + fixture.ingestion_path, + ingestion_manifest_sha256=fixture.ingestion_sha256, + ) + + assert dataset.rows == 6 + assert dataset.part_paths == tuple(item.data_path for item in fixture.dataset.artifacts) + + +def test_verified_batch_stream_is_bounded_fresh_and_canonical(tmp_path: Path) -> None: + fixture = _fixture(tmp_path) + dataset = verify_public_trade_dataset( + fixture.config, + fixture.ingestion_path, + ingestion_manifest_sha256=fixture.ingestion_sha256, + ) + + first = dataset.iter_verified_batches( + batch_rows=2, + memory_limit="64MB", + temp_directory=tmp_path, + ) + first_batches = list(first) + first_table = pa.Table.from_batches(first_batches, schema=fixture.table.schema) + assert first.validation.error_count == 0 + assert [batch.num_rows for batch in first_batches] == [2, 2, 2] + assert first_table.equals(fixture.table) + + second = dataset.iter_verified_batches( + batch_rows=1, + memory_limit="64MB", + temp_directory=tmp_path, + ) + second_batches = list(second) + assert all(batch.num_rows == 1 for batch in second_batches) + assert pa.Table.from_batches(second_batches, schema=fixture.table.schema).equals(first_table) + + +def test_verified_stream_scans_each_parquet_part_once( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + fixture = _fixture(tmp_path) + dataset = verify_public_trade_dataset( + fixture.config, + fixture.ingestion_path, + ingestion_manifest_sha256=fixture.ingestion_sha256, + ) + original = pq.ParquetFile.iter_batches + calls = 0 + + def _counted_iter_batches( + self: pq.ParquetFile, + *args: object, + **kwargs: object, + ) -> object: + nonlocal calls + calls += 1 + return original(self, *args, **kwargs) + + monkeypatch.setattr(pq.ParquetFile, "iter_batches", _counted_iter_batches) + stream = dataset.iter_verified_batches( + batch_rows=2, + memory_limit="64MB", + temp_directory=tmp_path, + ) + + assert sum(batch.num_rows for batch in stream) == dataset.rows + assert calls == len(dataset.part_paths) + + +def test_materialization_guard_is_checked_before_any_normalized_row_read( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + fixture = _fixture(tmp_path) + + def _forbidden_stream(*args: object, **kwargs: object) -> object: + del args, kwargs + raise AssertionError("materialization guard must run before normalized row reading") + + monkeypatch.setattr( + public_data.PublicTradeDataset, + "iter_verified_batches", + _forbidden_stream, + ) + with pytest.raises(PublicDataError, match="above materialization guard 5"): + read_public_trades( + fixture.config, + fixture.ingestion_path, + ingestion_manifest_sha256=fixture.ingestion_sha256, + materialization_max_rows=5, + ) + + +def test_incremental_dq_detects_duplicate_across_one_row_batches(tmp_path: Path) -> None: + fixture = _fixture(tmp_path, invalid_quality=True) + dataset = verify_public_trade_dataset( + fixture.config, + fixture.ingestion_path, + ingestion_manifest_sha256=fixture.ingestion_sha256, + ) + + stream = dataset.iter_verified_batches( + batch_rows=1, + memory_limit="64MB", + temp_directory=tmp_path, + ) + with pytest.raises(PublicDataError, match="failed quality validation"): + list(stream) + + +def test_physical_order_dq_survives_external_canonical_sort_across_parts( + tmp_path: Path, +) -> None: + fixture = _fixture(tmp_path, physical_clock_reversal=True) + dataset = verify_public_trade_dataset( + fixture.config, + fixture.ingestion_path, + ingestion_manifest_sha256=fixture.ingestion_sha256, + ) + + report = dataset.validate( + batch_rows=1, + memory_limit="64MB", + temp_directory=tmp_path, + ) + + assert any(item.rule_id == "temporal.out_of_order_event_time" for item in report.findings) + + +@pytest.mark.parametrize( + ("fixture_kwargs", "expected"), + [ + ({"raw_price_mismatch": True}, "exact raw aggregate-trade record: price"), + ({"normalized_scale_mismatch": True}, "scales do not match manifest"), + ], +) +def test_cross_batch_lineage_and_scale_failures_are_detected( + tmp_path: Path, + fixture_kwargs: dict[str, bool], + expected: str, +) -> None: + fixture = _fixture(tmp_path, **fixture_kwargs) + dataset = verify_public_trade_dataset( + fixture.config, + fixture.ingestion_path, + ingestion_manifest_sha256=fixture.ingestion_sha256, + ) + stream = dataset.iter_verified_batches( + batch_rows=1, + memory_limit="64MB", + temp_directory=tmp_path, + ) + + with pytest.raises(PublicDataError, match=expected): + list(stream) + + +def test_stream_rehashes_parquet_after_descriptor_verification(tmp_path: Path) -> None: + fixture = _fixture(tmp_path) + dataset = verify_public_trade_dataset( + fixture.config, + fixture.ingestion_path, + ingestion_manifest_sha256=fixture.ingestion_sha256, + ) + part = fixture.dataset.artifacts[0].data_path + part.write_bytes(part.read_bytes() + b"changed-after-verification") + + stream = dataset.iter_verified_batches( + batch_rows=2, + memory_limit="64MB", + temp_directory=tmp_path, + ) + with pytest.raises(PublicDataError, match="normalized Parquet part SHA-256 mismatch"): + list(stream) + + +def test_raw_terminal_sentinel_outside_range_is_preserved_but_not_normalized( + tmp_path: Path, +) -> None: + fixture = _fixture(tmp_path, raw_terminal_sentinel=True) + + result = read_public_trades( + fixture.config, + fixture.ingestion_path, + ingestion_manifest_sha256=fixture.ingestion_sha256, + ) + + assert result.rows == 6 + assert max(result.arrow_trades.column("event_ts_ns").to_pylist()) < END_NS + + +def test_rejects_oversized_raw_json_before_payload_parsing(tmp_path: Path) -> None: + fixture = _fixture(tmp_path) + metadata_path = fixture.exchange_info_paths["BTCUSDT"] + payload = read_json(metadata_path) + payload["unused_padding"] = "x" * (8 * 1024 * 1024) + ingestion_sha = _rewrite_raw_payload(fixture, metadata_path, payload) + + with pytest.raises(PublicDataError, match="exceeds bounded JSON size"): + verify_public_trade_dataset( + fixture.config, + fixture.ingestion_path, + ingestion_manifest_sha256=ingestion_sha, + ) + + +def test_rejects_giant_manifest_string_before_json_materialization(tmp_path: Path) -> None: + fixture = _fixture(tmp_path) + dataset_manifest = read_json(fixture.dataset.manifest_path) + dataset_manifest["unused_padding"] = "x" * (64 * 1024 + 1) + write_json(fixture.dataset.manifest_path, dataset_manifest) + ingestion = read_json(fixture.ingestion_path) + ingestion["normalized_datasets"][0]["manifest_sha256"] = sha256_file( + fixture.dataset.manifest_path + ) + ingestion_sha = _rewrite_ingestion(fixture, ingestion) + + with pytest.raises(PublicDataError, match="JSON string above bounded token size"): + verify_public_trade_dataset( + fixture.config, + fixture.ingestion_path, + ingestion_manifest_sha256=ingestion_sha, + ) + + +def test_inverse_lineage_rejects_dropped_selected_raw_trades(tmp_path: Path) -> None: + fixture = _fixture( + tmp_path, + complete=True, + drop_last_normalized_per_symbol=True, + ) + dataset = verify_public_trade_dataset( + fixture.config, + fixture.ingestion_path, + ingestion_manifest_sha256=fixture.ingestion_sha256, + ) + + stream = dataset.iter_verified_batches( + batch_rows=1, + memory_limit="64MB", + temp_directory=tmp_path, + ) + with pytest.raises(PublicDataError, match=r"raw selected rows.*do not match"): + list(stream) + + +def test_terminal_stream_summary_is_bound_to_top_level_claim(tmp_path: Path) -> None: + fixture = _fixture( + tmp_path, + complete=True, + drop_last_normalized_per_symbol=True, + ) + ingestion = read_json(fixture.ingestion_path) + ingestion["symbols"][0]["stream_summary"]["raw_page_count"] = 2 + ingestion_sha = _rewrite_ingestion(fixture, ingestion) + + with pytest.raises(PublicDataError, match="stream_summary disagrees"): + verify_public_trade_dataset( + fixture.config, + fixture.ingestion_path, + ingestion_manifest_sha256=ingestion_sha, + ) + + +def test_terminal_stream_summary_is_bound_to_declared_page_chain(tmp_path: Path) -> None: + fixture = _fixture( + tmp_path, + complete=True, + drop_last_normalized_per_symbol=True, + ) + ingestion = read_json(fixture.ingestion_path) + ingestion["symbols"][0]["raw_page_count"] = 2 + ingestion["symbols"][0]["stream_summary"]["raw_page_count"] = 2 + ingestion_sha = _rewrite_ingestion(fixture, ingestion) + + with pytest.raises(PublicDataError, match="does not match declared raw pages"): + verify_public_trade_dataset( + fixture.config, + fixture.ingestion_path, + ingestion_manifest_sha256=ingestion_sha, + ) + + +def test_complete_legacy_claim_requires_terminal_evidence(tmp_path: Path) -> None: + fixture = _fixture(tmp_path, complete=True) + + with pytest.raises(PublicDataError, match="lacks terminal stream evidence"): + verify_public_trade_dataset( + fixture.config, + fixture.ingestion_path, + ingestion_manifest_sha256=fixture.ingestion_sha256, + ) + + +def test_complete_range_cannot_end_after_terminal_page_download(tmp_path: Path) -> None: + fixture = _fixture( + tmp_path, + complete=True, + drop_last_normalized_per_symbol=True, + ) + ingestion = read_json(fixture.ingestion_path) + for path in fixture.aggregate_paths.values(): + sidecar_path = fixture.raw_manifest_paths[path] + sidecar = read_json(sidecar_path) + sidecar["downloaded_at_utc"] = "2023-01-01T00:00:00Z" + write_json(sidecar_path, sidecar) + entry = _raw_entry(ingestion, fixture, path) + entry["manifest_sha256"] = sha256_file(sidecar_path) + ingestion_sha = _rewrite_ingestion(fixture, ingestion) + + with pytest.raises(PublicDataError, match="ends after its terminal page was downloaded"): + verify_public_trade_dataset( + fixture.config, + fixture.ingestion_path, + ingestion_manifest_sha256=ingestion_sha, + ) diff --git a/Microstructure/tests/test_public_pipeline.py b/Microstructure/tests/test_public_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..f81ad62d7a1b8f3783983b755e3c9610c1c71012 --- /dev/null +++ b/Microstructure/tests/test_public_pipeline.py @@ -0,0 +1,743 @@ +from __future__ import annotations + +import json +import math +import shutil +from collections.abc import Mapping +from dataclasses import dataclass, replace +from pathlib import Path +from typing import Any +from urllib.parse import urlencode + +import polars as pl +import pytest + +import microstructure.public_pipeline as public_pipeline +from microstructure.cli import main +from microstructure.config import ProjectConfig, load_config +from microstructure.ingestion import IngestionResult, ingest_public_trades +from microstructure.pipeline import PipelineError, reproduce +from microstructure.provenance import sha256_file +from microstructure.public_data import PublicDataError, PublicTrades, read_public_trades +from microstructure.public_pipeline import ( + EXECUTION_EXCLUSION_REASON, + PublicPipelineError, + produce_public_trade_run, +) +from microstructure.reporting import load_run_bundle, verify_checksums +from microstructure.research.models import paired_block_bootstrap_difference + + +class _FakeResponse: + def __init__(self, payload: Any) -> None: + self.status_code = 200 + self._payload = payload + self.content = json.dumps(payload, separators=(",", ":")).encode() + self.text = self.content.decode() + self.headers: dict[str, str] = {} + self.url = "https://data-api.binance.vision/fixture" + + def json(self) -> Any: + return self._payload + + +class _FakeSession: + def __init__(self, responses: list[_FakeResponse]) -> None: + self.responses = responses + self.calls: list[dict[str, object]] = [] + + def get(self, url: str, *, params: Mapping[str, object], timeout: float) -> _FakeResponse: + self.calls.append({"url": url, "params": dict(params), "timeout": timeout}) + response = self.responses.pop(0) + response.url = f"{url}?{urlencode(params)}" + return response + + +@dataclass(frozen=True, slots=True) +class _CompletedFixture: + config: ProjectConfig + ingestion: IngestionResult + public: PublicTrades + run_dir: Path + + +@dataclass(frozen=True, slots=True) +class _UnifiedFixture: + source: _CompletedFixture + run_dir: Path + + +def _metadata(symbol: str) -> dict[str, object]: + base = "BTC" if symbol == "BTCUSDT" else "ETH" + return { + "symbols": [ + { + "symbol": symbol, + "status": "TRADING", + "baseAsset": base, + "quoteAsset": "USDT", + "filters": [ + { + "filterType": "PRICE_FILTER", + "minPrice": "0.01", + "maxPrice": "1000000.00", + "tickSize": "0.01", + }, + { + "filterType": "LOT_SIZE", + "minQty": "0.001", + "maxQty": "10000.000", + "stepSize": "0.001", + }, + ], + } + ] + } + + +def _aggregate_trades(symbol: str, *, start_ms: int, rows: int) -> list[dict[str, object]]: + id_start = 1_000_000 if symbol == "BTCUSDT" else 2_000_000 + price_start = 10_000 if symbol == "BTCUSDT" else 20_000 + price_pattern = (0, 1, 3, 2, 5, 1, 4, 2) + result: list[dict[str, object]] = [] + for index in range(rows): + trade_id = id_start + index + price_ticks = price_start + price_pattern[index % len(price_pattern)] + quantity_lots = 1 + index % 5 + result.append( + { + "a": trade_id, + "p": f"{price_ticks / 100:.2f}", + "q": f"{quantity_lots / 1000:.3f}", + "f": 10_000_000 + index, + "l": 10_000_000 + index, + "T": start_ms + index, + "m": bool(index % 2), + } + ) + return result + + +def _write_config(project_root: Path) -> ProjectConfig: + config_path = project_root / "configs" / "public-pipeline-fixture.toml" + config_path.parent.mkdir(parents=True, exist_ok=True) + config_path.write_text( + """ +[run] +name = "public-trade-fixture" +evidence_tier = "PUBLIC_SAMPLE_PARTIAL" +seed = 20260807 + +[data] +mode = "binance_rest" +source = "binance_spot_rest" +symbols = ["BTCUSDT", "ETHUSDT"] +start = "2024-01-02T00:00:00Z" +end = "2024-01-02T00:01:00Z" +max_events_per_symbol = 80 +raw_root = "data/raw" +partition_root = "data/normalized" +schema_version = "1.0.0" +base_url = "https://data-api.binance.vision" +request_limit = 100 +timeout_seconds = 5.0 +max_retries = 0 + +[quality] +max_spread_bps = 100.0 +max_silence_ms = 5000 +fail_on_error = true + +[features] +trade_windows = [2, 4] +volatility_window = 4 +intensity_window = 3 +label_horizon_events = 2 +large_trade_quantile = 0.90 + +[evaluation] +min_train_events = 24 +validation_events = 12 +test_events = 12 +step_events = 12 +embargo_events = 2 +bootstrap_samples = 12 +calibration_bins = 5 + +[models] +selection_metric = "log_loss" +logistic_c_values = [1.0] +tree_max_depth_values = [2] +tree_min_samples_leaf = 2 + +[execution] +decision_latency_events = 1 +order_latency_events = 1 +maker_fee_bps = 1.0 +taker_fee_bps = 4.0 +half_spread_bps = 1.0 +slippage_bps_per_unit = 0.20 +signal_threshold = 0.52 +max_position_units = 1.0 +order_size_units = 0.1 +limit_fill_base_probability = 0.55 +queue_ahead_units = 0.1 +limit_max_age_events = 5 +cancel_latency_events = 1 +liquidate_at_end = true +capacity_multipliers = [0.5, 1.0] +""".strip() + + "\n", + encoding="utf-8", + ) + protocol = project_root / "docs" / "PUBLIC_TRADE_PROTOCOL.md" + protocol.parent.mkdir(parents=True, exist_ok=True) + protocol.write_text( + "# Frozen public aggregate-trade fixture protocol\n\n" + "Retrospective PUBLIC_SAMPLE_PARTIAL predictive diagnostics only. " + "No execution or P&L.\n", + encoding="utf-8", + ) + return load_config(config_path) + + +def _json(path: Path) -> Any: + return json.loads(path.read_text(encoding="utf-8")) + + +@pytest.fixture(scope="module") +def completed_public_bundle( + tmp_path_factory: pytest.TempPathFactory, +) -> _CompletedFixture: + project_root = tmp_path_factory.mktemp("public-pipeline-project") + config = _write_config(project_root) + start_ms = int(config.data.start.timestamp() * 1000) + session = _FakeSession( + [ + _FakeResponse(_metadata("BTCUSDT")), + _FakeResponse(_aggregate_trades("BTCUSDT", start_ms=start_ms, rows=80)), + _FakeResponse(_metadata("ETHUSDT")), + _FakeResponse(_aggregate_trades("ETHUSDT", start_ms=start_ms, rows=80)), + ] + ) + ingestion = ingest_public_trades( + config, + project_root / "data", + session=session, # type: ignore[arg-type] + ) + assert len(session.calls) == 4 + public = read_public_trades( + config, + ingestion.ingestion_manifest_path, + ingestion_manifest_sha256=ingestion.ingestion_manifest_sha256, + ) + + # A newer-looking decoy proves that the producer never discovers or selects + # directory contents: the explicit path+digest pair remains the only authority. + decoy = ( + ingestion.ingestion_manifest_path.parent / "ingestion.manifest-zzzzzzzzzzzzzzzzzzzz.json" + ) + decoy.write_text("not a manifest\n", encoding="utf-8") + run_dir = project_root / "artifacts" / "staging-public-run" + produce_public_trade_run( + config, + run_dir, + ingestion_manifest_path=ingestion.ingestion_manifest_path, + ingestion_manifest_sha256=ingestion.ingestion_manifest_sha256, + ) + return _CompletedFixture(config, ingestion, public, run_dir) + + +@pytest.fixture(scope="module") +def unified_public_bundle( + completed_public_bundle: _CompletedFixture, + tmp_path_factory: pytest.TempPathFactory, +) -> _UnifiedFixture: + source = completed_public_bundle + target = tmp_path_factory.mktemp("unified-public-pipeline") / "public-run" + output = reproduce( + source.config, + target, + ingestion_manifest_path=source.ingestion.ingestion_manifest_path, + ingestion_manifest_sha256=source.ingestion.ingestion_manifest_sha256, + ) + return _UnifiedFixture(source=source, run_dir=output) + + +def test_public_run_is_manifest_anchored_partial_and_provenanced( + completed_public_bundle: _CompletedFixture, +) -> None: + fixture = completed_public_bundle + bundle = load_run_bundle(fixture.run_dir) + provenance = _json(fixture.run_dir / "provenance.json") + snapshot = _json(fixture.run_dir / "data" / "manifest_snapshot.json") + + assert bundle.evidence_tier == "PUBLIC_SAMPLE_PARTIAL" + assert bundle.manifest["data"]["rows"] == 160 + assert bundle.manifest["data"]["row_bound"] == 160 + assert bundle.manifest["data"]["all_requested_ranges_complete"] is False + assert bundle.manifest["data"]["reader_effective_evidence_tier"] == ("PUBLIC_SAMPLE_PARTIAL") + assert { + item["symbol"]: item["rows"] for item in bundle.manifest["data"]["symbol_coverage"] + } == { + "BTCUSDT": 80, + "ETHUSDT": 80, + } + assert provenance["config_sha256"] == fixture.config.hash + assert provenance["ingestion_manifest_sha256"] == (fixture.ingestion.ingestion_manifest_sha256) + assert provenance["ingestion_manifest_absolute_path"] == str( + fixture.ingestion.ingestion_manifest_path.resolve() + ) + assert fixture.ingestion.ingestion_manifest_sha256 in provenance["input_manifest_sha256"] + assert provenance["input_data_sha256"] + assert set(provenance["git"]) == {"commit", "dirty", "source_tree_sha256"} + assert len(provenance["git"]["source_tree_sha256"]) == 64 + assert provenance["execution_simulated"] is False + assert snapshot["manifest_authority"]["policy"].endswith("no directory discovery") + assert snapshot["manifest_authority"]["sha256"] == (fixture.ingestion.ingestion_manifest_sha256) + assert fixture.public.polars_trades.get_column("continuity_id").null_count() == 160 + assert bundle.quality["summary"] == {"errors": 0, "warnings": 0} + assert all( + audit["trade_ids_contiguous"] + and audit["availability_clock_nondecreasing"] + and not audit["source_rows_mutated"] + for audit in bundle.quality["aggregate_trade_continuity"] + ) + + protocol_path = fixture.run_dir / "protocol" / "PUBLIC_TRADE_PROTOCOL.md" + assert protocol_path.is_file() + assert provenance["protocol_sha256"] == sha256_file(protocol_path) + assert provenance["protocol_sha256"] == sha256_file( + fixture.config.project_root / "docs" / "PUBLIC_TRADE_PROTOCOL.md" + ) + assert provenance["run_key_inputs"]["protocol_sha256"] == provenance["protocol_sha256"] + assert bundle.manifest["artifacts"]["protocol"] == ("protocol/PUBLIC_TRADE_PROTOCOL.md") + + +def test_per_symbol_folds_are_purged_oos_and_test_never_selects( + completed_public_bundle: _CompletedFixture, +) -> None: + run_dir = completed_public_bundle.run_dir + manifest = _json(run_dir / "run_manifest.json") + for symbol in ("BTCUSDT", "ETHUSDT"): + slug = symbol.lower() + evaluation = pl.read_parquet(run_dir / "research" / slug / "evaluation_frame.parquet") + folds = _json(run_dir / "research" / slug / "folds.json") + predictions = pl.read_parquet(run_dir / "models" / slug / "predictions.parquet") + comparison = pl.read_parquet(run_dir / "models" / slug / "comparison.parquet") + selected = pl.read_parquet(run_dir / "models" / slug / "selected_test_predictions.parquet") + + assert evaluation.get_column("feature_ready").all() + assert evaluation.get_column("label_horizon_events").unique().to_list() == [2] + assert set(evaluation.get_column("continuity_id").drop_nulls().unique()) + assert all( + not name.startswith(("future_", "label_")) + for name in manifest["research"]["symbols"][symbol]["feature_columns"] + ) + + # Regression guard: serialized fold count is exactly the evaluated plan, + # not a nested/quadratically duplicated list. + validation_fold_ids = set( + comparison.filter(pl.col("split") == "validation").get_column("fold_id").unique() + ) + assert len(folds["folds"]) == len(validation_fold_ids) + assert [fold["fold_id"] for fold in folds["folds"]] == list(range(len(folds["folds"]))) + + final_train = {int(index) for index in folds["final_train_indices"]} + final_test = {int(index) for index in folds["test_indices"]} + assert final_train + assert final_test + assert final_train.isdisjoint(final_test) + indexed = evaluation.with_row_index("_research_row_id") + train_rows = indexed.filter(pl.col("_research_row_id").is_in(final_train)) + test_rows = indexed.filter(pl.col("_research_row_id").is_in(final_test)) + train_label_end = train_rows.get_column("label_information_end_ts_ns").max() + test_decision_start = test_rows.get_column("decision_ts_ns").min() + assert isinstance(train_label_end, int) + assert isinstance(test_decision_start, int) + assert train_label_end < test_decision_start + + test_predictions = predictions.filter(pl.col("split") == "test") + assert test_predictions.get_column("is_oos").all() + assert test_predictions.filter( + pl.col("fit_cutoff_ts_ns") >= pl.col("decision_ts_ns") + ).is_empty() + assert test_predictions.get_column("bootstrap_block_width_trades").unique().to_list() == [4] + assert test_predictions.filter( + (pl.col("decision_sequence") < pl.col("bootstrap_block_start_trade_id")) + | (pl.col("decision_sequence") > pl.col("bootstrap_block_end_trade_id")) + ).is_empty() + assert comparison.get_column("test_used_for_selection").not_().all() + assert set( + comparison.filter(pl.col("selected_on_validation")) + .get_column("selected_on") + .drop_nulls() + ) == {"validation"} + assert set( + comparison.filter(pl.col("split") == "test") + .get_column("bootstrap_block_policy") + .drop_nulls() + ) == {"fixed_contiguous_2x_label_horizon"} + assert selected.get_column("split").unique().to_list() == ["test"] + assert selected.get_column("requested_model").unique().to_list() == [ + manifest["research"]["symbols"][symbol]["selected_model"] + ] + + +def test_paired_hypothesis_uses_identical_test_rows_and_blocks( + completed_public_bundle: _CompletedFixture, +) -> None: + fixture = completed_public_bundle + run_dir = fixture.run_dir + manifest = _json(run_dir / "run_manifest.json") + payload = _json(run_dir / "metrics" / "hypothesis_evaluation.json") + + assert manifest["artifacts"]["hypothesis_evaluation"] == ("metrics/hypothesis_evaluation.json") + assert manifest["research"]["hypothesis_evaluation"] == { + "artifact": "metrics/hypothesis_evaluation.json", + "baseline": "historical_prior", + "caveat": payload["caveat"], + "cross_instrument_conclusion": payload["cross_instrument_conclusion"]["text"], + "cross_instrument_pooling": False, + "delta_definition": "selected_model_minus_historical_prior", + "exploratory": True, + "hypotheses": ["H0", "H1_exploratory"], + "metric": "log_loss", + "paired_on": ["row_id", "bootstrap_block"], + "per_symbol_only": True, + "persistent_alpha_claim_authorized": False, + "significance_claim_authorized": False, + } + assert payload["bootstrap"] == { + "block_policy": "fixed_contiguous_2x_label_horizon", + "block_width_trades": 4, + "ci_level": 0.95, + "method": "paired fixed-block percentile bootstrap", + "samples": fixture.config.evaluation.bootstrap_samples, + "seed_policy": "run_seed + symbol_index*100000 + 20000", + } + assert payload["cross_instrument_conclusion"]["status"] == "not_inferred" + assert payload["cross_instrument_conclusion"]["pooling_performed"] is False + assert payload["cross_instrument_conclusion"]["persistent_alpha_claim_authorized"] is False + + rows = {row["symbol"]: row for row in payload["per_symbol"]} + assert set(rows) == {"BTCUSDT", "ETHUSDT"} + identity_columns = [ + "row_id", + "y_true", + "bootstrap_block", + "bootstrap_block_start_trade_id", + "bootstrap_block_end_trade_id", + "bootstrap_block_width_trades", + "bootstrap_block_policy", + ] + for symbol_index, symbol in enumerate(fixture.config.data.symbols): + slug = symbol.lower() + predictions = pl.read_parquet(run_dir / "models" / slug / "predictions.parquet") + comparison = pl.read_parquet(run_dir / "models" / slug / "comparison.parquet") + row = rows[symbol] + selected = predictions.filter( + (pl.col("split") == "test") & (pl.col("requested_model") == row["selected_model"]) + ) + prior = predictions.filter( + (pl.col("split") == "test") & (pl.col("requested_model") == "historical_prior") + ) + + assert ( + selected.select(identity_columns) + .sort("row_id") + .equals(prior.select(identity_columns).sort("row_id")) + ) + assert selected.get_column("row_id").n_unique() == selected.height + assert selected.get_column("bootstrap_block").n_unique() == row["n_blocks"] + + direct = paired_block_bootstrap_difference( + selected, + prior, + metric="log_loss", + block_column="bootstrap_block", + n_bootstrap=fixture.config.evaluation.bootstrap_samples, + seed=fixture.config.run.seed + symbol_index * 100_000 + 20_000, + ) + + def _log_loss(frame: pl.DataFrame) -> float: + losses = [] + for truth, probability in frame.select("y_true", "probability").iter_rows(): + probability = min(max(float(probability), 1e-12), 1.0 - 1e-12) + truth = int(truth) + losses.append( + -(truth * math.log(probability) + (1 - truth) * math.log(1 - probability)) + ) + return sum(losses) / len(losses) + + manual_delta = _log_loss(selected) - _log_loss(prior) + assert row["point_delta"] == pytest.approx(manual_delta) + assert row["point_delta"] == pytest.approx(direct.point_estimate) + assert row["ci_low"] == pytest.approx(direct.lower) + assert row["ci_high"] == pytest.approx(direct.upper) + assert row["n_obs"] == selected.height == prior.height + assert row["n_blocks"] == direct.n_blocks + assert row["samples"] == direct.n_bootstrap + assert row["seed"] == direct.seed + assert row["status"] == direct.status + assert row["baseline"] == "historical_prior" + assert row["block_policy"] == "fixed_contiguous_2x_label_horizon" + assert row["favorable_direction"] == "negative_selected_minus_prior_is_favorable" + assert row["point_assessment"] in { + "favorable_point_only", + "unfavorable_point", + "point_tie", + "unavailable", + } + assert row["exploratory"] is True + assert row["significance_claim_authorized"] is False + assert row["h0_rejection_authorized"] is False + + attached = comparison.filter(pl.col("paired_metric").is_not_null()) + assert attached.height == 1 + attached_row = attached.row(0, named=True) + assert attached_row["split"] == "test" + assert attached_row["requested_model"] == row["selected_model"] + assert attached_row["paired_baseline"] == "historical_prior" + assert attached_row["paired_metric_delta"] == pytest.approx(row["point_delta"]) + assert attached_row["paired_metric_delta_ci_low"] == pytest.approx(row["ci_low"]) + assert attached_row["paired_metric_delta_ci_high"] == pytest.approx(row["ci_high"]) + assert comparison.filter(pl.col("paired_metric").is_null()).height == ( + comparison.height - 1 + ) + + for report_name in ( + "technical_report.md", + "executive_memo.md", + "model_comparison.md", + ): + report = (run_dir / "reports" / report_name).read_text(encoding="utf-8") + assert "Paired H0/H1 diagnostic" in report + assert "negative value favors the selected model" in report + assert "not p-values or confirmatory significance intervals" in report + assert "cannot support persistent alpha" in report + assert "BTCUSDT" in report + assert "ETHUSDT" in report + + +def test_trade_only_outputs_have_analysis_reports_integrity_and_no_execution_claim( + completed_public_bundle: _CompletedFixture, +) -> None: + run_dir = completed_public_bundle.run_dir + bundle = load_run_bundle(run_dir) + exclusion = _json(run_dir / "metrics" / "execution_exclusion.json") + analysis = _json(run_dir / "analysis" / "manifest.json") + + assert bundle.execution_metrics == () + assert bundle.execution_sensitivity == () + assert exclusion == { + "execution_metrics_rows": 0, + "execution_sensitivity_rows": 0, + "pnl_calculated": False, + "profitability_claim_authorized": False, + "reason": EXECUTION_EXCLUSION_REASON, + "status": "NOT_RUN", + } + assert bundle.manifest["execution_assumptions"]["status"] == "NOT_RUN" + assert bundle.manifest["execution_assumptions"]["pnl_calculated"] is False + assert not (run_dir / "execution").exists() + assert set(analysis["artifacts"]) == { + "trade_summary", + "feature_stability", + "flow_return_analysis", + } + assert analysis["descriptive_only"] is True + assert analysis["economic_claim_authorized"] is False + assert pl.read_parquet(run_dir / "analysis" / "trade_summary.parquet").height == 2 + assert pl.read_parquet(run_dir / "analysis" / "feature_stability.parquet").height > 0 + assert pl.read_parquet(run_dir / "analysis" / "flow_return_analysis.parquet").height == 2 + + for name in ("technical_report.md", "executive_memo.md", "model_comparison.md"): + rendered = (run_dir / "reports" / name).read_text(encoding="utf-8") + assert "PUBLIC SAMPLE / PARTIAL EVIDENCE" in rendered + assert EXECUTION_EXCLUSION_REASON in rendered + protected = verify_checksums(run_dir) + checksum_lines = (run_dir / "checksums.sha256").read_text(encoding="utf-8").splitlines() + assert protected == len(checksum_lines) + assert all("_SUCCESS" not in line for line in checksum_lines) + protected_paths = [run_dir / line.split(" ", 1)[1] for line in checksum_lines] + assert (run_dir / "_SUCCESS").stat().st_mtime_ns >= max( + path.stat().st_mtime_ns for path in protected_paths + ) + + +def test_explicit_manifest_digest_fails_closed_before_success( + completed_public_bundle: _CompletedFixture, tmp_path: Path +) -> None: + fixture = completed_public_bundle + stage = tmp_path / "bad-digest-stage" + + with pytest.raises(PublicDataError, match="ingestion manifest SHA-256 mismatch"): + produce_public_trade_run( + fixture.config, + stage, + ingestion_manifest_path=fixture.ingestion.ingestion_manifest_path, + ingestion_manifest_sha256="0" * 64, + ) + + assert stage.is_dir() + assert not (stage / "_SUCCESS").exists() + assert not list(stage.iterdir()) + + +def test_trade_id_gap_is_rejected_before_continuity_derivation( + completed_public_bundle: _CompletedFixture, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + fixture = completed_public_bundle + btc_ids = fixture.public.polars_trades.filter(pl.col("symbol") == "BTCUSDT").get_column( + "trade_id" + ) + pivot = int(btc_ids[40]) + gapped = fixture.public.polars_trades.with_columns( + pl.when((pl.col("symbol") == "BTCUSDT") & (pl.col("trade_id") >= pivot)) + .then(pl.col("trade_id") + 1) + .otherwise(pl.col("trade_id")) + .alias("trade_id") + ) + supplied = replace(fixture.public, polars_trades=gapped) + + def _reader( + config: ProjectConfig, + path: str | Path, + *, + ingestion_manifest_sha256: str, + ) -> PublicTrades: + del config, path, ingestion_manifest_sha256 + return supplied + + monkeypatch.setattr(public_pipeline, "read_public_trades", _reader) + with pytest.raises(PublicPipelineError, match="not contiguous"): + produce_public_trade_run( + fixture.config, + tmp_path / "gap-stage", + ingestion_manifest_path=fixture.ingestion.ingestion_manifest_path, + ingestion_manifest_sha256=fixture.ingestion.ingestion_manifest_sha256, + ) + + +def test_availability_reversal_is_rejected_before_continuity_derivation( + completed_public_bundle: _CompletedFixture, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + fixture = completed_public_bundle + btc_ids = fixture.public.polars_trades.filter(pl.col("symbol") == "BTCUSDT").get_column( + "trade_id" + ) + pivot = int(btc_ids[40]) + reversed_clock = fixture.public.polars_trades.with_columns( + pl.when((pl.col("symbol") == "BTCUSDT") & (pl.col("trade_id") == pivot)) + .then(pl.col("available_ts_ns") + 10_000_000) + .otherwise(pl.col("available_ts_ns")) + .alias("available_ts_ns") + ) + supplied = replace(fixture.public, polars_trades=reversed_clock) + + def _reader( + config: ProjectConfig, + path: str | Path, + *, + ingestion_manifest_sha256: str, + ) -> PublicTrades: + del config, path, ingestion_manifest_sha256 + return supplied + + monkeypatch.setattr(public_pipeline, "read_public_trades", _reader) + with pytest.raises(PublicPipelineError, match="availability clock reverses"): + produce_public_trade_run( + fixture.config, + tmp_path / "clock-stage", + ingestion_manifest_path=fixture.ingestion.ingestion_manifest_path, + ingestion_manifest_sha256=fixture.ingestion.ingestion_manifest_sha256, + ) + + +def test_unified_reproduce_is_atomic_idempotent_relocatable_and_manifest_bound( + unified_public_bundle: _UnifiedFixture, + tmp_path: Path, +) -> None: + fixture = unified_public_bundle + source = fixture.source + target = fixture.run_dir + checksum_before = (target / "checksums.sha256").read_bytes() + success_mtime = (target / "_SUCCESS").stat().st_mtime_ns + external_manifest_before = source.ingestion.ingestion_manifest_path.read_bytes() + + assert ( + reproduce( + source.config, + target, + ingestion_manifest_path=source.ingestion.ingestion_manifest_path, + ingestion_manifest_sha256=source.ingestion.ingestion_manifest_sha256.upper(), + ) + == target + ) + assert (target / "checksums.sha256").read_bytes() == checksum_before + assert (target / "_SUCCESS").stat().st_mtime_ns == success_mtime + + relocated = tmp_path / "relocated" / "_ingestion_manifests" / "ingestion.json" + relocated.parent.mkdir(parents=True) + shutil.copyfile(source.ingestion.ingestion_manifest_path, relocated) + assert ( + reproduce( + source.config, + target, + ingestion_manifest_path=relocated, + ingestion_manifest_sha256=source.ingestion.ingestion_manifest_sha256, + ) + == target + ) + + changed = tmp_path / "changed-ingestion.json" + changed.write_bytes(external_manifest_before + b"\n") + with pytest.raises(PipelineError, match="different ingestion manifest"): + reproduce( + source.config, + target, + ingestion_manifest_path=changed, + ingestion_manifest_sha256=sha256_file(changed), + ) + + assert source.ingestion.ingestion_manifest_path.read_bytes() == external_manifest_before + assert (target / "checksums.sha256").read_bytes() == checksum_before + assert not list(target.parent.glob(f".{target.name}.staging-*")) + + +def test_cli_reuses_verified_public_run_and_reports_scope( + unified_public_bundle: _UnifiedFixture, + capsys: pytest.CaptureFixture[str], +) -> None: + fixture = unified_public_bundle + source = fixture.source + + exit_code = main( + [ + "reproduce", + "--config", + str(source.config.path), + "--run-dir", + str(fixture.run_dir), + "--ingestion-manifest", + str(source.ingestion.ingestion_manifest_path), + "--ingestion-manifest-sha256", + source.ingestion.ingestion_manifest_sha256, + ] + ) + + assert exit_code == 0 + output = json.loads(capsys.readouterr().out) + assert output == { + "evidence_tier": "PUBLIC_SAMPLE_PARTIAL", + "observed_end_utc": load_run_bundle(fixture.run_dir).observed_end_utc, + "observed_start_utc": load_run_bundle(fixture.run_dir).observed_start_utc, + "run_dir": str(fixture.run_dir), + "run_id": source.config.run.name, + "status": "complete", + } diff --git a/Microstructure/tests/test_quality.py b/Microstructure/tests/test_quality.py new file mode 100644 index 0000000000000000000000000000000000000000..69e8a5770191a33ab5e76f7d75b6264f5e2e6b81 --- /dev/null +++ b/Microstructure/tests/test_quality.py @@ -0,0 +1,468 @@ +from __future__ import annotations + +import json +from pathlib import Path + +import pyarrow as pa # type: ignore[import-untyped] +import pytest + +from microstructure.data.book import DepthDelta, deltas_table +from microstructure.data.quality import ( + IncrementalQualityValidator, + validate_batches, + validate_table, +) +from microstructure.data.schemas import table_from_records +from microstructure.data.synthetic import generate_synthetic_market + + +def test_clean_synthetic_tables_pass_and_validation_does_not_mutate() -> None: + data = generate_synthetic_market( + symbols=("BTCUSDT",), + events_per_symbol=25, + start_ts_ns=1_704_153_600_000_000_000, + seed=14, + ) + trade_before = data.trades.to_pylist() + book_before = data.book_observations.to_pylist() + + trades = validate_table(data.trades, "trades") + books = validate_table(data.book_observations, "book_observations") + + assert not trades.has_errors + assert not books.has_errors + assert data.trades.to_pylist() == trade_before + assert data.book_observations.to_pylist() == book_before + + +def test_trade_quality_reports_duplicate_and_nonpositive_values_without_repair() -> None: + data = generate_synthetic_market( + symbols=("BTCUSDT",), + events_per_symbol=3, + start_ts_ns=1_704_153_600_000_000_000, + seed=15, + ) + records = data.trades.to_pylist() + records[1]["trade_id"] = records[0]["trade_id"] + records[1]["price_ticks"] = -1 + records[1]["price"] = -0.01 + records[2]["quantity_lots"] = 0 + records[2]["quantity"] = 0.0 + invalid = table_from_records("trades", records) + before = invalid.to_pylist() + + report = validate_table(invalid, "trades") + rule_ids = {finding.rule_id for finding in report.findings} + + assert report.has_errors + assert "trade.duplicate" in rule_ids + assert "trade.nonpositive_price" in rule_ids + assert "trade.nonpositive_quantity" in rule_ids + assert invalid.to_pylist() == before + + +def test_trade_identity_and_clock_state_are_scoped_by_venue() -> None: + data = generate_synthetic_market( + symbols=("BTCUSDT",), + events_per_symbol=2, + start_ts_ns=1_704_153_600_000_000_000, + seed=18, + ) + records = data.trades.to_pylist() + records[1]["venue"] = "second_venue" + records[1]["trade_id"] = records[0]["trade_id"] + cross_venue = table_from_records("trades", records) + + report = validate_table(cross_venue, "trades") + + assert "trade.duplicate" not in {finding.rule_id for finding in report.findings} + + +def test_book_quality_reports_sequence_gap_crossed_book_and_clock_discontinuity() -> None: + data = generate_synthetic_market( + symbols=("BTCUSDT",), + events_per_symbol=3, + start_ts_ns=1_704_153_600_000_000_000, + seed=16, + ) + records = data.book_observations.to_pylist() + records[1]["sequence_start"] = 4 + records[1]["sequence_end"] = 4 + records[1]["best_bid_ticks"] = records[1]["best_ask_ticks"] + 1 + records[1]["best_bid"] = records[1]["best_ask"] + records[1]["tick_size"] + records[1]["spread"] = records[1]["best_ask"] - records[1]["best_bid"] + records[1]["mid_price"] = (records[1]["best_bid"] + records[1]["best_ask"]) / 2 + records[1]["microprice"] = records[1]["mid_price"] + records[2]["received_ts_ns"] = records[1]["received_ts_ns"] - 1 + records[2]["available_ts_ns"] = max(records[2]["event_ts_ns"], records[2]["received_ts_ns"]) + invalid = table_from_records("book_observations", records) + + report = validate_table(invalid, "book_observations") + rule_ids = {finding.rule_id for finding in report.findings} + + assert "sequence.missing_range" in rule_ids + assert "book.crossed_or_locked" in rule_ids + assert "temporal.receive_clock_reversal" in rule_ids + + +def test_book_quality_rejects_float_values_inconsistent_with_exact_scales() -> None: + data = generate_synthetic_market( + symbols=("BTCUSDT",), + events_per_symbol=2, + start_ts_ns=1_704_153_600_000_000_000, + seed=17, + ) + records = data.book_observations.to_pylist() + records[0]["best_bid"] += records[0]["tick_size"] / 2.0 + inconsistent = table_from_records("book_observations", records) + + report = validate_table(inconsistent, "book_observations") + + assert "book.price_scale_mismatch" in {finding.rule_id for finding in report.findings} + + +def test_zero_depth_quantity_is_valid_delete_but_negative_quantity_is_error() -> None: + common = { + "venue": "binance_spot", + "symbol": "BTCUSDT", + "event_ts_ns": 1_000, + "received_ts_ns": 1_100, + "available_ts_ns": 1_100, + "availability_basis": "local_receive_time", + "capture_seq": 1, + "continuity_id": "session-1", + "first_update_id": 101, + "last_update_id": 101, + "previous_update_id": None, + "asks": (), + "tick_size": 0.01, + "lot_size": 0.001, + "source_artifact_id": "fixture", + } + delete = DepthDelta(bids=((100, 0),), **common) + negative = DepthDelta( + bids=((100, -1),), + **{**common, "event_ts_ns": 2_000, "received_ts_ns": 2_100, "available_ts_ns": 2_100}, + ) + table = deltas_table([delete, negative]) + + report = validate_table(table, "depth_deltas") + quantity_findings = [ + finding for finding in report.findings if finding.rule_id == "depth.negative_quantity" + ] + + assert len(quantity_findings) == 1 + assert quantity_findings[0].row_index == 1 + + +def test_depth_delta_quality_reports_gap_stale_and_previous_id_mismatch() -> None: + common = { + "venue": "binance_spot", + "symbol": "BTCUSDT", + "availability_basis": "local_receive_time", + "continuity_id": "session-1", + "bids": ((10_000, 1),), + "asks": (), + "tick_size": 0.01, + "lot_size": 0.001, + "source_artifact_id": "fixture", + } + deltas = [ + DepthDelta( + **common, + event_ts_ns=1_000, + received_ts_ns=1_100, + available_ts_ns=1_100, + capture_seq=1, + first_update_id=101, + last_update_id=102, + previous_update_id=None, + ), + DepthDelta( + **common, + event_ts_ns=2_000, + received_ts_ns=2_100, + available_ts_ns=2_100, + capture_seq=2, + first_update_id=105, + last_update_id=106, + previous_update_id=99, + ), + DepthDelta( + **common, + event_ts_ns=3_000, + received_ts_ns=3_100, + available_ts_ns=3_100, + capture_seq=3, + first_update_id=104, + last_update_id=105, + previous_update_id=None, + ), + ] + + report = validate_table(deltas_table(deltas), "depth_deltas") + rule_ids = {finding.rule_id for finding in report.findings} + + assert "sequence.missing_range" in rule_ids + assert "sequence.previous_id_mismatch" in rule_ids + assert "sequence.stale_or_duplicate" in rule_ids + + +def test_incremental_trade_state_crosses_batch_boundaries_with_global_indexes() -> None: + data = generate_synthetic_market( + symbols=("BTCUSDT",), + events_per_symbol=3, + start_ts_ns=1_704_153_600_000_000_000, + seed=41, + ) + records = data.trades.to_pylist() + first_event = int(records[0]["event_ts_ns"]) + first_received = int(records[0]["received_ts_ns"]) + records[1]["trade_id"] = records[0]["trade_id"] + records[1]["event_ts_ns"] = first_event - 1 + records[1]["received_ts_ns"] = first_received - 1 + records[1]["available_ts_ns"] = first_received + records[2]["event_ts_ns"] = first_event + 1_000 + records[2]["received_ts_ns"] = first_received + 1_000 + records[2]["available_ts_ns"] = first_received + 1_000 + batches = [table_from_records("trades", [record]) for record in records] + + report = validate_batches(batches, "trades", max_silence_ns=100) + by_rule = {finding.rule_id: finding for finding in report.findings} + + assert report.rows_checked == 3 + assert by_rule["trade.duplicate"].row_index == 1 + assert by_rule["trade.duplicate"].details["first_row"] == 0 + assert by_rule["temporal.out_of_order_event_time"].row_index == 1 + assert by_rule["temporal.out_of_order_event_time"].details["previous_row"] == 0 + assert by_rule["temporal.receive_clock_reversal"].row_index == 1 + assert by_rule["temporal.long_silence"].row_index == 2 + + +def test_incremental_book_sequence_gap_is_detected_across_batches() -> None: + data = generate_synthetic_market( + symbols=("BTCUSDT",), + events_per_symbol=2, + start_ts_ns=1_704_153_600_000_000_000, + seed=42, + ) + records = data.book_observations.to_pylist() + records[1]["sequence_start"] = int(records[0]["sequence_end"]) + 2 + records[1]["sequence_end"] = records[1]["sequence_start"] + + report = validate_batches( + ( + table_from_records("book_observations", [records[0]]), + table_from_records("book_observations", [records[1]]), + ), + "book_observations", + ) + gaps = [finding for finding in report.findings if finding.rule_id == "sequence.missing_range"] + + assert len(gaps) == 1 + assert gaps[0].row_index == 1 + assert gaps[0].details == { + "expected_sequence": int(records[0]["sequence_end"]) + 1, + "observed_start": records[1]["sequence_start"], + "missing_start": int(records[0]["sequence_end"]) + 1, + "missing_end": int(records[0]["sequence_end"]) + 1, + } + + +def test_incremental_depth_sequence_and_previous_hint_cross_batches() -> None: + common = { + "venue": "binance_spot", + "symbol": "BTCUSDT", + "availability_basis": "local_receive_time", + "continuity_id": "session-1", + "bids": ((10_000, 1),), + "asks": (), + "tick_size": 0.01, + "lot_size": 0.001, + "source_artifact_id": "fixture", + } + first = DepthDelta( + **common, + event_ts_ns=1_000, + received_ts_ns=1_100, + available_ts_ns=1_100, + capture_seq=1, + first_update_id=101, + last_update_id=102, + previous_update_id=None, + ) + second = DepthDelta( + **common, + event_ts_ns=2_000, + received_ts_ns=2_100, + available_ts_ns=2_100, + capture_seq=2, + first_update_id=105, + last_update_id=106, + previous_update_id=99, + ) + + report = validate_batches( + (deltas_table([first]), deltas_table([second])), + "depth_deltas", + ) + rules = {finding.rule_id: finding for finding in report.findings} + + assert rules["sequence.missing_range"].row_index == 1 + assert rules["sequence.previous_id_mismatch"].row_index == 1 + + +def test_incremental_state_is_isolated_by_venue_across_batches() -> None: + data = generate_synthetic_market( + symbols=("BTCUSDT",), + events_per_symbol=2, + start_ts_ns=1_704_153_600_000_000_000, + seed=43, + ) + records = data.trades.to_pylist() + records[1]["venue"] = "second_venue" + records[1]["trade_id"] = records[0]["trade_id"] + records[1]["event_ts_ns"] = int(records[0]["event_ts_ns"]) - 1 + records[1]["received_ts_ns"] = int(records[0]["received_ts_ns"]) - 1 + records[1]["available_ts_ns"] = records[0]["available_ts_ns"] + + report = validate_batches( + (table_from_records("trades", [record]) for record in records), + "trades", + ) + rule_ids = {finding.rule_id for finding in report.findings} + + assert "trade.duplicate" not in rule_ids + assert "temporal.out_of_order_event_time" not in rule_ids + assert "temporal.receive_clock_reversal" not in rule_ids + + +class _OneShotBatches: + def __init__(self, batches: list[pa.Table | pa.RecordBatch]) -> None: + self._batches = batches + self.iterations = 0 + + def __iter__(self): # type: ignore[no-untyped-def] + self.iterations += 1 + if self.iterations > 1: + raise AssertionError("batch iterable was consumed more than once") + yield from self._batches + + +def test_validate_batches_consumes_one_shot_iterable_once_and_accepts_record_batches() -> None: + data = generate_synthetic_market( + symbols=("BTCUSDT",), + events_per_symbol=4, + start_ts_ns=1_704_153_600_000_000_000, + seed=44, + ) + batches = _OneShotBatches(list(data.trades.to_batches(max_chunksize=1))) + + report = validate_batches(batches, "trades", row_chunk_size=1) + + assert batches.iterations == 1 + assert report.rows_checked == data.trades.num_rows + assert not report.has_errors + + +def test_incremental_bounded_preview_keeps_exact_totals_and_streams_all_jsonl( + tmp_path: Path, +) -> None: + data = generate_synthetic_market( + symbols=("BTCUSDT",), + events_per_symbol=12, + start_ts_ns=1_704_153_600_000_000_000, + seed=45, + ) + records = data.trades.to_pylist() + for record in records: + record["price_ticks"] = -1 + record["price"] = -float(record["tick_size"]) + invalid = table_from_records("trades", records) + before = invalid.to_pylist() + findings_path = tmp_path / "quality" / "findings.jsonl" + + report = validate_batches( + invalid.to_batches(max_chunksize=2), + "trades", + max_findings=3, + findings_jsonl_path=findings_path, + row_chunk_size=1, + ) + summary_path = tmp_path / "quality" / "summary.json" + report.write_json(summary_path) + streamed = [json.loads(line) for line in findings_path.read_text().splitlines()] + summary = json.loads(summary_path.read_text()) + + assert invalid.to_pylist() == before + assert report.error_count == len(records) + assert report.warning_count == 0 + assert report.has_errors + assert report.findings_truncated + assert len(report.findings) == 3 + assert len(streamed) == len(records) + assert [item["row_index"] for item in streamed] == list(range(len(records))) + assert summary["summary"] == {"errors": len(records), "warnings": 0} + assert summary["findings_preview"] == { + "retained": 3, + "total": len(records), + "truncated": True, + } + assert summary["findings_jsonl_path"] == str(findings_path.resolve()) + assert len(summary["findings"]) == 3 + + +def test_incremental_findings_publish_atomically_and_preserve_prior_on_abort( + tmp_path: Path, +) -> None: + findings_path = tmp_path / "quality" / "findings.jsonl" + findings_path.parent.mkdir(parents=True) + findings_path.write_text("prior-complete-evidence\n", encoding="utf-8") + validator = IncrementalQualityValidator( + "trades", + findings_jsonl_path=findings_path, + ) + + validator.close() + + assert findings_path.read_text(encoding="utf-8") == "prior-complete-evidence\n" + assert not list(findings_path.parent.glob(f".{findings_path.name}.*.tmp")) + + +def test_incremental_finish_is_idempotent_and_update_after_finish_fails() -> None: + data = generate_synthetic_market( + symbols=("BTCUSDT",), + events_per_symbol=2, + start_ts_ns=1_704_153_600_000_000_000, + seed=46, + ) + validator = IncrementalQualityValidator("trades", max_findings=0) + validator.update(data.trades) + + first = validator.finish() + + assert validator.finish() is first + with pytest.raises(RuntimeError, match="already closed"): + validator.update(data.trades) + + +def test_validate_batches_matches_unbounded_table_rule_semantics() -> None: + data = generate_synthetic_market( + symbols=("BTCUSDT",), + events_per_symbol=3, + start_ts_ns=1_704_153_600_000_000_000, + seed=47, + ) + records = data.trades.to_pylist() + records[1]["trade_id"] = records[0]["trade_id"] + records[2]["quantity_lots"] = 0 + records[2]["quantity"] = 0.0 + invalid = table_from_records("trades", records) + + legacy = validate_table(invalid, "trades") + incremental = validate_batches([invalid], "trades", max_findings=None) + + assert incremental.rows_checked == legacy.rows_checked + assert incremental.error_count == legacy.error_count + assert incremental.warning_count == legacy.warning_count + assert incremental.findings == legacy.findings diff --git a/Microstructure/tests/test_reporting.py b/Microstructure/tests/test_reporting.py new file mode 100644 index 0000000000000000000000000000000000000000..d0b3c68394ea645866c6bad4479bb1fbc9cf5753 --- /dev/null +++ b/Microstructure/tests/test_reporting.py @@ -0,0 +1,622 @@ +from __future__ import annotations + +import json +import os +import stat +from pathlib import Path +from typing import Any + +import pytest + +from microstructure.reporting import ( + ChecksumMismatchError, + IncompleteRunError, + RunBundleValidationError, + comparison_rows, + load_run_bundle, + render_executive_memo, + render_model_comparison, + render_technical_report, + write_checksum_manifest, + write_report_set, +) + +PROJECT_ROOT = Path(__file__).parents[1] + + +def _write_json(path: Path, payload: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8") + + +def _build_bundle( + root: Path, + *, + evidence_tier: str = "SYNTHETIC_SMOKE", + data_mode: str = "synthetic", + data_source: str = "synthetic_fixture_v1", + finalize: bool = True, +) -> Path: + manifest = { + "artifacts": { + "execution_metrics": "metrics/execution_metrics.json", + "execution_sensitivity": "metrics/execution_sensitivity.json", + "market_state": "dashboard/market_state.json", + "predictive_metrics": "metrics/predictive_metrics.json", + "quality_summary": "quality/summary.json", + }, + "data": { + "mode": data_mode, + "observed_end_utc": "2024-01-02T00:10:00Z", + "observed_start_utc": "2024-01-02T00:00:00Z", + "source": data_source, + "symbols": ["BTCUSDT", "ETHUSDT"], + }, + "evidence_tier": evidence_tier, + "execution_assumptions": { + "decision_latency_events": 1, + "taker_fee_bps": 4.0, + }, + "run_id": "unit-smoke", + "schema_version": "1.0.0", + "status": "complete", + } + provenance = { + "config_sha256": "a" * 64, + "evidence_tier": evidence_tier, + "generated_at_utc": "2026-08-07T12:00:00Z", + "git": {"commit": "UNBORN", "dirty": True}, + "input_manifest_sha256": ["b" * 64], + "runtime": {"machine": "test", "python": "3.12.0"}, + "seed": 7, + } + predictive = [ + { + "brier_score": 0.25, + "expected_calibration_error": 0.1, + "horizon_events": 20, + "instrument": "BTCUSDT", + "log_loss": 0.6931, + "model": "majority", + "n_obs": 200, + "period_end_utc": "2024-01-02T00:10:00Z", + "period_start_utc": "2024-01-02T00:08:00Z", + "pr_auc": 0.5, + "roc_auc": 0.5, + "roc_auc_ci_high": 0.55, + "roc_auc_ci_low": 0.45, + "selected_on": "validation:log_loss", + "split": "test", + }, + { + "instrument": "BTCUSDT", + "model": "validation-only-model", + "roc_auc": 0.99, + "split": "validation", + }, + { + "instrument": "BTCUSDT", + "model": "unsplit-model", + "roc_auc": 0.999, + }, + ] + execution = [ + { + "fees_bps": 4.0, + "fill_rate": 0.6, + "gross_bps": 1.0, + "horizon_events": 20, + "instrument": "BTCUSDT", + "max_drawdown": -2.0, + "model": "majority", + "net_bps": -3.0, + "split": "test", + "turnover": 8.0, + } + ] + _write_json(root / "run_manifest.json", manifest) + _write_json(root / "provenance.json", provenance) + _write_json(root / "metrics" / "predictive_metrics.json", predictive) + _write_json(root / "metrics" / "execution_metrics.json", execution) + _write_json( + root / "metrics" / "execution_sensitivity.json", + [ + { + "order_type": "market", + "size_multiplier": 1.0, + "net_pnl": -0.5, + "net_edge_bps": -3.0, + "fill_ratio": 1.0, + "turnover_notional": 8.0, + "maximum_drawdown": 0.5, + } + ], + ) + _write_json(root / "dashboard" / "market_state.json", [{"spread_bps": 2.0}]) + _write_json(root / "quality" / "summary.json", {"error_count": 0, "warning_count": 1}) + if finalize: + write_checksum_manifest(root) + (root / "_SUCCESS").write_text("", encoding="utf-8") + return root + + +def test_rendering_is_deterministic_held_out_only_and_watermarked(tmp_path: Path) -> None: + bundle = load_run_bundle(_build_bundle(tmp_path / "run")) + + first = render_technical_report(bundle) + second = render_technical_report(bundle) + table = render_model_comparison(bundle) + + assert first == second + assert "SYNTHETIC SMOKE — SOFTWARE VALIDATION ONLY" in first + assert "2024-01-02T00:00:00Z" in first + assert "Configuration SHA-256" in first + assert "UNBORN" in first + assert "Runtime metadata" in first + assert "Seed" in first + assert "0.5000 [0.4500, 0.5500]" in table + assert "0.2500" in table + assert "0.1000" in table + assert "-3.000" in table + assert "Configuration SHA-256" in table + assert "Input manifest SHA-256" in table + assert "Git commit" in table + assert "Execution sensitivity" in first + assert "size_multiplier" in first + assert len(bundle.execution_sensitivity) == 1 + assert "validation-only-model" not in table + assert "unsplit-model" not in table + assert len(comparison_rows(bundle)) == 1 + + +def test_report_set_is_written_outside_frozen_bundle(tmp_path: Path) -> None: + run_dir = _build_bundle(tmp_path / "run") + checksum_before = (run_dir / "checksums.sha256").read_bytes() + bundle = load_run_bundle(run_dir) + + paths = write_report_set(bundle, tmp_path / "published") + + assert paths.technical_report.is_file() + assert paths.executive_memo.is_file() + assert paths.model_comparison.is_file() + memo = paths.executive_memo.read_text(encoding="utf-8") + comparison = paths.model_comparison.read_text(encoding="utf-8") + assert "a" * 64 in memo + assert "b" * 64 in memo + assert "UNBORN" in memo + assert "a" * 64 in comparison + assert "b" * 64 in comparison + assert "UNBORN" in comparison + assert (run_dir / "checksums.sha256").read_bytes() == checksum_before + assert load_run_bundle(run_dir).run_id == "unit-smoke" + + +def test_incomplete_and_tampered_bundles_fail_clearly(tmp_path: Path) -> None: + incomplete = _build_bundle(tmp_path / "incomplete", finalize=False) + with pytest.raises(IncompleteRunError, match="_SUCCESS"): + load_run_bundle(incomplete) + + tampered = _build_bundle(tmp_path / "tampered") + (tampered / "quality" / "summary.json").write_text("{}\n", encoding="utf-8") + with pytest.raises(ChecksumMismatchError, match="checksum mismatch"): + load_run_bundle(tampered) + + +def test_checksum_manifest_fsyncs_file_before_replace_and_parent_directory( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + root = tmp_path / "durable-checksums" + root.mkdir() + (root / "artifact.txt").write_text("evidence\n", encoding="utf-8") + events: list[str] = [] + original_fsync = os.fsync + original_replace = os.replace + + def fsync(descriptor: int) -> None: + mode = os.fstat(descriptor).st_mode + events.append("fsync_directory" if stat.S_ISDIR(mode) else "fsync_file") + original_fsync(descriptor) + + def replace( + source: str | bytes | os.PathLike[str] | os.PathLike[bytes], + destination: str | bytes | os.PathLike[str] | os.PathLike[bytes], + ) -> None: + events.append("replace") + original_replace(source, destination) + + monkeypatch.setattr(os, "fsync", fsync) + monkeypatch.setattr(os, "replace", replace) + write_checksum_manifest(root) + assert events == ["fsync_file", "replace", "fsync_directory"] + + +def test_complete_bundle_rejects_conflicting_insufficient_marker(tmp_path: Path) -> None: + complete = _build_bundle(tmp_path / "conflicting-terminal") + (complete / "INSUFFICIENT_DATA").write_text("terminal\n", encoding="utf-8") + with pytest.raises(IncompleteRunError, match="conflicting"): + load_run_bundle(complete) + + +def test_synthetic_source_cannot_be_promoted_to_public_evidence(tmp_path: Path) -> None: + run_dir = _build_bundle( + tmp_path / "laundered", + evidence_tier="PUBLIC_SAMPLE_PARTIAL", + data_mode="synthetic", + data_source="synthetic_fixture_v1", + ) + with pytest.raises(RunBundleValidationError, match="cannot be promoted"): + load_run_bundle(run_dir) + + +def test_full_data_requires_manifested_complete_coverage(tmp_path: Path) -> None: + run_dir = _build_bundle( + tmp_path / "incomplete_full_data", + evidence_tier="FULL_DATA", + data_mode="binance_rest", + data_source="binance_spot_public_rest", + ) + + with pytest.raises(RunBundleValidationError, match="complete coverage"): + load_run_bundle(run_dir) + + +def test_public_bundle_requires_manifested_input_identity(tmp_path: Path) -> None: + run_dir = _build_bundle( + tmp_path / "missing-input", + evidence_tier="PUBLIC_SAMPLE_PARTIAL", + data_mode="binance_rest", + data_source="binance_spot_public_rest", + finalize=False, + ) + provenance_path = run_dir / "provenance.json" + provenance = json.loads(provenance_path.read_text(encoding="utf-8")) + provenance["input_manifest_sha256"] = [] + _write_json(provenance_path, provenance) + write_checksum_manifest(run_dir) + (run_dir / "_SUCCESS").write_text("complete\n", encoding="utf-8") + + with pytest.raises(RunBundleValidationError, match="at least one input manifest"): + load_run_bundle(run_dir) + + +def test_public_trade_only_report_uses_manifest_scope_and_excludes_execution( + tmp_path: Path, +) -> None: + run_dir = _build_bundle( + tmp_path / "public-trade-only", + evidence_tier="PUBLIC_SAMPLE_PARTIAL", + data_mode="binance_rest_trade_only", + data_source="binance_spot_public_rest", + finalize=False, + ) + manifest_path = run_dir / "run_manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + question = "Do signed aggregate trades predict future trade-price direction?" + exclusion_reason = "Trade-only data contain no quotes, depth, or queue state." + manifest["research"] = {"question": question} + manifest["data"]["symbol_coverage"] = [ + { + "symbol": "BTCUSDT", + "rows": 5_000, + "observed_start_utc": "2024-01-02T00:00:00Z", + "observed_end_inclusive_utc": "2024-01-02T00:01:53.619000Z", + "complete_range": False, + }, + { + "symbol": "ETHUSDT", + "rows": 5_000, + "observed_start_utc": "2024-01-02T00:00:00Z", + "observed_end_inclusive_utc": "2024-01-02T00:06:49.796000Z", + "complete_range": False, + }, + ] + manifest["execution_assumptions"] = { + "status": "NOT_RUN", + "reason": exclusion_reason, + "pnl_calculated": False, + "fills_calculated": False, + } + manifest["artifacts"]["hypothesis_evaluation"] = "metrics/hypothesis_evaluation.json" + _write_json(manifest_path, manifest) + _write_json( + run_dir / "metrics" / "hypothesis_evaluation.json", + { + "selection_metric": "log_loss", + "caveat": ("Exploratory paired interval only; no significance claim is authorized."), + "cross_instrument_conclusion": { + "status": "not_inferred", + "text": "BTCUSDT and ETHUSDT are not pooled.", + }, + "per_symbol": [ + { + "symbol": "BTCUSDT", + "selected_model": "logistic_l2_c1", + "baseline": "historical_prior", + "metric": "log_loss", + "point_delta": -0.012345, + "ci_low": -0.02, + "ci_high": 0.003, + "n_obs": 400, + "n_blocks": 10, + "samples": 500, + "seed": 20280807, + "status": "ok", + "favorable_direction": "negative_selected_minus_prior_is_favorable", + }, + { + "symbol": "ETHUSDT", + "selected_model": "shallow_tree_d2_leaf25", + "baseline": "historical_prior", + "metric": "log_loss", + "point_delta": 0.006789, + "ci_low": -0.004, + "ci_high": 0.018, + "n_obs": 400, + "n_blocks": 10, + "samples": 500, + "seed": 20380807, + "status": "ok", + "favorable_direction": "negative_selected_minus_prior_is_favorable", + }, + ], + }, + ) + _write_json(run_dir / "metrics" / "execution_metrics.json", []) + _write_json(run_dir / "metrics" / "execution_sensitivity.json", []) + write_checksum_manifest(run_dir) + (run_dir / "_SUCCESS").write_text("complete\n", encoding="utf-8") + + bundle = load_run_bundle(run_dir) + technical = render_technical_report(bundle) + memo = render_executive_memo(bundle) + published = write_report_set(bundle, tmp_path / "published-public-trade-only") + + assert bundle.execution_metrics == () + assert bundle.execution_sensitivity == () + assert len(bundle.hypothesis_evaluation["per_symbol"]) == 2 + assert question in technical + assert "### Per-symbol observed coverage" in technical + assert "| BTCUSDT | 5000 |" in technical + assert "2024-01-02T00:01:53.619000Z" in technical + assert "| ETHUSDT | 5000 |" in technical + assert "2024-01-02T00:06:49.796000Z" in technical + assert ( + "| BTCUSDT | 5000 | 2024-01-02T00:00:00Z | 2024-01-02T00:01:53.619000Z | false |" + ) in technical + assert ( + "| ETHUSDT | 5000 | 2024-01-02T00:00:00Z | 2024-01-02T00:06:49.796000Z | false |" + ) in technical + assert "Execution simulation and P&L were not run" in technical + assert "Execution sensitivity was not run" in technical + assert exclusion_reason in technical + assert "conditional on these assumptions" not in technical + assert "This scenario grid changes" not in technical + assert "Execution simulation, fills, execution sensitivity, and P&L were not run" in memo + assert exclusion_reason in memo + assert "simulated strategy outcomes" not in memo + assert "Simulated fills do not prove" not in memo + for rendered in ( + technical, + memo, + published.technical_report.read_text(encoding="utf-8"), + published.executive_memo.read_text(encoding="utf-8"), + published.model_comparison.read_text(encoding="utf-8"), + ): + assert "Paired H0/H1 diagnostic" in rendered + assert "negative value favors the selected model" in rendered + assert "BTCUSDT" in rendered + assert "-0.012345" in rendered + assert "ETHUSDT" in rendered + assert "0.006789" in rendered + assert "not p-values or confirmatory significance intervals" in rendered + assert "cannot support persistent alpha" in rendered + + +def test_m8_full_archive_report_preserves_date_components_and_narrow_scope( + tmp_path: Path, +) -> None: + run_dir = _build_bundle( + tmp_path / "m8-trade-only", + evidence_tier="FULL_DATA", + data_mode="binance_spot_daily_aggtrades_trade_only", + data_source="binance_spot_daily_aggtrades_archive", + finalize=False, + ) + manifest_path = run_dir / "run_manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + manifest["data"]["all_requested_ranges_complete"] = True + manifest["data"]["date_coverage"] = [ + { + "symbol": "BTCUSDT", + "date": "2024-01-05", + "role": "primary_test", + "rows": 100, + "observed_start_utc": "2024-01-05T00:00:00Z", + "observed_end_inclusive_utc": "2024-01-05T23:59:59.999000Z", + "complete": True, + "quality_errors": 0, + "quality_warnings": 0, + }, + { + "symbol": "BTCUSDT", + "date": "2024-01-06", + "role": "replication_test", + "rows": 120, + "observed_start_utc": "2024-01-06T00:00:00Z", + "observed_end_inclusive_utc": "2024-01-06T23:59:59.999000Z", + "complete": True, + "quality_errors": 0, + "quality_warnings": 0, + }, + ] + manifest["research"] = { + "scope": "trade_only", + "question": "Does the locked trade-only model improve next-20-trade log loss?", + } + manifest["execution_assumptions"] = { + "status": "NOT_RUN", + "reason": "No contemporaneous order book or local receipt clock.", + } + manifest["artifacts"]["hypothesis_evaluation"] = "metrics/hypothesis_evaluation.json" + _write_json(manifest_path, manifest) + _write_json(run_dir / "metrics" / "execution_metrics.json", []) + _write_json(run_dir / "metrics" / "execution_sensitivity.json", []) + _write_json( + run_dir / "metrics" / "predictive_metrics.json", + [ + { + "instrument": "BTCUSDT", + "model": "tree_depth_2", + "horizon_events": 20, + "split": "final_test", + "study_date": "2024-01-05", + "n_obs": 100, + "period_start_utc": "2024-01-05T00:00:00Z", + "period_end_utc": "2024-01-05T23:59:59.999000Z", + "log_loss": 0.61, + }, + { + "instrument": "BTCUSDT", + "model": "tree_depth_2", + "horizon_events": 20, + "split": "final_test", + "study_date": "2024-01-06", + "n_obs": 120, + "period_start_utc": "2024-01-06T00:00:00Z", + "period_end_utc": "2024-01-06T23:59:59.999000Z", + "log_loss": 0.65, + }, + ], + ) + _write_json( + run_dir / "metrics" / "hypothesis_evaluation.json", + { + "schema_version": "1.0.0", + "evidence_scope": "trade_only_complete_predeclared_daily_archives", + "selection_metric": "log_loss", + "caveat": "No p-values, H0 rejection, or significance claim is authorized.", + "cross_instrument_conclusion": { + "text": "BTCUSDT and ETHUSDT remain separate; no pooling is authorized." + }, + "per_date": [ + { + "symbol": "BTCUSDT", + "study_date": "2024-01-05", + "study_role": "primary_test", + "selected_model": "tree_depth_2", + "baseline": "historical_prior", + "selected_log_loss": 0.61, + "prior_log_loss": 0.64, + "point_delta": -0.03, + "ci_low": -0.05, + "ci_high": -0.01, + "n_obs": 100, + "n_blocks": 3, + "bootstrap_status": "ok", + }, + { + "symbol": "BTCUSDT", + "study_date": "2024-01-06", + "study_role": "replication_test", + "selected_model": "tree_depth_2", + "baseline": "historical_prior", + "selected_log_loss": 0.65, + "prior_log_loss": 0.64, + "point_delta": 0.01, + "ci_low": -0.02, + "ci_high": 0.04, + "n_obs": 120, + "n_blocks": 3, + "bootstrap_status": "ok", + }, + ], + "per_symbol": [ + { + "symbol": "BTCUSDT", + "selected_model": "tree_depth_2", + "baseline": "historical_prior", + "point_delta": -0.01, + "ci_low": -0.03, + "ci_high": 0.02, + "n_dates": 2, + "n_obs": 220, + "n_blocks": 6, + "status": "mixed", + "replication_status": "mixed", + "validation_date": "2024-01-04", + "validation_point_delta": -0.02, + "primary_date": "2024-01-05", + "primary_point_delta": -0.03, + "replication_date": "2024-01-06", + "replication_point_delta": 0.01, + "direction_consistent_across_validation_primary_replication": False, + "favorable_across_validation_primary_replication": False, + "validation_primary_replication_status": "mixed", + } + ], + }, + ) + write_checksum_manifest(run_dir) + (run_dir / "_SUCCESS").write_text("complete\n", encoding="utf-8") + + bundle = load_run_bundle(run_dir) + technical = render_technical_report(bundle) + memo = render_executive_memo(bundle) + published = write_report_set(bundle, tmp_path / "m8-published") + held_out_rows = comparison_rows(bundle) + + assert len(held_out_rows) == 2 + assert {row["study_date"] for row in held_out_rows} == {"2024-01-05", "2024-01-06"} + assert "### Per-date observed coverage" in technical + assert "M8 predeclared multi-date endpoint" in technical + assert "2024-01-05" in technical and "2024-01-06" in technical + assert "-0.030000" in technical and "0.010000" in technical + assert "Equal-date-weighted endpoint" in technical + assert "Validation → primary → replication direction consistency" in technical + assert "2024-01-04" in technical + assert "mixed" in technical + assert "not to full market observability" in technical + assert "contains no order-book, execution, P&L, capacity" in memo + for path in ( + published.technical_report, + published.executive_memo, + published.model_comparison, + ): + regenerated = path.read_text(encoding="utf-8") + assert "M8 predeclared multi-date endpoint" in regenerated + assert "2024-01-05" in regenerated and "2024-01-06" in regenerated + assert "No p-values, H0 rejection, or significance claim is authorized" in regenerated + + +def test_manifest_and_provenance_run_keys_must_match(tmp_path: Path) -> None: + run_dir = _build_bundle(tmp_path / "mismatched-run-key", finalize=False) + manifest_path = run_dir / "run_manifest.json" + provenance_path = run_dir / "provenance.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + provenance = json.loads(provenance_path.read_text(encoding="utf-8")) + manifest["run_key"] = "c" * 64 + provenance["run_key"] = "d" * 64 + _write_json(manifest_path, manifest) + _write_json(provenance_path, provenance) + write_checksum_manifest(run_dir) + (run_dir / "_SUCCESS").write_text("complete\n", encoding="utf-8") + + with pytest.raises(RunBundleValidationError, match="run keys do not match"): + load_run_bundle(run_dir) + + +def test_canonical_documents_make_no_unrun_performance_claim() -> None: + technical = (PROJECT_ROOT / "reports" / "technical_report.md").read_text(encoding="utf-8") + comparison = (PROJECT_ROOT / "reports" / "model_comparison.md").read_text(encoding="utf-8") + memo = (PROJECT_ROOT / "reports" / "executive_memo.md").read_text(encoding="utf-8") + resume = (PROJECT_ROOT / "portfolio" / "resume_bullets.md").read_text(encoding="utf-8") + + assert "SOURCE-CONTROLLED TEMPLATE" in technical + assert "manually copied empirical or synthetic performance results" in technical + assert "no copied model or execution numbers" in comparison + assert memo.count("page-break-after: always") == 1 + assert "Authorize no capital" in memo + assert "## Research-focused" in resume + assert "## Quant-trading-focused" in resume + assert "## Data-engineering-focused" in resume diff --git a/Microstructure/tests/test_schemas.py b/Microstructure/tests/test_schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..0aa55285e5b15036573e0e873298dcd60921e021 --- /dev/null +++ b/Microstructure/tests/test_schemas.py @@ -0,0 +1,86 @@ +from __future__ import annotations + +import pyarrow as pa +import pytest + +from microstructure.data.schemas import SCHEMA_VERSION, SchemaError, ensure_schema, get_schema +from microstructure.data.synthetic import generate_synthetic_market + + +def test_normalized_schemas_publish_temporal_and_numeric_contracts() -> None: + trades = get_schema("trades") + books = get_schema("book_observations") + + assert trades.metadata is not None + assert trades.metadata[b"schema_version"] == SCHEMA_VERSION.encode() + assert trades.field("event_ts_ns").type == pa.int64() + assert trades.field("available_ts_ns").type == pa.int64() + assert trades.field("price_ticks").type == pa.int64() + assert trades.field("quantity_lots").type == pa.int64() + assert books.field("best_bid_ticks").type == pa.int64() + assert books.field("continuity_id").type == pa.string() + + +def test_schema_registry_fails_closed_on_unknown_name_or_version() -> None: + with pytest.raises(SchemaError, match="unknown normalized schema"): + get_schema("mystery") + with pytest.raises(SchemaError, match="unsupported schema version"): + get_schema("trades", "2.0.0") + + +def test_synthetic_generator_is_deterministic_and_explicitly_labelled() -> None: + kwargs = { + "symbols": ("BTCUSDT", "ETHUSDT"), + "events_per_symbol": 20, + "start_ts_ns": 1_704_153_600_000_000_000, + "seed": 123, + } + first = generate_synthetic_market(**kwargs) + second = generate_synthetic_market(**kwargs) + changed = generate_synthetic_market(**{**kwargs, "seed": 124}) + + assert first.evidence_tier == "SYNTHETIC_SMOKE" + assert first.trades.equals(second.trades) + assert first.book_observations.equals(second.book_observations) + assert not first.trades.equals(changed.trades) + assert first.trades.schema.equals(get_schema("trades"), check_metadata=True) + assert first.book_observations.schema.equals( + get_schema("book_observations"), check_metadata=True + ) + assert set(first.trades.column("venue").to_pylist()) == {"synthetic"} + assert first.trades.num_rows == 40 + + +def test_synthetic_information_clock_never_precedes_event_or_receipt() -> None: + data = generate_synthetic_market( + symbols=("BTCUSDT",), + events_per_symbol=10, + start_ts_ns=1_704_153_600_000_000_000, + seed=7, + ) + for table in (data.trades, data.book_observations): + for row in table.to_pylist(): + assert row["available_ts_ns"] >= row["event_ts_ns"] + assert row["available_ts_ns"] >= row["received_ts_ns"] + assert row["availability_basis"] == "synthetic_receipt" + + +def test_schema_validation_rejects_mislabeled_row_or_metadata_version() -> None: + table = generate_synthetic_market( + symbols=("BTCUSDT",), + events_per_symbol=2, + start_ts_ns=1_704_153_600_000_000_000, + seed=8, + ).trades + records = table.to_pylist() + records[0]["schema_version"] = "2.0.0" + mislabeled = pa.Table.from_pylist(records, schema=table.schema) + + with pytest.raises(SchemaError, match="row schema_version mismatch"): + ensure_schema(mislabeled, "trades") + + bad_metadata = table.replace_schema_metadata( + {**(table.schema.metadata or {}), b"schema_version": b"2.0.0"} + ) + with pytest.raises(SchemaError, match="metadata version mismatch"): + ensure_schema(bad_metadata, "trades") diff --git a/Microstructure/tests/test_splits.py b/Microstructure/tests/test_splits.py new file mode 100644 index 0000000000000000000000000000000000000000..89376d8e3564441b59725f99487bf64a6d9ca88d --- /dev/null +++ b/Microstructure/tests/test_splits.py @@ -0,0 +1,112 @@ +from __future__ import annotations + +import polars as pl +import pytest + +from microstructure.config import EvaluationConfig +from microstructure.research.splits import SplitError, expanding_walk_forward_splits + + +def _config(*, embargo: int = 2) -> EvaluationConfig: + return EvaluationConfig( + min_train_events=6, + validation_events=3, + test_events=3, + step_events=3, + embargo_events=embargo, + bootstrap_samples=50, + calibration_bins=5, + ) + + +def _interval_frame(rows: int = 16) -> pl.DataFrame: + decision = list(range(rows)) + censored = [index + 2 >= rows for index in decision] + return pl.DataFrame( + { + "symbol": ["BTCUSDT"] * rows, + "decision_ts_ns": decision, + "label_information_end_ts_ns": [ + None if is_censored else index + 2 + for index, is_censored in zip(decision, censored, strict=True) + ], + "right_censored": censored, + } + ) + + +def test_expanding_folds_purge_overlap_and_apply_embargo() -> None: + frame = _interval_frame() + plan = expanding_walk_forward_splits(frame, _config()) + + assert len(plan.folds) == 2 + first = plan.folds[0] + assert first.validation_start_ts_ns == 6 + assert first.validation_end_ts_ns == 8 + assert first.train_indices.tolist() == [0, 1, 2, 3] + assert first.validation_indices.tolist() == [6, 7, 8] + assert first.purged_rows == 2 + assert first.embargoed_time_buckets == 2 + + second = plan.folds[1] + assert second.train_indices.tolist() == list(range(7)) + assert second.validation_indices.tolist() == [9, 10] + assert set(first.train_indices).issubset(set(second.train_indices)) + + for fold in plan.folds: + train = frame[fold.train_indices] + validation = frame[fold.validation_indices] + assert train.get_column("label_information_end_ts_ns").max() < fold.validation_start_ts_ns + assert validation.get_column("label_information_end_ts_ns").max() < plan.test_start_ts_ns + assert fold.train_end_ts_ns < fold.validation_start_ts_ns + + +def test_final_period_is_frozen_and_never_enters_development() -> None: + plan = expanding_walk_forward_splits(_interval_frame(), _config()) + assert plan.test_start_ts_ns == 13 + assert plan.test_end_ts_ns == 15 + # The final two decisions are censored; only t=13 has a complete two-event target. + assert plan.test_indices.tolist() == [13] + development_validation = { + int(index) for fold in plan.folds for index in fold.validation_indices + } + assert development_validation.isdisjoint(set(plan.test_indices)) + assert max(plan.final_train_indices) < min(plan.test_indices) + + +def test_validation_labels_cannot_end_inside_final_test() -> None: + frame = _interval_frame(rows=50) + config = EvaluationConfig( + min_train_events=20, + validation_events=10, + test_events=10, + step_events=10, + embargo_events=2, + bootstrap_samples=50, + calibration_bins=5, + ) + plan = expanding_walk_forward_splits(frame, config) + + assert plan.test_start_ts_ns == 40 + last_validation = frame.with_row_index("row_id").filter( + pl.col("row_id").is_in(plan.folds[-1].validation_indices) + ) + assert last_validation.get_column("decision_ts_ns").to_list() == list(range(30, 38)) + assert last_validation.get_column("label_information_end_ts_ns").max() < plan.test_start_ts_ns + + +def test_same_timestamp_instruments_stay_in_the_same_fold() -> None: + base = _interval_frame() + eth = base.with_columns(pl.lit("ETHUSDT").alias("symbol")) + pooled = pl.concat([base, eth]).sort(["decision_ts_ns", "symbol"]) + plan = expanding_walk_forward_splits(pooled, _config()) + first_validation = pooled.with_row_index("row_id").filter( + pl.col("row_id").is_in(plan.folds[0].validation_indices) + ) + counts = first_validation.group_by("decision_ts_ns").len().get_column("len") + assert counts.to_list() == [2, 2, 2] + + +def test_too_short_sample_fails_closed() -> None: + with pytest.raises(SplitError, match="need at least"): + expanding_walk_forward_splits(_interval_frame(rows=10), _config()) diff --git a/Microstructure/tests/test_storage.py b/Microstructure/tests/test_storage.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3d00d6ad2cbb29932e0eab23f7554a53f8c128 --- /dev/null +++ b/Microstructure/tests/test_storage.py @@ -0,0 +1,137 @@ +from __future__ import annotations + +from pathlib import Path + +import pyarrow.parquet as pq +import pytest + +from microstructure.data.schemas import get_schema +from microstructure.data.storage import ( + StorageError, + write_partitioned_parquet, + write_source_manifest, +) +from microstructure.data.synthetic import generate_synthetic_market +from microstructure.provenance import read_json, sha256_file + + +def test_partitioned_parquet_is_streamed_content_addressed_and_manifested( + tmp_path: Path, +) -> None: + start_ns = 1_704_153_600_000_000_000 + data = generate_synthetic_market( + symbols=("BTCUSDT", "ETHUSDT"), + events_per_symbol=7, + start_ts_ns=start_ns, + seed=11, + ) + result = write_partitioned_parquet( + data.trades.to_batches(max_chunksize=4), + root=tmp_path, + dataset="trades", + schema_name="trades", + source="synthetic_v1", + requested_start_ns=start_ns, + requested_end_ns=start_ns + 1_000_000_000, + max_rows_per_file=3, + downloaded_at_utc="2026-08-07T12:00:00Z", + ) + + assert result.rows == 14 + assert result.artifacts + assert result.manifest_path.is_file() + assert result.manifest_sha256 == sha256_file(result.manifest_path) + assert {item.symbol for item in result.artifacts} == {"BTCUSDT", "ETHUSDT"} + for artifact in result.artifacts: + assert artifact.data_path.is_file() + assert artifact.rows <= 3 + assert "symbol-" + artifact.symbol in str(artifact.data_path) + assert artifact.data_sha256 == sha256_file(artifact.data_path) + assert pq.read_schema(artifact.data_path).equals(get_schema("trades"), check_metadata=True) + manifest = read_json(artifact.manifest_path) + assert manifest["source"] == "synthetic_v1" + assert manifest["downloaded_at_utc"] == "2026-08-07T12:00:00Z" + assert manifest["schema_version"] == "1.0.0" + assert manifest["checksum"]["value"] == artifact.data_sha256 + assert manifest["requested_range_ns"]["start"] == start_ns + assert manifest["write_ordinal"] == artifact.write_ordinal + assert manifest["observed_range_ns"] == { + "start": artifact.observed_start_ns, + "end_inclusive": artifact.observed_end_inclusive_ns, + } + + dataset_manifest = read_json(result.manifest_path) + assert [item["write_ordinal"] for item in dataset_manifest["artifacts"]] == list( + range(len(result.artifacts)) + ) + + +def test_same_normalized_content_reuses_immutable_parquet(tmp_path: Path) -> None: + data = generate_synthetic_market( + symbols=("BTCUSDT",), + events_per_symbol=3, + start_ts_ns=1_704_153_600_000_000_000, + seed=99, + ) + kwargs = { + "root": tmp_path, + "dataset": "trades", + "schema_name": "trades", + "source": "synthetic_v1", + "downloaded_at_utc": "2026-08-07T12:00:00Z", + } + first = write_partitioned_parquet([data.trades], **kwargs) + second = write_partitioned_parquet([data.trades], **kwargs) + + assert [item.data_path for item in first.artifacts] == [ + item.data_path for item in second.artifacts + ] + assert first.manifest_path == second.manifest_path + assert len(list(tmp_path.rglob("*.parquet"))) == 1 + assert not list(tmp_path.rglob("*.tmp")) + + +def test_raw_source_manifest_contains_required_lineage_and_checksum(tmp_path: Path) -> None: + raw = tmp_path / "page.json" + raw.write_bytes(b'[{"a":1}]') + + manifest_path, manifest_sha = write_source_manifest( + raw, + source="binance_spot_public_api", + source_uri="https://data-api.binance.vision/api/v3/aggTrades?symbol=BTCUSDT", + downloaded_at_utc="2026-08-07T12:00:00Z", + requested_start_ns=100, + requested_end_ns=200, + response_headers={"ETag": "abc", "X-MBX-USED-WEIGHT-1M": "4"}, + ) + manifest = read_json(manifest_path) + + assert manifest_sha == sha256_file(manifest_path) + assert manifest["artifact_kind"] == "raw_source" + assert manifest["checksum"]["value"] == sha256_file(raw) + assert manifest["requested_range_ns"] == {"start": 100, "end_exclusive": 200} + assert manifest["response_headers"]["ETag"] == "abc" + + +def test_partition_writer_rejects_oversized_input_before_materializing_it( + tmp_path: Path, +) -> None: + data = generate_synthetic_market( + symbols=("BTCUSDT",), + events_per_symbol=3, + start_ts_ns=1_704_153_600_000_000_000, + seed=101, + ) + + with pytest.raises(StorageError, match="above the bounded-memory limit 2"): + write_partitioned_parquet( + iter((data.trades,)), + root=tmp_path, + dataset="trades", + schema_name="trades", + source="synthetic_v1", + max_input_batch_rows=2, + ) + + assert not list(tmp_path.rglob("*.parquet")) + assert not list(tmp_path.rglob("*.manifest-*.json")) diff --git a/Microstructure/tests/test_trade_only.py b/Microstructure/tests/test_trade_only.py new file mode 100644 index 0000000000000000000000000000000000000000..ef888120c456b5c64d57af3cc5d7bca40df52545 --- /dev/null +++ b/Microstructure/tests/test_trade_only.py @@ -0,0 +1,139 @@ +from __future__ import annotations + +import math + +import polars as pl +import pytest + +from microstructure.config import FeatureConfig +from microstructure.research.features import TemporalLeakageError +from microstructure.research.trade_only import ( + build_trade_only_research_frame, + validate_trade_only_temporal_contract, +) + +SECOND = 1_000_000_000 + + +def _config() -> FeatureConfig: + return FeatureConfig( + trade_windows=(2,), + volatility_window=2, + intensity_window=2, + label_horizon_events=2, + large_trade_quantile=0.9, + ) + + +def _trades() -> pl.DataFrame: + rows = [ + ("segment-a", 1, 0, 100.0, 1.0, "buy"), + ("segment-a", 2, 1, 101.0, 2.0, "sell"), + ("segment-a", 3, 2, 99.0, 3.0, "buy"), + ("segment-a", 4, 3, 102.0, 4.0, "buy"), + ("segment-a", 5, 4, 104.0, 5.0, "sell"), + ("segment-b", 10, 5, 200.0, 6.0, "buy"), + ("segment-b", 11, 6, 201.0, 7.0, "sell"), + ("segment-b", 12, 7, 199.0, 8.0, "sell"), + ] + return pl.DataFrame( + { + "symbol": ["BTCUSDT"] * len(rows), + "continuity_id": [row[0] for row in rows], + "trade_id": [row[1] for row in rows], + "event_ts_ns": [row[2] * SECOND for row in rows], + "available_ts_ns": [row[2] * SECOND for row in rows], + "price": [row[3] for row in rows], + "quantity": [row[4] for row in rows], + "aggressor_side": [row[5] for row in rows], + } + ) + + +def test_trade_only_features_are_hand_checked_and_causal() -> None: + frame = build_trade_only_research_frame(_trades(), _config()) + second = frame.filter(pl.col("decision_trade_id") == 2).row(0, named=True) + + assert second["signed_trade_volume_w2"] == pytest.approx(-1.0) + assert second["trade_volume_w2"] == pytest.approx(3.0) + assert second["trade_imbalance_w2"] == pytest.approx(-1.0 / 3.0) + assert second["trade_count_w2"] == 2.0 + assert second["trade_intensity_w2"] == pytest.approx(2.0) + assert second["log_trade_return_1"] == pytest.approx(math.log(101.0 / 100.0)) + assert second["realized_volatility_w2"] == pytest.approx(abs(math.log(101.0 / 100.0))) + assert second["max_feature_source_ts_ns"] == second["decision_ts_ns"] + assert second["max_feature_source_trade_id"] == second["decision_trade_id"] + + +def test_future_mutation_cannot_change_past_trade_features() -> None: + original = build_trade_only_research_frame(_trades(), _config()) + mutated_trades = _trades().with_columns( + pl.when(pl.col("available_ts_ns") > SECOND) + .then(pl.col("price") * 10.0) + .otherwise(pl.col("price")) + .alias("price"), + pl.when(pl.col("available_ts_ns") > SECOND) + .then(pl.col("quantity") * 100.0) + .otherwise(pl.col("quantity")) + .alias("quantity"), + pl.when(pl.col("available_ts_ns") > SECOND) + .then(pl.lit("sell")) + .otherwise(pl.col("aggressor_side")) + .alias("aggressor_side"), + ) + mutated = build_trade_only_research_frame(mutated_trades, _config()) + feature_columns = [ + "signed_trade_volume_w2", + "trade_volume_w2", + "trade_imbalance_w2", + "trade_intensity_w2", + "log_trade_return_1", + "realized_volatility_w2", + ] + past = pl.col("decision_ts_ns") <= SECOND + + assert ( + original.filter(past) + .select(feature_columns) + .equals(mutated.filter(past).select(feature_columns)) + ) + + +def test_future_trade_labels_are_exact_censored_and_continuity_local() -> None: + frame = build_trade_only_research_frame(_trades(), _config()) + second = frame.filter(pl.col("decision_trade_id") == 2).row(0, named=True) + assert second["future_trade_return"] == pytest.approx(math.log(102.0 / 101.0)) + assert second["future_trade_price"] == 102.0 + assert second["future_trade_direction"] == 1 + assert second["future_trade_up"] == 1 + assert second["label_information_end_ts_ns"] == 3 * SECOND + assert second["label_information_end_trade_id"] == 4 + + segment_a_tail = frame.filter( + (pl.col("continuity_id") == "segment-a") & pl.col("decision_trade_id").is_in([4, 5]) + ) + assert segment_a_tail.get_column("right_censored").to_list() == [True, True] + assert segment_a_tail.get_column("future_trade_return").null_count() == 2 + + first_b = frame.filter(pl.col("decision_trade_id") == 10).row(0, named=True) + assert first_b["signed_trade_volume_w2"] == pytest.approx(6.0) + assert first_b["trade_imbalance_w2"] == pytest.approx(1.0) + assert first_b["log_trade_return_1"] == 0.0 + assert first_b["future_trade_price"] == 199.0 + assert first_b["label_information_end_trade_id"] == 12 + + audit = validate_trade_only_temporal_contract(frame) + assert audit.rows == 8 + assert audit.labeled_rows == 4 + assert audit.right_censored_rows == 4 + assert audit.continuity_segments == 2 + + +def test_trade_only_lineage_guard_rejects_future_source() -> None: + frame = build_trade_only_research_frame(_trades(), _config()) + leaked = frame.with_columns( + (pl.col("feature_cutoff_ts_ns") + 1).alias("max_feature_source_ts_ns") + ) + + with pytest.raises(TemporalLeakageError, match="feature lineage"): + validate_trade_only_temporal_contract(leaked) diff --git a/Microstructure/uv.lock b/Microstructure/uv.lock new file mode 100644 index 0000000000000000000000000000000000000000..2442f20e692bed40d7acf85b6bfed970f143161a --- /dev/null +++ b/Microstructure/uv.lock @@ -0,0 +1,1490 @@ +version = 1 +revision = 3 +requires-python = ">=3.12" +resolution-markers = [ + "python_full_version >= '3.15' and sys_platform == 'win32'", + "python_full_version >= '3.15' and sys_platform == 'emscripten'", + "python_full_version >= '3.15' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.14.*' and sys_platform == 'win32'", + "python_full_version == '3.14.*' and sys_platform == 'emscripten'", + "python_full_version == '3.14.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version < '3.14' and sys_platform == 'win32'", + "python_full_version < '3.14' and sys_platform == 'emscripten'", + "python_full_version < '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] + +[[package]] +name = "altair" +version = "6.2.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jinja2" }, + { name = "jsonschema" }, + { name = "narwhals" }, + { name = "packaging" }, + { name = "typing-extensions", marker = "python_full_version < '3.15'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/06/a1/5e6cc638a66da48cfc89a79c2f4810dfec00b63385f9b009ab1f069779bb/altair-6.2.2.tar.gz", hash = "sha256:a1ff9d9cfe81c75414641826312b9471780e19d39293ba0b012933f6b6cba0fe", size = 766606, upload-time = "2026-06-23T12:47:13.384Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e3/99/d6031f4f146298951c46b1bf1cc160c2a63f6e44b3c13a30054add100d5f/altair-6.2.2-py3-none-any.whl", hash = "sha256:94014f8ad8617c3cb163d1137359cd6db5ba134b9b46d93cfd8b609fd245a583", size = 797613, upload-time = "2026-06-23T12:47:11.451Z" }, +] + +[[package]] +name = "anyio" +version = "4.14.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "idna" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/61/cc/a381afa6efea9f496eff839d4a6a1aed3bfafc7b3ab4b0d1b243a12573dd/anyio-4.14.2.tar.gz", hash = "sha256:cfa139f3ed1a23ee8f88a145ddb5ac7605b8bbfd8592baacd7ce3d8bb4313c7f", size = 260176, upload-time = "2026-07-12T20:29:07.082Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/da/35/f2287558c17e29fafc8ef3daf819bb9834061cfa43bff8014f7df7f63bdc/anyio-4.14.2-py3-none-any.whl", hash = "sha256:9f505dda5ac9f0c8309b5e8bd445a8c2bf7246f3ce950121e45ea15bc41d1494", size = 125813, upload-time = "2026-07-12T20:29:05.763Z" }, +] + +[[package]] +name = "attrs" +version = "26.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9a/8e/82a0fe20a541c03148528be8cac2408564a6c9a0cc7e9171802bc1d26985/attrs-26.1.0.tar.gz", hash = "sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32", size = 952055, upload-time = "2026-03-19T14:22:25.026Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" }, +] + +[[package]] +name = "blinker" +version = "1.9.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/21/28/9b3f50ce0e048515135495f198351908d99540d69bfdc8c1d15b73dc55ce/blinker-1.9.0.tar.gz", hash = "sha256:b4ce2265a7abece45e7cc896e98dbebe6cead56bcf805a3d23136d145f5445bf", size = 22460, upload-time = "2024-11-08T17:25:47.436Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/10/cb/f2ad4230dc2eb1a74edf38f1a38b9b52277f75bef262d8908e60d957e13c/blinker-1.9.0-py3-none-any.whl", hash = "sha256:ba0efaa9080b619ff2f3459d1d500c57bddea4a6b424b60a91141db6fd2f08bc", size = 8458, upload-time = "2024-11-08T17:25:46.184Z" }, +] + +[[package]] +name = "certifi" +version = "2026.7.22" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a3/c2/24167ea9858356b47a87a50d39908bfdb72ceeefe0041586e704e5376b3a/certifi-2026.7.22.tar.gz", hash = "sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55", size = 138112, upload-time = "2026-07-22T03:35:12.644Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0b/a7/71ac2cff56fec219ed242bb11b8efb69fcc4bec75db06fb7bfe35de520e6/certifi-2026.7.22-py3-none-any.whl", hash = "sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775", size = 136983, upload-time = "2026-07-22T03:35:11.276Z" }, +] + +[[package]] +name = "charset-normalizer" +version = "3.4.9" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/bd/2a/23f34ec9d04624958e137efdc394888716353190e75f25dd22c7a2c7a8aa/charset_normalizer-3.4.9.tar.gz", hash = "sha256:673611bbd43f0810bec0b0f028ddeaaa501190339cac411f347ac76917c3ae7b", size = 152439, upload-time = "2026-07-07T14:34:58.454Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/70/4a/ecbd131485c07fcdfad54e28946d513e3da22ef3b4bd854dcafae54ec739/charset_normalizer-3.4.9-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:45b0cc4e3556cd875e09102988d1ab8356c998b596c9fced84547c8138b487a0", size = 319300, upload-time = "2026-07-07T14:33:15.666Z" }, + { url = "https://files.pythonhosted.org/packages/ec/96/5d9364e3342d69f3a045e1777bc47c85c383e6e9466d561b33fdb419d1f9/charset_normalizer-3.4.9-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9b2aff1c7b3884512b9512c3eaadd9bab39fb45042ffaaa1dd08ff2b9f8109d9", size = 215802, upload-time = "2026-07-07T14:33:17.031Z" }, + { url = "https://files.pythonhosted.org/packages/4b/4c/5361f9aa7f2cb58d94f2ab831b3d493f69efb1d239654b4744e3c09527cb/charset_normalizer-3.4.9-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9104ed0bd76a429d46f9ec0dbc9b08ad1d2dcdf2b00a5a0daa1c145329b35b44", size = 237171, upload-time = "2026-07-07T14:33:18.576Z" }, + { url = "https://files.pythonhosted.org/packages/50/78/ce342ca4ff30b2eb49fe6d9578df85974f90c67d294113e94efdd9664cbd/charset_normalizer-3.4.9-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:7b86a2b16095d250c6f58b3d9b2eee6f4147754344f3dab0922f7c9bf7d226c9", size = 233075, upload-time = "2026-07-07T14:33:20.084Z" }, + { url = "https://files.pythonhosted.org/packages/01/c4/4fa4c8b3097a11f3c5f09a35b72ed6855fb1d332469504962ab7bafcc702/charset_normalizer-3.4.9-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5e226f6218febc71f6c1fc2fafb91c226f75bdc1d8fb12d66823716e891608fd", size = 224256, upload-time = "2026-07-07T14:33:21.747Z" }, + { url = "https://files.pythonhosted.org/packages/87/3a/ad914516df7e358a81aae018caa5e0470ba827fa6d763b1d2e87d920a5f6/charset_normalizer-3.4.9-cp312-cp312-manylinux_2_31_armv7l.whl", hash = "sha256:90c44bc373b7687f6948b693cceaea1348ae0975d7474746559494468e3c1d84", size = 208784, upload-time = "2026-07-07T14:33:23.313Z" }, + { url = "https://files.pythonhosted.org/packages/d7/74/3c12f9755717dfe5c5c87da63f35d765fa0c00382ec26bf23f7fae34f2ba/charset_normalizer-3.4.9-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:9cdef90ae47919cae358d8ab15797a800ed41da7aba5d72419fb510729e2ed4b", size = 219928, upload-time = "2026-07-07T14:33:24.814Z" }, + { url = "https://files.pythonhosted.org/packages/33/9a/895095b83e7907abd6d3d99aad3a38ad0d9686cc186cb0c94c24320fe63e/charset_normalizer-3.4.9-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:60f44ade2cf573dad7a277e6f8ca9a51a21dda572b13bd7d8539bb3cd5dbedde", size = 218489, upload-time = "2026-07-07T14:33:26.42Z" }, + { url = "https://files.pythonhosted.org/packages/a1/34/ef5c05f412f42520d7709b7d3784d19640839eb7366ded1755511585429f/charset_normalizer-3.4.9-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:a1786910334ed46ab1dd73222f2cd1e05c2c3bb39f6dddb4f8b36fc382058a39", size = 210267, upload-time = "2026-07-07T14:33:27.952Z" }, + { url = "https://files.pythonhosted.org/packages/83/dc/9b29fa4412b318bf3bfea985c35d67eb55e04b59a7c3f2237168b0e0be6f/charset_normalizer-3.4.9-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:03d07803992c6c7bbc976327f34b18b6160327fc81cb82c9d504720ac0be3b62", size = 226030, upload-time = "2026-07-07T14:33:29.397Z" }, + { url = "https://files.pythonhosted.org/packages/0e/42/6dbc00b8cd16011691203e33570fa42ed5746599a2e878112d16eab403a3/charset_normalizer-3.4.9-cp312-cp312-win32.whl", hash = "sha256:78841cccf1af7b40f6f716338d50c0902dbe88d9f800b3c973b7a9a0a693a642", size = 151185, upload-time = "2026-07-07T14:33:30.781Z" }, + { url = "https://files.pythonhosted.org/packages/80/cc/f920afd1a23c58ccd53c1d36085a71893a4737ff5e66e0371efab6809850/charset_normalizer-3.4.9-cp312-cp312-win_amd64.whl", hash = "sha256:4b3dac63058cc36820b0dd072f89898604e2d39686fe05321729d00d8ac185a0", size = 162557, upload-time = "2026-07-07T14:33:32.176Z" }, + { url = "https://files.pythonhosted.org/packages/f0/e6/0386d43a261ff4e4b30c5857af7df877254b46bec7b9d1b74b6bf969a90b/charset_normalizer-3.4.9-cp312-cp312-win_arm64.whl", hash = "sha256:78fa18e436a1a0e58dbd7e02fc4473f3f32cceb12df9dfca542d075961c307d2", size = 152665, upload-time = "2026-07-07T14:33:33.711Z" }, + { url = "https://files.pythonhosted.org/packages/b2/06/97ec2aeae780b31d742b6352218b43841a6871e2564578ca522dce4a45c3/charset_normalizer-3.4.9-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:440eede837960000d74978f0eba527be106b5b9aee0daf779d395276ed0b0614", size = 317688, upload-time = "2026-07-07T14:33:35.408Z" }, + { url = "https://files.pythonhosted.org/packages/d0/39/8ff066c672434225f8d25f8b739f992af250944392173dcc88362681c9bf/charset_normalizer-3.4.9-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:21e764fd1e70b6a3e205a0e46f3051701f98a8cb3fad66eeb80e48bb502f8698", size = 214982, upload-time = "2026-07-07T14:33:36.996Z" }, + { url = "https://files.pythonhosted.org/packages/92/8f/3a47a3667c83c2df9483d91644c6c107de3bf8874aa1793da9d3012eb986/charset_normalizer-3.4.9-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e4fd89cc178bced6ad29cb3e6dd4aa63fa5017c3524dbd0b25998fb64a87cc8b", size = 236460, upload-time = "2026-07-07T14:33:38.536Z" }, + { url = "https://files.pythonhosted.org/packages/f1/60/b22cdbee7e4013dab8b0d7647fc6181120fbbbc8f7025c226d15bd5a47fc/charset_normalizer-3.4.9-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:bd47ba7fc3ca94896759ea0109775132d3e7ab921fbf54038e1bab2e46c313c9", size = 232003, upload-time = "2026-07-07T14:33:40.059Z" }, + { url = "https://files.pythonhosted.org/packages/ea/f8/72eb13dcabe7257035cea8aefd922caad2f110d252bf9f67c4c2ca763aee/charset_normalizer-3.4.9-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:84fd18bcc17526fc2b3c1af7d2b9217d32c9c04448c16ec693b9b4f1985c3d33", size = 223149, upload-time = "2026-07-07T14:33:41.631Z" }, + { url = "https://files.pythonhosted.org/packages/b0/3e/faee8f9de92b14ee1198e9163252bb15efee7301b31256a3b6d9ebfdd0dd/charset_normalizer-3.4.9-cp313-cp313-manylinux_2_31_armv7l.whl", hash = "sha256:5b10cd92fc5c498b35a8635df6d5a100207f88b63a4dc1de7ef9a548e1e2cd63", size = 207901, upload-time = "2026-07-07T14:33:43.209Z" }, + { url = "https://files.pythonhosted.org/packages/3a/25/45f30093ae27dd7b92a793b61882a38685f993700113ca36e0c9c14965e1/charset_normalizer-3.4.9-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a4fbdde9dd4a9ce5fd52c2b3a347bb50cc89483ef783f1cb00d408c13f7a96c0", size = 219176, upload-time = "2026-07-07T14:33:44.725Z" }, + { url = "https://files.pythonhosted.org/packages/48/18/c8f397329c35e32f6a837e488986f4ae03bd2abebc453b48714991630c2f/charset_normalizer-3.4.9-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:416c229f77e5ea25b3dfd4b582f8d73d7e43c22320302b9ab128a2d3a0b38efe", size = 217356, upload-time = "2026-07-07T14:33:46.192Z" }, + { url = "https://files.pythonhosted.org/packages/86/7e/5ce0bba863470fd1902d5e5843968951bddf38abe4742fc97116ef4598b3/charset_normalizer-3.4.9-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:75286256590a6320cf106a0d28970d3560aad9ee09aa7b34fb40524792436d35", size = 209614, upload-time = "2026-07-07T14:33:47.705Z" }, + { url = "https://files.pythonhosted.org/packages/6c/ef/2473d3c4d869155be4af1191111d59c4d5c4e0173026f7e85b176e23bf65/charset_normalizer-3.4.9-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:69b157c5d3292bcd443faca052f3096f637f1e074b98212a933c074ae23dc3b8", size = 224991, upload-time = "2026-07-07T14:33:49.238Z" }, + { url = "https://files.pythonhosted.org/packages/d0/a3/53ddae3db108a088156aa8ddfafd411ebbc1340f48c5573f697b27f69a39/charset_normalizer-3.4.9-cp313-cp313-win32.whl", hash = "sha256:51307f5c71007673a2bf8232ad973483d281e74cb99c8c5a990af1eefa6277d9", size = 150622, upload-time = "2026-07-07T14:33:50.711Z" }, + { url = "https://files.pythonhosted.org/packages/e8/ef/6953a77c7cf2c2ff9998e6f575ab3e380119f100223381565a4f94c1f836/charset_normalizer-3.4.9-cp313-cp313-win_amd64.whl", hash = "sha256:fe2c7201c642b7c308f1675355ad7ff7b66acfe3541625efe5a3ad38f29d6115", size = 161947, upload-time = "2026-07-07T14:33:52.197Z" }, + { url = "https://files.pythonhosted.org/packages/6e/fb/d560d1d1555debbfe7849d9cac6145c1b537709d79576bf22557ed803b82/charset_normalizer-3.4.9-cp313-cp313-win_arm64.whl", hash = "sha256:611057cc5d5c0afc743ba8be6bd828c17e0aaa8643f9d0a9b9bb7dea80eb8012", size = 152594, upload-time = "2026-07-07T14:33:53.486Z" }, + { url = "https://files.pythonhosted.org/packages/7e/8d/496817fa0944239ecae662dd57ea765cfeaec6a735f9f025d4b7b72e7143/charset_normalizer-3.4.9-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:0327fcd59a935777d83410750c50600ee9571af2846f71ce40f25b13da1ef380", size = 317253, upload-time = "2026-07-07T14:33:54.994Z" }, + { url = "https://files.pythonhosted.org/packages/2b/f9/ef4a69ea338ad3c0deceea0f5f7d2380ae8b52132b06d652cb0d2cd86706/charset_normalizer-3.4.9-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8a79d9f4d8001473a30c163556b3c3bfebec837495a412dde78b51672f6134f9", size = 215898, upload-time = "2026-07-07T14:33:56.334Z" }, + { url = "https://files.pythonhosted.org/packages/8c/e7/5ddfd76fc061eb52de219658a4aa431cbacadf0a0219c8854f00da50d289/charset_normalizer-3.4.9-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:33bdcc2a32c0a0e861f60841a512c8acc658c87c2ac59d89e3a46dacf7d866e4", size = 236718, upload-time = "2026-07-07T14:33:57.9Z" }, + { url = "https://files.pythonhosted.org/packages/49/ba/768fa3f36048d81c477a0ce61f813bc1454d80917ccfe550abd9f44f5e24/charset_normalizer-3.4.9-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f840ed6d8ecba8255df8c42b87fadeda98ddfc6eeec05e2dc66e26d46dd6f58a", size = 232519, upload-time = "2026-07-07T14:33:59.811Z" }, + { url = "https://files.pythonhosted.org/packages/f4/c4/b3e049d2aa3766180c78507110543d9d50894cc97f57de543f1be521dcdc/charset_normalizer-3.4.9-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c25fe15c70c59eb7c5ce8c06a1f3fa1da0ecc5ea1e7a5922c40fd2fa9b0d5046", size = 223143, upload-time = "2026-07-07T14:34:01.517Z" }, + { url = "https://files.pythonhosted.org/packages/19/79/55c32d06d76ae4feafe053f061f3e3ab70bcf19f4007797ce8c3efda7830/charset_normalizer-3.4.9-cp314-cp314-manylinux_2_31_armv7l.whl", hash = "sha256:f7fb7d750cfa0a070d2c24e831fd3481019a60dd317ea2b39acbcebc08b6ed81", size = 206742, upload-time = "2026-07-07T14:34:03.04Z" }, + { url = "https://files.pythonhosted.org/packages/10/e0/47c079dd82d217c807479cd59ffd30af56307ea31c108b75758970459ad3/charset_normalizer-3.4.9-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:4d1c96a7a18b9690a4d46df09e3e3382406ae3213727cd1019ebade1c4a81917", size = 219191, upload-time = "2026-07-07T14:34:04.657Z" }, + { url = "https://files.pythonhosted.org/packages/42/ab/b9bc2e77d6b44a7e46ef62ec5cac1c9a6ba7b9135a5d560f002696ec9995/charset_normalizer-3.4.9-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:a4cfde78a9f2880208d16a93b795726a3017d5977e08d1e162a7a31322479c41", size = 218328, upload-time = "2026-07-07T14:34:06.115Z" }, + { url = "https://files.pythonhosted.org/packages/f1/78/c9c71d599f5aa2d42bcdd35cbbd46d7f535351a57e40ff7d8e5a7e219401/charset_normalizer-3.4.9-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:d4d6fcde76f94f5cb9e43e9e9a61f16dacefd228cbbf6f1a09bd9b219a92f1a1", size = 207406, upload-time = "2026-07-07T14:34:07.554Z" }, + { url = "https://files.pythonhosted.org/packages/f6/39/c914445c321a845097ce4f6ac7de9a18228a77b766272125a1ce00d851eb/charset_normalizer-3.4.9-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:898f0e9068ca27d37f8e83a5b962821df851532e6c4a7d615c1c033f9da6eedf", size = 225157, upload-time = "2026-07-07T14:34:09.061Z" }, + { url = "https://files.pythonhosted.org/packages/9b/f2/c0d4b8508565a36bc5c624e88ed297f5b0b1095011034d7f5b83a69908b5/charset_normalizer-3.4.9-cp314-cp314-win32.whl", hash = "sha256:c1c948747b03be832dceed96ca815cef7360de9aa19d37c730f8e3f6101aca48", size = 151095, upload-time = "2026-07-07T14:34:10.901Z" }, + { url = "https://files.pythonhosted.org/packages/49/fd/a1d26144398c67486422a72bf5812cda22cb4ccfcd95a290fb41ceb4b8e2/charset_normalizer-3.4.9-cp314-cp314-win_amd64.whl", hash = "sha256:16b65ea0f2465b6fb52aa22de5eca612aa964ddfec00a912e26f4656cbef890b", size = 162796, upload-time = "2026-07-07T14:34:12.47Z" }, + { url = "https://files.pythonhosted.org/packages/20/95/d75e82f8ce9fd323ebf059c16c9aadefb22a1ecde13b7840b35835e4886c/charset_normalizer-3.4.9-cp314-cp314-win_arm64.whl", hash = "sha256:40a126142a56b2dfc0aacbad1de8310cbf60da7656db0e6b16eebd48e3e93519", size = 153334, upload-time = "2026-07-07T14:34:14.044Z" }, + { url = "https://files.pythonhosted.org/packages/00/5e/17398df3a139985ba9d11ed072531986f408c8fca952835ef1ab1820c02b/charset_normalizer-3.4.9-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:609b3ba8fcc0fb5ab7af00719d0fb6ad0cb518e48e7712d12fd68f1327951198", size = 338848, upload-time = "2026-07-07T14:34:15.688Z" }, + { url = "https://files.pythonhosted.org/packages/cd/91/7253a32e86b7e1d1239b1b36ba6dd0f021a21107ab33054b53119cc083b9/charset_normalizer-3.4.9-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:51447e9aa2684679af07ca5021c3db526e0284347ebf4ffcec1154c3350cfe32", size = 223022, upload-time = "2026-07-07T14:34:17.248Z" }, + { url = "https://files.pythonhosted.org/packages/cb/32/2e64bd2be10e89c61e57ebe6a93fd98ae88eb7ebe414b5121f22c96c69eb/charset_normalizer-3.4.9-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:cc1b0fff8ead343dae06305f954eb8468ba0ec1a97881f42489d198e4ce3c632", size = 241590, upload-time = "2026-07-07T14:34:18.813Z" }, + { url = "https://files.pythonhosted.org/packages/3d/ef/d96ec496cfea0c21db43b0ad03891308b02388d054cc902cf0e5a1ad6a88/charset_normalizer-3.4.9-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:fa36ec09ef71d158186bc79e359ff5fdd6e7996fe8ab638f00d6b93139ba4fcf", size = 239584, upload-time = "2026-07-07T14:34:20.52Z" }, + { url = "https://files.pythonhosted.org/packages/d4/ce/9af95f7876194bd7a14e3dfe4a4de2e0bff02666a3910d72beafd06cc297/charset_normalizer-3.4.9-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:df115d4d83168fdf2cae48ef1ff6d1cb4c466364e30861b37121de0f3bf1b990", size = 230224, upload-time = "2026-07-07T14:34:22.189Z" }, + { url = "https://files.pythonhosted.org/packages/52/94/af74dde74a3996bd959c350709bfe50e297823d70a8c1cbd54b838880863/charset_normalizer-3.4.9-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:f86c6358749bd4fda175388691e3ba8c46e24c5347d0afd20f9b7edfc9faf07d", size = 212667, upload-time = "2026-07-07T14:34:23.857Z" }, + { url = "https://files.pythonhosted.org/packages/ee/f0/f1c4fe746c395922961b5916ed1d7d6e7d4c84851d19ed43cc89980ec953/charset_normalizer-3.4.9-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:32286a2c8d167e897177b673176c1e3e00d4057caf5d2b64eef9a3666b03018e", size = 227179, upload-time = "2026-07-07T14:34:25.586Z" }, + { url = "https://files.pythonhosted.org/packages/e4/56/6c745619ac397e8871e2bcd3cea1eec86b877488f33888b3aef5c3ed506e/charset_normalizer-3.4.9-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:83aed2c10721ddd90f68140685391b50811a880af20654c59af6b6c66c40513c", size = 225372, upload-time = "2026-07-07T14:34:27.212Z" }, + { url = "https://files.pythonhosted.org/packages/78/ad/98aae8630ac71f16711968e38a5acfecce41b778bf2f0312851020f565a8/charset_normalizer-3.4.9-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:cd6c3d4b783c556fa00bf540854e42f135e2f256abd29669fcd0da0f2dec79c2", size = 215222, upload-time = "2026-07-07T14:34:28.774Z" }, + { url = "https://files.pythonhosted.org/packages/f7/40/9593d54209765207a7f11073c06494c1721e4ca4a0a426c597679bf7f91e/charset_normalizer-3.4.9-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:ee2f2a527e3c1a6e6411eb4209642e138b544a2d72fe5d0d76daf77b24063534", size = 231958, upload-time = "2026-07-07T14:34:30.345Z" }, + { url = "https://files.pythonhosted.org/packages/b1/27/693ee5e8a18191eb38647360c51cd505013e2bd3b366aa43fd5344c21e3c/charset_normalizer-3.4.9-cp314-cp314t-win32.whl", hash = "sha256:0d861473f743244d349b50f850d10eb87aeb22bbdcc8e64f79273c94af5a8226", size = 155580, upload-time = "2026-07-07T14:34:31.884Z" }, + { url = "https://files.pythonhosted.org/packages/80/3f/bd97d3d9c613013d07cb7733d299385b41df37f0471310f5a73dc359f0b8/charset_normalizer-3.4.9-cp314-cp314t-win_amd64.whl", hash = "sha256:9b8e0f3107e2200b76f6054de99016eac3ee6762713587b36baaa7e4bd2ae177", size = 167620, upload-time = "2026-07-07T14:34:33.438Z" }, + { url = "https://files.pythonhosted.org/packages/3d/c6/eee9dca4439b1061f76373f06ea855678cc4a64c1c3c90b50e479edbb8eb/charset_normalizer-3.4.9-cp314-cp314t-win_arm64.whl", hash = "sha256:19ac87f93086ce37b86e098888555c4b4bc48102279bae3350098c0ed664b501", size = 158037, upload-time = "2026-07-07T14:34:35.018Z" }, + { url = "https://files.pythonhosted.org/packages/98/2b/f97f1c193fb855c345d678f5077d6926034db0722df74c8f057020e05a25/charset_normalizer-3.4.9-py3-none-any.whl", hash = "sha256:68e5f26a1ad57ded6d1cfb85331d1c1a195314756471d97758c48498bb4dcdf5", size = 64538, upload-time = "2026-07-07T14:34:56.993Z" }, +] + +[[package]] +name = "click" +version = "8.4.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/76/d4/81420972a676e8ffea40450d8c8c92943e7218a78fe9b64359836cc9876b/click-8.4.2.tar.gz", hash = "sha256:9a6cea6e60b17ebe0a44c5cc636d94f09bd66142c1cd7d8b4cd731c4917a15f6", size = 338000, upload-time = "2026-06-24T17:45:15.148Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fb/e2/79c688af8b210d232694e31e59da9f6ec747bae31c3f5946e4e9b98860d5/click-8.4.2-py3-none-any.whl", hash = "sha256:e6f9f66136c816745b9d65817da91d61d957fb16e02e4dcd0552553c5a197b76", size = 119243, upload-time = "2026-06-24T17:45:13.73Z" }, +] + +[[package]] +name = "colorama" +version = "0.4.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, +] + +[[package]] +name = "coverage" +version = "7.15.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/be/c3/4f2195f512fb172aa425a8803a874b2baa9ba7f80ff7b6080998761fc701/coverage-7.15.4.tar.gz", hash = "sha256:0548198fff07ccf4faf469520bce1c2eceb1ce3e62891921138dec10907f9d00", size = 936952, upload-time = "2026-08-06T13:50:24.442Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1d/48/bc8d4ba7b37551a767bd863f15b3f80182b271c2f55975356f5f7dbe94c2/coverage-7.15.4-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:d4fedd1f7f428f9fe83b1ead5e7cc87a43427be31aadafbac3ac0636dc7abb22", size = 222543, upload-time = "2026-08-06T13:47:37.562Z" }, + { url = "https://files.pythonhosted.org/packages/20/dd/88d6f83f1fffc974a3691a34a97951c5b12df7512a6782c5963883cbc058/coverage-7.15.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:37e2f0cdf58e2e1fed4e4d5a8f8786ae2f7eb80b478016876667dc4a01d60a97", size = 222905, upload-time = "2026-08-06T13:47:38.927Z" }, + { url = "https://files.pythonhosted.org/packages/bd/5c/54ee0d4748585bb0acab9891cd8d92f2d3593165b4e59fc9de113bfb3140/coverage-7.15.4-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:fb55d0e70bb15f2e81477613627286581414693d74ac7963c93a790dd453ca9d", size = 254407, upload-time = "2026-08-06T13:47:40.488Z" }, + { url = "https://files.pythonhosted.org/packages/8c/3f/f0642a372f494bd0d7dad3b497083b910194a5f1c88be2c94fef707c3b59/coverage-7.15.4-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:899b9da30f3c6c336566e3707495bb23e8302d39d862f01fa78c48b99b9437e2", size = 257145, upload-time = "2026-08-06T13:47:41.931Z" }, + { url = "https://files.pythonhosted.org/packages/71/17/8b46d0ed68251016002ec972c8fc0119961a765d0984cafb8bf317c43758/coverage-7.15.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d15715e8c46552827e5e4f30a35575a2dbcad14454cf3284c54483946bd16931", size = 258257, upload-time = "2026-08-06T13:47:43.527Z" }, + { url = "https://files.pythonhosted.org/packages/30/b8/8498a0e72d0adbe15477dd07463d2b3bb2c9f6a4815e8589e50939e2c3ae/coverage-7.15.4-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:002a438859f7b430bc99afeaf01a6d187dad1d0dc907b64cdeffc632a5db8fd8", size = 260517, upload-time = "2026-08-06T13:47:45.121Z" }, + { url = "https://files.pythonhosted.org/packages/41/e1/7dce19c3bdb1e3dd63e769508216500edad81bd5f69a26d724e32aceaf78/coverage-7.15.4-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e4193a04b518f7968f3099755f5509ee7cccc6dc2b92a6b14841934d22e222c9", size = 254785, upload-time = "2026-08-06T13:47:46.541Z" }, + { url = "https://files.pythonhosted.org/packages/dd/b1/e1494703c675a2561723cd9b89f45c9168782c31280c611b1f767851e57c/coverage-7.15.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:e98dcc55d572b38e69d117da7e8e8efb8500f1f5eaf81ecd460a63220790b839", size = 256176, upload-time = "2026-08-06T13:47:48.155Z" }, + { url = "https://files.pythonhosted.org/packages/73/76/a5629d270fb638a43a4b10466f51e2f49d532c1aa4da2913cbbb150bbe0a/coverage-7.15.4-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:af6c538498ce66c10d3fd541c2a8d5b03da5850355add34e6cba564210cb9e72", size = 254321, upload-time = "2026-08-06T13:47:49.757Z" }, + { url = "https://files.pythonhosted.org/packages/ff/4f/9c44447218435d5766b911534f9d798144a5560f85e9a54ebe5f3f5d19f9/coverage-7.15.4-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:1d10025d96ea89fc2f73714dbc4cbd433fe012c1ac9e23f895d7728b238b6e52", size = 258390, upload-time = "2026-08-06T13:47:51.248Z" }, + { url = "https://files.pythonhosted.org/packages/de/36/c1e127616fb3fa18a9ff71e76c417f2fd7424332a4870015ac224ef4c039/coverage-7.15.4-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:d802e1947603162ded419bff83ac7489820355d2b856dfb09206574e3a37ac0c", size = 253894, upload-time = "2026-08-06T13:47:52.816Z" }, + { url = "https://files.pythonhosted.org/packages/e9/b9/fdb92c8ae7a8bb9b850cc253b7b3b9c8526f68130002048b5671cd510d09/coverage-7.15.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:c2de40895718f91951b86712b4c5b694acaf9a0a49be13874896f599a1eed3f4", size = 255763, upload-time = "2026-08-06T13:47:54.296Z" }, + { url = "https://files.pythonhosted.org/packages/6f/c0/a7d51b2587c7bdb76e71b0896d2565bf7d60436b5122fc83e511adb1f7cd/coverage-7.15.4-cp312-cp312-win32.whl", hash = "sha256:5c3431b2161279b7db5c2a1aa58ae02e5cb8c3c42d93a5094be3f5537bd5b11b", size = 224597, upload-time = "2026-08-06T13:47:56.074Z" }, + { url = "https://files.pythonhosted.org/packages/49/b9/5c5f80cc55f5acaaca6dee677626bfcec8c87204a7809b438b08e84f4571/coverage-7.15.4-cp312-cp312-win_amd64.whl", hash = "sha256:6befeab5fb2b51c958ca4ac6c5d141a1e8240f4f76e46350f1911963deda49cd", size = 225135, upload-time = "2026-08-06T13:47:57.52Z" }, + { url = "https://files.pythonhosted.org/packages/47/e4/2a4561f89ff6bf7c925c287d0f2cce8bdf139c3a33735c87e3203401cf94/coverage-7.15.4-cp312-cp312-win_arm64.whl", hash = "sha256:67bc345491ab55b837277d76f5775d057e8c7f1ac44d890d8c2c82adde258c6f", size = 224515, upload-time = "2026-08-06T13:47:58.977Z" }, + { url = "https://files.pythonhosted.org/packages/f1/84/651a9310859673aaa3b3203f1aa1641ca60fcf2494683e1c9474c7172780/coverage-7.15.4-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:c705b28feb2775dc82a25f1d473a370bc37ff93f5177f4e29ce2425f560f6921", size = 222565, upload-time = "2026-08-06T13:48:00.796Z" }, + { url = "https://files.pythonhosted.org/packages/82/f9/4dcf700137e8af550670f4d74d1b63828ce93e1e2b05e5f10710eb2ea987/coverage-7.15.4-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:3ff205ab5e3ecc670f6a4dd19d9cbf12ede53dd41cfc1e15716ec961ea6d314e", size = 222936, upload-time = "2026-08-06T13:48:02.391Z" }, + { url = "https://files.pythonhosted.org/packages/07/4a/612ff1e780b3fbfd637486f542f84adc5503873d8b5d279dec1ffeef9414/coverage-7.15.4-cp313-cp313-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:5172326e861a38b48b48befca15e0f477a26b283337a33a739c8fed229934e36", size = 253926, upload-time = "2026-08-06T13:48:04.382Z" }, + { url = "https://files.pythonhosted.org/packages/b0/04/d1cff1c2ead4708a6a79c01d3736b6a25bd38a36678398f72a8dd33dfad9/coverage-7.15.4-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:12b59c90084e3234fb11184886bf4a40f4f16a8c8f867be2e087b81f8e8868d4", size = 256523, upload-time = "2026-08-06T13:48:05.996Z" }, + { url = "https://files.pythonhosted.org/packages/b9/80/d34e13fb4b293cbdb9665838cf5522077b8ad14ef947550631a4bced36a5/coverage-7.15.4-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:349062d66f00b40fa2c1c222438bad25fabf755631b5d82937fe985c8008615c", size = 257759, upload-time = "2026-08-06T13:48:08.036Z" }, + { url = "https://files.pythonhosted.org/packages/0f/e7/2c5fe7636fdb0732fe0f09f308a5b066864078b7fc61f6678e8478554f2e/coverage-7.15.4-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4256ced708e598e05209bc1a8ab4074e04a51dba4c62fb45926a229af675ace7", size = 259890, upload-time = "2026-08-06T13:48:09.834Z" }, + { url = "https://files.pythonhosted.org/packages/92/28/9689f0858dfff59c2ea688938ab9fa2925631235df67126a42b6c5c70ae1/coverage-7.15.4-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:d80f974b20782d9612c8b4c9beeca867074c7cf4079d1419843fa25a26428b25", size = 254121, upload-time = "2026-08-06T13:48:11.459Z" }, + { url = "https://files.pythonhosted.org/packages/f9/e2/785077c230c157243eb5aa9a26c3be260ecd02001bead54a3cada3df8e03/coverage-7.15.4-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:2e179f19bfe1d31f8eeeaa12990194d761c4f62f0759661000bca6cd8729f40b", size = 255891, upload-time = "2026-08-06T13:48:13.209Z" }, + { url = "https://files.pythonhosted.org/packages/d4/90/e20371b17b40f912f21305c2db2f30efa3de306f7320fc916804872c85a4/coverage-7.15.4-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:8bc16bb47b7679670eceff71d78bfb7d6e5b143f6c2cd117487ec7c75e0d4b78", size = 253859, upload-time = "2026-08-06T13:48:14.736Z" }, + { url = "https://files.pythonhosted.org/packages/05/49/25371987ee459a5f67c0427fb75c74f9358e65f2c71fe75bf41c1b6c5fcb/coverage-7.15.4-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:1cd685005cd2c4200adfc14cf39a603b9320efab3f18a8f7f156d20c9cc3345f", size = 258011, upload-time = "2026-08-06T13:48:16.464Z" }, + { url = "https://files.pythonhosted.org/packages/30/6e/32e67467f6154bf4f1c4f63b05acc5097cba4237d45bbeeea446b52e8ac1/coverage-7.15.4-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:337399ad2c93b3acd2a937627dae8b3e86b66707cd3d3e856347999aadf1ef8d", size = 253676, upload-time = "2026-08-06T13:48:18.493Z" }, + { url = "https://files.pythonhosted.org/packages/03/c1/8b24192e89286399765155251f99ee9f070a9d637109018ac23d99b99f6f/coverage-7.15.4-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:96e257121228ec5cd2bb919276e94ac11074471bc37d68dbae0e8308cce15fff", size = 255453, upload-time = "2026-08-06T13:48:20.057Z" }, + { url = "https://files.pythonhosted.org/packages/16/6f/8b41ebdf67c87854e17c035336a90f1cfbad0c14c2a584301be6ff148718/coverage-7.15.4-cp313-cp313-win32.whl", hash = "sha256:c65a9e0dfc6143491879da4e13b5e30f8be192055de508d737fb14601edbd22c", size = 224605, upload-time = "2026-08-06T13:48:21.655Z" }, + { url = "https://files.pythonhosted.org/packages/e0/e2/2946c7f0b42b152ecb21ff1bdad72e3d301e790c0c487e4a86e8c9f69347/coverage-7.15.4-cp313-cp313-win_amd64.whl", hash = "sha256:2ff8f5e9b8f7a94f0c11c45631eee103dbcb7d63274edd12c56efe1be690b3b4", size = 225148, upload-time = "2026-08-06T13:48:23.376Z" }, + { url = "https://files.pythonhosted.org/packages/9e/83/3f4a69957f48ae7a0aba76c34743f88963d607b19e03f3f8e66f91cae0f9/coverage-7.15.4-cp313-cp313-win_arm64.whl", hash = "sha256:6e0a8a5083b096487d6cfced94cdd514d8f5db6f113610fb36c0620edb1028cf", size = 224536, upload-time = "2026-08-06T13:48:25.117Z" }, + { url = "https://files.pythonhosted.org/packages/ea/ac/748cf29eeb2d6be34a3176ce26a4f49e38085ee08e8935f05f6f26ed7e0f/coverage-7.15.4-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:770e9325ab5ea6d56f77e59b29ecfe0ac20b57a82a601876f90494a4dda0386f", size = 222608, upload-time = "2026-08-06T13:48:26.806Z" }, + { url = "https://files.pythonhosted.org/packages/0b/02/1abbf5c984677b0aa439cdacaccbf38d248939d8ef8fe1cc7a50d73edb77/coverage-7.15.4-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:d12b33a3a50a1676b7784dc8d00a0c6d66a9f2add4b85a041c19b6a7e53ef23c", size = 222940, upload-time = "2026-08-06T13:48:28.432Z" }, + { url = "https://files.pythonhosted.org/packages/eb/e1/ff8f9f53d9fcf586125b55d0b1f04ec1c14955fee41e83d5814bee141bb5/coverage-7.15.4-cp314-cp314-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:5669c8378ebde86f5def7a25d29586631b58acc27ffde04399f678f3dfc6e082", size = 253985, upload-time = "2026-08-06T13:48:29.995Z" }, + { url = "https://files.pythonhosted.org/packages/a1/26/595759762e514e81be1d7d01ed03444303bcd152226a6529998d253f9201/coverage-7.15.4-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:ff97a14362eef486483ed44042ca2027ea257df6ff768e62358ee0c9776925ac", size = 256492, upload-time = "2026-08-06T13:48:31.634Z" }, + { url = "https://files.pythonhosted.org/packages/24/68/b79aabac54d482be23b5fcdd4f4662bff24a78edc4ee29201726929936d5/coverage-7.15.4-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5a325e815318638aed1655d9c06e6d7c2d3d46c09231ce988070428a8762d734", size = 257837, upload-time = "2026-08-06T13:48:33.186Z" }, + { url = "https://files.pythonhosted.org/packages/09/0f/bf7f297885a5bf6fd71e5782404e0ff059ca09e8711ceb3a08544abde45a/coverage-7.15.4-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:474223409d88eb20d2d6a0d37ea60e8647a65a90cc008dc1f0410af5f64f1e0d", size = 260152, upload-time = "2026-08-06T13:48:34.75Z" }, + { url = "https://files.pythonhosted.org/packages/fd/f1/296744e854ff8368542343457414380465e9ceefb9192342feb9d3bc461d/coverage-7.15.4-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:7f2f62ae3cd189dd2e13aece758c57b3eecbd27be070dbd4cbd10936049e5dbf", size = 253978, upload-time = "2026-08-06T13:48:36.434Z" }, + { url = "https://files.pythonhosted.org/packages/55/b0/bbdb2e9057493e66220a2e149ca2d301ba0e3a58a83bd6b90de9826d16f3/coverage-7.15.4-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:39ece820e29e0a2ba34b3ecb3be83c27e997eed8926f2ba6fe7ce7a0bda5843b", size = 255846, upload-time = "2026-08-06T13:48:38.317Z" }, + { url = "https://files.pythonhosted.org/packages/96/e4/38015b2b6d21258713bd17e76b59d033b191efb5703589cffd037dfbca20/coverage-7.15.4-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:f21b56dcace11dfe013014201f577dcd592b2a9b72182d930361b47cf6f73f25", size = 253808, upload-time = "2026-08-06T13:48:39.993Z" }, + { url = "https://files.pythonhosted.org/packages/0b/64/0d515c1e60ee6fbfd1a0e79c07cd87d388a233b7adc37758735677203808/coverage-7.15.4-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:93a3a0b662abcc10c73a47cbc72cd60f63618d6989fb2d1286e50eacd974f303", size = 258081, upload-time = "2026-08-06T13:48:41.971Z" }, + { url = "https://files.pythonhosted.org/packages/91/71/04d9e7a3642146c6351338aef4ef85ab11dbbb54744c13245caba1aad1c0/coverage-7.15.4-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:141fae2cabf5569b782c10afc4c850ce10f618c13f8db54765cba99cc839da1f", size = 253624, upload-time = "2026-08-06T13:48:43.731Z" }, + { url = "https://files.pythonhosted.org/packages/b4/a7/6c28b74c81ebff66987b0e2522ba5cffa3e90b0c33cb6a2eb264d4ee8cf1/coverage-7.15.4-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:81294c7e6ab30c5f74c0353b11b2fd6320e72d9bee6ac73b357caa8b916323a5", size = 255280, upload-time = "2026-08-06T13:48:45.58Z" }, + { url = "https://files.pythonhosted.org/packages/52/af/bc19996a7014b98d7bbb0f0939453c67074af65784a3aa16a789a07381fa/coverage-7.15.4-cp314-cp314-win32.whl", hash = "sha256:7bbd7d6418e0dab31a206af5203bd43ae36edb8e7fba1940b055d3e9249290d7", size = 224768, upload-time = "2026-08-06T13:48:47.525Z" }, + { url = "https://files.pythonhosted.org/packages/ee/90/219484e476d6e101ba0a444852579e05f5b75c37c611a42ed1190f73ef62/coverage-7.15.4-cp314-cp314-win_amd64.whl", hash = "sha256:f0204ed122758782970526057093f448051a39db9d810d4e344bb87a3546f425", size = 225259, upload-time = "2026-08-06T13:48:49.513Z" }, + { url = "https://files.pythonhosted.org/packages/b7/66/fa77daf4e383e5f776dac62c2409b6af81910ae6fe326bd5170dba74cc63/coverage-7.15.4-cp314-cp314-win_arm64.whl", hash = "sha256:9e71e7bc71c686a123347ae47a0de33a175e797a85bb57b791492adf4eec8ed8", size = 224684, upload-time = "2026-08-06T13:48:51.235Z" }, + { url = "https://files.pythonhosted.org/packages/58/5b/f03bf0ce362bbf3f785fa5219620d00778d4ac6fc9e407734828e9c672f6/coverage-7.15.4-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:7c922735321eef3f87c280a3d39afff6b646723a2880b862cda4ac7a093b8aa8", size = 223338, upload-time = "2026-08-06T13:48:52.896Z" }, + { url = "https://files.pythonhosted.org/packages/0f/76/e77d0ae22501831cc9f92193e8a957a5caa1dd177f90a6d1d9b106242d92/coverage-7.15.4-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:f41c17c4668a655ce96d090d8d5ffdc24ef64b5a02f9753884d08483e8a4a41a", size = 223609, upload-time = "2026-08-06T13:48:54.688Z" }, + { url = "https://files.pythonhosted.org/packages/82/1a/b1f089da8d38ac612fa2dd6dc7f4a1a7657d12f3e261d2996edd3a838d0b/coverage-7.15.4-cp314-cp314t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:46822e9b6ff1c6a72b518c162c44a8f45a61a1d609c51084bf5b16c023c5037b", size = 264970, upload-time = "2026-08-06T13:48:56.403Z" }, + { url = "https://files.pythonhosted.org/packages/bf/31/e66d98d6e9c7fcc88470f1e234eaf6b1950dc0dfbf797f7282c1c861da24/coverage-7.15.4-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:3d6f4955b73b5445271379a59e3792b0d978f42d4a01e0cf7a67d9c33a3bb0a5", size = 267088, upload-time = "2026-08-06T13:48:58.41Z" }, + { url = "https://files.pythonhosted.org/packages/59/a1/ae94eb2c541add426378408379f233591e069040b1e2cdb33df9498a0682/coverage-7.15.4-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3fc9e047706fb4a9abb54f719d3aa643e80e5bb3818182c40aee01ac0f0247ba", size = 269508, upload-time = "2026-08-06T13:49:00.42Z" }, + { url = "https://files.pythonhosted.org/packages/9c/c7/88a10694a1c6a213569766aba9f25847b28155d4ac731b13226db216356d/coverage-7.15.4-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:05e491d4f3165d62d4f5c8fd48dfeabf2ae8f42cbbd484319af33ea851b78982", size = 270629, upload-time = "2026-08-06T13:49:02.234Z" }, + { url = "https://files.pythonhosted.org/packages/b3/34/d8b8232e5e55169933b59aabcef2fedfa4b9d8897361bb80fcbda146505f/coverage-7.15.4-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:226c66e80ec0598d3b9b4874123df167ccca342aca8714f77cac6829688ee09c", size = 264043, upload-time = "2026-08-06T13:49:04.102Z" }, + { url = "https://files.pythonhosted.org/packages/7e/35/58b009dbf8c471c7224716478b9fed4a7e1af15320e1ed41660978504663/coverage-7.15.4-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:ac41cc14bebda0dbfb0628036b7f75706935c95bcc07fefe9a0f93614aa60a57", size = 266963, upload-time = "2026-08-06T13:49:05.821Z" }, + { url = "https://files.pythonhosted.org/packages/62/aa/57fbda1b42c892968273c56b6ee9dc0f1310850859230a507bc7873b1f65/coverage-7.15.4-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:8af623e5cd92080acddd02b38f2f406a2c3a0893c38950b211890361448fbf26", size = 264569, upload-time = "2026-08-06T13:49:07.706Z" }, + { url = "https://files.pythonhosted.org/packages/98/8a/360e6e7f24d477b7e889703af0afa878d15b6d4d8d2a822b2835c169a879/coverage-7.15.4-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:07545711d4f0f32852a18f18ad11f76f0109909d09e78b9008b4cfc67e829429", size = 268299, upload-time = "2026-08-06T13:49:09.587Z" }, + { url = "https://files.pythonhosted.org/packages/4e/89/6f701261aee21b6b5fa8f7872229406dc917e125069448292223bf213606/coverage-7.15.4-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:a0865421cfdc53654b342d515e5a233187590882d20b95752150e53f65460017", size = 263413, upload-time = "2026-08-06T13:49:11.604Z" }, + { url = "https://files.pythonhosted.org/packages/3f/0f/6f04036edc260ed425af83e834f627fad48941ce97b50bfe6edd8b6fa623/coverage-7.15.4-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:460115e32ee40566476db5048f9bec1e842c127ad8e6f8be745aad3ac9cbc839", size = 265725, upload-time = "2026-08-06T13:49:13.38Z" }, + { url = "https://files.pythonhosted.org/packages/c4/ce/d19b5d4d5c49a7bfb925fd74310fee7d28bc99520ac3367ccbc54e662518/coverage-7.15.4-cp314-cp314t-win32.whl", hash = "sha256:cbde877ef9dd7baf272b9bfef2b8a25edd45d9170fc326951dd20eb480335e85", size = 225079, upload-time = "2026-08-06T13:49:15.265Z" }, + { url = "https://files.pythonhosted.org/packages/26/bb/7aa1b3b173faee0679037ca950bbbe1247273656697994d8d13f80f8d4b4/coverage-7.15.4-cp314-cp314t-win_amd64.whl", hash = "sha256:3da9e92d1c551fd7563833e9ade686efb0c4b7363ab7681a94283958c950bf5e", size = 225911, upload-time = "2026-08-06T13:49:17.279Z" }, + { url = "https://files.pythonhosted.org/packages/81/1c/4ea9e47426d80038d9222db3c4534cb6021a74b237d3ff97ffd33b6600dd/coverage-7.15.4-cp314-cp314t-win_arm64.whl", hash = "sha256:3a54f5a0d85050c73a38f6793090ee83974531e67fe5e57a1da9bee11398aa5e", size = 225219, upload-time = "2026-08-06T13:49:19.293Z" }, + { url = "https://files.pythonhosted.org/packages/2b/c4/dc5d2ac8f9142e7ec7de66e7bf0591db29d78955a040bd915870d9c0e657/coverage-7.15.4-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:2c9872e4d9dc5d3cf616bf4b382f5a00359305a5be666a3dd0b5cdb4e49597f9", size = 222604, upload-time = "2026-08-06T13:49:21.279Z" }, + { url = "https://files.pythonhosted.org/packages/70/39/33e63df81fe2ee100897451841c821467635923e58e37c6bd4b46dd8106c/coverage-7.15.4-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:e101dbb4b9b72f0cddd8cdc8c9c5b47f456766f5e0ac82dbfb75e5c55409b78a", size = 222944, upload-time = "2026-08-06T13:49:23.187Z" }, + { url = "https://files.pythonhosted.org/packages/99/1f/ef3ffb5557febc75a0d97aa459d0266d7d741110265121cc6d8539343d44/coverage-7.15.4-cp315-cp315-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:7d1abebdb047729e852b9c77a00497dfbeb11eb3a117e037d7dbc3ac8e5f5c54", size = 254050, upload-time = "2026-08-06T13:49:25.008Z" }, + { url = "https://files.pythonhosted.org/packages/6f/f5/1f0f6f77698c3601ca0ae7431e34b24c62ca2f06fecb23b73ed1f651d2be/coverage-7.15.4-cp315-cp315-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:d28a4a899354d0ea6214cc59b4fa19eefbce1b9ff1688ab579acf49e894bd3fb", size = 256967, upload-time = "2026-08-06T13:49:26.896Z" }, + { url = "https://files.pythonhosted.org/packages/03/7a/2ed9bed79925f4367c83c77f66a89e5ca7229c288d2d19ad5f36d1ca0070/coverage-7.15.4-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ffb3c2aacea411cc7e1d27712490c11108e2de1d39019ae32915493a59a8b9ed", size = 258587, upload-time = "2026-08-06T13:49:28.692Z" }, + { url = "https://files.pythonhosted.org/packages/45/8c/fa34044f71b7cc4ecb6da9c2408770959b0591fa9b5fb6fb6bca38f94298/coverage-7.15.4-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a9447978a92f405d301123cfd39ff49895490efb769a758fe2734c7f631bf8ce", size = 260785, upload-time = "2026-08-06T13:49:30.472Z" }, + { url = "https://files.pythonhosted.org/packages/4f/54/d5727ce36b4524a7394ab9f5f1df378e1f23affcdab01037dc8655185cc7/coverage-7.15.4-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:050467a7983b8e2fe7dd41a78bb30c3e7f8c0b8cafda14b1c46f8b5e3cf2dd3c", size = 254545, upload-time = "2026-08-06T13:49:32.271Z" }, + { url = "https://files.pythonhosted.org/packages/dc/e6/6e3783e576719590194bdffb6dd6d85490801785b7c331e35a245d8cb8b5/coverage-7.15.4-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:d003b7a5708ddad5c206c79607a6b92abb6fc13c57d99d8a4468cc03a2941ced", size = 256682, upload-time = "2026-08-06T13:49:34.089Z" }, + { url = "https://files.pythonhosted.org/packages/dc/f2/bacdbde18b69ed2de424fcf64d9fb0a4913753d4f0eca8bae9daad69f4bd/coverage-7.15.4-cp315-cp315-musllinux_1_2_i686.whl", hash = "sha256:c38efe30fd74e5c19e9433f11fb1f5dc9c6522770971b7c6145bbaa413dc8800", size = 254560, upload-time = "2026-08-06T13:49:36.052Z" }, + { url = "https://files.pythonhosted.org/packages/6c/a3/1fb927196e3477c1b48831169ab58ba08f451ba87ae311ff1de68b26a616/coverage-7.15.4-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:1f4f826d70f772ab8b0c052329580d7fe8b8abd191e4ce0c8f81aec6614665d3", size = 258792, upload-time = "2026-08-06T13:49:38.01Z" }, + { url = "https://files.pythonhosted.org/packages/41/58/30d4c149c69053de0edfe325614c1d28d508f62b1783e0e4a234d2e49136/coverage-7.15.4-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:4a4bf917c9953f57c957be31c1cd504e3bd2f34d4a352b9d391a3025336f6768", size = 253968, upload-time = "2026-08-06T13:49:39.934Z" }, + { url = "https://files.pythonhosted.org/packages/89/e4/77f639371b918aad30dda4051f95404b43578f7f2e2f87ba73e02ed1ff37/coverage-7.15.4-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:1c9bf40ebef178a45192c75c4964760bb261b0e6ad725da5fc4c93f674f19753", size = 255893, upload-time = "2026-08-06T13:49:41.825Z" }, + { url = "https://files.pythonhosted.org/packages/5c/62/13be29b3ddab35f14c87967a4820a05106d2a3eccb4fa4ff550bf30b75e0/coverage-7.15.4-cp315-cp315-win32.whl", hash = "sha256:43619d04c3671792d2c4706ae8bf45e265dc87bbd4078189ef8b847ea1e74be2", size = 224768, upload-time = "2026-08-06T13:49:44.08Z" }, + { url = "https://files.pythonhosted.org/packages/a1/70/af0c6be0f964af6954f6b74bc109b0dbca02824696d2520fb17fe1ab06e3/coverage-7.15.4-cp315-cp315-win_amd64.whl", hash = "sha256:be619439dbcd31a2eab10b32de9fff62c26ed4bab69dc32b8363fdaaa0882809", size = 225242, upload-time = "2026-08-06T13:49:45.899Z" }, + { url = "https://files.pythonhosted.org/packages/4f/2d/f3bd3aab899fc9efc18b53133ee68f5f98574ef480649b23e12962226387/coverage-7.15.4-cp315-cp315-win_arm64.whl", hash = "sha256:def597967dafc2e8d97c9097ea453c464e0bb8ed38f193a43070f10dc623bb6d", size = 224674, upload-time = "2026-08-06T13:49:48.322Z" }, + { url = "https://files.pythonhosted.org/packages/f5/ca/f69251cd63eabc6438321aea22148754cce758a26bde07dd490e3fe7cfc5/coverage-7.15.4-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:c7dbc748ac8a1e3e59a2b28bea47675e6e778081dbbf081bde0d75def2fcbe1d", size = 223333, upload-time = "2026-08-06T13:49:50.293Z" }, + { url = "https://files.pythonhosted.org/packages/a7/a7/037b53b2885b0d8447064432491a4d5a1014cd9f97a594d53acd0c04541a/coverage-7.15.4-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:2413074a5ecbb61a01a7888fc72db0ca324d13588c5b38bc0dd8564cdcdfea26", size = 223630, upload-time = "2026-08-06T13:49:52.637Z" }, + { url = "https://files.pythonhosted.org/packages/80/4f/152b8a4779ae90da11bb24f7467df8a59f0be48a5c52acb856325ca48289/coverage-7.15.4-cp315-cp315t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:4e6f6f632b7b2f714bf7a1346e8f97b650ee71f3c298aaad42a2ab60f0f07645", size = 264489, upload-time = "2026-08-06T13:49:54.52Z" }, + { url = "https://files.pythonhosted.org/packages/10/2d/84b4b9e0e1dd6528a51920ff7031f35b789382e467a28ec6a5a578cb8812/coverage-7.15.4-cp315-cp315t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:8df457da2249d3c75ca2e5e835d59c725abfe92d27fdff6cd99eed85b51d5e9a", size = 267567, upload-time = "2026-08-06T13:49:56.721Z" }, + { url = "https://files.pythonhosted.org/packages/53/fc/ba01cc25299f9f8a2c8b02d3b28c53f3543d9fbfbe4e74fa2760b48f163e/coverage-7.15.4-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:050f66a08805acb5b8a23c6d4a517b1ecf82c08e81ed0e4bd727df065e5c6624", size = 270123, upload-time = "2026-08-06T13:49:58.736Z" }, + { url = "https://files.pythonhosted.org/packages/cf/d0/db2647cbf40b14f8c308f94ff7bf89c06d564e59f396906edf50086ec788/coverage-7.15.4-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:1587fb771d1ccceef708fdde1e5af8c7ed24b486b61d13a321acb7d8145390aa", size = 271107, upload-time = "2026-08-06T13:50:00.811Z" }, + { url = "https://files.pythonhosted.org/packages/70/ff/4d2d17924552c458bb4f77dd631f0e3bc92fbbdf2d2d916cd4b33bbfd5b1/coverage-7.15.4-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:8b4f1c3a69ca580f3fbd6b2046915f536d7f586874f25c1bb23add2a3c88d50f", size = 264955, upload-time = "2026-08-06T13:50:03.023Z" }, + { url = "https://files.pythonhosted.org/packages/ee/de/dc010c7a3691f396d93bbc26bfcafa1c2a3a351cd520470f15faf5795bd5/coverage-7.15.4-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:ffb58d7eff5b7f6ecc6fa21d6288ab7f968a212cb67d682c269c09b9eba3b66f", size = 267949, upload-time = "2026-08-06T13:50:05.557Z" }, + { url = "https://files.pythonhosted.org/packages/78/ea/dc96a11375e83c045c2f7c61fb6918277cfe9401db7c0f7b1d111a84b2e5/coverage-7.15.4-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:d9df165544774574ee004b953023d1bebada1894a80b1052a43d798b0f676e67", size = 264421, upload-time = "2026-08-06T13:50:07.612Z" }, + { url = "https://files.pythonhosted.org/packages/c8/86/b77131a0f9503ce461cd577076147d7a9040f0c5dda772686f729e2cc9cb/coverage-7.15.4-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:f9de0a24a4079b53e523b5c5e2c5945ec251ab486652659955187cf255a259bc", size = 269121, upload-time = "2026-08-06T13:50:09.58Z" }, + { url = "https://files.pythonhosted.org/packages/24/24/944bc35007862955e7ebf05754e645419dcf5d7526c52735cfa2715e8ebf/coverage-7.15.4-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:150089274bdc9f940628552cb92844e0223c987f1902ab8efe9f45a2ec758d88", size = 264565, upload-time = "2026-08-06T13:50:11.722Z" }, + { url = "https://files.pythonhosted.org/packages/c7/cc/a3bb9f93e7e740659163e2ea584f8196ddcd2c456a5dbe15f6c50105fec1/coverage-7.15.4-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:a58a94fed5da6997d258e8f7668c1e195fbd04a691d781b7558f1e468f9e68bc", size = 266522, upload-time = "2026-08-06T13:50:13.786Z" }, + { url = "https://files.pythonhosted.org/packages/49/dd/e0e40f3560d878d888c580698ff5ad1179f5e1c3ac949684ef66b41a3817/coverage-7.15.4-cp315-cp315t-win32.whl", hash = "sha256:ebd5a6d8466ff30836572f3ba2cae8a5e8f85029b1c6d5e2ed338dc472a5166a", size = 225068, upload-time = "2026-08-06T13:50:15.825Z" }, + { url = "https://files.pythonhosted.org/packages/c6/7e/37732ea80eebc30e976e4cdab15c190bc42d96959a42e38ddf6f8c60468f/coverage-7.15.4-cp315-cp315t-win_amd64.whl", hash = "sha256:288bde2a2d7ab6b6c2d7252fcde8b524387f2d970bdba9658fc6f8bbcaef0f9b", size = 225895, upload-time = "2026-08-06T13:50:17.928Z" }, + { url = "https://files.pythonhosted.org/packages/c6/08/1e00f7923eaaba45fb3d51dd794125fc766304b1df264f3a9c6557bfb30e/coverage-7.15.4-cp315-cp315t-win_arm64.whl", hash = "sha256:68be5e1de60ff13c9095bbec0e5a7fa45b33b101752215b91345ea1f61c4a278", size = 225213, upload-time = "2026-08-06T13:50:19.981Z" }, + { url = "https://files.pythonhosted.org/packages/b4/d9/e70c286c979378f061d8266e279b686ab0b0b688e1fe0af864684f23a77d/coverage-7.15.4-py3-none-any.whl", hash = "sha256:964730a1e9de9c0cf11be6a1a3c79ce419c34882842abd256086ba4698705e84", size = 214332, upload-time = "2026-08-06T13:50:22.192Z" }, +] + +[[package]] +name = "duckdb" +version = "1.5.5" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7d/19/e57151753576373c6696a12022648546cca6038e8833fda2908ee2342d9b/duckdb-1.5.5.tar.gz", hash = "sha256:72f33ee57ca7595b23957671a2cc7f7fe2be0ecc2d68f63abedcfcaa3a5c1238", size = 18066741, upload-time = "2026-07-22T10:55:17.819Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d6/40/2e05d324400fdaa5656c9f48d6298da421cb034d85e509fa0e6e325cf04b/duckdb-1.5.5-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:d4dd65f8941a604b947e0b9b4b4f7165988e29a23ec0b69b4038520956d9933e", size = 32753858, upload-time = "2026-07-22T10:54:05.514Z" }, + { url = "https://files.pythonhosted.org/packages/79/15/5ceb58ffb5bb8a62b3fd7abb39c41467cdf94850ece02e6d88664dfc75ce/duckdb-1.5.5-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:33db46679b071f108d57139493dee2d37e1f5efcf5c5c039c2969eed11a6c8a7", size = 17368293, upload-time = "2026-07-22T10:54:09.139Z" }, + { url = "https://files.pythonhosted.org/packages/bf/5c/bf02da0b354fe83cca4f95a4fbf762181af466f7d551ab2a093f7698882a/duckdb-1.5.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f0b88535a5d86fdd63dba6ea02ab68c003dfb9e4892b11256ef24c4da208baae", size = 15509131, upload-time = "2026-07-22T10:54:12.228Z" }, + { url = "https://files.pythonhosted.org/packages/ea/a9/5f1f09da421d8e930e0b063d11c1b3f90363f40ede74438cd188afdd13a2/duckdb-1.5.5-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f316eae2323d9a851883fdf2dee91c1f9efe251ab33e14a2272f82a913422ed6", size = 19391959, upload-time = "2026-07-22T10:54:15.551Z" }, + { url = "https://files.pythonhosted.org/packages/4f/98/6549769f158126fa64fd6c1ac2eb59a18282146c939867a3eb31b7c1db07/duckdb-1.5.5-cp312-cp312-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7a6d2d11859d82a936ebdcb30ce3d8a1cbb3e990bff05c12abb9b54c44fa7bd1", size = 21510909, upload-time = "2026-07-22T10:54:19.681Z" }, + { url = "https://files.pythonhosted.org/packages/af/b7/5753b41d3124838f868f9f523362812d9fc45409e9e4dd70dcbb0a25826e/duckdb-1.5.5-cp312-cp312-win_amd64.whl", hash = "sha256:ddfbdb096c11d51ee22492397d342c90a82e62c5d09961477895934d0a25372f", size = 13168544, upload-time = "2026-07-22T10:54:22.789Z" }, + { url = "https://files.pythonhosted.org/packages/5c/28/44b679c7d46245f8398feae7edac959d1b83d4eb143e25b3fce0630b78bd/duckdb-1.5.5-cp312-cp312-win_arm64.whl", hash = "sha256:2725d2b9ace3a4e75d72fc5a239f6a44b502c580edadb8fb2676db772c5f9282", size = 13988684, upload-time = "2026-07-22T10:54:26.003Z" }, + { url = "https://files.pythonhosted.org/packages/47/37/4a38116e7700720fd152c666292214fd3abdf916496991296d8d1f66efbf/duckdb-1.5.5-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:cd98829b67788609017e65c761bd42a5dd0f9129441bed8bda4d6881ccf819f0", size = 32754294, upload-time = "2026-07-22T10:54:29.822Z" }, + { url = "https://files.pythonhosted.org/packages/66/42/7d392f1ba1eee0eaf4ab4c8c7a604bfe3536cd63f979cf5c98798664f807/duckdb-1.5.5-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:feead93c56679b79592d437c62975d39cb67adedffa7592c763baf8160ac7366", size = 17368211, upload-time = "2026-07-22T10:54:33.359Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/0a6f4fa60562faa615e55e15bd1953a2f2b17a8edd8105e5cda215e43457/duckdb-1.5.5-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:49c963d9469373d7aba8d750d9ea565ab823e94166efed953f184dd9b169b98c", size = 15509136, upload-time = "2026-07-22T10:54:36.369Z" }, + { url = "https://files.pythonhosted.org/packages/e4/cb/023c89f51978545b9fab318581bba0c457a58e7530d2d933e54ae7d8647c/duckdb-1.5.5-cp313-cp313-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a736217825461732b5442d05a220f3da2e23a0dae114efbf08c9bf171b53098a", size = 19392147, upload-time = "2026-07-22T10:54:39.551Z" }, + { url = "https://files.pythonhosted.org/packages/3e/c5/41bef391fb8b23dbc133c9f2ba016e7a7a8124513d2cc1b430f1897d87e4/duckdb-1.5.5-cp313-cp313-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:078e6a60dd8eedde5832f45422ca5c4a6b8c837aeabd8a56ca0b7d933f588053", size = 21511060, upload-time = "2026-07-22T10:54:42.788Z" }, + { url = "https://files.pythonhosted.org/packages/07/9f/c44dfc1f924ac29b3252dc1b91393c01d009dbfe9f8ed33f10b986151bd1/duckdb-1.5.5-cp313-cp313-win_amd64.whl", hash = "sha256:6826504277dba513c0c5d71d828456c94d729c9d2482f94b2e289f90a9167e28", size = 13168028, upload-time = "2026-07-22T10:54:46.127Z" }, + { url = "https://files.pythonhosted.org/packages/ca/88/591384b2cd59abddd6f5dc175e60374f9abae6064429f0c4402854c10f44/duckdb-1.5.5-cp313-cp313-win_arm64.whl", hash = "sha256:baa9c5702002fabb559ded2a39008f9f421fcbc7237d388b8213eff1e08858de", size = 13989955, upload-time = "2026-07-22T10:54:49.262Z" }, + { url = "https://files.pythonhosted.org/packages/3e/56/12c65bfa2d2605b81981b264788891bcf11ec72227889554cead5d8d13b9/duckdb-1.5.5-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:8e6413dd40facb7b8ab21bd844450cd8f549b29e138635be9cf090ef4d2049e2", size = 32761946, upload-time = "2026-07-22T10:54:53.412Z" }, + { url = "https://files.pythonhosted.org/packages/b9/46/682ce155f17e0d2822d4f13ee3db9ca4b5b7c2da61b841b2629035e1f4bc/duckdb-1.5.5-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:64078acfd16541132ac6e191eb81b2845554444a0305cc1aa581ba107e514aa8", size = 17375069, upload-time = "2026-07-22T10:54:57.269Z" }, + { url = "https://files.pythonhosted.org/packages/39/ce/a24bcbd3289c8f305a430759c5fc12242740b4af3e17f7593f3a34e333d2/duckdb-1.5.5-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:8c11775cc99a447618d5f1840126db17f2652f3eae05529df4f81f40e2df7151", size = 15519791, upload-time = "2026-07-22T10:55:00.681Z" }, + { url = "https://files.pythonhosted.org/packages/d9/76/3a01afbc615c1d418c0de58a6b68ac5ce2a8563232c0464bfbc2ce552398/duckdb-1.5.5-cp314-cp314-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:77bbc1e6ba12e1e06f9020117bdf848627ecfdf36f907550e62e008e6109dece", size = 19398251, upload-time = "2026-07-22T10:55:04.168Z" }, + { url = "https://files.pythonhosted.org/packages/a1/43/3a5e81d1728f4d234c79bfe385808ee7c04834f7c37a4b5c257459c25614/duckdb-1.5.5-cp314-cp314-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fbf0f2d48b43c6c304d00463b463c27ead6c4b01c3c1816b750f728decf71afe", size = 21513851, upload-time = "2026-07-22T10:55:07.864Z" }, + { url = "https://files.pythonhosted.org/packages/91/41/fc7c829172c60ca22485251eab285f4f1a0d87b486a024c726f21471d86e/duckdb-1.5.5-cp314-cp314-win_amd64.whl", hash = "sha256:9dc826c4b50e64f6c4e4d07a3a9cb075ef70ba3899dc43ec5493dc3d7b04b353", size = 13691858, upload-time = "2026-07-22T10:55:11.181Z" }, + { url = "https://files.pythonhosted.org/packages/e1/2c/95d9216b79e9273689d7ebce125a54503ed0c9bd7da931f0265888e99779/duckdb-1.5.5-cp314-cp314-win_arm64.whl", hash = "sha256:63e48d4b74b15aeacd688976432a7225163df8c226eddeb8536bba2d4d4ff433", size = 14470180, upload-time = "2026-07-22T10:55:14.445Z" }, +] + +[[package]] +name = "event-driven-microstructure" +version = "0.1.0" +source = { editable = "." } +dependencies = [ + { name = "duckdb" }, + { name = "numpy" }, + { name = "polars" }, + { name = "pyarrow" }, + { name = "requests" }, + { name = "scikit-learn" }, + { name = "streamlit" }, + { name = "websockets" }, +] + +[package.optional-dependencies] +dev = [ + { name = "mypy" }, + { name = "pytest" }, + { name = "pytest-cov" }, + { name = "ruff" }, + { name = "types-requests" }, +] + +[package.metadata] +requires-dist = [ + { name = "duckdb", specifier = ">=1.1,<2" }, + { name = "mypy", marker = "extra == 'dev'", specifier = ">=1.13,<2" }, + { name = "numpy", specifier = ">=2,<3" }, + { name = "polars", specifier = ">=1.20,<2" }, + { name = "pyarrow", specifier = ">=18,<24" }, + { name = "pytest", marker = "extra == 'dev'", specifier = ">=8.3,<10" }, + { name = "pytest-cov", marker = "extra == 'dev'", specifier = ">=6,<8" }, + { name = "requests", specifier = ">=2.32,<3" }, + { name = "ruff", marker = "extra == 'dev'", specifier = ">=0.8,<1" }, + { name = "scikit-learn", specifier = ">=1.5,<2" }, + { name = "streamlit", specifier = ">=1.40,<2" }, + { name = "types-requests", marker = "extra == 'dev'", specifier = ">=2.32,<3" }, + { name = "websockets", specifier = ">=14,<17" }, +] +provides-extras = ["dev"] + +[[package]] +name = "h11" +version = "0.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/01/ee/02a2c011bdab74c6fb3c75474d40b3052059d95df7e73351460c8588d963/h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1", size = 101250, upload-time = "2025-04-24T03:35:25.427Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" }, +] + +[[package]] +name = "httptools" +version = "0.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/43/e5/d471fcb0e14523fe1c3f4ba58ca52480e7bd70ad7109a3846bc75892f7fb/httptools-0.8.0.tar.gz", hash = "sha256:6b2a32f18d97e16e90827d7a819ffa8dbd8cc245fc4e1fa9d1095b54ef4bd999", size = 271342, upload-time = "2026-05-25T22:17:48.841Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/14/88/1d21a36da8f5cb0fa49eafd4b169eba5608d57e75bbcf61845cbc6243216/httptools-0.8.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:880490234c10f70a9830743097e8958d6e4b9f5a0ffc24515023afeef984054d", size = 208247, upload-time = "2026-05-25T22:17:07.843Z" }, + { url = "https://files.pythonhosted.org/packages/a5/42/cc4feea2945cb3051038f090c9b36bd5b8a9d7f5a894a506a8983e33fd1c/httptools-0.8.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:5931891fb7b441b8a3853cf1b85c82c903defce084dd5f6771ca46e31bf862c5", size = 113064, upload-time = "2026-05-25T22:17:09.136Z" }, + { url = "https://files.pythonhosted.org/packages/e3/a6/febbb8b8db0f58b38e44ad6cb946e6a255ae49b55f2e8543408fb7501ccd/httptools-0.8.0-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:b15fc622b0f869d19207c4089a501d9bcc63ca5e071ffdd2f03f922df882dcb2", size = 523851, upload-time = "2026-05-25T22:17:10.106Z" }, + { url = "https://files.pythonhosted.org/packages/b7/e4/f90a0df0b83beff265b7e3b65f2a4cefd95792d4be0ac3e16049f2acd3c2/httptools-0.8.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:425f83884fd6343828d8c565f046cb72b6d19063f6924093e11bcd8e1548cd09", size = 518842, upload-time = "2026-05-25T22:17:11.218Z" }, + { url = "https://files.pythonhosted.org/packages/9e/2d/0c9ac76dd2c893841fbf6498d6acec4f2442e1b7067f6e3e316a80e494e8/httptools-0.8.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:ef7c3c97f4311c7be57e2986629df89d49cb434dbff78eafcd48c2bff986b15a", size = 501238, upload-time = "2026-05-25T22:17:12.728Z" }, + { url = "https://files.pythonhosted.org/packages/ca/42/906adc91ae3a5fa9c59c0a2f21c139725bd7e5b41ae6acd485cd14123ebf/httptools-0.8.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a1afd7c9fbff0d9f5d489c4ce2768bd09c84a46ddefc7161e6aa82ae35c85745", size = 509567, upload-time = "2026-05-25T22:17:13.842Z" }, + { url = "https://files.pythonhosted.org/packages/05/0b/4240efeb672751ee5b9b380cb0e3fdc050bc05f68adc7a8aefc4fcd9a69a/httptools-0.8.0-cp312-cp312-win_amd64.whl", hash = "sha256:cd96f29b4bab1d42fa6e3d008711c75e0f79e94e06827330160e3a304227f150", size = 90918, upload-time = "2026-05-25T22:17:15.155Z" }, + { url = "https://files.pythonhosted.org/packages/5e/e5/8cfcabc5546e8022f168be28bcdaa128a240a0befdd03b59d558b4f18bd6/httptools-0.8.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:614ceea8ea606848bece2338ac03b3ce5324bcb4be8dc7d377ed708012fa4db8", size = 205148, upload-time = "2026-05-25T22:17:16.333Z" }, + { url = "https://files.pythonhosted.org/packages/2a/0e/0fb14848c19a686c8062ff9067c1a48793e3224b47bc5b201535b6036fce/httptools-0.8.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:2d689918c15a013c65ef52d9fd495d766893ab831a2c8d89f2ac5940a5df847c", size = 111368, upload-time = "2026-05-25T22:17:17.586Z" }, + { url = "https://files.pythonhosted.org/packages/2e/1b/46f1cecf06b9bbde8e4b8c88034ac7908989e5ff7a3a388ef38392949c1f/httptools-0.8.0-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:eb3028cca2fc0a6d720e52ef61d8ebb62fcbfeb1de56874546d858d3f25a26b7", size = 486447, upload-time = "2026-05-25T22:17:18.564Z" }, + { url = "https://files.pythonhosted.org/packages/77/00/258bfc0837221f81d9725c45f9b948a6a6b2994a147a4fb66e85100c668f/httptools-0.8.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:88bdd940f2b5d487b4d032c6afa5489a7dc4694410d43de3c38c4fb3af0dc45d", size = 482448, upload-time = "2026-05-25T22:17:19.912Z" }, + { url = "https://files.pythonhosted.org/packages/04/ab/d1cef3b5523f4d272a70f42a776c3169a2dddfe3a54de4b2ce4a36341528/httptools-0.8.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:6a43c9dd399758ccc0531acb0a3c4a6c299ee893ee9400e9c893b7bdcfae0681", size = 464460, upload-time = "2026-05-25T22:17:20.882Z" }, + { url = "https://files.pythonhosted.org/packages/ce/48/5d1d072442277bb2b3434e0e60690b8e8c23840ef7de8b6ea54040a536d3/httptools-0.8.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:0770728beb05094c809b98e814edff5fef69d26ad7d21185f2f6d5884a0ba683", size = 471312, upload-time = "2026-05-25T22:17:22.085Z" }, + { url = "https://files.pythonhosted.org/packages/0d/66/b96623b27e51a68199ef4efdda0613cced9233fe3062ac74e50749c5ad37/httptools-0.8.0-cp313-cp313-win_amd64.whl", hash = "sha256:7685df791fad561384bfb139e77fde27a1ffd93134e016f95a0db424ffbf77b1", size = 90117, upload-time = "2026-05-25T22:17:23.074Z" }, + { url = "https://files.pythonhosted.org/packages/1a/12/fa3fbf5f9517b273edea2dc982aa82a8c634091e67c590792b729017bc6f/httptools-0.8.0-cp314-cp314-macosx_10_13_universal2.whl", hash = "sha256:de242a49b5d18e0a8776e654e9f6bf6d89f3875a5c35b425a0e7ce940feb3fd6", size = 206183, upload-time = "2026-05-25T22:17:24.004Z" }, + { url = "https://files.pythonhosted.org/packages/30/fc/5e7c4cb443370f2090a3aba0453a07384d29ff66b7435bb90e77e1037599/httptools-0.8.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:159e9ab5f701ccd42e555a12f1ad8ff69702910fc1c996cf2bb66e5fcb7a231b", size = 112079, upload-time = "2026-05-25T22:17:25.216Z" }, + { url = "https://files.pythonhosted.org/packages/ba/53/771bd891eb0f236f32145d6a1775777ec85745f3cc983a1f23d1a3b8ddfe/httptools-0.8.0-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:c4a9f1707e4823d54dfec6c33fa3697d302aed536ed352a7ebb5a061ddb869d0", size = 481596, upload-time = "2026-05-25T22:17:26.186Z" }, + { url = "https://files.pythonhosted.org/packages/62/42/94e15bc68ce3d423243c45d7f1b0c7561f13844f97dc52ae23182fb65628/httptools-0.8.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d76ad7b951387e3632c8716a9bb03ac5b45c5f16119aa409db0459520887944e", size = 480865, upload-time = "2026-05-25T22:17:27.542Z" }, + { url = "https://files.pythonhosted.org/packages/1c/7c/fe2980fc03723272e30f135b62360b075f513dfe7cc73aef36c7f04012bd/httptools-0.8.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:a3b7387147361c3fd47a0bde763c5c91b5b4cd4dc9989b8ece84ff436c99843b", size = 463189, upload-time = "2026-05-25T22:17:28.546Z" }, + { url = "https://files.pythonhosted.org/packages/15/1b/47fc5fff68acd1bfa20b4734059c9a06cadb88119dcd5258b5b0d21d91c8/httptools-0.8.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:f256d6ce930c52ca1cb2a960b7da03548c454e7d28b06059ad41bfe789036ce0", size = 466610, upload-time = "2026-05-25T22:17:29.816Z" }, + { url = "https://files.pythonhosted.org/packages/60/bd/07b13c93ffd9bec9546e0d43f8e19378dd696dbd278511406bc07371ef1f/httptools-0.8.0-cp314-cp314-win_amd64.whl", hash = "sha256:19d1ee275bb59ba2643ba9a3a1e51cc0c788caf2b8df506368e03f56fdd08527", size = 92705, upload-time = "2026-05-25T22:17:31.133Z" }, + { url = "https://files.pythonhosted.org/packages/fd/c4/121648f68ce066d7bd762d6b6d97e620847642d38d54f3d90ff11d947629/httptools-0.8.0-cp314-cp314t-macosx_10_13_universal2.whl", hash = "sha256:de1ed58a974e75d56560acc7e7fed01a454994429456f65209789992e41f2568", size = 215023, upload-time = "2026-05-25T22:17:32.401Z" }, + { url = "https://files.pythonhosted.org/packages/b9/b0/312a062ae741ae3e8baa8c8bf20be81b2e67337b259ab4349bebc7b6142e/httptools-0.8.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:e93c227b595c6926c1acee96891dd9da4be338cfbe82e5cd3bb9d8dd7dc4ac0b", size = 117405, upload-time = "2026-05-25T22:17:33.742Z" }, + { url = "https://files.pythonhosted.org/packages/fc/37/fccd705f795386bb05bf413012fecff2a33e5aa8c2f069096de3e9fd8702/httptools-0.8.0-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:2a021c3a8e65cc125390d72f59b968afca3bdcaff25bd67965e0a055a14946ca", size = 558497, upload-time = "2026-05-25T22:17:34.732Z" }, + { url = "https://files.pythonhosted.org/packages/bd/39/f172e8003576de35f5ba77ff417cf0e34429d35dc014deef15afa337a72c/httptools-0.8.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:48774d39cbb70e2b1f71f88852a3087ae1d3a1eb80482bb48c13067ab080c14f", size = 571585, upload-time = "2026-05-25T22:17:35.813Z" }, + { url = "https://files.pythonhosted.org/packages/3e/b9/f5564760af99f3dbbf3f9104dc00e5da27e96cf433c6bdcf77617f70bf3f/httptools-0.8.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:88eead8ec8680a9f146c655bc88445a325bd7921cfd8194c7337e9467282427d", size = 543297, upload-time = "2026-05-25T22:17:37.08Z" }, + { url = "https://files.pythonhosted.org/packages/99/67/8d9f2c313618e161b82f3873188e7196126da1d6e29688df40eb3997c77a/httptools-0.8.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:2c032fa028f46871ec7e1fc59fc15e8023eab3e6bbe6ece786a1611719a5d081", size = 539535, upload-time = "2026-05-25T22:17:38.032Z" }, + { url = "https://files.pythonhosted.org/packages/48/63/b906c01e53f50d432c0defe43ce52764a111dc1bdd028bafbeb54dcfd008/httptools-0.8.0-cp314-cp314t-win_amd64.whl", hash = "sha256:384c17174464c8e873398b7af24f0b1f44d992c820328413951a625323155d77", size = 108209, upload-time = "2026-05-25T22:17:39.473Z" }, +] + +[[package]] +name = "idna" +version = "3.18" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/cd/63/9496c57188a2ee585e0f1db071d75089a11e98aa86eb99d9d7618fc1edce/idna-3.18.tar.gz", hash = "sha256:ffb385a7e039654cef1ab9ef32c6fafe283c0c0467bba1d9029738ce4a14a848", size = 196711, upload-time = "2026-06-02T14:34:07.794Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1e/5e/d4e9f1a599fb8e573b7b87160658329fbf28d19eac2718f51fc3def3aa5a/idna-3.18-py3-none-any.whl", hash = "sha256:7f952cbe720b688055e3f87de14f5c3e5fdaa8bc3928985c4077ca689de849a2", size = 65455, upload-time = "2026-06-02T14:34:06.319Z" }, +] + +[[package]] +name = "iniconfig" +version = "2.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/72/34/14ca021ce8e5dfedc35312d08ba8bf51fdd999c576889fc2c24cb97f4f10/iniconfig-2.3.0.tar.gz", hash = "sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730", size = 20503, upload-time = "2025-10-18T21:55:43.219Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" }, +] + +[[package]] +name = "itsdangerous" +version = "2.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9c/cb/8ac0172223afbccb63986cc25049b154ecfb5e85932587206f42317be31d/itsdangerous-2.2.0.tar.gz", hash = "sha256:e0050c0b7da1eea53ffaf149c0cfbb5c6e2e2b69c4bef22c81fa6eb73e5f6173", size = 54410, upload-time = "2024-04-16T21:28:15.614Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/04/96/92447566d16df59b2a776c0fb82dbc4d9e07cd95062562af01e408583fc4/itsdangerous-2.2.0-py3-none-any.whl", hash = "sha256:c6242fc49e35958c8b15141343aa660db5fc54d4f13a1db01a3f5891b98700ef", size = 16234, upload-time = "2024-04-16T21:28:14.499Z" }, +] + +[[package]] +name = "jinja2" +version = "3.1.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markupsafe" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/df/bf/f7da0350254c0ed7c72f3e33cef02e048281fec7ecec5f032d4aac52226b/jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d", size = 245115, upload-time = "2025-03-05T20:05:02.478Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", size = 134899, upload-time = "2025-03-05T20:05:00.369Z" }, +] + +[[package]] +name = "joblib" +version = "1.5.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/41/f2/d34e8b3a08a9cc79a50b2208a93dce981fe615b64d5a4d4abee421d898df/joblib-1.5.3.tar.gz", hash = "sha256:8561a3269e6801106863fd0d6d84bb737be9e7631e33aaed3fb9ce5953688da3", size = 331603, upload-time = "2025-12-15T08:41:46.427Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7b/91/984aca2ec129e2757d1e4e3c81c3fcda9d0f85b74670a094cc443d9ee949/joblib-1.5.3-py3-none-any.whl", hash = "sha256:5fc3c5039fc5ca8c0276333a188bbd59d6b7ab37fe6632daa76bc7f9ec18e713", size = 309071, upload-time = "2025-12-15T08:41:44.973Z" }, +] + +[[package]] +name = "jsonschema" +version = "4.26.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "attrs" }, + { name = "jsonschema-specifications" }, + { name = "referencing" }, + { name = "rpds-py" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b3/fc/e067678238fa451312d4c62bf6e6cf5ec56375422aee02f9cb5f909b3047/jsonschema-4.26.0.tar.gz", hash = "sha256:0c26707e2efad8aa1bfc5b7ce170f3fccc2e4918ff85989ba9ffa9facb2be326", size = 366583, upload-time = "2026-01-07T13:41:07.246Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/69/90/f63fb5873511e014207a475e2bb4e8b2e570d655b00ac19a9a0ca0a385ee/jsonschema-4.26.0-py3-none-any.whl", hash = "sha256:d489f15263b8d200f8387e64b4c3a75f06629559fb73deb8fdfb525f2dab50ce", size = 90630, upload-time = "2026-01-07T13:41:05.306Z" }, +] + +[[package]] +name = "jsonschema-specifications" +version = "2025.9.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "referencing" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/19/74/a633ee74eb36c44aa6d1095e7cc5569bebf04342ee146178e2d36600708b/jsonschema_specifications-2025.9.1.tar.gz", hash = "sha256:b540987f239e745613c7a9176f3edb72b832a4ac465cf02712288397832b5e8d", size = 32855, upload-time = "2025-09-08T01:34:59.186Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/41/45/1a4ed80516f02155c51f51e8cedb3c1902296743db0bbc66608a0db2814f/jsonschema_specifications-2025.9.1-py3-none-any.whl", hash = "sha256:98802fee3a11ee76ecaca44429fda8a41bff98b00a0f2838151b113f210cc6fe", size = 18437, upload-time = "2025-09-08T01:34:57.871Z" }, +] + +[[package]] +name = "librt" +version = "0.15.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/36/9b/356320fbae2ac8467e21c5e73e1389c80468e4998c62cc7d3536cc51b614/librt-0.15.0.tar.gz", hash = "sha256:4e66cbe84437497d951b799d3e1551291b6fb3d643820a7014b3655d57a59162", size = 214338, upload-time = "2026-08-07T10:49:42.663Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ba/39/99c25030e782bdfb7a21be8c05254806a2e4bbb05c8d50c2a2130acbfa05/librt-0.15.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:e87bc679f86a99aa3b26e3c78eeb821a247c9a28eae48eaafcc32c3bf4c3bb9e", size = 151021, upload-time = "2026-08-07T10:47:00.057Z" }, + { url = "https://files.pythonhosted.org/packages/14/43/f4b1bd1b2888798a1409808889a25ea1ba49eaabce7d681ed27734c2df9d/librt-0.15.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:71599e011ac880e8e45d46047d714871894c7d4ab6f25626f8d4f89da21f368d", size = 155267, upload-time = "2026-08-07T10:47:01.311Z" }, + { url = "https://files.pythonhosted.org/packages/0c/db/3ad9c965c72f1e1d6beeec44ec10a54e17be8ae042fbb4baade16cbadced/librt-0.15.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c802434092b769b1d613ed2e13fac15fbfce1934a74bd10283b03c0fae231cd1", size = 503136, upload-time = "2026-08-07T10:47:02.45Z" }, + { url = "https://files.pythonhosted.org/packages/4b/07/5888a6d76acd62ebce66c61b74d94e9370b9c32929f111e487bb6546f8ed/librt-0.15.0-cp312-cp312-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:5500eeae393a184d14e1f35645962c27129d20c81afa4069e6ef826ebc2b3aaa", size = 496670, upload-time = "2026-08-07T10:47:03.675Z" }, + { url = "https://files.pythonhosted.org/packages/29/39/ab57cc2f5b276156da02bb7f5a8921bada1cb1993ffec99acf811c602c23/librt-0.15.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:6ecfc32dfb46fb7b565bcd6abf9412acf978775a998273d22888a6d7953730dd", size = 513688, upload-time = "2026-08-07T10:47:04.981Z" }, + { url = "https://files.pythonhosted.org/packages/a7/b9/bdbb0b648b5c2befb031f4c6f3b1dd857415e8fb492a25a3c764a6681e6c/librt-0.15.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:89cc46cfd15022e35084355478c9ac809d90b1152222706ac9a7655ec21df6fa", size = 531904, upload-time = "2026-08-07T10:47:06.211Z" }, + { url = "https://files.pythonhosted.org/packages/93/26/473c2e4b6c104e9e58e27ce95fc8005c8bd4fc36cae4f254371125a92db8/librt-0.15.0-cp312-cp312-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:d5f51401d102c885b9ca509e62c79b1dbff286e1b9b047fde6f763780789356d", size = 524427, upload-time = "2026-08-07T10:47:07.592Z" }, + { url = "https://files.pythonhosted.org/packages/26/60/03b3abb82b41714671b907bf6989b228e31e6a8af52dec82b5b0728dc250/librt-0.15.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:cc30523e3f1a23fb7511cc659834a0d01a1042bb9de359bc1c131cc4ec6c9656", size = 543155, upload-time = "2026-08-07T10:47:08.866Z" }, + { url = "https://files.pythonhosted.org/packages/f2/0e/9bb1f0a4affbd0a1888f4f79dc03ed2a299d9a2c26c59ab2a97dcbf11903/librt-0.15.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:59fe030d8ae4a57e3fb7756bf35a858de74e04066fc8555c53d0af979132af81", size = 546890, upload-time = "2026-08-07T10:47:10.327Z" }, + { url = "https://files.pythonhosted.org/packages/dc/84/6937a280d461f7de6e031ffb02edc2b7c3c90d49d630565ce8ff27cbc5f2/librt-0.15.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:5a6526a2a956bbb1e4ae3568c82e650fc99119c66bb011ea60715744955a2b4d", size = 555163, upload-time = "2026-08-07T10:47:11.798Z" }, + { url = "https://files.pythonhosted.org/packages/bc/95/2a2853c1ee014bf102116e7f897a04beeaeb2461b45b79af98bdfb95f1ef/librt-0.15.0-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:85ea21ec6730194d67156b0e0b5430ccb1d61f8b8b907e39b37f9812b74a13f0", size = 535812, upload-time = "2026-08-07T10:47:13.279Z" }, + { url = "https://files.pythonhosted.org/packages/c9/4c/cf9601c1b4c5f09280acd5d83abdb2e68527a2be8257136eb42304218622/librt-0.15.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:1e47b8ba865d7ede071a91a7163073bbaeb72541f1ef8a07d512c45c7b5007f2", size = 573688, upload-time = "2026-08-07T10:47:14.727Z" }, + { url = "https://files.pythonhosted.org/packages/47/6d/9ac7cbec46189a7625af4b5acbd25f10d827f4141b2002181848c8418923/librt-0.15.0-cp312-cp312-win32.whl", hash = "sha256:a5207ec414d1c4a2a7231b2086970dc036f94293cdf338190984958a013a42f1", size = 106138, upload-time = "2026-08-07T10:47:15.973Z" }, + { url = "https://files.pythonhosted.org/packages/38/d0/2ae99c83be86ce23f925ac1aeeedc777e97f427c4a8d190c70d0a16e9a87/librt-0.15.0-cp312-cp312-win_amd64.whl", hash = "sha256:73b30cfa976659b3917c8f6153bdb0591c6a9ec6583599fd24a689b690622022", size = 126974, upload-time = "2026-08-07T10:47:17.049Z" }, + { url = "https://files.pythonhosted.org/packages/5d/ef/dd24f9635c730b86b87587967dda7516b1845e8b17684603d31607fed598/librt-0.15.0-cp312-cp312-win_arm64.whl", hash = "sha256:a54cf9e0ef47b96af580849db5471142200568ce1e02cbf416addab551369570", size = 112292, upload-time = "2026-08-07T10:47:18.222Z" }, + { url = "https://files.pythonhosted.org/packages/e7/42/467b53a601b406ccd7b97c1fd54b59cb34f9185ad5ce7e9d5c3c4e8961c8/librt-0.15.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:db13ca398005abcbe538deda87b686d9bd08b7001cf40c4c06b444960ae10a26", size = 151029, upload-time = "2026-08-07T10:47:19.312Z" }, + { url = "https://files.pythonhosted.org/packages/3e/e6/36c2299b7a94b84fdd01220d8a777a71be5be0925bb0dbdf71c0a06a34d9/librt-0.15.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:aa1f1995789dca3698bc550aaceb09a51bd5df0a057ff84ff15296cd1975b801", size = 155194, upload-time = "2026-08-07T10:47:20.398Z" }, + { url = "https://files.pythonhosted.org/packages/c9/b6/ed5071f9325845e670bd36012757419767fbf56af77ed483077b9e4db541/librt-0.15.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:55456ea87d8df21808446d03817be2f65e20391c1c615d9187440dff28cd08dc", size = 502568, upload-time = "2026-08-07T10:47:21.652Z" }, + { url = "https://files.pythonhosted.org/packages/7f/81/6450c67c3615d87704bcbc21323fafc69c799b06a044c447529f725d4b01/librt-0.15.0-cp313-cp313-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:5a86a5a08c2235316bdb359d5dbb6ce0abfca7fac06363103e2c5af571d92f95", size = 496153, upload-time = "2026-08-07T10:47:22.925Z" }, + { url = "https://files.pythonhosted.org/packages/e1/d6/5f52b722bc75076954b3bfd49be15ea362df4d580c6fb315d0f617100d30/librt-0.15.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e56b6a368529bed262da40ce13f8fef590db0479819cca84f16a1f01ac356d0b", size = 513336, upload-time = "2026-08-07T10:47:24.213Z" }, + { url = "https://files.pythonhosted.org/packages/8d/e2/c08fd1d36ce63ea5a12b85c5d37f4550b5f86a692167e41e5a74222607ae/librt-0.15.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:234d8d394721fa0d786af15ebf1f3fb7f3ed82fd1cd0cde45c2f247b5d4281d2", size = 531661, upload-time = "2026-08-07T10:47:25.507Z" }, + { url = "https://files.pythonhosted.org/packages/3f/d8/d9482fcbeb177b9eb87bb3899eeb3b42be690313c652f9e146b1d0681fb2/librt-0.15.0-cp313-cp313-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:d8363d7accb0286ac3a0e633f396e93800dafb8150494505daf9515bbda591f3", size = 524487, upload-time = "2026-08-07T10:47:26.79Z" }, + { url = "https://files.pythonhosted.org/packages/10/cc/075171517b41f861753034fbb151b42cfc83bcc853849f24f5e66fd60ccf/librt-0.15.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:0f0ee3644d951f31055ad07d77d92520e84505dd7a432cc4cd501dd70ee06785", size = 543201, upload-time = "2026-08-07T10:47:27.999Z" }, + { url = "https://files.pythonhosted.org/packages/b0/03/42c2330f37eeb475b6affeedd06518f60035f323af3a839335e3fc9fef2d/librt-0.15.0-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:2cfd1a81a648806e6a7717be4cc4d1bb392fa229752bf8444ba365e381e984d6", size = 546467, upload-time = "2026-08-07T10:47:29.396Z" }, + { url = "https://files.pythonhosted.org/packages/57/1e/1ad4c5638f7e64d8560328bd25c54b409a661bdb6ff254b38ff90744288d/librt-0.15.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:a6cd22c9da0d866558e46a041f1cc0c2bbb26b61b137b2347fa834c332e1d101", size = 555139, upload-time = "2026-08-07T10:47:30.815Z" }, + { url = "https://files.pythonhosted.org/packages/49/41/39fa7d15db1204cd1cbe6514680fbdc243adf754a0885061308f43afc013/librt-0.15.0-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:6d5225ef8801e4ea5e482fa9b5dfb891dd9ef6f6d870f1f25d449ca2c70ac218", size = 536050, upload-time = "2026-08-07T10:47:32.222Z" }, + { url = "https://files.pythonhosted.org/packages/1e/88/c6dcf0dd8e26dc0c9a499a2abab8646c86dcaf9ecea9524cb46d3686331a/librt-0.15.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6d28a05796b99f749bf8794f17ba9ba1612d0076b802e9cfc62c554634e9ce3b", size = 573700, upload-time = "2026-08-07T10:47:33.527Z" }, + { url = "https://files.pythonhosted.org/packages/1b/9b/ab54c71a7918a7c34fa5327fb61390a77446a07a146fbfb1165250a61035/librt-0.15.0-cp313-cp313-pyemscripten_2025_0_wasm32.whl", hash = "sha256:2067ff438048cead9d223ca5675bae2a25e520a7c3e6c1498bf9c6892d22caab", size = 82194, upload-time = "2026-08-07T10:47:34.835Z" }, + { url = "https://files.pythonhosted.org/packages/8d/b2/4f9a243bb892395f3becb80789ade13771701091f9f07ab8230247953ba8/librt-0.15.0-cp313-cp313-win32.whl", hash = "sha256:1cd3b721f24c206398b9e26da3c3a9c011e6e89d06f318ba8ebefc30f1003890", size = 106231, upload-time = "2026-08-07T10:47:36.251Z" }, + { url = "https://files.pythonhosted.org/packages/bf/af/64aff4885a40b93132382f2c314647d722574605416504379184ef3045ea/librt-0.15.0-cp313-cp313-win_amd64.whl", hash = "sha256:f395a4a9a03ac062dbe9a9f82e0c720502e590a38feee6a757bc82e9c63afbd8", size = 126996, upload-time = "2026-08-07T10:47:37.453Z" }, + { url = "https://files.pythonhosted.org/packages/27/83/335bccf6c7cb9028cb0b54aead27d9ece3f01f83bc6baa2abace5da655c1/librt-0.15.0-cp313-cp313-win_arm64.whl", hash = "sha256:0a15cb554761247d84a3ec0cbdf4078d70725384f0e4662c0fa3b26266eb60ad", size = 112188, upload-time = "2026-08-07T10:47:38.729Z" }, + { url = "https://files.pythonhosted.org/packages/a8/93/949053fb462eecc4a9a5ee770a81f4b40be7b79538b245545d4aebc6b58b/librt-0.15.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:f5de7feedc56337a088eb15cd9fafa9938367362221d8cc62c642b7f94821993", size = 149833, upload-time = "2026-08-07T10:47:39.86Z" }, + { url = "https://files.pythonhosted.org/packages/61/ca/8281aa6cd560a3420e4497729f6b704b53be3eeaaef82d5aeadddaf7441f/librt-0.15.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:6c0eb900c0e91f4aebe680845242e614f1864edfd44106380d0752ac29522bf8", size = 154088, upload-time = "2026-08-07T10:47:41.065Z" }, + { url = "https://files.pythonhosted.org/packages/dd/02/1a1662dceaba6a086360891448d5ce9a7d3555976cae59a31a39d744b9c7/librt-0.15.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e8c9a650a188e38bac005048cbe6342e81407782944d01934540ab75e417df21", size = 494215, upload-time = "2026-08-07T10:47:42.388Z" }, + { url = "https://files.pythonhosted.org/packages/69/84/99211619dc656370a3740c33d2b0b6d5a3fb1e73689314f6ed477a397dc4/librt-0.15.0-cp314-cp314-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:92bfed8deec93df30286b9fe9e3b1dd17329cc076a192b4ee5ec223841d54953", size = 491173, upload-time = "2026-08-07T10:47:43.683Z" }, + { url = "https://files.pythonhosted.org/packages/d4/aa/5448d0b05f4579b635d3899176817ebf561af0e57bacd425b5b1887264c1/librt-0.15.0-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ec4b19788f835711a2072f9dbe6b03b3bf32ed1f0fb30cf399bdd59d9f0c33fa", size = 505512, upload-time = "2026-08-07T10:47:45.314Z" }, + { url = "https://files.pythonhosted.org/packages/95/82/01940e40b83c43a546c4a3c896cf34ca272a9690899d55914e4827b3dcce/librt-0.15.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d4c7bacb70930f3d0a56f4ecf1be474a1f0d941b01dd73b756f3c256d42cb879", size = 523073, upload-time = "2026-08-07T10:47:46.66Z" }, + { url = "https://files.pythonhosted.org/packages/88/fa/759c0030f3ee371439eb26de34fc745807caf0abb878af7af4b8b7c3dd3d/librt-0.15.0-cp314-cp314-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:3e79f05e4a08b4d880342673312bbc895b56df7765605796f15902eb5367d3ae", size = 515080, upload-time = "2026-08-07T10:47:48.319Z" }, + { url = "https://files.pythonhosted.org/packages/0b/27/894e072228fcb159703c655da69f8cd10dbed489c36e3df7dd032a2483be/librt-0.15.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:a417149c0cba4d50b61e992e5a15e69eaf96746609b461cc4ed168aeef6b79dd", size = 534164, upload-time = "2026-08-07T10:47:49.875Z" }, + { url = "https://files.pythonhosted.org/packages/98/a3/0078e91c1f36f8815db17827de15650b9a3fe56c55fbf998c854b34e40d3/librt-0.15.0-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:da7a94d6a3411f579d72aa3e3bc5fbca7ed4549f3dbd7e5de3aa567333374285", size = 540616, upload-time = "2026-08-07T10:47:51.408Z" }, + { url = "https://files.pythonhosted.org/packages/86/33/81a29b796dd52a45e9ef7974c7732926e8f10f15b8d2be505665979f896d/librt-0.15.0-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:856f743ae607f2c1380eccb566c0038a9fb3eabf0fc2be2704d76d9f73557239", size = 545890, upload-time = "2026-08-07T10:47:52.818Z" }, + { url = "https://files.pythonhosted.org/packages/05/82/8be1baa1350e5d30cfd70ae79d0a6f4dc5862ef47f7bb2808aabc9bb86e5/librt-0.15.0-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:779a6e7c894737e5983e7790a9c78c4000c30e23c9aada08081bdbea53b0fa60", size = 523287, upload-time = "2026-08-07T10:47:54.165Z" }, + { url = "https://files.pythonhosted.org/packages/c6/4f/d1be6a01a35c20ef734e0e44113f87d4af756a9354a89dcfbe3b4f8af5e1/librt-0.15.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:96bb17dbe8bab3c0954fbebfc69ed395599de75b6bbc35e3270a878e15d4dd65", size = 565868, upload-time = "2026-08-07T10:47:55.566Z" }, + { url = "https://files.pythonhosted.org/packages/67/88/649cfa33f5825927b160610f670bdab012a64d627eddb94fa795ea4292fd/librt-0.15.0-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:7220697efaa6e5348fc3d18ee7f8563d4bfecd9872b37ffb915bfc1d08840622", size = 81619, upload-time = "2026-08-07T10:47:56.886Z" }, + { url = "https://files.pythonhosted.org/packages/22/31/8e88a8d5e48fc8d1a817787fb6811dfff6499acd6c8683dd83934aa6ede0/librt-0.15.0-cp314-cp314-win32.whl", hash = "sha256:f54598964d357b1c5ab77cf5d92f21e598fe0e23cdbe9618480807f81b4eba15", size = 100138, upload-time = "2026-08-07T10:47:58.093Z" }, + { url = "https://files.pythonhosted.org/packages/80/92/20fd6c4b6a1b1a564b076d55cd3d427d8428217d7638dc25a654cc4791d4/librt-0.15.0-cp314-cp314-win_amd64.whl", hash = "sha256:3ff5893a2c23d886aa9ce786de5ac6ddc74aeeaf90743682b74d920e117d2e28", size = 121258, upload-time = "2026-08-07T10:47:59.564Z" }, + { url = "https://files.pythonhosted.org/packages/fc/28/6af430b44d9ebb897b865a3c363b6dcace51357be2347cc0f8f869656a86/librt-0.15.0-cp314-cp314-win_arm64.whl", hash = "sha256:3722a099730704c9a3d70c879fc0f51daec25fe5f1555672d97bc595abeafb95", size = 106467, upload-time = "2026-08-07T10:48:01.097Z" }, + { url = "https://files.pythonhosted.org/packages/7e/aa/b42bb798942ced219f6d63b27e07f91237887a8d0bd0921666db79a13790/librt-0.15.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:38c0c7d4b6fc06c3324b3f9162c8391bfc4fd9dde53afe1033ce7edb48d5a714", size = 159523, upload-time = "2026-08-07T10:48:02.442Z" }, + { url = "https://files.pythonhosted.org/packages/75/03/1b53cd4ef904e73b1d828a5f90143bf94a2967d7cfff0b9ccf93e12aa9b4/librt-0.15.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:8b2fdd7ead3c995c37940a790690660d0ca006c302db26cc51933f6766866fc3", size = 161638, upload-time = "2026-08-07T10:48:03.725Z" }, + { url = "https://files.pythonhosted.org/packages/ac/c4/9f9c9fba097d49e9e694c2b4dc331df31884645ecbc58a93b4b5fc69d2c5/librt-0.15.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2fde98cf1fc4bac144ce23c2c4c017b924ba714509ea9334977b0b27050c837d", size = 701795, upload-time = "2026-08-07T10:48:05.135Z" }, + { url = "https://files.pythonhosted.org/packages/4c/05/0966840bda0380c8ae167b9043c6230202941cc90ea29c48e096964c765e/librt-0.15.0-cp314-cp314t-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:e3b461183c5fa7681b48560f91515f53a953122fb30c71e07abc67d7ddf58c38", size = 682147, upload-time = "2026-08-07T10:48:06.555Z" }, + { url = "https://files.pythonhosted.org/packages/18/af/1c47ca573c30ea47d195aec26133af522fea1104afaace028d7b32247ea8/librt-0.15.0-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4bbcc257e3babea20a91715c361b24554ec4e8f51aa578568afc230799fe1a19", size = 696397, upload-time = "2026-08-07T10:48:08.03Z" }, + { url = "https://files.pythonhosted.org/packages/2e/0f/1aed6223d4f9f9d1171a8596ff100ea4c3f7699fea7a4ba657c3e60daa6c/librt-0.15.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b845b8d48088fad0cadc84be4b8fda63203be7e9237b71015b3925443c1f35ab", size = 722542, upload-time = "2026-08-07T10:48:09.569Z" }, + { url = "https://files.pythonhosted.org/packages/c6/22/9e3a929aea456c97d69e6ef3884efea56d4807f97399471cc946baebd8af/librt-0.15.0-cp314-cp314t-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:b30e600e8f337b9bd7f39b86d9fdfedc73cc46e3d0f745931a23a234220bb7e2", size = 729709, upload-time = "2026-08-07T10:48:11.129Z" }, + { url = "https://files.pythonhosted.org/packages/e9/1b/c327ef6018e3a9ca0b8e7c5eddeeb331ba8f9b76c24e126d37d0f6d62faf/librt-0.15.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:64b0c8c35aa4c4ed79896359f3e0b285cbe4e610042106500da4811c322cc108", size = 752891, upload-time = "2026-08-07T10:48:12.558Z" }, + { url = "https://files.pythonhosted.org/packages/d7/d1/d5f1ea02c56930087009e39db9b70660a663e76c730b27b925d786718457/librt-0.15.0-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:0da0d94cb802f32a0524653e7201f2cef72d5f700a5407678f5290483d4fcd08", size = 745301, upload-time = "2026-08-07T10:48:14.55Z" }, + { url = "https://files.pythonhosted.org/packages/d9/3c/5f7c585d15ebb2250c73e7c0ee4e9e47be72c65d520c07ddbcdc62037674/librt-0.15.0-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:4a6369168d371207339b1e50d4532b06a7121586141f82599505a3f315751d47", size = 747921, upload-time = "2026-08-07T10:48:16.453Z" }, + { url = "https://files.pythonhosted.org/packages/7f/52/1443a446486eba966bcbca1696b472e4f210320ec42f490a47f48fbf0fdc/librt-0.15.0-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:c434e072557ade9cbc642d052c89d031efe47d5c9614523619d0d74a02378e81", size = 727561, upload-time = "2026-08-07T10:48:18.089Z" }, + { url = "https://files.pythonhosted.org/packages/79/91/2270a9380f11725cf83ce1925a5e32dd1dde2be9bba597f25c10a38644e7/librt-0.15.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:c7eec6a42018bc1d45763b1c162d3d2bf7c3b9a1b0ed30d3e91dcba390efefcc", size = 774417, upload-time = "2026-08-07T10:48:19.611Z" }, + { url = "https://files.pythonhosted.org/packages/9e/3b/f4b1548d4f5b99186737fe27aec238e9823e8d5d23bf4df007c030689dc5/librt-0.15.0-cp314-cp314t-win32.whl", hash = "sha256:6912fa5e635d74529ac7cdb1bdf6ca3af4453da8d1edbe0110ee1cb4ad407ebf", size = 104381, upload-time = "2026-08-07T10:48:21.048Z" }, + { url = "https://files.pythonhosted.org/packages/80/b6/134afad262def1de04c0843c376d02135f1168af43f22e09a52bd8394727/librt-0.15.0-cp314-cp314t-win_amd64.whl", hash = "sha256:8e11699ed745931c395acd3621b07062e0f840efa6935aad87a64ed0995f0915", size = 127034, upload-time = "2026-08-07T10:48:22.561Z" }, + { url = "https://files.pythonhosted.org/packages/99/5f/1b6846b20572bd699c9e9ec321a5f781845bee477df2aa2a43b28bc40119/librt-0.15.0-cp314-cp314t-win_arm64.whl", hash = "sha256:5d2a91724463bfed4f573cd7a9fdc856d2e230d0c0e5a61416a93481dccd8605", size = 110827, upload-time = "2026-08-07T10:48:23.804Z" }, + { url = "https://files.pythonhosted.org/packages/c6/44/4de9f4ddadb009a55c7758eb5736d62534a7daaf27bd71bc50e64b606b06/librt-0.15.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:8443e38dcfcfdbcf5add5118c623efd788d65ac2e25756d6251a54a06a4d0aca", size = 149843, upload-time = "2026-08-07T10:48:25.148Z" }, + { url = "https://files.pythonhosted.org/packages/1f/eb/5d9ab71e30119c44094e0275f38b47dd327aea0f843a080396677029d508/librt-0.15.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:6d15a29033c57490cfe2069097c6fc4049e4e65ffbb749be7dc453b7c4c68965", size = 154510, upload-time = "2026-08-07T10:48:26.485Z" }, + { url = "https://files.pythonhosted.org/packages/d0/9c/8505d1b8f5e8c19587bd03f7429993b3e9ce5c06819d856bfb11d919374c/librt-0.15.0-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d2c05c729b589e734c09578bf5964be48a911765484840d017bbc84f49d4c4ad", size = 497543, upload-time = "2026-08-07T10:48:28.045Z" }, + { url = "https://files.pythonhosted.org/packages/1d/9a/3a8390775cb095765aded027ac9c63e7c8ea74e731498607544c6505de0e/librt-0.15.0-cp315-cp315-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:fa60887537e1d0cd2d9982269d33a709bf54b195cd2b9364fc0a758022af5bd9", size = 480452, upload-time = "2026-08-07T10:48:29.531Z" }, + { url = "https://files.pythonhosted.org/packages/e7/40/258a4a7117ee915d66de5cd9b8ade65a440993161107ce3a686f1859955c/librt-0.15.0-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:d8bc24219b24c0af375718942ab75e3544b2763085f40f965be4326734ae8328", size = 507768, upload-time = "2026-08-07T10:48:31.007Z" }, + { url = "https://files.pythonhosted.org/packages/6b/c6/2f4dd296c97a0b85b98894519b279408ec9dd602d4f692b1ea0e25dee670/librt-0.15.0-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:86a21a7bd3fe3a419512ef424cc1c020f6771d0b29cfddff36d1635a855e63f0", size = 525122, upload-time = "2026-08-07T10:48:32.7Z" }, + { url = "https://files.pythonhosted.org/packages/49/dd/29eab42be13b2bf0ea8cb227135a45d44693e30a7e8b92871981ff56b82b/librt-0.15.0-cp315-cp315-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:dbab647e88d90b3167b91efe7091e248653688ed4337e4f90907a722c7361bb9", size = 520371, upload-time = "2026-08-07T10:48:34.294Z" }, + { url = "https://files.pythonhosted.org/packages/91/ed/4bad71adeca8fe208b775c2a35417fa5a2584c8f4791daaf89a89450fea1/librt-0.15.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:d8edcf6f550e918dca779c069b9e156385c60b406f99fc7641f32c52f7193659", size = 537258, upload-time = "2026-08-07T10:48:35.88Z" }, + { url = "https://files.pythonhosted.org/packages/4c/63/59dba6143fdcc7240c54458b629f3250000a61b8945890fc9efd451b19c5/librt-0.15.0-cp315-cp315-musllinux_1_2_i686.whl", hash = "sha256:8b62076030baa2d8b1501a46bf0e19c27a489aa90671c55665bff7887f7660b0", size = 527432, upload-time = "2026-08-07T10:48:37.466Z" }, + { url = "https://files.pythonhosted.org/packages/ec/21/21a24c6a2327d8362580efebe77286bf47b0f4062ec5ea41766e609d3c7d/librt-0.15.0-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:d00d20d1818e82a07a0ee0aa89a98b17ed7916b92441090b683719cb20a59b6d", size = 548108, upload-time = "2026-08-07T10:48:39.384Z" }, + { url = "https://files.pythonhosted.org/packages/5a/6d/fc68c89a7971418b41f9a873623ff935cb864097544c6a2f8ce491c8ef5d/librt-0.15.0-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:4e6ee93fc3cf848dcbf0cce2eca73d8e7dcd0cc2b6df3a529d57750b30a4c55c", size = 529681, upload-time = "2026-08-07T10:48:41.392Z" }, + { url = "https://files.pythonhosted.org/packages/65/7e/c2d98766124400d722063a630b0fde38a9fc768705d37eecca15c47dc192/librt-0.15.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:32896a0af72508ea979e0acb4e4c04cbeeae04938167950d535c83c45597167d", size = 567736, upload-time = "2026-08-07T10:48:43.124Z" }, + { url = "https://files.pythonhosted.org/packages/55/6c/f8c34a95e3a515c6e1c192b89511e7253c89a7760c6b500d57ffdb8d2dc8/librt-0.15.0-cp315-cp315-pyemscripten_2026_5_wasm32.whl", hash = "sha256:ec3ba415afaf951f6951b1dd16d3c8e4f540065fc382d7e70b823a79567ca374", size = 81673, upload-time = "2026-08-07T10:48:44.645Z" }, + { url = "https://files.pythonhosted.org/packages/c9/9e/e23fa8e78679ec45728188650b39e8ff476c83b691c96f749217df3b1b7c/librt-0.15.0-cp315-cp315-win32.whl", hash = "sha256:d2813ba2503764f0450680c533d13df7cff9b49df1411062eded5f67db4195b9", size = 100081, upload-time = "2026-08-07T10:48:46.171Z" }, + { url = "https://files.pythonhosted.org/packages/e1/dc/3eb4c5e297343f0620a55532cd7c8d764d3001fa2159212dadf480464827/librt-0.15.0-cp315-cp315-win_amd64.whl", hash = "sha256:b87d67e33afaf265262f2a66db578284b88ee2e6fcd224579cb5c15518677ad8", size = 121228, upload-time = "2026-08-07T10:48:47.631Z" }, + { url = "https://files.pythonhosted.org/packages/97/70/43abce19f04e49762f8ec834c8fafee13cc40fd6b94a72a24e534febfcd0/librt-0.15.0-cp315-cp315-win_arm64.whl", hash = "sha256:713bd7df21170b982e729e46870f31d6b437bd1a9b4648cffb529bd3c2ec5c4b", size = 106487, upload-time = "2026-08-07T10:48:49.095Z" }, + { url = "https://files.pythonhosted.org/packages/de/15/83f2deddb9368b8951ec8c9477269b5b9b8bd9bbf15e57402d0f38817dca/librt-0.15.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:3de789c82752730f94782a5ee518baf9c05edf85733aeaf73bb6e518755cdf54", size = 159448, upload-time = "2026-08-07T10:48:50.649Z" }, + { url = "https://files.pythonhosted.org/packages/06/bf/043097353f9b3c73b583d07f6b8e552795463f4bfc8caf85e42eee50c26a/librt-0.15.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:e0b5deec9a8664eb722c797241970fd4aa1894d25fda36a1ddac0f7407606bd6", size = 161686, upload-time = "2026-08-07T10:48:52.174Z" }, + { url = "https://files.pythonhosted.org/packages/f4/2a/8ae77f9719d42ce71cd708560a3557b38ac3c17a0383e57f87084de45bbe/librt-0.15.0-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5563302a8359bc2295bb7084d1a8ed1519df96afb30eb2aa4e0bff7b54228988", size = 710668, upload-time = "2026-08-07T10:48:53.782Z" }, + { url = "https://files.pythonhosted.org/packages/61/34/c0436ea134deb9a0d6da80a396a2739a81cb31e0418f7227239e23140898/librt-0.15.0-cp315-cp315t-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:22d6263b9d39d7bbb286fa791945646e3218f1be2d693e36fb630f1d0e59cd13", size = 679396, upload-time = "2026-08-07T10:48:55.645Z" }, + { url = "https://files.pythonhosted.org/packages/4a/9f/001e0d99aa9250d5cd5715a9081291a20656083459f9019cda15255329e1/librt-0.15.0-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:39ffd14646190c454f0d86e0d256b33f00a87a26ab410e619773b841d0e41416", size = 704313, upload-time = "2026-08-07T10:48:57.46Z" }, + { url = "https://files.pythonhosted.org/packages/2d/53/b34fa9d0ff00f136f4d58ebb4c411ff634baed1eb412bb602a2bc8dcafcb/librt-0.15.0-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c47318cd3a61401452de11282242937e3e057c4fd3dbaf601e269d0928a06c0a", size = 729847, upload-time = "2026-08-07T10:48:59.231Z" }, + { url = "https://files.pythonhosted.org/packages/86/ac/fa4d7a424665040e95baf480a6d523446057684b6758624c85338e8a23b2/librt-0.15.0-cp315-cp315t-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a56a1d4f859a82ca5b99fc4b82c9b027b15e3c455c5cd99e7d0719f27bb20b6c", size = 742736, upload-time = "2026-08-07T10:49:01.151Z" }, + { url = "https://files.pythonhosted.org/packages/8a/f1/e17a9bb5de6fb8c3186ed1a7d68d21618b027ac2d3633e03d3b6109c67ae/librt-0.15.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:077471b3182db4e17c36ae91555f36a4d2c00080b267f749bcad34a478a9a302", size = 763454, upload-time = "2026-08-07T10:49:03.039Z" }, + { url = "https://files.pythonhosted.org/packages/1d/ec/ecd02cd30935b931b9cdbfed6ab5a099c51b280b4e7baa274da80978ed27/librt-0.15.0-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:411ca4d1b905b860ceba7570dd6717a71dedaddcc4b0f77ece710aa41ee11f8d", size = 743296, upload-time = "2026-08-07T10:49:04.941Z" }, + { url = "https://files.pythonhosted.org/packages/e6/b5/b3c2b8353ce820a4854f78d19321344242f89fa71c975b71132ba9bf242a/librt-0.15.0-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:1256589e0b0adb31751d685a68bce29d73407ddf4ef05d4188f49d5dcf9566d9", size = 756217, upload-time = "2026-08-07T10:49:06.825Z" }, + { url = "https://files.pythonhosted.org/packages/3c/52/6cc22542ba59146b05cca2a656f9ff8bb67e38e63d12c3b0cc183d837bf1/librt-0.15.0-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:f42b74a53e5f26a0ba0007411a7455b66c67ce4022a39cc1f56fc4efd65bcbab", size = 741934, upload-time = "2026-08-07T10:49:08.839Z" }, + { url = "https://files.pythonhosted.org/packages/40/32/a04b72b1aa86e3be23b2ecff8c1aad2dcc955bd3956d6d26e7e34267e57a/librt-0.15.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:291bf73caf78b9e88d6fae9bfd693207ff7d832e2fdbe2cf8e746bc13f5f892b", size = 783763, upload-time = "2026-08-07T10:49:10.661Z" }, + { url = "https://files.pythonhosted.org/packages/6c/f0/89eb11dffbe9279ff37144dec786927314502ae0b114f1449dc78c458aab/librt-0.15.0-cp315-cp315t-win32.whl", hash = "sha256:c16d15ee371643ab48dc8248a3e680ebbeca573a13af2c3dd0c985b142d77162", size = 104313, upload-time = "2026-08-07T10:49:12.305Z" }, + { url = "https://files.pythonhosted.org/packages/6d/4a/1f1978c200f563beda63c36adff2d65bbecb81e365e8e69e572f5f70fbc6/librt-0.15.0-cp315-cp315t-win_amd64.whl", hash = "sha256:dbd605739f228912dc49027cb764456b9757750bdc2b6b7773164db7096c6fd1", size = 126889, upload-time = "2026-08-07T10:49:13.881Z" }, + { url = "https://files.pythonhosted.org/packages/38/a6/800800bfed7b1fb10fc3f3d557785c3854e80d3f7a9800d784b176a1fc2d/librt-0.15.0-cp315-cp315t-win_arm64.whl", hash = "sha256:84d244b00604d17df3fc7736c327892d6bba66181254aa4087be807b6c342bdc", size = 110700, upload-time = "2026-08-07T10:49:15.499Z" }, +] + +[[package]] +name = "markupsafe" +version = "3.0.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7e/99/7690b6d4034fffd95959cbe0c02de8deb3098cc577c67bb6a24fe5d7caa7/markupsafe-3.0.3.tar.gz", hash = "sha256:722695808f4b6457b320fdc131280796bdceb04ab50fe1795cd540799ebe1698", size = 80313, upload-time = "2025-09-27T18:37:40.426Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5a/72/147da192e38635ada20e0a2e1a51cf8823d2119ce8883f7053879c2199b5/markupsafe-3.0.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:d53197da72cc091b024dd97249dfc7794d6a56530370992a5e1a08983ad9230e", size = 11615, upload-time = "2025-09-27T18:36:30.854Z" }, + { url = "https://files.pythonhosted.org/packages/9a/81/7e4e08678a1f98521201c3079f77db69fb552acd56067661f8c2f534a718/markupsafe-3.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1872df69a4de6aead3491198eaf13810b565bdbeec3ae2dc8780f14458ec73ce", size = 12020, upload-time = "2025-09-27T18:36:31.971Z" }, + { url = "https://files.pythonhosted.org/packages/1e/2c/799f4742efc39633a1b54a92eec4082e4f815314869865d876824c257c1e/markupsafe-3.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3a7e8ae81ae39e62a41ec302f972ba6ae23a5c5396c8e60113e9066ef893da0d", size = 24332, upload-time = "2025-09-27T18:36:32.813Z" }, + { url = "https://files.pythonhosted.org/packages/3c/2e/8d0c2ab90a8c1d9a24f0399058ab8519a3279d1bd4289511d74e909f060e/markupsafe-3.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d6dd0be5b5b189d31db7cda48b91d7e0a9795f31430b7f271219ab30f1d3ac9d", size = 22947, upload-time = "2025-09-27T18:36:33.86Z" }, + { url = "https://files.pythonhosted.org/packages/2c/54/887f3092a85238093a0b2154bd629c89444f395618842e8b0c41783898ea/markupsafe-3.0.3-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:94c6f0bb423f739146aec64595853541634bde58b2135f27f61c1ffd1cd4d16a", size = 21962, upload-time = "2025-09-27T18:36:35.099Z" }, + { url = "https://files.pythonhosted.org/packages/c9/2f/336b8c7b6f4a4d95e91119dc8521402461b74a485558d8f238a68312f11c/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:be8813b57049a7dc738189df53d69395eba14fb99345e0a5994914a3864c8a4b", size = 23760, upload-time = "2025-09-27T18:36:36.001Z" }, + { url = "https://files.pythonhosted.org/packages/32/43/67935f2b7e4982ffb50a4d169b724d74b62a3964bc1a9a527f5ac4f1ee2b/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:83891d0e9fb81a825d9a6d61e3f07550ca70a076484292a70fde82c4b807286f", size = 21529, upload-time = "2025-09-27T18:36:36.906Z" }, + { url = "https://files.pythonhosted.org/packages/89/e0/4486f11e51bbba8b0c041098859e869e304d1c261e59244baa3d295d47b7/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:77f0643abe7495da77fb436f50f8dab76dbc6e5fd25d39589a0f1fe6548bfa2b", size = 23015, upload-time = "2025-09-27T18:36:37.868Z" }, + { url = "https://files.pythonhosted.org/packages/2f/e1/78ee7a023dac597a5825441ebd17170785a9dab23de95d2c7508ade94e0e/markupsafe-3.0.3-cp312-cp312-win32.whl", hash = "sha256:d88b440e37a16e651bda4c7c2b930eb586fd15ca7406cb39e211fcff3bf3017d", size = 14540, upload-time = "2025-09-27T18:36:38.761Z" }, + { url = "https://files.pythonhosted.org/packages/aa/5b/bec5aa9bbbb2c946ca2733ef9c4ca91c91b6a24580193e891b5f7dbe8e1e/markupsafe-3.0.3-cp312-cp312-win_amd64.whl", hash = "sha256:26a5784ded40c9e318cfc2bdb30fe164bdb8665ded9cd64d500a34fb42067b1c", size = 15105, upload-time = "2025-09-27T18:36:39.701Z" }, + { url = "https://files.pythonhosted.org/packages/e5/f1/216fc1bbfd74011693a4fd837e7026152e89c4bcf3e77b6692fba9923123/markupsafe-3.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:35add3b638a5d900e807944a078b51922212fb3dedb01633a8defc4b01a3c85f", size = 13906, upload-time = "2025-09-27T18:36:40.689Z" }, + { url = "https://files.pythonhosted.org/packages/38/2f/907b9c7bbba283e68f20259574b13d005c121a0fa4c175f9bed27c4597ff/markupsafe-3.0.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:e1cf1972137e83c5d4c136c43ced9ac51d0e124706ee1c8aa8532c1287fa8795", size = 11622, upload-time = "2025-09-27T18:36:41.777Z" }, + { url = "https://files.pythonhosted.org/packages/9c/d9/5f7756922cdd676869eca1c4e3c0cd0df60ed30199ffd775e319089cb3ed/markupsafe-3.0.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:116bb52f642a37c115f517494ea5feb03889e04df47eeff5b130b1808ce7c219", size = 12029, upload-time = "2025-09-27T18:36:43.257Z" }, + { url = "https://files.pythonhosted.org/packages/00/07/575a68c754943058c78f30db02ee03a64b3c638586fba6a6dd56830b30a3/markupsafe-3.0.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:133a43e73a802c5562be9bbcd03d090aa5a1fe899db609c29e8c8d815c5f6de6", size = 24374, upload-time = "2025-09-27T18:36:44.508Z" }, + { url = "https://files.pythonhosted.org/packages/a9/21/9b05698b46f218fc0e118e1f8168395c65c8a2c750ae2bab54fc4bd4e0e8/markupsafe-3.0.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ccfcd093f13f0f0b7fdd0f198b90053bf7b2f02a3927a30e63f3ccc9df56b676", size = 22980, upload-time = "2025-09-27T18:36:45.385Z" }, + { url = "https://files.pythonhosted.org/packages/7f/71/544260864f893f18b6827315b988c146b559391e6e7e8f7252839b1b846a/markupsafe-3.0.3-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:509fa21c6deb7a7a273d629cf5ec029bc209d1a51178615ddf718f5918992ab9", size = 21990, upload-time = "2025-09-27T18:36:46.916Z" }, + { url = "https://files.pythonhosted.org/packages/c2/28/b50fc2f74d1ad761af2f5dcce7492648b983d00a65b8c0e0cb457c82ebbe/markupsafe-3.0.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a4afe79fb3de0b7097d81da19090f4df4f8d3a2b3adaa8764138aac2e44f3af1", size = 23784, upload-time = "2025-09-27T18:36:47.884Z" }, + { url = "https://files.pythonhosted.org/packages/ed/76/104b2aa106a208da8b17a2fb72e033a5a9d7073c68f7e508b94916ed47a9/markupsafe-3.0.3-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:795e7751525cae078558e679d646ae45574b47ed6e7771863fcc079a6171a0fc", size = 21588, upload-time = "2025-09-27T18:36:48.82Z" }, + { url = "https://files.pythonhosted.org/packages/b5/99/16a5eb2d140087ebd97180d95249b00a03aa87e29cc224056274f2e45fd6/markupsafe-3.0.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:8485f406a96febb5140bfeca44a73e3ce5116b2501ac54fe953e488fb1d03b12", size = 23041, upload-time = "2025-09-27T18:36:49.797Z" }, + { url = "https://files.pythonhosted.org/packages/19/bc/e7140ed90c5d61d77cea142eed9f9c303f4c4806f60a1044c13e3f1471d0/markupsafe-3.0.3-cp313-cp313-win32.whl", hash = "sha256:bdd37121970bfd8be76c5fb069c7751683bdf373db1ed6c010162b2a130248ed", size = 14543, upload-time = "2025-09-27T18:36:51.584Z" }, + { url = "https://files.pythonhosted.org/packages/05/73/c4abe620b841b6b791f2edc248f556900667a5a1cf023a6646967ae98335/markupsafe-3.0.3-cp313-cp313-win_amd64.whl", hash = "sha256:9a1abfdc021a164803f4d485104931fb8f8c1efd55bc6b748d2f5774e78b62c5", size = 15113, upload-time = "2025-09-27T18:36:52.537Z" }, + { url = "https://files.pythonhosted.org/packages/f0/3a/fa34a0f7cfef23cf9500d68cb7c32dd64ffd58a12b09225fb03dd37d5b80/markupsafe-3.0.3-cp313-cp313-win_arm64.whl", hash = "sha256:7e68f88e5b8799aa49c85cd116c932a1ac15caaa3f5db09087854d218359e485", size = 13911, upload-time = "2025-09-27T18:36:53.513Z" }, + { url = "https://files.pythonhosted.org/packages/e4/d7/e05cd7efe43a88a17a37b3ae96e79a19e846f3f456fe79c57ca61356ef01/markupsafe-3.0.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:218551f6df4868a8d527e3062d0fb968682fe92054e89978594c28e642c43a73", size = 11658, upload-time = "2025-09-27T18:36:54.819Z" }, + { url = "https://files.pythonhosted.org/packages/99/9e/e412117548182ce2148bdeacdda3bb494260c0b0184360fe0d56389b523b/markupsafe-3.0.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:3524b778fe5cfb3452a09d31e7b5adefeea8c5be1d43c4f810ba09f2ceb29d37", size = 12066, upload-time = "2025-09-27T18:36:55.714Z" }, + { url = "https://files.pythonhosted.org/packages/bc/e6/fa0ffcda717ef64a5108eaa7b4f5ed28d56122c9a6d70ab8b72f9f715c80/markupsafe-3.0.3-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4e885a3d1efa2eadc93c894a21770e4bc67899e3543680313b09f139e149ab19", size = 25639, upload-time = "2025-09-27T18:36:56.908Z" }, + { url = "https://files.pythonhosted.org/packages/96/ec/2102e881fe9d25fc16cb4b25d5f5cde50970967ffa5dddafdb771237062d/markupsafe-3.0.3-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8709b08f4a89aa7586de0aadc8da56180242ee0ada3999749b183aa23df95025", size = 23569, upload-time = "2025-09-27T18:36:57.913Z" }, + { url = "https://files.pythonhosted.org/packages/4b/30/6f2fce1f1f205fc9323255b216ca8a235b15860c34b6798f810f05828e32/markupsafe-3.0.3-cp313-cp313t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:b8512a91625c9b3da6f127803b166b629725e68af71f8184ae7e7d54686a56d6", size = 23284, upload-time = "2025-09-27T18:36:58.833Z" }, + { url = "https://files.pythonhosted.org/packages/58/47/4a0ccea4ab9f5dcb6f79c0236d954acb382202721e704223a8aafa38b5c8/markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:9b79b7a16f7fedff2495d684f2b59b0457c3b493778c9eed31111be64d58279f", size = 24801, upload-time = "2025-09-27T18:36:59.739Z" }, + { url = "https://files.pythonhosted.org/packages/6a/70/3780e9b72180b6fecb83a4814d84c3bf4b4ae4bf0b19c27196104149734c/markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_riscv64.whl", hash = "sha256:12c63dfb4a98206f045aa9563db46507995f7ef6d83b2f68eda65c307c6829eb", size = 22769, upload-time = "2025-09-27T18:37:00.719Z" }, + { url = "https://files.pythonhosted.org/packages/98/c5/c03c7f4125180fc215220c035beac6b9cb684bc7a067c84fc69414d315f5/markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:8f71bc33915be5186016f675cd83a1e08523649b0e33efdb898db577ef5bb009", size = 23642, upload-time = "2025-09-27T18:37:01.673Z" }, + { url = "https://files.pythonhosted.org/packages/80/d6/2d1b89f6ca4bff1036499b1e29a1d02d282259f3681540e16563f27ebc23/markupsafe-3.0.3-cp313-cp313t-win32.whl", hash = "sha256:69c0b73548bc525c8cb9a251cddf1931d1db4d2258e9599c28c07ef3580ef354", size = 14612, upload-time = "2025-09-27T18:37:02.639Z" }, + { url = "https://files.pythonhosted.org/packages/2b/98/e48a4bfba0a0ffcf9925fe2d69240bfaa19c6f7507b8cd09c70684a53c1e/markupsafe-3.0.3-cp313-cp313t-win_amd64.whl", hash = "sha256:1b4b79e8ebf6b55351f0d91fe80f893b4743f104bff22e90697db1590e47a218", size = 15200, upload-time = "2025-09-27T18:37:03.582Z" }, + { url = "https://files.pythonhosted.org/packages/0e/72/e3cc540f351f316e9ed0f092757459afbc595824ca724cbc5a5d4263713f/markupsafe-3.0.3-cp313-cp313t-win_arm64.whl", hash = "sha256:ad2cf8aa28b8c020ab2fc8287b0f823d0a7d8630784c31e9ee5edea20f406287", size = 13973, upload-time = "2025-09-27T18:37:04.929Z" }, + { url = "https://files.pythonhosted.org/packages/33/8a/8e42d4838cd89b7dde187011e97fe6c3af66d8c044997d2183fbd6d31352/markupsafe-3.0.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:eaa9599de571d72e2daf60164784109f19978b327a3910d3e9de8c97b5b70cfe", size = 11619, upload-time = "2025-09-27T18:37:06.342Z" }, + { url = "https://files.pythonhosted.org/packages/b5/64/7660f8a4a8e53c924d0fa05dc3a55c9cee10bbd82b11c5afb27d44b096ce/markupsafe-3.0.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c47a551199eb8eb2121d4f0f15ae0f923d31350ab9280078d1e5f12b249e0026", size = 12029, upload-time = "2025-09-27T18:37:07.213Z" }, + { url = "https://files.pythonhosted.org/packages/da/ef/e648bfd021127bef5fa12e1720ffed0c6cbb8310c8d9bea7266337ff06de/markupsafe-3.0.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f34c41761022dd093b4b6896d4810782ffbabe30f2d443ff5f083e0cbbb8c737", size = 24408, upload-time = "2025-09-27T18:37:09.572Z" }, + { url = "https://files.pythonhosted.org/packages/41/3c/a36c2450754618e62008bf7435ccb0f88053e07592e6028a34776213d877/markupsafe-3.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:457a69a9577064c05a97c41f4e65148652db078a3a509039e64d3467b9e7ef97", size = 23005, upload-time = "2025-09-27T18:37:10.58Z" }, + { url = "https://files.pythonhosted.org/packages/bc/20/b7fdf89a8456b099837cd1dc21974632a02a999ec9bf7ca3e490aacd98e7/markupsafe-3.0.3-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e8afc3f2ccfa24215f8cb28dcf43f0113ac3c37c2f0f0806d8c70e4228c5cf4d", size = 22048, upload-time = "2025-09-27T18:37:11.547Z" }, + { url = "https://files.pythonhosted.org/packages/9a/a7/591f592afdc734f47db08a75793a55d7fbcc6902a723ae4cfbab61010cc5/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:ec15a59cf5af7be74194f7ab02d0f59a62bdcf1a537677ce67a2537c9b87fcda", size = 23821, upload-time = "2025-09-27T18:37:12.48Z" }, + { url = "https://files.pythonhosted.org/packages/7d/33/45b24e4f44195b26521bc6f1a82197118f74df348556594bd2262bda1038/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:0eb9ff8191e8498cca014656ae6b8d61f39da5f95b488805da4bb029cccbfbaf", size = 21606, upload-time = "2025-09-27T18:37:13.485Z" }, + { url = "https://files.pythonhosted.org/packages/ff/0e/53dfaca23a69fbfbbf17a4b64072090e70717344c52eaaaa9c5ddff1e5f0/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:2713baf880df847f2bece4230d4d094280f4e67b1e813eec43b4c0e144a34ffe", size = 23043, upload-time = "2025-09-27T18:37:14.408Z" }, + { url = "https://files.pythonhosted.org/packages/46/11/f333a06fc16236d5238bfe74daccbca41459dcd8d1fa952e8fbd5dccfb70/markupsafe-3.0.3-cp314-cp314-win32.whl", hash = "sha256:729586769a26dbceff69f7a7dbbf59ab6572b99d94576a5592625d5b411576b9", size = 14747, upload-time = "2025-09-27T18:37:15.36Z" }, + { url = "https://files.pythonhosted.org/packages/28/52/182836104b33b444e400b14f797212f720cbc9ed6ba34c800639d154e821/markupsafe-3.0.3-cp314-cp314-win_amd64.whl", hash = "sha256:bdc919ead48f234740ad807933cdf545180bfbe9342c2bb451556db2ed958581", size = 15341, upload-time = "2025-09-27T18:37:16.496Z" }, + { url = "https://files.pythonhosted.org/packages/6f/18/acf23e91bd94fd7b3031558b1f013adfa21a8e407a3fdb32745538730382/markupsafe-3.0.3-cp314-cp314-win_arm64.whl", hash = "sha256:5a7d5dc5140555cf21a6fefbdbf8723f06fcd2f63ef108f2854de715e4422cb4", size = 14073, upload-time = "2025-09-27T18:37:17.476Z" }, + { url = "https://files.pythonhosted.org/packages/3c/f0/57689aa4076e1b43b15fdfa646b04653969d50cf30c32a102762be2485da/markupsafe-3.0.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:1353ef0c1b138e1907ae78e2f6c63ff67501122006b0f9abad68fda5f4ffc6ab", size = 11661, upload-time = "2025-09-27T18:37:18.453Z" }, + { url = "https://files.pythonhosted.org/packages/89/c3/2e67a7ca217c6912985ec766c6393b636fb0c2344443ff9d91404dc4c79f/markupsafe-3.0.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:1085e7fbddd3be5f89cc898938f42c0b3c711fdcb37d75221de2666af647c175", size = 12069, upload-time = "2025-09-27T18:37:19.332Z" }, + { url = "https://files.pythonhosted.org/packages/f0/00/be561dce4e6ca66b15276e184ce4b8aec61fe83662cce2f7d72bd3249d28/markupsafe-3.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1b52b4fb9df4eb9ae465f8d0c228a00624de2334f216f178a995ccdcf82c4634", size = 25670, upload-time = "2025-09-27T18:37:20.245Z" }, + { url = "https://files.pythonhosted.org/packages/50/09/c419f6f5a92e5fadde27efd190eca90f05e1261b10dbd8cbcb39cd8ea1dc/markupsafe-3.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fed51ac40f757d41b7c48425901843666a6677e3e8eb0abcff09e4ba6e664f50", size = 23598, upload-time = "2025-09-27T18:37:21.177Z" }, + { url = "https://files.pythonhosted.org/packages/22/44/a0681611106e0b2921b3033fc19bc53323e0b50bc70cffdd19f7d679bb66/markupsafe-3.0.3-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f190daf01f13c72eac4efd5c430a8de82489d9cff23c364c3ea822545032993e", size = 23261, upload-time = "2025-09-27T18:37:22.167Z" }, + { url = "https://files.pythonhosted.org/packages/5f/57/1b0b3f100259dc9fffe780cfb60d4be71375510e435efec3d116b6436d43/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:e56b7d45a839a697b5eb268c82a71bd8c7f6c94d6fd50c3d577fa39a9f1409f5", size = 24835, upload-time = "2025-09-27T18:37:23.296Z" }, + { url = "https://files.pythonhosted.org/packages/26/6a/4bf6d0c97c4920f1597cc14dd720705eca0bf7c787aebc6bb4d1bead5388/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:f3e98bb3798ead92273dc0e5fd0f31ade220f59a266ffd8a4f6065e0a3ce0523", size = 22733, upload-time = "2025-09-27T18:37:24.237Z" }, + { url = "https://files.pythonhosted.org/packages/14/c7/ca723101509b518797fedc2fdf79ba57f886b4aca8a7d31857ba3ee8281f/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:5678211cb9333a6468fb8d8be0305520aa073f50d17f089b5b4b477ea6e67fdc", size = 23672, upload-time = "2025-09-27T18:37:25.271Z" }, + { url = "https://files.pythonhosted.org/packages/fb/df/5bd7a48c256faecd1d36edc13133e51397e41b73bb77e1a69deab746ebac/markupsafe-3.0.3-cp314-cp314t-win32.whl", hash = "sha256:915c04ba3851909ce68ccc2b8e2cd691618c4dc4c4232fb7982bca3f41fd8c3d", size = 14819, upload-time = "2025-09-27T18:37:26.285Z" }, + { url = "https://files.pythonhosted.org/packages/1a/8a/0402ba61a2f16038b48b39bccca271134be00c5c9f0f623208399333c448/markupsafe-3.0.3-cp314-cp314t-win_amd64.whl", hash = "sha256:4faffd047e07c38848ce017e8725090413cd80cbc23d86e55c587bf979e579c9", size = 15426, upload-time = "2025-09-27T18:37:27.316Z" }, + { url = "https://files.pythonhosted.org/packages/70/bc/6f1c2f612465f5fa89b95bead1f44dcb607670fd42891d8fdcd5d039f4f4/markupsafe-3.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:32001d6a8fc98c8cb5c947787c5d08b0a50663d139f1305bac5885d98d9b40fa", size = 14146, upload-time = "2025-09-27T18:37:28.327Z" }, +] + +[[package]] +name = "mypy" +version = "1.20.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "librt", marker = "platform_python_implementation != 'PyPy'" }, + { name = "mypy-extensions" }, + { name = "pathspec" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/04/af/e3d4b3e9ec91a0ff9aabfdb38692952acf49bbb899c2e4c29acb3a6da3ae/mypy-1.20.2.tar.gz", hash = "sha256:e8222c26daaafd9e8626dec58ae36029f82585890589576f769a650dd20fd665", size = 3817349, upload-time = "2026-04-21T17:12:28.473Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/4e/7560e4528db9e9b147e4c0f22660466bf30a0a1fe3d63d1b9d3b0fd354ee/mypy-1.20.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:4dbfcf869f6b0517f70cf0030ba6ea1d6645e132337a7d5204a18d8d5636c02b", size = 14539393, upload-time = "2026-04-21T17:07:12.52Z" }, + { url = "https://files.pythonhosted.org/packages/32/d9/34a5efed8124f5a9234f55ac6a4ced4201e2c5b81e1109c49ad23190ec8c/mypy-1.20.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:4b6481b228d072315b053210b01ac320e1be243dc17f9e5887ef167f23f5fae4", size = 13361642, upload-time = "2026-04-21T17:06:53.742Z" }, + { url = "https://files.pythonhosted.org/packages/d1/14/eb377acf78c03c92d566a1510cda8137348215b5335085ef662ab82ecd3a/mypy-1.20.2-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:34397cdced6b90b836e38182076049fdb41424322e0b0728c946b0939ebdf9f6", size = 13740347, upload-time = "2026-04-21T17:12:04.73Z" }, + { url = "https://files.pythonhosted.org/packages/b9/94/7e4634a32b641aa1c112422eed1bbece61ee16205f674190e8b536f884de/mypy-1.20.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a5da6976f20cae27059ea8d0c86e7cef3de720e04c4bb9ee18e3690fdb792066", size = 14734042, upload-time = "2026-04-21T17:07:43.16Z" }, + { url = "https://files.pythonhosted.org/packages/7a/f3/f7e62395cb7f434541b4491a01149a4439e28ace4c0c632bbf5431e92d1f/mypy-1.20.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:56908d7e08318d39f85b1f0c6cfd47b0cac1a130da677630dac0de3e0623e102", size = 14964958, upload-time = "2026-04-21T17:11:00.665Z" }, + { url = "https://files.pythonhosted.org/packages/3e/0d/47e3c3a0ec2a876e35aeac365df3cac7776c36bbd4ed18cc521e1b9d255b/mypy-1.20.2-cp312-cp312-win_amd64.whl", hash = "sha256:d52ad8d78522da1d308789df651ee5379088e77c76cb1994858d40a426b343b9", size = 10911340, upload-time = "2026-04-21T17:10:49.179Z" }, + { url = "https://files.pythonhosted.org/packages/d6/b2/6c852d72e0ea8b01f49da817fb52539993cde327e7d010e0103dc12d0dac/mypy-1.20.2-cp312-cp312-win_arm64.whl", hash = "sha256:785b08db19c9f214dc37d65f7c165d19a30fcecb48abfa30f31b01b5acaabb58", size = 9833947, upload-time = "2026-04-21T17:09:05.267Z" }, + { url = "https://files.pythonhosted.org/packages/5b/c4/b93812d3a192c9bcf5df405bd2f30277cd0e48106a14d1023c7f6ed6e39b/mypy-1.20.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:edfbfca868cdd6bd8d974a60f8a3682f5565d3f5c99b327640cedd24c4264026", size = 14524670, upload-time = "2026-04-21T17:10:30.737Z" }, + { url = "https://files.pythonhosted.org/packages/f3/47/42c122501bff18eaf1e8f457f5c017933452d8acdc52918a9f59f6812955/mypy-1.20.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:e2877a02380adfcdbc69071a0f74d6e9dbbf593c0dc9d174e1f223ffd5281943", size = 13336218, upload-time = "2026-04-21T17:08:44.069Z" }, + { url = "https://files.pythonhosted.org/packages/92/8f/75bbc92f41725fbd585fb17b440b1119b576105df1013622983e18640a93/mypy-1.20.2-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7488448de6007cd5177c6cea0517ac33b4c0f5ee9b5e9f2be51ce75511a85517", size = 13724906, upload-time = "2026-04-21T17:08:01.02Z" }, + { url = "https://files.pythonhosted.org/packages/a1/32/4c49da27a606167391ff0c39aa955707a00edc500572e562f7c36c08a71f/mypy-1.20.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bb9c2fa06887e21d6a3a868762acb82aec34e2c6fd0174064f27c93ede68ad15", size = 14726046, upload-time = "2026-04-21T17:11:22.354Z" }, + { url = "https://files.pythonhosted.org/packages/7f/fc/4e354a1bd70216359deb0c9c54847ee6b32ef78dfb09f5131ff99b494078/mypy-1.20.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:9d56a78b646f2e3daa865bc70cd5ec5a46c50045801ca8ff17a0c43abc97e3ee", size = 14955587, upload-time = "2026-04-21T17:12:16.033Z" }, + { url = "https://files.pythonhosted.org/packages/62/b2/c0f2056e9eb8f08c62cafd9715e4584b89132bdc832fcf85d27d07b5f3e5/mypy-1.20.2-cp313-cp313-win_amd64.whl", hash = "sha256:2a4102b03bb7481d9a91a6da8d174740c9c8c4401024684b9ca3b7cc5e49852f", size = 10922681, upload-time = "2026-04-21T17:06:35.842Z" }, + { url = "https://files.pythonhosted.org/packages/e5/14/065e333721f05de8ef683d0aa804c23026bcc287446b61cac657b902ccac/mypy-1.20.2-cp313-cp313-win_arm64.whl", hash = "sha256:a95a9248b0c6fd933a442c03c3b113c3b61320086b88e2c444676d3fd1ca3330", size = 9830560, upload-time = "2026-04-21T17:07:51.023Z" }, + { url = "https://files.pythonhosted.org/packages/ae/d1/b4ec96b0ecc620a4443570c6e95c867903428cfcde4206518eafdd5880c3/mypy-1.20.2-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:419413398fe250aae057fd2fe50166b61077083c9b82754c341cf4fd73038f30", size = 14524561, upload-time = "2026-04-21T17:06:27.325Z" }, + { url = "https://files.pythonhosted.org/packages/3a/63/d2c2ff4fa66bc49477d32dfa26e8a167ba803ea6a69c5efb416036909d30/mypy-1.20.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:e73c07f23009962885c197ccb9b41356a30cc0e5a1d0c2ea8fd8fb1362d7f924", size = 13363883, upload-time = "2026-04-21T17:11:11.239Z" }, + { url = "https://files.pythonhosted.org/packages/2a/56/983916806bf4eddeaaa2c9230903c3669c6718552a921154e1c5182c701f/mypy-1.20.2-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0c64e5973df366b747646fc98da921f9d6eba9716d57d1db94a83c026a08e0fb", size = 13742945, upload-time = "2026-04-21T17:08:34.181Z" }, + { url = "https://files.pythonhosted.org/packages/19/65/0cd9285ab010ee8214c83d67c6b49417c40d86ce46f1aa109457b5a9b8d7/mypy-1.20.2-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5a65aa591af023864fd08a97da9974e919452cfe19cb146c8a5dc692626445dc", size = 14706163, upload-time = "2026-04-21T17:05:15.51Z" }, + { url = "https://files.pythonhosted.org/packages/94/97/48ff3b297cafcc94d185243a9190836fb1b01c1b0918fff64e941e973cc9/mypy-1.20.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:4fef51b01e638974a6e69885687e9bd40c8d1e09a6cd291cca0619625cf1f558", size = 14938677, upload-time = "2026-04-21T17:05:39.562Z" }, + { url = "https://files.pythonhosted.org/packages/fd/a1/1b4233d255bdd0b38a1f284feeb1c143ca508c19184964e22f8d837ec851/mypy-1.20.2-cp314-cp314-win_amd64.whl", hash = "sha256:913485a03f1bcf5d279409a9d2b9ed565c151f61c09f29991e5faa14033da4c8", size = 11089322, upload-time = "2026-04-21T17:06:44.29Z" }, + { url = "https://files.pythonhosted.org/packages/78/c2/ce7ee2ba36aeb954ba50f18fa25d9c1188578654b97d02a66a15b6f09531/mypy-1.20.2-cp314-cp314-win_arm64.whl", hash = "sha256:c3bae4f855d965b5453784300c12ffc63a548304ac7f99e55d4dc7c898673aa3", size = 10017775, upload-time = "2026-04-21T17:07:20.732Z" }, + { url = "https://files.pythonhosted.org/packages/4e/a1/9d93a7d0b5859af0ead82b4888b46df6c8797e1bc5e1e262a08518c6d48e/mypy-1.20.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:2de3dcea53babc1c3237a19002bc3d228ce1833278f093b8d619e06e7cc79609", size = 15549002, upload-time = "2026-04-21T17:08:23.107Z" }, + { url = "https://files.pythonhosted.org/packages/00/d2/09a6a10ee1bf0008f6c144d9676f2ca6a12512151b4e0ad0ff6c4fac5337/mypy-1.20.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:52b176444e2e5054dfcbcb8c75b0b719865c96247b37407184bbfca5c353f2c2", size = 14401942, upload-time = "2026-04-21T17:07:31.837Z" }, + { url = "https://files.pythonhosted.org/packages/57/da/9594b75c3c019e805250bed3583bdf4443ff9e6ef08f97e39ae308cb06f2/mypy-1.20.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:688c3312e5dadb573a2c69c82af3a298d43ecf9e6d264e0f95df960b5f6ac19c", size = 15041649, upload-time = "2026-04-21T17:09:34.653Z" }, + { url = "https://files.pythonhosted.org/packages/97/77/f75a65c278e6e8eba2071f7f5a90481891053ecc39878cc444634d892abe/mypy-1.20.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:29752dbbf8cc53f89f6ac096d363314333045c257c9c75cbd189ca2de0455744", size = 15864588, upload-time = "2026-04-21T17:11:44.936Z" }, + { url = "https://files.pythonhosted.org/packages/d7/46/1a4e1c66e96c1a3246ddf5403d122ac9b0a8d2b7e65730b9d6533ba7a6d3/mypy-1.20.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:803203d2b6ea644982c644895c2f78b28d0e208bba7b27d9b921e0ec5eb207c6", size = 16093956, upload-time = "2026-04-21T17:10:17.683Z" }, + { url = "https://files.pythonhosted.org/packages/5a/2c/78a8851264dec38cd736ca5b8bc9380674df0dd0be7792f538916157716c/mypy-1.20.2-cp314-cp314t-win_amd64.whl", hash = "sha256:9bcb8aa397ff0093c824182fd76a935a9ba7ad097fcbef80ae89bf6c1731d8ec", size = 12568661, upload-time = "2026-04-21T17:11:54.473Z" }, + { url = "https://files.pythonhosted.org/packages/83/01/cd7318aa03493322ce275a0e14f4f52b8896335e4e79d4fb8153a7ad2b77/mypy-1.20.2-cp314-cp314t-win_arm64.whl", hash = "sha256:e061b58443f1736f8a37c48978d7ab581636d6ab03e3d4f99e3fa90463bb9382", size = 10389240, upload-time = "2026-04-21T17:09:42.719Z" }, + { url = "https://files.pythonhosted.org/packages/28/9a/f23c163e25b11074188251b0b5a0342625fc1cdb6af604757174fa9acc9b/mypy-1.20.2-py3-none-any.whl", hash = "sha256:a94c5a76ab46c5e6257c7972b6c8cff0574201ca7dc05647e33e795d78680563", size = 2637314, upload-time = "2026-04-21T17:05:54.5Z" }, +] + +[[package]] +name = "mypy-extensions" +version = "1.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a2/6e/371856a3fb9d31ca8dac321cda606860fa4548858c0cc45d9d1d4ca2628b/mypy_extensions-1.1.0.tar.gz", hash = "sha256:52e68efc3284861e772bbcd66823fde5ae21fd2fdb51c62a211403730b916558", size = 6343, upload-time = "2025-04-22T14:54:24.164Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/79/7b/2c79738432f5c924bef5071f933bcc9efd0473bac3b4aa584a6f7c1c8df8/mypy_extensions-1.1.0-py3-none-any.whl", hash = "sha256:1be4cccdb0f2482337c4743e60421de3a356cd97508abadd57d47403e94f5505", size = 4963, upload-time = "2025-04-22T14:54:22.983Z" }, +] + +[[package]] +name = "narwhals" +version = "2.24.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2b/1d/58946e5aab18393e793bd4add6985b95d0e01c3a2d832f38f54468b10dcd/narwhals-2.24.0.tar.gz", hash = "sha256:b5c0f684ccd9d7475b564111e319a4964abcf2baf79d3cf6b1003d06ac9b828d", size = 661143, upload-time = "2026-07-13T10:49:19.086Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7e/85/a5bfaebfd305ac18b57b0854d74e37e586809061a91fda62f0bd50c8518e/narwhals-2.24.0-py3-none-any.whl", hash = "sha256:42fdedf44e5b2ca7505630d45b4ac3058f38d8485cba9fe1652ca23152df7489", size = 461030, upload-time = "2026-07-13T10:49:17.571Z" }, +] + +[[package]] +name = "numpy" +version = "2.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/22/fd/89965aa4ac08c74998539fcbf24fa3540f3e15237fbeb6bcf9c908f4aade/numpy-2.5.1.tar.gz", hash = "sha256:a48a113e6afea91f5608793bafa7ef2ad481fefbda87ec5069f483de61cb9fa3", size = 20755553, upload-time = "2026-07-04T17:08:00.933Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/62/7b/14687aa674250e5e546f616f486b0d56d3631cd5b2415739141ce40bdcea/numpy-2.5.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:2c889b56fe48b1018f764b0eec8df59ab654e9148aa91faa12596043500de277", size = 16801574, upload-time = "2026-07-04T17:06:12.423Z" }, + { url = "https://files.pythonhosted.org/packages/e1/19/cc5bb2a3f2913d27d6dbb2c78d25921fabaedc6741d4a5a615a11f3c5bf3/numpy-2.5.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ab451b59c5643c570974c43aef780703ef1d3b4965d2be07afd530615a9358d1", size = 11772250, upload-time = "2026-07-04T17:06:15.726Z" }, + { url = "https://files.pythonhosted.org/packages/42/77/fdf34a71dd30f54979b18603bee915e0aaf825b07afe79acd60b04b691e2/numpy-2.5.1-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:78798bd5b9ad744056af8efa90e3b9ddaa53272a0848a483084a1cc0a13b2dc0", size = 5331516, upload-time = "2026-07-04T17:06:17.913Z" }, + { url = "https://files.pythonhosted.org/packages/ce/e2/eb7efa015b4cce41e2517bf182a7fce0d7d5b9d9ed76a29bfa0f4fe4505c/numpy-2.5.1-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:2ae0ca40bcb22d6ba59c1dfd5446f49940b0f2d821fde133f10dda11f816b84e", size = 6664863, upload-time = "2026-07-04T17:06:20.02Z" }, + { url = "https://files.pythonhosted.org/packages/a9/4b/a2b32dd94ee9ffbeecb28152240042a3949db33b1c834d44090b80e1b3b8/numpy-2.5.1-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:61ac47e772e6b8ea489e1d2f441a34c5c3ac17327e7ce294cbdf535795ad4e75", size = 15167977, upload-time = "2026-07-04T17:06:21.621Z" }, + { url = "https://files.pythonhosted.org/packages/b8/a9/6e73d68500f80773f65f0654ea932019d6694329a0eb0ed0533de38df376/numpy-2.5.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:59fda5e192b570217ec2580c96f00e9a7e12ef6866a900eb089b62c1a32545ca", size = 16672469, upload-time = "2026-07-04T17:06:24.064Z" }, + { url = "https://files.pythonhosted.org/packages/24/7d/ad3e59015135f5261c95fd4cafeff159c955febd83a99a1d9250c4233815/numpy-2.5.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:f7119ebff1a9829e9f431a4f9d28e703023bb6b9fe7c8f724467dbfc27c94ab3", size = 16527531, upload-time = "2026-07-04T17:06:26.69Z" }, + { url = "https://files.pythonhosted.org/packages/83/d0/a39b2fbcde9cb17a1dac678f254b33a6336298af9df338824c685425d5e8/numpy-2.5.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e824c2acf8862052246be5a44c15da1777940c60d010dd2aab897824d9c430f9", size = 18431940, upload-time = "2026-07-04T17:06:29.521Z" }, + { url = "https://files.pythonhosted.org/packages/04/12/cff070947791c1ed425ff76413189adbdc2fbe215eba7ce7fa454a03c7f8/numpy-2.5.1-cp312-cp312-win32.whl", hash = "sha256:08d60c810432eb83360958dea0999ac4cfb94531ea8efcbf0b7f277c2068aeb2", size = 6066764, upload-time = "2026-07-04T17:06:32.571Z" }, + { url = "https://files.pythonhosted.org/packages/65/66/53f31807a48a750f9d748da273bc3fcedd12b27ff1f3e373bfec55ef2dc0/numpy-2.5.1-cp312-cp312-win_amd64.whl", hash = "sha256:f7d60026c0bdb1380e83bfa7a0419c4577ee4b9a08880afcb6dadeb74c649fa2", size = 12430966, upload-time = "2026-07-04T17:06:34.926Z" }, + { url = "https://files.pythonhosted.org/packages/2b/2a/d1a88066b1c14186f5d3c0d18c94f17b064511982bab0578d49ee9d43c29/numpy-2.5.1-cp312-cp312-win_arm64.whl", hash = "sha256:17a25e09640602e10bc8de0e6fa2b3fd68eedd84ba6d7842dc8f32f9ab87bd0b", size = 10350488, upload-time = "2026-07-04T17:06:37.785Z" }, + { url = "https://files.pythonhosted.org/packages/eb/07/ec2a3f0c91761581d4b7104a740791800025983f9a4dc4e73f91a99aeac4/numpy-2.5.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:0bfebd8695f9863592fe744be833a258120b14a9f39da255e8aa8fade2c0ddd1", size = 16796419, upload-time = "2026-07-04T17:06:40.37Z" }, + { url = "https://files.pythonhosted.org/packages/ab/ab/ddb499fc4f8780354395face5b65c7fd107bcd6e1d667a5f07d046956f6f/numpy-2.5.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:30b44a6b53a7ae63c54c089a8726e5563ed302716c5b7ccc85afade40b0e7ff6", size = 11765832, upload-time = "2026-07-04T17:06:42.768Z" }, + { url = "https://files.pythonhosted.org/packages/88/b3/3c28c558a09fc72100c646dac6d2fce8e834c471b0edca01a29996706117/numpy-2.5.1-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:6165343f81b56ef8f514f396989e529b61d9dc709b99421b07e9f3e698e2287d", size = 5325143, upload-time = "2026-07-04T17:06:45.466Z" }, + { url = "https://files.pythonhosted.org/packages/5e/0e/ce19b985bb15c596f4f05954e76cccc77c845083b3b8f938a6c68e523128/numpy-2.5.1-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:4939237038ada79308dda3204ac6462df056b5672b2e25db1149cf873668b3e1", size = 6659749, upload-time = "2026-07-04T17:06:47.288Z" }, + { url = "https://files.pythonhosted.org/packages/2e/20/1ee6614d64332a1bba6411f38e68cb79eec1b2459e20a623777c5c5492a2/numpy-2.5.1-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1c6759f538fb912fc46de0a6b1758ccf7b57bc7c7ebebc23974fdac3de8db0cd", size = 15164716, upload-time = "2026-07-04T17:06:49.494Z" }, + { url = "https://files.pythonhosted.org/packages/ed/a7/2bcd3fdbb87804755c35b729bf8709d62025c5f4cfd7d5b2415997097515/numpy-2.5.1-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9726558e8db4a5bf7929a70ae50f63abda4daf0efe810e3bfbab95976f75fc1a", size = 16661440, upload-time = "2026-07-04T17:06:52.061Z" }, + { url = "https://files.pythonhosted.org/packages/fc/d7/a41e3310c886fe457d36e670bbf24fae411aca8a7b6ad92a32afd924077c/numpy-2.5.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:3935f3b419b244a02732676fa5317a9193cc596a4c0646db07e5b421229ac9f7", size = 16526305, upload-time = "2026-07-04T17:06:54.605Z" }, + { url = "https://files.pythonhosted.org/packages/53/75/4333a9a707c1edd3a4e1a0c58eca52c0f31e55089fa80db02b5565b24df7/numpy-2.5.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:dc932a65ded7ce9013d120845a2514dcccb1a67bfc8deb8d37633762951904a6", size = 18423008, upload-time = "2026-07-04T17:06:57.54Z" }, + { url = "https://files.pythonhosted.org/packages/ee/90/e314a32b1c11a2ffe818ddad3a57b50b4b6e1b6c487192eb50cdef0415d0/numpy-2.5.1-cp313-cp313-win32.whl", hash = "sha256:4b4ff1608417eb7a59da7b967bbb798cacfe071d2caf526a24281cd562072ed9", size = 6063885, upload-time = "2026-07-04T17:07:00.14Z" }, + { url = "https://files.pythonhosted.org/packages/10/70/800b3fca480af32df9e8ea9f3d4a0c8feb4b32d7f195d174eabbda4829ad/numpy-2.5.1-cp313-cp313-win_amd64.whl", hash = "sha256:6c3fe51bc6a16453d452997053454f309e8e0ed7b42d6b361ce4ac8c32913d74", size = 12425674, upload-time = "2026-07-04T17:07:02.387Z" }, + { url = "https://files.pythonhosted.org/packages/8b/0b/196350c122f50f6ca56846f2d71efd5e0d24b7b2e07355e019b2e2c7a11e/numpy-2.5.1-cp313-cp313-win_arm64.whl", hash = "sha256:f7feb014281029e628ba2d5a007407443b06e418b6fe451d1e2adcbc8eba0107", size = 10350256, upload-time = "2026-07-04T17:07:04.878Z" }, + { url = "https://files.pythonhosted.org/packages/db/f4/731b6085a83faf6ca843394cbd5e217280c214399f7e8b21b9f552af0ae2/numpy-2.5.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:7c786fe9a5bbe360022e584c5a34cf6b54265c71bd7ec8ac3d8fec38968071f8", size = 16795063, upload-time = "2026-07-04T17:07:07.374Z" }, + { url = "https://files.pythonhosted.org/packages/bf/64/0e215f2048dd11a55bb989ed41b3585ef57452404e638d703a211a3e4157/numpy-2.5.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:32985c896d897419ef8da6917872d80b78ad0ea26d85b23245c7366ffde76d75", size = 11776652, upload-time = "2026-07-04T17:07:09.907Z" }, + { url = "https://files.pythonhosted.org/packages/b5/59/2b844c7a6e9deff69b404a66221e1542937734f65d5e6e39411876053862/numpy-2.5.1-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:efd736408cc97c79b9e6917338dfc8f06013b2274f992e96b1d9a81a71e2a2c2", size = 5335944, upload-time = "2026-07-04T17:07:12.227Z" }, + { url = "https://files.pythonhosted.org/packages/86/51/9bf7cb2cabcebc9e017e4ec7e6322b378317a542c08b4cb68479c1efc716/numpy-2.5.1-cp314-cp314-macosx_14_0_x86_64.whl", hash = "sha256:ab84dc6b074fa881cae55bea94cc4f68e285181ba7f32497bf7dee6b1496165b", size = 6656266, upload-time = "2026-07-04T17:07:14.368Z" }, + { url = "https://files.pythonhosted.org/packages/83/3e/fb7615b211b82a32f44d5180a6d421b61f84d4fadd578b48ba4ac34e189f/numpy-2.5.1-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:caf3e317d33d60c37986b452613f4ab51246d0691350c03d0cb4a898627f4a95", size = 15179720, upload-time = "2026-07-04T17:07:16.272Z" }, + { url = "https://files.pythonhosted.org/packages/41/5f/0f992cb24560673496c5d68de61913b57166ce530ffda07c1f280e0cc464/numpy-2.5.1-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:54ad769f17bc2d833b620851989f62054fb9ab93c969d9e1dc3c8e3d56beea21", size = 16664835, upload-time = "2026-07-04T17:07:19.021Z" }, + { url = "https://files.pythonhosted.org/packages/a2/2f/97d6475ee91afe2587797d09446f9d3e475ad4cb681662d824809327b75a/numpy-2.5.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:c12afb53450fa976d4c681c50a7423729a4c51c0465ed9f32b8a9cabbc472373", size = 16539135, upload-time = "2026-07-04T17:07:22.015Z" }, + { url = "https://files.pythonhosted.org/packages/c4/5b/4db81e4ba0be7e2776b1de68c82aa862c7f8ec27e1b4927d4ae075e20678/numpy-2.5.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:e8c11c405efc5ff6816d5983c96cdfa215bab3428961243af3ff59b228490438", size = 18426684, upload-time = "2026-07-04T17:07:24.941Z" }, + { url = "https://files.pythonhosted.org/packages/1f/64/c0ba2d90724d450279a7df8f32057241070250a26a7e2b5337d77347f481/numpy-2.5.1-cp314-cp314-win32.whl", hash = "sha256:f2479a47f8d5932d1718168a681ad6e536a9df484c83cfcf9de365e164537ace", size = 6116103, upload-time = "2026-07-04T17:07:27.622Z" }, + { url = "https://files.pythonhosted.org/packages/c1/1a/837f9ed7405adcd7a40538792eb169eddd8fa5630c16a1ef49dae71a30f4/numpy-2.5.1-cp314-cp314-win_amd64.whl", hash = "sha256:24d0eb82c0541d3415a33425db64ae439dffccd7b4dbcb30e7c35120205c506a", size = 12562177, upload-time = "2026-07-04T17:07:29.887Z" }, + { url = "https://files.pythonhosted.org/packages/22/ed/49707938b6dd0a78a9178dd93227dc89e4c11af47f5c798d70366e8d0483/numpy-2.5.1-cp314-cp314-win_arm64.whl", hash = "sha256:5a4c988b38d261deeeaad9954e3deb091ad905c94e8bb6708654ef1d97f286b0", size = 10627739, upload-time = "2026-07-04T17:07:32.568Z" }, + { url = "https://files.pythonhosted.org/packages/a6/c7/bb4b882cfe7f299cbc8b66e42e7dd78cf9d14e40f9469fc5e3db7e15b3bd/numpy-2.5.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:a33276be12fa045805f477f22482088b66bb758ffbe89a9d21457de863a32e22", size = 11894709, upload-time = "2026-07-04T17:07:34.941Z" }, + { url = "https://files.pythonhosted.org/packages/40/3f/5af7f4a7f6224aef48017aa82bb6174c7a659d724be0c75017b7e64a55b4/numpy-2.5.1-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:f089d7b00756190aacf1f5d34bdf38c3c430ac82b4f868f8cede73380460fce7", size = 5453810, upload-time = "2026-07-04T17:07:37.495Z" }, + { url = "https://files.pythonhosted.org/packages/20/c9/3474309bc94d634d3f9c3eddf03250ecb8c22cd948ef16fef69a77cc5d7b/numpy-2.5.1-cp314-cp314t-macosx_14_0_x86_64.whl", hash = "sha256:09e9bfd8d2cf479c7d174804fb3811c53a8e9f20a37444008606b57d6b7a826d", size = 6761189, upload-time = "2026-07-04T17:07:39.563Z" }, + { url = "https://files.pythonhosted.org/packages/90/8a/558ae39fdd55d7e7f7fef9a84a6e964ac6b23edbd2a07e52bb084500507d/numpy-2.5.1-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e68d8dd1e7eba712948f2053a29ec86917bc70ba1358df869d9f06649ef9cf09", size = 15225039, upload-time = "2026-07-04T17:07:41.682Z" }, + { url = "https://files.pythonhosted.org/packages/63/27/ca7392b2d030277bdf0273e7d23255b3ee57d57a7c170a6f4fb3981e1e5d/numpy-2.5.1-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:99d5095fa265a0c4152e7bb12759e14381ef5496152f1ce58f44bdf55c44beb4", size = 16701306, upload-time = "2026-07-04T17:07:44.611Z" }, + { url = "https://files.pythonhosted.org/packages/02/42/03d53ae7996c44d4374a8262e9dc41671fd56cbb98f7d47ef85cf5da4c6b/numpy-2.5.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:ab87a91b3cc3382b8956095bd8f95e00cf679bb81554339be1a2ba404a1473c1", size = 16589955, upload-time = "2026-07-04T17:07:47.694Z" }, + { url = "https://files.pythonhosted.org/packages/7b/15/6c1784ae469640e65db111e9a34b3d0f14d91e8a38b9ce34810ced370dbb/numpy-2.5.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:224ca51130ef7da85bea2191625181cb4f337f9cb64b471f10c1a12aa8b60077", size = 18464252, upload-time = "2026-07-04T17:07:50.684Z" }, + { url = "https://files.pythonhosted.org/packages/94/a8/f98e50356cf167df656c526c2dfeec2d7dde182f2a3da4b458a5938e2776/numpy-2.5.1-cp314-cp314t-win32.whl", hash = "sha256:6eab239876581b2b3c5a242281b6007bbdbcd1c7085d7709bb57c5929b11e6bf", size = 6263298, upload-time = "2026-07-04T17:07:53.445Z" }, + { url = "https://files.pythonhosted.org/packages/72/ac/96ae880cdecad0b3275d9359fcec72667b49a4863c9f12942e43679dda02/numpy-2.5.1-cp314-cp314t-win_amd64.whl", hash = "sha256:83ce9c80d5b521b0d77ddcbe5447c218d247929b6cc056ca5351342accfff0af", size = 12748623, upload-time = "2026-07-04T17:07:55.384Z" }, + { url = "https://files.pythonhosted.org/packages/a1/5a/4d2b1601df3602dba7a14f3348ba9bfe94a18adb428e693df6154c293831/numpy-2.5.1-cp314-cp314t-win_arm64.whl", hash = "sha256:5a6db61f9aaa57e369905c67d852045d3c4f7126405b29d09b19dec118e9c9cb", size = 10697674, upload-time = "2026-07-04T17:07:58.506Z" }, +] + +[[package]] +name = "packaging" +version = "26.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7d/fa/3944b40b07da9ce895c0e6303a5ab7d53da063554f534556b134a54d6093/packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", size = 313412, upload-time = "2026-08-04T18:15:28.737Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" }, +] + +[[package]] +name = "pandas" +version = "3.0.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, + { name = "python-dateutil" }, + { name = "tzdata", marker = "sys_platform == 'emscripten' or sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/be/4f/5f3422a2afec5ffc46308b79e53291365a93748b498ac2e58bead0197916/pandas-3.0.5.tar.gz", hash = "sha256:dca3734d6ab7c906e6730f0788b0a1dbb9f2467731f9711f77995c8e9d62d712", size = 4658219, upload-time = "2026-07-22T22:19:28.819Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1c/54/1dc810ea558d1320b597aa140a514f2fdf1d2ea09c38cf556f13ea712ec9/pandas-3.0.5-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:fa290c16964d4963fbfbc358928239cf3bd755b20e988ce944877def2f44471d", size = 10411717, upload-time = "2026-07-22T22:18:08.307Z" }, + { url = "https://files.pythonhosted.org/packages/68/56/fbe81c09195924d8b7b8d4461a20458fe80a6a5ed6b24f0314da684277e1/pandas-3.0.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:c2e26bb46934b8a2ca0c3de1d3d606fc5f6746584791b2db264d58cf370e08dc", size = 9957095, upload-time = "2026-07-22T22:18:10.6Z" }, + { url = "https://files.pythonhosted.org/packages/e0/51/fac252f4a913ed5eabf3c11b880a9e8d5a6c10f0b2129d0462212d238b4d/pandas-3.0.5-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:73fa87b08a7ef706f8aafda39ddaccf2a99047bea62d8c88a0361bcafb2237bc", size = 10485458, upload-time = "2026-07-22T22:18:12.834Z" }, + { url = "https://files.pythonhosted.org/packages/12/98/e976540c1addf70442be7842a18cf70884a964abbf69442504f4d2939989/pandas-3.0.5-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d373ce03ffd84010ed9839fa73672a9c8256990532e158440c0085db7d914b34", size = 10998091, upload-time = "2026-07-22T22:18:15.209Z" }, + { url = "https://files.pythonhosted.org/packages/a4/8c/1f29b5be8d3fc47dd7567eb167fabba2085879b31e0287ce7cba6d3d2ff4/pandas-3.0.5-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:2a29c53d85ea98c5e792c59ef82ee9fbe6ca902c0d0adb6b23f45ef894cd7bf6", size = 11499501, upload-time = "2026-07-22T22:18:17.689Z" }, + { url = "https://files.pythonhosted.org/packages/9d/e2/bd9c98ad2df7b38bde002adde4cdf353519da51881634323b126c55997f9/pandas-3.0.5-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a5ad3b02ed6bc7d7ae9b70804b2c6aa31827489d150f8e623ce82491b82085d7", size = 12060559, upload-time = "2026-07-22T22:18:20.147Z" }, + { url = "https://files.pythonhosted.org/packages/f3/9a/ffbd852d58bd74a617fe2f8ee6a58a96982271ce41cf981eab22190b4a4b/pandas-3.0.5-cp312-cp312-pyemscripten_2024_0_wasm32.whl", hash = "sha256:b2acb4650527eec6822c3dadb2b771277b65e7dae7a267d4bccf65fd1bb3fbce", size = 7197652, upload-time = "2026-07-22T22:18:22.502Z" }, + { url = "https://files.pythonhosted.org/packages/70/b5/d2d3e9ae73362ba4229651b0ee1455cf78073a1ce585f6ff693782ce263e/pandas-3.0.5-cp312-cp312-win_amd64.whl", hash = "sha256:80a611068e8a3ac23f7398c6c14eb46dc974e5cc9997f653e2dcfd1da74edd41", size = 9831691, upload-time = "2026-07-22T22:18:24.534Z" }, + { url = "https://files.pythonhosted.org/packages/52/51/dea1e89d6a6796b9c43f85a09b484ee03edb8a4c4842e73e200a8c11301c/pandas-3.0.5-cp312-cp312-win_arm64.whl", hash = "sha256:25ff585b972a18ef1fe9ffa3ac6544d9950508aa76832e5147640b6022821e49", size = 9105796, upload-time = "2026-07-22T22:18:27.064Z" }, + { url = "https://files.pythonhosted.org/packages/bf/09/7b95c4a0025227d6f118c4039b423412ac6a982db02864166185d812fbc7/pandas-3.0.5-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:c1c05a767fe8e5b4fe9e1c29806829c582052eaedb9120a3da83ba3f69e24a5b", size = 10385742, upload-time = "2026-07-22T22:18:29.346Z" }, + { url = "https://files.pythonhosted.org/packages/8d/0c/dc78fd8c4da477b4b5e8ad37295af352190d21ef63a9ee1bc071753074cc/pandas-3.0.5-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:b86765f268b56f7e665b93bce9d5df69dee7f99e595cf8fb839483ab315942a3", size = 9932067, upload-time = "2026-07-22T22:18:31.833Z" }, + { url = "https://files.pythonhosted.org/packages/3e/71/3592c055cf44df9808550f9368ceda80ff2b224d355ef73fe251dcda1802/pandas-3.0.5-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c597ecf5616b5c420372c1d4d4c00dbbfba7398bea857dcc984347e1ea48417b", size = 10466756, upload-time = "2026-07-22T22:18:34.195Z" }, + { url = "https://files.pythonhosted.org/packages/e3/70/4363150359f95b4cb4bcbb34ca23572bb5495749a621a8f3d5a1ddfd293c/pandas-3.0.5-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4b11c36e218331d0387cbe3a0a5f75162357a1d92d57b2b08a336ff94b19b2be", size = 10938525, upload-time = "2026-07-22T22:18:36.81Z" }, + { url = "https://files.pythonhosted.org/packages/f7/d0/317e7a0c67c0e69fa905a0161409397a7dc2d46ff611f6ca4803352c042b/pandas-3.0.5-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:cf52e1f61d229496da17dc7ab54acdee627357e7008fd4fecba3d0ba2937fa58", size = 11489303, upload-time = "2026-07-22T22:18:39.287Z" }, + { url = "https://files.pythonhosted.org/packages/f1/8d/36dade89b49e4f9d5cbdbe863772581f98c0c6d78fc39ad4c557f6f2e17e/pandas-3.0.5-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:db172144bb56422bd157812f3b021eacc255451470b31e2c633c349490a1cfee", size = 11989004, upload-time = "2026-07-22T22:18:42.208Z" }, + { url = "https://files.pythonhosted.org/packages/9c/ba/18c4ec8a746e177da05a9e7a7963781d8ea195780724f854601b6ebd6b78/pandas-3.0.5-cp313-cp313-win_amd64.whl", hash = "sha256:0d298e951f23016ce4699951d044ae6418dbc91bf68cefca0f77666fcbb4e5c6", size = 9826896, upload-time = "2026-07-22T22:18:44.539Z" }, + { url = "https://files.pythonhosted.org/packages/de/ec/28a57266b753799a87b8bc79e7887ac6fd981b8c6d2978a0b7e7b6bd708c/pandas-3.0.5-cp313-cp313-win_arm64.whl", hash = "sha256:66266d3442a5e8b3c90274c2b8b230bee42dd1c286bc822cc2f9f2c7e12b883e", size = 9094790, upload-time = "2026-07-22T22:18:47.468Z" }, + { url = "https://files.pythonhosted.org/packages/51/2f/cf6aae281264f4463f0875bcbb15fd2bb6d291cc535187dad1732475e4a9/pandas-3.0.5-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:2f264fc46911cc8131a7322a16199bbf8e353d27c10bb211f5bd0c814324dc36", size = 10390034, upload-time = "2026-07-22T22:18:49.818Z" }, + { url = "https://files.pythonhosted.org/packages/06/ec/5189518c7a7659c4bdcc6b1eb32c46c6f3c86b0661ffd84143d1112c7732/pandas-3.0.5-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:53730687fcd161883b24e10411c06d6a4c0f2275d2faf3bb2bc25deb4ba8007c", size = 9980065, upload-time = "2026-07-22T22:18:52.249Z" }, + { url = "https://files.pythonhosted.org/packages/ea/f1/598503ce8d7e3c35601e0747ba288c7864baae66380725bc12f13f884dfe/pandas-3.0.5-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:960d3ebcf249f75206899fcd2c6de53f736b7265759ced0d3e559df0b8b709b0", size = 10545532, upload-time = "2026-07-22T22:18:54.813Z" }, + { url = "https://files.pythonhosted.org/packages/fa/de/ceae2adf7034e07e9910299fe412e1819c4f0dd520700a888bcb03625448/pandas-3.0.5-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9e94c2c5ca43bd3ca32bf64d32308887b65e5f9bfd8023ea52755107a999f93b", size = 10963120, upload-time = "2026-07-22T22:18:57.42Z" }, + { url = "https://files.pythonhosted.org/packages/66/25/86e0f4451874eb79e688deeebe3c451fec4557f8952005818d800ee8ac7e/pandas-3.0.5-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:e819dd5f62966b481a8cb649d3299ebd886a1ea91ed5a99bf7ce77c98d18ab94", size = 11563178, upload-time = "2026-07-22T22:18:59.729Z" }, + { url = "https://files.pythonhosted.org/packages/f3/45/8643daa3b4147e433adfcccefdd0380d3aad79d86b15d8999730fe1944d5/pandas-3.0.5-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:3c5ed2e7c06e91d340dfd091d7934f9bc82e4a36b95f647f090b9d1c9ac649da", size = 12028708, upload-time = "2026-07-22T22:19:02.164Z" }, + { url = "https://files.pythonhosted.org/packages/96/58/ad979ae617615576e8aafd569c9d4b62f1191d896e38f51d66ba06f3b89a/pandas-3.0.5-cp314-cp314-win_amd64.whl", hash = "sha256:cd8f7c6dc98527058ee6264219343f5392240a6f1bfa654fc5d79023020d0c92", size = 9951806, upload-time = "2026-07-22T22:19:04.596Z" }, + { url = "https://files.pythonhosted.org/packages/69/32/7ac03886b304049a9d2625ee88f59af760d8a93bd30ed9239bce7b9869a8/pandas-3.0.5-cp314-cp314-win_arm64.whl", hash = "sha256:5183427f5a8156d480f30333777bc978be93650a49a7c01db26adffe95b31e85", size = 9238297, upload-time = "2026-07-22T22:19:06.836Z" }, + { url = "https://files.pythonhosted.org/packages/be/ed/1d1f2ee5547d5167face2376d11c8b2a4c7bfff5a416ee7a9046891fab1e/pandas-3.0.5-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:303da736987d481074ca720ada325f8bd80c64ebc2d45ed79b29df3aaa4a26ca", size = 10849690, upload-time = "2026-07-22T22:19:09.391Z" }, + { url = "https://files.pythonhosted.org/packages/57/55/17e17152e98fbb0c4b1e562bc65387a2f20a80db0f4a86bf8d3a0e4248d4/pandas-3.0.5-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:3b2801bbb049d0136f6c213eae02b5fca969384fc2064dd728d8620552aa49da", size = 10509945, upload-time = "2026-07-22T22:19:11.773Z" }, + { url = "https://files.pythonhosted.org/packages/88/90/817d44dbf83facf9556f33576d9af0a241981e7bb5c00606c0bcb5df8dda/pandas-3.0.5-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cce3a9d11d2b1f82c69a27ec1f4948a170e2c403c4bbfa8cca62e3fdebe2ef3a", size = 10392197, upload-time = "2026-07-22T22:19:14.024Z" }, + { url = "https://files.pythonhosted.org/packages/f1/da/889f00c0a6f5aa1545add70abbf01502dff87ab577adb855bd631c54d2f2/pandas-3.0.5-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ef01af4d8dc6cd2c8d6c7736f149574ef93fe043811eeb5e445f2647154b5040", size = 10862726, upload-time = "2026-07-22T22:19:16.351Z" }, + { url = "https://files.pythonhosted.org/packages/bc/98/f1e934fb3c98fce859c6147c6785816c7b5b9ab7821115c5d8c4de9842b9/pandas-3.0.5-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:e2759e890db96dfcffdbd9b86c3c2cb6afaf58def482820317e06163ec1066cd", size = 11414864, upload-time = "2026-07-22T22:19:18.981Z" }, + { url = "https://files.pythonhosted.org/packages/fe/be/d448af7d657d82e1888dd8551f79c6d6fb161080b5b9752d84d910ec2319/pandas-3.0.5-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:b58b1b39d46a5862e3fb18f50d1a201398619d16a0f9f73f57eea5583cf0e63c", size = 11925105, upload-time = "2026-07-22T22:19:21.515Z" }, + { url = "https://files.pythonhosted.org/packages/29/c1/ccb4238212c8c4f496c584f3044d94e0c030ed8e1d68999db46c91c2242f/pandas-3.0.5-cp314-cp314t-win_amd64.whl", hash = "sha256:1c10461f6eeb35d8f05b6184c65c8b9991663b66c46b1d559b682cb34ae7c6ea", size = 10387612, upload-time = "2026-07-22T22:19:24.257Z" }, + { url = "https://files.pythonhosted.org/packages/d2/cf/6a51b2c38980e04c279fd2fa908a1b0982064e860444acfca4ec2e2c8359/pandas-3.0.5-cp314-cp314t-win_arm64.whl", hash = "sha256:3c5015fd1730fbf883647e88068176c839c102cea883ba1769a6f4593bfc1f8c", size = 9509776, upload-time = "2026-07-22T22:19:26.694Z" }, +] + +[[package]] +name = "pathspec" +version = "1.1.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/5a/82/42f767fc1c1143d6fd36efb827202a2d997a375e160a71eb2888a925aac1/pathspec-1.1.1.tar.gz", hash = "sha256:17db5ecd524104a120e173814c90367a96a98d07c45b2e10c2f3919fff91bf5a", size = 135180, upload-time = "2026-04-27T01:46:08.907Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f1/d9/7fb5aa316bc299258e68c73ba3bddbc499654a07f151cba08f6153988714/pathspec-1.1.1-py3-none-any.whl", hash = "sha256:a00ce642f577bf7f473932318056212bc4f8bfdf53128c78bbd5af0b9b20b189", size = 57328, upload-time = "2026-04-27T01:46:07.06Z" }, +] + +[[package]] +name = "pillow" +version = "12.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1c/3d/bb7fca845737cf9d7dbde16ed1843984665ff2e0a518f5db43e77ec540b9/pillow-12.3.0.tar.gz", hash = "sha256:3b8182a766685eaa002637e28b4ec8d6b18819a0c71f579bf0dbaa5830297cce", size = 47025035, upload-time = "2026-07-01T11:56:38.965Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/37/bf/fb3ebff8ddcb76aac5a01389251bbbb9519922a9b520d8247c1ca864a25d/pillow-12.3.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ba09209fbe443b4acccebe845d8a138b89a8f4fbaeedd44953490b5315d5e965", size = 5345969, upload-time = "2026-07-01T11:54:06.397Z" }, + { url = "https://files.pythonhosted.org/packages/d8/66/9a386a92561f402389a4fc70c18838bf6d35eb5eb5c6850b4b2dc64f5048/pillow-12.3.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ffd0c5368496f41b0944be820fcb7a838aa6e623d250b01acf2643939c3f99d7", size = 4780323, upload-time = "2026-07-01T11:54:09.351Z" }, + { url = "https://files.pythonhosted.org/packages/25/27/ac8f99618ffd3dde21db0f4d4b1d2ab00c0880595bfd17df103f7f39fd0c/pillow-12.3.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d9c7f76c0673154f044e9d78c8655fb4213f6ca31a836df48b40fe5d187717b9", size = 6266838, upload-time = "2026-07-01T11:54:11.71Z" }, + { url = "https://files.pythonhosted.org/packages/84/21/a35af28dcc61f37ed850a2d64c65c701321dfbf25085e469d5559360cbbf/pillow-12.3.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:78cb2c6865a35ab8ff8b75fd122f6033b92a62c82801110e48ddd6c936a45d91", size = 6940830, upload-time = "2026-07-01T11:54:13.732Z" }, + { url = "https://files.pythonhosted.org/packages/eb/51/8b08617af3ad95e33ce6d7dd2c99ed6c8298f7fb131636303956be022e25/pillow-12.3.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:e491916b378fba47242221bb9ead245211b70d504f495d105d17b14a24b4907c", size = 6344383, upload-time = "2026-07-01T11:54:15.756Z" }, + { url = "https://files.pythonhosted.org/packages/1d/72/cf78ac9780bb93c28328f408973845a309d4d145041665f734572ced1b52/pillow-12.3.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0dd2064cbc55aaec028ef5fbb60fa47bb6c3e7918e07ff17935284b227a9d2df", size = 7052934, upload-time = "2026-07-01T11:54:17.721Z" }, + { url = "https://files.pythonhosted.org/packages/20/20/25e0f4dc178a6bc0696793720055519a0de89e7661dae886992decbd2f81/pillow-12.3.0-cp312-cp312-win32.whl", hash = "sha256:dbce0b29841537a2fa4a214c2bbf14de3587c9680caa9b4e217568472490b28f", size = 6472684, upload-time = "2026-07-01T11:54:19.839Z" }, + { url = "https://files.pythonhosted.org/packages/45/89/da2f7971a317f83d807fdd4065c0af40208e59e692cc43d315a71a0e96d1/pillow-12.3.0-cp312-cp312-win_amd64.whl", hash = "sha256:a2b55dd6b2a4c4b7d87ffa56bdb33fdc5fdb9a462173861a7bc097f17d91cb09", size = 7227137, upload-time = "2026-07-01T11:54:22.025Z" }, + { url = "https://files.pythonhosted.org/packages/de/47/4845a0a6c0dbf1db8456bd9fc791f13c5ced7ced20606d08a0aacfd25b49/pillow-12.3.0-cp312-cp312-win_arm64.whl", hash = "sha256:331b624368d4f1d069149002f25f44bc61c8919ce8ddb3c45bdad8f6e2d89510", size = 2568267, upload-time = "2026-07-01T11:54:24.051Z" }, + { url = "https://files.pythonhosted.org/packages/9d/ac/31fb64e1e7efb5a4b50cd3d92049ba89ac6e4d8d3bb6a74e15048ca3353e/pillow-12.3.0-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:21900ce7ba264168cd50defae43cd75d25c833ad4ad6e73ffc5596d12e25ac89", size = 4161684, upload-time = "2026-07-01T11:54:25.934Z" }, + { url = "https://files.pythonhosted.org/packages/87/b4/9805e23d2b4d77842b468513841fda254ee42f0289d25088340e4ff46e2d/pillow-12.3.0-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:4e8c2a84d977f50b9daed6eeaf3baef67d00d5d74d932288f02cb94518ee3ace", size = 4255487, upload-time = "2026-07-01T11:54:27.935Z" }, + { url = "https://files.pythonhosted.org/packages/df/39/ecf519435a200c693fe053a6ee4d835b41cf963a4dfc2551c4e637cb2a71/pillow-12.3.0-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:ae26d61dfa7a47befdc7572b521024e8745f3d809bd95ca9505a7bba9ef849ec", size = 3696433, upload-time = "2026-07-01T11:54:29.813Z" }, + { url = "https://files.pythonhosted.org/packages/42/92/2fc3ffad878ae8dd5469ec1bc8eb83b71f48e13efdf68f02709003982a32/pillow-12.3.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:7a743ff716f746fc19a9557f60dab1600d4613255f8a7aeb3cdde4db7eb15a66", size = 5345889, upload-time = "2026-07-01T11:54:31.97Z" }, + { url = "https://files.pythonhosted.org/packages/10/76/8803c13605b763d33d156c4678fc77f8443389c0c51c8aef707bb02015f4/pillow-12.3.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:d69141514cc30b774ceea5e3ed3a6635c8d8a96edf664689b890f4089111fb35", size = 4780109, upload-time = "2026-07-01T11:54:34.026Z" }, + { url = "https://files.pythonhosted.org/packages/1f/01/e18aff37cb0b4aac47ac90f016d347a49aca667ef97f190b06ac2aabc928/pillow-12.3.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f7401aebd7f581d7f83a439d87d474999317ee099218e5ad25d125290990ba65", size = 6263736, upload-time = "2026-07-01T11:54:36.131Z" }, + { url = "https://files.pythonhosted.org/packages/f7/62/de5bdd77d935331f4f802edc11e4d82950f642caad6cb2f949837b8560e2/pillow-12.3.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0847a763afefb695bc912d7c131e7e0632d4edc1d8698f58ddabec8e46b8b6d3", size = 6937129, upload-time = "2026-07-01T11:54:38.216Z" }, + { url = "https://files.pythonhosted.org/packages/70/4d/105627a13300c5e0df1d174230b32fd1273062c96f7745fd552b945d1e1d/pillow-12.3.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:571b9fcb07b97ef3a492028fb3d2dc0993ca23a06138b0315286566d29ef718a", size = 6339562, upload-time = "2026-07-01T11:54:40.354Z" }, + { url = "https://files.pythonhosted.org/packages/6b/1d/f13de01a553988ab895ba1c722e06cf3144d4f57656fd5b81b6d881f1179/pillow-12.3.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:756c768d0c9c2955feb7a56c37ea24aea2e369f8d36a88da270b6a9f19e62b5e", size = 7049439, upload-time = "2026-07-01T11:54:42.489Z" }, + { url = "https://files.pythonhosted.org/packages/c9/f9/066794cca041b969964f779ee5fa66a9498bbf34248ac39c5d7954e4198f/pillow-12.3.0-cp313-cp313-win32.whl", hash = "sha256:a876864214e136f0eb367788dbd7df045f4806801518e2cfe9e13229cfe06d8f", size = 6473287, upload-time = "2026-07-01T11:54:44.9Z" }, + { url = "https://files.pythonhosted.org/packages/a6/9b/7a58e61d62be561da3a356fe2384d4059a6345fc130e23ef1c36a5b81d24/pillow-12.3.0-cp313-cp313-win_amd64.whl", hash = "sha256:1cca606cd25738df4ed873d5ad46bbdb3d83b5cbca291f6b4ff13a4df6b0bbe8", size = 7239691, upload-time = "2026-07-01T11:54:47.141Z" }, + { url = "https://files.pythonhosted.org/packages/aa/b0/c4ed4f0ef8f8fa5ee8351537db6650bb8189f7e118842978dd6589065692/pillow-12.3.0-cp313-cp313-win_arm64.whl", hash = "sha256:b629de27fda84b42cde7edef0d85f13b958b47f6e9bbcbba9b673c562a89bd8b", size = 2568185, upload-time = "2026-07-01T11:54:49.137Z" }, + { url = "https://files.pythonhosted.org/packages/dc/01/001f65b68192f0228cc1dbbc8d2530ab5d58b61037ba0587f946fea607cd/pillow-12.3.0-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:9cf95fe4d0f84c82d282745d9bb08ad9f926efa00be4697e767b814ce40d4330", size = 4161736, upload-time = "2026-07-01T11:54:51.156Z" }, + { url = "https://files.pythonhosted.org/packages/1a/d2/0219746d0fd16fc8a84498e79452375be3797d3ce4044596ce565164b84f/pillow-12.3.0-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:8728f216dcdb6e6d555cf971cb34076139ad74b31fc2c14da4fafc741c5f6217", size = 4255435, upload-time = "2026-07-01T11:54:53.414Z" }, + { url = "https://files.pythonhosted.org/packages/c8/02/8d0bc62ef0302318c46ff2a512822d2610e81c7aa46c9b3abe6cbaca5ad0/pillow-12.3.0-cp314-cp314-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:a45650e8ce7fafffd731db8550230db6b0d306d181a90b67d3e6bca2f1990930", size = 3696262, upload-time = "2026-07-01T11:54:55.739Z" }, + { url = "https://files.pythonhosted.org/packages/85/e2/73c77d218410b14f5f2d565e8a998d5317b7b9c75368d29985139f7a46f0/pillow-12.3.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:ba54cfebe86920a559a7c4d6b9050791c20513650a1952ebe3368c7dc70306f8", size = 5350344, upload-time = "2026-07-01T11:54:57.657Z" }, + { url = "https://files.pythonhosted.org/packages/c7/da/32c752228ae345f489e3a42499d817b6c3996da7e8a3bc7a04fc806b243b/pillow-12.3.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:e158cb00350dc278f3b91551101aa7d12415a66ebf2c91d8d5ac14e56ddd3ad0", size = 4780131, upload-time = "2026-07-01T11:54:59.713Z" }, + { url = "https://files.pythonhosted.org/packages/b1/9d/8b2c807dbef61a5197c047afe99823787eb66f63daf9fb2432f91d6f0462/pillow-12.3.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e9aeb04d6aef139de265b29683e119b638208f88cf73cdd1658aa07221165321", size = 6263757, upload-time = "2026-07-01T11:55:01.778Z" }, + { url = "https://files.pythonhosted.org/packages/5c/44/c85361f65dbe00eea8576ee467c768d25129989efb76e94f205e9ca9bb46/pillow-12.3.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:251bf95b67017e27b13d82f5b326234ca62d70f9cf4c2b9032de2358a3b12c7b", size = 6936962, upload-time = "2026-07-01T11:55:03.93Z" }, + { url = "https://files.pythonhosted.org/packages/18/7e/e483414b35800b86b6f08dbbc7803fb5cd52c4d6f897f47d53ea2c7e6f65/pillow-12.3.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:fe3cca2e4e8a592be0f269a1ca4835c25199d9f3ce815c8491048f785b0a0198", size = 6339171, upload-time = "2026-07-01T11:55:05.989Z" }, + { url = "https://files.pythonhosted.org/packages/f0/f4/68c491844841ede6bed70189546b3ee9731cf9f2cbad396faff5e1ccba45/pillow-12.3.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:23aceaa007d6172b02c277f0cd359c79492bbb14f7072b4ede9fbcaf20648130", size = 7048116, upload-time = "2026-07-01T11:55:08.131Z" }, + { url = "https://files.pythonhosted.org/packages/a3/34/77f3f793fed8efc7d243f21b33c5a3f0d1c97ee70346d3db855587e155ff/pillow-12.3.0-cp314-cp314-win32.whl", hash = "sha256:af8d94b0db561cf68b88a267c5c44b49e134f525d0dc2cb7ed413a66bc23559a", size = 6467209, upload-time = "2026-07-01T11:55:10.408Z" }, + { url = "https://files.pythonhosted.org/packages/f1/e0/492879f69d94f91f60fc8cd05ba03650e9520afebb2fb7aa12777d7c7f38/pillow-12.3.0-cp314-cp314-win_amd64.whl", hash = "sha256:fdafc9cce40277e0f7a0feabce0ee50dd2fa1800f3b38015e51296b5e814048d", size = 7237707, upload-time = "2026-07-01T11:55:12.745Z" }, + { url = "https://files.pythonhosted.org/packages/c9/ac/6b11f2875f1c2ac040d84e1bbf9cf22a88038f901ca1037898b280b38365/pillow-12.3.0-cp314-cp314-win_arm64.whl", hash = "sha256:e91206ee562682b51b98ef4b26a6ef48fd84e15fd4c4bc5ec768eb641d206838", size = 2565995, upload-time = "2026-07-01T11:55:14.736Z" }, + { url = "https://files.pythonhosted.org/packages/52/69/c2208e56af9bfc1913afb24020297a691eb1d4ef688474c8a04913f65e04/pillow-12.3.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:164b31cd1a0490ab6efae01aa5df49da7061be0af1b30e035b6e9a1bfe34ee6e", size = 5352503, upload-time = "2026-07-01T11:55:17.076Z" }, + { url = "https://files.pythonhosted.org/packages/07/70/e5686d753e898a45d778ff1718dba8516ead6ab6b95d85fc8c4b70650cf2/pillow-12.3.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:5afb51d599ea772b8365ae807ae557f18bccfe46ab261fd1c2a9ed700fc6eb17", size = 4782956, upload-time = "2026-07-01T11:55:19.448Z" }, + { url = "https://files.pythonhosted.org/packages/d5/37/25c6692f06927ee973ff18c8d9ee98ad0b4d84ee67a09610c2dd1447958e/pillow-12.3.0-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3edce1d53195db527e0191f84b71d02022de0540bf43a16ed734ed7537b07385", size = 6322855, upload-time = "2026-07-01T11:55:21.613Z" }, + { url = "https://files.pythonhosted.org/packages/cc/91/420637fcb8f1bc11029e403b4538e6694744428d8246118e45719f944556/pillow-12.3.0-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bf16ba1b4d0b6b7c8e534936632270cf70eb00dbe09005bc345b2677b726855c", size = 6989642, upload-time = "2026-07-01T11:55:24.006Z" }, + { url = "https://files.pythonhosted.org/packages/10/08/b94d7811281ccf0d143a1cf768d1c49e1e54af63e7b708ab2ee3eb87face/pillow-12.3.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:24870b09b224f7ae3c39ed07d10e819d06f8720bc551847b1d623832b5b0e28d", size = 6391281, upload-time = "2026-07-01T11:55:26.252Z" }, + { url = "https://files.pythonhosted.org/packages/d2/87/24233f785f55474dc02ce3e739c5528a77e3a862e9333d1dd7a25cc31f70/pillow-12.3.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:30f2aa603c41533cc25c05acd0da21636e84a315768feb631c937177db558931", size = 7096716, upload-time = "2026-07-01T11:55:28.318Z" }, + { url = "https://files.pythonhosted.org/packages/23/26/fcb2f6e37175b04f53570b59937867e2b80ee1685e744023153028fc14f9/pillow-12.3.0-cp314-cp314t-win32.whl", hash = "sha256:4b0a7fe987b14c31ebda6083f74f22b561fd3739bc0ac51e019622e3d72668c7", size = 6474125, upload-time = "2026-07-01T11:55:30.956Z" }, + { url = "https://files.pythonhosted.org/packages/90/de/3634abee5f1c9e13c56787b7d5517b0ba8d6de51700b95578cf338349c9f/pillow-12.3.0-cp314-cp314t-win_amd64.whl", hash = "sha256:962864dc93511324d51ddbb5b9f8731bf71675b93ca612a07441896f4688fb8c", size = 7242939, upload-time = "2026-07-01T11:55:34.044Z" }, + { url = "https://files.pythonhosted.org/packages/ce/2a/fd13f8eb24de5714a6eb444a3d67e2842c6c576e159a43793adf23051351/pillow-12.3.0-cp314-cp314t-win_arm64.whl", hash = "sha256:0740a512dc522224c77d9aa5a8d70d8b7d73fb91f2c21125d8d025d3b8990e45", size = 2567506, upload-time = "2026-07-01T11:55:35.988Z" }, + { url = "https://files.pythonhosted.org/packages/5d/dc/8fdce34ec725a33c81c6ba122b904d6b9024e50ea9ac7bede62fab54506c/pillow-12.3.0-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:0feb2e9d6ad6c9e3c06effe9d00f3f1e618a6643273576b016f591e9315a7139", size = 4162063, upload-time = "2026-07-01T11:55:37.941Z" }, + { url = "https://files.pythonhosted.org/packages/76/66/2044b9a63d3b84ff048228dfcb7cd9bf0df983e8470971bf7d4c57b693de/pillow-12.3.0-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:9e881fca225083806662a5c43d627d215f258ff43c890f831966c7d7ba9c7402", size = 4255549, upload-time = "2026-07-01T11:55:40.022Z" }, + { url = "https://files.pythonhosted.org/packages/52/7e/1f67e6f4ece6b582ee4b539decbcc9f848dc245a93ed8cd7338bafef72f1/pillow-12.3.0-cp315-cp315-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:4998562bf62a445225f22e07c896bb04b35b1b1f2eb6d760584c9c51d7a5f78c", size = 3696331, upload-time = "2026-07-01T11:55:41.98Z" }, + { url = "https://files.pythonhosted.org/packages/12/40/d306fc2c8e4d45d7f175c77edca7063be7b86fe7fe6e68f4353bf71d808c/pillow-12.3.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:dc624f6bc473dacdf7ef7eb8678d0d08edf15cd94fad6ae5c7d6cc67a4e4902f", size = 5350370, upload-time = "2026-07-01T11:55:44.028Z" }, + { url = "https://files.pythonhosted.org/packages/dd/44/668fb1437e8ce420f62d6106eb66e44a5971602a4d794615bdf79315d82d/pillow-12.3.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:71d6097b330eea8fd15097780c8e89cb1a8ce7838669f48c5bacd6f663dd4701", size = 4780147, upload-time = "2026-07-01T11:55:46.073Z" }, + { url = "https://files.pythonhosted.org/packages/0c/08/93fa2e70e30a2d81547e481b6ee2bb9522117221fb1e0ce4b5df70967677/pillow-12.3.0-cp315-cp315-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:28ce87c5ab450a9dd970b52e5aca5fe63ed432d18a2eaddd1979a00a1ba24ace", size = 6273659, upload-time = "2026-07-01T11:55:48.264Z" }, + { url = "https://files.pythonhosted.org/packages/f8/6d/043e96ff814fc31a33077e4cba86082167db520c93632afdf2042febbb0c/pillow-12.3.0-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6b02afb9b97f65fbca5f31db6a2a3ba21aa93030225f150fa3f249717e938fb4", size = 6947439, upload-time = "2026-07-01T11:55:50.503Z" }, + { url = "https://files.pythonhosted.org/packages/af/92/ba71d2ee2ac0edf3fa33bd9d5ee9ee080da70b1766f3ca3934f9938ddac9/pillow-12.3.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:1182d52bc2d5e5d7d0949503aa7e36d12f42205dc287e4883f407b1988820d39", size = 6353577, upload-time = "2026-07-01T11:55:52.697Z" }, + { url = "https://files.pythonhosted.org/packages/0f/ce/e63064e2122923ff687c8ad792d0d736a7b3920a56a46982e81a7fdd25d6/pillow-12.3.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:e795b7eb908249c4e43c7c99fac7c2c75dab0c43566e37db472a355f63693d71", size = 7060394, upload-time = "2026-07-01T11:55:55.149Z" }, + { url = "https://files.pythonhosted.org/packages/54/76/a09cc3ccc8d773a7283d34c38bec1708f9e3cc932093cbc4c5e71ac4060b/pillow-12.3.0-cp315-cp315-win32.whl", hash = "sha256:57b3d78c95ba9059768b10e28b813002261d3f3dfc55cc48b0c988f625175827", size = 6467375, upload-time = "2026-07-01T11:55:57.769Z" }, + { url = "https://files.pythonhosted.org/packages/3e/03/1846c49ba3b1d5550392a4bbd06d6fb4578e1cd91a803198b5c90f5f7d53/pillow-12.3.0-cp315-cp315-win_amd64.whl", hash = "sha256:fa4ecea169a355be7a3ade2c783e2ed12f0e40d2c5621cda8b3297faf7fbb9f5", size = 7237048, upload-time = "2026-07-01T11:55:59.975Z" }, + { url = "https://files.pythonhosted.org/packages/fb/bb/89f35dcc79610423f9f195504d7def7f0d1416a711541b42867e25fe3412/pillow-12.3.0-cp315-cp315-win_arm64.whl", hash = "sha256:877c3f311ff35410f690861c4409e7ccbf0cd2f878e50628a28e5a0bb689e658", size = 2566006, upload-time = "2026-07-01T11:56:02.143Z" }, + { url = "https://files.pythonhosted.org/packages/30/88/707027ba09942dfa2c28759b5c222d769290a41c6d20ea60ec250801941f/pillow-12.3.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:e9871b1ffbfa9656b60aeee92ed5136a5742696006fa322b29ea3d8da0ecc9cf", size = 5352509, upload-time = "2026-07-01T11:56:04.2Z" }, + { url = "https://files.pythonhosted.org/packages/b0/6d/00352fa25332c2569cd387851f568cc5a4b75a9adbfb37ac4fbce4c02eec/pillow-12.3.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:53aa02d20d10c3d814d536aa4e5ac9b84ca0ff5a88377963b085ad6822f93e64", size = 4783167, upload-time = "2026-07-01T11:56:06.631Z" }, + { url = "https://files.pythonhosted.org/packages/13/4f/9e049dfa21af7c22427275720e2490267ba8138120add5c4c574deb69782/pillow-12.3.0-cp315-cp315t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:446c34dcc4324b084a53b705127dc15717b22c5e140ae0a3c38349d4efec071e", size = 6329237, upload-time = "2026-07-01T11:56:08.868Z" }, + { url = "https://files.pythonhosted.org/packages/36/16/cf6eeaae8d0fce8dd390a33437cf68c5d5bd73834a2bc6e2f14efda0ab45/pillow-12.3.0-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:cf1845d02ad822a369a49f2bb9345b1614744267682e7a03527dc3bf6eea1777", size = 6997047, upload-time = "2026-07-01T11:56:11.379Z" }, + { url = "https://files.pythonhosted.org/packages/1e/69/dbf769bdd55f48bf5733cac28edc6364ffaa072ec9ba336266e4fe66be55/pillow-12.3.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:186941b6aef820ad110fb01fb06eb925374dc3a21b17e37ec9a53b250c6fe2d1", size = 6400440, upload-time = "2026-07-01T11:56:13.908Z" }, + { url = "https://files.pythonhosted.org/packages/a0/e1/ffc9cfc2eea0d178da8018e18e959301ad9d6bc9f3edb7181e748a474b97/pillow-12.3.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:f13c32a3abd6079a66d9526e18dad9b6d280384d49d7c54040cd57b6424041d9", size = 7105895, upload-time = "2026-07-01T11:56:16.575Z" }, + { url = "https://files.pythonhosted.org/packages/18/f0/a5595c1e8c3ae44b9828cb2f0fa8155e5095ef04d6327b8f61cf44a3df85/pillow-12.3.0-cp315-cp315t-win32.whl", hash = "sha256:1657923d2d45afb66526e5b933e5b3052e6bdea196c90d3abb2424e18c77dae8", size = 6474384, upload-time = "2026-07-01T11:56:18.855Z" }, + { url = "https://files.pythonhosted.org/packages/e4/04/62bcd9f844984c5938d3b05264a61d797a29d3e0812341a8204af70bbdee/pillow-12.3.0-cp315-cp315t-win_amd64.whl", hash = "sha256:8cd2f7bdda092d99c9fc2fb7391354f306d01443d22785d0cbfafa2e2c8bb418", size = 7243537, upload-time = "2026-07-01T11:56:21.214Z" }, + { url = "https://files.pythonhosted.org/packages/3d/68/1f3066acedf37673694a7141381d8f811ae97f30d34413d236abe7d489f1/pillow-12.3.0-cp315-cp315t-win_arm64.whl", hash = "sha256:06ff022112bc9cbf83b60f8e028d94ad87b60621706487e65f673de61610ab59", size = 2567491, upload-time = "2026-07-01T11:56:23.506Z" }, +] + +[[package]] +name = "pluggy" +version = "1.6.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f9/e2/3e91f31a7d2b083fe6ef3fa267035b518369d9511ffab804f839851d2779/pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3", size = 69412, upload-time = "2025-05-15T12:30:07.975Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" }, +] + +[[package]] +name = "polars" +version = "1.43.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "polars-runtime-32" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/89/13/3873f213304bcbaaf39e63c8b905ceb460a0524448d57f86a829f6d4d0fd/polars-1.43.2.tar.gz", hash = "sha256:c699671b99eb71ff53334d237917aaa3db5ad4dda480abcb6c80e0eaee7b677b", size = 750312, upload-time = "2026-08-01T06:28:30.872Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2b/fe/0888040a24e4504098b85d8ad486b14cb01cf6b030bbe479dfc2dcffc2ac/polars-1.43.2-py3-none-any.whl", hash = "sha256:22aa0cb92a1ee2d60d6a15a638b2e8e0dd99aea21ac0cd8fb29da8e382e075a9", size = 847150, upload-time = "2026-08-01T06:27:15.543Z" }, +] + +[[package]] +name = "polars-runtime-32" +version = "1.43.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d4/06/11b578eeef05f867e3ee31b2a2fdd8e7684c2aa47822c49935d1be789c38/polars_runtime_32-1.43.2.tar.gz", hash = "sha256:d7b7c486bccee75a6af0158b87077da3d054657e3c60036b28644f4e1c7fdbf7", size = 3095669, upload-time = "2026-08-01T06:28:32.315Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/59/fc/12e6d4ca34d820297651134cfa35f86c33e898539fc6629cbb35d0089697/polars_runtime_32-1.43.2-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:91abf205d4ec93f92ba95386b7f8776559ae3dfce425ed2e527efa75d117d04a", size = 53088908, upload-time = "2026-08-01T06:27:18.268Z" }, + { url = "https://files.pythonhosted.org/packages/32/81/833b0853551deb810854f96b43dea342b6e6c9b0ea1afcccf774157d519d/polars_runtime_32-1.43.2-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:2cc3ff96fd44789b02eb5c15b98dfcb000101636b177d3034fae2feec19b118f", size = 47540529, upload-time = "2026-08-01T06:27:21.391Z" }, + { url = "https://files.pythonhosted.org/packages/83/55/7b2a75af14c9294d97f3bec132dd3018ddcd988bef32b5d28322150b8c11/polars_runtime_32-1.43.2-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:10ed36e615ab362feb7406e6d084e124b445ad284caa73bd93ae7e65745ed894", size = 51366340, upload-time = "2026-08-01T06:27:24.776Z" }, + { url = "https://files.pythonhosted.org/packages/62/60/64deacb3abc70c52e2d88a808a052d1621c86a48fe9194f2c065579ab1cd/polars_runtime_32-1.43.2-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6d5a7ae004a2723ebf4427f6d6a639f30f86af4cf077075f6b35d04711154fc3", size = 57304599, upload-time = "2026-08-01T06:27:27.875Z" }, + { url = "https://files.pythonhosted.org/packages/52/95/d6e3a236d7630e17c40d0ddee839bf2be9acf548fdc0e5ad65ed9ff0cac6/polars_runtime_32-1.43.2-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:09339eacc6d392206e78aabbaaa37d7276eb969b798f46cb1f367fd718798c60", size = 51520580, upload-time = "2026-08-01T06:27:30.913Z" }, + { url = "https://files.pythonhosted.org/packages/b6/5a/2deb8eac70e9a2ac26d88a66ae7cf52612865026f4f4a5e7ab11ad9d52bf/polars_runtime_32-1.43.2-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:452b400e59e7f56e4c6437f435e796903272a9388feee12de2bea049ae87025e", size = 55204471, upload-time = "2026-08-01T06:27:33.886Z" }, + { url = "https://files.pythonhosted.org/packages/29/9e/647401ae8a607bc0cc40ed7b8592d5b1be90ded0dc9b9d6d3aeb03f9524b/polars_runtime_32-1.43.2-cp310-abi3-win_amd64.whl", hash = "sha256:00e33c28e321410c8d66e814a90043101e3bdd9ed2c6dabda07565aa8adbbdf1", size = 52572176, upload-time = "2026-08-01T06:27:37.048Z" }, + { url = "https://files.pythonhosted.org/packages/96/8d/60a50c3f36c85218a7ffcb48c6fe2ce1f7bec799152d68b8658ebed2179c/polars_runtime_32-1.43.2-cp310-abi3-win_arm64.whl", hash = "sha256:350a4868cae85bf8b3f81b33ba47927c15256bd9264dfc8c0753f1b927eac9d3", size = 46582513, upload-time = "2026-08-01T06:27:40.025Z" }, +] + +[[package]] +name = "protobuf" +version = "7.35.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/da/01/9ef0afd7999eb9badb3a768b4aedd78c86d4c65cfaf1958ab276199e76b4/protobuf-7.35.1.tar.gz", hash = "sha256:ce115a26fe0c39a2c29973d914d327e516a6455464489fe3cd1e51a1b354f81a", size = 458717, upload-time = "2026-06-11T21:55:40.257Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/10/03/8aeeb7458d22546bf64b5250ca1daeb5ff757d900e8e4a7476c6f0db843e/protobuf-7.35.1-cp310-abi3-macosx_10_9_universal2.whl", hash = "sha256:24f857477359a85c0c235261b8ba905fd51b2562f4a64ca1df5473f29850cbf6", size = 433226, upload-time = "2026-06-11T21:55:31.719Z" }, + { url = "https://files.pythonhosted.org/packages/37/4b/dfb89eb0e652a1ff073c39a59fb5e3a83cfe9b57a2c83fa6d78270101767/protobuf-7.35.1-cp310-abi3-manylinux2014_aarch64.whl", hash = "sha256:11d6b0ec246892d85215b0a13ca6e0233cf5284b68f0ac02646427f4ff88a799", size = 328847, upload-time = "2026-06-11T21:55:34.035Z" }, + { url = "https://files.pythonhosted.org/packages/0f/58/dc12f2cd484951524af6e3382c785869b9b3fb5e52ee95ae23add53ee8f9/protobuf-7.35.1-cp310-abi3-manylinux2014_s390x.whl", hash = "sha256:b73f9489a4b8b1c9cb1f8ed951c736392592edb24b9d6819f36d2e10b171d5b4", size = 344030, upload-time = "2026-06-11T21:55:34.941Z" }, + { url = "https://files.pythonhosted.org/packages/e4/be/5b3cfe508bfab6761414ff944e3366eb13be4fd71efcd69450f89ba39f43/protobuf-7.35.1-cp310-abi3-manylinux2014_x86_64.whl", hash = "sha256:74758715c53d7158fb76caf4f0cfdacc5329a4b1bb994f865d6cf302d413a1c4", size = 327130, upload-time = "2026-06-11T21:55:35.921Z" }, + { url = "https://files.pythonhosted.org/packages/d8/bc/6d6c7ba8709c85f8f2c390b2b118d6fb08a783676a572271851bf45a7d22/protobuf-7.35.1-cp310-abi3-win32.whl", hash = "sha256:353652e4efd0bca5b5fc2656abf8307ef351f0cf938c9eba09f0e09c20a25c30", size = 428945, upload-time = "2026-06-11T21:55:37.034Z" }, + { url = "https://files.pythonhosted.org/packages/0a/19/8d0cb6f20a1ef7b18f1c8986ad5783f22f84cce39c6ce9a6e645ea55192e/protobuf-7.35.1-cp310-abi3-win_amd64.whl", hash = "sha256:230a75ddfc2de4806e56696ce9640c1cdfdb6543b7cfce98d42a4c0a0e7bdb87", size = 439996, upload-time = "2026-06-11T21:55:38.123Z" }, + { url = "https://files.pythonhosted.org/packages/19/c7/5f7c636ec43e0c545e28d1f1db71990108306f7bdcb89f069ba97e428e7f/protobuf-7.35.1-py3-none-any.whl", hash = "sha256:4bc97768d8fe4ad6743c8a19403e314511ed9f6d13205b687e52421c023ac1b9", size = 171659, upload-time = "2026-06-11T21:55:39.155Z" }, +] + +[[package]] +name = "pyarrow" +version = "23.0.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/88/22/134986a4cc224d593c1afde5494d18ff629393d74cc2eddb176669f234a4/pyarrow-23.0.1.tar.gz", hash = "sha256:b8c5873e33440b2bc2f4a79d2b47017a89c5a24116c055625e6f2ee50523f019", size = 1167336, upload-time = "2026-02-16T10:14:12.39Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9a/4b/4166bb5abbfe6f750fc60ad337c43ecf61340fa52ab386da6e8dbf9e63c4/pyarrow-23.0.1-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:f4b0dbfa124c0bb161f8b5ebb40f1a680b70279aa0c9901d44a2b5a20806039f", size = 34214575, upload-time = "2026-02-16T10:09:56.225Z" }, + { url = "https://files.pythonhosted.org/packages/e1/da/3f941e3734ac8088ea588b53e860baeddac8323ea40ce22e3d0baa865cc9/pyarrow-23.0.1-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:7707d2b6673f7de054e2e83d59f9e805939038eebe1763fe811ee8fa5c0cd1a7", size = 35832540, upload-time = "2026-02-16T10:10:03.428Z" }, + { url = "https://files.pythonhosted.org/packages/88/7c/3d841c366620e906d54430817531b877ba646310296df42ef697308c2705/pyarrow-23.0.1-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:86ff03fb9f1a320266e0de855dee4b17da6794c595d207f89bba40d16b5c78b9", size = 44470940, upload-time = "2026-02-16T10:10:10.704Z" }, + { url = "https://files.pythonhosted.org/packages/2c/a5/da83046273d990f256cb79796a190bbf7ec999269705ddc609403f8c6b06/pyarrow-23.0.1-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:813d99f31275919c383aab17f0f455a04f5a429c261cc411b1e9a8f5e4aaaa05", size = 47586063, upload-time = "2026-02-16T10:10:17.95Z" }, + { url = "https://files.pythonhosted.org/packages/5b/3c/b7d2ebcff47a514f47f9da1e74b7949138c58cfeb108cdd4ee62f43f0cf3/pyarrow-23.0.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:bf5842f960cddd2ef757d486041d57c96483efc295a8c4a0e20e704cbbf39c67", size = 48173045, upload-time = "2026-02-16T10:10:25.363Z" }, + { url = "https://files.pythonhosted.org/packages/43/b2/b40961262213beaba6acfc88698eb773dfce32ecdf34d19291db94c2bd73/pyarrow-23.0.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:564baf97c858ecc03ec01a41062e8f4698abc3e6e2acd79c01c2e97880a19730", size = 50621741, upload-time = "2026-02-16T10:10:33.477Z" }, + { url = "https://files.pythonhosted.org/packages/f6/70/1fdda42d65b28b078e93d75d371b2185a61da89dda4def8ba6ba41ebdeb4/pyarrow-23.0.1-cp312-cp312-win_amd64.whl", hash = "sha256:07deae7783782ac7250989a7b2ecde9b3c343a643f82e8a4df03d93b633006f0", size = 27620678, upload-time = "2026-02-16T10:10:39.31Z" }, + { url = "https://files.pythonhosted.org/packages/47/10/2cbe4c6f0fb83d2de37249567373d64327a5e4d8db72f486db42875b08f6/pyarrow-23.0.1-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:6b8fda694640b00e8af3c824f99f789e836720aa8c9379fb435d4c4953a756b8", size = 34210066, upload-time = "2026-02-16T10:10:45.487Z" }, + { url = "https://files.pythonhosted.org/packages/cb/4f/679fa7e84dadbaca7a65f7cdba8d6c83febbd93ca12fa4adf40ba3b6362b/pyarrow-23.0.1-cp313-cp313-macosx_12_0_x86_64.whl", hash = "sha256:8ff51b1addc469b9444b7c6f3548e19dc931b172ab234e995a60aea9f6e6025f", size = 35825526, upload-time = "2026-02-16T10:10:52.266Z" }, + { url = "https://files.pythonhosted.org/packages/f9/63/d2747d930882c9d661e9398eefc54f15696547b8983aaaf11d4a2e8b5426/pyarrow-23.0.1-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:71c5be5cbf1e1cb6169d2a0980850bccb558ddc9b747b6206435313c47c37677", size = 44473279, upload-time = "2026-02-16T10:11:01.557Z" }, + { url = "https://files.pythonhosted.org/packages/b3/93/10a48b5e238de6d562a411af6467e71e7aedbc9b87f8d3a35f1560ae30fb/pyarrow-23.0.1-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:9b6f4f17b43bc39d56fec96e53fe89d94bac3eb134137964371b45352d40d0c2", size = 47585798, upload-time = "2026-02-16T10:11:09.401Z" }, + { url = "https://files.pythonhosted.org/packages/5c/20/476943001c54ef078dbf9542280e22741219a184a0632862bca4feccd666/pyarrow-23.0.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:9fc13fc6c403d1337acab46a2c4346ca6c9dec5780c3c697cf8abfd5e19b6b37", size = 48179446, upload-time = "2026-02-16T10:11:17.781Z" }, + { url = "https://files.pythonhosted.org/packages/4b/b6/5dd0c47b335fcd8edba9bfab78ad961bd0fd55ebe53468cc393f45e0be60/pyarrow-23.0.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:5c16ed4f53247fa3ffb12a14d236de4213a4415d127fe9cebed33d51671113e2", size = 50623972, upload-time = "2026-02-16T10:11:26.185Z" }, + { url = "https://files.pythonhosted.org/packages/d5/09/a532297c9591a727d67760e2e756b83905dd89adb365a7f6e9c72578bcc1/pyarrow-23.0.1-cp313-cp313-win_amd64.whl", hash = "sha256:cecfb12ef629cf6be0b1887f9f86463b0dd3dc3195ae6224e74006be4736035a", size = 27540749, upload-time = "2026-02-16T10:12:23.297Z" }, + { url = "https://files.pythonhosted.org/packages/a5/8e/38749c4b1303e6ae76b3c80618f84861ae0c55dd3c2273842ea6f8258233/pyarrow-23.0.1-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:29f7f7419a0e30264ea261fdc0e5fe63ce5a6095003db2945d7cd78df391a7e1", size = 34471544, upload-time = "2026-02-16T10:11:32.535Z" }, + { url = "https://files.pythonhosted.org/packages/a3/73/f237b2bc8c669212f842bcfd842b04fc8d936bfc9d471630569132dc920d/pyarrow-23.0.1-cp313-cp313t-macosx_12_0_x86_64.whl", hash = "sha256:33d648dc25b51fd8055c19e4261e813dfc4d2427f068bcecc8b53d01b81b0500", size = 35949911, upload-time = "2026-02-16T10:11:39.813Z" }, + { url = "https://files.pythonhosted.org/packages/0c/86/b912195eee0903b5611bf596833def7d146ab2d301afeb4b722c57ffc966/pyarrow-23.0.1-cp313-cp313t-manylinux_2_28_aarch64.whl", hash = "sha256:cd395abf8f91c673dd3589cadc8cc1ee4e8674fa61b2e923c8dd215d9c7d1f41", size = 44520337, upload-time = "2026-02-16T10:11:47.764Z" }, + { url = "https://files.pythonhosted.org/packages/69/c2/f2a717fb824f62d0be952ea724b4f6f9372a17eed6f704b5c9526f12f2f1/pyarrow-23.0.1-cp313-cp313t-manylinux_2_28_x86_64.whl", hash = "sha256:00be9576d970c31defb5c32eb72ef585bf600ef6d0a82d5eccaae96639cf9d07", size = 47548944, upload-time = "2026-02-16T10:11:56.607Z" }, + { url = "https://files.pythonhosted.org/packages/84/a7/90007d476b9f0dc308e3bc57b832d004f848fd6c0da601375d20d92d1519/pyarrow-23.0.1-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:c2139549494445609f35a5cda4eb94e2c9e4d704ce60a095b342f82460c73a83", size = 48236269, upload-time = "2026-02-16T10:12:04.47Z" }, + { url = "https://files.pythonhosted.org/packages/b0/3f/b16fab3e77709856eb6ac328ce35f57a6d4a18462c7ca5186ef31b45e0e0/pyarrow-23.0.1-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:7044b442f184d84e2351e5084600f0d7343d6117aabcbc1ac78eb1ae11eb4125", size = 50604794, upload-time = "2026-02-16T10:12:11.797Z" }, + { url = "https://files.pythonhosted.org/packages/e9/a1/22df0620a9fac31d68397a75465c344e83c3dfe521f7612aea33e27ab6c0/pyarrow-23.0.1-cp313-cp313t-win_amd64.whl", hash = "sha256:a35581e856a2fafa12f3f54fce4331862b1cfb0bef5758347a858a4aa9d6bae8", size = 27660642, upload-time = "2026-02-16T10:12:17.746Z" }, + { url = "https://files.pythonhosted.org/packages/8d/1b/6da9a89583ce7b23ac611f183ae4843cd3a6cf54f079549b0e8c14031e73/pyarrow-23.0.1-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:5df1161da23636a70838099d4aaa65142777185cc0cdba4037a18cee7d8db9ca", size = 34238755, upload-time = "2026-02-16T10:12:32.819Z" }, + { url = "https://files.pythonhosted.org/packages/ae/b5/d58a241fbe324dbaeb8df07be6af8752c846192d78d2272e551098f74e88/pyarrow-23.0.1-cp314-cp314-macosx_12_0_x86_64.whl", hash = "sha256:fa8e51cb04b9f8c9c5ace6bab63af9a1f88d35c0d6cbf53e8c17c098552285e1", size = 35847826, upload-time = "2026-02-16T10:12:38.949Z" }, + { url = "https://files.pythonhosted.org/packages/54/a5/8cbc83f04aba433ca7b331b38f39e000efd9f0c7ce47128670e737542996/pyarrow-23.0.1-cp314-cp314-manylinux_2_28_aarch64.whl", hash = "sha256:0b95a3994f015be13c63148fef8832e8a23938128c185ee951c98908a696e0eb", size = 44536859, upload-time = "2026-02-16T10:12:45.467Z" }, + { url = "https://files.pythonhosted.org/packages/36/2e/c0f017c405fcdc252dbccafbe05e36b0d0eb1ea9a958f081e01c6972927f/pyarrow-23.0.1-cp314-cp314-manylinux_2_28_x86_64.whl", hash = "sha256:4982d71350b1a6e5cfe1af742c53dfb759b11ce14141870d05d9e540d13bc5d1", size = 47614443, upload-time = "2026-02-16T10:12:55.525Z" }, + { url = "https://files.pythonhosted.org/packages/af/6b/2314a78057912f5627afa13ba43809d9d653e6630859618b0fd81a4e0759/pyarrow-23.0.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:c250248f1fe266db627921c89b47b7c06fee0489ad95b04d50353537d74d6886", size = 48232991, upload-time = "2026-02-16T10:13:04.729Z" }, + { url = "https://files.pythonhosted.org/packages/40/f2/1bcb1d3be3460832ef3370d621142216e15a2c7c62602a4ea19ec240dd64/pyarrow-23.0.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5f4763b83c11c16e5f4c15601ba6dfa849e20723b46aa2617cb4bffe8768479f", size = 50645077, upload-time = "2026-02-16T10:13:14.147Z" }, + { url = "https://files.pythonhosted.org/packages/eb/3f/b1da7b61cd66566a4d4c8383d376c606d1c34a906c3f1cb35c479f59d1aa/pyarrow-23.0.1-cp314-cp314-win_amd64.whl", hash = "sha256:3a4c85ef66c134161987c17b147d6bffdca4566f9a4c1d81a0a01cdf08414ea5", size = 28234271, upload-time = "2026-02-16T10:14:09.397Z" }, + { url = "https://files.pythonhosted.org/packages/b5/78/07f67434e910a0f7323269be7bfbf58699bd0c1d080b18a1ab49ba943fe8/pyarrow-23.0.1-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:17cd28e906c18af486a499422740298c52d7c6795344ea5002a7720b4eadf16d", size = 34488692, upload-time = "2026-02-16T10:13:21.541Z" }, + { url = "https://files.pythonhosted.org/packages/50/76/34cf7ae93ece1f740a04910d9f7e80ba166b9b4ab9596a953e9e62b90fe1/pyarrow-23.0.1-cp314-cp314t-macosx_12_0_x86_64.whl", hash = "sha256:76e823d0e86b4fb5e1cf4a58d293036e678b5a4b03539be933d3b31f9406859f", size = 35964383, upload-time = "2026-02-16T10:13:28.63Z" }, + { url = "https://files.pythonhosted.org/packages/46/90/459b827238936d4244214be7c684e1b366a63f8c78c380807ae25ed92199/pyarrow-23.0.1-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:a62e1899e3078bf65943078b3ad2a6ddcacf2373bc06379aac61b1e548a75814", size = 44538119, upload-time = "2026-02-16T10:13:35.506Z" }, + { url = "https://files.pythonhosted.org/packages/28/a1/93a71ae5881e99d1f9de1d4554a87be37da11cd6b152239fb5bd924fdc64/pyarrow-23.0.1-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:df088e8f640c9fae3b1f495b3c64755c4e719091caf250f3a74d095ddf3c836d", size = 47571199, upload-time = "2026-02-16T10:13:42.504Z" }, + { url = "https://files.pythonhosted.org/packages/88/a3/d2c462d4ef313521eaf2eff04d204ac60775263f1fb08c374b543f79f610/pyarrow-23.0.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:46718a220d64677c93bc243af1d44b55998255427588e400677d7192671845c7", size = 48259435, upload-time = "2026-02-16T10:13:49.226Z" }, + { url = "https://files.pythonhosted.org/packages/cc/f1/11a544b8c3d38a759eb3fbb022039117fd633e9a7b19e4841cc3da091915/pyarrow-23.0.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:a09f3876e87f48bc2f13583ab551f0379e5dfb83210391e68ace404181a20690", size = 50629149, upload-time = "2026-02-16T10:13:57.238Z" }, + { url = "https://files.pythonhosted.org/packages/50/f2/c0e76a0b451ffdf0cf788932e182758eb7558953f4f27f1aff8e2518b653/pyarrow-23.0.1-cp314-cp314t-win_amd64.whl", hash = "sha256:527e8d899f14bd15b740cd5a54ad56b7f98044955373a17179d5956ddb93d9ce", size = 28365807, upload-time = "2026-02-16T10:14:03.892Z" }, +] + +[[package]] +name = "pydeck" +version = "0.9.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jinja2" }, + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f4/c9/f71032fca47ecc09d30904d9a610234b07139f89eabc2f054b141edcc30f/pydeck-0.9.3.tar.gz", hash = "sha256:695775cbfe51f5fdffbd9735ba469987fdc5efc96bc40a0ee4808170509c78b2", size = 5900912, upload-time = "2026-07-02T23:27:08.704Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6f/34/3998411437aff304a9ed4fa37a6fe1ef3132bcd2b5eac59851b80c86123c/pydeck-0.9.3-py2.py3-none-any.whl", hash = "sha256:d8a47c11c81fb12d51b1feb42427ff4f0e13cb599e48931021b2cba98b6849a6", size = 11428091, upload-time = "2026-07-02T23:27:06.399Z" }, +] + +[[package]] +name = "pygments" +version = "2.20.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/c3/b2/bc9c9196916376152d655522fdcebac55e66de6603a76a02bca1b6414f6c/pygments-2.20.0.tar.gz", hash = "sha256:6757cd03768053ff99f3039c1a36d6c0aa0b263438fcab17520b30a303a82b5f", size = 4955991, upload-time = "2026-03-29T13:29:33.898Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f4/7e/a72dd26f3b0f4f2bf1dd8923c85f7ceb43172af56d63c7383eb62b332364/pygments-2.20.0-py3-none-any.whl", hash = "sha256:81a9e26dd42fd28a23a2d169d86d7ac03b46e2f8b59ed4698fb4785f946d0176", size = 1231151, upload-time = "2026-03-29T13:29:30.038Z" }, +] + +[[package]] +name = "pytest" +version = "9.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "iniconfig" }, + { name = "packaging" }, + { name = "pluggy" }, + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e4/47/b9efed96c114afcfa3c9d3fe98a76a1d14c74a9e266d397cf6eb64be5e01/pytest-9.1.1.tar.gz", hash = "sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313", size = 1636369, upload-time = "2026-06-19T10:58:32.857Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" }, +] + +[[package]] +name = "pytest-cov" +version = "7.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "coverage" }, + { name = "pluggy" }, + { name = "pytest" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b1/51/a849f96e117386044471c8ec2bd6cfebacda285da9525c9106aeb28da671/pytest_cov-7.1.0.tar.gz", hash = "sha256:30674f2b5f6351aa09702a9c8c364f6a01c27aae0c1366ae8016160d1efc56b2", size = 55592, upload-time = "2026-03-21T20:11:16.284Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9d/7a/d968e294073affff457b041c2be9868a40c1c71f4a35fcc1e45e5493067b/pytest_cov-7.1.0-py3-none-any.whl", hash = "sha256:a0461110b7865f9a271aa1b51e516c9a95de9d696734a2f71e3e78f46e1d4678", size = 22876, upload-time = "2026-03-21T20:11:14.438Z" }, +] + +[[package]] +name = "python-dateutil" +version = "2.9.0.post0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "six" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" }, +] + +[[package]] +name = "python-multipart" +version = "0.0.32" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/5b/42/55c32bb9b12693c092ad250a0e82edb5b31ddeda6eb772de5f308b3804ad/python_multipart-0.0.32.tar.gz", hash = "sha256:be54b7f3fa167bb83e4fcd936b887b708f4e57fe75911c02aebf53efaf8d938e", size = 46881, upload-time = "2026-06-04T16:18:58.647Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e1/04/e8135ebd1ad02c56ec633277529b2602ff99ff634be76cdba5744cf554fd/python_multipart-0.0.32-py3-none-any.whl", hash = "sha256:ff6d3f776f16878c894e52e107296ffc890e913c611b1a4ec6c44e2821fe2e23", size = 30042, upload-time = "2026-06-04T16:18:57.319Z" }, +] + +[[package]] +name = "referencing" +version = "0.37.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "attrs" }, + { name = "rpds-py" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/22/f5/df4e9027acead3ecc63e50fe1e36aca1523e1719559c499951bb4b53188f/referencing-0.37.0.tar.gz", hash = "sha256:44aefc3142c5b842538163acb373e24cce6632bd54bdb01b21ad5863489f50d8", size = 78036, upload-time = "2025-10-13T15:30:48.871Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2c/58/ca301544e1fa93ed4f80d724bf5b194f6e4b945841c5bfd555878eea9fcb/referencing-0.37.0-py3-none-any.whl", hash = "sha256:381329a9f99628c9069361716891d34ad94af76e461dcb0335825aecc7692231", size = 26766, upload-time = "2025-10-13T15:30:47.625Z" }, +] + +[[package]] +name = "requests" +version = "2.34.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "charset-normalizer" }, + { name = "idna" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ac/c3/e2a2b89f2d3e2179abd6d00ebd70bff6273f37fb3e0cc209f48b39d00cbf/requests-2.34.2.tar.gz", hash = "sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed", size = 142856, upload-time = "2026-05-14T19:25:27.735Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075, upload-time = "2026-05-14T19:25:26.443Z" }, +] + +[[package]] +name = "rpds-py" +version = "2026.6.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/aa/2a/9618a122aeb2a169a28b03889a2995fe297588964333d4a7d67bdf46e147/rpds_py-2026.6.3.tar.gz", hash = "sha256:1cebd1337c242e4ec2293e541f712b2da849b29f48f0c293684b71c0632625d4", size = 64051, upload-time = "2026-06-30T07:17:53.009Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5c/be/2e8974163072e7bab7df1a5acd54c4498e75e35d6d18b864d3a9d5dadc92/rpds_py-2026.6.3-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:a0811d33247c3d6128a3001d763f2aa056bb3425204335400ac54f89eec3a0d0", size = 343691, upload-time = "2026-06-30T07:15:14.96Z" }, + { url = "https://files.pythonhosted.org/packages/a4/73/319dfa745dd668efe89309141ded489126461fcecd2b8f3a3cda185129b6/rpds_py-2026.6.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:538949e262e46caa31ac01bdb3c1e8f642622922cacbabbae6a8445d9dc33eaf", size = 338542, upload-time = "2026-06-30T07:15:16.267Z" }, + { url = "https://files.pythonhosted.org/packages/21/63/4239893be1c4d09b709b1a8f6be4188f0870084ff547f46606b8a75f1b03/rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:55927d532399c2c646100ff7feb48eaa940ad70f42cd68e1328f3ded9f81ca24", size = 368180, upload-time = "2026-06-30T07:15:17.62Z" }, + { url = "https://files.pythonhosted.org/packages/1c/ca/9c5de382225234ceb37b1844ebdb140db12b2a278bb9efe2fcd19f6c82ce/rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:f56f1695bc5c0871cbc33dc0130fcf503aab0c57dcc5a6700a4f49eba4f2652e", size = 375067, upload-time = "2026-06-30T07:15:18.952Z" }, + { url = "https://files.pythonhosted.org/packages/87/dc/863f69d1bf04ade34b7fe0d59b9fdf6f0135fe2d7cbca74f1d665589559d/rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:270b293dae9058fc9fcedab50f13cebf46fb8ed1d1d54e0521a9da5d6b211975", size = 490509, upload-time = "2026-06-30T07:15:20.434Z" }, + { url = "https://files.pythonhosted.org/packages/ce/ef/eac16a12048b45ec7c7fa94f2be3438a5f26bf9cc8580b18a1cfd609b7f6/rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:127565fead0a10943b282957bd5447804ff3160ad79f2ad2635e6d249e380680", size = 382754, upload-time = "2026-06-30T07:15:21.831Z" }, + { url = "https://files.pythonhosted.org/packages/04/8f/d2f3f532616be4d06c316ef119683e832bd3d41e112bf3a88f4151c95b17/rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ecabd69db66de867690f9797f2f8fa27ba501bbc24540cbdbdc649cd15888ba6", size = 366189, upload-time = "2026-06-30T07:15:23.371Z" }, + { url = "https://files.pythonhosted.org/packages/e3/29/41a7b0e98a4b44cd676ab7598419623373eb43b20be68c084935c1a8cf88/rpds_py-2026.6.3-cp312-cp312-manylinux_2_31_riscv64.whl", hash = "sha256:58eadac9cd119677b60e1cf8ac4052f35949d71b8a9e5556efccbe82533cf22a", size = 377750, upload-time = "2026-06-30T07:15:24.659Z" }, + { url = "https://files.pythonhosted.org/packages/2e/05/ecda0bec46f9a1565090bcdc941d023f6a25aff85fda28f89f8d19878152/rpds_py-2026.6.3-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:7491ee23305ac3eb59e492b6945881f5cd77a6f731061a3f25b77fd40f9e99a4", size = 395576, upload-time = "2026-06-30T07:15:25.987Z" }, + { url = "https://files.pythonhosted.org/packages/68/a8/6ed52f03ee6cb854ce78785cc9a9a672eb880e83fd7224d471f667d151f1/rpds_py-2026.6.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:2c99f7e8ccb3dd6e3e4bfeac657a7b208c9bac8075f4b078c02d7404c34107fa", size = 543807, upload-time = "2026-06-30T07:15:27.356Z" }, + { url = "https://files.pythonhosted.org/packages/8f/d6/156c0d3eea27ba09b92562ba2364ba124c0a061b199e17eac637cd25a5e2/rpds_py-2026.6.3-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:62698275682bf121181861295c9181e789030a2d516071f5b8f3c23c170cd0fc", size = 611187, upload-time = "2026-06-30T07:15:28.931Z" }, + { url = "https://files.pythonhosted.org/packages/f1/31/774212ed989c62f7f310220089f9b0a3fb8f40f5443d1727abd5d9f52bc9/rpds_py-2026.6.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a214c993455f99a89aaeadc9b21241900037adc9d97203e374d75513c5911822", size = 573030, upload-time = "2026-06-30T07:15:30.553Z" }, + { url = "https://files.pythonhosted.org/packages/c9/50/22f73127a41f1ce4f87fe39aadfb9a126345801c274aa93ae88456249327/rpds_py-2026.6.3-cp312-cp312-win32.whl", hash = "sha256:501f9f04a588d6a09179368c57071301445191767c64e4b52a6aa9871f1ef5ed", size = 202185, upload-time = "2026-06-30T07:15:32.027Z" }, + { url = "https://files.pythonhosted.org/packages/04/3a/f0ee4d4dde9d3b69dedf1b5f74e7a40017046d55052d173e418c6a94f960/rpds_py-2026.6.3-cp312-cp312-win_amd64.whl", hash = "sha256:2c958bf94822e9290a40aaf2a822d4bc5c88099093e3948ad6c571eca9272e5f", size = 220394, upload-time = "2026-06-30T07:15:33.359Z" }, + { url = "https://files.pythonhosted.org/packages/f3/83/3382fe37f809b59f02aac04dbc4e765b480b46ee0227ed516e3bdc4d3dfc/rpds_py-2026.6.3-cp312-cp312-win_arm64.whl", hash = "sha256:22bffe6042b9bcb0822bcd1955ec00e245daf17b4344e4ed8e9551b976b63e96", size = 215753, upload-time = "2026-06-30T07:15:34.778Z" }, + { url = "https://files.pythonhosted.org/packages/a4/9e/b818ee580026ec578138e961027a68820c40afeb1ec8f6819b54fb99e196/rpds_py-2026.6.3-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:3cfe765c1da0072636ca06628261e0ea05688e160d5c8a03e0217c3854037223", size = 343012, upload-time = "2026-06-30T07:15:36.005Z" }, + { url = "https://files.pythonhosted.org/packages/f3/6b/686d9dc4359a8f163cfbbf89ee0b4e586431de22fe8248edb63a8cf50d49/rpds_py-2026.6.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f4d78253f6996be4901669ad25319f842f740eccf4d58e3c7f3dd39e6dde1d8f", size = 338203, upload-time = "2026-06-30T07:15:37.462Z" }, + { url = "https://files.pythonhosted.org/packages/9e/9b/069aa329940f8207615e091f5eedbbd40e1e15eac68a0790fd05ccdf796c/rpds_py-2026.6.3-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:54f45a148e28767bf343d33a684693c70e451c6f4c0e9904709a723fafbdfc1f", size = 367984, upload-time = "2026-06-30T07:15:39.008Z" }, + { url = "https://files.pythonhosted.org/packages/14/db/34c203e4becff3703e4d3bc121842c00b8689197f398161203a880052f4e/rpds_py-2026.6.3-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:842e7b070435622248c7a2c44ae53fa1440e073cc3023bc919fed570884097a7", size = 374815, upload-time = "2026-06-30T07:15:40.253Z" }, + { url = "https://files.pythonhosted.org/packages/ee/7d/8071067d2cc453d916ad836e828c943f575e8a44612537759002a1e07381/rpds_py-2026.6.3-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8020133a74bd81b4572dd8e4be028a6b1ebcd70e6726edc3918008c08bee6ee6", size = 490545, upload-time = "2026-06-30T07:15:41.729Z" }, + { url = "https://files.pythonhosted.org/packages/a3/42/da06c5aa8f0484ff07f270787434204d9f4535e2f8c3b51ed402267e63c3/rpds_py-2026.6.3-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:cdc7e35386f3847df728fbcb5e887e2d79c19e2fa1eba9e51b6621d23e3243af", size = 382828, upload-time = "2026-06-30T07:15:43.327Z" }, + { url = "https://files.pythonhosted.org/packages/57/d7/fe978efc2ae50abe48eb7464668ea99f53c010c60aeebb7b35ad27f23661/rpds_py-2026.6.3-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:acac386b453c2516111b50985d60ce46e7fadb5ea71ae7b25f4c946935bf27cf", size = 365678, upload-time = "2026-06-30T07:15:44.992Z" }, + { url = "https://files.pythonhosted.org/packages/69/9d/1d8922e1990b2a6eb532b6ff53d3e73d2b3bbffc84116c75826bee73dfc6/rpds_py-2026.6.3-cp313-cp313-manylinux_2_31_riscv64.whl", hash = "sha256:425560c6fa0415f27261727bb20bd097568485e5eb0c121f1949417d1c516885", size = 377811, upload-time = "2026-06-30T07:15:46.523Z" }, + { url = "https://files.pythonhosted.org/packages/b1/3d/198dceafb4fb034a6a47347e1b0735d34e0bd4a50be4e898d408ee66cb14/rpds_py-2026.6.3-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:a550fb4950a06dde3beb4721f5ad4b25bf4513784665b0a8522c792e2bd822a4", size = 395382, upload-time = "2026-06-30T07:15:47.955Z" }, + { url = "https://files.pythonhosted.org/packages/1f/f1/13968e49655d40b6b19d8b9140296bbc6f1d86b3f0f6c346cf9f1adddf4b/rpds_py-2026.6.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:4f4bca01b63096f606e095734dd56e74e175f94cfbf24ff3d63281cec61f7bb7", size = 543832, upload-time = "2026-06-30T07:15:49.33Z" }, + { url = "https://files.pythonhosted.org/packages/ac/ab/289bcb1b90bd3e40a2900c561fa0e2087345ecbb094f0b870f2345142b7c/rpds_py-2026.6.3-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:ccffae9a092a00deb7efd545fe5e2c33c33b88e7c054337e9a74c179347d0b7d", size = 611011, upload-time = "2026-06-30T07:15:50.847Z" }, + { url = "https://files.pythonhosted.org/packages/1e/16/5043105e679436ccfbc8e5e0dd2d663ed18a8b8113515fd06a5e5d77c83e/rpds_py-2026.6.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:1cf01971c4f2c5553b772a542e4aaf191789cd331bc2cd4ff0e6e65ba49e1e97", size = 572431, upload-time = "2026-06-30T07:15:52.394Z" }, + { url = "https://files.pythonhosted.org/packages/85/ed/adab103321c0a6565d5ae1c2998349bc3ee175b82ccc5ae8fc04cc413075/rpds_py-2026.6.3-cp313-cp313-win32.whl", hash = "sha256:8c3d1e9c15b9d51ca0391e13da1a25a0a4df3c58a37c9dc368e0736cf7f69df0", size = 201710, upload-time = "2026-06-30T07:15:53.894Z" }, + { url = "https://files.pythonhosted.org/packages/7b/ed/a03b09668e74e5dabbf2e211f6468e1820c0552f7b0500082da31841bf7b/rpds_py-2026.6.3-cp313-cp313-win_amd64.whl", hash = "sha256:9250a9a0a6fd4648b3f868da8d91a4c52b5811a62df58e753d50ae4454a36f80", size = 219454, upload-time = "2026-06-30T07:15:55.25Z" }, + { url = "https://files.pythonhosted.org/packages/27/17/b8642c12930b71bc2b25831f6708ccf0f75abcd11883932ec9ce54ba3a78/rpds_py-2026.6.3-cp313-cp313-win_arm64.whl", hash = "sha256:900a67df3fd1660b035a4761c4ce73c382ea6b35f90f9863c36c6fd8bf8b09bb", size = 215063, upload-time = "2026-06-30T07:15:56.573Z" }, + { url = "https://files.pythonhosted.org/packages/b6/36/7fbe9dcdaf857fb3f63c2a2284b62492d95f5e8334e947e5fb6e7f68c9be/rpds_py-2026.6.3-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:931908d9fc855d8f74783377822be318edb6dcb19e47169dc038f9a1bf60b06e", size = 344510, upload-time = "2026-06-30T07:15:57.921Z" }, + { url = "https://files.pythonhosted.org/packages/ba/54/f785cc3d3f60839ca57a5af4927a9f347b07b2799c373fc20f7949f87c7e/rpds_py-2026.6.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:d7469697dce35be237db177d42e2a2ee26e6dcc5fc052078a6fefabd288c6edd", size = 339495, upload-time = "2026-06-30T07:15:59.238Z" }, + { url = "https://files.pythonhosted.org/packages/63/ef/d4cdaf309e6b095b43597103cf8c0b951d6cca2acce68c474f75ec12e0c7/rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bcfbcf66006befb9fd2aeaa9e01feaf881b4dc330a02ba07d2322b1c11be7b5d", size = 369454, upload-time = "2026-06-30T07:16:01.021Z" }, + { url = "https://files.pythonhosted.org/packages/96/4a/9559a68b7ee15db09d7981212e8c2e219d2a1d6d4faa0391d813c3496a36/rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:847927daf4cffbd4e90e42bc890069897101edd015f956cb8721b3473372edda", size = 374583, upload-time = "2026-06-30T07:16:02.287Z" }, + { url = "https://files.pythonhosted.org/packages/ef/75/8964aa7d2c6e8ac43eba8eb6e6b0fdda1f46d39f2fc3e6aa9f2cb17f485d/rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:aca6c1ef08a82bfe327cc156da694660f599923e2e6665b6d81c9c2d0ac9ffc8", size = 492919, upload-time = "2026-06-30T07:16:03.723Z" }, + { url = "https://files.pythonhosted.org/packages/8f/97/6908094ac804115e65aedfd90f1b5fee4eebebd3f6c4cfc5419939267565/rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ae50181a047c871561212bb97f7932a2d45fb53e947bd9b57ebad85b529cbc53", size = 383725, upload-time = "2026-06-30T07:16:05.305Z" }, + { url = "https://files.pythonhosted.org/packages/d1/9c/0d1fdc2e7aba23e290d603bc494e97bd205bae262ce33c6b32a69768ed5e/rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dc319e5a1de4b6913aac94bf6a2f9e847371e0a140a43dd4991db1a09bc2d504", size = 367255, upload-time = "2026-06-30T07:16:07.086Z" }, + { url = "https://files.pythonhosted.org/packages/c4/fe/f0209ca4a9ed074bc8acb44dfd0e81c3122e94c9689f5645b7973a866719/rpds_py-2026.6.3-cp314-cp314-manylinux_2_31_riscv64.whl", hash = "sha256:e4316bf32babbed84e691e352faf967ce2f0f024174a8643c37c94a1080374fc", size = 379060, upload-time = "2026-06-30T07:16:08.525Z" }, + { url = "https://files.pythonhosted.org/packages/c6/8d/f1cc54c616b9d8897de8738aac148d20afca93f68187475fe194d09a71b9/rpds_py-2026.6.3-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:8c6e5a2f750cc71c3e3b11d71661f21d6f9bc6cebc6564b1466417a1ec03ec77", size = 395960, upload-time = "2026-06-30T07:16:09.989Z" }, + { url = "https://files.pythonhosted.org/packages/fb/04/aafff00f73aeca2945f734f1d483c64ab8f472d0864ab02377fd8e89c3b2/rpds_py-2026.6.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:4470ce197d4090875cf6affbf1f853338387428df97c4fb7b7106317b8214698", size = 545356, upload-time = "2026-06-30T07:16:11.816Z" }, + { url = "https://files.pythonhosted.org/packages/fd/cc/e229663b9e4ddac5a4acbe9085dd80a71af2a5d356b8b39d6bff233f24b0/rpds_py-2026.6.3-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:ea964164cc9afa72d4d9b23cc28dafae93693c0a53e0b42acbff15b22c3f9ddd", size = 612319, upload-time = "2026-06-30T07:16:13.586Z" }, + { url = "https://files.pythonhosted.org/packages/e3/7a/8a0e6d3e6cd066af108b71b43122c3fe158dd9eb86acac626593a2582eb1/rpds_py-2026.6.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:639c8929aa0afe81be836b04de888460d6bed38b9c54cfc18da8f6bfabf5af5d", size = 573508, upload-time = "2026-06-30T07:16:15.23Z" }, + { url = "https://files.pythonhosted.org/packages/87/03/2a69ab618a789cf6cf85c86bb844c62d090e700ab1a2aa676b3741b6c516/rpds_py-2026.6.3-cp314-cp314-win32.whl", hash = "sha256:882076c00c0a608b131187055ddc5ae29f2e7eaf870d6168980420d58528a5c8", size = 202504, upload-time = "2026-06-30T07:16:16.893Z" }, + { url = "https://files.pythonhosted.org/packages/85/62/a3892ba945f4e24c78f352e5de3c7620d8479f73f211406a97263d13c7d2/rpds_py-2026.6.3-cp314-cp314-win_amd64.whl", hash = "sha256:0be972be84cfcaf46c8c6edf690ca0f154ac17babf1f6a955a51579b34ad2dc5", size = 220380, upload-time = "2026-06-30T07:16:18.108Z" }, + { url = "https://files.pythonhosted.org/packages/3d/e7/c2bd44dc831931815ad11ebb5f430b5a0a4d3caa9de837107876c30c3432/rpds_py-2026.6.3-cp314-cp314-win_arm64.whl", hash = "sha256:2a9c6f195058cb45335e8cc3802745c603d716eb96bc9625950c1aac71c0c703", size = 215976, upload-time = "2026-06-30T07:16:19.654Z" }, + { url = "https://files.pythonhosted.org/packages/79/9c/fff7b74bce9a091ec9a012a03f9ff5f69364eaf9451060dfc4486da2ffdd/rpds_py-2026.6.3-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:f90938e92afda60266da758ee7d363447f7f0138c9559f9e1811629580582d90", size = 346840, upload-time = "2026-06-30T07:16:21.268Z" }, + { url = "https://files.pythonhosted.org/packages/e9/44/77bcb1168b33704908295533d27f10eb811e9e3e193e8993dc99572211d3/rpds_py-2026.6.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:ec829541c45bca16e61c7ae50c20501f213605beb75d1aba91a6ee37fbbb56a4", size = 340282, upload-time = "2026-06-30T07:16:22.875Z" }, + { url = "https://files.pythonhosted.org/packages/87/3c/7a9081c7c9e645b39efe19e4ffbeccd80add246327cd9b888aecffd72317/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:afd70d95892096cdb26f15a00c45907b17817577aa8d1c76b2dcc2788391f9e9", size = 370403, upload-time = "2026-06-30T07:16:24.415Z" }, + { url = "https://files.pythonhosted.org/packages/f7/69/af47021eb7dad6ff3396cb001c08f0f3c4d06c20253f75be6421a59fe6b7/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:29dfa0533a5d4c94d4dfa1b694fcb56c9c63aad8330ffdd816fd225d0a7a162f", size = 376055, upload-time = "2026-06-30T07:16:26.111Z" }, + { url = "https://files.pythonhosted.org/packages/81/fc/a3bcf517084396a6dd258c592567a3c011ba4557f2fde23dceaf26e74f2e/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:af05d726809bff6b141be124d4c7ce998f9c9c7f30edb1f46c07aa103d540b41", size = 494419, upload-time = "2026-06-30T07:16:27.596Z" }, + { url = "https://files.pythonhosted.org/packages/c9/eb/13d529d1788135425c7bf207f8463458ca5d92e43f3f701365b83e9dffc1/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9826217f048f620d9a712672818bf231442c1b35d96b227a07eabd11b4bb6945", size = 384848, upload-time = "2026-06-30T07:16:29.183Z" }, + { url = "https://files.pythonhosted.org/packages/8e/f4/b7ac49f30013aba8f7b9566b1dd07e81de95e708c1374b7bacc5b9bc5c9c/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:536bceea4fa4acf7e1c61da2b5786304367c816c8895be71b8f537c480b0ea1f", size = 371369, upload-time = "2026-06-30T07:16:30.912Z" }, + { url = "https://files.pythonhosted.org/packages/31/86/6260bafa622f788b07ddec0e52d810305c8b9b0b8c27f58a2ab04bf62b4f/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:bc0011654b91cc4fb2ae701bec0a0ba1e552c0714247fa7af6c59e0ccfa3a4e1", size = 379673, upload-time = "2026-06-30T07:16:32.486Z" }, + { url = "https://files.pythonhosted.org/packages/19/c3/03f1ee79a047b48daeca157c89a18509cde22b6b951d642b9b0af1be660a/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:539d75de9e0d536c84ff18dfeb805398e58227001ce09231a26a08b9aed1ee0e", size = 397500, upload-time = "2026-06-30T07:16:34.471Z" }, + { url = "https://files.pythonhosted.org/packages/f0/95/8ed0cd8c377dca12aea498f119fe639fc474d1461545c39d2b5872eb1c0f/rpds_py-2026.6.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:166cf54d9f44fc6ceb53c7860258dde44a81406646de79f8ed3234fca3b6e538", size = 545978, upload-time = "2026-06-30T07:16:36.45Z" }, + { url = "https://files.pythonhosted.org/packages/d3/f2/0eb57f0eaa83f8fc152a7e03de968ab77e1f00732bebc892b190c6eebde7/rpds_py-2026.6.3-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:d34c20167764fbcf927194d532dd7e0c56772f0a5f943fa5ef9e9afbba8fb9db", size = 613350, upload-time = "2026-06-30T07:16:38.213Z" }, + { url = "https://files.pythonhosted.org/packages/5b/de/e0674bdbc3ef7634989b3f854c3f34bc1f587d36e5bfdc5c378d57034619/rpds_py-2026.6.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:ea7bb13b7c9a29791f87a0387ba7d3ad3a6d783d827e4d3f27b40a0ff44495e2", size = 576486, upload-time = "2026-06-30T07:16:39.797Z" }, + { url = "https://files.pythonhosted.org/packages/f2/f6/21101359743cd136ada781e8210a85769578422ba460672eea0e29739200/rpds_py-2026.6.3-cp314-cp314t-win32.whl", hash = "sha256:6de4744d05bd1aa1be4ed7ea1189e3979196808008113bbbf899a460966b925e", size = 201068, upload-time = "2026-06-30T07:16:41.316Z" }, + { url = "https://files.pythonhosted.org/packages/a6/b2/9574d4d44f7760c2aa32d92a0a4f41698e33f5b204a0bf5c9758f52c79d5/rpds_py-2026.6.3-cp314-cp314t-win_amd64.whl", hash = "sha256:c7b9a2f8f4d8e90af72571d3d495deebdd7e3c75451f5b41719aee166e940fc2", size = 220600, upload-time = "2026-06-30T07:16:43.091Z" }, + { url = "https://files.pythonhosted.org/packages/08/ae/f23a2697e6ee6340a578b0f136be6483657bef0c6f9497b752bb5c0964bb/rpds_py-2026.6.3-cp315-cp315-macosx_10_12_x86_64.whl", hash = "sha256:e059c5dde6452b44424bd1834557556c226b57781dee1227af23518459722b13", size = 344726, upload-time = "2026-06-30T07:16:44.5Z" }, + { url = "https://files.pythonhosted.org/packages/c3/63/e7b3a1a5358dd32c930a1062d8e15b67fd6e8922e81df9e91706d66ee5c8/rpds_py-2026.6.3-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:2f7c26fbc5acd2522b95d4177fe4710ffd8e9b20529e703ffbf8db4d93903f05", size = 339587, upload-time = "2026-06-30T07:16:46.255Z" }, + { url = "https://files.pythonhosted.org/packages/ec/64/10a85681916ca55fffb91b0a211f84e34297c109243484dd6394660a8a7c/rpds_py-2026.6.3-cp315-cp315-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a3086b538543802f84c843911242db20447de00d8752dd0efc936dbcf02218ba", size = 369585, upload-time = "2026-06-30T07:16:48.101Z" }, + { url = "https://files.pythonhosted.org/packages/76/c2/baf95c7c38823e12ba34407c5f5767a89e5cf2233895e56f608167ae9493/rpds_py-2026.6.3-cp315-cp315-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:8f2e5c5ee828d42cb11760761c0af6507927bec42d0ad5458f97c9203b054617", size = 375479, upload-time = "2026-06-30T07:16:49.93Z" }, + { url = "https://files.pythonhosted.org/packages/6a/94/0aad06c72d65101e11d33528d438cda99a39ce0da99466e156158f2541d3/rpds_py-2026.6.3-cp315-cp315-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ed0c1e5d10cdc7135537988c74a0188da68e2f3c30813ba3744ab1e42e0480f9", size = 492418, upload-time = "2026-06-30T07:16:51.641Z" }, + { url = "https://files.pythonhosted.org/packages/b5/17/de3f5a479a1f056535d7489819639d8cd591ea6281d700390b43b1abd745/rpds_py-2026.6.3-cp315-cp315-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8c2642a7603ec0b16ed77da4555db3b4b472341904873788327c0b0d7b95f1bb", size = 384123, upload-time = "2026-06-30T07:16:53.622Z" }, + { url = "https://files.pythonhosted.org/packages/46/7d/bf09bd1b145bb2671c03e1e6d1ab8651858d90d8c7dfeadd85a37a934fd8/rpds_py-2026.6.3-cp315-cp315-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8e4320744c1ffdd95a603def63344bfab2d33edeab301c5007e7de9f9f5b3885", size = 367351, upload-time = "2026-06-30T07:16:55.241Z" }, + { url = "https://files.pythonhosted.org/packages/a3/ea/1bb734f314b8be319149ddee80b18bd41372bdcfbdf88d28131c0cd37719/rpds_py-2026.6.3-cp315-cp315-manylinux_2_31_riscv64.whl", hash = "sha256:a9f4645593036b81bbdb36b9c8e0ea0d1c3fee968c4d59db0344c14087ef143a", size = 378827, upload-time = "2026-06-30T07:16:56.841Z" }, + { url = "https://files.pythonhosted.org/packages/4b/93/d9611e5b25e26df9a3649813ed66193ace9347a7c7fc4ab7cf70e94851c0/rpds_py-2026.6.3-cp315-cp315-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:e55d236be29255554da47abe5c577637db7c24a02b8b46f0ca9524c855801868", size = 395966, upload-time = "2026-06-30T07:16:58.557Z" }, + { url = "https://files.pythonhosted.org/packages/c3/cb/99d77e16e5534ae1d90629bbe419ba6ee170833a6a85e3aa1cc41726fbbc/rpds_py-2026.6.3-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:24e9c5386e16669b674a69c156c8eeefcb578f3b3397b713b08e6d60f3c7b187", size = 545680, upload-time = "2026-06-30T07:17:00.164Z" }, + { url = "https://files.pythonhosted.org/packages/59/15/11a29755f790cef7a2f755e8e14f4f0c33f39489e1893a632a2eee59672b/rpds_py-2026.6.3-cp315-cp315-musllinux_1_2_i686.whl", hash = "sha256:c60924535c75f1566b6eb75b5c31a48a43fef04fa2d0d201acbad8a9969c6107", size = 611853, upload-time = "2026-06-30T07:17:01.962Z" }, + { url = "https://files.pythonhosted.org/packages/68/86/0c27547e21644da938fb530f7e1a8148dd24d02db07e7a5f2567a17ce710/rpds_py-2026.6.3-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:38a2fea2787428f811719ceb9114cb78964a3138838320c29ac39526c79c16ba", size = 573715, upload-time = "2026-06-30T07:17:03.693Z" }, + { url = "https://files.pythonhosted.org/packages/29/71/4d8fcf700931815594bce892255bbd973b94efaf0fc1932b0590df18d886/rpds_py-2026.6.3-cp315-cp315-win32.whl", hash = "sha256:d483fe17f01ad64b7bf7cc38fcefff1ca9fb83f8c2b2542b68f97ffe0611b369", size = 202864, upload-time = "2026-06-30T07:17:05.746Z" }, + { url = "https://files.pythonhosted.org/packages/eb/62/b577562de0edbb55b2be85ce5fd09c33e386b9b13eee09833af4240fd5c4/rpds_py-2026.6.3-cp315-cp315-win_amd64.whl", hash = "sha256:67e3a721ffc5d8d2210d3671872298c4a84e4b8035cfe42ffd7cde35d772b146", size = 220430, upload-time = "2026-06-30T07:17:07.471Z" }, + { url = "https://files.pythonhosted.org/packages/c8/95/d6d0b2509825141eef60669a5739eec88dbc6a48053d6c92993a5704defe/rpds_py-2026.6.3-cp315-cp315-win_arm64.whl", hash = "sha256:6e84adbcf4bf841aed8116a8264b9f50b4cb3e7bd89b516122e616ac56ca269e", size = 215877, upload-time = "2026-06-30T07:17:09.008Z" }, + { url = "https://files.pythonhosted.org/packages/b7/bf/f3ea278f0afd615c1d0f19cb69043a41526e2bb600c2b536eb192218eb27/rpds_py-2026.6.3-cp315-cp315t-macosx_10_12_x86_64.whl", hash = "sha256:ae6dd8f10bd17aad820876d24caec9efdafd80a318d16c0a48edb5e136902c6b", size = 346933, upload-time = "2026-06-30T07:17:10.762Z" }, + { url = "https://files.pythonhosted.org/packages/9d/29/9907bdf1c5346763cf10b7f6852aad86652168c259def904cbe0082c5864/rpds_py-2026.6.3-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:bdbd97738551fca3917c1bd7188bec1920bb520104f28e7e1007f9ceb17b7690", size = 340274, upload-time = "2026-06-30T07:17:12.266Z" }, + { url = "https://files.pythonhosted.org/packages/6f/2c/8e03767b5778ef25cebf74a7a91a2c3806f8eced4c92cb7406bbe060756d/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8b95977e7211527ab0ba576e286d023389fbeeb32a6b7b771665d333c60e5342", size = 370763, upload-time = "2026-06-30T07:17:14.107Z" }, + { url = "https://files.pythonhosted.org/packages/2e/e1/df2a7e1ba2efd796af26194250b8d42c821b46592311595162af9ef0528d/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:d15fde0e6fb0d88a60d221204873743e5d9f0b7d29165e62cd86d0413ad74ba6", size = 376467, upload-time = "2026-06-30T07:17:15.76Z" }, + { url = "https://files.pythonhosted.org/packages/6b/de/8a0814d1946af29cb068fb259aa8622f856df1d0bab58429448726b537f5/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a136d453475ac0fcbda502ef1e6504bd28d6d904700915d278deeab0d00fe140", size = 496689, upload-time = "2026-06-30T07:17:17.308Z" }, + { url = "https://files.pythonhosted.org/packages/df/f3/f19e0c852ba13694f5a79f3b719331051573cb5693feacf8a88ffffc3a71/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f826877d462181e5eb1c26a0026b8d0cab05d99844ecb6d8bf3627a2ca0c0442", size = 385340, upload-time = "2026-06-30T07:17:18.928Z" }, + { url = "https://files.pythonhosted.org/packages/e2/ae/7ec3a9d2d4351f99e37bcb06b6b6f954512646bfdbf9742e1de727865daf/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:79486287de1730dbaff3dbd124d0ca4d2ef7f9d29bf2544f1f93c09b5bcbbd12", size = 372179, upload-time = "2026-06-30T07:17:20.539Z" }, + { url = "https://files.pythonhosted.org/packages/d3/ac/9cee911dff2aaa9a5a8354f6610bf2e6a616de9197c5fff4f54f82585f1e/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_31_riscv64.whl", hash = "sha256:808345f53cb952433ca2816f1604ff3515608a81784954f38d4452acfe8e61d5", size = 379993, upload-time = "2026-06-30T07:17:22.212Z" }, + { url = "https://files.pythonhosted.org/packages/83/6b/7c2a07ba88d1e9a936612f7a5d067467ed03d971d5a06f7d309dff044a7e/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:1967debc37f64f2c4dc90a7f563aec558b471966e12adcac4e1c4240496b6ebf", size = 398909, upload-time = "2026-06-30T07:17:23.66Z" }, + { url = "https://files.pythonhosted.org/packages/97/0b/776ffcb66783637b0031f6d58d6fb55913c8b5abf00aeecd46bf933fb477/rpds_py-2026.6.3-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:f0840b5b17057f7fd918b76183a4b5a0635f43e14eb2ce60dce1d4ee4707ea00", size = 546584, upload-time = "2026-06-30T07:17:25.264Z" }, + { url = "https://files.pythonhosted.org/packages/55/33/ba3bc04d7092bd553c9b2b195624992d2cc4f3de1f380b7b93cbee67bd79/rpds_py-2026.6.3-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:faa679d19a6696fd54259ad321251ad77a13e70e03dd834daa762a44fb6196ef", size = 614357, upload-time = "2026-06-30T07:17:26.888Z" }, + { url = "https://files.pythonhosted.org/packages/8b/71/14edf065f04630b1a8472f7653cad03f6c478bcf95ea0e6aed55451e33ea/rpds_py-2026.6.3-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:23a439f31ccbeff1574e24889128821d1f7917470e830cf6544dced1c662262a", size = 576533, upload-time = "2026-06-30T07:17:28.546Z" }, + { url = "https://files.pythonhosted.org/packages/ba/76/65002b08596c389105720a8c0d22298b8dc25a4baf89b2ce431343c8b1de/rpds_py-2026.6.3-cp315-cp315t-win32.whl", hash = "sha256:913ca42ccad3f8cc6e292b587ae8ae49c8c823e5dce51a736252fc7c7cdfa577", size = 201204, upload-time = "2026-06-30T07:17:30.193Z" }, + { url = "https://files.pythonhosted.org/packages/8c/97/d855d6b3c322d1f27e26f5241c42016b56cf01377ea8ed348285f54652f0/rpds_py-2026.6.3-cp315-cp315t-win_amd64.whl", hash = "sha256:ae3d4fe8c0b9213624fdce7279d70e3b148b682ca20719ebd193a23ebfa47324", size = 220719, upload-time = "2026-06-30T07:17:31.788Z" }, +] + +[[package]] +name = "ruff" +version = "0.16.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/73/e1/4508a569211b35599016e84ba65c1a992b7a4004b4b6c4bea02a851cba1b/ruff-0.16.2.tar.gz", hash = "sha256:c3d7828d12e8927a6fc65fe38e2c2541b9e762d360a1786d752cb1b8883b3c9c", size = 4885811, upload-time = "2026-08-07T13:31:01.432Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/14/57/db19951540f98859c956b50bdb4d31089b4d91e9f15e2968e7d5193806d5/ruff-0.16.2-py3-none-linux_armv6l.whl", hash = "sha256:3c8de4cf2181f01d57946d87d777aa52916976fc09942aed89938fab5e013318", size = 10847925, upload-time = "2026-08-07T13:30:14.468Z" }, + { url = "https://files.pythonhosted.org/packages/13/5a/995fe85a8470d3e391ac0f7fa8054bb454eaf33ee138196d6172ed1079c0/ruff-0.16.2-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:9a48cc05c6fbc811ca81b5d7ba95375affea6582d1b8024e455e41afbbf55344", size = 11072662, upload-time = "2026-08-07T13:30:18.143Z" }, + { url = "https://files.pythonhosted.org/packages/32/53/370d767c61c71a971a4ace36703a7ecd8c393956349a7325d7fab2b56827/ruff-0.16.2-py3-none-macosx_11_0_arm64.whl", hash = "sha256:a2c0d14fcbb26c91f0f867a6dc9bd71bbc30b1b6151829c884f23faeab2e5700", size = 10566771, upload-time = "2026-08-07T13:30:20.899Z" }, + { url = "https://files.pythonhosted.org/packages/85/d6/9d96948caf5a632be62d62202d5ec914d6856f204fd79eb036e5915e79ea/ruff-0.16.2-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:335c621622c4650330be50842561c6586ac6971bb8ab5407fe34dcc9efb16bbe", size = 10975825, upload-time = "2026-08-07T13:30:23.517Z" }, + { url = "https://files.pythonhosted.org/packages/3b/92/ea87129b3414acb0b5770563779c51804d37ac67675c7ba35447ddb14773/ruff-0.16.2-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:20e66910f2c37cc753f9ef6580c914a621b80c4fa3549d3e3521e29d0f5bfc3f", size = 10649437, upload-time = "2026-08-07T13:30:26.097Z" }, + { url = "https://files.pythonhosted.org/packages/ac/43/f8f291dcd4af5bb7872b74fdfa41a7cd7c856ca1d4069670971cf1b9f5cb/ruff-0.16.2-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c7e36fbfba65510548156902bcf1350a979a958ce0347ce0f90d73894036b39f", size = 11446761, upload-time = "2026-08-07T13:30:28.752Z" }, + { url = "https://files.pythonhosted.org/packages/71/4a/ef991fb2fcf516ab71f0808adcdd8da5e18c8cde447f4ceaf5f47a5132a5/ruff-0.16.2-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f0eab35f80df8f134aae5d1630e751901321d317cc8e50dc39e36fa3ed34cd12", size = 12336364, upload-time = "2026-08-07T13:30:31.468Z" }, + { url = "https://files.pythonhosted.org/packages/f3/24/f615e74f307e6ca0e56a482872477b856c70d530aa356abfb6dfe5ca8a80/ruff-0.16.2-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:40ea8c0594feb894e89c8c61ab9c103d38b0ea72dfde6c594107147ca31b1140", size = 11630720, upload-time = "2026-08-07T13:30:34.426Z" }, + { url = "https://files.pythonhosted.org/packages/c5/d3/8ef50149e8412a77f7ab409efdef0e2b23803707a3863da4fc64cb23d459/ruff-0.16.2-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ab3d62dde0b19facdd632008cc4827fc28ada7736c6bd35ab6f1050f0bfed53f", size = 11466130, upload-time = "2026-08-07T13:30:36.958Z" }, + { url = "https://files.pythonhosted.org/packages/dd/a7/a19334985c4dea8c381981fa252cd854c7ee52dc4b1686dc16f4a911c702/ruff-0.16.2-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:e43e1f5b8388da9eca1b9e88328d47a5cec794633ccf6f7484ac2dd15eee92c0", size = 11523634, upload-time = "2026-08-07T13:30:39.822Z" }, + { url = "https://files.pythonhosted.org/packages/6e/6c/96d192b0e742412ceda08c0a50f9669b253dde9fd6a60ea1a10c9fa79a63/ruff-0.16.2-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:c24788a980581e1d7ea3a0cbe4344c4fbeb0a6a9b1f4713aa46bb104f8294690", size = 10949807, upload-time = "2026-08-07T13:30:42.745Z" }, + { url = "https://files.pythonhosted.org/packages/fa/51/e26599ceca11e79ee255c7df515995561edf87e9ca1893284e44d98f5a86/ruff-0.16.2-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:81806b08329130005dd4a8a8394a0c9da8c6f4cafb16ba438d2a2ee6a18bedf1", size = 10646891, upload-time = "2026-08-07T13:30:45.522Z" }, + { url = "https://files.pythonhosted.org/packages/68/01/800c4b1f97bc8d7c6029e06b1f20473a3cf1e13c4933d8f3342add83fc55/ruff-0.16.2-py3-none-musllinux_1_2_i686.whl", hash = "sha256:4ce4e02bad779bef557f541a1b31f20d6abeae1cc05ed1b1ac019d4ffd1044c8", size = 11162063, upload-time = "2026-08-07T13:30:48.131Z" }, + { url = "https://files.pythonhosted.org/packages/e4/d0/1477ea50fc5a0d4b0b71d1d63d50770bdd794d90b43e37a7618e63ec9894/ruff-0.16.2-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:e0422abdf70070255fc4073ce9dfc814cc03db577013761ddd09bc1e4a9a4fbd", size = 11556038, upload-time = "2026-08-07T13:30:50.686Z" }, + { url = "https://files.pythonhosted.org/packages/b8/76/a7776f32048d991e16d4fa8ff91790b877342d3596cc3ed04acdbf1aaedc/ruff-0.16.2-py3-none-win32.whl", hash = "sha256:bf3a63d78fb39f4bf5ac8ae52051c5520505301abe19ba4e204c453b3f09bb0b", size = 10872850, upload-time = "2026-08-07T13:30:53.471Z" }, + { url = "https://files.pythonhosted.org/packages/00/0d/929c800d920e61397d82a01b60bffc68da3052c17d31de59efaad2e4ed75/ruff-0.16.2-py3-none-win_amd64.whl", hash = "sha256:bcabe2f6d0fc7819f1431793005af4e4de7371927d037345bf941252b195b9fa", size = 12023338, upload-time = "2026-08-07T13:30:56.193Z" }, + { url = "https://files.pythonhosted.org/packages/5b/6c/93e26c22c5f78ff87363e07da49c84955affbeb1098bd1936bf3b3f293bf/ruff-0.16.2-py3-none-win_arm64.whl", hash = "sha256:d614e95cedf38a2053fd351c55b103ba30d017d61688fdbfd40ee0412852a99f", size = 11374065, upload-time = "2026-08-07T13:30:58.775Z" }, +] + +[[package]] +name = "scikit-learn" +version = "1.9.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "joblib" }, + { name = "narwhals" }, + { name = "numpy" }, + { name = "scipy" }, + { name = "threadpoolctl" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/fa/6f/37092bdb25f712817231799fc5674d8e704066a8a70c1d2d40517e18b4ab/scikit_learn-1.9.0.tar.gz", hash = "sha256:8833266989d3a5110178a9fae30783675460724d0e1efb13b14901d2c660c557", size = 7750767, upload-time = "2026-06-02T11:54:32.706Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ac/20/75f915ff375d6249e6550ac740fdbbd66159a068fd3af1400ff62036b07a/scikit_learn-1.9.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:2bd41b0d201bc81575531b96b713d3eb5e5f50fb0b82101ff0f92294fdc236ac", size = 8741122, upload-time = "2026-06-02T11:53:24.08Z" }, + { url = "https://files.pythonhosted.org/packages/cc/d5/2b5148f2279196775e1db2aeb85d14b70ac80e7e32b3b28e7ebeafb0901d/scikit_learn-1.9.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:5be45aa4a42a68a533913a6ed736cf309de2226411c79ef8d609a5456f1939b1", size = 8261512, upload-time = "2026-06-02T11:53:27.183Z" }, + { url = "https://files.pythonhosted.org/packages/a0/ee/5adbc77656b71f9456a2f5a7a9fdb4bcf9207a6b962889f1c2f9323afa4e/scikit_learn-1.9.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5e50ed4da51974e86e940690e9a3d82e729b62b5a49f7c9bac534d515d39d86f", size = 8837603, upload-time = "2026-06-02T11:53:30.328Z" }, + { url = "https://files.pythonhosted.org/packages/6c/c2/63fdda36c56437eeb44aaf9493c8bcd62ce230ab1598924fc626ffbfa943/scikit_learn-1.9.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:056c92bb67ad4c28463c2f2653d9701449201e7e7a9e94e321be0f71c4fef2b8", size = 9132097, upload-time = "2026-06-02T11:53:33.456Z" }, + { url = "https://files.pythonhosted.org/packages/83/a4/c8e67227c680e2259c8864ae72ff48b06e16a6f51253a22167aa02a8aa4e/scikit_learn-1.9.0-cp312-cp312-win_amd64.whl", hash = "sha256:4306775fad04cc4b472a1b15af1ae9cede1540fbfcc17fbce3767cd8dc7ae283", size = 8211173, upload-time = "2026-06-02T11:53:36.602Z" }, + { url = "https://files.pythonhosted.org/packages/cf/fd/3c0863792e98e67e9184aa4029288a175935eb65443afcd30d4f143450cf/scikit_learn-1.9.0-cp312-cp312-win_arm64.whl", hash = "sha256:26e22435f63bcdcf396b574273f29f13dd531f5ea035801f5be10ba1540a4e60", size = 7867451, upload-time = "2026-06-02T11:53:39.075Z" }, + { url = "https://files.pythonhosted.org/packages/3c/01/cf3310626b6d48d3e9be69a1223f9180360b5e6edb045f50fade723ce494/scikit_learn-1.9.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:80746d63bd4b6eaca54d36fe5feaf4d28bb38dc6f9470f81c7cad7c40155f119", size = 8705188, upload-time = "2026-06-02T11:53:41.964Z" }, + { url = "https://files.pythonhosted.org/packages/3e/04/5acd7ae280c5f93b6ac5ef6cdec14eef4c8d1cd91d85b3292989c94d96b1/scikit_learn-1.9.0-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:5b934c45c252844a91d69fda3a34cff5e7307e1db10d77cb10a3980312c74713", size = 8228299, upload-time = "2026-06-02T11:53:44.817Z" }, + { url = "https://files.pythonhosted.org/packages/0c/39/ffe829a5b8ecb40a518724a997794657fdc354ada5e8fe8e64d998c0bac9/scikit_learn-1.9.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:38c3dcb9a1ffb85505ec53d54c7b4aea0cff70050425a7760c2af661ac85df05", size = 8789690, upload-time = "2026-06-02T11:53:47.461Z" }, + { url = "https://files.pythonhosted.org/packages/1f/88/8dab5de10c638c083772a6be83a3d8106ced492f74a928c8693638e5bb50/scikit_learn-1.9.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:da76d09304a4706db7cc1e3ebaa3b6b98a67365cc11d2996c4f1e58ba47df714", size = 9087723, upload-time = "2026-06-02T11:53:50.702Z" }, + { url = "https://files.pythonhosted.org/packages/20/3f/7917ca72464038f6240ec70c29f94862d08a34a74291ae4d4ec5eb8186a0/scikit_learn-1.9.0-cp313-cp313-win_amd64.whl", hash = "sha256:5808d98f15c6bf6d9d96d2348c1997392a5888ce7097e664105f930c4bca1277", size = 8184330, upload-time = "2026-06-02T11:53:53.396Z" }, + { url = "https://files.pythonhosted.org/packages/78/c7/15739eb2f61fda3c54639e9942414e5a19ad8a8d1f5a3266afad7cb7df80/scikit_learn-1.9.0-cp313-cp313-win_arm64.whl", hash = "sha256:d77f54c017633791bc0225a43e2f8d03745fdcfe4880268fcc4df15f505dec2e", size = 7840653, upload-time = "2026-06-02T11:53:56.035Z" }, + { url = "https://files.pythonhosted.org/packages/f4/7d/c9a35cf59b20a86fec24d306f1547b78dec194b08d367ce2a3e4854169d9/scikit_learn-1.9.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:9656acd4e93f74e0b66c8a36c88830a99252dfa900044d36bc2212ae89a47162", size = 8713289, upload-time = "2026-06-02T11:53:58.788Z" }, + { url = "https://files.pythonhosted.org/packages/3c/a7/552a7821597c632b907f7bfe8f36f9f572777af8ef8a48353041cf8e091a/scikit_learn-1.9.0-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:24360002ae845e7866522b0a5bbf690802e7bc388cac8663502e78aa98598aa2", size = 8245141, upload-time = "2026-06-02T11:54:01.694Z" }, + { url = "https://files.pythonhosted.org/packages/7d/79/f4a0c4fe9711154cddabf913471153af79056382ddc612cfe5ee0ff4b72e/scikit_learn-1.9.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5162ad10a418c8a282dde04c9aa06965de3e9a65f33c1440c0ae69bb1a09d913", size = 8847671, upload-time = "2026-06-02T11:54:04.448Z" }, + { url = "https://files.pythonhosted.org/packages/f0/af/4d72d9e475ac83719160c662619e4bf7b95c19507cd582e7d0167a3c3dae/scikit_learn-1.9.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1fea2cc5677ab49d6f5bade978c866da44957b712d92e9635e8b4f723013c3cb", size = 9118104, upload-time = "2026-06-02T11:54:07.205Z" }, + { url = "https://files.pythonhosted.org/packages/a2/d5/6a58eea2cb9abbb9b3f2bb8b2cfb3243d1152d69f442d256c7af71304769/scikit_learn-1.9.0-cp314-cp314-win_amd64.whl", hash = "sha256:64fa347efc1c839c487433e40c5144d38c336e8a2b59c81aa8660373945c2673", size = 8290674, upload-time = "2026-06-02T11:54:10.087Z" }, + { url = "https://files.pythonhosted.org/packages/65/5b/d4c879cf358f1187141cf90ced473f087183489090244f50c124a2ee478b/scikit_learn-1.9.0-cp314-cp314-win_arm64.whl", hash = "sha256:1b944b6db288f6b926e3650026ddafb988929de95d11fc2cc5fa117773c9ba42", size = 7978807, upload-time = "2026-06-02T11:54:12.769Z" }, + { url = "https://files.pythonhosted.org/packages/8a/43/bfae3121ec67ae09150d453c442c7c1cc166e9aefe056e6ab3b7728a5cfc/scikit_learn-1.9.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:4ccacf04ca5f4b492158a5f28afe0ace43f81b2571e4b9a66d34848b46128949", size = 9031941, upload-time = "2026-06-02T11:54:15.436Z" }, + { url = "https://files.pythonhosted.org/packages/75/b0/20a4546eb17f3b25d3c66df15810411c14ed5065bcfab50b53c96fb627b2/scikit_learn-1.9.0-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:ee1a8db2c18c08e34c7412d4b10be1cac214cd4ea7dc9715a6a327eb49a37c96", size = 8613528, upload-time = "2026-06-02T11:54:18.842Z" }, + { url = "https://files.pythonhosted.org/packages/18/3c/e440e039bb82cd19004edaaad00acbde0fb9b461083c3ecf37941c557312/scikit_learn-1.9.0-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:147e9329ef0e39f75d4cffa02b2aa48d827832684926cd5210d9a2cb5c57246b", size = 8855050, upload-time = "2026-06-02T11:54:21.699Z" }, + { url = "https://files.pythonhosted.org/packages/43/26/b341b8dab5998da6270a3a42c2152c578501354d36f944b5856757035ef8/scikit_learn-1.9.0-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5bad8f8b9950321b54c965fdcbac6c6c55e79e16646b49977bcf3668d3870a1a", size = 9097190, upload-time = "2026-06-02T11:54:24.454Z" }, + { url = "https://files.pythonhosted.org/packages/fb/de/b650b4d69b84468cfa2e28a3ff7b8103743029e6446ce1a97fe060ef688c/scikit_learn-1.9.0-cp314-cp314t-win_amd64.whl", hash = "sha256:78fc56eafd4edb9575d2d8950d1dd152061abb573341a1cb7e099fc40f6c6666", size = 8963204, upload-time = "2026-06-02T11:54:27.428Z" }, + { url = "https://files.pythonhosted.org/packages/ee/f3/ff83d76d7418112e5a61326443cdda87be3545dd8d6599c95b2481a4419e/scikit_learn-1.9.0-cp314-cp314t-win_arm64.whl", hash = "sha256:051075bda8b7aab87b1906ab3d4740a1e1224a19d7b3781a576736edc94e76aa", size = 8222661, upload-time = "2026-06-02T11:54:30.192Z" }, +] + +[[package]] +name = "scipy" +version = "1.18.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a7/25/c2700dfaf6442b4effaa91af24ebce5dc9d31bb4a69706313aae70d72cd0/scipy-1.18.0.tar.gz", hash = "sha256:67b2ad2ad54c72ca6d04975a9b2df8c3638c34ddd5b28738e94fc2b57929d378", size = 30774447, upload-time = "2026-06-19T15:01:43.456Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6a/19/ca10ead60b0acc80b2b833c2c4a4f2ff753d0f58b811f70d911c7e94a25c/scipy-1.18.0-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:7bd21faaf5a1a3b2eff922d02db5f191b99a6518db9078a8fb23169f6d22259a", size = 31056519, upload-time = "2026-06-19T14:59:45.203Z" }, + { url = "https://files.pythonhosted.org/packages/96/72/1e6442a00cd2924d361aa1b642ab6373ec35c6fabf311a760be9f76e0f13/scipy-1.18.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:265915e79107de9f946b855e50d7470d5893ec3f54b342e1aa6201cbdcd8bb6b", size = 28681889, upload-time = "2026-06-19T14:59:48.103Z" }, + { url = "https://files.pythonhosted.org/packages/9b/2d/11dd93d21e147a73ba22bd75c0b9208d3a2e0ec76d53170ce7d9029b1015/scipy-1.18.0-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:9ab7b758be6940954a713ee466e2043e9f6e2ed965c1fce5c91039f4be3d90a9", size = 20423580, upload-time = "2026-06-19T14:59:50.665Z" }, + { url = "https://files.pythonhosted.org/packages/9c/01/93552f75e0d2a7dd115a45e59209c51e8d514daff02fc887d2623be06fe1/scipy-1.18.0-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:97b6cddaaee0a779ef6b5ca83c9604b27cc16b2b8fc22c142652df8793319fb8", size = 23054441, upload-time = "2026-06-19T14:59:53.564Z" }, + { url = "https://files.pythonhosted.org/packages/3c/23/21f5e703643d66f21faa6b4c73195bfcad70c55efcb4f1ab327cd7c4101a/scipy-1.18.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:52a96e21517c7292375c0e27dd796a811f03fcea5fd4d108fdfea8145dcf17ab", size = 33968720, upload-time = "2026-06-19T14:59:56.415Z" }, + { url = "https://files.pythonhosted.org/packages/dd/aa/1b939f6c67ed68635bb538e6752d3dacc02f66535182e939a89581a44e9c/scipy-1.18.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1f55797419e16e7f30cf88ffb3113ce0467f00cfe3f70d5c281730b21769bfc2", size = 35287115, upload-time = "2026-06-19T14:59:59.411Z" }, + { url = "https://files.pythonhosted.org/packages/b6/ff/eec46be7e9234208f801062b53e1983085eddebd693f6c9bfb03b459830d/scipy-1.18.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:ad033410e2e0672ffdc1042110cef20e1c46f8fd0616cee1d44d8d58fad8fc11", size = 35577989, upload-time = "2026-06-19T15:00:02.235Z" }, + { url = "https://files.pythonhosted.org/packages/84/ca/210d4759c7210bb7d269437421959b39a33434e2776b60c5cb8a763bb30a/scipy-1.18.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:4a55985d54c769c872e64b7f4c8a81cc30ef700cc04296abbbf3705439c126de", size = 37421717, upload-time = "2026-06-19T15:00:05.102Z" }, + { url = "https://files.pythonhosted.org/packages/2b/54/9a9edb45345bd6744da5ddfb6628e5d5185920494c6a67ec45b6381004cb/scipy-1.18.0-cp312-cp312-win_amd64.whl", hash = "sha256:71ccc8faa2dd16ac310233203474a8b5cb67f10dedd54a3116d34943f4b19132", size = 36597428, upload-time = "2026-06-19T15:00:08.112Z" }, + { url = "https://files.pythonhosted.org/packages/99/0e/33f32a2a58987e26aec0f7df252cbbad1e90ae77bdbc76f40dd4ed0cf0ea/scipy-1.18.0-cp312-cp312-win_arm64.whl", hash = "sha256:d88363fd9d8fbd3511bd273f1a49efb2a540773ddf92a91d57498ce7dd7f3e76", size = 24351481, upload-time = "2026-06-19T15:00:11.103Z" }, + { url = "https://files.pythonhosted.org/packages/05/52/9c0136c2de7ae0779b7b366447766cec6d9f0702c56bb8ffeb04c8fd3af4/scipy-1.18.0-cp313-cp313-macosx_10_15_x86_64.whl", hash = "sha256:09143f676d157d9f546d663504ef9c1becb819824f1afc018814176411942446", size = 31036107, upload-time = "2026-06-19T15:00:14.03Z" }, + { url = "https://files.pythonhosted.org/packages/02/73/0291a64843270f4efb86cdcf2ee0f2048631b65ec6b405398b2b4dbf11bf/scipy-1.18.0-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:5efe260f69417b97ddae455bfb5a95e8359f7f66ad7fa9522a60feb66f169520", size = 28663303, upload-time = "2026-06-19T15:00:16.819Z" }, + { url = "https://files.pythonhosted.org/packages/d3/0f/10ffa0b697a572f4e0d48b92a88895d366422f019f723e7e14a84c050dac/scipy-1.18.0-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:68363b7eaacd8b5dd426df56d782cc156468ac79a127a1b87ca597d6e2e82197", size = 20404960, upload-time = "2026-06-19T15:00:19.635Z" }, + { url = "https://files.pythonhosted.org/packages/7e/d2/e896cea21ba8edd6c81d4c55b1ffcc717e79698dcbebf9641b4cfb4c6622/scipy-1.18.0-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:c5557d8be5da8e41353fcd4d21491fdbab83b062fc579e94dc09a7c8ab4f669b", size = 23034074, upload-time = "2026-06-19T15:00:22.107Z" }, + { url = "https://files.pythonhosted.org/packages/ea/b2/e83ea34279a52c03374477c74006256ec78df65fc877baa4617d6de1d202/scipy-1.18.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0d13bca67c096d89fb95ced0d8921807300fce0275643aef9533cc63a0773468", size = 33942038, upload-time = "2026-06-19T15:00:24.964Z" }, + { url = "https://files.pythonhosted.org/packages/f6/af/e8fe5fb136f51e2b01678b92cb4106d10d8cd68ec147ead2e7cb0ac75398/scipy-1.18.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a46f9273dbd0eb1cefba61c9b8648b4dfe3cbc14a080176f9a73e44b8336dc7f", size = 35266390, upload-time = "2026-06-19T15:00:28.059Z" }, + { url = "https://files.pythonhosted.org/packages/3a/49/2c5cbb907b56695fc67517811d1db234dfd83381a84814ec220aded2794d/scipy-1.18.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:5aba46108853ddfc77906b6557aac839d2b52e900c1d72a1180adaaab58d265f", size = 35551324, upload-time = "2026-06-19T15:00:31.014Z" }, + { url = "https://files.pythonhosted.org/packages/bb/73/eda39f7a2d306ff0ffc574afd13c0bbb6d10a603d9a413998ee269487a80/scipy-1.18.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:b6f758e35f12757b5d95c00bc6de2438e229c2664b7a92e96f205959d9f2dfa4", size = 37404785, upload-time = "2026-06-19T15:00:34.072Z" }, + { url = "https://files.pythonhosted.org/packages/b7/d2/ae881ee28d014f38e0ccbfd974a06a919ba9af34f1f74bf42b5301891d63/scipy-1.18.0-cp313-cp313-win_amd64.whl", hash = "sha256:1afac4a847207c7ff8efd321734a50b06d0280b3b2a2c0fc2f413101747ad7c7", size = 36554943, upload-time = "2026-06-19T15:00:36.903Z" }, + { url = "https://files.pythonhosted.org/packages/70/3a/21154e2d54eb3639c6bf4dbae2e531c68356bfe95990daa30df33b30d556/scipy-1.18.0-cp313-cp313-win_arm64.whl", hash = "sha256:c5dbddf60e58c2312316d097271a8e73d40eaf2eabfa4d95ed7d3695bbf2ce7b", size = 24350911, upload-time = "2026-06-19T15:00:40.062Z" }, + { url = "https://files.pythonhosted.org/packages/78/b5/915a19b3de2f7430062b509653563db1633ddbb6f021b06731521115d4e2/scipy-1.18.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:4c256ee70c0d1a8a2ace807e199ccd4e3f57037433842abb3fb36bc17eaa9578", size = 31036253, upload-time = "2026-06-19T15:00:43.216Z" }, + { url = "https://files.pythonhosted.org/packages/d7/88/b72def7262e150d16be13fca37a96481138d624e700340bc3362a7588929/scipy-1.18.0-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:2ef3abc54a4ffc53765374b0d5728532dfdd2585ed23f6b11c206a1f0b1b9af8", size = 28673758, upload-time = "2026-06-19T15:00:46.663Z" }, + { url = "https://files.pythonhosted.org/packages/91/02/2e636a61a525632c373cf6a9c24442a3ffb79e364d38e98b32042964ac32/scipy-1.18.0-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:f2a6af57bd9e4a75d70e4117e78a1bbee84f79ae3fbb6d0111005d6ebcc4cb8d", size = 20415514, upload-time = "2026-06-19T15:00:49.399Z" }, + { url = "https://files.pythonhosted.org/packages/c9/b6/2135974442f6aba159d9d39d774a1c8cb19947016725d69fecc685df45bf/scipy-1.18.0-cp314-cp314-macosx_14_0_x86_64.whl", hash = "sha256:3f1ac564d3bf6c03d861d2cd87a1bea0da2887136f7fb1bf519c05a8971452d6", size = 23034398, upload-time = "2026-06-19T15:00:51.941Z" }, + { url = "https://files.pythonhosted.org/packages/f6/e6/ba89ec5abf6ee9257c0d1ec985573f3ae32742c24bc03e016388a40b1b15/scipy-1.18.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:40395a5fcd1abee49a5c7aaa98c29db393eedc835138560a588c47ec16156690", size = 33998032, upload-time = "2026-06-19T15:00:54.838Z" }, + { url = "https://files.pythonhosted.org/packages/7f/c4/bc41eb19b0fd0db868f4132920879019318d80cc522ad8f2bca4611af808/scipy-1.18.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8ca01e8ae69f1b18e9a58d91afead31be3cef0dd905a10249dac559ee15460a0", size = 35283333, upload-time = "2026-06-19T15:00:58.152Z" }, + { url = "https://files.pythonhosted.org/packages/53/a4/cbdeef6eb3830a8462a9d4ada814de5fc984345cc9ecf17cbec51a036f1e/scipy-1.18.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7a7f3b01647384dbc3a711e8c6778e0aabbe93959249fef5c7393396bcac0867", size = 35610216, upload-time = "2026-06-19T15:01:01.155Z" }, + { url = "https://files.pythonhosted.org/packages/80/4d/b2b82502b65f661d1b789c1665dcdf315d5f12194e06fc0b37946294ebae/scipy-1.18.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:6aa94e78ec192a30063a5e72e561c28af769dc311190b24fe91774eff1969709", size = 37418960, upload-time = "2026-06-19T15:01:04.155Z" }, + { url = "https://files.pythonhosted.org/packages/93/3e/902d836831474b0ab5a37d16404f7bc5fafd9efba632890e271ba952635f/scipy-1.18.0-cp314-cp314-win_amd64.whl", hash = "sha256:2d8bbdc6c817f5b4006a54d799d4f5bab6f910193cbb9a1ff310833d4d270f61", size = 37288845, upload-time = "2026-06-19T15:01:07.822Z" }, + { url = "https://files.pythonhosted.org/packages/b6/43/8d73b337a3bdb14daa0314f0434210747c02d79d729ce1777574a817dcf6/scipy-1.18.0-cp314-cp314-win_arm64.whl", hash = "sha256:18e9575f1569b2c54174e6159d32942e03731177f63dce7975f0a0c88d102f5b", size = 24988971, upload-time = "2026-06-19T15:01:11.076Z" }, + { url = "https://files.pythonhosted.org/packages/b4/b4/f11918b0508a2787031a0499a03fbe3546f3bb5ca05d01038c45b278c09a/scipy-1.18.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:f351e0dd702687d12a402b867a1b4146a256923e1c38317cbc472f6372b94707", size = 31399325, upload-time = "2026-06-19T15:01:13.723Z" }, + { url = "https://files.pythonhosted.org/packages/7b/d1/1f287b57c0ff0ee5185dff3946d92c8017d39b0e431f0ae79a3ff1859512/scipy-1.18.0-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:7c7a51b33ce387193c97f228320cf8e87361daa1bba750638677729598b3e677", size = 29092110, upload-time = "2026-06-19T15:01:16.908Z" }, + { url = "https://files.pythonhosted.org/packages/ff/1a/7b74eb6c392fdcb27d414c0e7558a6d0231eb3b6d73571f479bb81ea8794/scipy-1.18.0-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:84031d7b052a54fae2f8632e0ec802073d385476eb9a63079bce6e23ef9283d4", size = 20833811, upload-time = "2026-06-19T15:01:20.488Z" }, + { url = "https://files.pythonhosted.org/packages/7c/ad/f3941716320a7b9cb4d68734a903b45fe16eff5fb7da7e16f2e619304979/scipy-1.18.0-cp314-cp314t-macosx_14_0_x86_64.whl", hash = "sha256:56abf29a7c067dde59be8b9a22d606a4ea1b2f2a4b756d9d903c62818f5dacce", size = 23396644, upload-time = "2026-06-19T15:01:23.364Z" }, + { url = "https://files.pythonhosted.org/packages/22/22/1446b62ffe07f9719b7d9b1b6a4e05a772833ae8f441fe4c22c34c9b250f/scipy-1.18.0-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1ad44305cfa24b1ba5803cbbebf033590ccbac1aa5d612d727b785325ab408b0", size = 34079318, upload-time = "2026-06-19T15:01:26.002Z" }, + { url = "https://files.pythonhosted.org/packages/56/3b/b87da667098bb470fa30c7011b0ba351ee976dd395c78798c66e941665a3/scipy-1.18.0-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:945c1761b93f38d7f99ae81ae80c63e621471608c7eeead563f6df025585cd58", size = 35324320, upload-time = "2026-06-19T15:01:28.881Z" }, + { url = "https://files.pythonhosted.org/packages/f8/a1/c7932f91909759b0267f75fdea34e91309f96b895757534b76a90b6b4344/scipy-1.18.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:1a4441f15d620578772a49e5ab48c0ee1f7a0220e387110283062729136b2553", size = 35699541, upload-time = "2026-06-19T15:01:31.968Z" }, + { url = "https://files.pythonhosted.org/packages/f7/86/5185061a1fcc41d18c5dc2463969b3a3964b31d9ac67b2fb05d4c7ff7670/scipy-1.18.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:9aac6192fac56bf2ca534389d24623f07b39ff83317d58287285e7fbd622ff76", size = 37472480, upload-time = "2026-06-19T15:01:35.136Z" }, + { url = "https://files.pythonhosted.org/packages/31/8e/f04c68e39919a010d34f2ee1367fd705b0a25a02f609d755f0bfbc0a15fc/scipy-1.18.0-cp314-cp314t-win_amd64.whl", hash = "sha256:e40baea28ae7f5475c779741e2d90b1247c78531207b49c7030e698ff81cee3f", size = 37365390, upload-time = "2026-06-19T15:01:38.091Z" }, + { url = "https://files.pythonhosted.org/packages/d5/19/969dc072906c84dd0a3b05dcf57ea750936087d7873549e408b35cfc3f97/scipy-1.18.0-cp314-cp314t-win_arm64.whl", hash = "sha256:368e0a705903c466aa5f08eefb39e6b1b6b2d659e7352a31fd9e2438365be0f8", size = 25279661, upload-time = "2026-06-19T15:01:40.817Z" }, +] + +[[package]] +name = "six" +version = "1.17.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, +] + +[[package]] +name = "starlette" +version = "1.3.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/eb/e3/7c1dc7381d9f8ab7d854328ebfa884e62cb3f3d8549ddfd37c7814f42afa/starlette-1.3.1.tar.gz", hash = "sha256:05d0213193f2fbaae60e2ecb593b4add4262ad4e46536b54abe36f11a71724e0", size = 2703240, upload-time = "2026-06-12T09:23:11.602Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ec/bb/2799cc2ede3ed41131f8975621e7213dfc7ef4acbbaadfa440f32500c370/starlette-1.3.1-py3-none-any.whl", hash = "sha256:c7372aae11c3c3f26a42df7bd626cec2f47d03483d261d369516a615a53714c6", size = 73632, upload-time = "2026-06-12T09:23:10.017Z" }, +] + +[[package]] +name = "streamlit" +version = "1.61.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "altair" }, + { name = "anyio" }, + { name = "blinker" }, + { name = "click" }, + { name = "httptools" }, + { name = "itsdangerous" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pandas" }, + { name = "pillow" }, + { name = "protobuf" }, + { name = "pyarrow" }, + { name = "pydeck" }, + { name = "python-multipart" }, + { name = "requests" }, + { name = "starlette" }, + { name = "tenacity" }, + { name = "toml" }, + { name = "typing-extensions" }, + { name = "uvicorn" }, + { name = "watchdog", marker = "sys_platform != 'darwin'" }, + { name = "websockets" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ad/4a/6d0bf2f78de59924564caf47298341c09f61bf3814f15f0d15ef09fe1e3d/streamlit-1.61.1.tar.gz", hash = "sha256:68acf1ff1b6005b19205c2777d832deea0c1edd6fbbf7f43f091b96220e5e35f", size = 9907073, upload-time = "2026-08-05T14:51:01.956Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4f/e3/deeea39117e1ffbce29755b45bceb214692e0a0aa496a17ce742b98ef3e1/streamlit-1.61.1-py3-none-any.whl", hash = "sha256:3f0ebf6764c3f938f8107414c9533942fa85a84b57affdaa7727d562210d8ece", size = 10512871, upload-time = "2026-08-05T14:50:59.246Z" }, +] + +[[package]] +name = "tenacity" +version = "9.1.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/47/c6/ee486fd809e357697ee8a44d3d69222b344920433d3b6666ccd9b374630c/tenacity-9.1.4.tar.gz", hash = "sha256:adb31d4c263f2bd041081ab33b498309a57c77f9acf2db65aadf0898179cf93a", size = 49413, upload-time = "2026-02-07T10:45:33.841Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d7/c1/eb8f9debc45d3b7918a32ab756658a0904732f75e555402972246b0b8e71/tenacity-9.1.4-py3-none-any.whl", hash = "sha256:6095a360c919085f28c6527de529e76a06ad89b23659fa881ae0649b867a9d55", size = 28926, upload-time = "2026-02-07T10:45:32.24Z" }, +] + +[[package]] +name = "threadpoolctl" +version = "3.6.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/b7/4d/08c89e34946fce2aec4fbb45c9016efd5f4d7f24af8e5d93296e935631d8/threadpoolctl-3.6.0.tar.gz", hash = "sha256:8ab8b4aa3491d812b623328249fab5302a68d2d71745c8a4c719a2fcaba9f44e", size = 21274, upload-time = "2025-03-13T13:49:23.031Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/d5/f9a850d79b0851d1d4ef6456097579a9005b31fea68726a4ae5f2d82ddd9/threadpoolctl-3.6.0-py3-none-any.whl", hash = "sha256:43a0b8fd5a2928500110039e43a5eed8480b918967083ea48dc3ab9f13c4a7fb", size = 18638, upload-time = "2025-03-13T13:49:21.846Z" }, +] + +[[package]] +name = "toml" +version = "0.10.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/be/ba/1f744cdc819428fc6b5084ec34d9b30660f6f9daaf70eead706e3203ec3c/toml-0.10.2.tar.gz", hash = "sha256:b3bda1d108d5dd99f4a20d24d9c348e91c4db7ab1b749200bded2f839ccbe68f", size = 22253, upload-time = "2020-11-01T01:40:22.204Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/44/6f/7120676b6d73228c96e17f1f794d8ab046fc910d781c8d151120c3f1569e/toml-0.10.2-py2.py3-none-any.whl", hash = "sha256:806143ae5bfb6a3c6e736a764057db0e6a0e05e338b5630894a5f779cabb4f9b", size = 16588, upload-time = "2020-11-01T01:40:20.672Z" }, +] + +[[package]] +name = "types-requests" +version = "2.33.0.20260712" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/db/51/703318f7b7be8bee126ec13bf615050f932d0179b8784420f3a0199cc769/types_requests-2.33.0.20260712.tar.gz", hash = "sha256:2141b67ab534a5c5cd2dac5034f2a35f42e699c5bf185eee608c5246a069d7fb", size = 25084, upload-time = "2026-07-12T05:14:20.455Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/62/e7/010c87f559e216d83f9dc51e939633fd0d0ead3377340181ab0e223cd3b5/types_requests-2.33.0.20260712-py3-none-any.whl", hash = "sha256:de027e28c171d3da529689cbfa023b0b4eab188c8dfa22fd834eebd2cee6e7bb", size = 21392, upload-time = "2026-07-12T05:14:19.616Z" }, +] + +[[package]] +name = "typing-extensions" +version = "4.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, +] + +[[package]] +name = "tzdata" +version = "2026.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/92/ff/5a28bdfd8c3ebec42564ac7d0e54ca3db65044a9314a97f9564fa7a1e926/tzdata-2026.3.tar.gz", hash = "sha256:4a1518b8993086a7982523e071643f3c0e5f213e75b21318e78bcabfff9d1415", size = 198674, upload-time = "2026-07-10T08:50:37.887Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e5/6d/b53b99a9f2766d095985947a5782f1702cabb129a34f7a802d7197af832f/tzdata-2026.3-py2.py3-none-any.whl", hash = "sha256:dc096730c87af6cab1b171c9d532be840741ff5d459015e7f6947bd7d7e54931", size = 348168, upload-time = "2026-07-10T08:50:36.46Z" }, +] + +[[package]] +name = "urllib3" +version = "2.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/53/0c/06f8b233b8fd13b9e5ee11424ef85419ba0d8ba0b3138bf360be2ff56953/urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c", size = 433602, upload-time = "2026-05-07T16:13:18.596Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087, upload-time = "2026-05-07T16:13:17.151Z" }, +] + +[[package]] +name = "uvicorn" +version = "0.52.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "h11" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/03/18/ccce41535dee1be77735592bd19965f3972c82e07ee703d324709496b716/uvicorn-0.52.1.tar.gz", hash = "sha256:112ec661814189acbccd3f7b86460147cc065fc92c0821afa78918780e4354dd", size = 100571, upload-time = "2026-08-01T18:19:30.732Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c7/d5/68e6e9bca63c0badf67002890a46d3784c958de45b65e1275ec583ca1f06/uvicorn-0.52.1-py3-none-any.whl", hash = "sha256:e4403f9d93188cf9d1088e9f40e3acd12630e2df8675316704379a7fc20fff6a", size = 79859, upload-time = "2026-08-01T18:19:29.294Z" }, +] + +[[package]] +name = "watchdog" +version = "6.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/db/7d/7f3d619e951c88ed75c6037b246ddcf2d322812ee8ea189be89511721d54/watchdog-6.0.0.tar.gz", hash = "sha256:9ddf7c82fda3ae8e24decda1338ede66e1c99883db93711d8fb941eaa2d8c282", size = 131220, upload-time = "2024-11-01T14:07:13.037Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a9/c7/ca4bf3e518cb57a686b2feb4f55a1892fd9a3dd13f470fca14e00f80ea36/watchdog-6.0.0-py3-none-manylinux2014_aarch64.whl", hash = "sha256:7607498efa04a3542ae3e05e64da8202e58159aa1fa4acddf7678d34a35d4f13", size = 79079, upload-time = "2024-11-01T14:06:59.472Z" }, + { url = "https://files.pythonhosted.org/packages/5c/51/d46dc9332f9a647593c947b4b88e2381c8dfc0942d15b8edc0310fa4abb1/watchdog-6.0.0-py3-none-manylinux2014_armv7l.whl", hash = "sha256:9041567ee8953024c83343288ccc458fd0a2d811d6a0fd68c4c22609e3490379", size = 79078, upload-time = "2024-11-01T14:07:01.431Z" }, + { url = "https://files.pythonhosted.org/packages/d4/57/04edbf5e169cd318d5f07b4766fee38e825d64b6913ca157ca32d1a42267/watchdog-6.0.0-py3-none-manylinux2014_i686.whl", hash = "sha256:82dc3e3143c7e38ec49d61af98d6558288c415eac98486a5c581726e0737c00e", size = 79076, upload-time = "2024-11-01T14:07:02.568Z" }, + { url = "https://files.pythonhosted.org/packages/ab/cc/da8422b300e13cb187d2203f20b9253e91058aaf7db65b74142013478e66/watchdog-6.0.0-py3-none-manylinux2014_ppc64.whl", hash = "sha256:212ac9b8bf1161dc91bd09c048048a95ca3a4c4f5e5d4a7d1b1a7d5752a7f96f", size = 79077, upload-time = "2024-11-01T14:07:03.893Z" }, + { url = "https://files.pythonhosted.org/packages/2c/3b/b8964e04ae1a025c44ba8e4291f86e97fac443bca31de8bd98d3263d2fcf/watchdog-6.0.0-py3-none-manylinux2014_ppc64le.whl", hash = "sha256:e3df4cbb9a450c6d49318f6d14f4bbc80d763fa587ba46ec86f99f9e6876bb26", size = 79078, upload-time = "2024-11-01T14:07:05.189Z" }, + { url = "https://files.pythonhosted.org/packages/62/ae/a696eb424bedff7407801c257d4b1afda455fe40821a2be430e173660e81/watchdog-6.0.0-py3-none-manylinux2014_s390x.whl", hash = "sha256:2cce7cfc2008eb51feb6aab51251fd79b85d9894e98ba847408f662b3395ca3c", size = 79077, upload-time = "2024-11-01T14:07:06.376Z" }, + { url = "https://files.pythonhosted.org/packages/b5/e8/dbf020b4d98251a9860752a094d09a65e1b436ad181faf929983f697048f/watchdog-6.0.0-py3-none-manylinux2014_x86_64.whl", hash = "sha256:20ffe5b202af80ab4266dcd3e91aae72bf2da48c0d33bdb15c66658e685e94e2", size = 79078, upload-time = "2024-11-01T14:07:07.547Z" }, + { url = "https://files.pythonhosted.org/packages/07/f6/d0e5b343768e8bcb4cda79f0f2f55051bf26177ecd5651f84c07567461cf/watchdog-6.0.0-py3-none-win32.whl", hash = "sha256:07df1fdd701c5d4c8e55ef6cf55b8f0120fe1aef7ef39a1c6fc6bc2e606d517a", size = 79065, upload-time = "2024-11-01T14:07:09.525Z" }, + { url = "https://files.pythonhosted.org/packages/db/d9/c495884c6e548fce18a8f40568ff120bc3a4b7b99813081c8ac0c936fa64/watchdog-6.0.0-py3-none-win_amd64.whl", hash = "sha256:cbafb470cf848d93b5d013e2ecb245d4aa1c8fd0504e863ccefa32445359d680", size = 79070, upload-time = "2024-11-01T14:07:10.686Z" }, + { url = "https://files.pythonhosted.org/packages/33/e8/e40370e6d74ddba47f002a32919d91310d6074130fe4e17dabcafc15cbf1/watchdog-6.0.0-py3-none-win_ia64.whl", hash = "sha256:a1914259fa9e1454315171103c6a30961236f508b9b623eae470268bbcc6a22f", size = 79067, upload-time = "2024-11-01T14:07:11.845Z" }, +] + +[[package]] +name = "websockets" +version = "16.1.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/21/f7/bc3a25c5ec26ce62ce487690becc2f3710bbc7b33338f005ad390db0b986/websockets-16.1.1.tar.gz", hash = "sha256:db234eda965dcce15df96bb9709f587cd87d4d52aaf0e80e2f34ec04c7670c57", size = 182204, upload-time = "2026-07-17T22:51:05.858Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/17/9d/681cda21c9eee743203a6cb79b9d3d05adad9aa60ec660c6c9bf4dd619ca/websockets-16.1.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:cc97814dfb786a83b6e2dc2e79351e1b83e6d715647d6887fcabd83026417a00", size = 179600, upload-time = "2026-07-17T22:49:13.92Z" }, + { url = "https://files.pythonhosted.org/packages/fb/8d/6195a88b45e8d2a8f745fc2046e36f885a3c9763e6767d2c46229bf9510c/websockets-16.1.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:e047dc87ef7ca50f4d309bf775ad4a71711c58556d75d7bd0604b2317f43e94b", size = 177272, upload-time = "2026-07-17T22:49:15.453Z" }, + { url = "https://files.pythonhosted.org/packages/73/e3/fe2d498c64dea0095c9a9f9a351af4cd6eef31b618395582bc1f38ba45ff/websockets-16.1.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:01fbdcbac298efe19360b94bc0039c8f746f0220ba570f327577bfee81059175", size = 177542, upload-time = "2026-07-17T22:49:16.875Z" }, + { url = "https://files.pythonhosted.org/packages/fe/ed/f1831681fce0e3242346e5458486003c5f124ed69e5e0b847fd029db4973/websockets-16.1.1-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:0f62863e8a00a6d33c3d6566ec0b89f23787b747ffe0c3bc71ec0e76b82c94b1", size = 187137, upload-time = "2026-07-17T22:49:18.323Z" }, + { url = "https://files.pythonhosted.org/packages/6f/79/4ff9dcc1bb46f6b4c536936dde1fd60f9b564f3304307274db97f4c9496d/websockets-16.1.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8087e82f842609734c9b5a1330464f8e94e346ba0e18c832c08bafa4b0d63c15", size = 188374, upload-time = "2026-07-17T22:49:19.65Z" }, + { url = "https://files.pythonhosted.org/packages/62/c3/5c49b6efb36cab733d23773f6de575e1dba65736ead17d5d2b2a1daef779/websockets-16.1.1-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:2bb5d041a8307d2e18782e7ce777f6fdb1e8c2f5d09291484b18c294b789d9aa", size = 191155, upload-time = "2026-07-17T22:49:21.331Z" }, + { url = "https://files.pythonhosted.org/packages/6e/f6/56ccceda3a4838d18f1d40821480da4775397e8b1eecf4031e20c50e2e90/websockets-16.1.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:1db4de4a0e95673f7545d393c49eeb0c2f18ac1ef93073218c79d5cdb2ee75ab", size = 189011, upload-time = "2026-07-17T22:49:22.889Z" }, + { url = "https://files.pythonhosted.org/packages/86/d6/ad5286241a2bce1107e2798d3bfbd62cf79aee167bdb654f8cb1e9dbf949/websockets-16.1.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f17dbe07eb3ea7f99e4df9b7e0efefe80fbf30d37a8cc4d561a0aed310bc8847", size = 187766, upload-time = "2026-07-17T22:49:24.339Z" }, + { url = "https://files.pythonhosted.org/packages/bc/67/d65c970b7e347fdca69479beb7811c2060529956730a7a4e3ae7c66b0e31/websockets-16.1.1-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:4b57693728576d84ede0a77987ab16881b783d2cd9f1dc180a8fbbc3f79c4428", size = 185173, upload-time = "2026-07-17T22:49:25.743Z" }, + { url = "https://files.pythonhosted.org/packages/1d/5b/14af3cd4ee69d8ea9baca58f3dc3cfb1ba78332a347fd478cb096549d60e/websockets-16.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:2a636ff1e7a5c4edf71ef0e79adae7f25dba93b4fcbe3dc958733477ffeb0eaf", size = 187809, upload-time = "2026-07-17T22:49:27.147Z" }, + { url = "https://files.pythonhosted.org/packages/7b/11/be301710d70de97e3e7b3586e6d492c9c06d6a61bf1c2202c36cf0c75607/websockets-16.1.1-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:d6bec75c290fe484a8ba4cacdf838501e17c06ecfbbf31eede81a9e431bd7751", size = 186412, upload-time = "2026-07-17T22:49:28.611Z" }, + { url = "https://files.pythonhosted.org/packages/db/07/fe1435bf6fe738a3d3b54dbe0c18dabf12cba4d909ac8b58b539ce27c1f4/websockets-16.1.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:54509b8e92fee4453e152b7558ddef37ce9705a044922f2095a6105e3f80c96f", size = 188290, upload-time = "2026-07-17T22:49:29.965Z" }, + { url = "https://files.pythonhosted.org/packages/8a/0a/81f394aff8efcbb01208c1ced77df0a3c7fcce584a88c7273663697946c2/websockets-16.1.1-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:f0aa4aad3b1b69ad3fd85a0fd0952ec64331c762bd77ec51cc814170873890b2", size = 185844, upload-time = "2026-07-17T22:49:31.447Z" }, + { url = "https://files.pythonhosted.org/packages/39/5c/dd485b995473f415510251fe9bd708f2d24458f439fce958daf8d66dc7c6/websockets-16.1.1-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:42290eb6db4ccaca7012656738214f8514082fb6fa40cdeb61bb9a471b52e383", size = 186823, upload-time = "2026-07-17T22:49:33.104Z" }, + { url = "https://files.pythonhosted.org/packages/9d/0b/f78de76ff446f1e66af12b43c48a35f31744de93cfdec2f4ea67d5d7bbf1/websockets-16.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:53260c8930da5771cec89439bff99c20c8cb03ddb9588b980697355a83cd4bd3", size = 187102, upload-time = "2026-07-17T22:49:34.616Z" }, + { url = "https://files.pythonhosted.org/packages/37/a1/4cf892007778eaf84ad162bfc98046e0ed89b63ac55949e3236626b2a23f/websockets-16.1.1-cp312-cp312-win32.whl", hash = "sha256:1d27fa8462ad6a1cb36206a3d0640b2333340def181fae11ed7f9adeaa5c0747", size = 179943, upload-time = "2026-07-17T22:49:36.213Z" }, + { url = "https://files.pythonhosted.org/packages/d9/de/6abe251d28c3a3f217096575400b27750b18e0b1d2fff3a2a239960fea07/websockets-16.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:b436f6ec4fc3a6b4237c84d3f83170ed2b40bb584222f0ac47a0c8a5921980c7", size = 180243, upload-time = "2026-07-17T22:49:37.626Z" }, + { url = "https://files.pythonhosted.org/packages/ce/fd/6ec6c6d2850aea25b1b2aa9901a016980bb87d01e89b3eb00470b1b5d471/websockets-16.1.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:ab59169ace05dcb49a1d4118f0bde139557adf45091bd85747e36bf5de984dd1", size = 179587, upload-time = "2026-07-17T22:49:38.959Z" }, + { url = "https://files.pythonhosted.org/packages/5f/d8/1d299d2dd34087db39831a34cc645ef8a6f89d78efada6983093513cd81c/websockets-16.1.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:5e3b7d601f6f84156b08cc4a5e541c2b50ad7b36cfc302b657a12477c904a5df", size = 177272, upload-time = "2026-07-17T22:49:40.293Z" }, + { url = "https://files.pythonhosted.org/packages/3d/86/0a70d3ae2f0f2256bb41302d9804dbca65d4360281e7feb3e1f94102ac46/websockets-16.1.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:cd2ca96a082a36964aca83e992f72abeb61b7306c1a6cba4c7d06a7b93750cac", size = 177530, upload-time = "2026-07-17T22:49:41.786Z" }, + { url = "https://files.pythonhosted.org/packages/b5/c2/c676c69444d9db448b3f0a55a98dcc534affce0bce961d9d2f0b8499b10a/websockets-16.1.1-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:f5d497865f05bb222cab7016c6034542e84e5f29f49c6fd3f4939cda7197b5b8", size = 187197, upload-time = "2026-07-17T22:49:43.658Z" }, + { url = "https://files.pythonhosted.org/packages/0b/13/88137fbaf726ebe29d62c1117fa11fa2bbb6209dc79d4ad738efbe36a2aa/websockets-16.1.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bae954c382e013d5ea5b190d2830526bfa45ad121c326da0049b8c769f185db6", size = 188433, upload-time = "2026-07-17T22:49:45.147Z" }, + { url = "https://files.pythonhosted.org/packages/01/6d/46c2f2ce6751cb26f39293e1ecbf8544cb01321397cd476c2756b98c216d/websockets-16.1.1-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:e09f753a169951eb4f28c2c774f71069304f66e7277e0f5a2892423599cfa854", size = 189868, upload-time = "2026-07-17T22:49:46.581Z" }, + { url = "https://files.pythonhosted.org/packages/29/2b/170a9e8097636cfde4dc3c592b6e00b18a44a2f5407606d96ca542dd5838/websockets-16.1.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:024193f8551a2b0eafbdd160911012c4e6c228c28430c84433253299a9e42d6a", size = 189059, upload-time = "2026-07-17T22:49:47.972Z" }, + { url = "https://files.pythonhosted.org/packages/a7/48/f0d4ebc9ab4b473b8861b9e20fdb663d515d42f7befdf62cdb60fee7a1ec/websockets-16.1.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:aabe464bfd13bd25f4821faf111da6fefdc389f870265a53105580e45b0a2e49", size = 187814, upload-time = "2026-07-17T22:49:49.344Z" }, + { url = "https://files.pythonhosted.org/packages/d5/ba/39a41d3ae8e72696a9492581900611c5a91e2b07563b0bcd2523adea9854/websockets-16.1.1-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a28fcbc9b6baf54a2e23f8655f308e4ccc6afdd7266f8fe7954f320dcda0f785", size = 185229, upload-time = "2026-07-17T22:49:50.787Z" }, + { url = "https://files.pythonhosted.org/packages/3c/36/ac15b604f850d1907f0a85ed721cefe47cd45034b3620069b829746cccbe/websockets-16.1.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:79eace538c6a97e96d0d03d4f9d314f9677f5ed85a8a984992ffd90b13cb8a56", size = 187874, upload-time = "2026-07-17T22:49:52.228Z" }, + { url = "https://files.pythonhosted.org/packages/a8/f3/3fbd5d71d59299c3770faa5884d4f45070236ca5a35ab3a61830812c409a/websockets-16.1.1-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:496af849a472b531f758dbd4d61338f5000538cb1a7b3d20d9d32a264517f509", size = 186469, upload-time = "2026-07-17T22:49:53.776Z" }, + { url = "https://files.pythonhosted.org/packages/b4/fc/dd90349bba58af2a53ef2ddd9c32716c81eb6d59a0687939fff561860878/websockets-16.1.1-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:5283810d2646741a0d8da2aa733d6aefa0545809afccb2a5d105a26bc45125f1", size = 188347, upload-time = "2026-07-17T22:49:55.202Z" }, + { url = "https://files.pythonhosted.org/packages/4c/f3/f73ba86427682da59b78c11d77ba56d5b801c32e84afe79b274bbd6a9bb2/websockets-16.1.1-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:4e3b680b1e0a27457e727a0d572fd81dffa87b6dbf8b228ab57da64f7d85aead", size = 185903, upload-time = "2026-07-17T22:49:56.75Z" }, + { url = "https://files.pythonhosted.org/packages/34/7c/f95eb20e80104173b3a0a092291f89ea4047ef6e608e0a57ca06eb14eecb/websockets-16.1.1-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:69159730a823dde3ea8d08783e8d47ef135a6d7e8d44eb127e32b321c9db8e3e", size = 186855, upload-time = "2026-07-17T22:49:58.467Z" }, + { url = "https://files.pythonhosted.org/packages/b0/35/dd875b3e050ff232d60fa377707f890e369f74d134f1be32e8f68879747c/websockets-16.1.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:ed5bb271084b46530ee2ddc0410537a9961152c5ccba2fc98c5276d992ccba87", size = 187140, upload-time = "2026-07-17T22:50:00.016Z" }, + { url = "https://files.pythonhosted.org/packages/e8/dc/5cbfcb41824502f6af93b8f3943a4d06c67c23c7d2e31eb18748c4a5b2a7/websockets-16.1.1-cp313-cp313-win32.whl", hash = "sha256:cfb70b4eb56cac4da0a83588f3ad50d46beb0690391082f3d4e2d488c70b68ea", size = 179928, upload-time = "2026-07-17T22:50:01.685Z" }, + { url = "https://files.pythonhosted.org/packages/b0/c1/71e5deb5b7f8f226997ab64908c184ac3105c0155ce2d486f318e5dd08a8/websockets-16.1.1-cp313-cp313-win_amd64.whl", hash = "sha256:d9531d9cbeac99af6f038fb1bc351403531f7d634a2c2e10e2f7c854c6ed5b68", size = 180242, upload-time = "2026-07-17T22:50:03.117Z" }, + { url = "https://files.pythonhosted.org/packages/73/a2/ba78a164eeea4620df4a4df4bd2ed6017438c4655cc0f36f2c0bc0432355/websockets-16.1.1-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:443aefe96b7fdb132e2a70806cca1f2af49bb3f28e47abcd7c2e9dcf4d8fa1b8", size = 179635, upload-time = "2026-07-17T22:50:05.001Z" }, + { url = "https://files.pythonhosted.org/packages/b9/08/d26d7a7628cd4ac34cbbdb63ac80914ca842ed8e42938c40a53567806df3/websockets-16.1.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:6456ff333092d509127d75a638cb411afae8ff17f092635015d1902efec8a293", size = 177320, upload-time = "2026-07-17T22:50:06.427Z" }, + { url = "https://files.pythonhosted.org/packages/0f/45/ebec83e6269536aa5932533c67b0af5c781f3e73fdbcd68672dcf43f4f44/websockets-16.1.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:fce6c48559c86d1ac3632ccb1bebc7d5442fbe79bd9bb0e40379ee54be2a4051", size = 177544, upload-time = "2026-07-17T22:50:07.834Z" }, + { url = "https://files.pythonhosted.org/packages/c9/d5/abc614d2297f6c1c3e01e61260364457a47c25cc1cf6a879038902bc6aa8/websockets-16.1.1-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:92b820d345f7a3fc7b8163949ee92df910f290c3fc517b3d5301c78065adafe1", size = 187270, upload-time = "2026-07-17T22:50:09.275Z" }, + { url = "https://files.pythonhosted.org/packages/52/71/4c99af3b87dff1b2927981f6876607d4acb45338c665242168d3982f7758/websockets-16.1.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2a606d9c24035242a3e256e9d5b77ed9cd6bccfcb7cf993e5ca3c0f6f68fb6a7", size = 188509, upload-time = "2026-07-17T22:50:10.722Z" }, + { url = "https://files.pythonhosted.org/packages/9b/b4/5c8ca14b0df7eb84ed0524165c5359150210140817a3312aee57bf62a1cf/websockets-16.1.1-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:414e596c75f74e0994084694189d7dc9229fb278e33064d6784b73ffbba3ca31", size = 189882, upload-time = "2026-07-17T22:50:12.293Z" }, + { url = "https://files.pythonhosted.org/packages/25/c1/bedfba9e70557129cb8083748d167bdcc01483dedf0f0df143676df05cbe/websockets-16.1.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:536676848fc5961aca9d20389951f59169508f765637a172403dc5434d722fa0", size = 189114, upload-time = "2026-07-17T22:50:13.789Z" }, + { url = "https://files.pythonhosted.org/packages/df/09/aa835b2787835aebd839114be5de51b797cb480b63ba42b26d34dfe147cb/websockets-16.1.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:97fd3a0e8b53efa41970ac1dff3d8cf0d2884cadeb4caaf95db7ad1526926ee3", size = 187861, upload-time = "2026-07-17T22:50:15.179Z" }, + { url = "https://files.pythonhosted.org/packages/20/26/f6408330694dbc9830857d9d23bc14ac4f6875127a480cfdda8d5ca21198/websockets-16.1.1-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:7b1b19636af86a3c7995d4d028dbe376f39b4bf31541146f9c123582a6c94562", size = 185286, upload-time = "2026-07-17T22:50:16.741Z" }, + { url = "https://files.pythonhosted.org/packages/17/9a/e0675e70dd8a80762cf35bb18799d3f290a4890ffe6439bc51d222796083/websockets-16.1.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:41c8e77f17294c0ac18008a7309b99b34ee72247ef10b6dff4c3f8b5ac29896b", size = 187935, upload-time = "2026-07-17T22:50:18.213Z" }, + { url = "https://files.pythonhosted.org/packages/33/c1/3234cfb86afde01b81e9bddcc6e534c440975d60a13991259e833069ab3e/websockets-16.1.1-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:9f63bcef7f4b02b06b35fc01c93b96c43b5e88e1e8868676caacf493d5a31f3a", size = 186444, upload-time = "2026-07-17T22:50:19.67Z" }, + { url = "https://files.pythonhosted.org/packages/89/87/9c15206e1d778923d8daa9657de07aa62ea815e13448319c98458c37b281/websockets-16.1.1-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:dab9eb87869da2d6ed3af3f3adf28414baae6ec9d4df355ffc18889132f3436c", size = 188409, upload-time = "2026-07-17T22:50:21.28Z" }, + { url = "https://files.pythonhosted.org/packages/f2/00/cf5de5c67676de2d3eef8b2a518f168f6796595447a5b7161ba0d012915c/websockets-16.1.1-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:43e3a9fdd7cbf7ba6040c31fae0faf84ca1474fef777c4e37912f1540f854499", size = 185958, upload-time = "2026-07-17T22:50:22.719Z" }, + { url = "https://files.pythonhosted.org/packages/62/c0/731b6ddede2e4136912ec4cff2cffbda35af73546be4762c3d7bd3bd79af/websockets-16.1.1-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:056ae37939ed7e9974f364f5864e76e49182622d8f9751ac1903c0d09b013985", size = 186911, upload-time = "2026-07-17T22:50:24.108Z" }, + { url = "https://files.pythonhosted.org/packages/8c/7f/39c634472c4469a24a7c09cecddffb08fac6d0e74f73881a94ee8a40a196/websockets-16.1.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:a0eadbbf2c30f01efa58e1f110eb6fa293261f6b0b1aa38f7f48707107690af9", size = 187204, upload-time = "2026-07-17T22:50:25.548Z" }, + { url = "https://files.pythonhosted.org/packages/26/89/9667c256c256dafcc62d21328ce7a40067da857969b68ee9af375b0aaf72/websockets-16.1.1-cp314-cp314-win32.whl", hash = "sha256:195c978b065fa40910582464f99d6b15c8b314c68e0546549a55ed83f4735328", size = 179603, upload-time = "2026-07-17T22:50:27.086Z" }, + { url = "https://files.pythonhosted.org/packages/bd/dd/1c099d6c0fc5deb6b46ccdbb6981fdb4b12c917869cb3952408409dc18db/websockets-16.1.1-cp314-cp314-win_amd64.whl", hash = "sha256:4e8d01cc3bcae7bbf8167f944aeafefed590fae5693552bba9794a9df68371cc", size = 179948, upload-time = "2026-07-17T22:50:28.521Z" }, + { url = "https://files.pythonhosted.org/packages/35/25/9956b2d5e0529d5d23924f21bba1440d4c5c88a562e4f08550871ffa97a7/websockets-16.1.1-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:0ffd3031ea8bda8d61762e84220186105ba3b748b3c8da2ae4f7816fac03e573", size = 179963, upload-time = "2026-07-17T22:50:29.982Z" }, + { url = "https://files.pythonhosted.org/packages/17/06/55ffc976c488b6aee9ea05761ff7c4e88e7c1fd82818c8ca7b556ad2f90c/websockets-16.1.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:84a2cef8deffbd9ab8ee0ea546a2a6a7030c28f44e6cdd4547dbfeb489eb8999", size = 177497, upload-time = "2026-07-17T22:50:31.396Z" }, + { url = "https://files.pythonhosted.org/packages/0c/e8/f7dac2e980bacc92bdc26cebae4ae4d50cae5380732c50980598fc0bbae4/websockets-16.1.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:3df13f73af9b3b38ab1195eb299ecb67a4330c911c97ae04043ff74085728abe", size = 177698, upload-time = "2026-07-17T22:50:32.829Z" }, + { url = "https://files.pythonhosted.org/packages/b2/39/26762f734113e22da2b942c3aca85798e0c0405d64c256549540ff31e5a1/websockets-16.1.1-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:23253dd5bcae3f9aaee0a1d30967a8dbd52e5d3cff93a2e5b84df57b77d4750d", size = 187561, upload-time = "2026-07-17T22:50:34.24Z" }, + { url = "https://files.pythonhosted.org/packages/11/94/c3f330851806b9b02138b774d593478323e73c99238681b4b93efe64e02d/websockets-16.1.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9c1c5705e314449e3308872fe084b8571ce078ee4fc55a98a769bdefe5917392", size = 188732, upload-time = "2026-07-17T22:50:36.088Z" }, + { url = "https://files.pythonhosted.org/packages/d1/f2/eb2c450f052de334ae33cf200ece6e87b0e14d186807074e4eb1cd2cdea2/websockets-16.1.1-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:69e52d175a0a7d1e13b4b67ad41c560b7d98e8c6f6126eb0bda496c784faf8c7", size = 190872, upload-time = "2026-07-17T22:50:38.008Z" }, + { url = "https://files.pythonhosted.org/packages/70/31/2ac8cecf3a74f7fed9132129fc3d90b3998a1554570c11a69b2a8c20332d/websockets-16.1.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:1f79c89b5eb034d1722938a891916582f8f7f503f58ca22518a63c3f2cd18499", size = 189305, upload-time = "2026-07-17T22:50:39.53Z" }, + { url = "https://files.pythonhosted.org/packages/6a/cf/8ab19650d3c0d4562c92e70ab47c257c4aa5c6a713ed87fe63766b31fefc/websockets-16.1.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:39f2a024af5c345ffe8fcf1ee18c049c024c94df393bb09b044a6917c77bde43", size = 188033, upload-time = "2026-07-17T22:50:40.912Z" }, + { url = "https://files.pythonhosted.org/packages/66/d7/a49a38a6127a4acb134fb1912b215d900cc657605cff32445bf519f3acc4/websockets-16.1.1-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:952303a7318d4cbe1011400839bb2051c9f84fa0a35923267f5daba34b15d458", size = 185748, upload-time = "2026-07-17T22:50:42.559Z" }, + { url = "https://files.pythonhosted.org/packages/95/3e/ad1fa40388c7f2e0bb2c7930d0090b6c5498594bd1cdaec18864df3d9e97/websockets-16.1.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:249116b4a76063d930a46391ad56e135c286e4562a18309029fc2c73f4ed4c62", size = 188285, upload-time = "2026-07-17T22:50:43.974Z" }, + { url = "https://files.pythonhosted.org/packages/35/b8/d5db28ca264b9104f82196f92dc8843e35fd391f763d42e4ad358f5bc97e/websockets-16.1.1-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:61922544a0587a13fd3f53e4c0e5e606510c7b0d9d22c8444e5fae22a06b38cb", size = 186777, upload-time = "2026-07-17T22:50:45.474Z" }, + { url = "https://files.pythonhosted.org/packages/42/9c/726cb39d0cc43ae848dce4aa2acb04eecc6738b1264ec6d700bf6bcfb9f8/websockets-16.1.1-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:46dcaa042cd1de6c59e7d9269fa63ff7572b6df40510600b678f0826b3c7af51", size = 188682, upload-time = "2026-07-17T22:50:46.973Z" }, + { url = "https://files.pythonhosted.org/packages/be/c7/1168704de8c2dd483edabe4a22cbe4465dd8be8dd95561d214f9fe092871/websockets-16.1.1-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:38565aca3e01ea8734e578fb2118dade0ecb0250533f29e22b8d1a7a196cf4d0", size = 186377, upload-time = "2026-07-17T22:50:48.413Z" }, + { url = "https://files.pythonhosted.org/packages/ca/40/f9ff2d630ffce4e7dfea0b2288e1caf9ebbf9ff8a9ec9396136ce8b94935/websockets-16.1.1-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:42f599f4d48c7e1a3338fdaac3acd075be3b3cf02d4b274f3bf2767aedd3d217", size = 187148, upload-time = "2026-07-17T22:50:49.845Z" }, + { url = "https://files.pythonhosted.org/packages/b5/71/e177c8299f78d7cbe2d14df228643c10c70c0e86e108e092056bbcc16e46/websockets-16.1.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:dcc04fedf83effaeb9cce98abc9469bb1b42ef85f03e01c8c1f4438ef7555737", size = 187578, upload-time = "2026-07-17T22:50:51.619Z" }, + { url = "https://files.pythonhosted.org/packages/49/b2/b6987faf330f5af5c787a2610124c2e8403d51724f9001ec4fff6311fe7a/websockets-16.1.1-cp314-cp314t-win32.whl", hash = "sha256:8483c2096363120eea8b07c06ae7304d520f686665fffd4811fad423930a65d7", size = 179729, upload-time = "2026-07-17T22:50:53.269Z" }, + { url = "https://files.pythonhosted.org/packages/a2/6e/fbac6ed878dd362fbad7d415fa4f84d38e3e33fed8cde45c64e783acf826/websockets-16.1.1-cp314-cp314t-win_amd64.whl", hash = "sha256:bcce07e23e5769375158f5efdcdafa8d5cd014b93c6683865b840ed65b96f231", size = 180072, upload-time = "2026-07-17T22:50:54.969Z" }, + { url = "https://files.pythonhosted.org/packages/be/4d/2d0d67834092e354d2b0498f014a41249a89556bc406cf86f3e1557bb463/websockets-16.1.1-py3-none-any.whl", hash = "sha256:6abbd3e82c731c8e531714466acd5d87b5e88ac3243465337ba71d68e23ae7e3", size = 173814, upload-time = "2026-07-17T22:51:04.184Z" }, +]