From 45d350a74fdd36d64addd8506cf120516bfbe261 Mon Sep 17 00:00:00 2001 From: PureSaber <88314620+PureSaber@users.noreply.github.com> Date: Tue, 6 Oct 2026 23:22:25 +0800 Subject: [PATCH] feat: verify and independently restore authoritative paper accounts --- README.md | 29 ++++ src/quant_paper_sim/cli.py | 17 ++ src/quant_paper_sim/recovery.py | 176 +++++++++++++++++++++ tests/test_recovery.py | 268 ++++++++++++++++++++++++++++++++ 4 files changed, 490 insertions(+) create mode 100644 src/quant_paper_sim/recovery.py create mode 100644 tests/test_recovery.py diff --git a/README.md b/README.md index 4ad58fe..cabcc7d 100644 --- a/README.md +++ b/README.md @@ -80,6 +80,35 @@ provenance explicitly. ## Authoritative state +### 低频账本核验、独立备份与恢复 + +```powershell +quant-paper verify --config configs/paper.yaml +quant-paper backup --config configs/paper.yaml --out backups/account-20261006 +quant-paper restore --config configs/recovered.yaml --backup backups/account-20261006 +``` + +`verify`只读回放权威日志,核对成交、费用、事件及累计账本哈希,并将全部账户投影 +与回放结果比较;它不创建目录、不取写锁、不迁移和改写文件。返回 +`replay_verified`、`projection_status`、`mismatched_files`及`pending_commit`。 +`needs_rebuild`说明投影缺失、损坏或存在未清理提交标记;权威日志有效时可使用既有 +`status`重新生成投影。日志或历史归档损坏时明确失败,不从投影余额重建账户。 + +`backup`取账户写锁,在真实回放通过后创建全新且独立的目录,保存权威日志原始字节、 +全部嵌套历史归档及逐文件SHA-256清单。它不会覆盖已有备份;最后写入清单作为完成 +标记。备份只包含账户事实,不包含信号、市场输入、运行环境或配置;这些另行保存。 + +恢复配置的`state_dir`必须指向空目录,成交规则和证券目录必须与备份一致。 +`restore`先核验全部备份、版本白名单和回放哈希,再安装原始权威字节并生成投影。 +恢复不要求原信号文件仍存在。原状态、现有账户与旧认证资料不会被覆盖;也无需`init`。 +权威日志安装后若投影写入中断,使用`status --config configs/recovered.yaml`继续重建; +已存在状态的目录不会接受第二次`restore`。 + +验收包括提交前后杀死独立进程、写锁自动释放、重复步进只记一次、规则不匹配、 +伪造投影清单、损坏/缺失备份及嵌套归档的独立恢复。当前锁定 +`quant-execution@v0.5.1`,仍为低频研究模拟,不增加纳秒或真实券商执行能力。 + + `state/execution_log.json` is the only persisted execution truth. It contains: - schema and exact `quant-execution` version; diff --git a/src/quant_paper_sim/cli.py b/src/quant_paper_sim/cli.py index cb2a8f9..2bb29b1 100644 --- a/src/quant_paper_sim/cli.py +++ b/src/quant_paper_sim/cli.py @@ -8,6 +8,7 @@ from quant_execution import ReplayError from quant_paper_sim.engine import initialize, preflight, run_step, status +from quant_paper_sim.recovery import backup_state, restore_state, verify_state from quant_paper_sim.state import StateError @@ -19,13 +20,29 @@ def main(argv: list[str] | None = None) -> None: ("init", "Reset authoritative paper execution state to cash"), ("status", "Replay authoritative state and print its portfolio projection"), ("preflight", "Read and validate inputs without replaying or modifying the account"), + ("verify", "Replay and inspect saved account evidence without modifying files"), + ("backup", "Create an independent verified authoritative journal backup"), + ("restore", "Restore a verified backup to an empty state directory"), ): item = sub.add_parser(command, help=help_text) item.add_argument("--config", required=True) + if command == "backup": + item.add_argument("--out", required=True, type=Path) + elif command == "restore": + item.add_argument("--backup", required=True, type=Path) args = parser.parse_args(argv) config_path = Path(args.config) try: + if args.command in {"verify", "backup", "restore"}: + if args.command == "backup": + evidence = backup_state(config_path, args.out) + elif args.command == "restore": + evidence = restore_state(config_path, args.backup) + else: + evidence = verify_state(config_path) + print(json.dumps(evidence, indent=2, ensure_ascii=False)) + return if args.command == "preflight": print(json.dumps(preflight(config_path), indent=2, ensure_ascii=False)) return diff --git a/src/quant_paper_sim/recovery.py b/src/quant_paper_sim/recovery.py new file mode 100644 index 0000000..4c433e7 --- /dev/null +++ b/src/quant_paper_sim/recovery.py @@ -0,0 +1,176 @@ +"""Read-only replay checks and independent, byte-preserving account backups.""" + +from __future__ import annotations + +import hashlib +import json +from pathlib import Path + +from .engine import ( + _assert_config_compatible, + _commit, + _compile, + _latest_trades, + _portfolio_from, + _projection_bytes, + _state_paths, + _validate_pending_marker, + _verify_migration_archive, +) +from .instrument_catalog import load_configured_catalog +from .readers.signals import load_config +from .state import ( + StateError, + atomic_write_bytes, + atomic_write_json, + install_or_open_archive, + is_compat_migrated_log, + read_regular_bytes, + regular_file_exists, + state_writer_lock, + validate_log, +) + +MANIFEST = "backup_manifest.json" +BACKUP_SCHEMA = "quant-paper-backup/1.0.0" + + +def _configuration(config_path): + cfg = load_config(config_path) + return cfg, load_configured_catalog(cfg, config_path), _state_paths(config_path, cfg) + + +def _authority_files(paths): + """Include the complete validated historical archive chain, without projections.""" + payloads = {"execution_log.json": read_regular_bytes(paths.log, "authoritative execution log")} + log = validate_log(json.loads(payloads["execution_log.json"])) + _verify_migration_archive(paths, log) + current = log + while is_compat_migrated_log(current): + name = current["migration"]["source_archive"] + if name in payloads: + raise StateError("cyclic authoritative archive chain") + payloads[name] = read_regular_bytes(paths.root / name, "compatibility archive") + if hashlib.sha256(payloads[name]).hexdigest() != current["migration"]["source_file_sha256"]: + raise StateError("compatibility archive changed while collecting backup evidence") + current = validate_log(json.loads(payloads[name])) + return log, payloads + + +def _replay(log, cfg, catalog): + _assert_config_compatible(log, cfg, catalog) + compiled = _compile(log, catalog) + as_of = log["steps"][-1]["as_of"] if log["steps"] else "init" + portfolio = _portfolio_from(compiled, log, as_of) + return compiled, portfolio, _latest_trades(compiled) + + +def verify_state(config_path: Path) -> dict: + """Inspect saved evidence without locks, migration, repair or directory creation.""" + cfg, catalog, paths = _configuration(config_path) + log, payloads = _authority_files(paths) + compiled, portfolio, trades = _replay(log, cfg, catalog) + expected = _projection_bytes(compiled, log, portfolio, trades) + manifest = { + "schema": "quant-paper-projections/1.0.0", + "authoritative_sha256": log["content_sha256"], + "files": { + name: hashlib.sha256(data).hexdigest() for name, data in sorted(expected.items()) + }, + } + expected["projection_manifest.json"] = json.dumps( + manifest, indent=2, ensure_ascii=False + ).encode("utf-8") + mismatched = [] + for name, data in expected.items(): + path = paths.root / name + if ( + not regular_file_exists(path, "account projection") + or read_regular_bytes(path, "account projection") != data + ): + mismatched.append(name) + pending = _validate_pending_marker(paths) is not None + if ( + read_regular_bytes(paths.log, "authoritative execution log") + != payloads["execution_log.json"] + ): + raise StateError("authoritative execution log changed during verification") + return { + "replay_verified": True, + "authoritative_sha256": log["content_sha256"], + "journal_file_sha256": hashlib.sha256(payloads["execution_log.json"]).hexdigest(), + "steps": len(log["steps"]), + "projection_status": "needs_rebuild" if mismatched or pending else "complete", + "mismatched_files": sorted(mismatched), + "pending_commit": pending, + "portfolio": portfolio.to_dict(), + } + + +def backup_state(config_path: Path, output: Path) -> dict: + cfg, catalog, paths = _configuration(config_path) + output = output.resolve() + if output.is_relative_to(paths.root.resolve()) or paths.root.resolve().is_relative_to(output): + raise StateError("backup must be independent of the account state directory") + if not regular_file_exists(paths.log, "authoritative execution log"): + raise StateError("cannot back up missing authoritative execution log") + with state_writer_lock(paths.root): + log, payloads = _authority_files(paths) + _replay(log, cfg, catalog) + output.mkdir(parents=True, exist_ok=False) + for name, data in payloads.items(): + with install_or_open_archive(output / name, data): + pass + manifest = { + "schema": BACKUP_SCHEMA, + "authoritative_sha256": log["content_sha256"], + "files": { + name: hashlib.sha256(data).hexdigest() for name, data in sorted(payloads.items()) + }, + } + # The last durable write marks a complete backup; a partial folder is rejected. + atomic_write_json(output / MANIFEST, manifest) + return {"backup": str(output), "steps": len(log["steps"]), **manifest} + + +def _load_backup(backup): + manifest = json.loads(read_regular_bytes(backup / MANIFEST, "backup manifest")) + if ( + not isinstance(manifest, dict) + or set(manifest) != {"schema", "authoritative_sha256", "files"} + or manifest["schema"] != BACKUP_SCHEMA + or not isinstance(manifest["files"], dict) + ): + raise StateError("invalid backup manifest") + # Validating the journal and each migration derives all permitted basenames. + from .state import StatePaths + + log, payloads = _authority_files(StatePaths(backup)) + expected = {name: hashlib.sha256(data).hexdigest() for name, data in sorted(payloads.items())} + if ( + manifest["authoritative_sha256"] != log["content_sha256"] + or manifest["files"] != expected + or {p.name for p in backup.iterdir()} != set(payloads) | {MANIFEST} + ): + raise StateError("backup file set or checksum mismatch") + return log, payloads + + +def restore_state(config_path: Path, backup: Path) -> dict: + """Restore verified authority to an empty account; never import projection balances.""" + cfg, catalog, paths = _configuration(config_path) + log, payloads = _load_backup(backup) + compiled, portfolio, trades = _replay(log, cfg, catalog) + with state_writer_lock(paths.root): + if any(p.name != ".paper_state.lock" for p in paths.root.iterdir()): + raise StateError( + "restore requires an empty state directory; preserve existing evidence" + ) + for name, data in payloads.items(): + if name != "execution_log.json": + with install_or_open_archive(paths.root / name, data): + pass + # Install exact authority before projections so a later interruption is replay-repairable. + atomic_write_bytes(paths.log, payloads["execution_log.json"]) + _commit(paths, log, compiled, portfolio, trades, write_authoritative=False) + return verify_state(config_path) diff --git a/tests/test_recovery.py b/tests/test_recovery.py new file mode 100644 index 0000000..8b61a29 --- /dev/null +++ b/tests/test_recovery.py @@ -0,0 +1,268 @@ +import hashlib +import json +import subprocess +import sys +import time +from pathlib import Path + +import pytest +import yaml +from test_execution_state import paper_config, write_signal +from test_state_compatibility import compatibility_case + +from quant_paper_sim import engine +from quant_paper_sim.cli import main +from quant_paper_sim.engine import run_step, status +from quant_paper_sim.recovery import backup_state, restore_state, verify_state +from quant_paper_sim.state import ( + HISTORICAL_REPLAY_PROFILE, + LOG_SCHEMA, + PREVIOUS_COMPAT_MIGRATION_KIND, + PREVIOUS_EXECUTION_VERSION, + PREVIOUS_PAPER_SIM_VERSION, + StateError, + seal_log, + state_writer_lock, +) + + +def account(tmp_path): + config, signal, state = paper_config(tmp_path) + write_signal(signal, as_of="2025-03-03", targets=[("600519.SH", 0.5, 10)]) + expected = run_step(config).portfolio + return config, signal, state, expected + + +def restored_config(config, destination): + cfg = yaml.safe_load(config.read_text(encoding="utf-8")) + cfg["state_dir"] = str(destination) + restored = config.with_name("restored.yaml") + restored.write_text(yaml.safe_dump(cfg), encoding="utf-8") + return restored + + +def files(root): + return {p.name: p.read_bytes() for p in root.iterdir() if p.is_file()} + + +def test_verify_is_read_only_and_detects_resigned_projection_corruption(tmp_path): + config, _, state, expected = account(tmp_path) + before = files(state) + report = verify_state(config) + assert report["replay_verified"] and report["projection_status"] == "complete" + assert files(state) == before + portfolio = state / "portfolio.json" + payload = json.loads(portfolio.read_text()) + payload["cash"] += 100 + portfolio.write_text(json.dumps(payload), encoding="utf-8") + manifest_path = state / "projection_manifest.json" + manifest = json.loads(manifest_path.read_text()) + manifest["files"][portfolio.name] = hashlib.sha256(portfolio.read_bytes()).hexdigest() + manifest_path.write_text(json.dumps(manifest), encoding="utf-8") + damaged = files(state) + report = verify_state(config) + assert report["projection_status"] == "needs_rebuild" + assert "portfolio.json" in report["mismatched_files"] + assert files(state) == damaged + assert status(config).to_dict() == expected.to_dict() + assert verify_state(config)["projection_status"] == "complete" + + +def test_independent_backup_restores_exact_authority_without_signal_inputs(tmp_path): + config, signal, state, expected = account(tmp_path) + source = files(state) + backup = tmp_path / "backup" + saved = backup_state(config, backup) + assert saved["steps"] == 1 and files(state) == source + signal.unlink() + destination = tmp_path / "recovered" + restored = restored_config(config, destination) + result = restore_state(restored, backup) + assert result["projection_status"] == "complete" + assert (destination / "execution_log.json").read_bytes() == source["execution_log.json"] + assert status(restored).to_dict() == expected.to_dict() + with pytest.raises((StateError, FileExistsError)): + backup_state(config, backup) + with pytest.raises(StateError, match="empty"): + restore_state(restored, backup) + + +@pytest.mark.parametrize("damage", ["checksum", "missing", "manifest", "extra"]) +def test_invalid_backup_is_rejected_before_destination_is_created(tmp_path, damage): + config, _, _, _ = account(tmp_path) + backup = tmp_path / "backup" + backup_state(config, backup) + if damage == "checksum": + (backup / "execution_log.json").write_text("{}") + elif damage == "missing": + (backup / "execution_log.json").unlink() + elif damage == "extra": + (backup / "other.json").write_text("{}") + else: + manifest = json.loads((backup / "backup_manifest.json").read_text()) + manifest["files"]["../execution_log.json"] = "0" * 64 + (backup / "backup_manifest.json").write_text(json.dumps(manifest)) + destination = tmp_path / "recovered" + with pytest.raises((StateError, OSError, ValueError)): + restore_state(restored_config(config, destination), backup) + assert not destination.exists() + + +def test_restore_projection_failure_keeps_authority_recoverable(tmp_path, monkeypatch): + config, _, state, expected = account(tmp_path) + backup = tmp_path / "backup" + backup_state(config, backup) + destination = tmp_path / "recovered" + restored = restored_config(config, destination) + original = engine.atomic_write_bytes + + def fail(path: Path, data, **kwargs): + if path.name == "nav.csv": + raise OSError("injected projection interruption") + return original(path, data, **kwargs) + + with monkeypatch.context() as patch: + patch.setattr(engine, "atomic_write_bytes", fail) + with pytest.raises(OSError, match="injected"): + restore_state(restored, backup) + assert (destination / "execution_log.json").read_bytes() == ( + state / "execution_log.json" + ).read_bytes() + assert (destination / ".paper_commit_pending.json").is_file() + assert status(restored).to_dict() == expected.to_dict() + + +def test_backup_and_restore_respect_writer_lock_and_config_identity(tmp_path): + config, _, state, _ = account(tmp_path) + with state_writer_lock(state), pytest.raises(StateError, match="already"): + backup_state(config, tmp_path / "locked-backup") + assert not (tmp_path / "locked-backup").exists() + backup = tmp_path / "backup" + backup_state(config, backup) + restored = restored_config(config, tmp_path / "recovered") + cfg = yaml.safe_load(restored.read_text()) + cfg["commission_rate"] = 0.001 + restored.write_text(yaml.safe_dump(cfg)) + with pytest.raises(StateError, match="configuration"): + restore_state(restored, backup) + assert not (tmp_path / "recovered").exists() + + +def test_recovery_cli_round_trip_and_missing_authority_fail_closed(tmp_path, capsys): + config, _, state, _ = account(tmp_path) + main(["verify", "--config", str(config)]) + assert json.loads(capsys.readouterr().out)["replay_verified"] + backup = tmp_path / "backup" + main(["backup", "--config", str(config), "--out", str(backup)]) + assert json.loads(capsys.readouterr().out)["steps"] == 1 + restored = restored_config(config, tmp_path / "restored") + main(["restore", "--config", str(restored), "--backup", str(backup)]) + assert json.loads(capsys.readouterr().out)["projection_status"] == "complete" + (state / "execution_log.json").unlink() + with pytest.raises((StateError, OSError)): + backup_state(config, tmp_path / "invalid") + assert not (tmp_path / "invalid").exists() + + +def test_migrated_historical_archive_is_required_and_preserved_in_backup(tmp_path): + config, _, state, _ = compatibility_case(tmp_path) + expected = run_step(config).portfolio + authority = files(state) + backup = tmp_path / "historical-backup" + saved = backup_state(config, backup) + assert len(saved["files"]) == 2 + archive = next(backup.glob("execution_log.v*.json")) + assert archive.read_bytes() == authority[archive.name] + restored = restored_config(config, tmp_path / "recovered") + restore_state(restored, backup) + assert status(restored).to_dict() == expected.to_dict() + archive.unlink() + with pytest.raises(StateError, match="archive is missing"): + restore_state(restored_config(config, tmp_path / "invalid"), backup) + assert not (tmp_path / "invalid").exists() + + +def test_nested_release_archives_survive_independent_restore(tmp_path): + config, _, state, historical_bytes = compatibility_case(tmp_path) + historical = json.loads(historical_bytes) + previous = { + **historical, + "quant_paper_sim_version": PREVIOUS_PAPER_SIM_VERSION, + "quant_execution_version": PREVIOUS_EXECUTION_VERSION, + "migration": { + "kind": PREVIOUS_COMPAT_MIGRATION_KIND, + "replay_profile": HISTORICAL_REPLAY_PROFILE, + "source_schema": LOG_SCHEMA, + "source_quant_paper_sim_version": "0.2.0", + "source_quant_execution_version": "0.2.0", + "source_content_sha256": historical["content_sha256"], + "source_file_sha256": hashlib.sha256(historical_bytes).hexdigest(), + "source_archive": f"execution_log.v0.2.0.{historical['content_sha256']}.json", + }, + } + previous = seal_log(previous) + (state / previous["migration"]["source_archive"]).write_bytes(historical_bytes) + (state / "execution_log.json").write_text(json.dumps(previous), encoding="utf-8") + expected = run_step(config).portfolio + backup = tmp_path / "nested-backup" + saved = backup_state(config, backup) + assert len(saved["files"]) == 3 + restored = restored_config(config, tmp_path / "recovered") + restore_state(restored, backup) + assert status(restored).to_dict() == expected.to_dict() + for name in saved["files"]: + assert (tmp_path / "recovered" / name).read_bytes() == (state / name).read_bytes() + + +@pytest.mark.parametrize("phase", ["before_authority", "after_authority"]) +def test_killed_writer_releases_lock_and_retry_matches_uninterrupted_account(tmp_path, phase): + config, signal, state, first = account(tmp_path) + backup = tmp_path / "backup" + backup_state(config, backup) + reference_config = restored_config(config, tmp_path / "reference") + restore_state(reference_config, backup) + write_signal(signal, as_of="2025-03-04", targets=[("600519.SH", 0.3, 11)]) + expected = run_step(reference_config).portfolio + ready = tmp_path / "writer-ready" + code = """ +import sys, time +from pathlib import Path +from quant_paper_sim import engine +real = engine.atomic_write_json +def pause(path, payload, **kwargs): + if path.name == 'execution_log.json': + if sys.argv[3] == 'after_authority': + real(path, payload, **kwargs) + Path(sys.argv[2]).write_text('ready') + time.sleep(30) + return real(path, payload, **kwargs) +engine.atomic_write_json = pause +engine.run_step(Path(sys.argv[1])) +""" + process = subprocess.Popen( + [sys.executable, "-c", code, str(config), str(ready), phase], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + try: + deadline = time.monotonic() + 15 + while not ready.exists() and process.poll() is None and time.monotonic() < deadline: + time.sleep(0.02) + assert ready.exists(), "writer did not reach the authority commit boundary" + with pytest.raises(StateError, match="already"): + run_step(config) + process.kill() + process.communicate(timeout=5) + finally: + if process.poll() is None: + process.kill() + process.communicate(timeout=5) + assert (state / ".paper_commit_pending.json").is_file() + assert status(config).to_dict() == ( + first.to_dict() if phase == "before_authority" else expected.to_dict() + ) + assert run_step(config).portfolio.to_dict() == expected.to_dict() + sealed = (state / "execution_log.json").read_bytes() + assert run_step(config).portfolio.to_dict() == expected.to_dict() + assert (state / "execution_log.json").read_bytes() == sealed + assert verify_state(config)["projection_status"] == "complete"