#28 süreçler-arası dosya kilidi (id-yarışı) + atomik render (os.replace) + eksik-satır savunması. Closes #28
Browse files at this commit8a9d0e9f17b95c0678f0eda2b64516a46ede032bParent: 8fb6156- fix
- #28 süreçler-arası dosya kilidi (id-yarışı) + atomik render (os.replace) + eksik-satır savunması. Closes #28
2 changed files +147 -10
- src/costlog.py +77 -10
- tests/unit/test_costlog.py +70 -0
src/costlog.pymodified+77 -10
| @@ -18,10 +18,22 @@ CLI: | |||
| 18 | python -m src.costlog demo # örnek satırlar ekle (sonra sil) | 18 | python -m src.costlog demo # örnek satırlar ekle (sonra sil) |
| 19 | """ | 19 | """ |
| 20 | from __future__ import annotations | 20 | from __future__ import annotations |
| 21 | +import contextlib | ||
| 21 | import json | 22 | import json |
| 22 | import os | 23 | import os |
| 24 | +import tempfile | ||
| 25 | +import time | ||
| 23 | from datetime import datetime, timezone | 26 | from datetime import datetime, timezone |
| 24 | 27 | ||
| 28 | +try: # POSIX | ||
| 29 | + import fcntl | ||
| 30 | +except ImportError: | ||
| 31 | + fcntl = None | ||
| 32 | +try: # Windows | ||
| 33 | + import msvcrt | ||
| 34 | +except ImportError: | ||
| 35 | + msvcrt = None | ||
| 36 | + | ||
| 25 | from .pricing import (Usage, cost_usd, price_table_rows, | 37 | from .pricing import (Usage, cost_usd, price_table_rows, |
| 26 | PRICING_UPDATED, PRICING_SOURCE, OFFPEAK_FACTOR) | 38 | PRICING_UPDATED, PRICING_SOURCE, OFFPEAK_FACTOR) |
| 27 | 39 | ||
| @@ -45,6 +57,42 @@ def _now_iso() -> str: | |||
| 45 | return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") | 57 | return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") |
| 46 | 58 | ||
| 47 | 59 | ||
| 60 | +@contextlib.contextmanager | ||
| 61 | +def _file_lock(target: str): | ||
| 62 | + """Süreçler-arası eksklüzif kilit (AUDIT EXP-007 #28): id-atama + append kritik | ||
| 63 | + bölümünü serileştirir → duplicate run_id + iç-içe append (bozuk satır) önlenir. | ||
| 64 | + fcntl (POSIX) / msvcrt (Windows); ikisi de yoksa no-op (yalnız tek-süreç güvence).""" | ||
| 65 | + lockpath = target + ".lock" | ||
| 66 | + d = os.path.dirname(lockpath) | ||
| 67 | + if d: | ||
| 68 | + os.makedirs(d, exist_ok=True) | ||
| 69 | + f = open(lockpath, "a+") | ||
| 70 | + try: | ||
| 71 | + if fcntl is not None: | ||
| 72 | + fcntl.flock(f.fileno(), fcntl.LOCK_EX) | ||
| 73 | + elif msvcrt is not None: | ||
| 74 | + f.seek(0) | ||
| 75 | + for _ in range(200): # ~10s dene (LK_LOCK zaten bloklar; NBLCK ile döngü) | ||
| 76 | + try: | ||
| 77 | + msvcrt.locking(f.fileno(), msvcrt.LK_NBLCK, 1) | ||
| 78 | + break | ||
| 79 | + except OSError: | ||
| 80 | + time.sleep(0.05) | ||
| 81 | + yield | ||
| 82 | + finally: | ||
| 83 | + try: | ||
| 84 | + if fcntl is not None: | ||
| 85 | + fcntl.flock(f.fileno(), fcntl.LOCK_UN) | ||
| 86 | + elif msvcrt is not None: | ||
| 87 | + f.seek(0) | ||
| 88 | + try: | ||
| 89 | + msvcrt.locking(f.fileno(), msvcrt.LK_UNLCK, 1) | ||
| 90 | + except OSError: | ||
| 91 | + pass | ||
| 92 | + finally: | ||
| 93 | + f.close() | ||
| 94 | + | ||
| 95 | + | ||
| 48 | def _load(ledger: str = LEDGER) -> list[dict]: | 96 | def _load(ledger: str = LEDGER) -> list[dict]: |
| 49 | if not os.path.exists(ledger): | 97 | if not os.path.exists(ledger): |
| 50 | return [] | 98 | return [] |
| @@ -79,10 +127,9 @@ def record(module: str, model: str, usage: Usage, items: int = 1, *, | |||
| 79 | ts: str | None = None, ledger: str = LEDGER, | 127 | ts: str | None = None, ledger: str = LEDGER, |
| 80 | maliyet: str = MALIYET) -> dict: | 128 | maliyet: str = MALIYET) -> dict: |
| 81 | """Bir run'ı kaydet: maliyet+birim maliyet hesapla, JSONL'e ekle, Maliyet.md render et.""" | 129 | """Bir run'ı kaydet: maliyet+birim maliyet hesapla, JSONL'e ekle, Maliyet.md render et.""" |
| 82 | - runs = _load(ledger) | 130 | + usd = cost_usd(model, usage, tier) # saf hesap — kilidin DIŞINDA |
| 83 | - usd = cost_usd(model, usage, tier) | ||
| 84 | rec = { | 131 | rec = { |
| 85 | - "run_id": _next_id(runs), | 132 | + "run_id": None, # kilit içinde atanır (yarış önleme #28) |
| 86 | "ts": ts or _now_iso(), | 133 | "ts": ts or _now_iso(), |
| 87 | "module": module, | 134 | "module": module, |
| 88 | "model": model, | 135 | "model": model, |
| @@ -96,10 +143,16 @@ def record(module: str, model: str, usage: Usage, items: int = 1, *, | |||
| 96 | "quality": quality or {}, | 143 | "quality": quality or {}, |
| 97 | "note": note, | 144 | "note": note, |
| 98 | } | 145 | } |
| 99 | - os.makedirs(os.path.dirname(ledger), exist_ok=True) | 146 | + d = os.path.dirname(ledger) |
| 100 | - with open(ledger, "a", encoding="utf-8") as f: | 147 | + if d: |
| 101 | - f.write(json.dumps(rec, ensure_ascii=False) + "\n") | 148 | + os.makedirs(d, exist_ok=True) |
| 102 | - render(ledger, maliyet) | 149 | + # KRİTİK BÖLÜM: id-atama (max-scan) + append tek kilit altında → eşzamanlı iki |
| 150 | + # süreç aynı id'yi almaz, satırlar iç-içe girmez (#28). | ||
| 151 | + with _file_lock(ledger): | ||
| 152 | + rec["run_id"] = _next_id(_load(ledger)) | ||
| 153 | + with open(ledger, "a", encoding="utf-8") as f: | ||
| 154 | + f.write(json.dumps(rec, ensure_ascii=False) + "\n") | ||
| 155 | + render(ledger, maliyet) # kilit DIŞINDA + atomik (aşağı) | ||
| 103 | return rec | 156 | return rec |
| 104 | 157 | ||
| 105 | 158 | ||
| @@ -195,7 +248,12 @@ def render(ledger: str = LEDGER, maliyet: str = MALIYET) -> None: | |||
| 195 | """runs.jsonl'dan Maliyet.md'nin AUTO bloklarını yeniden üret.""" | 248 | """runs.jsonl'dan Maliyet.md'nin AUTO bloklarını yeniden üret.""" |
| 196 | if not os.path.exists(maliyet) or os.path.getsize(maliyet) == 0: | 249 | if not os.path.exists(maliyet) or os.path.getsize(maliyet) == 0: |
| 197 | _init_maliyet(maliyet) | 250 | _init_maliyet(maliyet) |
| 198 | - runs = _load(ledger) | 251 | + # Savunmacı (AUDIT #28/#29): tablolar hard-key erişir; eksik-alanlı (geçerli-JSON |
| 252 | + # ama kısmi/elle-düzenlenmiş) satır tüm render'ı çökertmesin → böyle satırları | ||
| 253 | + # tablolardan ATLA (yine de _next_id bunları _load ile görür, id çakışmaz). | ||
| 254 | + _need = {"run_id", "ts", "module", "model", "tier", "items", "usage", | ||
| 255 | + "cost_usd", "unit_cost_usd"} | ||
| 256 | + runs = [r for r in _load(ledger) if isinstance(r, dict) and _need <= r.keys()] | ||
| 199 | with open(maliyet, encoding="utf-8") as f: | 257 | with open(maliyet, encoding="utf-8") as f: |
| 200 | text = f.read() | 258 | text = f.read() |
| 201 | text = _replace_block(text, "PRICING", _price_table()) | 259 | text = _replace_block(text, "PRICING", _price_table()) |
| @@ -205,8 +263,17 @@ def render(ledger: str = LEDGER, maliyet: str = MALIYET) -> None: | |||
| 205 | text = _replace_block(text, "STAMP", | 263 | text = _replace_block(text, "STAMP", |
| 206 | f"_Son güncelleme: {_now_iso()} · toplam run: {len(runs)} · " | 264 | f"_Son güncelleme: {_now_iso()} · toplam run: {len(runs)} · " |
| 207 | f"bu görünüm `runs.jsonl`'dan otomatik üretildi._") | 265 | f"bu görünüm `runs.jsonl`'dan otomatik üretildi._") |
| 208 | - with open(maliyet, "w", encoding="utf-8") as f: | 266 | + # ATOMİK yaz (AUDIT #28): temp'e yaz + os.replace → eşzamanlı render yarım/bozuk |
| 209 | - f.write(text) | 267 | + # Maliyet.md bırakmaz (os.replace atomiktir). |
| 268 | + d = os.path.dirname(maliyet) or "." | ||
| 269 | + fd, tmp = tempfile.mkstemp(dir=d, suffix=".md.tmp") | ||
| 270 | + try: | ||
| 271 | + with os.fdopen(fd, "w", encoding="utf-8") as f: | ||
| 272 | + f.write(text) | ||
| 273 | + os.replace(tmp, maliyet) | ||
| 274 | + finally: | ||
| 275 | + if os.path.exists(tmp): | ||
| 276 | + os.remove(tmp) | ||
| 210 | 277 | ||
| 211 | 278 | ||
| 212 | def _init_maliyet(path: str) -> None: | 279 | def _init_maliyet(path: str) -> None: |
tests/unit/test_costlog.pyadded+70 -0
| @@ -0,0 +1,70 @@ | |||
| 1 | +"""costlog testleri (AUDIT EXP-007 #28 + #29 kapsam-boşluğu). Hepsi offline (temp | ||
| 2 | +dosya), gerçek Obsidian vault'a dokunmaz.""" | ||
| 3 | +import os | ||
| 4 | +import tempfile | ||
| 5 | +import unittest | ||
| 6 | +import warnings | ||
| 7 | + | ||
| 8 | +import src.costlog as costlog | ||
| 9 | +from src.pricing import Usage | ||
| 10 | + | ||
| 11 | + | ||
| 12 | +class CostlogTests(unittest.TestCase): | ||
| 13 | + def _paths(self, d): | ||
| 14 | + return os.path.join(d, "runs.jsonl"), os.path.join(d, "Maliyet.md") | ||
| 15 | + | ||
| 16 | + def test_sequential_ids_and_unit_cost(self): | ||
| 17 | + with tempfile.TemporaryDirectory() as d: | ||
| 18 | + L, M = self._paths(d) | ||
| 19 | + r1 = costlog.record("ozet", "deepseek-chat", | ||
| 20 | + Usage(input_cache_miss=1000, output=500), items=10, | ||
| 21 | + ledger=L, maliyet=M) | ||
| 22 | + r2 = costlog.record("chat", "deepseek-chat", | ||
| 23 | + Usage(input_cache_miss=1000, output=500), items=1, | ||
| 24 | + ledger=L, maliyet=M) | ||
| 25 | + self.assertEqual(r1["run_id"], "R0001") | ||
| 26 | + self.assertEqual(r2["run_id"], "R0002") # #28: monoton, çakışmasız | ||
| 27 | + self.assertAlmostEqual(r1["unit_cost_usd"], round(r1["cost_usd"] / 10, 6)) | ||
| 28 | + self.assertTrue(os.path.exists(M) and os.path.exists(L)) | ||
| 29 | + | ||
| 30 | + def test_unknown_model_does_not_crash_or_drop(self): | ||
| 31 | + with tempfile.TemporaryDirectory() as d: | ||
| 32 | + L, M = self._paths(d) | ||
| 33 | + with warnings.catch_warnings(): | ||
| 34 | + warnings.simplefilter("ignore") | ||
| 35 | + r = costlog.record("ozet", "gpt-yok", Usage(output=1), ledger=L, maliyet=M) | ||
| 36 | + self.assertEqual(r["cost_usd"], 0.0) # #R2: crash yok, 0 maliyet | ||
| 37 | + self.assertEqual(costlog._load(L)[0]["run_id"], "R0001") # kayıt DÜŞMEDİ | ||
| 38 | + | ||
| 39 | + def test_render_atomic_no_tmp_leftover(self): | ||
| 40 | + with tempfile.TemporaryDirectory() as d: | ||
| 41 | + L, M = self._paths(d) | ||
| 42 | + costlog.record("ozet", "deepseek-chat", Usage(output=1), ledger=L, maliyet=M) | ||
| 43 | + leftovers = [f for f in os.listdir(d) if f.endswith(".tmp")] | ||
| 44 | + self.assertEqual(leftovers, []) # #28: temp temizlendi | ||
| 45 | + | ||
| 46 | + def test_corrupt_line_skipped(self): | ||
| 47 | + with tempfile.TemporaryDirectory() as d: | ||
| 48 | + L, _ = self._paths(d) | ||
| 49 | + with open(L, "w", encoding="utf-8") as f: | ||
| 50 | + f.write('{"run_id":"R1","cost_usd":0.1}\n') | ||
| 51 | + f.write('YARIM {bozuk\n') | ||
| 52 | + f.write('{"run_id":"R2","cost_usd":0.2}\n') | ||
| 53 | + with warnings.catch_warnings(): | ||
| 54 | + warnings.simplefilter("ignore") | ||
| 55 | + rows = costlog._load(L) | ||
| 56 | + self.assertEqual([r["run_id"] for r in rows], ["R1", "R2"]) | ||
| 57 | + | ||
| 58 | + def test_next_id_after_corrupt(self): | ||
| 59 | + with tempfile.TemporaryDirectory() as d: | ||
| 60 | + L, M = self._paths(d) | ||
| 61 | + with open(L, "w", encoding="utf-8") as f: | ||
| 62 | + f.write('{"run_id":"R0007"}\nBOZUK\n') | ||
| 63 | + with warnings.catch_warnings(): | ||
| 64 | + warnings.simplefilter("ignore") | ||
| 65 | + r = costlog.record("ozet", "deepseek-chat", Usage(output=1), ledger=L, maliyet=M) | ||
| 66 | + self.assertEqual(r["run_id"], "R0008") # max+1, bozuk satıra rağmen | ||
| 67 | + | ||
| 68 | + | ||
| 69 | +if __name__ == "__main__": | ||
| 70 | + unittest.main() | ||