Skip to content

World's first open-source, agentic video production system. 12 production pipelines, 100+ tools, 700+ agent skill and production-knowledge files. Turn your AI coding assistant into a full video production studio.

feat(cache): content-addressed cache for reproducible tool outputs (#379)

Aaryan Mehtadec50941413f
diff --git a/lib/asset_cache.py b/lib/asset_cache.py
new file mode 100644
index 00000000..cf05cf6b
--- /dev/null
+++ b/lib/asset_cache.py
@@ -0,0 +1,563 @@
+"""Content-addressed cache for reproducible tool outputs.
+
+Every paid generation tool (FLUX, Imagen, ElevenLabs, Kling, ...) already
+declares the two things needed to know when a call is a repeat: its
+``idempotency_key_fields`` (the inputs that determine the output) and its
+``determinism`` class. Nothing consumed them, so re-running a pipeline with
+the same brief paid the same provider for the same bytes again. This cache
+closes that gap: when a deterministic (or seed-pinned) tool is about to
+produce an artifact it has produced before, the bytes are copied back from
+disk and the API call is skipped.
+
+Keyed by *content*, not by output path. The cache key is derived by the tool
+(``BaseTool.cache_key``) from tool identity + version + the declared
+idempotency fields, so the same prompt/seed/model resolves to the same entry
+no matter where the caller asks the file to land. That is also why an edit
+recomputes only what changed: touch one scene's prompt and only that scene's
+key moves, so every other asset is a hit. There is no dependency graph and no
+scheduler here. Correct keys make selective recompute fall out for free.
+
+Design decisions
+----------------
+
+- **Only reproducible calls are cached.** Deterministic tools always; seeded
+ tools only when a seed is pinned in the inputs (an unpinned seed is
+ effectively stochastic and must not be frozen); stochastic tools never.
+ The eligibility decision lives in the tool wrapper; this module trusts the
+ key it is handed.
+
+- **Manifest is JSONL, rewritten atomically.** One entry per line carrying the
+ content key, the reconstruction metadata (tool, version, model, seed, the
+ original ``cost_usd`` that a hit now saves, and the ToolResult ``data``
+ payload), and LRU timestamps. Mutations rewrite the whole file via
+ ``os.replace`` so readers always see a consistent snapshot.
+
+- **File locking on every mutation.** Concurrent runs against the same cache
+ serialize on ``asset_cache.lock``. Uses ``filelock`` when importable, else a
+ naive ``O_EXCL`` create-file fallback with a polling retry. 60s timeout.
+
+- **Blobs are copied, never hard-linked.** A hard link would share an inode
+ with the caller's output file, so a later in-place rewrite of that file (a
+ normal regeneration) would silently mutate the stored blob. Store and restore
+ both copy, keeping cache content immutable at the cost of the extra disk.
+
+- **LRU eviction at cap.** Default cap is 20 GB, overridable via
+ ``OPENMONTAGE_ASSET_CACHE_MAX_GB``. Ingesting past the cap evicts
+ least-recently-accessed entries until there is room.
+
+- **Off unless asked.** Enabled only when ``OPENMONTAGE_ASSET_CACHE`` is set to
+ a truthy value, so it can never change the behavior of an existing run that
+ did not opt in. The directory honors ``OPENMONTAGE_ASSET_CACHE_DIR``.
+
+Non-goals (intentional for this phase)
+--------------------------------------
+- **Single-artifact tools only.** Tools that emit one file at ``output_path``
+ (the shape of every paid image / audio / video generator here) are cached.
+ Multi-artifact tools (batch image sets, TTS + sidecar metadata) are left for
+ a follow-up rather than guessing a path remap.
+- **No cross-machine sync.** The cache lives on one filesystem; there is no
+ shared-object-store story yet.
+"""
+from __future__ import annotations
+
+import json
+import os
+import shutil
+import tempfile
+import time
+from contextlib import contextmanager
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from typing import Any, Iterator, Optional
+
+try:
+ import filelock # type: ignore
+ _HAVE_FILELOCK = True
+except ImportError:
+ _HAVE_FILELOCK = False
+
+
+# Default 20 GB cap. Overridable via OPENMONTAGE_ASSET_CACHE_MAX_GB.
+_DEFAULT_MAX_TOTAL_BYTES = 20 * 1024 * 1024 * 1024
+
+# Reject ingesting an artifact under this size; almost always a failed or
+# empty generation the caller did not catch.
+_MIN_USABLE_BYTES = 1
+
+
+# ----------------------------------------------------------------------
+# Config resolution
+# ----------------------------------------------------------------------
+
+
+def asset_cache_enabled() -> bool:
+ """Whether the asset cache is active.
+
+ Off by default. Honors ``OPENMONTAGE_ASSET_CACHE``: ``1``/``true``/``yes``/
+ ``on`` (any case) enable it; anything else (including unset) leaves it
+ off, so an existing run that did not opt in behaves exactly as before.
+ """
+ val = os.environ.get("OPENMONTAGE_ASSET_CACHE", "").strip().lower()
+ return val in {"1", "true", "yes", "on"}
+
+
+def default_asset_cache_dir() -> Path:
+ """Resolve the cache directory.
+
+ Honors ``OPENMONTAGE_ASSET_CACHE_DIR`` if set, else
+ ``~/.openmontage/asset_cache``. Kept separate from the clip byte cache
+ (``clips_cache``) so eviction budgets do not contend.
+ """
+ override = os.environ.get("OPENMONTAGE_ASSET_CACHE_DIR")
+ if override:
+ return Path(override).expanduser()
+ return Path.home() / ".openmontage" / "asset_cache"
+
+
+def default_max_total_bytes() -> int:
+ """Resolve the max-cache-size budget.
+
+ Honors ``OPENMONTAGE_ASSET_CACHE_MAX_GB`` (float or int) if set, else the
+ default 20 GB. An invalid override falls back to the default rather than
+ crashing a production run over a bad env var.
+ """
+ override = os.environ.get("OPENMONTAGE_ASSET_CACHE_MAX_GB")
+ if override:
+ try:
+ return int(float(override) * 1024 * 1024 * 1024)
+ except ValueError:
+ pass
+ return _DEFAULT_MAX_TOTAL_BYTES
+
+
+# ----------------------------------------------------------------------
+# Dataclass for one manifest row
+# ----------------------------------------------------------------------
+
+
+@dataclass
+class AssetCacheEntry:
+ """One row in the cache manifest.
+
+ ``key`` is the content hash the tool computed. ``data_json`` is the
+ ToolResult ``data`` payload serialized so a hit can hand back the same
+ structured result the live call would have. ``cost_usd`` is what the
+ original call cost, i.e. what a hit now saves.
+ """
+
+ key: str
+ file_name: str # relative to cache_dir, e.g. "<hash>.png"
+ size_bytes: int
+ added_at: float
+ last_access_at: float
+ tool_name: str = ""
+ tool_version: str = ""
+ model: str = ""
+ seed: Optional[int] = None
+ cost_usd: float = 0.0
+ data_json: str = ""
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+ @classmethod
+ def from_dict(cls, d: dict[str, Any]) -> "AssetCacheEntry":
+ # Tolerate extra fields from future schema evolution; only read the
+ # ones we know about. Missing fields default.
+ seed = d.get("seed", None)
+ try:
+ seed = int(seed) if seed is not None else None
+ except (TypeError, ValueError):
+ seed = None
+ return cls(
+ key=str(d["key"]),
+ file_name=str(d["file_name"]),
+ size_bytes=int(d.get("size_bytes", 0) or 0),
+ added_at=float(d.get("added_at", 0.0) or 0.0),
+ last_access_at=float(
+ d.get("last_access_at", d.get("added_at", 0.0)) or 0.0
+ ),
+ tool_name=str(d.get("tool_name", "") or ""),
+ tool_version=str(d.get("tool_version", "") or ""),
+ model=str(d.get("model", "") or ""),
+ seed=seed,
+ cost_usd=float(d.get("cost_usd", 0.0) or 0.0),
+ data_json=str(d.get("data_json", "") or ""),
+ )
+
+
+# ----------------------------------------------------------------------
+# The cache itself
+# ----------------------------------------------------------------------
+
+
+class AssetCache:
+ """Process-safe, LRU-evicted, content-addressed cache of tool outputs.
+
+ Not a singleton; see ``get_default_asset_cache()`` for the process-level
+ default. Tests that want a pristine cache should instantiate
+ ``AssetCache(cache_dir=tmp_path)`` directly.
+ """
+
+ MANIFEST_NAME = "asset_manifest.jsonl"
+ LOCK_NAME = "asset_cache.lock"
+
+ def __init__(
+ self,
+ cache_dir: Optional[Path] = None,
+ max_total_bytes: Optional[int] = None,
+ ):
+ self.cache_dir = Path(cache_dir) if cache_dir else default_asset_cache_dir()
+ self.max_total_bytes = (
+ int(max_total_bytes)
+ if max_total_bytes is not None
+ else default_max_total_bytes()
+ )
+ self.cache_dir.mkdir(parents=True, exist_ok=True)
+ self.manifest_path = self.cache_dir / self.MANIFEST_NAME
+ self.lock_path = self.cache_dir / self.LOCK_NAME
+
+ # Per-instance runtime counters. Reset when a new AssetCache is built.
+ self.hits = 0
+ self.misses = 0
+ self.evictions_count = 0
+ self.bytes_evicted = 0
+ self.cost_saved_usd = 0.0
+
+ # ------------------------------------------------------------------
+ # Locking
+ # ------------------------------------------------------------------
+
+ @contextmanager
+ def _locked(self, timeout: float = 60.0) -> Iterator[None]:
+ """Acquire an exclusive lock for the duration of the block.
+
+ Prefers ``filelock.FileLock``; falls back to a naive O_EXCL create-file
+ lock with polling retry so the cache still works without ``filelock``
+ installed. The fallback is not reentrant, so do not nest ``_locked()``.
+ """
+ if _HAVE_FILELOCK:
+ lock = filelock.FileLock(str(self.lock_path), timeout=timeout)
+ with lock:
+ yield
+ return
+
+ deadline = time.time() + timeout
+ acquired = False
+ while time.time() < deadline:
+ try:
+ fd = os.open(
+ str(self.lock_path),
+ os.O_CREAT | os.O_EXCL | os.O_WRONLY,
+ )
+ os.close(fd)
+ acquired = True
+ break
+ except FileExistsError:
+ time.sleep(0.05)
+ if not acquired:
+ raise TimeoutError(
+ f"AssetCache: could not acquire lock at {self.lock_path} "
+ f"after {timeout}s"
+ )
+ try:
+ yield
+ finally:
+ try:
+ os.unlink(self.lock_path)
+ except OSError:
+ pass
+
+ # ------------------------------------------------------------------
+ # Manifest I/O (caller holds the lock)
+ # ------------------------------------------------------------------
+
+ def _read_manifest(self) -> dict[str, AssetCacheEntry]:
+ """Read the manifest into a dict keyed by content key.
+
+ Malformed lines are skipped silently; one bad row must not poison the
+ whole manifest. Missing file returns an empty dict (first-run case).
+ """
+ entries: dict[str, AssetCacheEntry] = {}
+ if not self.manifest_path.exists():
+ return entries
+ try:
+ with open(self.manifest_path, "r", encoding="utf-8") as f:
+ for line in f:
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ d = json.loads(line)
+ entry = AssetCacheEntry.from_dict(d)
+ entries[entry.key] = entry
+ except (json.JSONDecodeError, KeyError, TypeError, ValueError):
+ continue
+ except OSError:
+ return {}
+ return entries
+
+ def _write_manifest(self, entries: dict[str, AssetCacheEntry]) -> None:
+ """Rewrite the manifest atomically via a sibling tmpfile + os.replace."""
+ tmp_fd, tmp_name = tempfile.mkstemp(
+ prefix="asset_manifest.", suffix=".tmp", dir=str(self.cache_dir)
+ )
+ try:
+ with os.fdopen(tmp_fd, "w", encoding="utf-8") as f:
+ for entry in entries.values():
+ f.write(json.dumps(entry.to_dict(), ensure_ascii=False) + "\n")
+ os.replace(tmp_name, self.manifest_path)
+ except Exception:
+ try:
+ if os.path.exists(tmp_name):
+ os.unlink(tmp_name)
+ except OSError:
+ pass
+ raise
+
+ # ------------------------------------------------------------------
+ # Public API: try_restore, store, stats
+ # ------------------------------------------------------------------
+
+ def try_restore(self, key: str, dest: Path) -> Optional[dict[str, Any]]:
+ """Materialize a cached artifact for ``key`` into ``dest`` if present.
+
+ Returns the reconstruction metadata (``data``, ``model``, ``seed``,
+ ``cost_usd``, ``tool_name``, ``tool_version``) on a hit, or ``None`` on
+ a miss. On hit the entry's ``last_access_at`` is bumped for LRU. On
+ manifest/filesystem drift (entry present, blob gone) the stale entry is
+ pruned and the call reports a miss so the caller regenerates.
+ """
+ dest = Path(dest)
+ with self._locked():
+ entries = self._read_manifest()
+ entry = entries.get(key)
+ if entry is None:
+ self.misses += 1
+ return None
+
+ blob_path = self.cache_dir / entry.file_name
+ if not blob_path.exists():
+ del entries[key]
+ self._write_manifest(entries)
+ self.misses += 1
+ return None
+
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ if dest.exists() or dest.is_symlink():
+ try:
+ dest.unlink()
+ except OSError:
+ pass
+
+ if not _copy_file(blob_path, dest):
+ # Cannot reach dest, so treat as a miss and let the caller regenerate.
+ # The blob is still valid; leave the entry alone.
+ self.misses += 1
+ return None
+
+ entry.last_access_at = time.time()
+ entries[key] = entry
+ self._write_manifest(entries)
+ self.hits += 1
+ self.cost_saved_usd += entry.cost_usd
+
+ try:
+ data = json.loads(entry.data_json) if entry.data_json else {}
+ except (json.JSONDecodeError, TypeError):
+ data = {}
+ return {
+ "data": data if isinstance(data, dict) else {},
+ "model": entry.model or None,
+ "seed": entry.seed,
+ "cost_usd": entry.cost_usd,
+ "tool_name": entry.tool_name,
+ "tool_version": entry.tool_version,
+ }
+
+ def store(
+ self,
+ key: str,
+ source_path: Path,
+ *,
+ tool_name: str = "",
+ tool_version: str = "",
+ model: str = "",
+ seed: Optional[int] = None,
+ cost_usd: float = 0.0,
+ data: Optional[dict[str, Any]] = None,
+ ) -> bool:
+ """Ingest a freshly produced artifact under ``key``.
+
+ ``source_path`` is the file the tool just wrote to its output path. We
+ do not move or mutate it; the caller keeps its file and the cache
+ holds a second reference via hard link (or copy on cross-drive).
+ Returns ``True`` if stored (or already present), ``False`` on failure
+ (missing/empty source, lock timeout, link/copy failure).
+ """
+ source_path = Path(source_path)
+ if not source_path.exists():
+ return False
+ try:
+ size_bytes = source_path.stat().st_size
+ except OSError:
+ return False
+ if size_bytes < _MIN_USABLE_BYTES:
+ return False
+
+ try:
+ data_json = json.dumps(data or {}, ensure_ascii=False, sort_keys=True)
+ except (TypeError, ValueError):
+ data_json = "{}"
+
+ with self._locked():
+ entries = self._read_manifest()
+
+ if key in entries and (self.cache_dir / entries[key].file_name).exists():
+ entries[key].last_access_at = time.time()
+ self._write_manifest(entries)
+ return True
+
+ self._evict_to_fit_locked(entries, size_bytes)
+
+ # Blob name is the key plus the source extension. Keys are SHA-256
+ # hex, so they are unique and filesystem-safe.
+ ext = source_path.suffix or ""
+ blob_name = f"{key}{ext}"
+ blob_path = self.cache_dir / blob_name
+
+ if blob_path.exists():
+ try:
+ blob_path.unlink()
+ except OSError:
+ return False
+
+ if not _copy_file(source_path, blob_path):
+ return False
+
+ now = time.time()
+ entries[key] = AssetCacheEntry(
+ key=key,
+ file_name=blob_name,
+ size_bytes=size_bytes,
+ added_at=now,
+ last_access_at=now,
+ tool_name=tool_name,
+ tool_version=tool_version,
+ model=model,
+ seed=seed,
+ cost_usd=float(cost_usd or 0.0),
+ data_json=data_json,
+ )
+ self._write_manifest(entries)
+ return True
+
+ def stats(self) -> dict[str, Any]:
+ """Snapshot of cache state plus this session's hit/miss/savings counters."""
+ with self._locked():
+ entries = self._read_manifest()
+ total_bytes = sum(e.size_bytes for e in entries.values())
+ return {
+ "cache_dir": str(self.cache_dir),
+ "entry_count": len(entries),
+ "total_bytes": total_bytes,
+ "total_mb": round(total_bytes / (1024 * 1024), 1),
+ "max_total_bytes": self.max_total_bytes,
+ "max_total_gb": round(self.max_total_bytes / (1024 ** 3), 2),
+ "usage_fraction": (
+ round(total_bytes / self.max_total_bytes, 3)
+ if self.max_total_bytes > 0 else 0.0
+ ),
+ "hits_this_session": self.hits,
+ "misses_this_session": self.misses,
+ "cost_saved_usd_this_session": round(self.cost_saved_usd, 4),
+ "evictions_this_session": self.evictions_count,
+ "bytes_evicted_this_session": self.bytes_evicted,
+ "filelock_backend": "filelock" if _HAVE_FILELOCK else "o_excl_fallback",
+ }
+
+ # ------------------------------------------------------------------
+ # LRU eviction (caller holds the lock)
+ # ------------------------------------------------------------------
+
+ def _evict_to_fit_locked(
+ self, entries: dict[str, AssetCacheEntry], needed_bytes: int
+ ) -> None:
+ """Evict least-recently-accessed entries until ``needed_bytes`` fits.
+
+ Mutates ``entries`` in place. Skips victims whose blob has already
+ vanished (drift) so eviction is best-effort and never blocks a store.
+ """
+ if needed_bytes <= 0:
+ return
+ current_bytes = sum(e.size_bytes for e in entries.values())
+ if current_bytes + needed_bytes <= self.max_total_bytes:
+ return
+
+ sorted_victims = sorted(entries.values(), key=lambda e: e.last_access_at)
+ for victim in sorted_victims:
+ if current_bytes + needed_bytes <= self.max_total_bytes:
+ break
+ blob_path = self.cache_dir / victim.file_name
+ try:
+ if blob_path.exists():
+ blob_path.unlink()
+ except OSError:
+ # In-use on Windows, for instance. Leave it; try the next.
+ continue
+ current_bytes -= victim.size_bytes
+ del entries[victim.key]
+ self.evictions_count += 1
+ self.bytes_evicted += victim.size_bytes
+
+
+# ----------------------------------------------------------------------
+# Module-level helpers
+# ----------------------------------------------------------------------
+
+
+def _copy_file(src: Path, dst: Path) -> bool:
+ """Copy ``src`` to ``dst`` as an independent file. True on success.
+
+ Deliberately a copy, never a hard link. A hard link shares an inode with the
+ cache blob, so a later in-place rewrite of either file (a normal
+ regeneration) would silently mutate the stored bytes and corrupt the entry.
+ The store must stay immutable, which is worth the extra disk. ``copy2``
+ handles cross-drive transparently.
+ """
+ src = Path(src)
+ dst = Path(dst)
+ try:
+ shutil.copy2(str(src), str(dst))
+ return True
+ except (OSError, shutil.SameFileError):
+ return False
+
+
+# ----------------------------------------------------------------------
+# Default-singleton accessor
+# ----------------------------------------------------------------------
+
+
+_DEFAULT_CACHE: Optional[AssetCache] = None
+
+
+def get_default_asset_cache() -> AssetCache:
+ """Return a process-level default ``AssetCache`` at the resolved path.
+
+ Lazily constructed on first call. Tests wanting a pristine cache should
+ instantiate ``AssetCache(cache_dir=tmp_path)`` directly.
+ """
+ global _DEFAULT_CACHE
+ if _DEFAULT_CACHE is None:
+ _DEFAULT_CACHE = AssetCache()
+ return _DEFAULT_CACHE
+
+
+def reset_default_asset_cache() -> None:
+ """Drop the cached singleton so the next accessor re-reads env vars.
+
+ Useful for tests that mutate ``OPENMONTAGE_ASSET_CACHE_DIR``.
+ """
+ global _DEFAULT_CACHE
+ _DEFAULT_CACHE = None
diff --git a/tests/lib/test_asset_cache.py b/tests/lib/test_asset_cache.py
new file mode 100644
index 00000000..663c03ad
--- /dev/null
+++ b/tests/lib/test_asset_cache.py
@@ -0,0 +1,308 @@
+"""Tests for the content-addressed asset cache (lib/asset_cache.py).
+
+These do not touch the network and do not require filelock. They exercise the
+cache's public surface (try_restore, store, stats), content-vs-path keying,
+LRU eviction, manifest persistence, and the enable/config env vars. Cache dirs
+are scoped to pytest's ``tmp_path`` so nothing escapes the test session.
+"""
+from __future__ import annotations
+
+import json
+import os
+import sys
+from pathlib import Path
+
+PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent
+sys.path.insert(0, str(PROJECT_ROOT))
+
+from lib.asset_cache import ( # noqa: E402
+ AssetCache,
+ AssetCacheEntry,
+ _copy_file,
+ asset_cache_enabled,
+ default_asset_cache_dir,
+ default_max_total_bytes,
+ get_default_asset_cache,
+ reset_default_asset_cache,
+)
+
+
+# ----------------------------------------------------------------------
+# Helpers
+# ----------------------------------------------------------------------
+
+
+def _fake_asset(path: Path, payload: bytes) -> Path:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with open(path, "wb") as f:
+ f.write(payload)
+ return path
+
+
+# ----------------------------------------------------------------------
+# Enable / config resolution
+# ----------------------------------------------------------------------
+
+
+def test_disabled_by_default(monkeypatch):
+ monkeypatch.delenv("OPENMONTAGE_ASSET_CACHE", raising=False)
+ assert asset_cache_enabled() is False
+
+
+def test_enabled_by_truthy_values(monkeypatch):
+ for val in ("1", "true", "TRUE", "yes", "On"):
+ monkeypatch.setenv("OPENMONTAGE_ASSET_CACHE", val)
+ assert asset_cache_enabled() is True
+ for val in ("0", "false", "no", "", "off"):
+ monkeypatch.setenv("OPENMONTAGE_ASSET_CACHE", val)
+ assert asset_cache_enabled() is False
+
+
+def test_default_cache_dir_uses_env_override(monkeypatch, tmp_path):
+ monkeypatch.setenv("OPENMONTAGE_ASSET_CACHE_DIR", str(tmp_path / "overridden"))
+ assert default_asset_cache_dir() == tmp_path / "overridden"
+
+
+def test_default_cache_dir_falls_back_to_home(monkeypatch):
+ monkeypatch.delenv("OPENMONTAGE_ASSET_CACHE_DIR", raising=False)
+ assert default_asset_cache_dir() == Path.home() / ".openmontage" / "asset_cache"
+
+
+def test_default_max_total_bytes_respects_and_guards_env(monkeypatch):
+ monkeypatch.setenv("OPENMONTAGE_ASSET_CACHE_MAX_GB", "5")
+ assert default_max_total_bytes() == 5 * 1024 * 1024 * 1024
+ monkeypatch.setenv("OPENMONTAGE_ASSET_CACHE_MAX_GB", "not-a-number")
+ assert default_max_total_bytes() == 20 * 1024 * 1024 * 1024
+
+
+# ----------------------------------------------------------------------
+# Entry round-trip
+# ----------------------------------------------------------------------
+
+
+def test_entry_round_trip_through_dict():
+ entry = AssetCacheEntry(
+ key="abc123",
+ file_name="abc123.png",
+ size_bytes=42,
+ added_at=1000.0,
+ last_access_at=2000.0,
+ tool_name="flux_image",
+ tool_version="0.1.0",
+ model="fal-ai/flux-pro/v1.1",
+ seed=7,
+ cost_usd=0.05,
+ data_json='{"provider": "flux"}',
+ )
+ assert AssetCacheEntry.from_dict(entry.to_dict()) == entry
+
+
+def test_entry_from_dict_tolerates_missing_and_bad_fields():
+ entry = AssetCacheEntry.from_dict(
+ {"key": "x", "file_name": "x.png", "seed": "not-an-int"}
+ )
+ assert entry.key == "x"
+ assert entry.size_bytes == 0
+ assert entry.seed is None
+ assert entry.cost_usd == 0.0
+
+
+# ----------------------------------------------------------------------
+# store / try_restore core flow
+# ----------------------------------------------------------------------
+
+
+def test_miss_on_empty_cache(tmp_path):
+ cache = AssetCache(cache_dir=tmp_path / "cache")
+ dest = tmp_path / "project" / "out.png"
+ assert cache.try_restore("nope", dest) is None
+ assert not dest.exists()
+ assert cache.misses == 1 and cache.hits == 0
+
+
+def test_store_then_restore_round_trip(tmp_path):
+ cache = AssetCache(cache_dir=tmp_path / "cache")
+ src = _fake_asset(tmp_path / "gen" / "img.png", b"PIXELS-red-fox")
+ ok = cache.store(
+ "k1", src, tool_name="flux_image", tool_version="0.1.0",
+ model="flux-pro", seed=7, cost_usd=0.05, data={"output": str(src), "provider": "flux"},
+ )
+ assert ok is True
+
+ dest = tmp_path / "project" / "scene1.png"
+ meta = cache.try_restore("k1", dest)
+ assert meta is not None
+ assert dest.exists()
+ assert dest.read_bytes() == b"PIXELS-red-fox"
+ assert meta["cost_usd"] == 0.05
+ assert meta["seed"] == 7
+ assert meta["model"] == "flux-pro"
+ assert meta["data"]["provider"] == "flux"
+ assert cache.hits == 1
+ assert cache.cost_saved_usd == 0.05
+
+
+def test_same_key_restores_to_any_output_path(tmp_path):
+ """Content-addressed: the same key materializes wherever asked."""
+ cache = AssetCache(cache_dir=tmp_path / "cache")
+ src = _fake_asset(tmp_path / "gen" / "img.png", b"BYTES")
+ cache.store("k1", src, cost_usd=0.10)
+
+ d1 = tmp_path / "a" / "x.png"
+ d2 = tmp_path / "b" / "y.png"
+ assert cache.try_restore("k1", d1) is not None
+ assert cache.try_restore("k1", d2) is not None
+ assert d1.read_bytes() == d2.read_bytes() == b"BYTES"
+ assert cache.hits == 2
+ assert round(cache.cost_saved_usd, 2) == 0.20
+
+
+def test_restored_blob_is_immutable_when_destination_overwritten(tmp_path):
+ # Overwriting a restored file in place (a normal regeneration) must not
+ # mutate the stored blob. Hard links would share an inode and corrupt the
+ # cache; the store keeps immutable copies instead.
+ cache = AssetCache(cache_dir=tmp_path / "cache")
+ src = _fake_asset(tmp_path / "gen" / "img.bin", b"ORIGINAL")
+ cache.store("k1", src)
+
+ dest = tmp_path / "project" / "scene.bin"
+ assert cache.try_restore("k1", dest) is not None
+ assert dest.read_bytes() == b"ORIGINAL"
+
+ dest.write_bytes(b"REWRITTEN-IN-PLACE-DIFFERENT-BYTES")
+
+ blob = cache.cache_dir / "k1.bin"
+ assert blob.read_bytes() == b"ORIGINAL"
+ dest2 = tmp_path / "project2" / "scene.bin"
+ cache.try_restore("k1", dest2)
+ assert dest2.read_bytes() == b"ORIGINAL"
+
+
+def test_store_source_rewrite_does_not_mutate_blob(tmp_path):
+ # The other direction: rewriting the tool's own output after it was stored
+ # must not reach back into the cache blob.
+ cache = AssetCache(cache_dir=tmp_path / "cache")
+ src = _fake_asset(tmp_path / "gen" / "img.bin", b"ORIGINAL")
+ cache.store("k1", src)
+ src.write_bytes(b"REGENERATED")
+ assert (cache.cache_dir / "k1.bin").read_bytes() == b"ORIGINAL"
+
+
+def test_store_rejects_missing_source(tmp_path):
+ cache = AssetCache(cache_dir=tmp_path / "cache")
+ assert cache.store("k", tmp_path / "nope.png") is False
+
+
+def test_manifest_drift_prunes_and_misses(tmp_path):
+ cache = AssetCache(cache_dir=tmp_path / "cache")
+ src = _fake_asset(tmp_path / "gen" / "img.png", b"BYTES")
+ cache.store("k1", src)
+ (cache.cache_dir / "k1.png").unlink() # simulate filesystem drift
+
+ assert cache.try_restore("k1", tmp_path / "out.png") is None
+ assert "k1" not in cache._read_manifest()
+
+
+def test_store_same_key_twice_keeps_single_entry(tmp_path):
+ cache = AssetCache(cache_dir=tmp_path / "cache")
+ src = _fake_asset(tmp_path / "gen" / "img.png", b"BYTES")
+ assert cache.store("k1", src) is True
+ assert cache.store("k1", src) is True
+ assert len(cache._read_manifest()) == 1
+
+
+# ----------------------------------------------------------------------
+# LRU eviction
+# ----------------------------------------------------------------------
+
+
+def test_lru_eviction_evicts_oldest_first(tmp_path):
+ import time
+ cache = AssetCache(cache_dir=tmp_path / "cache", max_total_bytes=30 * 1024)
+ for i in range(1, 4):
+ src = _fake_asset(tmp_path / f"a{i}.png", b"z" * (10 * 1024))
+ cache.store(f"k{i}", src)
+ time.sleep(0.01)
+ # Bump k2 so k1 is the LRU victim.
+ cache.try_restore("k2", tmp_path / "proj" / "k2.png")
+
+ src4 = _fake_asset(tmp_path / "a4.png", b"z" * (10 * 1024))
+ cache.store("k4", src4)
+
+ entries = cache._read_manifest()
+ assert "k1" not in entries
+ assert {"k2", "k3", "k4"} <= set(entries)
+ assert cache.evictions_count == 1
+ assert not (cache.cache_dir / "k1.png").exists()
+
+
+# ----------------------------------------------------------------------
+# Persistence + resilience
+# ----------------------------------------------------------------------
+
+
+def test_manifest_survives_process_boundary(tmp_path):
+ cache_dir = tmp_path / "cache"
+ src = _fake_asset(tmp_path / "img.png", b"BYTES")
+ assert AssetCache(cache_dir=cache_dir).store("k1", src) is True
+
+ dest = tmp_path / "project" / "img.png"
+ assert AssetCache(cache_dir=cache_dir).try_restore("k1", dest) is not None
+ assert dest.read_bytes() == b"BYTES"
+
+
+def test_manifest_tolerates_corrupt_lines(tmp_path):
+ cache_dir = tmp_path / "cache"
+ cache = AssetCache(cache_dir=cache_dir)
+ good = AssetCacheEntry(
+ key="good", file_name="good.png", size_bytes=5,
+ added_at=1.0, last_access_at=1.0,
+ )
+ _fake_asset(cache_dir / "good.png", b"BYTES")
+ with open(cache_dir / AssetCache.MANIFEST_NAME, "w", encoding="utf-8") as f:
+ f.write("not json\n")
+ f.write(json.dumps(good.to_dict()) + "\n")
+ f.write('{"missing": true}\n')
+ assert list(cache._read_manifest().keys()) == ["good"]
+
+
+def test_copy_file_makes_independent_copy(tmp_path):
+ src = _fake_asset(tmp_path / "src.bin", b"BYTES")
+ dst = tmp_path / "other" / "dst.bin"
+ dst.parent.mkdir(exist_ok=True)
+ assert _copy_file(src, dst) is True
+ assert dst.read_bytes() == b"BYTES"
+ # Independent: overwriting the copy must not touch the source (no shared inode).
+ dst.write_bytes(b"CHANGED")
+ assert src.read_bytes() == b"BYTES"
+
+
+# ----------------------------------------------------------------------
+# stats + singleton
+# ----------------------------------------------------------------------
+
+
+def test_stats_reports_state_and_counters(tmp_path):
+ cache = AssetCache(cache_dir=tmp_path / "cache", max_total_bytes=10 * 1024 * 1024)
+ src = _fake_asset(tmp_path / "img.png", b"z" * 2000)
+ cache.store("k1", src, cost_usd=0.30)
+ cache.try_restore("k1", tmp_path / "proj" / "img.png")
+ cache.try_restore("missing", tmp_path / "proj" / "missing.png")
+
+ s = cache.stats()
+ assert s["entry_count"] == 1
+ assert s["total_bytes"] == 2000
+ assert s["hits_this_session"] == 1
+ assert s["misses_this_session"] == 1
+ assert s["cost_saved_usd_this_session"] == 0.30
+ assert s["filelock_backend"] in ("filelock", "o_excl_fallback")
+
+
+def test_get_default_asset_cache_honors_env_and_is_singleton(monkeypatch, tmp_path):
+ reset_default_asset_cache()
+ monkeypatch.setenv("OPENMONTAGE_ASSET_CACHE_DIR", str(tmp_path / "envcache"))
+ a = get_default_asset_cache()
+ b = get_default_asset_cache()
+ assert a is b
+ assert Path(a.cache_dir) == tmp_path / "envcache"
+ reset_default_asset_cache()
diff --git a/tests/tools/test_base_tool_cache.py b/tests/tools/test_base_tool_cache.py
new file mode 100644
index 00000000..255bd64a
--- /dev/null
+++ b/tests/tools/test_base_tool_cache.py
@@ -0,0 +1,334 @@
+"""Integration tests for content-addressed caching in BaseTool.execute().
+
+A fake tool counts how many times its real ``execute()`` body runs. With the
+cache enabled, a repeat of a reproducible call must be served from disk without
+running the body again, at zero cost, with byte-identical output, while
+stochastic tools, seed-unpinned calls, publishers, and failures are never
+cached. The cache is off unless OPENMONTAGE_ASSET_CACHE is set, so the whole
+existing suite is unaffected; these tests opt in explicitly.
+"""
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+
+PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent
+sys.path.insert(0, str(PROJECT_ROOT))
+
+from tools.base_tool import ( # noqa: E402
+ BaseTool,
+ Determinism,
+ ToolResult,
+ ToolRuntime,
+ ToolTier,
+)
+from lib.asset_cache import ( # noqa: E402
+ get_default_asset_cache,
+ reset_default_asset_cache,
+)
+
+
+# ----------------------------------------------------------------------
+# Fake tools: one base implementation; subclasses vary only class attrs.
+# The wrapper reads determinism/tier/name/version off ``self`` at call time,
+# so subclasses need no execute() of their own.
+# ----------------------------------------------------------------------
+
+
+class _GenBase(BaseTool):
+ name = "gen_base"
+ version = "1.0.0"
+ tier = ToolTier.GENERATE
+ determinism = Determinism.DETERMINISTIC
+ runtime = ToolRuntime.API
+ idempotency_key_fields = ["prompt"]
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.calls = 0
+
+ def estimate_cost(self, inputs: dict) -> float:
+ return 0.05
+
+ def execute(self, inputs: dict) -> ToolResult:
+ self.calls += 1
+ out = Path(inputs["output_path"])
+ out.parent.mkdir(parents=True, exist_ok=True)
+ payload = (
+ f"{self.name}|v{self.version}|{inputs.get('prompt')}"
+ f"|seed={inputs.get('seed')}|call={self.calls}"
+ )
+ out.write_bytes(payload.encode())
+ return ToolResult(
+ success=True,
+ data={"output": str(out), "prompt": inputs.get("prompt")},
+ artifacts=[str(out)],
+ cost_usd=self.estimate_cost(inputs),
+ seed=inputs.get("seed"),
+ model="fake-model-1",
+ )
+
+
+class _DetGen(_GenBase):
+ name = "det_gen"
+
+
+class _DetGenV2(_GenBase):
+ name = "det_gen" # same name, bumped version -> different key
+ version = "2.0.0"
+
+
+class _OtherGen(_GenBase):
+ name = "other_gen"
+
+
+class _SeededGen(_GenBase):
+ name = "seeded_gen"
+ determinism = Determinism.SEEDED
+ idempotency_key_fields = ["prompt", "seed"]
+
+
+class _StochGen(_GenBase):
+ name = "stoch_gen"
+ determinism = Determinism.STOCHASTIC
+
+
+class _PubTool(_GenBase):
+ name = "pub_tool"
+ tier = ToolTier.PUBLISH
+
+
+class _MultiArtGen(_GenBase):
+ name = "multi_art_gen"
+
+ def execute(self, inputs: dict) -> ToolResult:
+ self.calls += 1
+ out = Path(inputs["output_path"])
+ out.parent.mkdir(parents=True, exist_ok=True)
+ out.write_bytes(b"primary")
+ side = out.with_suffix(".meta.json")
+ side.write_bytes(b"{}")
+ return ToolResult(
+ success=True,
+ data={"output": str(out)},
+ artifacts=[str(out), str(side)],
+ cost_usd=0.05,
+ )
+
+
+class _FailingGen(_GenBase):
+ name = "failing_gen"
+
+ def execute(self, inputs: dict) -> ToolResult:
+ self.calls += 1
+ return ToolResult(success=False, error="boom")
+
+
+class _NoPathGen(_GenBase):
+ name = "nopath_gen"
+ out_dir = "." # set by the test
+
+ def execute(self, inputs: dict) -> ToolResult:
+ self.calls += 1
+ out = Path(self.out_dir) / f"gen_{self.calls}.png"
+ out.parent.mkdir(parents=True, exist_ok=True)
+ out.write_bytes(b"data")
+ return ToolResult(
+ success=True, data={"output": str(out)},
+ artifacts=[str(out)], cost_usd=0.05,
+ )
+
+
+class _InputFileGen(_GenBase):
+ """A deterministic tool whose output depends on the CONTENTS of a file
+ input declared via idempotency_key_fields (the Upscale/enhance shape).
+ """
+ name = "input_file_gen"
+ idempotency_key_fields = ["input_path"]
+
+ def execute(self, inputs: dict) -> ToolResult:
+ self.calls += 1
+ src = Path(inputs["input_path"]).read_bytes()
+ out = Path(inputs["output_path"])
+ out.parent.mkdir(parents=True, exist_ok=True)
+ out.write_bytes(b"OUT:" + src)
+ return ToolResult(
+ success=True, data={"output": str(out)},
+ artifacts=[str(out)], cost_usd=0.05,
+ )
+
+
+# ----------------------------------------------------------------------
+# Fixtures
+# ----------------------------------------------------------------------
+
+
+def cache_on(tmp_path, monkeypatch):
+ monkeypatch.setenv("OPENMONTAGE_ASSET_CACHE", "1")
+ monkeypatch.setenv("OPENMONTAGE_ASSET_CACHE_DIR", str(tmp_path / "asset_cache"))
+ reset_default_asset_cache()
+ yield tmp_path
+ reset_default_asset_cache()
+
+
+# ----------------------------------------------------------------------
+# The core win: reproducible repeat is free and identical
+# ----------------------------------------------------------------------
+
+
+def test_identical_call_is_served_from_cache(cache_on):
+ tool = _DetGen()
+ inp = {"prompt": "a red fox", "output_path": str(cache_on / "out1.png")}
+ r1 = tool.execute(inp)
+ assert r1.success and r1.from_cache is False and tool.calls == 1
+ first_bytes = Path(inp["output_path"]).read_bytes()
+
+ # Same content, different destination -> content-addressed hit.
+ inp2 = {"prompt": "a red fox", "output_path": str(cache_on / "out2.png")}
+ r2 = tool.execute(inp2)
+ assert r2.from_cache is True
+ assert r2.cost_usd == 0.0
+ assert tool.calls == 1, "cache hit must not re-run the tool body"
+ assert Path(inp2["output_path"]).read_bytes() == first_bytes
+ assert r2.data["output"] == inp2["output_path"] # output ref repointed
+ assert r2.data.get("cached") is True
+
+ stats = get_default_asset_cache().stats()
+ assert stats["hits_this_session"] == 1
+ assert stats["cost_saved_usd_this_session"] == 0.05
+
+
+def test_disabled_by_default_does_not_cache(tmp_path, monkeypatch):
+ monkeypatch.delenv("OPENMONTAGE_ASSET_CACHE", raising=False)
+ monkeypatch.setenv("OPENMONTAGE_ASSET_CACHE_DIR", str(tmp_path / "asset_cache"))
+ reset_default_asset_cache()
+ tool = _DetGen()
+ tool.execute({"prompt": "x", "output_path": str(tmp_path / "a.png")})
+ tool.execute({"prompt": "x", "output_path": str(tmp_path / "b.png")})
+ assert tool.calls == 2
+ reset_default_asset_cache()
+
+
+# ----------------------------------------------------------------------
+# Determinism gating
+# ----------------------------------------------------------------------
+
+
+def test_seeded_with_pinned_seed_is_cached(cache_on):
+ tool = _SeededGen()
+ a = {"prompt": "p", "seed": 42, "output_path": str(cache_on / "a.png")}
+ b = {"prompt": "p", "seed": 42, "output_path": str(cache_on / "b.png")}
+ tool.execute(a)
+ r = tool.execute(b)
+ assert r.from_cache is True
+ assert tool.calls == 1
+
+
+def test_seeded_without_seed_is_not_cached(cache_on):
+ tool = _SeededGen()
+ tool.execute({"prompt": "p", "output_path": str(cache_on / "a.png")})
+ tool.execute({"prompt": "p", "output_path": str(cache_on / "b.png")})
+ assert tool.calls == 2, "an unpinned seed is effectively stochastic"
+
+
+def test_seeded_different_seed_regenerates(cache_on):
+ tool = _SeededGen()
+ tool.execute({"prompt": "p", "seed": 1, "output_path": str(cache_on / "a.png")})
+ r = tool.execute({"prompt": "p", "seed": 2, "output_path": str(cache_on / "b.png")})
+ assert r.from_cache is False
+ assert tool.calls == 2
+
+
+def test_stochastic_is_never_cached(cache_on):
+ tool = _StochGen()
+ tool.execute({"prompt": "p", "output_path": str(cache_on / "a.png")})
+ tool.execute({"prompt": "p", "output_path": str(cache_on / "b.png")})
+ assert tool.calls == 2
+
+
+def test_publisher_is_never_cached(cache_on):
+ tool = _PubTool()
+ tool.execute({"prompt": "p", "output_path": str(cache_on / "a.png")})
+ tool.execute({"prompt": "p", "output_path": str(cache_on / "b.png")})
+ assert tool.calls == 2, "publishers have side effects beyond the file"
+
+
+# ----------------------------------------------------------------------
+# Key correctness: identity + version isolation
+# ----------------------------------------------------------------------
+
+
+def test_version_bump_invalidates(cache_on):
+ v1 = _DetGen()
+ v1.execute({"prompt": "p", "output_path": str(cache_on / "a.png")})
+ v2 = _DetGenV2()
+ r = v2.execute({"prompt": "p", "output_path": str(cache_on / "b.png")})
+ assert r.from_cache is False
+ assert v2.calls == 1, "a version bump must not serve the old blob"
+
+
+def test_different_tools_do_not_collide(cache_on):
+ a = _DetGen()
+ b = _OtherGen()
+ a.execute({"prompt": "p", "output_path": str(cache_on / "a.png")})
+ r = b.execute({"prompt": "p", "output_path": str(cache_on / "b.png")})
+ assert r.from_cache is False
+ assert b.calls == 1
+
+
+# ----------------------------------------------------------------------
+# What must NOT be stored
+# ----------------------------------------------------------------------
+
+
+def test_multi_artifact_is_not_stored(cache_on):
+ tool = _MultiArtGen()
+ tool.execute({"prompt": "p", "output_path": str(cache_on / "a.png")})
+ tool.execute({"prompt": "p", "output_path": str(cache_on / "b.png")})
+ assert tool.calls == 2, "multi-artifact tools are deferred, not cached"
+
+
+def test_failure_is_not_stored(cache_on):
+ tool = _FailingGen()
+ tool.execute({"prompt": "p", "output_path": str(cache_on / "a.png")})
+ tool.execute({"prompt": "p", "output_path": str(cache_on / "b.png")})
+ assert tool.calls == 2
+
+
+def test_no_output_path_is_not_cached(cache_on):
+ tool = _NoPathGen()
+ tool.out_dir = str(cache_on)
+ # Without an output_path there is nowhere to materialize a hit.
+ tool.execute({"prompt": "p"})
+ tool.execute({"prompt": "p"})
+ assert tool.calls == 2
+
+
+def test_file_valued_input_is_keyed_by_content(cache_on):
+ # Rewriting the file at the same input_path must invalidate the key, or a
+ # rerun would restore an output derived from the old input bytes.
+ tool = _InputFileGen()
+ src = cache_on / "in.bin"
+ src.write_bytes(b"AAAA")
+ tool.execute({"input_path": str(src), "output_path": str(cache_on / "o1.bin")})
+ assert tool.calls == 1
+
+ src.write_bytes(b"BBBB") # same path, different bytes
+ r2 = tool.execute({"input_path": str(src), "output_path": str(cache_on / "o2.bin")})
+ assert r2.from_cache is False
+ assert tool.calls == 2
+ assert Path(r2.artifacts[0]).read_bytes() == b"OUT:BBBB"
+
+
+def test_identical_file_input_still_hits(cache_on):
+ # The complement: unchanged input content at the same path is still a hit.
+ tool = _InputFileGen()
+ src = cache_on / "in.bin"
+ src.write_bytes(b"AAAA")
+ tool.execute({"input_path": str(src), "output_path": str(cache_on / "o1.bin")})
+ r2 = tool.execute({"input_path": str(src), "output_path": str(cache_on / "o2.bin")})
+ assert r2.from_cache is True
+ assert tool.calls == 1
diff --git a/tools/base_tool.py b/tools/base_tool.py
index 84cccd4a..6c7ff318 100644
--- a/tools/base_tool.py
+++ b/tools/base_tool.py
@@ -141,6 +141,7 @@ class ToolResult:
duration_seconds: float = 0.0
seed: Optional[int] = None
model: Optional[str] = None
+ from_cache: bool = False
import threading as _threading
@@ -241,6 +242,155 @@ def _instrument_execute(fn: Callable) -> Callable:
return wrapper
+_FILE_HASH_CHUNK = 1024 * 1024
+
+
+def _hash_file(path: Path) -> Optional[str]:
+ """SHA-256 of a file's bytes, read in chunks. None if it can't be read."""
+ try:
+ h = hashlib.sha256()
+ with open(path, "rb") as f:
+ for chunk in iter(lambda: f.read(_FILE_HASH_CHUNK), b""):
+ h.update(chunk)
+ return h.hexdigest()
+ except OSError:
+ return None
+
+
+def _fingerprint_value(value: Any) -> Any:
+ """Make one cache-key value content-addressed.
+
+ A value that points at an existing file is replaced by a hash of the file's
+ bytes, so rewriting the file at the same path changes the key. A path string
+ on its own would not, which would let a rerun restore output derived from
+ stale input bytes. Lists and dicts are walked so nested asset paths are
+ covered too; everything else passes through unchanged.
+ """
+ if isinstance(value, (str, os.PathLike)):
+ try:
+ path = Path(value)
+ if path.is_file():
+ digest = _hash_file(path)
+ if digest is not None:
+ return {"__file_sha256__": digest}
+ except (OSError, ValueError):
+ pass
+ return value
+ if isinstance(value, (list, tuple)):
+ return [_fingerprint_value(v) for v in value]
+ if isinstance(value, dict):
+ return {k: _fingerprint_value(v) for k, v in value.items()}
+ return value
+
+
+def _is_cacheable(tool: "BaseTool", inputs: dict[str, Any]) -> bool:
+ """Whether a call may be served from / written to the asset cache.
+
+ Cache only reproducible, single-output calls whose sole side effect is the
+ file they write: a declared idempotency contract, a concrete output_path to
+ materialize into, not a publisher, and a determinism class that guarantees
+ the same bytes: deterministic always, seeded only when a seed is pinned
+ (an unpinned seed is effectively stochastic), stochastic never.
+ """
+ if not tool.idempotency_key_fields:
+ return False
+ if not inputs.get("output_path"):
+ return False
+ if tool.tier == ToolTier.PUBLISH:
+ return False
+ det = tool.determinism
+ if det == Determinism.STOCHASTIC:
+ return False
+ if det == Determinism.SEEDED and inputs.get("seed") is None:
+ return False
+ return True
+
+
+def _result_from_cache(restored: dict[str, Any], dest: Any) -> "ToolResult":
+ """Build a ToolResult for a cache hit that was materialized to ``dest``."""
+ data = dict(restored.get("data") or {})
+ # Repoint the stored output reference to where the caller asked for it.
+ if "output" in data:
+ data["output"] = str(dest)
+ data["cached"] = True
+ return ToolResult(
+ success=True,
+ data=data,
+ artifacts=[str(dest)],
+ cost_usd=0.0,
+ duration_seconds=0.0,
+ seed=restored.get("seed"),
+ model=restored.get("model"),
+ from_cache=True,
+ )
+
+
+def _cache_execute(fn: Callable) -> Callable:
+ """Wrap a tool's execute() with content-addressed output caching.
+
+ When the asset cache is enabled and the call is reproducible, a repeat of a
+ prior call links the cached artifact back into the requested output path and
+ returns a free ToolResult without invoking fn or paying a provider. On a
+ miss, fn runs and a single-file success is ingested for next time.
+
+ The cache layer is strictly optional and non-fatal: any failure importing or
+ using it falls through to the live call untouched. It is also off unless
+ OPENMONTAGE_ASSET_CACHE is set, so an existing run behaves exactly as before.
+ """
+ if getattr(fn, "_asset_cached", False):
+ return fn
+
+ @functools.wraps(fn)
+ def wrapper(self, inputs: Any, *args: Any, **kwargs: Any):
+ try:
+ from lib.asset_cache import asset_cache_enabled, get_default_asset_cache
+ except Exception:
+ return fn(self, inputs, *args, **kwargs)
+
+ if not asset_cache_enabled() or not isinstance(inputs, dict):
+ return fn(self, inputs, *args, **kwargs)
+ if not _is_cacheable(self, inputs):
+ return fn(self, inputs, *args, **kwargs)
+
+ try:
+ key = self.cache_key(inputs)
+ cache = get_default_asset_cache()
+ except Exception:
+ return fn(self, inputs, *args, **kwargs)
+
+ dest = inputs["output_path"]
+ try:
+ restored = cache.try_restore(key, Path(dest))
+ except Exception:
+ restored = None
+ if restored is not None:
+ return _result_from_cache(restored, dest)
+
+ result = fn(self, inputs, *args, **kwargs)
+
+ try:
+ artifacts = getattr(result, "artifacts", None) or []
+ if getattr(result, "success", False) and len(artifacts) == 1:
+ art = Path(artifacts[0])
+ if art.exists():
+ cache.store(
+ key,
+ art,
+ tool_name=self.name,
+ tool_version=self.version,
+ model=getattr(result, "model", None) or "",
+ seed=getattr(result, "seed", None),
+ cost_usd=float(getattr(result, "cost_usd", 0.0) or 0.0),
+ data=getattr(result, "data", None),
+ )
+ except Exception:
+ pass
+ return result
+
+ wrapper._asset_cached = True # type: ignore[attr-defined]
+ return wrapper
+
+
class BaseTool(ABC):
"""Abstract base class for all OpenMontage tools."""
@@ -249,7 +399,9 @@ class BaseTool(ABC):
super().__init_subclass__(**kwargs)
impl = cls.__dict__.get("execute")
if impl is not None and not getattr(impl, "__isabstractmethod__", False):
- cls.execute = _instrument_execute(impl)
+ # Cache is outermost: a hit skips both the live call and its event
+ # emission. Instrumentation wraps the raw implementation beneath it.
+ cls.execute = _cache_execute(_instrument_execute(impl))
# --- Identity (override in subclasses) ---
name: str = ""
@@ -407,6 +559,31 @@ class BaseTool(ABC):
raw = json.dumps(key_data, sort_keys=True)
return hashlib.sha256(raw.encode()).hexdigest()[:16]
+ def cache_key(self, inputs: dict[str, Any]) -> str:
+ """Content-addressed key for this call, used by the asset cache.
+
+ Combines tool identity and version with the declared
+ ``idempotency_key_fields`` so identical inputs to the same tool version
+ resolve to the same key, while a version bump or a different tool never
+ collides. Returns the full SHA-256 hex; the cache stores blobs under it.
+
+ File-valued fields are fingerprinted by content, not by path string, so
+ rewriting an input file at the same path changes the key rather than
+ serving output derived from the old bytes. Output-path fields are not in
+ this set, so the same content is a hit regardless of where the caller
+ wants the file to land.
+ """
+ key_data = {
+ "tool": self.name,
+ "version": self.version,
+ "fields": {
+ k: _fingerprint_value(inputs.get(k))
+ for k in self.idempotency_key_fields
+ },
+ }
+ raw = json.dumps(key_data, sort_keys=True, default=str)
+ return hashlib.sha256(raw.encode()).hexdigest()
+
# ---- Execution ----
@abstractmethod