@ultimat3/cache 31.47.1 → 31.49.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 +19 -6
- package/README.md +20 -6
- package/package.json +2 -2
- package/src/errors.ts +30 -12
- package/src/index.ts +7 -4
- package/src/invalidate.ts +35 -5
- package/src/lru.ts +5 -1
- 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 +81 -21
- package/src/semantic.ts +18 -10
- package/src/shared-scopes.ts +32 -0
- package/src/tier-bounds.ts +70 -0
- package/src/tiers.ts +18 -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
|
|
@@ -82,7 +82,12 @@ Tier 1. Tagged caching + THE invalidation graph.
|
|
|
82
82
|
included (scope `'semantic'`, `jitterFraction: 0`). `X_CACHE_TTL_INVALID`, never a resolution.
|
|
83
83
|
- **`assertTtl` also SPREADS the lease it validated.** `rng` is injected (`LruOptions.rng`,
|
|
84
84
|
`RedisTierOptions.rng`) — never `Math.random()` at a call site; `rng: () => 0` is the full lease.
|
|
85
|
-
`jitterFraction` outside `[0, 1)` is `X_CACHE_JITTER_INVALID`, refused, not clamped
|
|
85
|
+
`jitterFraction` outside `[0, 1)` is `X_CACHE_JITTER_INVALID`, refused, not clamped, when the
|
|
86
|
+
tier is built (`assertJitterFraction`) and again at each write.
|
|
87
|
+
- **A rung's limits are constructor options, set through `runtime.ts`'s `cacheTiers`** (`As of
|
|
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 — 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.
|
|
86
91
|
- **`cacheStack` is the production read path, and `@ultimat3/query`'s `readThrough` is its
|
|
87
92
|
caller** — it is what makes an action's `cache.invalidates` reach a `cache:` query.
|
|
88
93
|
- **`cacheStack` shares one in-flight `load()` per key** through `@ultimat3/core`'s
|
|
@@ -124,9 +129,12 @@ Tier 1. Tagged caching + THE invalidation graph.
|
|
|
124
129
|
- **A bust has no script.** `readBucket` pages `ZSCAN … COUNT 1000` — never a score/offset
|
|
125
130
|
cursor: a concurrent prune of a read tie group, or a re-write re-scoring a read tie member, shifts
|
|
126
131
|
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)
|
|
128
|
-
`
|
|
129
|
-
|
|
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).
|
|
130
138
|
- **A `set` joins its buckets BEFORE it writes the value, and re-checks membership after**; only a
|
|
131
139
|
literal `null` from `ZSCORE` counts as busted-in-the-air (`lostMembership`).
|
|
132
140
|
- **Every command the tier sends names ONE key** (the lease `EVAL` included), and bucket keys carry
|
|
@@ -152,7 +160,10 @@ Tier 1. Tagged caching + THE invalidation graph.
|
|
|
152
160
|
`receiveInvalidationBroadcast`; `cli` CHOOSES the bus (`runtime-cache-bus.ts`). The subscriber is
|
|
153
161
|
its own connection, and every connect unsubscribes before it subscribes (Bun keeps the old
|
|
154
162
|
listener: a bare re-subscribe delivers twice) — `redis-pubsub.test.ts`. The inbound half cannot
|
|
155
|
-
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
|
|
156
167
|
throw.
|
|
157
168
|
- **A `cdn` tier holding `noopPurgeDriver()` reports `skipped`, never keys** (`isNoopPurgeDriver`,
|
|
158
169
|
in `cdn.ts`). **`report.cdn` is what depends; `report.tiers` is what cleared** — `busted` is built
|
|
@@ -194,6 +205,7 @@ Tier 1. Tagged caching + THE invalidation graph.
|
|
|
194
205
|
| `tags.ts` | `tag` factory, wire form, match semantics, `tagKeys`, declared-tag registry |
|
|
195
206
|
| `graph.ts` | tag → dependents (cache keys, ISR routes, CDN paths, live queries) |
|
|
196
207
|
| `tiers.ts` | `CacheTier`, `TierLabel`, `assertTtl`, read-through stack |
|
|
208
|
+
| `tier-bounds.ts` | `assertFiniteCapacity` / `assertFiniteDurationMs` / `assertFiniteSimilarityFloor`: a tier's other screened knobs |
|
|
197
209
|
| `fence.ts` | the invalidation fence a fill (here or in `query`) checks before it publishes |
|
|
198
210
|
| `tier-leading.ts` | which fence each in-flight load holds, and whether a reader may join it |
|
|
199
211
|
| `tier-fence.ts` | `TierFence`/`FenceVerdict`, and how a fill samples and asks a shared tier's fence |
|
|
@@ -218,6 +230,7 @@ Tier 1. Tagged caching + THE invalidation graph.
|
|
|
218
230
|
| `purge-cloudflare.ts` | `cloudflarePurgeDriver`: cache-tag purge, `purge_everything` |
|
|
219
231
|
| `purge-env.ts` | `selectPurgeDriver`: which edge an environment purges, and nothing else |
|
|
220
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 |
|
|
221
234
|
| `cache-events-fixture.ts` | tests only: `recordCacheEvents()`, the `cache.*` events a test caused |
|
|
222
235
|
| `semantic.ts` | embedding cache for LLM calls |
|
|
223
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.
|
|
@@ -611,7 +622,10 @@ a job boundary the class is gone and the `code` is what survives — match on th
|
|
|
611
622
|
(`CacheDriverUnavailableError`, `CachePurgeFailedError`). An app hands its own to the boot in
|
|
612
623
|
`apps/web/runtime.ts` — `cacheTiers: [myRedisTier]` replaces the rung of that name (`cache.tiers`
|
|
613
624
|
still decides which rungs exist; a supplied rung it does not name is logged `cache.tier.unnamed`
|
|
614
|
-
and unused)
|
|
625
|
+
and unused). It is also the one way to set a built-in rung's limits: `cacheTiers: [lruTier({
|
|
626
|
+
maxBytes })]`, never an `app.config.ts` key. A `redisTier` with no `client` and no `REDIS_URL` or
|
|
627
|
+
`VALKEY_URL` dials the local server, and the boot logs `cache.tier.default-redis`
|
|
628
|
+
(`usesDefaultRedisClient`). `purge: myPurgeDriver` replaces the `CLOUDFLARE_*`/`FASTLY_*` selection. The
|
|
615
629
|
conformance suites are `@ultimat3/testing/conformance`'s `cacheTierConformance` and
|
|
616
630
|
`purgeDriverConformance`.
|
|
617
631
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultimat3/cache",
|
|
3
|
-
"version": "31.
|
|
3
|
+
"version": "31.49.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.49.0"
|
|
47
47
|
}
|
|
48
48
|
}
|
package/src/errors.ts
CHANGED
|
@@ -67,11 +67,18 @@ export class CacheTagUnknownError extends UltimateError {
|
|
|
67
67
|
}
|
|
68
68
|
}
|
|
69
69
|
|
|
70
|
+
/**
|
|
71
|
+
* Where an app tunes a rung. The boot builds `lru` and `redis` with their defaults and takes a
|
|
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 — save
|
|
74
|
+
* `cache.defaultTtlMs`, which the boot passes into the rungs it builds (`optionHome` says so).
|
|
75
|
+
*/
|
|
76
|
+
const RUNG_FILE = 'apps/web/runtime.ts';
|
|
77
|
+
|
|
70
78
|
/** A single entry cannot fit the tier's byte budget, so caching it would evict everything. */
|
|
71
79
|
export class CacheTooLargeError extends UltimateError {
|
|
72
80
|
constructor(input: { key: string; bytes: number; maxBytes: number; tier: string }) {
|
|
73
81
|
const bytes = String(input.bytes);
|
|
74
|
-
// The cap is a constructor option on every tier, never an `app.config.ts` key.
|
|
75
82
|
const raise =
|
|
76
83
|
input.tier === 'redis'
|
|
77
84
|
? `redisTier({ maxValueBytes: ${bytes} })`
|
|
@@ -79,7 +86,7 @@ export class CacheTooLargeError extends UltimateError {
|
|
|
79
86
|
super({
|
|
80
87
|
code: 'X_CACHE_TOO_LARGE',
|
|
81
88
|
cause: `entry "${input.key}" is ${input.bytes}B, over the ${input.tier} budget of ${input.maxBytes}B`,
|
|
82
|
-
fix:
|
|
89
|
+
fix: `cacheTiers: [${raise}] // in ${RUNG_FILE}, replacing the rung the boot builds — or cache a projection instead of the row`,
|
|
83
90
|
});
|
|
84
91
|
}
|
|
85
92
|
}
|
|
@@ -128,10 +135,7 @@ const limitEffect = (value: number): string =>
|
|
|
128
135
|
? ', and every comparison against NaN is false, so the limit stops being enforced rather than being enforced wrongly — NaN is what Number(process.env.…) answers for an unset variable, and it is not nullish, so `??` does not catch it'
|
|
129
136
|
: ', and it is applied as given, so the tier is bounded at a value nobody chose';
|
|
130
137
|
|
|
131
|
-
/**
|
|
132
|
-
* The factory each scope's limits are constructor options of — the fix names where the corrected
|
|
133
|
-
* option goes. None is an `app.config.ts` key: the runtime builds every tier with defaults.
|
|
134
|
-
*/
|
|
138
|
+
/** The factory each scope's limits are constructor options of: where the corrected one goes. */
|
|
135
139
|
const LIMIT_OWNER: Readonly<Record<string, string>> = {
|
|
136
140
|
lru: 'lruTier',
|
|
137
141
|
redis: 'redisTier',
|
|
@@ -141,6 +145,24 @@ const LIMIT_OWNER: Readonly<Record<string, string>> = {
|
|
|
141
145
|
ladder: 'cacheStack',
|
|
142
146
|
};
|
|
143
147
|
|
|
148
|
+
/**
|
|
149
|
+
* Where a corrected tier option goes. `lru` and `redis` are the rungs a boot builds, so theirs also
|
|
150
|
+
* names the `cacheTiers` line: an app on the defaults has no `lruTier(...)` call of its own to edit.
|
|
151
|
+
*/
|
|
152
|
+
function optionHome(tier: string, option: string, example: string): string {
|
|
153
|
+
// `hasOwn`: `tier` is a caller's string, and `constructor` must not read the prototype.
|
|
154
|
+
const owner = Object.hasOwn(LIMIT_OWNER, tier) ? LIMIT_OWNER[tier] : tier;
|
|
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
|
+
}
|
|
163
|
+
return `${owner}(...)${rung} — a constructor option, never an app.config.ts key`;
|
|
164
|
+
}
|
|
165
|
+
|
|
144
166
|
export class CacheLimitInvalidError extends UltimateError {
|
|
145
167
|
constructor(input: {
|
|
146
168
|
option: string;
|
|
@@ -155,9 +177,7 @@ export class CacheLimitInvalidError extends UltimateError {
|
|
|
155
177
|
*/
|
|
156
178
|
source?: string | undefined;
|
|
157
179
|
}) {
|
|
158
|
-
const where =
|
|
159
|
-
input.source ??
|
|
160
|
-
`${LIMIT_OWNER[input.tier] ?? input.tier}(...) — a constructor option, never an app.config.ts key`;
|
|
180
|
+
const where = input.source ?? optionHome(input.tier, input.option, input.example);
|
|
161
181
|
super({
|
|
162
182
|
code: 'X_CACHE_LIMIT_INVALID',
|
|
163
183
|
cause: `the ${input.tier} tier was given ${input.option}=${String(input.value)}; it must be ${input.expected}${limitEffect(input.value)}`,
|
|
@@ -205,9 +225,7 @@ export class CacheJitterInvalidError extends UltimateError {
|
|
|
205
225
|
cause: `the ${input.tier} tier was configured with jitterFraction=${String(
|
|
206
226
|
input.jitterFraction,
|
|
207
227
|
)}; a jitter fraction is a finite number in [0, 1)`,
|
|
208
|
-
|
|
209
|
-
// tiers with none (`runtime-cache.ts`), so the config path this used to name did not exist.
|
|
210
|
-
fix: `{ jitterFraction: 0.05 } // in the ${input.tier} tier's lruTier({ ... }) or redisTier({ ... }): a value in [0, 1) — 0.05 is the default, 0 disables jitter`,
|
|
228
|
+
fix: `{ jitterFraction: 0.05 } // a value in [0, 1) — 0.05 is the default, 0 disables jitter — in ${optionHome(input.tier, 'jitterFraction', '0.05')}`,
|
|
211
229
|
meta: { tier: input.tier, jitterFraction: input.jitterFraction },
|
|
212
230
|
});
|
|
213
231
|
}
|
package/src/index.ts
CHANGED
|
@@ -68,7 +68,7 @@ export type { FastlyPurgeOptions } from './purge-fastly';
|
|
|
68
68
|
export { fastlyPurgeDriver } from './purge-fastly';
|
|
69
69
|
export type { PurgeFetch } from './purge-http';
|
|
70
70
|
export type { RedisLike, RedisTierOptions } from './redis';
|
|
71
|
-
export { namespaceFor, redisTier } from './redis';
|
|
71
|
+
export { namespaceFor, redisTier, usesDefaultRedisClient } from './redis';
|
|
72
72
|
export type {
|
|
73
73
|
InvalidationBus,
|
|
74
74
|
InvalidationSubscription,
|
|
@@ -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,7 +18,7 @@ import type {
|
|
|
17
18
|
TierInvalidation,
|
|
18
19
|
TtlJitter,
|
|
19
20
|
} from './tiers';
|
|
20
|
-
import {
|
|
21
|
+
import { assertJitterFraction, assertTtl, nowMs } from './tiers';
|
|
21
22
|
import { decodeCacheValue, encodeCacheValue } from './value-codec';
|
|
22
23
|
|
|
23
24
|
export interface LruOptions {
|
|
@@ -130,6 +131,9 @@ export class LruCache {
|
|
|
130
131
|
options.defaultTtlMs ?? 60_000,
|
|
131
132
|
);
|
|
132
133
|
this.clock = options.clock ?? systemClock;
|
|
134
|
+
if (options.jitterFraction !== undefined) {
|
|
135
|
+
assertJitterFraction('lru', options.jitterFraction);
|
|
136
|
+
}
|
|
133
137
|
this.jitter = {
|
|
134
138
|
...(options.jitterFraction === undefined ? {} : { jitterFraction: options.jitterFraction }),
|
|
135
139
|
...(options.rng === undefined ? {} : { rng: options.rng }),
|
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,7 +33,7 @@ import type {
|
|
|
30
33
|
TierInvalidation,
|
|
31
34
|
TtlJitter,
|
|
32
35
|
} from './tiers';
|
|
33
|
-
import {
|
|
36
|
+
import { assertJitterFraction, assertTtl, nowMs } from './tiers';
|
|
34
37
|
import { decodeCacheValue, encodeCacheValue } from './value-codec';
|
|
35
38
|
|
|
36
39
|
/** The slice of Bun's Redis client this tier uses. Narrow on purpose: easy to fake in tests. */
|
|
@@ -131,19 +134,30 @@ function leaseFrom(reply: unknown): Lease {
|
|
|
131
134
|
* the operator sees which key the store refused rather than a count.
|
|
132
135
|
*
|
|
133
136
|
* The `fix:` is the call, not a command: there is no `x cache` in this build, and the retry is one
|
|
134
|
-
* line of the app's own code. It is safe to repeat because every key the store refused
|
|
135
|
-
*
|
|
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.
|
|
136
140
|
*/
|
|
137
141
|
function raiseSweepFailure(failures: readonly unknown[], attempted: number): never {
|
|
138
142
|
const first = failures[0];
|
|
139
143
|
if (first instanceof Error) throw first;
|
|
140
144
|
throw new CacheDriverUnavailableError({
|
|
141
145
|
driver: 'redis',
|
|
142
|
-
cause:
|
|
143
|
-
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",
|
|
144
148
|
});
|
|
145
149
|
}
|
|
146
150
|
|
|
151
|
+
/** The tiers `redisTier` built with no `client`: the ones core's `redisClient()` will dial for. */
|
|
152
|
+
const onDefaultClient = new WeakSet<CacheTier>();
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Whether `tier` is a `redisTier` left to core's default client, which reads `REDIS_URL`, then
|
|
156
|
+
* `VALKEY_URL`, then the local server. A tier's options are closed over, so the boot asks here: a
|
|
157
|
+
* rung it did not build still owes an operator a word when no URL is set (`runtime-cache.ts`).
|
|
158
|
+
*/
|
|
159
|
+
export const usesDefaultRedisClient = (tier: CacheTier): boolean => onDefaultClient.has(tier);
|
|
160
|
+
|
|
147
161
|
export function redisTier(options: RedisTierOptions = {}): CacheTier {
|
|
148
162
|
const ns = namespaceFor(options.prefix ?? 'x', options.buildId);
|
|
149
163
|
const defaultTtlMs = assertFiniteDurationMs(
|
|
@@ -157,6 +171,9 @@ export function redisTier(options: RedisTierOptions = {}): CacheTier {
|
|
|
157
171
|
'maxValueBytes',
|
|
158
172
|
options.maxValueBytes ?? DEFAULT_REDIS_MAX_VALUE_BYTES,
|
|
159
173
|
);
|
|
174
|
+
if (options.jitterFraction !== undefined) {
|
|
175
|
+
assertJitterFraction('redis', options.jitterFraction);
|
|
176
|
+
}
|
|
160
177
|
const jitter: TtlJitter = {
|
|
161
178
|
...(options.jitterFraction === undefined ? {} : { jitterFraction: options.jitterFraction }),
|
|
162
179
|
...(options.rng === undefined ? {} : { rng: options.rng }),
|
|
@@ -183,9 +200,10 @@ export function redisTier(options: RedisTierOptions = {}): CacheTier {
|
|
|
183
200
|
// A bust skips the park: skipped for a stall, it leaves stale rows serving until TTL.
|
|
184
201
|
const bustConn = (): RedisLike => views().bust;
|
|
185
202
|
|
|
186
|
-
const { valueKey, writeBucketsFor, bustBucketsFor, sweepBucketsFor } =
|
|
203
|
+
const { valueKey, writeBucketsFor, bustBucketsFor, sweepBucketsFor, collectionBucketOf } =
|
|
204
|
+
bucketLayout(ns);
|
|
187
205
|
|
|
188
|
-
|
|
206
|
+
const tier: CacheTier = {
|
|
189
207
|
name: 'redis',
|
|
190
208
|
|
|
191
209
|
/**
|
|
@@ -268,10 +286,20 @@ export function redisTier(options: RedisTierOptions = {}): CacheTier {
|
|
|
268
286
|
/** The fleet-wide half of the fill fence: generations other replicas' busts move. */
|
|
269
287
|
fence: (scope: FenceScope) => sampleGenerations(conn(), ns, clock, scope),
|
|
270
288
|
|
|
289
|
+
/** The namespace a bust sweeps — per build by default, so two builds are two scopes. */
|
|
290
|
+
scope: ns,
|
|
291
|
+
|
|
271
292
|
/**
|
|
272
|
-
* Read every bucket the tags match, a page per round trip and the buckets concurrently;
|
|
273
|
-
*
|
|
274
|
-
* 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`).
|
|
275
303
|
*/
|
|
276
304
|
async invalidateTags(tags: readonly CacheTag[]): Promise<TierInvalidation> {
|
|
277
305
|
const claimed = new Set<string>();
|
|
@@ -290,29 +318,61 @@ export function redisTier(options: RedisTierOptions = {}): CacheTier {
|
|
|
290
318
|
await bumpGenerations(bustConn(), ns, tags);
|
|
291
319
|
const buckets = [...claimed];
|
|
292
320
|
const pages = await Promise.all(buckets.map((bucket) => readBucket(bustConn(), bucket)));
|
|
293
|
-
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()]));
|
|
294
322
|
// A member may sit in two buckets; deleting it twice is harmless but reporting it twice
|
|
295
|
-
// makes the `/_x` panel overstate what cleared.
|
|
296
|
-
const
|
|
297
|
-
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()];
|
|
298
332
|
|
|
299
|
-
// Only what actually died leaves its buckets. A member the store refused to delete keeps its
|
|
300
|
-
// membership, so the retry `report.errors` asks for still finds it.
|
|
301
333
|
const gone = new Map<string, Set<string>>();
|
|
302
334
|
for (const { read, sweep } of perTag) {
|
|
303
|
-
const
|
|
304
|
-
if (
|
|
335
|
+
const found = read.flatMap((bucket) => [...(held.get(bucket)?.keys() ?? [])]);
|
|
336
|
+
if (found.length === 0) continue;
|
|
305
337
|
for (const bucket of sweep) {
|
|
306
338
|
const into = gone.get(bucket) ?? new Set<string>();
|
|
307
|
-
for (const member of
|
|
339
|
+
for (const member of found) into.add(member);
|
|
308
340
|
gone.set(bucket, into);
|
|
309
341
|
}
|
|
310
342
|
}
|
|
311
|
-
await sweepBuckets(bustConn(), gone);
|
|
343
|
+
const swept = await sweepBuckets(bustConn(), gone);
|
|
344
|
+
const { deleted, failures } = await unlinkAll(bustConn(), members);
|
|
312
345
|
|
|
313
|
-
|
|
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);
|
|
314
372
|
const stripped = [...deleted].map((key) => key.slice(valueKey('').length));
|
|
315
373
|
return { tier: 'redis', keys: stripped };
|
|
316
374
|
},
|
|
317
375
|
};
|
|
376
|
+
if (options.client === undefined) onDefaultClient.add(tier);
|
|
377
|
+
return tier;
|
|
318
378
|
}
|
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';
|
|
@@ -102,67 +103,12 @@ export interface CacheSetOptions {
|
|
|
102
103
|
export type TtlScope = TierName | 'semantic';
|
|
103
104
|
|
|
104
105
|
/**
|
|
105
|
-
* A tier's
|
|
106
|
-
* `
|
|
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.
|
|
106
|
+
* A tier's TTL spread, screened when the tier is BUILT as well as at each write: found only at the
|
|
107
|
+
* first `set`, a bad fraction refused every write of a tier that had booted healthy.
|
|
110
108
|
*/
|
|
111
|
-
export function
|
|
112
|
-
if (Number.
|
|
113
|
-
throw new
|
|
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
|
-
});
|
|
109
|
+
export function assertJitterFraction(tier: TtlScope, fraction: number): number {
|
|
110
|
+
if (Number.isFinite(fraction) && fraction >= 0 && fraction < 1) return fraction;
|
|
111
|
+
throw new CacheJitterInvalidError({ tier, jitterFraction: fraction });
|
|
166
112
|
}
|
|
167
113
|
|
|
168
114
|
export function assertTtl(
|
|
@@ -174,10 +120,10 @@ export function assertTtl(
|
|
|
174
120
|
if (!Number.isFinite(ttlMs) || ttlMs <= 0) {
|
|
175
121
|
throw new CacheTtlInvalidError({ key, ttlMs, tier });
|
|
176
122
|
}
|
|
177
|
-
const fraction =
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
123
|
+
const fraction =
|
|
124
|
+
jitter.jitterFraction === undefined
|
|
125
|
+
? DEFAULT_TTL_JITTER_FRACTION
|
|
126
|
+
: assertJitterFraction(tier, jitter.jitterFraction);
|
|
181
127
|
if (fraction === 0) return ttlMs;
|
|
182
128
|
// Clamped rather than trusted: an `rng` outside [0, 1) would EXTEND the lease past what the
|
|
183
129
|
// caller asked for, which is a stale read no reader can explain.
|
|
@@ -204,6 +150,13 @@ export interface CacheTier {
|
|
|
204
150
|
* may never be told about — still stops the fill (`tier-fence.ts`). Omitted by in-process tiers.
|
|
205
151
|
*/
|
|
206
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;
|
|
207
160
|
/**
|
|
208
161
|
* Drop every entry — implemented ONLY by a tier whose store is this process's own heap (`lru`).
|
|
209
162
|
* `flushProcessTiers()` calls it when the process cannot know which busts it missed. A shared
|