Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
17 changes: 17 additions & 0 deletions src/quant_paper_sim/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand All @@ -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
Expand Down
176 changes: 176 additions & 0 deletions src/quant_paper_sim/recovery.py
Original file line number Diff line number Diff line change
@@ -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)
Loading
Loading