Skip to content

Universal SEO skill for Claude Code. 26 sub-skills + 19 sub-agents covering technical SEO, E-E-A-T, schema, GEO/AEO, agent readiness (Lighthouse Agentic Browsing, WebMCP, llms.txt), backlinks, local SEO, e-commerce, international SEO, Google APIs, and PDF/Excel reporting. 9 optional extensions for live SEO data.

fix(banana): lock and atomically write the image cost ledger

Adam Burgessb100ee8b92e8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7c80228..508c9d0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- **The Banana cost ledger had the same defect, with no locking at all.**
+ `extensions/banana/scripts/cost_tracker.py` read and wrote `~/.banana/costs.json` with
+ no file locking on any platform and a non-atomic write. Measured 4 entries lost out of
+ 20 concurrent `log` calls, and 3 of those processes crashed outright with
+ `JSONDecodeError` after reading a half-written file. It is also harder to notice than
+ the DataForSEO case: this ledger carries running aggregates (`total_cost`,
+ `total_images`, `daily`) incremented in the same write as the entry, so a lost write
+ drops both together and the file still looks internally consistent. Given the same
+ treatment: one exclusive lock across the whole read-modify-write in `log`, atomic
+ writes, `msvcrt` fallback with a hard failure when no locking primitive exists, and a
+ corrupt ledger that fails closed instead of raising a bare traceback. `reset` takes the
+ lock but deliberately does not read first, so it still works as the recovery path for a
+ corrupt ledger. `BANANA_HOME` overrides the ledger and pricing paths for the new
+ `tests/test_banana_cost_tracker.py`.
- **Spend ledger lost concurrent writes (`dataforseo_costs.py`).** The ledger took its
file lock twice, once to read and once to write, and released it in between, so two
concurrent `log` calls both read the same ledger and the second silently overwrote the
diff --git a/extensions/banana/scripts/cost_tracker.py b/extensions/banana/scripts/cost_tracker.py
index e1e958a..d4f1c64 100755
--- a/extensions/banana/scripts/cost_tracker.py
+++ b/extensions/banana/scripts/cost_tracker.py
@@ -13,31 +13,148 @@ Usage:
import argparse
import json
+import os
import sys
+import tempfile
+from contextlib import contextmanager
from datetime import datetime, timezone
from pathlib import Path
-LEDGER_PATH = Path.home() / ".banana" / "costs.json"
-PRICING_PATH = Path.home() / ".banana" / "pricing.json"
+try:
+ import fcntl
+except ImportError:
+ fcntl = None
+
+try:
+ import msvcrt
+except ImportError:
+ msvcrt = None
+
+# BANANA_HOME lets tests (and anyone running an isolated budget) point the
+# ledger and pricing config somewhere other than the real ones. Resolved at
+# import.
+BANANA_DIR = Path(os.environ.get("BANANA_HOME") or Path.home() / ".banana")
+LEDGER_PATH = BANANA_DIR / "costs.json"
+LOCK_PATH = BANANA_DIR / "costs.lock"
+PRICING_PATH = BANANA_DIR / "pricing.json"
PRICING_SOURCE = "https://ai.google.dev/gemini-api/docs/pricing"
+
+def _empty_ledger():
+ return {"total_cost": 0.0, "total_images": 0, "entries": [], "daily": {}}
+
+
# Batch API gets 50% discount
BATCH_DISCOUNT = 0.5
-def _load_ledger():
- """Load the cost ledger from disk."""
- if not LEDGER_PATH.exists():
- return {"total_cost": 0.0, "total_images": 0, "entries": [], "daily": {}}
- with open(LEDGER_PATH, "r") as f:
- return json.load(f)
+class LedgerError(RuntimeError):
+ """The cost ledger could not be read or written safely."""
-def _save_ledger(ledger):
- """Save the cost ledger to disk."""
- LEDGER_PATH.parent.mkdir(parents=True, exist_ok=True)
- with open(LEDGER_PATH, "w") as f:
- json.dump(ledger, f, indent=2)
+def _lock(handle, exclusive):
+ """Take an advisory lock on an open handle, blocking until acquired.
+
+ Never degrades to running unlocked: a cost ledger that silently drops
+ entries is worse than one that refuses to run.
+ """
+ if fcntl is not None:
+ fcntl.flock(handle, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
+ elif msvcrt is not None:
+ # msvcrt has no shared mode, so readers take an exclusive lock too.
+ # LK_LOCK retries 10 times at 1s intervals, then raises OSError.
+ handle.seek(0)
+ msvcrt.locking(handle.fileno(), msvcrt.LK_LOCK, 1)
+ else:
+ raise LedgerError(
+ "No file-locking primitive available (neither fcntl nor msvcrt). "
+ "Refusing to touch the cost ledger unlocked."
+ )
+
+
+def _unlock(handle):
+ if fcntl is not None:
+ fcntl.flock(handle, fcntl.LOCK_UN)
+ elif msvcrt is not None:
+ handle.seek(0)
+ msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
+
+
+def _read_ledger():
+ """Read the ledger. Caller must hold the lock."""
+ if not LEDGER_PATH.exists():
+ return _empty_ledger()
+ try:
+ with open(LEDGER_PATH, "r") as f:
+ ledger = json.load(f)
+ except json.JSONDecodeError as exc:
+ raise LedgerError(
+ f"Cost ledger {LEDGER_PATH} is not valid JSON ({exc}). Refusing to "
+ "continue from a zero balance, which would under-report spend. "
+ "Inspect the file, then repair or remove it."
+ ) from exc
+ if not isinstance(ledger, dict) or not isinstance(ledger.get("entries"), list):
+ raise LedgerError(
+ f"Cost ledger {LEDGER_PATH} has an unexpected shape (no 'entries' "
+ "list). Inspect the file, then repair or remove it."
+ )
+ # Tolerate ledgers written before a field existed.
+ ledger.setdefault("total_cost", 0.0)
+ ledger.setdefault("total_images", 0)
+ ledger.setdefault("daily", {})
+ return ledger
+
+
+def _write_ledger(ledger):
+ """Write the ledger atomically. Caller must hold the exclusive lock.
+
+ tempfile + os.replace so a crash mid-write can never leave a truncated,
+ unparseable ledger behind.
+ """
+ BANANA_DIR.mkdir(parents=True, exist_ok=True)
+ fd, tmp_path = tempfile.mkstemp(dir=str(BANANA_DIR), prefix=".costs.", suffix=".tmp")
+ try:
+ with os.fdopen(fd, "w") as f:
+ json.dump(ledger, f, indent=2)
+ f.flush()
+ os.fsync(f.fileno())
+ os.replace(tmp_path, LEDGER_PATH)
+ except Exception:
+ if os.path.exists(tmp_path):
+ os.unlink(tmp_path)
+ raise
+
+
+@contextmanager
+def _locked_ledger(write=False):
+ """Yield the ledger under ONE lock held across the whole read-modify-write.
+
+ Reading under one lock, dropping it, then re-taking it to write loses
+ entries: two concurrent `log` calls both read the same ledger and the
+ second overwrites the first. This ledger also carries running aggregates
+ (total_cost, total_images, daily), so a lost write drops the entry and its
+ aggregate increment together and the file still looks self-consistent.
+
+ The lock lives in a separate .lock file on purpose. The atomic write
+ replaces the ledger's inode, so a lock held on the ledger itself would not
+ protect the replacement.
+ """
+ BANANA_DIR.mkdir(parents=True, exist_ok=True)
+ with open(LOCK_PATH, "a+") as lock_handle:
+ _lock(lock_handle, exclusive=write)
+ try:
+ ledger = _read_ledger()
+ yield ledger
+ if write:
+ _write_ledger(ledger)
+ finally:
+ _unlock(lock_handle)
+
+
+def _ledger_snapshot():
+ """Read the ledger under a shared lock. For read-only commands."""
+ with _locked_ledger() as ledger:
+ return ledger
def _load_pricing_config():
@@ -85,7 +202,6 @@ def _lookup_cost(model, resolution, batch=False):
def cmd_log(args):
"""Log a generation to the ledger."""
- ledger = _load_ledger()
cost, checked_date = _lookup_cost(args.model, args.resolution, getattr(args, "batch", False))
today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S")
@@ -100,24 +216,29 @@ def cmd_log(args):
"prompt": args.prompt[:100],
}
- ledger["entries"].append(entry)
- ledger["total_cost"] = round(ledger["total_cost"] + cost, 4)
- ledger["total_images"] += 1
+ # Read and write inside one lock, so a concurrent log cannot overwrite this
+ # entry (and its aggregate increments) with a ledger it read beforehand.
+ with _locked_ledger(write=True) as ledger:
+ ledger["entries"].append(entry)
+ ledger["total_cost"] = round(ledger["total_cost"] + cost, 4)
+ ledger["total_images"] += 1
+
+ if today not in ledger["daily"]:
+ ledger["daily"][today] = {"count": 0, "cost": 0.0}
+ ledger["daily"][today]["count"] += 1
+ ledger["daily"][today]["cost"] = round(ledger["daily"][today]["cost"] + cost, 4)
- if today not in ledger["daily"]:
- ledger["daily"][today] = {"count": 0, "cost": 0.0}
- ledger["daily"][today]["count"] += 1
- ledger["daily"][today]["cost"] = round(ledger["daily"][today]["cost"] + cost, 4)
+ total_cost = ledger["total_cost"]
+ total_images = ledger["total_images"]
- _save_ledger(ledger)
- print(json.dumps({"logged": True, "cost": cost, "total_cost": ledger["total_cost"],
- "total_images": ledger["total_images"], "approximate": True,
+ print(json.dumps({"logged": True, "cost": cost, "total_cost": total_cost,
+ "total_images": total_images, "approximate": True,
"pricing_checked_date": checked_date}))
def cmd_summary(args):
"""Show cost summary."""
- ledger = _load_ledger()
+ ledger = _ledger_snapshot()
print(f"Total images: {ledger['total_images']}")
print(f"Total cost: approx ${ledger['total_cost']:.3f}")
print()
@@ -136,7 +257,7 @@ def cmd_summary(args):
def cmd_today(args):
"""Show today's usage."""
- ledger = _load_ledger()
+ ledger = _ledger_snapshot()
today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
daily = ledger.get("daily", {}).get(today, {"count": 0, "cost": 0.0})
print(f"Today ({today}): {daily['count']} images, approx ${daily['cost']:.3f}")
@@ -162,7 +283,16 @@ def cmd_reset(args):
if not args.confirm:
print("Error: Pass --confirm to reset the cost ledger.", file=sys.stderr)
sys.exit(1)
- _save_ledger({"total_cost": 0.0, "total_images": 0, "entries": [], "daily": {}})
+ # Takes the same exclusive lock as `log`, but deliberately does NOT read
+ # first: reset is the recovery path for a corrupt ledger, so it must not
+ # depend on the existing file parsing.
+ BANANA_DIR.mkdir(parents=True, exist_ok=True)
+ with open(LOCK_PATH, "a+") as lock_handle:
+ _lock(lock_handle, exclusive=True)
+ try:
+ _write_ledger(_empty_ledger())
+ finally:
+ _unlock(lock_handle)
print("Cost ledger reset.")
@@ -197,7 +327,12 @@ def main():
args = parser.parse_args()
cmds = {"log": cmd_log, "summary": cmd_summary, "today": cmd_today,
"estimate": cmd_estimate, "reset": cmd_reset}
- cmds[args.command](args)
+ try:
+ cmds[args.command](args)
+ except LedgerError as exc:
+ # Fail closed and loudly rather than under-reporting spend.
+ print(f"Error: {exc}", file=sys.stderr)
+ sys.exit(1)
if __name__ == "__main__":
diff --git a/tests/test_banana_cost_tracker.py b/tests/test_banana_cost_tracker.py
new file mode 100644
index 0000000..905db47
--- /dev/null
+++ b/tests/test_banana_cost_tracker.py
@@ -0,0 +1,217 @@
+"""
+Tests for extensions/banana/scripts/cost_tracker.py — cost-ledger integrity.
+
+Same defect class as tests/test_dataforseo_costs.py, and worse here: this
+ledger had no file locking at all, non-atomic writes, and running aggregates
+(total_cost, total_images, daily) that are incremented alongside each entry.
+A lost write dropped the entry AND its aggregate increments together, so the
+file stayed internally self-consistent while under-reporting spend. Internal
+consistency is therefore not evidence that nothing was lost.
+
+Every test runs against an isolated BANANA_HOME, never the real
+~/.banana/costs.json.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+from concurrent.futures import ThreadPoolExecutor
+from pathlib import Path
+
+import pytest
+
+_REPO = Path(__file__).resolve().parents[1]
+_SCRIPT = _REPO / "extensions" / "banana" / "scripts" / "cost_tracker.py"
+
+MODEL = "gemini-3.1-flash-image-preview"
+COST_1K = 0.039
+
+
+def _seed_pricing(home: Path) -> None:
+ """Write the dated pricing config the tracker requires."""
+ home.mkdir(parents=True, exist_ok=True)
+ (home / "pricing.json").write_text(json.dumps({
+ "checked_date": "2026-08-02",
+ "models": {MODEL: {"512": 0.020, "1K": COST_1K, "2K": 0.078, "4K": 0.156}},
+ }))
+
+
+def _run(home: Path, *argv: str) -> subprocess.CompletedProcess:
+ """Invoke the CLI in a subprocess with an isolated ledger."""
+ if not (home / "pricing.json").exists():
+ _seed_pricing(home)
+ env = dict(os.environ)
+ env["BANANA_HOME"] = str(home)
+ return subprocess.run(
+ [sys.executable, str(_SCRIPT), *argv],
+ capture_output=True,
+ text=True,
+ env=env,
+ )
+
+
+def _ledger(home: Path) -> dict:
+ return json.loads((home / "costs.json").read_text())
+
+
+# ---------------------------------------------------------------------------
+# concurrency
+# ---------------------------------------------------------------------------
+
+
+def test_concurrent_logs_do_not_lose_entries(tmp_path) -> None:
+ """20 concurrent `log` calls must produce exactly 20 entries.
+
+ Fails on the pre-fix code, which had no locking whatsoever.
+ """
+ calls = 20
+
+ with ThreadPoolExecutor(max_workers=calls) as pool:
+ results = list(
+ pool.map(
+ lambda i: _run(
+ tmp_path, "log", "--model", MODEL, "--resolution", "1K",
+ "--prompt", f"call-{i}",
+ ),
+ range(calls),
+ )
+ )
+
+ failed = [r for r in results if r.returncode != 0]
+ assert not failed, f"{len(failed)} log calls failed: {failed[0].stderr}"
+
+ ledger = _ledger(tmp_path)
+ assert len(ledger["entries"]) == calls, (
+ f"lost {calls - len(ledger['entries'])} of {calls} concurrent writes"
+ )
+
+ prompts = sorted(e["prompt"] for e in ledger["entries"])
+ assert prompts == sorted(f"call-{i}" for i in range(calls)), "entries were clobbered"
+
+
+def test_concurrent_logs_keep_aggregates_correct(tmp_path) -> None:
+ """The running aggregates must match the entries after concurrent writes.
+
+ These are the numbers the user actually reads, and they were incremented
+ in the same lost write as the entry itself.
+ """
+ calls = 20
+
+ with ThreadPoolExecutor(max_workers=calls) as pool:
+ list(
+ pool.map(
+ lambda i: _run(
+ tmp_path, "log", "--model", MODEL, "--resolution", "1K",
+ "--prompt", f"call-{i}",
+ ),
+ range(calls),
+ )
+ )
+
+ ledger = _ledger(tmp_path)
+ assert ledger["total_images"] == calls
+ assert ledger["total_cost"] == pytest.approx(calls * COST_1K, abs=1e-4)
+ assert ledger["total_cost"] == pytest.approx(
+ sum(e["cost"] for e in ledger["entries"]), abs=1e-4
+ )
+
+ daily_count = sum(d["count"] for d in ledger["daily"].values())
+ daily_cost = sum(d["cost"] for d in ledger["daily"].values())
+ assert daily_count == calls
+ assert daily_cost == pytest.approx(calls * COST_1K, abs=1e-4)
+
+
+def test_concurrent_log_and_reset_keep_the_ledger_parseable(tmp_path) -> None:
+ """Interleaved writers must never leave a torn/unparseable ledger."""
+ _run(tmp_path, "log", "--model", MODEL, "--resolution", "1K", "--prompt", "seed")
+
+ def job(i: int) -> subprocess.CompletedProcess:
+ if i % 5 == 4:
+ return _run(tmp_path, "reset", "--confirm")
+ return _run(tmp_path, "log", "--model", MODEL, "--resolution", "1K",
+ "--prompt", f"p{i}")
+
+ with ThreadPoolExecutor(max_workers=10) as pool:
+ list(pool.map(job, range(10)))
+
+ ledger = _ledger(tmp_path)
+ assert isinstance(ledger["entries"], list)
+ assert _run(tmp_path, "summary").returncode == 0
+
+
+# ---------------------------------------------------------------------------
+# durability
+# ---------------------------------------------------------------------------
+
+
+def test_corrupt_ledger_is_not_silently_zeroed(tmp_path) -> None:
+ """A truncated ledger must fail closed, not restart the budget at zero."""
+ tmp_path.mkdir(parents=True, exist_ok=True)
+ ledger = tmp_path / "costs.json"
+ ledger.write_text('{"entries": [{"ts": "2026-01-01T00:00:00", "cos')
+
+ result = _run(tmp_path, "log", "--model", MODEL, "--resolution", "1K",
+ "--prompt", "x")
+ assert result.returncode != 0, "corrupt ledger must not be silently accepted"
+ assert "not valid JSON" in result.stderr
+
+ # Left in place for inspection, not overwritten.
+ assert ledger.read_text().endswith('"cos')
+
+
+def test_reset_recovers_a_corrupt_ledger(tmp_path) -> None:
+ """reset must not depend on the existing file parsing.
+
+ It is the documented recovery path, so requiring a readable ledger first
+ would leave a corrupt ledger unrecoverable through the CLI.
+ """
+ tmp_path.mkdir(parents=True, exist_ok=True)
+ (tmp_path / "costs.json").write_text("{ this is not json")
+
+ assert _run(tmp_path, "reset", "--confirm").returncode == 0
+ assert _ledger(tmp_path) == {
+ "total_cost": 0.0, "total_images": 0, "entries": [], "daily": {},
+ }
+
+
+def test_ledger_write_is_atomic_no_temp_files_left(tmp_path) -> None:
+ """The tempfile used for the atomic replace must not accumulate."""
+ for i in range(5):
+ _run(tmp_path, "log", "--model", MODEL, "--resolution", "1K",
+ "--prompt", f"p{i}")
+
+ leftovers = list(tmp_path.glob(".costs.*.tmp"))
+ assert leftovers == [], f"temp files left behind: {leftovers}"
+
+
+def test_missing_aggregate_fields_are_tolerated(tmp_path) -> None:
+ """An older ledger without the aggregate keys must still be loggable."""
+ tmp_path.mkdir(parents=True, exist_ok=True)
+ (tmp_path / "costs.json").write_text('{"entries": []}')
+
+ assert _run(tmp_path, "log", "--model", MODEL, "--resolution", "1K",
+ "--prompt", "x").returncode == 0
+ ledger = _ledger(tmp_path)
+ assert ledger["total_images"] == 1
+ assert ledger["total_cost"] == pytest.approx(COST_1K)
+
+
+# ---------------------------------------------------------------------------
+# portability guard
+# ---------------------------------------------------------------------------
+
+
+def test_locking_is_never_disabled_unconditionally() -> None:
+ """The tracker must never run the ledger unlocked on any platform."""
+ source = _SCRIPT.read_text()
+ assert "import fcntl" in source and "import msvcrt" in source
+ assert "Refusing to touch the cost ledger unlocked" in source
+
+
+def test_isolated_home_is_honoured(tmp_path) -> None:
+ """Tests must never write to the operator's real ~/.banana ledger."""
+ _run(tmp_path, "log", "--model", MODEL, "--resolution", "1K", "--prompt", "x")
+ assert (tmp_path / "costs.json").exists()