From 27c5111e338fe1f711424394e5d5d9ede9c0469d Mon Sep 17 00:00:00 2001 From: PureSaber Date: Tue, 13 Oct 2026 12:37:56 +0800 Subject: [PATCH] Prevent paper init from overwriting existing account evidence --- README.md | 5 +++++ src/quant_paper_sim/cli.py | 2 +- src/quant_paper_sim/engine.py | 7 ++++++- tests/test_init_preserves_history.py | 27 +++++++++++++++++++++++++++ tests/test_instrument_catalog.py | 6 +++++- 5 files changed, 44 insertions(+), 3 deletions(-) create mode 100644 tests/test_init_preserves_history.py diff --git a/README.md b/README.md index cabcc7d..53b75fb 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,11 @@ maintain a second portfolio implementation and it has no live-order path. ## Commands +`init` creates an account only in an empty `state_dir`; it refuses to overwrite an existing +journal, projection, legacy file, or incomplete account. To start over, back up the old account +and configure a separate empty directory. A configuration mismatch is repaired by restoring +the original configuration or creating a separate account, never by resetting its journal. + ```bash python -m pip install --no-deps -r requirements.lock python -m pip check diff --git a/src/quant_paper_sim/cli.py b/src/quant_paper_sim/cli.py index 2bb29b1..2d66987 100644 --- a/src/quant_paper_sim/cli.py +++ b/src/quant_paper_sim/cli.py @@ -17,7 +17,7 @@ def main(argv: list[str] | None = None) -> None: sub = parser.add_subparsers(dest="command", required=True) for command, help_text in ( ("step", "Load research-close signals and execute a paper rebalance"), - ("init", "Reset authoritative paper execution state to cash"), + ("init", "Initialize a new cash account in an empty state directory"), ("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"), diff --git a/src/quant_paper_sim/engine.py b/src/quant_paper_sim/engine.py index 3d321ad..5a40b4d 100644 --- a/src/quant_paper_sim/engine.py +++ b/src/quant_paper_sim/engine.py @@ -120,7 +120,7 @@ def _assert_config_compatible( if log["execution_config"] != _execution_config(cfg, catalog): raise StateError( "execution configuration differs from the authoritative log; " - "run quant-paper init to start a new state" + "restore the original configuration, or back up this account and use a new empty state_dir" ) @@ -589,6 +589,11 @@ def initialize(config_path: Path) -> RebalanceResult: paths = _state_paths(config_path, cfg) initial_capital = float(cfg.get("initial_capital", 100_000)) with state_writer_lock(paths.root): + if any(entry.name != ".paper_state.lock" for entry in paths.root.iterdir()): + raise StateError( + "init requires an empty state directory; existing account files were preserved. " + "Use quant-paper backup, then configure a new empty state_dir for a new account" + ) log = new_log( initial_cash=initial_capital, execution_config=_execution_config(cfg, catalog), diff --git a/tests/test_init_preserves_history.py b/tests/test_init_preserves_history.py new file mode 100644 index 0000000..fe29b76 --- /dev/null +++ b/tests/test_init_preserves_history.py @@ -0,0 +1,27 @@ +import pytest +from test_execution_state import paper_config, write_signal + +from quant_paper_sim.engine import initialize, run_step +from quant_paper_sim.state import StateError + + +def test_reinitialization_keeps_all_existing_account_bytes(tmp_path): + config, signal, state = paper_config(tmp_path) + initialize(config) + write_signal(signal, as_of="2026-07-28", targets=[("000001", 1.0, 10.0)]) + run_step(config) + before = {p.relative_to(state): p.read_bytes() for p in state.rglob("*") if p.is_file()} + with pytest.raises(StateError, match="empty state directory"): + initialize(config) + assert before == {p.relative_to(state): p.read_bytes() for p in state.rglob("*") if p.is_file()} + + +@pytest.mark.parametrize("name", ["portfolio.json", "nav.csv", ".paper_commit_pending.json"]) +def test_partial_or_legacy_state_is_not_erased(tmp_path, name): + config, _, state = paper_config(tmp_path) + state.mkdir() + (state / name).write_bytes(b"existing possibly damaged evidence") + with pytest.raises(StateError, match="empty state directory"): + initialize(config) + assert (state / name).read_bytes() == b"existing possibly damaged evidence" + assert not (state / "execution_log.json").exists() diff --git a/tests/test_instrument_catalog.py b/tests/test_instrument_catalog.py index 7e4a2b3..d28146e 100644 --- a/tests/test_instrument_catalog.py +++ b/tests/test_instrument_catalog.py @@ -403,7 +403,11 @@ def test_three_complete_runs_have_identical_authoritative_and_execution_hashes( ) -> None: config, _, state = paper_case(tmp_path) hashes: list[tuple[str, str, str, str, str]] = [] - for _ in range(3): + original = yaml.safe_load(config.read_text(encoding="utf-8")) + for number in range(3): + # Each deterministic replay starts a separate account; init never resets one. + state = tmp_path / f"replay-{number}" + config.write_text(yaml.safe_dump(original | {"state_dir": str(state)}), encoding="utf-8") initialize(config) run_step(config) log = load_log(state / "execution_log.json")