fix(854-2): M01 키 대장 쓰기 원자적 · 파일 쓰기 중간 실패 때 대장 · 파일 저장 전으로 되돌림 — 묶음 ②

- master_keys.save_book = 임시 파일 → 교체(반쪽 대장 없음 · 빌더도 같은 길)
- Store_Save.save = 대장 → 파일 차례 그대로 · 파일 쓰기가 끊기면 쓴(쓰려던) 파일 · 기계 대 · 대장을 저장 전 글로(대장만 앞서가지 않음)
- 시험 test_854_2_m01_key_book — 첫 파일 · 둘째 파일(반쯤 쓴 뒤) 끊김 = 바이트 그대로 · 끊김 없음 = 대장 · 파일 같이 감

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 16:00:36 +09:00
co-authored by Claude Opus 5.5
parent 9c67cdac64
commit ba6f25b971
3 changed files with 155 additions and 5 deletions
+38 -4
View File
@@ -116,16 +116,50 @@ def save(batch: list[dict]) -> list[dict]:
new = [x for x in new + cache.labor_errors(fresh, gone) if x not in old]
if new:
raise store.StoreError(422, {"errors": new})
if book["다음"] != issued:
mk.save_book(book, book_path)
out = [{"file": name, "version": _write(name, before[name], after[name])} for name in names]
# 대장(원자적) → 파일 · 중간에 끊기면 쓴 것 모두 저장 전으로(대장만 · 파일만 앞서가지 않게)
raw = {n: (store.FOLDER / n).read_bytes() for n in names if not _machine(n)}
book_raw = book_path.read_bytes() if book["다음"] != issued else None
tried: list[str] = []
try:
if book_raw is not None:
mk.save_book(book, book_path)
out = []
for name in names:
tried.append(name)
out.append({"file": name, "version": _write(name, before[name], after[name])})
except BaseException:
_undo(tried, before, after, raw, book_path, book_raw)
raise
# 저장 뒤 — 쓴 파일만 기억에 갈아 끼우고 흔들린 자리를 알려 줘 그 줄만 다시 세게
cache.adopt(store.FOLDER, after, fresh, names, narrowed[2])
return out
def _machine(name: str) -> bool:
return name == mmf.NAME and mmf.here(store.FOLDER) # 기계 = 폴더(826-2)
def _put(path, raw: bytes) -> None:
tmp = path.with_name(f".{path.name}.tmp")
tmp.write_bytes(raw)
os.replace(tmp, path)
def _undo(names, before, after, raw, book_path, book_raw) -> None:
"""쓰기 중간 실패 — 쓴(쓰려던) 파일 · 대장을 저장 전 글로 되돌림."""
for name in names:
if _machine(name):
mmf.write(
store.FOLDER, before[name], after[name]
) # 바뀐 · 더한 · 지운 대를 저장 전으로
else:
_put(store.FOLDER / name, raw[name])
if book_raw is not None:
_put(book_path, book_raw)
def _write(name: str, before: dict, after: dict) -> str:
if name == mmf.NAME and mmf.here(store.FOLDER): # 기계 = 바뀐 대 파일만(826-2)
if _machine(name): # 기계 = 바뀐 대 파일만(826-2)
mmf.write(store.FOLDER, after, before)
return store.version(name)
path = store.FOLDER / name
+4 -1
View File
@@ -7,6 +7,7 @@
from __future__ import annotations
import json
import os
import re
from decimal import Decimal
from pathlib import Path
@@ -77,7 +78,9 @@ def save_book(book: dict, path: Path = BOOK) -> None:
comma = "," if i < len(items) - 1 else ""
lines.append(f" {json.dumps(key)}: {json.dumps(v, ensure_ascii=False)}{comma}")
lines += [" }", "}"]
path.write_text("\n".join(lines) + "\n", encoding="utf-8", newline="\n")
tmp = path.with_name(f".{path.name}.tmp") # 임시 파일 → 교체(원자적 · 끊겨도 반쪽 대장 없음)
tmp.write_text("\n".join(lines) + "\n", encoding="utf-8", newline="\n")
os.replace(tmp, path)
def lookup(book: dict) -> dict:
+113
View File
@@ -0,0 +1,113 @@
"""M01 저장 안전(PLAN 854-2 · 요구 894 걸음 1) — 마스터 사본 폴더에서만 씀.
- 키 대장 · 파일 쓰기: 중간에 끊겨도 대장 · 파일이 저장 전 그대로(대장만 앞서가지 않음).
"""
from __future__ import annotations
import json
import shutil
from pathlib import Path
import pytest
from M01_MasterData import M01_MasterData_Store as store
from M01_MasterData import M01_MasterData_Store_Save as save_mod
REAL = store.FOLDER
OWN = "로직_자체.json"
MACHINE = "EQ000002"
LABOR = "LB000002" # 보통인부
@pytest.fixture
def master(tmp_path: Path, monkeypatch) -> Path:
for path in REAL.glob("*.json"):
if not path.name.startswith("_") or path.name == store.mk.BOOK.name:
shutil.copy(path, tmp_path / path.name)
shutil.copytree(REAL / "기계", tmp_path / "기계")
monkeypatch.setattr(store, "FOLDER", tmp_path)
return tmp_path
def _bytes(folder: Path) -> dict[str, bytes]:
out = {p.name: p.read_bytes() for p in folder.glob("*.json")}
out |= {f"기계/{p.name}": p.read_bytes() for p in (folder / "기계").glob("*.json")}
return out
def _new_logic() -> dict:
return {
"op": "add",
"row": {
"원문번호": "",
"구분": "자체",
"상세구분": "",
"소유": "현장",
"이름": "sub5임시 대장 시험",
"결과단위": "원/㎡",
"출처": "자체",
"입력": [],
"중간": [],
"호표": [
{
"종류": "인력",
"요소": LABOR,
"이름": "보통인부",
"단위": "인",
"수량": "1 / 7",
"비목": "노무비",
}
],
"덧줄": [],
"끝수": None,
},
}
def _batch() -> list[dict]:
"""기계 한 대 고침(기계 폴더) + 자체 로직 새 줄(GX 키 발급 = 대장 바뀜)."""
machine = json.loads((store.FOLDER / "기계" / f"{MACHINE}.json").read_text(encoding="utf-8"))
machine["비고"] = "sub5임시"
return [
{
"file": "기계.json",
"version": store.version("기계.json"),
"changes": [{"op": "edit", "key": MACHINE, "row": machine}],
},
{"file": OWN, "version": store.version(OWN), "changes": [_new_logic()]},
]
@pytest.mark.parametrize("fail_at", [0, 1])
def test_파일_쓰기가_끊기면_대장과_파일이_저장_전_그대로(
master: Path, monkeypatch, fail_at
) -> None:
before = _bytes(master)
real = save_mod._write
calls = []
def broken(name, was, now):
calls.append(name)
if len(calls) - 1 == fail_at:
if fail_at: # 둘째 파일은 쓴 뒤에 끊김(반쯤 쓴 꼴)
real(name, was, now)
raise OSError("디스크 흉내 실패")
return real(name, was, now)
monkeypatch.setattr(save_mod, "_write", broken)
with pytest.raises(OSError):
store.save(_batch())
after = _bytes(master)
assert after == before # 대장 · 기계 · 로직 파일 모두 저장 전 글 그대로
assert not list(master.glob(".*.tmp")) and not list((master / "기계").glob(".*.tmp"))
def test_끊김_없으면_대장과_파일이_같이_간다(master: Path) -> None:
book_before = store.mk.load_book(master / store.mk.BOOK.name)["다음"].get("GX", 1)
store.save(_batch())
book = store.mk.load_book(master / store.mk.BOOK.name)
keys = [r["키"] for r in json.loads((master / OWN).read_text(encoding="utf-8"))["줄"]]
assert f"GX{book_before:06d}" in keys and book["다음"]["GX"] == book_before + 1
machine = json.loads((master / "기계" / f"{MACHINE}.json").read_text(encoding="utf-8"))
assert machine["비고"] == "sub5임시"