diff --git a/src/costlog.py b/src/costlog.py index 7174ab7..791052e 100644 --- a/src/costlog.py +++ b/src/costlog.py @@ -18,10 +18,22 @@ CLI: python -m src.costlog demo # örnek satırlar ekle (sonra sil) """ from __future__ import annotations +import contextlib import json import os +import tempfile +import time from datetime import datetime, timezone +try: # POSIX + import fcntl +except ImportError: + fcntl = None +try: # Windows + import msvcrt +except ImportError: + msvcrt = None + from .pricing import (Usage, cost_usd, price_table_rows, PRICING_UPDATED, PRICING_SOURCE, OFFPEAK_FACTOR) @@ -45,6 +57,42 @@ def _now_iso() -> str: return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") +@contextlib.contextmanager +def _file_lock(target: str): + """Süreçler-arası eksklüzif kilit (AUDIT EXP-007 #28): id-atama + append kritik + bölümünü serileştirir → duplicate run_id + iç-içe append (bozuk satır) önlenir. + fcntl (POSIX) / msvcrt (Windows); ikisi de yoksa no-op (yalnız tek-süreç güvence).""" + lockpath = target + ".lock" + d = os.path.dirname(lockpath) + if d: + os.makedirs(d, exist_ok=True) + f = open(lockpath, "a+") + try: + if fcntl is not None: + fcntl.flock(f.fileno(), fcntl.LOCK_EX) + elif msvcrt is not None: + f.seek(0) + for _ in range(200): # ~10s dene (LK_LOCK zaten bloklar; NBLCK ile döngü) + try: + msvcrt.locking(f.fileno(), msvcrt.LK_NBLCK, 1) + break + except OSError: + time.sleep(0.05) + yield + finally: + try: + if fcntl is not None: + fcntl.flock(f.fileno(), fcntl.LOCK_UN) + elif msvcrt is not None: + f.seek(0) + try: + msvcrt.locking(f.fileno(), msvcrt.LK_UNLCK, 1) + except OSError: + pass + finally: + f.close() + + def _load(ledger: str = LEDGER) -> list[dict]: if not os.path.exists(ledger): return [] @@ -79,10 +127,9 @@ def record(module: str, model: str, usage: Usage, items: int = 1, *, ts: str | None = None, ledger: str = LEDGER, maliyet: str = MALIYET) -> dict: """Bir run'ı kaydet: maliyet+birim maliyet hesapla, JSONL'e ekle, Maliyet.md render et.""" - runs = _load(ledger) - usd = cost_usd(model, usage, tier) + usd = cost_usd(model, usage, tier) # saf hesap — kilidin DIŞINDA rec = { - "run_id": _next_id(runs), + "run_id": None, # kilit içinde atanır (yarış önleme #28) "ts": ts or _now_iso(), "module": module, "model": model, @@ -96,10 +143,16 @@ def record(module: str, model: str, usage: Usage, items: int = 1, *, "quality": quality or {}, "note": note, } - os.makedirs(os.path.dirname(ledger), exist_ok=True) - with open(ledger, "a", encoding="utf-8") as f: - f.write(json.dumps(rec, ensure_ascii=False) + "\n") - render(ledger, maliyet) + d = os.path.dirname(ledger) + if d: + os.makedirs(d, exist_ok=True) + # KRİTİK BÖLÜM: id-atama (max-scan) + append tek kilit altında → eşzamanlı iki + # süreç aynı id'yi almaz, satırlar iç-içe girmez (#28). + with _file_lock(ledger): + rec["run_id"] = _next_id(_load(ledger)) + with open(ledger, "a", encoding="utf-8") as f: + f.write(json.dumps(rec, ensure_ascii=False) + "\n") + render(ledger, maliyet) # kilit DIŞINDA + atomik (aşağı) return rec @@ -195,7 +248,12 @@ def render(ledger: str = LEDGER, maliyet: str = MALIYET) -> None: """runs.jsonl'dan Maliyet.md'nin AUTO bloklarını yeniden üret.""" if not os.path.exists(maliyet) or os.path.getsize(maliyet) == 0: _init_maliyet(maliyet) - runs = _load(ledger) + # Savunmacı (AUDIT #28/#29): tablolar hard-key erişir; eksik-alanlı (geçerli-JSON + # ama kısmi/elle-düzenlenmiş) satır tüm render'ı çökertmesin → böyle satırları + # tablolardan ATLA (yine de _next_id bunları _load ile görür, id çakışmaz). + _need = {"run_id", "ts", "module", "model", "tier", "items", "usage", + "cost_usd", "unit_cost_usd"} + runs = [r for r in _load(ledger) if isinstance(r, dict) and _need <= r.keys()] with open(maliyet, encoding="utf-8") as f: text = f.read() text = _replace_block(text, "PRICING", _price_table()) @@ -205,8 +263,17 @@ def render(ledger: str = LEDGER, maliyet: str = MALIYET) -> None: text = _replace_block(text, "STAMP", f"_Son güncelleme: {_now_iso()} · toplam run: {len(runs)} · " f"bu görünüm `runs.jsonl`'dan otomatik üretildi._") - with open(maliyet, "w", encoding="utf-8") as f: - f.write(text) + # ATOMİK yaz (AUDIT #28): temp'e yaz + os.replace → eşzamanlı render yarım/bozuk + # Maliyet.md bırakmaz (os.replace atomiktir). + d = os.path.dirname(maliyet) or "." + fd, tmp = tempfile.mkstemp(dir=d, suffix=".md.tmp") + try: + with os.fdopen(fd, "w", encoding="utf-8") as f: + f.write(text) + os.replace(tmp, maliyet) + finally: + if os.path.exists(tmp): + os.remove(tmp) def _init_maliyet(path: str) -> None: diff --git a/tests/unit/test_costlog.py b/tests/unit/test_costlog.py new file mode 100644 index 0000000..669527f --- /dev/null +++ b/tests/unit/test_costlog.py @@ -0,0 +1,70 @@ +"""costlog testleri (AUDIT EXP-007 #28 + #29 kapsam-boşluğu). Hepsi offline (temp +dosya), gerçek Obsidian vault'a dokunmaz.""" +import os +import tempfile +import unittest +import warnings + +import src.costlog as costlog +from src.pricing import Usage + + +class CostlogTests(unittest.TestCase): + def _paths(self, d): + return os.path.join(d, "runs.jsonl"), os.path.join(d, "Maliyet.md") + + def test_sequential_ids_and_unit_cost(self): + with tempfile.TemporaryDirectory() as d: + L, M = self._paths(d) + r1 = costlog.record("ozet", "deepseek-chat", + Usage(input_cache_miss=1000, output=500), items=10, + ledger=L, maliyet=M) + r2 = costlog.record("chat", "deepseek-chat", + Usage(input_cache_miss=1000, output=500), items=1, + ledger=L, maliyet=M) + self.assertEqual(r1["run_id"], "R0001") + self.assertEqual(r2["run_id"], "R0002") # #28: monoton, çakışmasız + self.assertAlmostEqual(r1["unit_cost_usd"], round(r1["cost_usd"] / 10, 6)) + self.assertTrue(os.path.exists(M) and os.path.exists(L)) + + def test_unknown_model_does_not_crash_or_drop(self): + with tempfile.TemporaryDirectory() as d: + L, M = self._paths(d) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + r = costlog.record("ozet", "gpt-yok", Usage(output=1), ledger=L, maliyet=M) + self.assertEqual(r["cost_usd"], 0.0) # #R2: crash yok, 0 maliyet + self.assertEqual(costlog._load(L)[0]["run_id"], "R0001") # kayıt DÜŞMEDİ + + def test_render_atomic_no_tmp_leftover(self): + with tempfile.TemporaryDirectory() as d: + L, M = self._paths(d) + costlog.record("ozet", "deepseek-chat", Usage(output=1), ledger=L, maliyet=M) + leftovers = [f for f in os.listdir(d) if f.endswith(".tmp")] + self.assertEqual(leftovers, []) # #28: temp temizlendi + + def test_corrupt_line_skipped(self): + with tempfile.TemporaryDirectory() as d: + L, _ = self._paths(d) + with open(L, "w", encoding="utf-8") as f: + f.write('{"run_id":"R1","cost_usd":0.1}\n') + f.write('YARIM {bozuk\n') + f.write('{"run_id":"R2","cost_usd":0.2}\n') + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + rows = costlog._load(L) + self.assertEqual([r["run_id"] for r in rows], ["R1", "R2"]) + + def test_next_id_after_corrupt(self): + with tempfile.TemporaryDirectory() as d: + L, M = self._paths(d) + with open(L, "w", encoding="utf-8") as f: + f.write('{"run_id":"R0007"}\nBOZUK\n') + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + r = costlog.record("ozet", "deepseek-chat", Usage(output=1), ledger=L, maliyet=M) + self.assertEqual(r["run_id"], "R0008") # max+1, bozuk satıra rağmen + + +if __name__ == "__main__": + unittest.main()