Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
dd2d238
feat: add Client.GetMany with batch upstream and batch backends
molon Oct 6, 2026
0e05e03
test: fix data races in stale-refresh tests
molon Oct 6, 2026
e0339b7
fix: match x/sync/singleflight on Goexit and harden batch backends
molon Oct 6, 2026
350346f
fix: per-key failure handling in GetMany
molon Oct 6, 2026
c7dca4e
fix: bound GetMany's per-key fallback and tighten its error and timeo…
molon Oct 8, 2026
d83a40d
fix: keep whole-batch errors intact while never reading them as not-f…
molon Oct 8, 2026
ca6885c
test: cover how whole-batch errors meet the double-check and Get, and…
molon Oct 8, 2026
5e99f15
docs: align README examples with the current API
molon Oct 6, 2026
d6b12d4
fix: fetch each key as Get would when the upstream has no batch support
molon Oct 8, 2026
c4ba2d3
fix: claim per-key fetches only when they start, and stop on a cancel…
molon Oct 8, 2026
a3e687e
fix: GORMCache never serves another key's row on a case-insensitive k…
molon Oct 8, 2026
112cd9c
fix: quote GORMCache's key column, which MySQL reserves
molon Oct 8, 2026
fac0a92
fix: keep the single-key write-back in line with GetMany, and don't h…
molon Oct 8, 2026
750d052
feat: write the upstream before this layer, and guard backfills
molon Oct 6, 2026
dbdadad
fix: serialize backfills with writes instead of undoing them afterwards
molon Oct 8, 2026
5c1b087
docs: describe the write stripes, and test local write failures
molon Oct 8, 2026
5b2c8f1
docs: say that Set/Del keep the upstream change when this layer's wri…
molon Oct 8, 2026
3dc6b40
fix: a read after Set/Del never gets a value fetched before it, and w…
molon Oct 8, 2026
caafeba
fix: let a write with a done ctx through when it need not wait, and r…
molon Oct 8, 2026
a9797ea
fix: a write that gives up waiting still drops this layer's entry, an…
molon Oct 8, 2026
ee66cc1
test: randomized interleavings never read older than a completed write
molon Oct 8, 2026
4e7cac2
feat: create MySQL cache tables case-sensitive, and test GORMCache on…
molon Oct 8, 2026
c34d8a8
fix: don't bound a batch over a lower Client as one fetch, and let GO…
molon Oct 8, 2026
0e3a352
feat: create MySQL cache tables with utf8mb4_0900_bin
molon Oct 8, 2026
9364893
fix: sort GORMCache.SetMany rows so overlapping batches don't deadloc…
molon Oct 8, 2026
d84b7e4
fix: GORMCache writes no longer deadlock each other on PostgreSQL, an…
molon Oct 8, 2026
d3f8731
fix: RedisCache reads replies without copying them again
molon Oct 9, 2026
a91af7f
fix: RedisCache.GetMany read an unreachable Redis as empty values; ba…
molon Oct 9, 2026
97c294a
fix: answer every waiter when the upstream exits, and detach a claime…
molon Oct 9, 2026
bf787de
feat: WithGetManyChunkSize splits BatchUpstream calls, and WithGetMan…
molon Oct 9, 2026
ce776c1
feat: DoubleCheckAuto re-reads only when this Client wrote the key's …
molon Oct 9, 2026
e598135
feat: GORMCache.Migrate checks the MySQL version before creating its …
molon Oct 9, 2026
146c6c8
docs: Get and GetMany outcomes side by side, what GetMany returns whe…
molon Oct 9, 2026
21e574b
docs: stripe figures for 4096 stripes, and WithGetManyChunkSize as th…
molon Oct 10, 2026
ab4e592
test: re-runnable scripts for the GORM deadlock, double-check and bat…
molon Oct 10, 2026
083a664
docs: design notes, glossary, ADRs, FAQ and measurements, in Chinese
molon Oct 10, 2026
74ba540
refactor: move the flight group and the write stripes into internal p…
molon Oct 10, 2026
2fa16bf
docs: the FAQ in English and Chinese
molon Oct 10, 2026
e022fec
test: the deadlock script checks its own results, and runs the table …
molon Oct 10, 2026
f1a105b
feat: Migrate rejects an existing MySQL table whose key column is not…
molon Oct 10, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# cachex

Go 泛型多层缓存客户端:合并回源、二次检查、不存在缓存、返回陈旧值、批量读、写入顺序保证;后端有 Ristretto、SyncMap、BigCache、Redis、GORM。

## 先读什么

| 文档 | 什么时候读 |
|---|---|
| [docs/design.md](docs/design.md) | 动任何机制之前:现行设计总览和各分篇的链接 |
| [GLOSSARY.md](GLOSSARY.md) | 写文档、写注释、和用户讨论时,用这里的叫法 |
| [docs/adr/](docs/adr/) | 想改一个「看起来很奇怪」的做法之前,先看有没有对应的决策 |
| [docs/todo.md](docs/todo.md) | 发现了但这次不解决的问题都在这里 |
| [docs/faq_ZH.md](docs/faq_ZH.md) | 用户问过的问题(英文版是 `docs/faq.md`) |
| [docs/research/](docs/research/README.md) | 实测数据;复跑脚本在 `tools/bench/` |

## 仓库布局

- 根目录就是 `cachex` 包:`client.go`(单 key 读取、写入、回填)、`batch.go`(批量读、`claimed`:每个在途回源恰好发布一次)、`double_check.go`、`entry.go`、各后端(`ristretto.go`、`syncmap.go`、`bigcache.go`、`redis.go`、`gorm.go`、`transform.go`)。
- `internal/flight`(合并回源的登记表)、`internal/stripe`(分片锁):从 cachex 里拆出来的通用部件,暂不公开;以后别的库需要时再挪到公开路径。
- 测试和代码放在一起。`get_compat_test.go` 固定了单 key `Get` 和 main 一致的可观察行为,改它要有对应的 ADR。`gorm_container_test.go` 用 testcontainers 在 MySQL 和 PostgreSQL 上跑,没有 Docker 时自动跳过。
- `tools/bench/<日期-主题>/`:实测的复跑脚本,带 `bench` build tag,平时的 `go test ./...` 不会运行。

## 常用命令

```sh
go test -race ./... # 全量,约 3 分钟
go test -short -p=1 -count=1 ./... # CI 的跑法
golangci-lint run ./... # 用 CI 锁定的 v2.13.2;本机旧版本跑不了 go1.26 的代码
go test -tags bench -v -run <Test> ./tools/bench/<目录>/ # 复跑实测
```

并发相关的测试要用钩子或 channel 控制时序,不靠 `sleep` 碰运气;新加的时序测试用 `-race -count=20` 以上跑几遍确认稳定。修 bug 时先写能复现的测试,确认它在旧代码上失败。

## 协作约定

- **文档语言**:`README.md`/`README_ZH.md`、`BENCHMARK.md`/`BENCHMARK_ZH.md`、`docs/faq.md`/`docs/faq_ZH.md` 是中英双语,**两份必须逐段一一对应**,改一份就同步改另一份。其余文档(`GLOSSARY.md`、`docs/` 下的全部、本文件)只写中文;术语表里保留每个术语对应的英文。
- **设计结论写回 design**:只写现在成立的设计,被推翻的直接删,理由写进 ADR。专题写进 `docs/design/` 的对应分篇,`docs/design.md` 跟着同步。
- **ADR**:只给难回退、没有背景会让人意外、确实有过取舍的决定写,编号递增。
- **不解决的问题记 todo**:当场记进 `docs/todo.md`,解决了就删。
- **用户问过的问题记 faq**:先给结论,再给依据;中英两份都要加。
- **实测存档**:报告写进 `docs/research/` 并更新索引,脚本放进 `tools/bench/<日期-主题>/`。
- **文档里不引用其他缓存库或同类项目**。依赖的库(例如 `golang.org/x/sync`)和 Go 官方的 issue 可以引用。
- **提交和 PR**:提交信息、PR 描述用英文,照仓库现有的风格写,不加任何 AI 署名。行为变了就更新 PR 描述里的行为变化表。

## 底线

这些地方最容易被「顺手优化」改坏:

- **先写上游,再写本层;任何失败都删掉本层条目。** 不要改回「先写本层」。见 [ADR 0002](docs/adr/0002-upstream-first-writes.md)。
- **回填必须持分片读锁、核对写入代数,写入之后还要摘除在途回源。** 少任何一步,旧值都可能盖过写入。见 [ADR 0003](docs/adr/0003-striped-backfill-guard.md)。
- **每个在途回源恰好发布一次结果**,panic 和 Goexit 也不例外。不要让等待方去等一个永远不会来的结果。见 [ADR 0006](docs/adr/0006-goexit-publishes-an-error.md)。
- **回源用的 ctx 不带领头请求的取消,也不带它的 GORM 事务。** 见 [ADR 0007](docs/adr/0007-detached-fetch-context.md)。
- **批量读里,不存在不是错误**,缺席的 key 就是不存在;整批失败的错误不能被当成「全部不存在」。见 [ADR 0004](docs/adr/0004-batch-result-shape.md)。
- **GORMCache 的 key 列条件要用 clause 构造**(`key` 是 MySQL 的保留字),**只返回 key 完全相等的行**,**批量写按字节序加锁**,MySQL 表的 `key` 列只认 `utf8mb4_0900_bin`,**只支持各数据库默认的隔离级别**、不在代码里设置它。见 [ADR 0009](docs/adr/0009-gorm-exact-keys-and-collation.md)、[ADR 0010](docs/adr/0010-gorm-deadlock-ordering-and-retry.md)。
- **Redis pipeline 的错误要逐条命令判断**,连接层面的失败要设到没发出去的命令上,否则 `GET` 会把故障读成空值。见 [design/backends.md](docs/design/backends.md#批量pipeline)。
157 changes: 157 additions & 0 deletions GLOSSARY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
# cachex 术语表

cachex 是一个多层缓存客户端:一层缓存未命中时向下一层取值,并负责合并并发请求、处理过期和不存在的 key、保证写入在各层的先后顺序。本表统一这些概念的叫法,括号里是代码和英文文档中对应的术语。

## 层与数据

**层(layer)**:
一个 Client 连同它自己的存储,构成缓存链路上的一级,例如内存层、Redis 层。
_避免_:级、tier

**后端(backend)**:
一层用来存值的存储,例如 Ristretto、Redis、数据库表。
_避免_:store、存储层

**上游(upstream)**:
一层未命中时去取值的地方,可以是下一层,也可以是数据源。
_避免_:下游、loader

**数据源(source)**:
链路最底层、保存真实数据的地方,通常是数据库或其他服务;它不是缓存。
_避免_:origin、源站

**条目(entry)**:
后端里为一个 key 存的一份值。
_避免_:item

**不存在记录(not-found entry)**:
不存在缓存里为一个 key 记下的「它在上游不存在」,带有记录的时间,同样分新鲜、陈旧、腐烂。

## 新鲜度

**新鲜(fresh)**:
条目还在可信期内,直接作为结果返回。

**陈旧(stale)**:
条目已过可信期、但仍在可用期内:开启返回陈旧值时先返回它,同时在后台刷新。
_避免_:过期(容易和「腐烂」混淆)

**腐烂(rotten)**:
条目已过可用期,不能再返回,必须回源。
_避免_:过期、失效

**新鲜期 / 陈旧期(fresh TTL / stale TTL)**:
条目保持新鲜的时长,以及新鲜期之后还能作为陈旧值返回的额外时长。

## 读取

**命中 / 未命中(hit / miss)**:
一层在后端里找到 / 没找到可用条目。

**回源(fetch)**:
一层因为未命中或条目腐烂,向上游取值。
_避免_:load、加载、拉取

**回填(backfill)**:
回源拿到结果后,把它写进本层(值写进后端,「不存在」写进不存在缓存)。
_避免_:write-back、写回、回写

**刷新(refresh)**:
为了更新陈旧条目而在后台发起的回源,调用方不等它。
_避免_:重新加载

**返回陈旧值(serve-stale)**:
读到陈旧条目时先把它返回、再在后台刷新的读取方式。
_避免_:stale-while-revalidate(意思相同,但本项目不用这个叫法)

**不存在缓存(not-found cache)**:
专门记录「这个 key 在上游不存在」的缓存,有自己的新鲜期和陈旧期。
_避免_:空值缓存、negative cache

**二次检查(double-check)**:
认领回源之后、真正去上游之前,再读一次本层,看是否有别的请求刚把结果写进来。
_避免_:双重检查锁

## 合并回源

**在途回源(flight)**:
一个 key 正在进行、尚未发布结果的回源;同一个 key 的并发请求共用它。

**认领(claim)**:
请求为一个 key 登记在途回源;登记成功即成为领头请求,否则成为等待方。

**领头请求(leader)**:
认领成功、由它发起这次回源的请求;它和等待方一样等待结果。
_避免_:owner、主请求

**等待方(waiter)**:
发现 key 已有在途回源、等待它的结果的请求。

**发布(publish)**:
在途回源把结果(值或错误)交给所有等待方,并结束这次在途回源。

**摘除(drop)**:
在不打断的前提下,把一个在途回源从登记中移除:已在等的请求照样拿到结果,之后来的请求重新回源。

**回源槽位(fetch slot)**:
同一个 key 允许同时存在的在途回源份数;默认 1 份,即完全合并。

## 写入

**写入(write)**:
调用方主动发起的 `Set` 或 `Del`,从本层一路写到不再是缓存的那一层为止。
_避免_:更新(容易和回填混淆)

**失效(invalidate)**:
删掉一层里某个 key 的条目和不存在记录,让下次读取回源。

**写入顺序(write order)**:
先写上游、再写本层;同一个 key 的写入在各层按同一顺序生效。

**分片锁(striped lock)**:
把 key 按哈希分进固定数量的分片、每个分片一把锁的做法,用来给同一个 key 的写入和回填排序,而不用为每个 key 单独建锁。

**分片(stripe)**:
key 按哈希分成的固定若干组之一;同一组的 key 共用一份写入协调状态。
_避免_:分段(分段指 chunk)、桶、segment

**写入代数(write generation)**:
一个分片上已发生的写入次数,用来判断「回源期间有没有发生写入」。

**分片纪元(stripe epoch)**:
一个分片上写入与回填的总次数,用来判断「读取之后本层有没有被写过」。

## 批量

**批量读(batch read)**:
一次调用读取多个 key(`GetMany`),语义与逐个读取相同。

**批量上游(batch upstream)**:
能一次回答多个 key 的上游。

**分段(chunk)**:
大批量被切成的一部分,每一段单独发出一次调用或一条语句。
_避免_:批(单独说「批」时指整个批量读)、分片(分片指 stripe)

**整批失败(whole-batch failure)**:
一次批量调用整体出错,无法知道哪些 key 成功;所有 key 都按失败处理。

**部分失败(partial failure)**:
一次批量调用里只有部分 key 出错,其余 key 正常返回。

**三种结果(outcome)**:
每个 key 读取后必然是三者之一:找到(值可以是 nil)、不存在、失败。

## 一致性

**旧值回填(stale backfill)**:
回源读到旧值后,在一次写入完成之后才把旧值回填进去,导致这次写入被悄悄撤销。

**实例(instance)**:
运行 cachex 的一个进程;多个实例可能共用 Redis 或数据库这样的下层。

**租约(lease)**:
(尚未实现)由共享层发给领头请求的令牌;写入会让令牌作废,持有作废令牌的回填被拒绝。

**失效广播(invalidation broadcast)**:
(尚未实现)一个实例写入后通知其他实例失效各自内存层的做法。
Loading
Loading