Communitygithub.com

内容哈希缓存模式

使用SHA-256内容哈希缓存昂贵的文件处理结果——路径无关、自动失效,并支持服务层分离。适用于重复文件处理缓慢,且需要基于内容而非路径进行缓存和失效的场景。

内容哈希缓存模式 是什么?

该技能提供了一种基于内容哈希的文件缓存模式,旨在优化昂贵文件处理操作(如PDF解析、文本提取、图像分析)的性能。通过使用SHA-256内容哈希作为缓存键,而非传统的文件路径,该模式能自动适应文件移动或重命名,并在文件内容变化时自动使缓存失效。它要求处理函数保持纯粹,通过单独的服务层封装缓存逻辑,从而遵循单一职责原则。缓存条目以`{hash}.json`格式存储于文件系统中,实现O(1)查找,无需维护索引文件。该技能支持`--cache/--no-cache`命令行选项,并可优雅处理缓存损坏。它依赖Python的`hashlib`、`dataclasses`和`json`模块,适用于所有支持这些模块的平台。核心设计理念包括:内容哈希(路径无关)、O(1)文件查找、服务层分离(SRP)以及手动JSON序列化以完全控制不可变数据类的序列化。

兼容平台~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 命令行选项
  • 希望在不修改现有纯函数的情况下为其添加缓存

核心模式

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. 服务层包装器(单一职责原则)

保持处理函数的纯粹性。将缓存作为独立的服务层添加。

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 选项的命令行工具
  • 跨多次运行处理相同文件的批处理场景
  • 在不修改现有纯函数的情况下为其添加缓存

何时不使用

  • 必须始终是最新数据的数据(实时数据流)
  • 缓存条目极大(应考虑流式处理)
  • 结果依赖于文件内容以外的参数(例如,不同的提取配置)

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.

相关技能