@ultimat3/cache 30.9.0 → 31.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CLAUDE.md CHANGED
@@ -16,8 +16,13 @@ Tier 1. Tagged caching + THE invalidation graph.
16
16
  itself off (no eviction, no similarity floor). Never `Math.max(1, x)` in front: a clamp is not a
17
17
  validator. **The `Finite` in the names is load-bearing** — `bun run finite-bounds` recognises a
18
18
  repair by the call's shape.
19
- - `invalidateTags()` in `invalidate.ts` is the ONLY fan-out path, and the only writer of the log
20
- `recentInvalidations()` reads. Never call `tier.invalidateTags()` from outside it.
19
+ - `invalidateTags()` in `invalidate.ts` is the ONLY fan-out path, and (with `flushProcessTiers`) the
20
+ only emitter of `cache.invalidate`. Never call `tier.invalidateTags()` from outside it.
21
+ - **No ring buffer, no slot (v31, `X_INSTRUMENT_SLOT_FORBIDDEN`)**: busts, swallowed refusals and
22
+ every rung a read asks are core bus events — `cache.invalidate`, `cache.tier_failure`,
23
+ `cache.hit`/`cache.miss` — payloads core's (`CacheInvalidateEvent`, `CacheTierFailureEvent`,
24
+ `CacheLookupEvent`), re-exported. The `/_x` panel subscribes and keeps its own buffer. Tests read
25
+ them through `recordCacheEvents()` (`cache-events-fixture.ts`).
21
26
  - **The fan-out clears FARTHEST tier first, and reports in read order** (core's `CACHE_TIERS`, what `/_x`
22
27
  renders). Near-to-far lets a racing read promote the stale far value straight back up.
23
28
  `CacheStack.drop` reverses for the same reason. `invalidation-race.test.ts`.
@@ -49,30 +54,28 @@ Tier 1. Tagged caching + THE invalidation graph.
49
54
  - **`flushProcessTiers(source)` is for a process that cannot name what it missed** (its bus was
50
55
  away): `CacheTier.clear()` on in-process tiers only, tagged ISR pages stale, fills fenced out
51
56
  (`markAllInvalidated`). Never re-emits. A shared tier must NOT implement `clear`.
52
- - **`bestEffort()` is the only sanctioned way to swallow a cache refusal.** Its label is `TierLabel`
57
+ - **`bestEffort()` is the only sanctioned way to swallow a cache refusal.** A `cache.tier_failure` subscriber that throws is contained by the bus, as every subscriber is (`instrument.subscriber_failed`, logged once) — never the read's failure. Its label is `TierLabel`
53
58
  (`TierName` plus `'query-read'`), deliberately not a widening of `TierName`.
54
59
  - **A refusal is rendered with `renderThrowable()`, never `error.message`** — at all five absorbing
55
60
  sites. Tiers, revalidators, broadcasts and purge `fetch`es are app-supplied, so their rejection
56
61
  values are too. The code field keeps its own total probe (`ultimateCode` in `tier-failures.ts`):
57
62
  a driver `code` is a SQLSTATE, never an `X_*`.
58
63
  - Tier failures go into `report.errors`; a cache tier may never fail a business read or write.
59
- `cacheStack` routes every `get`/`set`/`del` through `bestEffort()` into
60
- `recentTierFailures()`. `load()` is the one unguarded call (it IS the business read).
64
+ `cacheStack` routes every `get`/`set`/`del` through `bestEffort()` into a
65
+ `cache.tier_failure` event. `load()` is the one unguarded call (it IS the business read).
61
66
  `LruCache.set` still throws `X_CACHE_TOO_LARGE` to a direct caller.
62
67
  - **`serializeTags` is the wire form; `tagKeys` is the IDENTITY form** (sorted, de-duplicated —
63
68
  `@ultimat3/query`'s `cacheKeyFor` builds keys from it). It lives here because `action` and `query`
64
69
  are one tier and cannot share a copy. `@ultimat3/render`'s order-preserving route form is its
65
70
  internal `routeTagKeys` (`render/src/route.ts`) — one public `tagKeys`, this one.
66
- - **Two exports have no production caller and both are KEPT**: `invalidateWireTags` (the outbound
67
- twin of `receiveInvalidationBroadcast`, which `packages/cli/src/runtime-cache.ts` calls) and
68
- `recentTierFailures()` (no `/_x` panel reads it yet). Wire the panel or leave them.
71
+ - **`invalidateWireTags` has no production caller and is KEPT**: the outbound twin of
72
+ `receiveInvalidationBroadcast`, which `packages/cli/src/runtime-cache.ts` calls.
69
73
  - `tag.x` typing comes from the `CacheTagRegistry` augmentation, generated by `x manifest`.
70
74
  - **`declareTags()` is additive and process-wide: a test undoes it with `isolateDeclaredTags()`,
71
75
  never `resetDeclaredTags()`** (the empty set switches `assertKnownTags` off).
72
- - **Every process-global registry has that seam: `isolateGraph()`, `isolateTiers()`,
73
- `isolateTierFailures()`.** A reset belongs only where an empty registry is the subject, paired
74
- with the module-scope isolate and `afterAll(restore)` — the leak guard sees additions, never
75
- deletions. `isolateTierFailures`/`resetTierFailures` stay off `index.ts`.
76
+ - **Every process-global registry has that seam: `isolateGraph()`, `isolateTiers()`.** A reset
77
+ belongs only where an empty registry is the subject, paired with the module-scope isolate and
78
+ `afterAll(restore)` — the leak guard sees additions, never deletions.
76
79
  - Clocks are injected (`LruOptions.clock`, `CacheStackOptions.clock`); read them through `nowMs()`.
77
80
  - **`ttlMs` is positive and finite, and `assertTtl` (`tiers.ts`) is the one place that says so** —
78
81
  every tier calls it before writing, the request memo and `memorySemanticCache.remember`
@@ -103,29 +106,38 @@ Tier 1. Tagged caching + THE invalidation graph.
103
106
  - **A promotion carries the entry's remaining life**, `hit.expiresAt - now`, and drops a hit that
104
107
  fails `isExpired`. So every tier's `get` reports `expiresAt`: `redis.ts` reads `PTTL` pipelined
105
108
  with the `GET` (server clock). `-1`/`-2` are sentinels, and `PTTL: -2` beside a returned value is a MISS.
106
- - **`t:` is the TAG's bucket and `e:` is the ENTITY index; one key is never both.**
107
- `writeBucketsFor` joins the declared tag plus `e:{entity}`; `bustBucketsFor` reads the index for a
108
- collection bust and `t:{entity}:<id>` + `t:{entity}` for a row one. A row bust still `SREM`s what
109
- it deleted from the index (`sweepBucketsFor`). Pinned by `tier-parity.test.ts` and
110
- `redis.live.test.ts`.
109
+ - **`t2:` is the TAG's bucket and `e2:` is the ENTITY index; one key is never both**
110
+ (`redis-buckets.ts`). `writeBucketsFor` joins the declared tag plus `e2:{entity}`;
111
+ `bustBucketsFor` reads the index for a collection bust and `t2:{entity}:<id>` + `t2:{entity}` for
112
+ a row one. `sweepBucketsFor` (what a bust `ZREM`s from) is a superset: a row bust cleans the index
113
+ it never reads. Pinned by `tag-parity.test.ts`, `tier-parity.test.ts` and `redis.live.test.ts`.
114
+ - **A bucket is a sorted set scored `expiry + TAG_GRACE_MS` (writer's clock), and every join prunes
115
+ `-inf (now`** — so it holds live keys only (`redis-tag-bound.test.ts`). The grace absorbs clock
116
+ skew between pods; never score by the bare expiry. Changing the layout bumps the segment (`t2`)
117
+ rather than migrating.
111
118
  - **Every tier stores codec TEXT, never the caller's object** (`value-codec.ts`: JSON + tagged
112
119
  `Date`/`bigint`/`Map`/`Set`, app `$x` keys escaped). One shape whichever tier hit, no shared
113
120
  mutable reference; a cycle, depth > 512 or a bigint > 4096 chars is `X_CACHE_VALUE_UNENCODABLE`
114
121
  at the write. Only `x1:`-marked text is revived; unmarked (pre-codec) is plain `JSON.parse`.
115
122
  - **`CacheTier.set` REJECTS, never throws synchronously** — `lruTier`/`memoTier` are
116
123
  `async` for that alone.
117
- - **`redis.ts`'s script deletes NOTHING — it reads.** It returns the members; the tier `DEL`s them
118
- client-side one key at a time (slot-local on Cluster/Dragonfly) and `SREM`s only what
119
- `Promise.allSettled` says died, so a refused `DEL` stays findable for the retry.
124
+ - **A bust has no script.** `readBucket` pages `ZSCAN … COUNT 1000` — never a score/offset
125
+ cursor: a concurrent prune of a read tie group, or a re-write re-scoring a read tie member, shifts
126
+ an offset past live keys. `ZSCAN` returns every member present for the whole scan (the fake's
127
+ `ZSCAN` keeps exactly that guarantee and nothing stronger); `unlinkAll` `UNLINK`s one key per command; `sweepBuckets` `ZREM`s only what
128
+ `Promise.allSettled` says died, 8 commands in flight, so a refused `UNLINK` stays findable for the
129
+ retry. 10k members ≤ 100 sequential round trips (`roundTrips` in the fixture counts them).
120
130
  - **A `set` joins its buckets BEFORE it writes the value, and re-checks membership after**; only a
121
- literal `0` from `SISMEMBER` counts as busted-in-the-air (`saysAbsent`).
122
- - **Tag keys carry a `{entity}` hash tag and `invalidateTags` issues one script call per tag**, so
123
- no command's `KEYS` ever spans two hash tags.
124
- - **Every tag set carries a lease that only grows** — `TAG_MEMBER_SCRIPT` does `SADD` + `EXPIRE` in
125
- one call (`GT` alone leaves a fresh bucket immortal).
126
- - **A fake cannot run Lua, so it must never pretend to.** The fakes are recorders; a test reading a
127
- script's reply states it with `answerEval(script, reply)`, and an unprogrammed `EVAL` throws.
128
- Every claim about what a script DOES belongs in `redis.live.test.ts`.
131
+ literal `null` from `ZSCORE` counts as busted-in-the-air (`lostMembership`).
132
+ - **Every command the tier sends names ONE key** (the lease `EVAL` included), and bucket keys carry
133
+ a `{entity}` hash tag — slot-local on Redis Cluster and Dragonfly by construction.
134
+ - **Every tag set carries a lease that only grows** — `REDIS_TAG_LEASE_SCRIPT`, the tier's one
135
+ script (`GT` alone leaves a fresh bucket immortal).
136
+ - **`redisTier({ maxValueBytes })`, default 1 MiB of encoded UTF-8, is `X_CACHE_TOO_LARGE`** —
137
+ checked after encoding, before any bucket is joined; the LRU's `maxBytes`, on the shared rung.
138
+ - **The fake holds plain commands as state and never runs Lua** (`redis-fake-fixture.ts`): values,
139
+ sorted sets, `UNLINK`. An `EVAL` other than the lease script throws. Every claim about what a
140
+ script DOES belongs in `redis.live.test.ts`.
129
141
  - **The Redis namespace carries the build id by default** (`namespaceFor`, `appVersion()`);
130
142
  `buildId: null` opts out. Changing the layout is a cold cache.
131
143
  - **Redis down is a slow miss, never a hang** (`redis-deadline.ts`). Every value-path command gets
@@ -135,9 +147,13 @@ Tier 1. Tagged caching + THE invalidation graph.
135
147
  so is a STOPPED store (Bun's `ERR_REDIS_CONNECTION_CLOSED`, typed in `withinDeadline`, a bust's
136
148
  included). A server's own error reply passes through (`redis-outage.test.ts`).
137
149
  The client is core's `redisClient()` (no offline queue, endless reconnect); never `Bun.redis`.
138
- - **Cross-instance invalidation is a SEAM, never a transport.** `registerInvalidationBroadcast` /
139
- `receiveInvalidationBroadcast`; `cli` owns the bus. The inbound half cannot re-emit (only it passes
140
- `emit: false`). An undeclared inbound tag goes to `report.errors`, never a throw.
150
+ - **Cross-instance invalidation is a SEAM; the one wire this package speaks is Redis pub/sub**
151
+ (`redis-pubsub.ts`, rung 1: Redis, no NATS). `registerInvalidationBroadcast` /
152
+ `receiveInvalidationBroadcast`; `cli` CHOOSES the bus (`runtime-cache-bus.ts`). The subscriber is
153
+ its own connection, and every connect unsubscribes before it subscribes (Bun keeps the old
154
+ listener: a bare re-subscribe delivers twice) — `redis-pubsub.test.ts`. The inbound half cannot
155
+ re-emit (only it passes `emit: false`). An undeclared inbound tag goes to `report.errors`, never a
156
+ throw.
141
157
  - **A `cdn` tier holding `noopPurgeDriver()` reports `skipped`, never keys** (`isNoopPurgeDriver`,
142
158
  in `cdn.ts`). **`report.cdn` is what depends; `report.tiers` is what cleared** — `busted` is built
143
159
  from `tiers` + `isr` + `liveQueries`, never `cdn`.
@@ -166,6 +182,11 @@ Tier 1. Tagged caching + THE invalidation graph.
166
182
  - **The purge URL in a `fix:` goes through `renderFixShellArg`** — it is operator data, and
167
183
  `renderFixLiteral`'s double quotes leave `$(…)` live.
168
184
 
185
+ - **`./adapter` (`adapter.ts`) is the `cacheTiers` and `purge` ports for an adapter author**:
186
+ `CacheTier`, `PurgeDriver`, their shapes and the two errors a tier or driver raises. No installer:
187
+ `@ultimat3/cli` READS `runtime.ts`'s `cacheTiers` (each replaces the rung of its own name;
188
+ `cache.tiers` still names the ladder) and `purge`. Type moves: none — every name stays on `.` too.
189
+
169
190
  ## Files
170
191
 
171
192
  | File | Owns |
@@ -177,25 +198,28 @@ Tier 1. Tagged caching + THE invalidation graph.
177
198
  | `tier-leading.ts` | which fence each in-flight load holds, and whether a reader may join it |
178
199
  | `tier-fence.ts` | `TierFence`/`FenceVerdict`, and how a fill samples and asks a shared tier's fence |
179
200
  | `redis-fence.ts` | the leased generation keys a bust writes and a fill watches |
201
+ | `redis-buckets.ts` | the tag → keys sorted-set layout: join + prune + lease, paged read, `UNLINK`, sweep |
180
202
  | `set-options.ts` | how two callers' `CacheSetOptions` combine, and the `null`-load TTL |
181
- | `tier-failures.ts` | `bestEffort()`, and the bounded log of refusals it absorbs |
203
+ | `tier-failures.ts` | `bestEffort()`, and the `cache.tier_failure` event for each refusal it absorbs |
182
204
  | `memo.ts` | request memo over the ALS ctx (WeakMap, no lifecycle) |
183
205
  | `lru.ts` | byte-budgeted LRU (linked list + map + tag index) |
184
206
  | `value-codec.ts` | the one value encoding every tier stores and decodes |
185
- | `redis.ts` | the shared tier over core's `redisClient()` (`@ultimat3/core/redis`, never `Bun.redis`), build-namespaced keys, hash-tagged buckets, one script call per tag |
207
+ | `redis.ts` | the shared tier over core's `redisClient()` (`@ultimat3/core/redis`, never `Bun.redis`), build-namespaced keys, the value budget, the write/bust order |
208
+ | `redis-pubsub.ts` | `redisPubSub`/`redisPubSubAt`: invalidations between replicas over Redis pub/sub, resubscribe on every connect |
186
209
  | `redis-deadline.ts` | `withinDeadline`: a per-command deadline (150 ms, `commandTimeoutMs`), a 5 s park of the value path after one is missed, and the bust view that skips the park on its own 1,000 ms |
187
210
  | `cdn.ts` | `Cache-Control`/`Surrogate-Key` emission, `surrogateKeys`, the purge key list, the `PurgeDriver` seam |
188
211
  | `purge-http.ts` | the HTTP half both remote drivers share: one POST, batching, key guard, and core's retryable table re-exported |
189
212
  | `purge-fastly.ts` | `fastlyPurgeDriver`: surrogate-key batch purge, `purge_all` |
190
213
  | `purge-cloudflare.ts` | `cloudflarePurgeDriver`: cache-tag purge, `purge_everything` |
191
214
  | `purge-env.ts` | `selectPurgeDriver`: which edge an environment purges, and nothing else |
192
- | `invalidate.ts` | the single entry point, `InvalidationReport`, and the bounded log `/_x` renders |
215
+ | `invalidate.ts` | the single entry point, `InvalidationReport`, and the `cache.invalidate` event |
216
+ | `cache-events-fixture.ts` | tests only: `recordCacheEvents()`, the `cache.*` events a test caused |
193
217
  | `semantic.ts` | embedding cache for LLM calls |
194
218
 
195
219
  ## Commands
196
220
 
197
221
  ```
198
- bun test packages/cache
222
+ bun test ./packages/cache/
199
223
  bun run --filter @ultimat3/cache typecheck
200
224
  ```
201
225
 
package/README.md CHANGED
@@ -29,7 +29,7 @@ Reads walk down until a hit, then populate every tier they walked past. Writes p
29
29
  |---|---|---|---|---|
30
30
  | 0 | `request-memo` | ALS context (`WeakMap`) | dies with the request | never |
31
31
  | 1 | `lru` | in-process, byte-budgeted | tag index | never |
32
- | 2 | `redis` | `redisClient()` (`@ultimat3/core/redis`) | tag→keys set, one `EVAL` **per tag** + slot-local `DEL`s | single node |
32
+ | 2 | `redis` | `redisClient()` (`@ultimat3/core/redis`) | tag→keys sorted sets, paged reads + slot-local `UNLINK`s | single node |
33
33
  | 3 | `cdn` | headers + purge driver | surrogate keys | no CDN |
34
34
 
35
35
  A tier is a `CacheTier` (`get`/`set`/`del`/`invalidateTags`, plus an optional `fence` for a tier
@@ -152,8 +152,10 @@ tier that did not answer, so `read`, `write` and `drop` carry on. A feed too big
152
152
  to throw is `load()` — it *is* the business read, and absorbing it would hand back `undefined` as
153
153
  though it were the value.
154
154
 
155
- `recentTierFailures()` is where those refusals go: last 100, newest first, each naming the tier, the
156
- operation, the key and the `X_*` code, and each one also logged as `cache.tier.failed`. Same
155
+ Each refusal is one `cache.tier_failure` event on core's instrumentation bus (`CacheTierFailureEvent`,
156
+ `As of 2026-11`, v31), naming the tier, the operation, the key and the `X_*` code, and each one also
157
+ logged as `cache.tier.failed` — `subscribe('cache.tier_failure', …)` to keep them. Every rung a read
158
+ asks is a `cache.hit` or `cache.miss` event (`{ tier, key }`). Same
157
159
  bargain as `report.errors` on the invalidation side — degraded is visible, not merely slow.
158
160
 
159
161
  `bestEffort(label, op, key, run)` is that guard, exported: a cache that is not a rung of this ladder
@@ -167,7 +169,6 @@ closed (`TierLabel`) so the panel can group by it. `'query-read'` is in that uni
167
169
  ```ts
168
170
  tag.post // the collection — busts lists
169
171
  tag('post', id) // one row — also busts the lists that contained it
170
- tagsFor(Post, row) // both, for a repo write
171
172
  ```
172
173
 
173
174
  Wire form is `post` / `post:<id>`, identical in Redis keys, CDN surrogate keys and
@@ -193,47 +194,51 @@ fixture entity therefore turns validation on for every later file in the same `b
193
194
  | Key | Holds |
194
195
  |---|---|
195
196
  | `<prefix>:<buildId>:c:<key>` | the value, `SET … PX` |
196
- | `<prefix>:<buildId>:t:{<entity>}` | members carrying the **collection tag** — `tag('post')` |
197
- | `<prefix>:<buildId>:t:{<entity>}:<id>` | members carrying **that row's tag** — `tag('post', '1')` |
198
- | `<prefix>:<buildId>:e:{<entity>}` | members carrying **any** tag of the entity — the index |
199
-
200
- Four keys, three jobs, and the fourth is why: `t:` buckets are the tags a caller declared and `e:`
201
- is the entity index. A **collection bust** reads the index, so it clears the rows too; a **row
202
- bust** reads that row's bucket and the collection tag's, so `post:2` survives a bust of `post:1`.
203
- That is `tagMatches` — the same predicate the LRU answers through its two indexes and the request
204
- memo answers through `tagsIntersect` — and the shared tier is the rung that did not, because `t:`
205
- served as the index as well: `invalidateTags([tag('post', '1')])` came back with every post-tagged
206
- key in the store and deleted them, so one row write emptied the shared tier for that entity while
207
- the in-process tier one rung closer kept exactly the row that had changed.
208
- `tier-parity.test.ts` compares all three rungs and `redis.live.test.ts` runs the same two busts
209
- against a real server.
210
-
211
- `{<entity>}` is a **Redis Cluster hash tag**, not decoration: it is what makes a row's bucket, its
212
- collection's bucket and the index hash to one slot, so a script may take them in one `KEYS`.
213
- Invalidation issues
214
- **one script call per tag** for that reason — the batched form carried every tag's buckets in one
215
- `EVAL` and was rejected with `CROSSSLOT` before the script ran, landing in `report.errors` as a
216
- partial bust while stale rows served until TTL. Value keys are still deleted client-side, one `DEL`
217
- each, which is slot-local under every topology.
218
-
219
- The script **deletes nothing at all** — not the value keys, and not the buckets either. The tier
220
- `SREM`s exactly the members whose `DEL` succeeded, from every bucket that member joined —
221
- including, for a row bust, the entity index it deliberately never *reads*. Reading `e:{entity}` for
222
- a row bust would return every key of the entity; removing from it cannot over-reach, and a member
223
- left there is a corpse in a set every later write renews the lease on. A refused delete keeps its
224
- membership and the retry the error asks for still finds it; dropping the bucket inside the script
225
- made that failure permanent. A `set` mirrors it: buckets are joined **before** the value is written and membership is
226
- re-checked after, because a bust that landed in between would otherwise leave a row nothing can
227
- reach by tag, serving until its own lease ran out.
228
-
229
- **Every tag set carries a lease**, renewed on each write to the member's own TTL plus 60s, raised
230
- only when the new lease is longer — a 60s member must not shorten a bucket a 1h member is in.
231
- Without it a tag set grew forever: value keys died after five minutes, their membership never did,
232
- and after a month `SMEMBERS` on a multi-million-member set blocked the server for hundreds of
233
- milliseconds and answered with a list the client then `DEL`'d in batches. One publish became a
234
- Redis outage. The renewal is a script (`REDIS_TAG_MEMBER_SCRIPT`, one key in `KEYS`) rather than
235
- `EXPIRE … GT`, because `GT` treats a key with no TTL as infinite and would leave a **fresh** bucket
236
- immortal — which is the bug being fixed.
197
+ | `<prefix>:<buildId>:t2:{<entity>}` | members carrying the **collection tag** — `tag('post')` |
198
+ | `<prefix>:<buildId>:t2:{<entity>}:<id>` | members carrying **that row's tag** — `tag('post', '1')` |
199
+ | `<prefix>:<buildId>:e2:{<entity>}` | members carrying **any** tag of the entity — the index |
200
+
201
+ Every bucket is a **sorted set**, scored by when its member may be forgotten: the value's expiry
202
+ plus `TAG_GRACE_MS` (60 s), on the writer's clock. Layout and commands: `redis-buckets.ts`.
203
+
204
+ `t2:` buckets are the tags a caller declared and `e2:` is the entity index. A **collection bust**
205
+ reads the index, so it clears the rows too; a **row bust** reads that row's bucket and the
206
+ collection tag's, so `post:2` survives a bust of `post:1`. That is `tagMatches` — the predicate the
207
+ LRU answers through its two indexes and the request memo through `tagsIntersect`.
208
+ `tag-parity.test.ts` and `tier-parity.test.ts` compare the rungs; `redis.live.test.ts` runs the
209
+ same busts against a real server. The `2` marks the sorted-set layout: a v30 pod's `t:`/`e:` plain
210
+ sets never collide with these on a shared server, and expire on their own lease.
211
+
212
+ **A bucket holds live keys only.** Every write `ZADD`s its member, `ZREMRANGEBYSCORE`s everything
213
+ already past its score, and grows the bucket's lease (`REDIS_TAG_LEASE_SCRIPT`: `EXPIRE … GT`
214
+ alone leaves a fresh key immortal) — three single-key commands, one pipelined round trip. Before
215
+ this only a bust removed members, so an entity written constantly and never invalidated collected
216
+ every key it ever wrote, and its first bust read millions in one reply. The grace is what keeps a
217
+ pod whose clock runs ahead from pruning a member whose value key still lives.
218
+ `redis-tag-bound.test.ts`.
219
+
220
+ **A bust is paged and pipelined**, on the post-commit path:
221
+
222
+ | Step | Commands | Bound |
223
+ |---|---|---|
224
+ | fence | `SET` per generation key (`redis-fence.ts`) | one round trip |
225
+ | read | `ZSCAN … COUNT 1000` (`BUST_PAGE_SIZE`), buckets concurrently | a page per round trip; returns every member present for the whole scan, so a concurrent prune or re-score skips nothing — a score/offset cursor did |
226
+ | delete | `UNLINK` per value key, 1,024 per burst | `UNLINK` frees off the server's main thread |
227
+ | sweep | `ZREM` of exactly what died, 1,000 members per command, 8 in flight | — |
228
+
229
+ 10k members clear in 25 sequential round trips (≤ 100 is the test). Every command names **one
230
+ key**, so a bust is slot-local on Redis Cluster and Dragonfly whatever tags it carries;
231
+ `{<entity>}` is still a **Redis Cluster hash tag**, so a row's bucket, its collection's and the
232
+ index share a slot. A refused `UNLINK` keeps its membership — the bust `ZREM`s only what it
233
+ deleted, including from the index a row bust never *reads* — so the retry the error asks for still
234
+ finds it. A `set` mirrors it: buckets are joined **before** the value is written and membership is
235
+ re-checked (`ZSCORE`) after, because a bust that landed in between would otherwise leave a row
236
+ nothing can reach by tag. A collection bust leaves its members in the ROW buckets it never read;
237
+ the prune and the lease bound them, and a later bust's `UNLINK` of a dead key is a no-op.
238
+
239
+ **A value is capped too**: `redisTier({ maxValueBytes })`, default `DEFAULT_REDIS_MAX_VALUE_BYTES`
240
+ (1 MiB) of encoded UTF-8, refused with `X_CACHE_TOO_LARGE` before any bucket is joined — the LRU's
241
+ `maxBytes` answer, on the rung every replica shares.
237
242
 
238
243
  **`buildId` defaults to `appVersion()`** (`APP_VERSION`, else `dev`), so two builds sharing one
239
244
  Redis cannot read each other's payloads. Rename `PostView.author` to `PostView.authorId` and
@@ -280,7 +285,7 @@ a paused server hung `stack.read` 45 s and a bust 20 s, on an action's commit pa
280
285
  | stopped | refused at once (no offline queue) → a miss | refused at once → `report.errors`; retry with the same tags |
281
286
  | back | the client reconnects on its own, every pod, no restart | answers |
282
287
 
283
- A missed deadline or a parked command is `X_CACHE_DRIVER_UNAVAILABLE` in `recentTierFailures()`,
288
+ A missed deadline or a parked command is a `cache.tier_failure` event with `X_CACHE_DRIVER_UNAVAILABLE`,
284
289
  the cause naming the deadline or the park left; a stopped server's refusal is recorded with Bun's
285
290
  own `ERR_REDIS_CONNECTION_CLOSED` message and no `code`. The client is core's `redisClient()` (`@ultimat3/core/redis`,
286
291
  `REDIS_URL`), never `Bun.redis`: its default offline queue made the first read against a stopped
@@ -303,13 +308,15 @@ for the same reason.
303
308
  `cdn` is what the dependency graph hangs off these tags, not what cleared: the `cdn` tier purges
304
309
  those paths (as surrogate keys, alongside the tags), so what actually cleared is that tier's row
305
310
  in `tiers`. With no `cdn` tier registered the list purges nowhere, which is why
306
- `recentInvalidations()` reports `busted` from `tiers` and never from `cdn` — a partial bust that
307
- reads as a clean one is the failure that log exists to catch.
311
+ the `cache.invalidate` event reports `busted` from `tiers` and never from `cdn` — a partial bust
312
+ that reads as a clean one is the failure that event exists to catch.
308
313
 
309
- Every report is also kept: `recentInvalidations()` hands back the last 100, newest first, each
310
- one naming the span that triggered it. That is the log the `/_x` cache panel renders — "did it
311
- actually clear?" is answerable without a log dive because the one fan-out path retained the
312
- answer, not because a second recorder was wired next to it.
314
+ Every bust is also one `cache.invalidate` event on core's bus (`CacheInvalidateEvent`: `tags`,
315
+ `busted`, `errors`, `durationMs`, and `source` — the span that called `invalidateTags`, else
316
+ `'invalidateTags'`; `'cache.broadcast'` for a peer's bust; a flush's own source). The `/_x` cache panel subscribes and keeps its own bounded buffer — "did it
317
+ actually clear?" is answerable without a log dive because the one fan-out path emits the answer,
318
+ not because a second recorder was wired next to it. A flush's `source` also rides on its `cache.flush`
319
+ span as `ultimate.cache.flush_source`.
313
320
 
314
321
  ### The order of one bust
315
322
 
@@ -352,6 +359,28 @@ A receiver that re-broadcast would be a storm bounded by nothing. A failed send
352
359
  What happens to that bust is the sender's (`@ultimat3/cli` keeps the refused tags, bounded, and
353
360
  publishes them when the bus returns); with no such sender the other pods clear on TTL.
354
361
 
362
+ **Which bus carries it — one rule, logged at boot as `cache.broadcast bus=… source=…`**
363
+ (`packages/cli/src/runtime-cache-bus.ts`):
364
+
365
+ | Deployment | Bus |
366
+ |---|---|
367
+ | `NATS_URL` set, or `runtime.ts` supplies a `transport` | that transport |
368
+ | no NATS, `REDIS_URL` (else `VALKEY_URL`) set — rung 1 | Redis pub/sub, `redisPubSubAt(url)` |
369
+ | neither | the in-process bus: this replica only |
370
+
371
+ `redisPubSub({ publisher, subscriber })` is the protocol, over two dedicated connections
372
+ (`REDIS_CLIENT_OPTIONS`): a subscribed connection refuses every other command, and the publisher's
373
+ `onconnect` is how the hop hears it is back. Bun 1.4.4 reconnects a dropped subscriber but the
374
+ server has forgotten the subscription and the client still holds the listener, so each connect
375
+ unsubscribes, subscribes afresh — one SUBSCRIBE/UNSUBSCRIBE at a time, or a flapping connection
376
+ registers the listener twice — then fires `onReconnect`; the CLI's listener calls
377
+ `flushProcessTiers`, because pub/sub keeps nothing for the window it was away, and publishes the
378
+ busts it deferred. A publisher connect fires `onReconnect` too: after a Redis restart the
379
+ subscriber may be back first, and the deferred busts are refused until the publisher is. A publish
380
+ on a disconnected publisher waits up to `PUBLISHER_CONNECT_WAIT_MS` (1 s) once per outage, then
381
+ refuses at once and is deferred. The channel is the hop's one subject,
382
+ unprefixed: old and new builds of one app must hear each other mid-rollout.
383
+
355
384
  **`flushProcessTiers(source)` is the repair for a process that cannot know what it missed** — its
356
385
  bus connection was down for a window, or a peer says it had more refused busts than it could keep.
357
386
  It calls `CacheTier.clear()` on every tier that has one (only a tier whose store is this process's
@@ -377,7 +406,7 @@ afterAll(restoreTags);
377
406
  |---|---|
378
407
  | `isolateDeclaredTags()` | the declared-tag set |
379
408
  | `isolateGraph()` | every tag → dependent edge, across all three indexes |
380
- | `isolateTiers()` | everything `resetTiers()` drops: the tier registry in registration order, the revalidator, the invalidation broadcast, `recentInvalidations()` and `recentTierFailures()` |
409
+ | `isolateTiers()` | everything `resetTiers()` drops: the tier registry in registration order, the revalidators and the invalidation broadcast |
381
410
 
382
411
  Each returns the function that puts back **exactly what it found**, so a per-test `resetGraph()` is
383
412
  still fine — pair it with the module-scope isolate and the process gets its baseline back. A reset
@@ -385,12 +414,8 @@ alone is not a substitute: it drops what a neighbouring file registered, and
385
414
  `@ultimat3/testing`'s leak guard compares its samples for *additions*, so the loss is invisible to
386
415
  it and surfaces as a failure in an innocent file. That is the one leak no mechanism catches for you.
387
416
  The last two live in the modules that own the state because a test file cannot reach it: the
388
- revalidator has no reader, and neither log has a writer.
389
-
390
- **`resetTierFailures()` and `isolateTierFailures()` are deliberately off `index.ts`.** Nothing
391
- outside this package clears that log except through `resetTiers()`, which `isolateTiers()` already
392
- covers — so a suite outside `packages/cache` isolates the tiers and gets the failure log with them.
393
- `recentTierFailures()` is the only member of that module the public surface carries.
417
+ revalidator has no reader. The events this package emits hold no state here: a test subscribes and
418
+ unsubscribes (core's `resetInstrumentation()` is the backstop).
394
419
 
395
420
  ## CDN
396
421
 
@@ -438,7 +463,7 @@ nothing loads that file's contents at runtime:
438
463
  A `cdn` tier holding the noop driver answers an invalidation with
439
464
  `{ tier: 'cdn', keys: [], skipped: 'no purge driver configured' }` — never a list of keys. The noop
440
465
  echoes what it is handed, so reporting its reply as accepted made every tag read as CLEARED in
441
- `report.tiers` and in `recentInvalidations().busted`, with `errors: []`, in the default state of a
466
+ `report.tiers` and in the `cache.invalidate` event's `busted`, with `errors: []`, in the default state of a
442
467
  deployment that has no CDN at all. `isNoopPurgeDriver(driver)` is the same probe, exported.
443
468
 
444
469
  Both pairs at once is `X_CONFIG_INVALID`: one process purges exactly one edge. Half a pair
@@ -485,16 +510,22 @@ a job boundary the class is gone and the `code` is what survives — match on th
485
510
  | Class | Code | Declared in |
486
511
  |---|---|---|
487
512
  | `CacheDriverUnavailableError` | `X_CACHE_DRIVER_UNAVAILABLE` | `src/errors.ts` |
488
- | `CacheJitterInvalidError` | `X_CACHE_JITTER_INVALID` | `src/errors.ts` |
489
- | `CacheLimitInvalidError` | `X_CACHE_LIMIT_INVALID` | `src/errors.ts` |
490
513
  | `CachePurgeFailedError` | `X_CACHE_PURGE_FAILED` | `src/errors.ts` |
491
- | `CacheTagUnknownError` | `X_CACHE_TAG_UNKNOWN` | `src/errors.ts` |
492
514
  | `CacheTooLargeError` | `X_CACHE_TOO_LARGE` | `src/errors.ts` |
493
- | `CacheTtlInvalidError` | `X_CACHE_TTL_INVALID` | `src/errors.ts` |
494
515
  | `CacheValueUnencodableError` | `X_CACHE_VALUE_UNENCODABLE` | `src/errors.ts` |
495
516
 
517
+ ## Writing a tier or a purge driver: `@ultimat3/cache/adapter`
518
+
519
+ `CacheTier`, `PurgeDriver`, the shapes they read and answer (`CacheEntry`, `CacheSetOptions`,
520
+ `TierInvalidation`, `TierFence`, `FenceScope`, `CacheTag`) and the errors they raise
521
+ (`CacheDriverUnavailableError`, `CachePurgeFailedError`). An app hands its own to the boot in
522
+ `apps/web/runtime.ts` — `cacheTiers: [myRedisTier]` replaces the rung of that name (`cache.tiers`
523
+ still decides which rungs exist; a supplied rung it does not name is logged `cache.tier.unnamed`
524
+ and unused), `purge: myPurgeDriver` replaces the `CLOUDFLARE_*`/`FASTLY_*` selection. The
525
+ conformance suites are `@ultimat3/testing/conformance`'s `cacheTierConformance` and
526
+ `purgeDriverConformance`.
527
+
496
528
  ## Boundary
497
529
 
498
530
  Tier 1. Imports `@ultimat3/core` and `@ultimat3/schema` only. Knows nothing about
499
- entities, HTTP or jobs — `tagsFor()` takes structural `{ name }` / `{ id }` arguments so
500
- `@ultimat3/entity` can depend on cache and never the reverse.
531
+ entities, HTTP or jobs, so `@ultimat3/entity` can depend on cache and never the reverse.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/cache",
3
- "version": "30.9.0",
3
+ "version": "31.1.0",
4
4
  "description": "Tagged caching: request memo, LRU, Redis, CDN — one invalidation graph",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -24,7 +24,8 @@
24
24
  "provenance": true
25
25
  },
26
26
  "exports": {
27
- ".": "./src/index.ts"
27
+ ".": "./src/index.ts",
28
+ "./adapter": "./src/adapter.ts"
28
29
  },
29
30
  "files": [
30
31
  "src",
@@ -42,6 +43,6 @@
42
43
  "test": "bun test"
43
44
  },
44
45
  "dependencies": {
45
- "@ultimat3/core": "30.9.0"
46
+ "@ultimat3/core": "31.1.0"
46
47
  }
47
48
  }
package/src/adapter.ts ADDED
@@ -0,0 +1,17 @@
1
+ // `@ultimat3/cache/adapter`: cache's two `ADAPTER_PORTS` rows — `cacheTiers` (`CacheTier`) and
2
+ // `purge` (`PurgeDriver`) — as an adapter author needs them: the interfaces and the errors a tier or
3
+ // a purge driver raises. No installer: the boot READS both from `apps/<app>/runtime.ts`
4
+ // (`runtime-cache.ts`), and the shipped tiers and drivers stay on `.`.
5
+
6
+ export type { PurgeDriver } from './cdn';
7
+ export { CacheDriverUnavailableError, CachePurgeFailedError } from './errors';
8
+ export type { FenceScope } from './fence';
9
+ export type { CacheTag } from './tags';
10
+ export type { FenceVerdict, TierFence } from './tier-fence';
11
+ export type {
12
+ CacheEntry,
13
+ CacheSetOptions,
14
+ CacheTier,
15
+ TierInvalidation,
16
+ TierName,
17
+ } from './tiers';
package/src/cdn.ts CHANGED
@@ -174,7 +174,7 @@ export function cdnTier(options: CdnTierOptions = {}): CacheTier {
174
174
  async invalidateTags(tags: readonly CacheTag[]): Promise<TierInvalidation> {
175
175
  // The default state of any deployment with no CDN credentials, and it has to say so: the
176
176
  // noop driver ECHOES its argument, so every tag came back as an accepted purge and
177
- // `recentInvalidations().busted` listed keys nothing had cleared, `errors: []`. `skipped`
177
+ // the invalidation event's `busted` listed keys nothing had cleared, `errors: []`. `skipped`
178
178
  // is the field that already exists for this — a tier that did not run, named as one.
179
179
  if (isNoopPurgeDriver(driver)) {
180
180
  return { tier: 'cdn', keys: [], skipped: 'no purge driver configured' };
package/src/errors.ts CHANGED
@@ -70,7 +70,8 @@ export class CacheTooLargeError extends UltimateError {
70
70
  super({
71
71
  code: 'X_CACHE_TOO_LARGE',
72
72
  cause: `entry "${input.key}" is ${input.bytes}B, over the ${input.tier} budget of ${input.maxBytes}B`,
73
- fix: `raise cache.${input.tier}.maxBytes in app.config.ts, or cache a projection instead of the row`,
73
+ // The cap is a constructor option on every tier, never an `app.config.ts` key.
74
+ fix: `${input.tier}Tier({ ${input.tier === 'redis' ? 'maxValueBytes' : 'maxBytes'}: ${String(input.bytes)} }) where the tier is built, or cache a projection instead of the row`,
74
75
  });
75
76
  }
76
77
  }
package/src/index.ts CHANGED
@@ -1,5 +1,11 @@
1
1
  // Public API of @ultimat3/cache. Explicit, no `export *`.
2
2
 
3
+ // The `cache.*` payloads are core's (the bus is tier 0); re-exported, never a second shape.
4
+ export type {
5
+ CacheInvalidateEvent,
6
+ CacheLookupEvent,
7
+ CacheTierFailureEvent,
8
+ } from '@ultimat3/core';
3
9
  export type { CacheHeaderOptions, CdnTierOptions, PurgeDriver } from './cdn';
4
10
  export {
5
11
  cacheHeaders,
@@ -10,25 +16,17 @@ export {
10
16
  } from './cdn';
11
17
  export type { CacheErrorCode } from './errors';
12
18
  export {
13
- CACHE_ERROR_CODES,
14
- CACHE_ERROR_TITLES,
15
19
  CacheDriverUnavailableError,
16
- CacheJitterInvalidError,
17
- CacheLimitInvalidError,
18
20
  CachePurgeFailedError,
19
- CacheTagUnknownError,
20
21
  CacheTooLargeError,
21
- CacheTtlInvalidError,
22
22
  CacheValueUnencodableError,
23
23
  } from './errors';
24
24
  export type { CacheFence, FenceScope } from './fence';
25
- export { FENCE_MEMORY, markInvalidated, sampleFence } from './fence';
25
+ export { markInvalidated, sampleFence } from './fence';
26
26
  export type { CacheDependent, DependentKind } from './graph';
27
27
  export {
28
28
  dependentsOf,
29
29
  dependentsOfKind,
30
- graphSize,
31
- graphSnapshot,
32
30
  isolateGraph,
33
31
  registerDependent,
34
32
  resetGraph,
@@ -36,7 +34,6 @@ export {
36
34
  } from './graph';
37
35
  export type {
38
36
  InvalidationBroadcast,
39
- InvalidationEvent,
40
37
  InvalidationReport,
41
38
  Revalidator,
42
39
  TagRevalidator,
@@ -50,36 +47,33 @@ export {
50
47
  isolateTiers,
51
48
  purgeEdgeAgain,
52
49
  receiveInvalidationBroadcast,
53
- recentInvalidations,
54
50
  registeredTiers,
55
51
  registerInvalidationBroadcast,
56
52
  registerRevalidator,
57
53
  registerTier,
58
54
  resetTiers,
59
55
  } from './invalidate';
60
- export type { LruOptions, LruStats } from './lru';
61
-
56
+ export type { LruOptions } from './lru';
62
57
  export { estimateBytes, LruCache, lruTier } from './lru';
63
- export { clearMemo, memoSize, memoTier } from './memo';
58
+ export { memoTier } from './memo';
64
59
  export type { CloudflarePurgeOptions } from './purge-cloudflare';
65
- export {
66
- CLOUDFLARE_API_URL,
67
- CLOUDFLARE_MAX_TAGS_PER_REQUEST,
68
- cloudflarePurgeDriver,
69
- } from './purge-cloudflare';
60
+ export { CLOUDFLARE_API_URL, cloudflarePurgeDriver } from './purge-cloudflare';
70
61
  export type { PurgeEnvironment, PurgeSelection } from './purge-env';
71
- export { CDN_PURGE_ENV_KEYS, selectPurgeDriver } from './purge-env';
62
+ export { selectPurgeDriver } from './purge-env';
72
63
  export type { FastlyPurgeOptions } from './purge-fastly';
73
- export { FASTLY_API_URL, FASTLY_MAX_KEYS_PER_REQUEST, fastlyPurgeDriver } from './purge-fastly';
64
+ export { fastlyPurgeDriver } from './purge-fastly';
74
65
  export type { PurgeFetch } from './purge-http';
75
- export { DEFAULT_PURGE_TIMEOUT_MS } from './purge-http';
76
66
  export type { RedisLike, RedisTierOptions } from './redis';
77
- export {
78
- namespaceFor,
79
- REDIS_INVALIDATE_SCRIPT,
80
- REDIS_TAG_MEMBER_SCRIPT,
81
- redisTier,
82
- } from './redis';
67
+ export { namespaceFor, redisTier } from './redis';
68
+ export type {
69
+ InvalidationBus,
70
+ InvalidationSubscription,
71
+ PubSubListener,
72
+ RedisPublisherLike,
73
+ RedisPubSubOptions,
74
+ RedisSubscriberLike,
75
+ } from './redis-pubsub';
76
+ export { redisPubSub, redisPubSubAt } from './redis-pubsub';
83
77
  export type {
84
78
  Embedding,
85
79
  SemanticCache,
@@ -87,7 +81,7 @@ export type {
87
81
  SemanticHit,
88
82
  SemanticRememberOptions,
89
83
  } from './semantic';
90
- export { cosineSimilarity, memorySemanticCache } from './semantic';
84
+ export { memorySemanticCache } from './semantic';
91
85
  export type { CacheTag, CacheTagRegistry, TagFactory } from './tags';
92
86
  export {
93
87
  assertKnownTags,
@@ -101,11 +95,10 @@ export {
101
95
  tag,
102
96
  tagKeys,
103
97
  tagMatches,
104
- tagsFor,
105
98
  tagsIntersect,
106
99
  } from './tags';
107
- export type { TierFailure, TierOperation } from './tier-failures';
108
- export { bestEffort, recentTierFailures } from './tier-failures';
100
+ export type { TierOperation } from './tier-failures';
101
+ export { bestEffort } from './tier-failures';
109
102
  export type { FenceVerdict, TierFence } from './tier-fence';
110
103
  export type {
111
104
  CacheEntry,