@ultimat3/cache 31.48.0 → 31.50.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 +15 -6
- package/README.md +16 -5
- package/package.json +2 -2
- package/src/errors.ts +10 -5
- package/src/index.ts +6 -3
- package/src/invalidate.ts +35 -5
- package/src/lru.ts +2 -7
- package/src/purge-cloudflare.ts +1 -1
- package/src/purge-fastly.ts +1 -1
- package/src/redis-buckets.ts +132 -17
- package/src/redis.ts +65 -26
- package/src/semantic.ts +18 -10
- package/src/shared-scopes.ts +32 -0
- package/src/tier-bounds.ts +70 -0
- package/src/tiers.ts +9 -65
package/CLAUDE.md
CHANGED
|
@@ -11,7 +11,7 @@ Tier 1. Tagged caching + THE invalidation graph.
|
|
|
11
11
|
## Rules
|
|
12
12
|
|
|
13
13
|
- **A tier's own LIMIT is screened where `app.config.ts` names it** — `assertFiniteCapacity`,
|
|
14
|
-
`assertFiniteDurationMs`, `assertFiniteSimilarityFloor
|
|
14
|
+
`assertFiniteDurationMs`, `assertFiniteSimilarityFloor` (`tier-bounds.ts`; `assertTtl` is in `tiers.ts`), all
|
|
15
15
|
raising `X_CACHE_LIMIT_INVALID`. A `NaN` limit makes every comparison false, so the guard switches
|
|
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
|
|
@@ -86,7 +86,8 @@ Tier 1. Tagged caching + THE invalidation graph.
|
|
|
86
86
|
tier is built (`assertJitterFraction`) and again at each write.
|
|
87
87
|
- **A rung's limits are constructor options, set through `runtime.ts`'s `cacheTiers`** (`As of
|
|
88
88
|
2026-11`, #1178). The boot builds `lru` and `redis` with defaults; no `app.config.ts` key exists,
|
|
89
|
-
because it would be a second spelling of that replacement
|
|
89
|
+
because it would be a second spelling of that replacement — save `cache.defaultTtlMs`, which the
|
|
90
|
+
boot passes into both rungs, so that one limit's `fix:` names it too. Every limit `fix:` names the line.
|
|
90
91
|
- **`cacheStack` is the production read path, and `@ultimat3/query`'s `readThrough` is its
|
|
91
92
|
caller** — it is what makes an action's `cache.invalidates` reach a `cache:` query.
|
|
92
93
|
- **`cacheStack` shares one in-flight `load()` per key** through `@ultimat3/core`'s
|
|
@@ -128,9 +129,12 @@ Tier 1. Tagged caching + THE invalidation graph.
|
|
|
128
129
|
- **A bust has no script.** `readBucket` pages `ZSCAN … COUNT 1000` — never a score/offset
|
|
129
130
|
cursor: a concurrent prune of a read tie group, or a re-write re-scoring a read tie member, shifts
|
|
130
131
|
an offset past live keys. `ZSCAN` returns every member present for the whole scan (the fake's
|
|
131
|
-
`ZSCAN` keeps exactly that guarantee and nothing stronger)
|
|
132
|
-
`
|
|
133
|
-
|
|
132
|
+
`ZSCAN` keeps exactly that guarantee and nothing stronger). **Sweep BEFORE delete** (`As of
|
|
133
|
+
2026-11-19`): `sweepBuckets` `ZREM`s what was read (8 in flight, settled), then `unlinkAll`
|
|
134
|
+
`UNLINK`s one key per command, then `rejoinBuckets` `ZADD … GT`s back (never lowering a fill's later score; Redis ≥ 6.2), at its read score, every member
|
|
135
|
+
whose `UNLINK` was refused — into a READ bucket only if it held it, into a collection bust's unread collection-tag bucket only if the value's own stored tags name it (`writtenUnder`); 1,000 members per `ZADD`, 8 in flight, each followed by the lease script so a re-created bucket is never immortal (`redis-rejoin.test.ts`, `redis.live.test.ts`). Delete-then-sweep orphaned a
|
|
136
|
+
fill landing between the two (`redis-ordering.test.ts`). 10k members ≤ 100 sequential round trips
|
|
137
|
+
(`roundTrips` in the fixture counts them).
|
|
134
138
|
- **A `set` joins its buckets BEFORE it writes the value, and re-checks membership after**; only a
|
|
135
139
|
literal `null` from `ZSCORE` counts as busted-in-the-air (`lostMembership`).
|
|
136
140
|
- **Every command the tier sends names ONE key** (the lease `EVAL` included), and bucket keys carry
|
|
@@ -156,7 +160,10 @@ Tier 1. Tagged caching + THE invalidation graph.
|
|
|
156
160
|
`receiveInvalidationBroadcast`; `cli` CHOOSES the bus (`runtime-cache-bus.ts`). The subscriber is
|
|
157
161
|
its own connection, and every connect unsubscribes before it subscribes (Bun keeps the old
|
|
158
162
|
listener: a bare re-subscribe delivers twice) — `redis-pubsub.test.ts`. The inbound half cannot
|
|
159
|
-
re-emit (only it passes `emit: false`)
|
|
163
|
+
re-emit (only it passes `emit: false`), and **skips a shared read tier only for the sender's own
|
|
164
|
+
scope** (`shared-scopes.ts`): a fenced tier whose `CacheTier.scope` (redis: its namespace, per
|
|
165
|
+
build) equals what the frame's `SharedTierScopes` names. No scope on either side, or another
|
|
166
|
+
build's, is a bust — a rolling deploy's two namespaces each need theirs (`broadcast.test.ts`). The edge is still purged. An undeclared inbound tag goes to `report.errors`, never a
|
|
160
167
|
throw.
|
|
161
168
|
- **A `cdn` tier holding `noopPurgeDriver()` reports `skipped`, never keys** (`isNoopPurgeDriver`,
|
|
162
169
|
in `cdn.ts`). **`report.cdn` is what depends; `report.tiers` is what cleared** — `busted` is built
|
|
@@ -198,6 +205,7 @@ Tier 1. Tagged caching + THE invalidation graph.
|
|
|
198
205
|
| `tags.ts` | `tag` factory, wire form, match semantics, `tagKeys`, declared-tag registry |
|
|
199
206
|
| `graph.ts` | tag → dependents (cache keys, ISR routes, CDN paths, live queries) |
|
|
200
207
|
| `tiers.ts` | `CacheTier`, `TierLabel`, `assertTtl`, read-through stack |
|
|
208
|
+
| `tier-bounds.ts` | `assertFiniteCapacity` / `assertFiniteDurationMs` / `assertFiniteSimilarityFloor`: a tier's other screened knobs |
|
|
201
209
|
| `fence.ts` | the invalidation fence a fill (here or in `query`) checks before it publishes |
|
|
202
210
|
| `tier-leading.ts` | which fence each in-flight load holds, and whether a reader may join it |
|
|
203
211
|
| `tier-fence.ts` | `TierFence`/`FenceVerdict`, and how a fill samples and asks a shared tier's fence |
|
|
@@ -222,6 +230,7 @@ Tier 1. Tagged caching + THE invalidation graph.
|
|
|
222
230
|
| `purge-cloudflare.ts` | `cloudflarePurgeDriver`: cache-tag purge, `purge_everything` |
|
|
223
231
|
| `purge-env.ts` | `selectPurgeDriver`: which edge an environment purges, and nothing else |
|
|
224
232
|
| `invalidate.ts` | the single entry point, `InvalidationReport`, and the `cache.invalidate` event |
|
|
233
|
+
| `shared-scopes.ts` | which shared tiers a broadcast names as cleared (`SharedTierScopes`), and which a receiver may skip |
|
|
225
234
|
| `cache-events-fixture.ts` | tests only: `recordCacheEvents()`, the `cache.*` events a test caused |
|
|
226
235
|
| `semantic.ts` | embedding cache for LLM calls |
|
|
227
236
|
|
package/README.md
CHANGED
|
@@ -292,15 +292,18 @@ pod whose clock runs ahead from pruning a member whose value key still lives.
|
|
|
292
292
|
|---|---|---|
|
|
293
293
|
| fence | `SET` per generation key (`redis-fence.ts`) | one round trip |
|
|
294
294
|
| 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 |
|
|
295
|
+
| sweep | `ZREM` of what was read, 1,000 members per command, 8 in flight | — |
|
|
295
296
|
| delete | `UNLINK` per value key, 1,024 per burst | `UNLINK` frees off the server's main thread |
|
|
296
|
-
|
|
|
297
|
+
| re-join | `ZADD … GT` back, at its read score unless a fill since scored it later, each member whose `UNLINK` was refused (Redis ≥ 6.2) | only on a refusal |
|
|
297
298
|
|
|
298
299
|
10k members clear in 25 sequential round trips (≤ 100 is the test). Every command names **one
|
|
299
300
|
key**, so a bust is slot-local on Redis Cluster and Dragonfly whatever tags it carries;
|
|
300
301
|
`{<entity>}` is still a **Redis Cluster hash tag**, so a row's bucket, its collection's and the
|
|
301
|
-
index share a slot.
|
|
302
|
-
|
|
303
|
-
|
|
302
|
+
index share a slot. **Sweep before delete** (`As of 2026-11-19`): a fill from another replica that
|
|
303
|
+
landed between a delete and a later sweep re-joined a member the sweep then removed — a live value
|
|
304
|
+
no bust could reach, stale for its whole TTL. A refused `UNLINK` is re-joined to the buckets it
|
|
305
|
+
left (a bucket the bust read only if it held it, so a row never joins its collection's), including
|
|
306
|
+
the index a row bust never *reads*, so the retry the error asks for still finds it. A `set` mirrors it: buckets are joined **before** the value is written and membership is
|
|
304
307
|
re-checked (`ZSCORE`) after, because a bust that landed in between would otherwise leave a row
|
|
305
308
|
nothing can reach by tag. A collection bust leaves its members in the ROW buckets it never read;
|
|
306
309
|
the prune and the lease bound them, and a later bust's `UNLINK` of a dead key is a no-op.
|
|
@@ -431,7 +434,15 @@ bus.subscribe('cache.invalidate', (wireTags) => receiveInvalidationBroadcast(wir
|
|
|
431
434
|
|
|
432
435
|
The inbound half **cannot** re-emit, and that is structural rather than a flag: `emit` lives on the
|
|
433
436
|
private fan-out options and `receiveInvalidationBroadcast` is the only caller that passes `false`.
|
|
434
|
-
A receiver that re-broadcast would be a storm bounded by nothing.
|
|
437
|
+
A receiver that re-broadcast would be a storm bounded by nothing. Inbound, a **shared** read tier
|
|
438
|
+
(one with a `fence`, as `redisTier` has) is skipped, `As of 2026-11-19`, **only when the sender
|
|
439
|
+
cleared the same keys**: `fn`'s second argument (`SharedTierScopes`, tier name → `CacheTier.scope`,
|
|
440
|
+
the Redis namespace — per build) names what its bust cleared, the frame carries it, and
|
|
441
|
+
`receiveInvalidationBroadcast(wireTags, sender)` skips a fenced tier whose `scope` equals the
|
|
442
|
+
sender's. Another build's frame on a rolling deploy (`x:v1` vs `x:v2`), a frame naming no scope (an
|
|
443
|
+
older pod), or a fenced tier with no `scope` is busted — a skipped bust is a stale row for the TTL.
|
|
444
|
+
Within one build, a second bust per replica deleted what readers had refilled since.
|
|
445
|
+
The in-process tiers and the edge are still cleared. A failed send lands in
|
|
435
446
|
`report.errors` under `tier: "broadcast"` and the write that triggered the bust still succeeds.
|
|
436
447
|
What happens to that bust is the sender's (`@ultimat3/cli` keeps the refused tags, bounded, and
|
|
437
448
|
publishes them when the bus returns); with no such sender the other pods clear on TTL.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultimat3/cache",
|
|
3
|
-
"version": "31.
|
|
3
|
+
"version": "31.50.0",
|
|
4
4
|
"description": "Tagged caching: request memo, LRU, Redis, CDN — one invalidation graph",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ultimate",
|
|
@@ -43,6 +43,6 @@
|
|
|
43
43
|
"test": "bun test"
|
|
44
44
|
},
|
|
45
45
|
"dependencies": {
|
|
46
|
-
"@ultimat3/core": "31.
|
|
46
|
+
"@ultimat3/core": "31.50.0"
|
|
47
47
|
}
|
|
48
48
|
}
|
package/src/errors.ts
CHANGED
|
@@ -70,7 +70,8 @@ export class CacheTagUnknownError extends UltimateError {
|
|
|
70
70
|
/**
|
|
71
71
|
* Where an app tunes a rung. The boot builds `lru` and `redis` with their defaults and takes a
|
|
72
72
|
* replacement from `runtime.ts`'s `cacheTiers`: the one way, so every fix below names it. Limits
|
|
73
|
-
* are not `app.config.ts` keys — they would be a second spelling of that same replacement
|
|
73
|
+
* are not `app.config.ts` keys — they would be a second spelling of that same replacement — save
|
|
74
|
+
* `cache.defaultTtlMs`, which the boot passes into the rungs it builds (`optionHome` says so).
|
|
74
75
|
*/
|
|
75
76
|
const RUNG_FILE = 'apps/web/runtime.ts';
|
|
76
77
|
|
|
@@ -151,10 +152,14 @@ const LIMIT_OWNER: Readonly<Record<string, string>> = {
|
|
|
151
152
|
function optionHome(tier: string, option: string, example: string): string {
|
|
152
153
|
// `hasOwn`: `tier` is a caller's string, and `constructor` must not read the prototype.
|
|
153
154
|
const owner = Object.hasOwn(LIMIT_OWNER, tier) ? LIMIT_OWNER[tier] : tier;
|
|
154
|
-
const
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
155
|
+
const built = tier === 'lru' || tier === 'redis';
|
|
156
|
+
const rung = built
|
|
157
|
+
? `; for the rung a boot builds, cacheTiers: [${owner}({ ${option}: ${example} })] in ${RUNG_FILE}`
|
|
158
|
+
: '';
|
|
159
|
+
// The one limit the boot also reads from config: it hands `cache.defaultTtlMs` to both rungs.
|
|
160
|
+
if (built && option === 'defaultTtlMs') {
|
|
161
|
+
return `${owner}(...)${rung}, or cache.defaultTtlMs in app.config.ts, which the boot passes to the lru and redis rungs it builds`;
|
|
162
|
+
}
|
|
158
163
|
return `${owner}(...)${rung} — a constructor option, never an app.config.ts key`;
|
|
159
164
|
}
|
|
160
165
|
|
package/src/index.ts
CHANGED
|
@@ -86,6 +86,7 @@ export type {
|
|
|
86
86
|
SemanticRememberOptions,
|
|
87
87
|
} from './semantic';
|
|
88
88
|
export { memorySemanticCache } from './semantic';
|
|
89
|
+
export type { SharedTierScopes } from './shared-scopes';
|
|
89
90
|
export type { CacheTag, CacheTagRegistry, TagFactory } from './tags';
|
|
90
91
|
export {
|
|
91
92
|
assertKnownTags,
|
|
@@ -101,6 +102,11 @@ export {
|
|
|
101
102
|
tagMatches,
|
|
102
103
|
tagsIntersect,
|
|
103
104
|
} from './tags';
|
|
105
|
+
export {
|
|
106
|
+
assertFiniteCapacity,
|
|
107
|
+
assertFiniteDurationMs,
|
|
108
|
+
assertFiniteSimilarityFloor,
|
|
109
|
+
} from './tier-bounds';
|
|
104
110
|
export type { TierOperation } from './tier-failures';
|
|
105
111
|
export { bestEffort } from './tier-failures';
|
|
106
112
|
export type { FenceVerdict, TierFence } from './tier-fence';
|
|
@@ -118,9 +124,6 @@ export type {
|
|
|
118
124
|
TtlScope,
|
|
119
125
|
} from './tiers';
|
|
120
126
|
export {
|
|
121
|
-
assertFiniteCapacity,
|
|
122
|
-
assertFiniteDurationMs,
|
|
123
|
-
assertFiniteSimilarityFloor,
|
|
124
127
|
assertTtl,
|
|
125
128
|
cacheStack,
|
|
126
129
|
DEFAULT_LOAD_DEADLINE_MS,
|
package/src/invalidate.ts
CHANGED
|
@@ -17,6 +17,8 @@ import {
|
|
|
17
17
|
import { markAllInvalidated, markInvalidated } from './fence';
|
|
18
18
|
import { dependentsOfKind, graphSnapshot } from './graph';
|
|
19
19
|
import { logPartial, resetPartialLog } from './partial-log';
|
|
20
|
+
import type { SharedTierScopes } from './shared-scopes';
|
|
21
|
+
import { clearedBySender, sharedScopes } from './shared-scopes';
|
|
20
22
|
import type { CacheTag } from './tags';
|
|
21
23
|
import { assertKnownTags, knownTags, parseTag, serializeTags } from './tags';
|
|
22
24
|
import type { CacheTier, TierInvalidation } from './tiers';
|
|
@@ -46,7 +48,14 @@ export const EVERY_TAG = 'every-tag';
|
|
|
46
48
|
* on pod 3, their next request lands on pod 7, and pod 7's in-process copy serves the pre-edit
|
|
47
49
|
* value for up to `defaultTtlMs`. The user watches their edit vanish and re-submits.
|
|
48
50
|
*/
|
|
49
|
-
export type InvalidationBroadcast = (
|
|
51
|
+
export type InvalidationBroadcast = (
|
|
52
|
+
wireTags: readonly string[],
|
|
53
|
+
/**
|
|
54
|
+
* What this process's own bust cleared in each shared tier: carry it to the peers. The fan-out
|
|
55
|
+
* always passes it; optional in the type so the 31.48 shape stays compatible.
|
|
56
|
+
*/
|
|
57
|
+
sender?: SharedTierScopes,
|
|
58
|
+
) => Promise<void> | void;
|
|
50
59
|
|
|
51
60
|
export interface InvalidationReport {
|
|
52
61
|
readonly tags: readonly string[];
|
|
@@ -159,7 +168,11 @@ export function invalidateTags(tags: readonly CacheTag[]): Promise<InvalidationR
|
|
|
159
168
|
* pods know an entity the old ones do not, and a throw here kills the subscriber loop that
|
|
160
169
|
* delivered it — which would silently end cross-instance invalidation for the whole process.
|
|
161
170
|
*/
|
|
162
|
-
export function receiveInvalidationBroadcast(
|
|
171
|
+
export function receiveInvalidationBroadcast(
|
|
172
|
+
wire: readonly string[],
|
|
173
|
+
/** The sender's `SharedTierScopes`; omitted (an older pod's frame), every tier is cleared. */
|
|
174
|
+
sender?: SharedTierScopes,
|
|
175
|
+
): Promise<InvalidationReport> {
|
|
163
176
|
const declared = new Set(knownTags());
|
|
164
177
|
const errors: { tier: string; message: string }[] = [];
|
|
165
178
|
const accepted: CacheTag[] = [];
|
|
@@ -169,7 +182,13 @@ export function receiveInvalidationBroadcast(wire: readonly string[]): Promise<I
|
|
|
169
182
|
if (declared.size === 0 || declared.has(parsed.entity)) accepted.push(parsed);
|
|
170
183
|
else errors.push({ tier: 'broadcast', message: `ignored undeclared tag "${value}"` });
|
|
171
184
|
}
|
|
172
|
-
return fanOut(accepted, {
|
|
185
|
+
return fanOut(accepted, {
|
|
186
|
+
source: 'cache.broadcast',
|
|
187
|
+
emit: false,
|
|
188
|
+
validate: false,
|
|
189
|
+
errors,
|
|
190
|
+
...(sender === undefined ? {} : { sender }),
|
|
191
|
+
});
|
|
173
192
|
}
|
|
174
193
|
|
|
175
194
|
interface FanOutOptions {
|
|
@@ -180,6 +199,8 @@ interface FanOutOptions {
|
|
|
180
199
|
/** The local path throws on a typo; the inbound one has already filtered instead. */
|
|
181
200
|
readonly validate: boolean;
|
|
182
201
|
readonly errors: { tier: string; message: string }[];
|
|
202
|
+
/** Inbound only: the shared scopes the sender's own bust already cleared. */
|
|
203
|
+
readonly sender?: SharedTierScopes;
|
|
183
204
|
}
|
|
184
205
|
|
|
185
206
|
function fanOut(tags: readonly CacheTag[], options: FanOutOptions): Promise<InvalidationReport> {
|
|
@@ -206,7 +227,12 @@ function fanOut(tags: readonly CacheTag[], options: FanOutOptions): Promise<Inva
|
|
|
206
227
|
// report says every tier cleared, and the LRU is stale again before the call returns.
|
|
207
228
|
// The EDGE is not one of them here: it is purged last, below (`purgeEdge`).
|
|
208
229
|
const farthestFirst = [...sortTiers(registry)].reverse();
|
|
209
|
-
|
|
230
|
+
// Inbound, a shared tier the sender's own bust already cleared is skipped (`clearedBySender`).
|
|
231
|
+
// The edge is not: a peer's purge after its own drop is the one that holds (`purgeEdgeAgain`).
|
|
232
|
+
const readTiers = farthestFirst.filter(
|
|
233
|
+
(one) => !isEdgeTier(one) && (emit || !clearedBySender(one, options.sender)),
|
|
234
|
+
);
|
|
235
|
+
for (const tier of readTiers) {
|
|
210
236
|
try {
|
|
211
237
|
tiers.push(await tier.invalidateTags(tags));
|
|
212
238
|
cleared.push(tier.name);
|
|
@@ -251,7 +277,11 @@ function fanOut(tags: readonly CacheTag[], options: FanOutOptions): Promise<Inva
|
|
|
251
277
|
// to "the other pods clear on TTL" rather than failing the write that triggered the bust.
|
|
252
278
|
if (emit && wire.length > 0 && broadcast !== undefined) {
|
|
253
279
|
try {
|
|
254
|
-
|
|
280
|
+
// Only what ANSWERED: a shared tier whose bust was refused here is the peers' to clear.
|
|
281
|
+
await broadcast(
|
|
282
|
+
wire,
|
|
283
|
+
sharedScopes(farthestFirst.filter((one) => cleared.includes(one.name))),
|
|
284
|
+
);
|
|
255
285
|
cleared.push('broadcast');
|
|
256
286
|
} catch (error) {
|
|
257
287
|
errors.push({ tier: 'broadcast', message: renderThrowable(error) });
|
package/src/lru.ts
CHANGED
|
@@ -9,6 +9,7 @@ import { utf8ByteLength } from './byte-length';
|
|
|
9
9
|
import { CacheTooLargeError } from './errors';
|
|
10
10
|
import type { CacheTag } from './tags';
|
|
11
11
|
import { serializeTag } from './tags';
|
|
12
|
+
import { assertFiniteCapacity, assertFiniteDurationMs } from './tier-bounds';
|
|
12
13
|
import type {
|
|
13
14
|
CacheEntry,
|
|
14
15
|
CacheSetOptions,
|
|
@@ -17,13 +18,7 @@ import type {
|
|
|
17
18
|
TierInvalidation,
|
|
18
19
|
TtlJitter,
|
|
19
20
|
} from './tiers';
|
|
20
|
-
import {
|
|
21
|
-
assertFiniteCapacity,
|
|
22
|
-
assertFiniteDurationMs,
|
|
23
|
-
assertJitterFraction,
|
|
24
|
-
assertTtl,
|
|
25
|
-
nowMs,
|
|
26
|
-
} from './tiers';
|
|
21
|
+
import { assertJitterFraction, assertTtl, nowMs } from './tiers';
|
|
27
22
|
import { decodeCacheValue, encodeCacheValue } from './value-codec';
|
|
28
23
|
|
|
29
24
|
export interface LruOptions {
|
package/src/purge-cloudflare.ts
CHANGED
|
@@ -17,7 +17,7 @@ import {
|
|
|
17
17
|
purgePost,
|
|
18
18
|
requireCredential,
|
|
19
19
|
} from './purge-http';
|
|
20
|
-
import { assertFiniteDurationMs } from './
|
|
20
|
+
import { assertFiniteDurationMs } from './tier-bounds';
|
|
21
21
|
|
|
22
22
|
export const CLOUDFLARE_API_URL = 'https://api.cloudflare.com/client/v4';
|
|
23
23
|
|
package/src/purge-fastly.ts
CHANGED
package/src/redis-buckets.ts
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
import { CacheDriverUnavailableError } from './errors';
|
|
7
7
|
import type { RedisLike } from './redis';
|
|
8
8
|
import type { CacheTag } from './tags';
|
|
9
|
+
import { decodeCacheValue } from './value-codec';
|
|
9
10
|
|
|
10
11
|
/**
|
|
11
12
|
* How long a member outlives its value key, in ms. The score is the WRITER's clock and the prune
|
|
@@ -55,6 +56,8 @@ export function bucketLayout(ns: string) {
|
|
|
55
56
|
const entityKey = (entity: string): string => `${ns}:e2:{${entity}}`;
|
|
56
57
|
return {
|
|
57
58
|
valueKey: (key: string): string => `${ns}:c:${key}`,
|
|
59
|
+
/** The bare collection tag's bucket — the one a collection bust sweeps but never reads. */
|
|
60
|
+
collectionBucketOf: (entity: string): string => tagKey({ entity }),
|
|
58
61
|
/** A write joins its tag's bucket plus its entity's index. */
|
|
59
62
|
writeBucketsFor: (owned: CacheTag): string[] => [tagKey(owned), entityKey(owned.entity)],
|
|
60
63
|
/**
|
|
@@ -118,17 +121,25 @@ export async function lostMembership(
|
|
|
118
121
|
}
|
|
119
122
|
|
|
120
123
|
/** `[cursor, [member, score, …]]` — flat in RESP2 and RESP3 alike; `[member, score]` pairs read too. */
|
|
121
|
-
function scanPage(
|
|
124
|
+
function scanPage(
|
|
125
|
+
reply: unknown,
|
|
126
|
+
bucket: string,
|
|
127
|
+
): { readonly cursor: string; entries: [string, string][] } {
|
|
122
128
|
if (!Array.isArray(reply) || reply.length !== 2 || !Array.isArray(reply[1])) {
|
|
123
129
|
throw unreadable(bucket);
|
|
124
130
|
}
|
|
125
|
-
const [cursor,
|
|
131
|
+
const [cursor, flat] = reply as [unknown, unknown[]];
|
|
126
132
|
if (typeof cursor !== 'string' && typeof cursor !== 'number') throw unreadable(bucket);
|
|
127
|
-
const
|
|
128
|
-
? (
|
|
129
|
-
:
|
|
130
|
-
|
|
131
|
-
|
|
133
|
+
const pairs = flat.every(Array.isArray)
|
|
134
|
+
? (flat as unknown[][]).map(([member, score]) => [member, score])
|
|
135
|
+
: flat.flatMap((member, i) => (i % 2 === 0 ? [[member, flat[i + 1]]] : []));
|
|
136
|
+
// RESP3 answers a score as a double, RESP2 as text: either is kept as the text `ZADD` takes.
|
|
137
|
+
const entries = pairs.map(([member, score]) => {
|
|
138
|
+
if (typeof member !== 'string') throw unreadable(bucket);
|
|
139
|
+
if (typeof score !== 'string' && typeof score !== 'number') throw unreadable(bucket);
|
|
140
|
+
return [member, String(score)] as [string, string];
|
|
141
|
+
});
|
|
142
|
+
return { cursor: String(cursor), entries };
|
|
132
143
|
}
|
|
133
144
|
|
|
134
145
|
const unreadable = (bucket: string): CacheDriverUnavailableError =>
|
|
@@ -139,23 +150,23 @@ const unreadable = (bucket: string): CacheDriverUnavailableError =>
|
|
|
139
150
|
});
|
|
140
151
|
|
|
141
152
|
/**
|
|
142
|
-
* Every member of one bucket, `ZSCAN … COUNT BUST_PAGE_SIZE` per round trip. `ZSCAN`, never a
|
|
153
|
+
* Every member of one bucket with its score, `ZSCAN … COUNT BUST_PAGE_SIZE` per round trip. `ZSCAN`, never a
|
|
143
154
|
* score cursor: Redis guarantees a scan returns every member present from its first call to its
|
|
144
155
|
* last, whatever is added, removed or re-scored meanwhile. A `(score, offset)` cursor broke on
|
|
145
156
|
* exactly those — a concurrent prune of a read page of tied dead members, or a re-write moving a
|
|
146
157
|
* read tie member up, shifted the offset past live keys, which served stale until TTL. A scan
|
|
147
|
-
* may return a member twice; the
|
|
158
|
+
* may return a member twice; the map dedupes. The score is what a refused delete is re-joined at.
|
|
148
159
|
*/
|
|
149
|
-
export async function readBucket(client: RedisLike, bucket: string): Promise<string
|
|
150
|
-
const members = new
|
|
160
|
+
export async function readBucket(client: RedisLike, bucket: string): Promise<Map<string, string>> {
|
|
161
|
+
const members = new Map<string, string>();
|
|
151
162
|
let cursor = '0';
|
|
152
163
|
do {
|
|
153
164
|
const reply = await client.send('ZSCAN', [bucket, cursor, 'COUNT', String(BUST_PAGE_SIZE)]);
|
|
154
165
|
const page = scanPage(reply, bucket);
|
|
155
|
-
for (const member of page.
|
|
166
|
+
for (const [member, score] of page.entries) members.set(member, score);
|
|
156
167
|
cursor = page.cursor;
|
|
157
168
|
} while (cursor !== '0');
|
|
158
|
-
return
|
|
169
|
+
return members;
|
|
159
170
|
}
|
|
160
171
|
|
|
161
172
|
/** `UNLINK` each key on its own (slot-local), pipelined per batch; which ones died is the answer. */
|
|
@@ -178,19 +189,48 @@ export async function unlinkAll(
|
|
|
178
189
|
return { deleted, failures };
|
|
179
190
|
}
|
|
180
191
|
|
|
181
|
-
/**
|
|
192
|
+
/** Which members each bucket really lost, and every `ZREM` the store refused. */
|
|
193
|
+
export interface SweepResult {
|
|
194
|
+
readonly removed: Map<string, Set<string>>;
|
|
195
|
+
readonly failures: unknown[];
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* `ZREM` the members from every bucket named, `SWEEP_CONCURRENCY` commands in flight. Settled, never
|
|
200
|
+
* rejected: a refused chunk leaves its members where they were, which is a bucket still reaching
|
|
201
|
+
* them, and the caller must still delete the values the chunks that WERE removed point at.
|
|
202
|
+
*/
|
|
182
203
|
export async function sweepBuckets(
|
|
183
204
|
client: RedisLike,
|
|
184
205
|
gone: ReadonlyMap<string, ReadonlySet<string>>,
|
|
185
|
-
): Promise<
|
|
186
|
-
const
|
|
206
|
+
): Promise<SweepResult> {
|
|
207
|
+
const removed = new Map<string, Set<string>>();
|
|
208
|
+
const failures: unknown[] = [];
|
|
209
|
+
const work: (() => Promise<void>)[] = [];
|
|
187
210
|
for (const [bucket, members] of gone) {
|
|
188
211
|
const list = [...members];
|
|
189
212
|
for (let start = 0; start < list.length; start += SWEEP_CHUNK) {
|
|
190
213
|
const chunk = list.slice(start, start + SWEEP_CHUNK);
|
|
191
|
-
work.push(() =>
|
|
214
|
+
work.push(() =>
|
|
215
|
+
client.send('ZREM', [bucket, ...chunk]).then(
|
|
216
|
+
() => {
|
|
217
|
+
const into = removed.get(bucket) ?? new Set<string>();
|
|
218
|
+
for (const member of chunk) into.add(member);
|
|
219
|
+
removed.set(bucket, into);
|
|
220
|
+
},
|
|
221
|
+
(reason: unknown) => {
|
|
222
|
+
failures.push(reason);
|
|
223
|
+
},
|
|
224
|
+
),
|
|
225
|
+
);
|
|
192
226
|
}
|
|
193
227
|
}
|
|
228
|
+
await inFlight(work);
|
|
229
|
+
return { removed, failures };
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** Run `work`, `SWEEP_CONCURRENCY` at a time. Each task settles its own failure. */
|
|
233
|
+
async function inFlight(work: readonly (() => Promise<void>)[]): Promise<void> {
|
|
194
234
|
let next = 0;
|
|
195
235
|
const worker = async (): Promise<void> => {
|
|
196
236
|
while (next < work.length) {
|
|
@@ -201,3 +241,78 @@ export async function sweepBuckets(
|
|
|
201
241
|
};
|
|
202
242
|
await Promise.all(Array.from({ length: Math.min(SWEEP_CONCURRENCY, work.length) }, worker));
|
|
203
243
|
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Put back every member whose value key the store refused to delete, in each bucket the sweep took
|
|
247
|
+
* it out of, at the score its bucket read gave it — so the retry the error asks for still reaches
|
|
248
|
+
* it. `SWEEP_CHUNK` members per `ZADD`, `SWEEP_CONCURRENCY` in flight, as the sweep: a large bust
|
|
249
|
+
* whose deletes failed must not answer with one command per member per bucket. Each `ZADD` is
|
|
250
|
+
* followed by the bucket's lease: one the sweep emptied is re-created by it, and a bucket with no
|
|
251
|
+
* TTL outlives every value it names. Settled: what the store refuses is reported, never thrown.
|
|
252
|
+
*/
|
|
253
|
+
export async function rejoinBuckets(
|
|
254
|
+
client: RedisLike,
|
|
255
|
+
removed: ReadonlyMap<string, ReadonlySet<string>>,
|
|
256
|
+
survivors: ReadonlyMap<string, string>,
|
|
257
|
+
now: number,
|
|
258
|
+
): Promise<unknown[]> {
|
|
259
|
+
if (survivors.size === 0) return [];
|
|
260
|
+
const failures: unknown[] = [];
|
|
261
|
+
const work: (() => Promise<void>)[] = [];
|
|
262
|
+
for (const [bucket, members] of removed) {
|
|
263
|
+
const back = [...members].flatMap((member) => {
|
|
264
|
+
const score = survivors.get(member);
|
|
265
|
+
return score === undefined ? [] : [[score, member] as const];
|
|
266
|
+
});
|
|
267
|
+
for (let start = 0; start < back.length; start += SWEEP_CHUNK) {
|
|
268
|
+
const chunk = back.slice(start, start + SWEEP_CHUNK);
|
|
269
|
+
const latest = Math.max(...chunk.map(([score]) => Number(score)));
|
|
270
|
+
const lease = String(Math.max(1, Math.ceil((latest - now) / 1_000)));
|
|
271
|
+
// `GT` (Redis 6.2+): a fill that re-joined since, at a LATER score, keeps it. The read score
|
|
272
|
+
// written over it made the membership prunable while the fill's value still lived.
|
|
273
|
+
const args = [bucket, 'GT', ...chunk.flat()];
|
|
274
|
+
work.push(() =>
|
|
275
|
+
client
|
|
276
|
+
.send('ZADD', args)
|
|
277
|
+
.then(() => client.send('EVAL', [REDIS_TAG_LEASE_SCRIPT, '1', bucket, lease]))
|
|
278
|
+
.then(
|
|
279
|
+
() => undefined,
|
|
280
|
+
(reason: unknown) => void failures.push(reason),
|
|
281
|
+
),
|
|
282
|
+
);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
await inFlight(work);
|
|
286
|
+
return failures;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Which of `members` were written under `tag` — read off each value's own stored tag list, for a
|
|
291
|
+
* bucket a bust swept but never read. A value that cannot be read answers yes: an extra member
|
|
292
|
+
* costs a miss, a missing one serves stale. Only on a refused delete, `SWEEP_CONCURRENCY` at once.
|
|
293
|
+
*/
|
|
294
|
+
export async function writtenUnder(
|
|
295
|
+
client: RedisLike,
|
|
296
|
+
members: ReadonlySet<string>,
|
|
297
|
+
tag: string,
|
|
298
|
+
): Promise<Set<string>> {
|
|
299
|
+
const held = new Set<string>();
|
|
300
|
+
const work = [...members].map((member) => async (): Promise<void> => {
|
|
301
|
+
const tags = await client.get(member).then(storedTags, () => undefined);
|
|
302
|
+
if (tags === undefined || tags.includes(tag)) held.add(member);
|
|
303
|
+
});
|
|
304
|
+
await inFlight(work);
|
|
305
|
+
return held;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** The `t` list of a stored entry, or `undefined` when the text is gone or not one. */
|
|
309
|
+
function storedTags(text: string | null): readonly string[] | undefined {
|
|
310
|
+
if (text === null) return undefined;
|
|
311
|
+
try {
|
|
312
|
+
const entry = decodeCacheValue(text);
|
|
313
|
+
const tags = typeof entry === 'object' && entry !== null ? Reflect.get(entry, 't') : undefined;
|
|
314
|
+
return Array.isArray(tags) ? tags.filter((each) => typeof each === 'string') : undefined;
|
|
315
|
+
} catch {
|
|
316
|
+
return undefined;
|
|
317
|
+
}
|
|
318
|
+
}
|
package/src/redis.ts
CHANGED
|
@@ -14,14 +14,17 @@ import {
|
|
|
14
14
|
joinBuckets,
|
|
15
15
|
lostMembership,
|
|
16
16
|
readBucket,
|
|
17
|
+
rejoinBuckets,
|
|
17
18
|
sweepBuckets,
|
|
18
19
|
unlinkAll,
|
|
20
|
+
writtenUnder,
|
|
19
21
|
} from './redis-buckets';
|
|
20
22
|
import type { DeadlinedRedis } from './redis-deadline';
|
|
21
23
|
import { DEFAULT_REDIS_COMMAND_TIMEOUT_MS, withinDeadline } from './redis-deadline';
|
|
22
24
|
import { bumpGenerations, sampleGenerations } from './redis-fence';
|
|
23
25
|
import type { CacheTag } from './tags';
|
|
24
26
|
import { parseTag, serializeTag } from './tags';
|
|
27
|
+
import { assertFiniteCapacity, assertFiniteDurationMs } from './tier-bounds';
|
|
25
28
|
import type {
|
|
26
29
|
CacheEntry,
|
|
27
30
|
CacheSetOptions,
|
|
@@ -30,13 +33,7 @@ import type {
|
|
|
30
33
|
TierInvalidation,
|
|
31
34
|
TtlJitter,
|
|
32
35
|
} from './tiers';
|
|
33
|
-
import {
|
|
34
|
-
assertFiniteCapacity,
|
|
35
|
-
assertFiniteDurationMs,
|
|
36
|
-
assertJitterFraction,
|
|
37
|
-
assertTtl,
|
|
38
|
-
nowMs,
|
|
39
|
-
} from './tiers';
|
|
36
|
+
import { assertJitterFraction, assertTtl, nowMs } from './tiers';
|
|
40
37
|
import { decodeCacheValue, encodeCacheValue } from './value-codec';
|
|
41
38
|
|
|
42
39
|
/** The slice of Bun's Redis client this tier uses. Narrow on purpose: easy to fake in tests. */
|
|
@@ -137,16 +134,17 @@ function leaseFrom(reply: unknown): Lease {
|
|
|
137
134
|
* the operator sees which key the store refused rather than a count.
|
|
138
135
|
*
|
|
139
136
|
* The `fix:` is the call, not a command: there is no `x cache` in this build, and the retry is one
|
|
140
|
-
* line of the app's own code. It is safe to repeat because every key the store refused
|
|
141
|
-
*
|
|
137
|
+
* line of the app's own code. It is safe to repeat because every key the store refused to delete
|
|
138
|
+
* is re-joined to the buckets the sweep took it out of (`rejoinBuckets`), and a refused `ZREM` left
|
|
139
|
+
* its members where they were.
|
|
142
140
|
*/
|
|
143
141
|
function raiseSweepFailure(failures: readonly unknown[], attempted: number): never {
|
|
144
142
|
const first = failures[0];
|
|
145
143
|
if (first instanceof Error) throw first;
|
|
146
144
|
throw new CacheDriverUnavailableError({
|
|
147
145
|
driver: 'redis',
|
|
148
|
-
cause:
|
|
149
|
-
fix: "await invalidateTags(tags) again once redis answers — from '@ultimat3/cache', with the same tags; every key it
|
|
146
|
+
cause: `redis refused ${String(failures.length)} command(s) of a bust over ${String(attempted)} value keys`,
|
|
147
|
+
fix: "await invalidateTags(tags) again once redis answers — from '@ultimat3/cache', with the same tags; every key it could not delete was put back in its buckets, so the retry reaches it",
|
|
150
148
|
});
|
|
151
149
|
}
|
|
152
150
|
|
|
@@ -202,7 +200,8 @@ export function redisTier(options: RedisTierOptions = {}): CacheTier {
|
|
|
202
200
|
// A bust skips the park: skipped for a stall, it leaves stale rows serving until TTL.
|
|
203
201
|
const bustConn = (): RedisLike => views().bust;
|
|
204
202
|
|
|
205
|
-
const { valueKey, writeBucketsFor, bustBucketsFor, sweepBucketsFor } =
|
|
203
|
+
const { valueKey, writeBucketsFor, bustBucketsFor, sweepBucketsFor, collectionBucketOf } =
|
|
204
|
+
bucketLayout(ns);
|
|
206
205
|
|
|
207
206
|
const tier: CacheTier = {
|
|
208
207
|
name: 'redis',
|
|
@@ -287,10 +286,20 @@ export function redisTier(options: RedisTierOptions = {}): CacheTier {
|
|
|
287
286
|
/** The fleet-wide half of the fill fence: generations other replicas' busts move. */
|
|
288
287
|
fence: (scope: FenceScope) => sampleGenerations(conn(), ns, clock, scope),
|
|
289
288
|
|
|
289
|
+
/** The namespace a bust sweeps — per build by default, so two builds are two scopes. */
|
|
290
|
+
scope: ns,
|
|
291
|
+
|
|
290
292
|
/**
|
|
291
|
-
* Read every bucket the tags match, a page per round trip and the buckets concurrently;
|
|
292
|
-
*
|
|
293
|
-
* names one key, so a bust is slot-local on Redis
|
|
293
|
+
* Read every bucket the tags match, a page per round trip and the buckets concurrently; `ZREM`
|
|
294
|
+
* what they held; THEN `UNLINK` it, one key per command; and re-join any member whose value
|
|
295
|
+
* the store refused to delete. Every command names one key, so a bust is slot-local on Redis
|
|
296
|
+
* Cluster whatever tags it carries.
|
|
297
|
+
*
|
|
298
|
+
* Sweep before delete, never after: another replica's fill can land between the two. After a
|
|
299
|
+
* delete, its `ZADD` re-joins a member the later sweep then removes — a live value no tag
|
|
300
|
+
* reaches, missed by every later bust and stale for the whole TTL. Before it, the fill's
|
|
301
|
+
* membership either lands after the sweep (and survives, reachable) or before it, where its
|
|
302
|
+
* own `ZSCORE` re-check finds it gone and deletes the value (`set`).
|
|
294
303
|
*/
|
|
295
304
|
async invalidateTags(tags: readonly CacheTag[]): Promise<TierInvalidation> {
|
|
296
305
|
const claimed = new Set<string>();
|
|
@@ -309,27 +318,57 @@ export function redisTier(options: RedisTierOptions = {}): CacheTier {
|
|
|
309
318
|
await bumpGenerations(bustConn(), ns, tags);
|
|
310
319
|
const buckets = [...claimed];
|
|
311
320
|
const pages = await Promise.all(buckets.map((bucket) => readBucket(bustConn(), bucket)));
|
|
312
|
-
const held = new Map(buckets.map((bucket, i) => [bucket, pages[i] ??
|
|
321
|
+
const held = new Map(buckets.map((bucket, i) => [bucket, pages[i] ?? new Map()]));
|
|
313
322
|
// A member may sit in two buckets; deleting it twice is harmless but reporting it twice
|
|
314
|
-
// makes the `/_x` panel overstate what cleared.
|
|
315
|
-
const
|
|
316
|
-
const
|
|
323
|
+
// makes the `/_x` panel overstate what cleared. Its highest score is the one it re-joins at.
|
|
324
|
+
const scores = new Map<string, string>();
|
|
325
|
+
for (const page of pages) {
|
|
326
|
+
for (const [member, score] of page) {
|
|
327
|
+
const seen = scores.get(member);
|
|
328
|
+
if (seen === undefined || Number(score) > Number(seen)) scores.set(member, score);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
const members = [...scores.keys()];
|
|
317
332
|
|
|
318
|
-
// Only what actually died leaves its buckets. A member the store refused to delete keeps its
|
|
319
|
-
// membership, so the retry `report.errors` asks for still finds it.
|
|
320
333
|
const gone = new Map<string, Set<string>>();
|
|
321
334
|
for (const { read, sweep } of perTag) {
|
|
322
|
-
const
|
|
323
|
-
if (
|
|
335
|
+
const found = read.flatMap((bucket) => [...(held.get(bucket)?.keys() ?? [])]);
|
|
336
|
+
if (found.length === 0) continue;
|
|
324
337
|
for (const bucket of sweep) {
|
|
325
338
|
const into = gone.get(bucket) ?? new Set<string>();
|
|
326
|
-
for (const member of
|
|
339
|
+
for (const member of found) into.add(member);
|
|
327
340
|
gone.set(bucket, into);
|
|
328
341
|
}
|
|
329
342
|
}
|
|
330
|
-
await sweepBuckets(bustConn(), gone);
|
|
343
|
+
const swept = await sweepBuckets(bustConn(), gone);
|
|
344
|
+
const { deleted, failures } = await unlinkAll(bustConn(), members);
|
|
331
345
|
|
|
332
|
-
|
|
346
|
+
// A member the store refused to delete goes back into the buckets it left, so the retry
|
|
347
|
+
// `report.errors` asks for still finds it. A bucket this bust READ gets back only what it
|
|
348
|
+
// held — a row in its collection's bucket would die with every other row's bust. One it only
|
|
349
|
+
// swept is unknown, so it gets the member back: the entity index holds every write's member
|
|
350
|
+
// by construction, and an extra member there costs a miss, where a missing one serves stale.
|
|
351
|
+
// The one other unread bucket is a collection bust's collection-tag bucket: a row-only
|
|
352
|
+
// member put there dies with every later row bust, so the value's own tags decide.
|
|
353
|
+
const survivors = new Map([...scores].filter(([member]) => !deleted.has(member)));
|
|
354
|
+
const unreadTag = new Map(
|
|
355
|
+
tags
|
|
356
|
+
.filter((owned) => owned.id === undefined)
|
|
357
|
+
.map((owned) => [collectionBucketOf(owned.entity), serializeTag(owned)] as const),
|
|
358
|
+
);
|
|
359
|
+
const left = new Map<string, ReadonlySet<string>>();
|
|
360
|
+
for (const [bucket, out] of swept.removed) {
|
|
361
|
+
const read = held.get(bucket);
|
|
362
|
+
const back = [...out].filter((m) => survivors.has(m) && (read?.has(m) ?? true));
|
|
363
|
+
const tag = read === undefined ? unreadTag.get(bucket) : undefined;
|
|
364
|
+
left.set(
|
|
365
|
+
bucket,
|
|
366
|
+
tag === undefined ? new Set(back) : await writtenUnder(bustConn(), new Set(back), tag),
|
|
367
|
+
);
|
|
368
|
+
}
|
|
369
|
+
const lost = await rejoinBuckets(bustConn(), left, survivors, nowMs(clock));
|
|
370
|
+
const refused = [...failures, ...swept.failures, ...lost];
|
|
371
|
+
if (refused.length > 0) raiseSweepFailure(refused, members.length);
|
|
333
372
|
const stripped = [...deleted].map((key) => key.slice(valueKey('').length));
|
|
334
373
|
return { tier: 'redis', keys: stripped };
|
|
335
374
|
},
|
package/src/semantic.ts
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
// Keyed by embedding, matched by cosine similarity above a threshold — exact string keys miss on
|
|
3
3
|
// "list my orders" vs "show me my orders", which is most of the traffic.
|
|
4
4
|
//
|
|
5
|
-
// The in-memory default is correct but O(n)
|
|
6
|
-
//
|
|
5
|
+
// The in-memory default is correct but O(n), and as of 2026-11 it is the only implementation: no
|
|
6
|
+
// Postgres/pgvector-backed one exists. The interface is a driver so an app can supply one.
|
|
7
7
|
|
|
8
8
|
import type { Clock } from '@ultimat3/core';
|
|
9
9
|
import { systemClock } from '@ultimat3/core';
|
|
@@ -13,9 +13,9 @@ import {
|
|
|
13
13
|
assertFiniteCapacity,
|
|
14
14
|
assertFiniteDurationMs,
|
|
15
15
|
assertFiniteSimilarityFloor,
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
} from './
|
|
16
|
+
} from './tier-bounds';
|
|
17
|
+
import { assertTtl, nowMs } from './tiers';
|
|
18
|
+
import { decodeCacheValue, encodeCacheValue } from './value-codec';
|
|
19
19
|
|
|
20
20
|
export type Embedding = readonly number[];
|
|
21
21
|
|
|
@@ -85,7 +85,11 @@ export function cosineSimilarity(a: Embedding, b: Embedding): number {
|
|
|
85
85
|
interface SemanticRecord {
|
|
86
86
|
readonly key: string;
|
|
87
87
|
readonly embedding: Embedding;
|
|
88
|
-
|
|
88
|
+
/**
|
|
89
|
+
* `{ v }` as `value-codec.ts` text, as the LRU tier holds it — never the caller's object, or a
|
|
90
|
+
* hit is the writer's live object and one reader's edit is every later reader's answer.
|
|
91
|
+
*/
|
|
92
|
+
readonly text: string;
|
|
89
93
|
readonly expiresAt: number;
|
|
90
94
|
readonly tags: readonly CacheTag[];
|
|
91
95
|
}
|
|
@@ -128,7 +132,7 @@ export function memorySemanticCache(options: SemanticCacheOptions = {}): Semanti
|
|
|
128
132
|
override,
|
|
129
133
|
'the override argument to lookup(embedding, override)',
|
|
130
134
|
);
|
|
131
|
-
let best:
|
|
135
|
+
let best: { readonly record: SemanticRecord; readonly similarity: number } | undefined;
|
|
132
136
|
for (const record of live()) {
|
|
133
137
|
const similarity = cosineSimilarity(embedding, record.embedding);
|
|
134
138
|
// A similarity that is not a number is not a match. Every comparison against `NaN` is
|
|
@@ -138,10 +142,13 @@ export function memorySemanticCache(options: SemanticCacheOptions = {}): Semanti
|
|
|
138
142
|
if (!Number.isFinite(similarity)) continue;
|
|
139
143
|
if (similarity < floor) continue;
|
|
140
144
|
if (best === undefined || similarity > best.similarity) {
|
|
141
|
-
best = {
|
|
145
|
+
best = { record, similarity };
|
|
142
146
|
}
|
|
143
147
|
}
|
|
144
|
-
return Promise.resolve(
|
|
148
|
+
if (best === undefined) return Promise.resolve(undefined);
|
|
149
|
+
// Decoded once, for the winner only: a fresh object per hit.
|
|
150
|
+
const { v } = decodeCacheValue(best.record.text) as { readonly v: T };
|
|
151
|
+
return Promise.resolve({ value: v, similarity: best.similarity, key: best.record.key });
|
|
145
152
|
},
|
|
146
153
|
|
|
147
154
|
remember<T>(
|
|
@@ -157,11 +164,12 @@ export function memorySemanticCache(options: SemanticCacheOptions = {}): Semanti
|
|
|
157
164
|
const ttlMs = assertTtl(key, rememberOptions?.ttlMs ?? defaultTtlMs, 'semantic', {
|
|
158
165
|
jitterFraction: 0,
|
|
159
166
|
});
|
|
167
|
+
const text = encodeCacheValue({ v: value }, { key, tier: 'semantic' });
|
|
160
168
|
records.delete(key);
|
|
161
169
|
records.set(key, {
|
|
162
170
|
key,
|
|
163
171
|
embedding,
|
|
164
|
-
|
|
172
|
+
text,
|
|
165
173
|
expiresAt: nowMs(clock) + ttlMs,
|
|
166
174
|
tags: rememberOptions?.tags ?? [],
|
|
167
175
|
});
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// Which shared tiers a cross-instance broadcast names as already cleared, and which of them a
|
|
2
|
+
// receiver may therefore skip. Kept apart from the fan-out so the skip rule has one home.
|
|
3
|
+
|
|
4
|
+
import type { CacheTier } from './tiers';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Shared tier name → the `CacheTier.scope` a bust cleared there. A broadcast carries the sender's,
|
|
8
|
+
* so a receiver skips only the shared tiers whose keys the sender's own bust already reached: on a
|
|
9
|
+
* rolling deploy the two builds' Redis namespaces differ, and each must still be busted.
|
|
10
|
+
*/
|
|
11
|
+
export type SharedTierScopes = Readonly<Record<string, string>>;
|
|
12
|
+
|
|
13
|
+
/** What this process's bust clears in each shared tier — the `sender` its broadcast carries. */
|
|
14
|
+
export function sharedScopes(tiers: readonly CacheTier[]): SharedTierScopes {
|
|
15
|
+
const scopes: Record<string, string> = {};
|
|
16
|
+
for (const tier of tiers) {
|
|
17
|
+
if (tier.fence !== undefined && tier.scope !== undefined) scopes[tier.name] = tier.scope;
|
|
18
|
+
}
|
|
19
|
+
return scopes;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Inbound, a SHARED read tier is skipped only when the sender's bust reached the very keys this
|
|
24
|
+
* one holds: same tier, same `scope`. A second bust per replica deleted what readers refilled
|
|
25
|
+
* since and re-fenced their fills. Any doubt clears it — a frame naming no scope (an older pod),
|
|
26
|
+
* another build's namespace on a rolling deploy, a fenced tier with no `scope` — because a skipped
|
|
27
|
+
* bust is a pre-write row for the whole TTL, and a needless one is one more load.
|
|
28
|
+
*/
|
|
29
|
+
export function clearedBySender(tier: CacheTier, sender: SharedTierScopes | undefined): boolean {
|
|
30
|
+
if (tier.fence === undefined || tier.scope === undefined || sender === undefined) return false;
|
|
31
|
+
return Object.hasOwn(sender, tier.name) && sender[tier.name] === tier.scope;
|
|
32
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// The bounds a tier's constructor screens besides its TTL: a ceiling (bytes or entries), a
|
|
2
|
+
// millisecond duration, the semantic tier's similarity floor. Split from `tiers.ts` (its 500-line
|
|
3
|
+
// ceiling); `assertTtl` and the jitter screen stay there, beside the lease they apply.
|
|
4
|
+
|
|
5
|
+
import { CacheLimitInvalidError } from './errors';
|
|
6
|
+
import type { TtlScope } from './tiers';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* A tier's ceiling — bytes or entries — screened where it is still nameable. The same rule as
|
|
10
|
+
* `assertTtl` in `tiers.ts`, over the other knob a tier's constructor takes. A SEPARATE refusal
|
|
11
|
+
* from `X_CACHE_TOO_LARGE`, which is one entry against a valid ceiling: this one is the ceiling
|
|
12
|
+
* itself, and it needs a screen because a bad ceiling refuses nothing and evicts nothing rather
|
|
13
|
+
* than refusing everything. `NaN > x` and `x > NaN` are both false.
|
|
14
|
+
*/
|
|
15
|
+
export function assertFiniteCapacity(tier: TtlScope, option: string, value: number): number {
|
|
16
|
+
if (Number.isSafeInteger(value) && value > 0) return value;
|
|
17
|
+
throw new CacheLimitInvalidError({
|
|
18
|
+
tier,
|
|
19
|
+
option,
|
|
20
|
+
value,
|
|
21
|
+
expected: 'a whole number greater than zero',
|
|
22
|
+
example: '10_000',
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* A millisecond duration: a driver's request budget (handed to `AbortSignal.timeout`, which THROWS
|
|
28
|
+
* on a non-finite one — inside `purgePost`'s try, so the config typo came back as a retryable
|
|
29
|
+
* transport failure that never happened) and a tier's own `defaultTtlMs`, which is otherwise only
|
|
30
|
+
* screened by `assertTtl` at the first `set`, one write into the process's life.
|
|
31
|
+
*
|
|
32
|
+
* The `Finite` in all three names here is NOT load-bearing, `As of 2026-08-26`. It was: a name
|
|
33
|
+
* regex meant `assertCapacity` and `assertTimeoutMs` left all nine of this package's options
|
|
34
|
+
* reading as unchecked while every one of them was screened. `bun run finite-bounds` now reads
|
|
35
|
+
* `SCREENING_CALLEES` in `scripts/lib/finite-screens.ts` — rename freely, move the rows.
|
|
36
|
+
*/
|
|
37
|
+
export function assertFiniteDurationMs(tier: string, option: string, value: number): number {
|
|
38
|
+
if (Number.isSafeInteger(value) && value > 0) return value;
|
|
39
|
+
throw new CacheLimitInvalidError({
|
|
40
|
+
tier,
|
|
41
|
+
option,
|
|
42
|
+
value,
|
|
43
|
+
expected: 'a whole number of milliseconds greater than zero',
|
|
44
|
+
example: '60_000',
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The similarity floor the semantic tier decides "same question" with — a correctness boundary,
|
|
50
|
+
* not a tuning knob, so `NaN` here does not loosen it, it removes it: `similarity < NaN` is false
|
|
51
|
+
* for every record. Cosine similarity is in [-1, 1] and a floor of 0 already admits an orthogonal
|
|
52
|
+
* vector, so anything outside [0, 1] is a number nobody can have meant.
|
|
53
|
+
*/
|
|
54
|
+
export function assertFiniteSimilarityFloor(
|
|
55
|
+
tier: TtlScope,
|
|
56
|
+
option: string,
|
|
57
|
+
value: number,
|
|
58
|
+
/** Passed only where the value is a CALL argument rather than a factory option. */
|
|
59
|
+
source?: string | undefined,
|
|
60
|
+
): number {
|
|
61
|
+
if (Number.isFinite(value) && value >= 0 && value <= 1) return value;
|
|
62
|
+
throw new CacheLimitInvalidError({
|
|
63
|
+
tier,
|
|
64
|
+
option,
|
|
65
|
+
value,
|
|
66
|
+
expected: 'a number from 0 to 1',
|
|
67
|
+
example: '0.92',
|
|
68
|
+
source,
|
|
69
|
+
});
|
|
70
|
+
}
|
package/src/tiers.ts
CHANGED
|
@@ -5,11 +5,12 @@
|
|
|
5
5
|
|
|
6
6
|
import type { CacheTierName, Clock, Scheduler } from '@ultimat3/core';
|
|
7
7
|
import { CACHE_TIERS, instrument, singleFlight, systemClock, tryUseContext } from '@ultimat3/core';
|
|
8
|
-
import { CacheJitterInvalidError,
|
|
8
|
+
import { CacheJitterInvalidError, CacheTtlInvalidError } from './errors';
|
|
9
9
|
import type { CacheFence, FenceScope } from './fence';
|
|
10
10
|
import { markInvalidated, sampleFence } from './fence';
|
|
11
11
|
import { mergeSetOptions, tagsAddedSince, ttlOptionsFor } from './set-options';
|
|
12
12
|
import type { CacheTag } from './tags';
|
|
13
|
+
import { assertFiniteDurationMs } from './tier-bounds';
|
|
13
14
|
import { bestEffort } from './tier-failures';
|
|
14
15
|
import type { TierFence, TierFences } from './tier-fence';
|
|
15
16
|
import { sampleTierFences, verdictOf } from './tier-fence';
|
|
@@ -101,70 +102,6 @@ export interface CacheSetOptions {
|
|
|
101
102
|
*/
|
|
102
103
|
export type TtlScope = TierName | 'semantic';
|
|
103
104
|
|
|
104
|
-
/**
|
|
105
|
-
* A tier's ceiling — bytes or entries — screened where it is still nameable. The same rule as
|
|
106
|
-
* `assertTtl` beside it, over the other knob a tier's constructor takes. A SEPARATE refusal from
|
|
107
|
-
* `X_CACHE_TOO_LARGE`, which is one entry against a valid ceiling: this one is the ceiling itself,
|
|
108
|
-
* and it needs a screen because a bad ceiling refuses nothing and evicts nothing rather than
|
|
109
|
-
* refusing everything. `NaN > x` and `x > NaN` are both false.
|
|
110
|
-
*/
|
|
111
|
-
export function assertFiniteCapacity(tier: TtlScope, option: string, value: number): number {
|
|
112
|
-
if (Number.isSafeInteger(value) && value > 0) return value;
|
|
113
|
-
throw new CacheLimitInvalidError({
|
|
114
|
-
tier,
|
|
115
|
-
option,
|
|
116
|
-
value,
|
|
117
|
-
expected: 'a whole number greater than zero',
|
|
118
|
-
example: '10_000',
|
|
119
|
-
});
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
/**
|
|
123
|
-
* A millisecond duration: a driver's request budget (handed to `AbortSignal.timeout`, which THROWS
|
|
124
|
-
* on a non-finite one — inside `purgePost`'s try, so the config typo came back as a retryable
|
|
125
|
-
* transport failure that never happened) and a tier's own `defaultTtlMs`, which is otherwise only
|
|
126
|
-
* screened by `assertTtl` at the first `set`, one write into the process's life.
|
|
127
|
-
*
|
|
128
|
-
* The `Finite` in all three names here is NOT load-bearing, `As of 2026-08-26`. It was: a name
|
|
129
|
-
* regex meant `assertCapacity` and `assertTimeoutMs` left all nine of this package's options
|
|
130
|
-
* reading as unchecked while every one of them was screened. `bun run finite-bounds` now reads
|
|
131
|
-
* `SCREENING_CALLEES` in `scripts/lib/finite-screens.ts` — rename freely, move the rows.
|
|
132
|
-
*/
|
|
133
|
-
export function assertFiniteDurationMs(tier: string, option: string, value: number): number {
|
|
134
|
-
if (Number.isSafeInteger(value) && value > 0) return value;
|
|
135
|
-
throw new CacheLimitInvalidError({
|
|
136
|
-
tier,
|
|
137
|
-
option,
|
|
138
|
-
value,
|
|
139
|
-
expected: 'a whole number of milliseconds greater than zero',
|
|
140
|
-
example: '60_000',
|
|
141
|
-
});
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
/**
|
|
145
|
-
* The similarity floor the semantic tier decides "same question" with — a correctness boundary,
|
|
146
|
-
* not a tuning knob, so `NaN` here does not loosen it, it removes it: `similarity < NaN` is false
|
|
147
|
-
* for every record. Cosine similarity is in [-1, 1] and a floor of 0 already admits an orthogonal
|
|
148
|
-
* vector, so anything outside [0, 1] is a number nobody can have meant.
|
|
149
|
-
*/
|
|
150
|
-
export function assertFiniteSimilarityFloor(
|
|
151
|
-
tier: TtlScope,
|
|
152
|
-
option: string,
|
|
153
|
-
value: number,
|
|
154
|
-
/** Passed only where the value is a CALL argument rather than a factory option. */
|
|
155
|
-
source?: string | undefined,
|
|
156
|
-
): number {
|
|
157
|
-
if (Number.isFinite(value) && value >= 0 && value <= 1) return value;
|
|
158
|
-
throw new CacheLimitInvalidError({
|
|
159
|
-
tier,
|
|
160
|
-
option,
|
|
161
|
-
value,
|
|
162
|
-
expected: 'a number from 0 to 1',
|
|
163
|
-
example: '0.92',
|
|
164
|
-
source,
|
|
165
|
-
});
|
|
166
|
-
}
|
|
167
|
-
|
|
168
105
|
/**
|
|
169
106
|
* A tier's TTL spread, screened when the tier is BUILT as well as at each write: found only at the
|
|
170
107
|
* first `set`, a bad fraction refused every write of a tier that had booted healthy.
|
|
@@ -213,6 +150,13 @@ export interface CacheTier {
|
|
|
213
150
|
* may never be told about — still stops the fill (`tier-fence.ts`). Omitted by in-process tiers.
|
|
214
151
|
*/
|
|
215
152
|
fence?(scope: FenceScope): Promise<TierFence>;
|
|
153
|
+
/**
|
|
154
|
+
* Which entries this tier's bust clears, as a string a peer can compare: two tiers of one name
|
|
155
|
+
* and one `scope` hold the same keys (`redisTier`: its namespace, so per build). Only read beside
|
|
156
|
+
* `fence`: an inbound broadcast skips a fenced tier ONLY when the sender named this same scope —
|
|
157
|
+
* omitted, the tier is cleared on every inbound broadcast.
|
|
158
|
+
*/
|
|
159
|
+
readonly scope?: string;
|
|
216
160
|
/**
|
|
217
161
|
* Drop every entry — implemented ONLY by a tier whose store is this process's own heap (`lru`).
|
|
218
162
|
* `flushProcessTiers()` calls it when the process cannot know which busts it missed. A shared
|