Communitygithub.com

內容雜湊快取模式

使用 SHA-256 內容雜湊來快取昂貴的檔案處理結果 — 與路徑無關、自動失效,並具備服務層分離。適用於重複處理相同檔案耗時較長,且快取應根據內容而非路徑失效的場景。

內容雜湊快取模式 是什麼?

此技能實作了一種基於內容雜湊的檔案快取模式,專為昂貴的檔案處理(如 PDF 解析、文字擷取、圖片分析)而設計。與傳統的路徑式快取不同,它使用檔案的 SHA-256 內容雜湊作為快取鍵,因此檔案移動或重新命名後仍可命中快取,且內容一旦變更便會自動失效。此模式遵循單一職責原則(SRP),將純粹的處理函式與快取邏輯分離於不同的服務層,並採用 `{hash}.json` 的檔案命名方式實現 O(1) 查詢,無需維護索引檔案。支援平台包括任何可執行 Python CLI 工具的環境,例如 Claude Code、Cursor 或 Codex,特別適合檔案處理管線與批次任務。技能還詳細說明了何時啟用、關鍵設計決策、最佳實踐以及應避免的反模式,確保開發者能正確且高效地整合快取機制。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/content-hash-cache-pattern

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

內容雜湊檔案快取模式

使用 SHA-256 內容雜湊作為快取鍵,快取昂貴的檔案處理結果(PDF 解析、文字擷取、圖片分析)。與基於路徑的快取不同,這種方法在檔案移動或重新命名後仍能命中快取,並且在內容變更時自動失效。

何時啟用

  • 建構檔案處理管線(PDF、圖片、文字擷取)
  • 處理成本高,且相同檔案被重複處理
  • 需要 --cache/--no-cache CLI 選項
  • 想為現有的純函式加入快取而不修改它們

核心模式

1. 基於內容雜湊的快取鍵

使用檔案內容(而非路徑)作為快取鍵:

import hashlib
from pathlib import Path

_HASH_CHUNK_SIZE = 65536  # 大型檔案使用 64KB 區塊

def compute_file_hash(path: Path) -> str:
    """檔案的 SHA-256 雜湊(對大型檔案進行區塊讀取)。"""
    if not path.is_file():
        raise FileNotFoundError(f"找不到檔案:{path}")
    sha256 = hashlib.sha256()
    with open(path, "rb") as f:
        while True:
            chunk = f.read(_HASH_CHUNK_SIZE)
            if not chunk:
                break
            sha256.update(chunk)
    return sha256.hexdigest()

為何使用內容雜湊? 檔案重新命名或移動 = 仍可命中快取。內容變更 = 自動失效。無需索引檔案。

2. 凍結資料類別作為快取條目

from dataclasses import dataclass

@dataclass(frozen=True, slots=True)
class CacheEntry:
    file_hash: str
    source_path: str
    document: ExtractedDocument  # 快取的結果

3. 基於檔案的快取儲存

每個快取條目儲存為 {hash}.json — 以雜湊值進行 O(1) 查詢,無需索引檔案。

import json
from typing import Any

def write_cache(cache_dir: Path, entry: CacheEntry) -> None:
    cache_dir.mkdir(parents=True, exist_ok=True)
    cache_file = cache_dir / f"{entry.file_hash}.json"
    data = serialize_entry(entry)
    cache_file.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")

def read_cache(cache_dir: Path, file_hash: str) -> CacheEntry | None:
    cache_file = cache_dir / f"{file_hash}.json"
    if not cache_file.is_file():
        return None
    try:
        raw = cache_file.read_text(encoding="utf-8")
        data = json.loads(raw)
        return deserialize_entry(data)
    except (json.JSONDecodeError, ValueError, KeyError):
        return None  # 將損毀視為快取未命中

4. 服務層包裝器(SRP)

保持處理函式純淨。將快取作為單獨的服務層加入。

def extract_with_cache(
    file_path: Path,
    *,
    cache_enabled: bool = True,
    cache_dir: Path = Path(".cache"),
) -> ExtractedDocument:
    """服務層:檢查快取 -> 執行萃取 -> 寫入快取。"""
    if not cache_enabled:
        return extract_text(file_path)  # 純函式,不知道快取的存在

    file_hash = compute_file_hash(file_path)

    # 檢查快取
    cached = read_cache(cache_dir, file_hash)
    if cached is not None:
        logger.info("快取命中:%s (hash=%s)", file_path.name, file_hash[:12])
        return cached.document

    # 快取未命中 -> 執行萃取 -> 儲存
    logger.info("快取未命中:%s (hash=%s)", file_path.name, file_hash[:12])
    doc = extract_text(file_path)
    entry = CacheEntry(file_hash=file_hash, source_path=str(file_path), document=doc)
    write_cache(cache_dir, entry)
    return doc

關鍵設計決策

決策理由
SHA-256 內容雜湊與路徑無關,內容變更時自動失效
{hash}.json 檔案命名O(1) 查詢,無需索引檔案
服務層包裝器SRP:萃取保持純淨,快取是獨立關注點
手動 JSON 序列化對凍結資料類別的序列化有完整控制
損毀時回傳 None優雅降級,下次執行時重新處理
cache_dir.mkdir(parents=True)第一次寫入時才延遲建立目錄

最佳實踐

  • 對內容進行雜湊,而不是路徑 — 路徑會變,內容身分不會
  • 對大型檔案進行區塊讀取 — 避免將整個檔案載入記憶體
  • 保持處理函式純淨 — 它們不應該知道快取的存在
  • 記錄快取命中/未命中 — 使用截斷的雜湊值以便除錯
  • 優雅處理損毀 — 將無效的快取條目視為未命中,絕不崩潰

應避免的反模式

# 錯誤:基於路徑的快取(檔案移動/重新命名時失效)
cache = {"/path/to/file.pdf": result}

# 錯誤:將快取邏輯放在處理函式內部(違反 SRP)
def extract_text(path, *, cache_enabled=False, cache_dir=None):
    if cache_enabled:  # 現在這個函式有兩個職責
        ...

# 錯誤:對巢狀的凍結資料類別使用 dataclasses.asdict()
# (可能導致複雜巢狀類型的問題)
data = dataclasses.asdict(entry)  # 應改用手動序列化

何時使用

  • 檔案處理管線(PDF 解析、OCR、文字擷取、圖片分析)
  • 受益於 --cache/--no-cache 選項的 CLI 工具
  • 跨執行批次處理中會出現相同檔案的情況
  • 為現有的純函式加入快取而不修改它們

何時不應使用

  • 資料必須永遠保持最新(即時饋送)
  • 快取條目極大(應考慮串流處理)
  • 結果取決於檔案內容以外的參數(例如不同的萃取設定)

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

相關技能