diff --git a/mcp/src/readme.ts b/mcp/src/readme.ts index d1e3a77..e2ba0b5 100644 --- a/mcp/src/readme.ts +++ b/mcp/src/readme.ts @@ -134,7 +134,10 @@ as real queueing, latency and failures, measured from simulated requests. finishes when they all answer. So a service wired to a cache and a database calls both. To model "cache first, database on a miss", wire service to cache and cache to database: a \`cache\` answers hits itself - and only passes misses on (\`hitRate\`). + and only passes misses on (\`hitRate\`). Two caches in a row with only + \`hitRate\` set multiply their misses; set \`cacheKeys\` on both (how many + of the 64 keys each holds) for a hit rate measured from the clients' + keys, where the second cache sees only what the first could not keep. - A node with no outgoing edge answers the request itself. - A \`queue\` acknowledges at once and buffers; \`worker\` nodes wired from it drain it. Always draw queue to worker. A worker wired to a queue drains diff --git a/src/clipboard.ts b/src/clipboard.ts index 79f1a3a..f6921d0 100644 --- a/src/clipboard.ts +++ b/src/clipboard.ts @@ -96,7 +96,14 @@ export function isTopology(value: unknown): value is Topology { ]) { if (!Number.isFinite(cfg[key])) return false; } - for (const key of ['chargeable', 'idempotencyKeys', 'flushEveryMs', 'freshReads']) { + for (const key of [ + 'chargeable', + 'idempotencyKeys', + 'flushEveryMs', + 'freshReads', + 'cacheKeys', + 'cacheTtlMs', + ]) { if (cfg[key] !== undefined && !Number.isFinite(cfg[key])) return false; } if (ids.has(n.id)) return false; diff --git a/src/components/Inspector.tsx b/src/components/Inspector.tsx index 430b680..bebf351 100644 --- a/src/components/Inspector.tsx +++ b/src/components/Inspector.tsx @@ -22,7 +22,12 @@ import { canPause, takesCorrectness, } from '../sim/behaviour'; -import { hottestKeyShare, MAX_KEY_SKEW } from '../sim/keys'; +import { hottestKeyShare, KEYSPACE, MAX_KEY_SKEW } from '../sim/keys'; +import { + DEFAULT_CACHE_KEYS, + effectiveCacheKeys, + MAX_CACHE_TTL_MS, +} from '../sim/cacheKeys'; import { DEFAULT_TRAFFIC_PERIOD_S } from '../sim/types'; import { DEFAULT_BURST_SIZE, @@ -145,7 +150,9 @@ type Field = | 'trafficPeriodS' | 'burstSize' | 'herdSize' - | 'herdSpreadMs'; + | 'herdSpreadMs' + | 'cacheKeys' + | 'cacheTtlMs'; const FIELDS_BY_KIND: Record = { // The client generates load and decides how long to wait for an answer. @@ -178,7 +185,18 @@ const FIELDS_BY_KIND: Record = { 'retries', ], // Only the cache has a hit rate. That single knob is the interesting one. - cache: ['hitRate', 'instances', 'capacity', 'serviceMs', 'serviceCv', 'queueLimit'], + // With keys tracked, the hit rate is measured, so the slider gives way to + // how many keys it holds and how long one stays; see shownFields. + cache: [ + 'hitRate', + 'cacheKeys', + 'cacheTtlMs', + 'instances', + 'capacity', + 'serviceMs', + 'serviceCv', + 'queueLimit', + ], // A database is slots, service time, and the write lock: the read/write // mix and the per-writer lock wait are what make it more than a service. db: [ @@ -231,7 +249,15 @@ const FIELDS_BY_KIND: Record = { // A CDN is a cache whose whole story is the hit rate: how much load never // reaches you. Capacity and service time are shown because a saturated // edge is still a real failure mode. - cdn: ['hitRate', 'instances', 'capacity', 'serviceMs', 'queueLimit'], + cdn: [ + 'hitRate', + 'cacheKeys', + 'cacheTtlMs', + 'instances', + 'capacity', + 'serviceMs', + 'queueLimit', + ], // A limiter has exactly two knobs, and the pair is the lesson: sustained // rate, and how much burst you forgive on top of it. ratelimiter: ['rateLimitRps', 'burst'], @@ -436,7 +462,7 @@ const KIND_BLURB: Record = { service: 'The workhorse. How many it handles at once, divided by how long each takes, is the ceiling everything else queues behind.', cache: - 'Answers hits without touching downstream. Each cache rolls its own hit chance, independently of the others, so stacking them multiplies misses rather than treating later caches as filters on earlier misses.', + 'Answers hits without touching downstream. With a set hit rate, each cache rolls its own chance, so stacking them multiplies misses. Turn on remembering keys and a later cache only sees what the earlier one could not keep.', db: 'Works on a few requests at once. When they are all busy, the rest wait in line here.', queue: 'A buffer. Depth is the whole story: it absorbs bursts up to the limit, then turns work away.', @@ -450,7 +476,7 @@ const KIND_BLURB: Record = { 'Watches one node and adds capacity when it runs hot. New capacity takes warmup time to arrive, so load always leads it.', region: 'Sends traffic to one region at a time. If that region dies, failover costs you a full outage window before the next one takes over.', - cdn: 'An edge cache in front of everything. At a 0.9 hit rate one CDN leaves a tenth of the traffic for the origin, and that chance is rolled independently of every other cache on the path. It is still the cheapest capacity you will ever add.', + cdn: 'An edge cache in front of everything. At a 0.9 hit rate one CDN leaves a tenth of the traffic for the origin, and with a set hit rate that chance is rolled independently of every other cache on the path. It is still the cheapest capacity you will ever add.', ratelimiter: 'A token bucket. Refuses excess traffic instantly instead of queueing it, which is what stops a busy system turning into a dead one.', breaker: @@ -625,6 +651,13 @@ const SHAPE_FIELDS: Partial>> = { /** This kind's fields, less the ones the node's traffic shape does not read. */ function shownFields(kind: NodeKind, config: NodeConfig): readonly Field[] { const fields = FIELDS_BY_KIND[kind]; + if (kind === 'cache' || kind === 'cdn') { + // A cache that tracks keys measures its hit rate instead of taking one. + const keyed = effectiveCacheKeys(config) > 0; + return fields.filter((f) => + f === 'hitRate' ? !keyed : f === 'cacheKeys' || f === 'cacheTtlMs' ? keyed : true, + ); + } if (kind !== 'client') return fields; const shape = config.traffic ?? 'steady'; return fields.filter((f) => SHAPE_FIELDS[f]?.has(shape) ?? true); @@ -654,6 +687,8 @@ const ABSENT_FIELD: Partial> = { burstSize: DEFAULT_BURST_SIZE, herdSize: DEFAULT_HERD_SIZE, herdSpreadMs: 0, + cacheKeys: DEFAULT_CACHE_KEYS, + cacheTtlMs: 0, }; /** A choice field's value, or its first option when absent. */ @@ -729,7 +764,7 @@ const FIELD_SPECS: Record = { term: 'hit-rate', label: 'Hit rate', unit: 'percent', - hint: 'Each cache or CDN rolls this chance on its own. Two at 80% leave about 4% of traffic for whatever is behind them, because the chances multiply.', + hint: 'Each cache or CDN rolls this chance on its own. Two at 80% leave about 4% of traffic for whatever is behind them, because the chances multiply. Turn on Remember which keys it holds for a hit rate that comes from the traffic instead.', min: 0, max: 1, step: 0.01, @@ -828,6 +863,26 @@ const FIELD_SPECS: Record = { ? 'Every one of the 64 keys is equally likely, about 1.6% of requests each.' : `The hottest of the 64 keys gets ${formatPct(hottestKeyShare(v))} of requests, and a sharded store sends all of them to one partition.`, }, + cacheKeys: { + control: 'number', + label: 'Keys it holds', + unit: `of the ${KEYSPACE} keys`, + hint: 'When it is full, the key used least recently makes room. Hot keys stay, so the hotter the traffic, the more it hits.', + min: 1, + max: KEYSPACE, + step: 1, + }, + cacheTtlMs: { + control: 'slider', + term: 'ttl', + label: 'Forget a key after', + unit: 'milliseconds, 0 keeps it until it is pushed out', + hint: 'Once a key is this old, the next read of it goes to the store again. Every key expiring at once is a stampede.', + min: 0, + max: MAX_CACHE_TTL_MS, + step: 500, + display: (v) => (v <= 0 ? 'never' : formatMs(v)), + }, traffic: { control: 'choice', term: 'traffic-shape', @@ -1406,6 +1461,8 @@ const FIELD_GROUPS: { title: string; fields: ReadonlySet }[] = [ 'herdSpreadMs', 'keySkew', 'hitRate', + 'cacheKeys', + 'cacheTtlMs', 'replicaCount', 'replicationLagMs', 'readFraction', @@ -2271,11 +2328,19 @@ function KindStatRows({ switch (kind) { case 'cache': return ( - + <> + + {stats.cachedKeys !== undefined && ( + + )} + ); case 'cdn': @@ -2290,6 +2355,12 @@ function KindStatRows({ label="Fetched from origin" value={formatRate(stats.originFetchRate)} /> + {stats.cachedKeys !== undefined && ( + + )} ); @@ -3586,9 +3657,24 @@ function SingleInspector({ )} - {grouped.map((group) => ( + {grouped.map((group, gi) => (
+ {gi === 0 && (node.kind === 'cache' || node.kind === 'cdn') && ( + 0} + locked={lockedFields?.includes('cacheKeys') ? lockNote : undefined} + onChange={(on) => + onChange(node.id, { + cacheKeys: on ? DEFAULT_CACHE_KEYS : undefined, + cacheTtlMs: undefined, + }) + } + /> + )} {group.fields.map((field) => { const spec = specFor(node.kind, field); const locked = lockedFields?.includes(field) ?? false; diff --git a/src/content/glossary.ts b/src/content/glossary.ts index 3a17cb8..6e8be71 100644 --- a/src/content/glossary.ts +++ b/src/content/glossary.ts @@ -459,7 +459,7 @@ export const GLOSSARY: GlossaryEntry[] = [ id: 'cache', term: 'Cache', short: 'Remembers recent answers so the work is not repeated', - why: 'A hit is answered immediately; a miss costs a full trip to whatever is behind it. For one cache, at 90% the database sees a tenth of the traffic. Each cache rolls that chance independently, so stacking two 80% caches leaves about 4% of traffic for whatever is behind them.', + why: 'A hit is answered immediately; a miss costs a full trip to whatever is behind it. For one cache, at 90% the database sees a tenth of the traffic. By default each cache rolls that chance independently, so stacking two 80% caches leaves about 4% of traffic for whatever is behind them. Turn on remembering keys and it holds real keys instead: the second cache then only sees what the first could not keep, and hits far less.', category: 'component', intro: { what: 'Fast memory that keeps recent answers so they do not have to be worked out again.', @@ -473,7 +473,7 @@ export const GLOSSARY: GlossaryEntry[] = [ id: 'hit-rate', term: 'Hit rate', short: 'The share of requests a cache can answer by itself', - why: 'Small changes here have outsized effects. Going from 90% to 80% hit rate on one cache does not add 10% more database load: it doubles it. Each hop rolls independently, so chaining caches multiplies miss chances rather than sharing what the first one missed.', + why: 'Small changes here have outsized effects. Going from 90% to 80% hit rate on one cache does not add 10% more database load: it doubles it. With the hit rate set, each hop rolls independently, so chaining caches multiplies miss chances. A cache that remembers its keys measures its hit rate instead: it hits more when a few keys are hot and less when traffic is spread evenly.', category: 'component', aliases: ['cache hit'], see: ['cache', 'cdn'], @@ -623,7 +623,16 @@ export const GLOSSARY: GlossaryEntry[] = [ why: 'Real traffic looks like this: a few popular users, products or videos, and many rare ones. The average load can look fine while whatever owns the top key is full. This simulator has only 64 keys, so its tail is much shorter than a real one with millions.', category: 'component', aliases: ['zipf', 'skew', 'key skew', 'key spread', 'power law', 'popular keys'], - see: ['hot-key', 'shard'], + see: ['hot-key', 'shard', 'ttl'], + }, + { + id: 'ttl', + term: 'TTL', + short: 'How long a cached answer is kept before it is fetched again', + why: 'A short TTL keeps answers fresh but sends more reads to the store. When a hot key expires, every reader that misses it goes to the store at the same moment, and a cache that restarts empty does the same for every key at once. That rush is called a cache stampede.', + category: 'component', + aliases: ['time to live', 'expiry', 'cache stampede', 'stampede', 'cold cache'], + see: ['cache', 'hit-rate'], }, { id: 'read-replica', diff --git a/src/content/glossary.wiring.test.ts b/src/content/glossary.wiring.test.ts index 6558d3b..8e0a296 100644 --- a/src/content/glossary.wiring.test.ts +++ b/src/content/glossary.wiring.test.ts @@ -99,17 +99,20 @@ describe('glossary wiring', () => { }); it('states independent hit-rate rolls on the cache and CDN inspector copy', () => { - // Issue #31: the engine is a per-hop coin flip. The inspector blurbs - // and the hit-rate hint have to say so, or stacking caches reads as a - // hierarchy the numbers do not model. + // Issue #31: with a set hit rate the engine is a per-hop coin flip. The + // inspector blurbs and the hit-rate hint have to say so, or stacking + // caches reads as a hierarchy that model does not have. const inspector = Object.entries(SOURCES).find(([path]) => path.endsWith('/Inspector.tsx'), )?.[1]; expect(inspector, 'Inspector.tsx not in the glob').toBeTruthy(); expect(inspector).toMatch( - /Each cache rolls its own hit chance, independently of the others/, + /With a set hit rate, each cache rolls its own chance, so stacking them multiplies misses/, + ); + // And it points at the model that does treat a later cache as a filter. + expect(inspector).toMatch( + /a later cache only sees what the earlier one could not keep/, ); - expect(inspector).toMatch(/treating later caches as filters on earlier misses/); expect(inspector).toMatch(/rolled independently of every other cache on the path/); expect(inspector).toMatch(/Each cache or CDN rolls this chance on its own/); expect(inspector).toMatch( diff --git a/src/share/wire.test.ts b/src/share/wire.test.ts index 3bf8ee5..657976a 100644 --- a/src/share/wire.test.ts +++ b/src/share/wire.test.ts @@ -160,6 +160,8 @@ describe('protocol tables', () => { burstSize: true, herdSize: true, herdSpreadMs: true, + cacheKeys: true, + cacheTtlMs: true, }; for (const field of Object.keys(every)) expect(WIRE_FIELDS).toContain(field); }); diff --git a/src/share/wire.ts b/src/share/wire.ts index bd67e6f..6ade58e 100644 --- a/src/share/wire.ts +++ b/src/share/wire.ts @@ -235,6 +235,8 @@ const FIELDS = [ 'burstSize', 'herdSize', 'herdSpreadMs', + 'cacheKeys', + 'cacheTtlMs', ] as const satisfies readonly ConfigField[]; /** Every field the wire can carry; exported so a test can prove it is complete. */ @@ -295,7 +297,13 @@ const SCHEMA: Record = { ], lb: [...COMMON, ...CORRECTNESS], service: [...COMMON, ...CORRECTNESS], - cache: ['hitRate', ...COMMON.filter((f) => f !== 'hitRate'), ...CORRECTNESS], + cache: [ + 'hitRate', + ...COMMON.filter((f) => f !== 'hitRate'), + ...CORRECTNESS, + 'cacheKeys', + 'cacheTtlMs', + ], db: ['readFraction', 'lockMs', ...COMMON, ...CORRECTNESS, 'flushEveryMs'], queue: COMMON, worker: [...COMMON, ...CORRECTNESS], @@ -309,7 +317,13 @@ const SCHEMA: Record = { ...COMMON, ], region: ['regions', 'activeRegion', 'failoverMs', ...COMMON, ...CORRECTNESS], - cdn: ['hitRate', ...COMMON.filter((f) => f !== 'hitRate'), ...CORRECTNESS], + cdn: [ + 'hitRate', + ...COMMON.filter((f) => f !== 'hitRate'), + ...CORRECTNESS, + 'cacheKeys', + 'cacheTtlMs', + ], ratelimiter: ['rateLimitRps', 'burst', ...COMMON, ...CORRECTNESS], breaker: [ 'errorThreshold', diff --git a/src/sim/behaviour-cache.ts b/src/sim/behaviour-cache.ts new file mode 100644 index 0000000..47bcea6 --- /dev/null +++ b/src/sim/behaviour-cache.ts @@ -0,0 +1,72 @@ +import { effectiveCacheKeys, effectiveCacheTtlMs, KeyedCache } from './cacheKeys'; +import type { BehaviourCtx, NodeStateLike, ReqLike } from './engine-types'; +import type { NodeStats } from './types'; + +/* ------------------------------------------------------------------ * + * The hit decision the cache and the CDN share. + * + * Both used to roll `hitRate` and nothing else. They still do unless + * `cacheKeys` is set, and the roll is drawn either way, in the same + * position, so switching a cache between the two models mid-run moves no + * other random number in the run. See cacheKeys.ts for the model itself. + * ------------------------------------------------------------------ */ + +function held(state: NodeStateLike): KeyedCache { + return state.ext as KeyedCache; +} + +/** Whether this request is answered from the cache. Draws one roll, always. */ +export function cacheHit( + ctx: BehaviourCtx, + state: NodeStateLike, + req: ReqLike, +): boolean { + const roll = ctx.roll(); + const capacity = effectiveCacheKeys(state.config); + if (capacity === 0) { + const rate = state.config.hitRate; + return roll < (rate < 0 ? 0 : rate > 1 ? 1 : rate); + } + const cache = held(state); + // A write is never answered from a copy. It goes to the store and the + // copy of its key is gone, so the next read fetches what it wrote. + if (req.isWrite) { + cache.invalidate(req.key); + return false; + } + return cache.lookup(req.key, ctx.now, effectiveCacheTtlMs(state.config), capacity); +} + +/** + * The hooks a key-tracking cache needs on top of its hit decision: where it + * keeps its keys, how it fills them from the answers behind it, what a crash + * does to them, and the readout. Inert on a cache that rolls `hitRate`. + */ +export const KEYED_CACHE_HOOKS = { + observesOutcome: true, + initState: (): KeyedCache => new KeyedCache(), + onDownstreamResult: ( + ctx: BehaviourCtx, + state: NodeStateLike, + child: ReqLike, + ok: boolean, + ): void => { + const capacity = effectiveCacheKeys(state.config); + if (capacity === 0) return; + // A cache that is down holds nothing, and an answer to a call it made + // before it went down is not let back in. + if (ctx.isCrashed(state.id)) return; + // A store downstream may be the one that decides a request is a write, + // so the answer, not the lookup, is where that is known for sure. + if (child.isWrite) held(state).invalidate(child.key); + else if (ok) held(state).fill(child.key, ctx.now, capacity); + }, + onMemoryLost: (state: NodeStateLike): void => { + held(state).clear(); + }, + decorateStats: (ctx: BehaviourCtx, state: NodeStateLike, stats: NodeStats): void => { + if (effectiveCacheKeys(state.config) > 0) { + stats.cachedKeys = held(state).goodAt(ctx.now, effectiveCacheTtlMs(state.config)); + } + }, +}; diff --git a/src/sim/behaviour-edge.ts b/src/sim/behaviour-edge.ts index e1268e5..4936a32 100644 --- a/src/sim/behaviour-edge.ts +++ b/src/sim/behaviour-edge.ts @@ -23,6 +23,7 @@ import type { NodeStats } from './types'; import type { BehaviourCtx, NodeStateLike, ReqLike } from './engine-types'; import type { ComponentBehaviour } from './behaviour'; import { clamp01 } from './behaviour'; +import { cacheHit, KEYED_CACHE_HOOKS } from './behaviour-cache'; /* ------------------------------------------------------------------ * * cdn @@ -54,10 +55,12 @@ const cdn: ComponentBehaviour = { pump: 'own', creditsJoinCompletion: true, - onServiceComplete: (ctx, state, _req) => { - // One RNG draw, unconditionally, in a fixed position. Drawing only on - // some paths would make the stream depend on config and break replay. - if (ctx.roll() < clamp01(state.config.hitRate)) { + ...KEYED_CACHE_HOOKS, + + onServiceComplete: (ctx, state, req) => { + // One RNG draw, unconditionally, in a fixed position, inside cacheHit. + // Drawing only on some paths would make the stream depend on config. + if (cacheHit(ctx, state, req)) { ctx.countHit(state); return 'complete'; } @@ -73,6 +76,7 @@ const cdn: ComponentBehaviour = { decorateStats: (ctx, state, stats: NodeStats) => { stats.originFetchRate = ctx.counterRate(state, 'originFetch'); + KEYED_CACHE_HOOKS.decorateStats(ctx, state, stats); }, }; diff --git a/src/sim/behaviour.ts b/src/sim/behaviour.ts index be68ee1..b19a681 100644 --- a/src/sim/behaviour.ts +++ b/src/sim/behaviour.ts @@ -28,6 +28,7 @@ import type { import type { BehaviourCtx, ReqLike, NodeStateLike } from './engine-types'; import { DATA_BEHAVIOURS } from './behaviour-data'; import { EDGE_BEHAVIOURS } from './behaviour-edge'; +import { cacheHit, KEYED_CACHE_HOOKS } from './behaviour-cache'; import { CONTROL_BEHAVIOURS } from './behaviour-control'; import { STORE_BEHAVIOURS } from './behaviour-store'; import { MESSAGING_BEHAVIOURS } from './behaviour-messaging'; @@ -275,6 +276,12 @@ export interface ComponentBehaviour { ok: boolean, reason: FailureReason, ): void; + /** + * The node went down and lost what it held in memory: a crash or a restart + * of the whole node. Called before its in-flight work is failed. A cache + * that tracks keys empties here, so it comes back cold. + */ + onMemoryLost?(state: NodeStateLike): void; /** A behaviour-owned timer for a request it held during admission. */ onWake?(ctx: BehaviourCtx, state: NodeStateLike, req: ReqLike): void; /** @@ -424,8 +431,9 @@ const cache: ComponentBehaviour = { buffersForConsumers: false, pump: 'own', creditsJoinCompletion: true, - onServiceComplete: (ctx, state, _req) => { - if (ctx.roll() < clamp01(state.config.hitRate)) { + ...KEYED_CACHE_HOOKS, + onServiceComplete: (ctx, state, req) => { + if (cacheHit(ctx, state, req)) { ctx.countHit(state); return 'complete'; } diff --git a/src/sim/cacheKeys.test.ts b/src/sim/cacheKeys.test.ts new file mode 100644 index 0000000..36ac794 --- /dev/null +++ b/src/sim/cacheKeys.test.ts @@ -0,0 +1,206 @@ +import { createHash } from 'node:crypto'; +import { describe, expect, it } from 'vitest'; +import { packTopology, unpackTopology } from '../share/wire'; +import { KeyedCache } from './cacheKeys'; +import { Engine } from './engine'; +import { makeNode } from './presets'; +import type { SimNode, Topology } from './types'; + +/** + * A cache that tracks which keys it holds (#31). What is worth pinning: that + * a cache without `cacheKeys` runs exactly as before, that the hit rate is + * measured from the keys and not the setting, and the two things the old + * model got wrong, chained caches and a cache that comes back empty. + */ + +function node(kind: SimNode['kind'], id: string): SimNode { + return { ...makeNode(kind, 0, 0, id), id }; +} + +interface Opts { + keys?: number; + skew?: number; + ttlMs?: number; + twoCaches?: boolean; +} + +/** client at 200/s -> cache (-> cache) -> db, both caches set to 80%. */ +function design({ keys, skew = 1, ttlMs, twoCaches = false }: Opts): Topology { + const client = node('client', 'client'); + client.config.rps = 200; + client.config.keySkew = skew; + const caches = (twoCaches ? ['c1', 'c2'] : ['c1']).map((id) => { + const c = node('cache', id); + c.config.hitRate = 0.8; + if (keys !== undefined) c.config.cacheKeys = keys; + if (ttlMs !== undefined) c.config.cacheTtlMs = ttlMs; + return c; + }); + const db = node('db', 'db'); + const path = ['client', ...caches.map((c) => c.id), 'db']; + return { + nodes: [client, ...caches, db], + edges: path + .slice(1) + .map((to, i) => ({ id: `e${i}`, from: path[i]!, to, weight: 1 })), + }; +} + +function runFor(t: Topology, seconds: number, each?: (e: Engine, s: number) => void) { + const engine = new Engine(t, 42); + for (let i = 0; i < seconds * 60; i++) { + if (each && i % 60 === 0) each(engine, i / 60); + engine.advance(1000 / 60); + } + return engine; +} + +function snapshotHash(t: Topology): string { + const engine = new Engine(t, 7); + const h = createHash('sha256'); + for (let i = 1; i <= 600; i++) { + engine.advance(1000 / 60); + if (i % 6 === 0) h.update(JSON.stringify(engine.snapshot())); + } + return h.digest('hex'); +} + +describe('the key store', () => { + it('evicts the key used least recently when full', () => { + const c = new KeyedCache(); + c.fill(1, 0, 2); + c.fill(2, 1, 2); + expect(c.lookup(1, 2, 0, 2)).toBe(true); // 1 is now the fresher + c.fill(3, 3, 2); + expect(c.lookup(2, 4, 0, 2)).toBe(false); + expect(c.lookup(1, 4, 0, 2)).toBe(true); + expect(c.lookup(3, 4, 0, 2)).toBe(true); + expect(c.size).toBe(2); + }); + + it('lets a key expire after its TTL, and refills it fresh', () => { + const c = new KeyedCache(); + c.fill(5, 0, 4); + expect(c.lookup(5, 999, 1000, 4)).toBe(true); + expect(c.goodAt(1000, 1000)).toBe(0); + expect(c.lookup(5, 1000, 1000, 4)).toBe(false); + c.fill(5, 1000, 4); + expect(c.lookup(5, 1500, 1000, 4)).toBe(true); + }); + + it('forgets a written key, everything on clear, and shrinks to a smaller size', () => { + const c = new KeyedCache(); + for (let k = 0; k < 8; k++) c.fill(k, k, 8); + c.invalidate(3); + expect(c.lookup(3, 10, 0, 8)).toBe(false); + expect(c.size).toBe(7); + // Shrunk to 2: the two most recently used stay. + expect(c.lookup(7, 11, 0, 2)).toBe(true); + expect(c.size).toBe(2); + expect(c.lookup(6, 12, 0, 2)).toBe(true); + c.clear(); + expect(c.size).toBe(0); + expect(c.lookup(6, 13, 0, 2)).toBe(false); + }); +}); + +describe('a cache that tracks keys', () => { + it('runs byte for byte as before when cacheKeys is unset or 0', () => { + expect(snapshotHash(design({ keys: 0 }))).toBe(snapshotHash(design({}))); + }); + + it('replays the same seed identically', () => { + expect(snapshotHash(design({ keys: 16 }))).toBe(snapshotHash(design({ keys: 16 }))); + }); + + it('survives a share link', () => { + const t = design({ keys: 24, ttlMs: 5000 }); + const back = unpackTopology(packTopology(t)); + const c1 = back?.nodes[1]; + expect(c1?.config.cacheKeys).toBe(24); + expect(c1?.config.cacheTtlMs).toBe(5000); + }); + + it('measures its hit rate from the keys, not from hitRate', () => { + // Measured at seed 42, 30s: 16 of 64 keys, even 28%; skew 1.0 62%; + // 8 keys 43%, 32 keys 83%. hitRate is 0.8 on every one of them. + const at = (o: Opts) => runFor(design(o), 30).snapshot().nodes.c1!; + const even = at({ keys: 16, skew: 0 }); + expect(even.hitRate).toBeGreaterThan(0.2); + expect(even.hitRate).toBeLessThan(0.35); + const hot = at({ keys: 16, skew: 1 }); + expect(hot.hitRate).toBeGreaterThan(0.55); + expect(hot.hitRate).toBeLessThan(0.7); + expect(hot.cachedKeys).toBe(16); + expect(at({ keys: 8 }).hitRate).toBeLessThan(hot.hitRate); + expect(at({ keys: 32 }).hitRate).toBeGreaterThan(hot.hitRate); + }); + + it('hits less with a TTL, because expired keys go back to the store', () => { + const keep = runFor(design({ keys: 16 }), 30).snapshot().nodes.c1!; + const ttl = runFor(design({ keys: 16, ttlMs: 2000 }), 30).snapshot().nodes.c1!; + expect(ttl.hitRate).toBeLessThan(keep.hitRate - 0.05); + }); + + it('leaves a second cache only the cold keys, instead of multiplying (#31)', () => { + // Measured at seed 42, 30s. Rolling: c1 77%, c2 84%, db 7.8/s, the + // misses multiplied. Tracking 16 keys each: c1 63%, c2 7%, db 59/s. + const rolled = runFor(design({ twoCaches: true }), 30).snapshot().nodes; + const keyed = runFor(design({ keys: 16, twoCaches: true }), 30).snapshot().nodes; + expect(rolled.c2!.hitRate).toBeGreaterThan(0.7); + expect(keyed.c2!.hitRate).toBeLessThan(0.15); + expect(keyed.db!.arrivalRate).toBeGreaterThan(4 * rolled.db!.arrivalRate); + }); + + it('comes back empty from a restart and fills again from the store', () => { + let before = -1; + let after = -1; + let refilled = -1; + runFor(design({ keys: 16 }), 25, (e, s) => { + if (s === 14) before = e.snapshot().nodes.c1!.cachedKeys!; + if (s === 15) { + e.injectFailure('c1', 'restart', { downMs: 1000 }); + after = e.snapshot().nodes.c1!.cachedKeys!; + } + if (s === 24) refilled = e.snapshot().nodes.c1!.cachedKeys!; + }); + expect(before).toBe(16); + expect(after).toBe(0); + expect(refilled).toBe(16); + }); + + it('stays empty while it is down, even as answers to its old calls come back', () => { + const engine = runFor(design({ keys: 16 }), 15); + expect(engine.snapshot().nodes.c1!.cachedKeys).toBe(16); + engine.injectFailure('c1', 'restart', { downMs: 1000 }); + let most = 0; + // Frame by frame through the second it is down. + for (let i = 0; i < 58; i++) { + engine.advance(1000 / 60); + most = Math.max(most, engine.snapshot().nodes.c1!.cachedKeys!); + } + expect(most).toBe(0); + }); + + it('fills only from reads, and a write forgets its key', () => { + // The database decides which calls are writes. Every one is here, so + // nothing is ever filled and nothing is ever answered from a copy. + const t = design({ keys: 64 }); + t.nodes.find((n) => n.id === 'db')!.config.readFraction = 0; + const c1 = runFor(t, 10).snapshot().nodes.c1!; + expect(c1.hitRate).toBe(0); + expect(c1.cachedKeys).toBe(0); + }); + + it('works the same on a CDN', () => { + const t = design({ keys: 16 }); + const cdn = node('cdn', 'c1'); + cdn.config.hitRate = 0.8; + cdn.config.cacheKeys = 16; + t.nodes[1] = cdn; + const s = runFor(t, 30).snapshot().nodes.c1!; + expect(s.hitRate).toBeGreaterThan(0.55); + expect(s.hitRate).toBeLessThan(0.7); + expect(s.cachedKeys).toBe(16); + }); +}); diff --git a/src/sim/cacheKeys.ts b/src/sim/cacheKeys.ts new file mode 100644 index 0000000..6b84d9e --- /dev/null +++ b/src/sim/cacheKeys.ts @@ -0,0 +1,132 @@ +import { KEYSPACE } from './keys'; +import type { NodeConfig } from './types'; + +/* ------------------------------------------------------------------ * + * A cache that remembers which keys it holds. + * + * The default cache rolls `hitRate` on every request, so two caches in a row + * are two independent coin flips and their misses multiply. That is not how + * a cache works: whether a request hits depends on whether its key is in + * there, and a request reaches the second cache only because the first one + * did not hold its key. With `cacheKeys` set, the cache holds that many of + * the keyspace's keys, fills a key when the call behind it answers a read, + * and evicts the key used least recently when it is full. Its hit rate is + * then measured, not set: hot keys make it high, an even spread makes it + * about `cacheKeys / KEYSPACE`, and a second cache behind the first sees + * only the cold keys the first one could not keep. + * + * Plain arrays over the keyspace, no random numbers and no events: a key is + * expired when the clock has passed its fill time plus the TTL, checked when + * the key is next looked up. Eviction scans 64 entries, which is cheaper than + * keeping a list in order. + * ------------------------------------------------------------------ */ + +/** Keys a cache holds when it switches to tracking keys and does not say. */ +export const DEFAULT_CACHE_KEYS = 16; +/** Longest TTL a cache accepts, in ms. */ +export const MAX_CACHE_TTL_MS = 60_000; + +/** + * How many keys the cache holds, 0..KEYSPACE. 0 means it does not track keys + * and rolls `hitRate` instead. Absent, negative and non-finite are all 0. + */ +export function effectiveCacheKeys(config: NodeConfig): number { + const v = config.cacheKeys; + if (v === undefined || !(v >= 1)) return 0; + return v > KEYSPACE ? KEYSPACE : Math.floor(v); +} + +/** How long a filled key stays good in ms, or 0 for until it is evicted. */ +export function effectiveCacheTtlMs(config: NodeConfig): number { + const v = config.cacheTtlMs; + if (v === undefined || !(v > 0)) return 0; + return v > MAX_CACHE_TTL_MS ? MAX_CACHE_TTL_MS : v; +} + +/** What one cache node holds. Lives in the node's `ext`. */ +export class KeyedCache { + /** When each key was filled, or -1 when it is not held. */ + private readonly filledAt = new Float64Array(KEYSPACE).fill(-1); + /** When each held key was last used, for eviction. */ + private readonly usedAt = new Float64Array(KEYSPACE); + private held = 0; + + /** Keys held right now, the expired ones still counted until next looked at. */ + get size(): number { + return this.held; + } + + /** Keys held and still good at `now`, for the readout. */ + goodAt(now: number, ttlMs: number): number { + if (ttlMs <= 0) return this.held; + let n = 0; + for (let k = 0; k < KEYSPACE; k++) { + const at = this.filledAt[k]!; + if (at >= 0 && now < at + ttlMs) n++; + } + return n; + } + + /** + * Whether `key` is held and still good at `now`. A hit counts as a use. + * An expired key is dropped here, so the miss that finds it goes downstream + * and fills it again, the way a TTL expiry sends every reader to the store. + */ + lookup(key: number, now: number, ttlMs: number, capacity: number): boolean { + this.fit(capacity); + const k = slot(key); + const at = this.filledAt[k]!; + if (at < 0) return false; + if (ttlMs > 0 && now >= at + ttlMs) { + this.drop(k); + return false; + } + this.usedAt[k] = now; + return true; + } + + /** Hold `key` from `now`, evicting the least recently used key when full. */ + fill(key: number, now: number, capacity: number): void { + if (capacity <= 0) return; + const k = slot(key); + if (this.filledAt[k]! < 0) { + this.fit(capacity - 1); + this.held++; + } + this.filledAt[k] = now; + this.usedAt[k] = now; + } + + /** Forget `key`, as a write to it does. */ + invalidate(key: number): void { + const k = slot(key); + if (this.filledAt[k]! >= 0) this.drop(k); + } + + /** Forget everything, as a process that lost its memory does. */ + clear(): void { + this.filledAt.fill(-1); + this.held = 0; + } + + /** Evict least recently used keys until at most `capacity` are held. */ + private fit(capacity: number): void { + while (this.held > capacity && this.held > 0) { + let oldest = -1; + for (let k = 0; k < KEYSPACE; k++) { + if (this.filledAt[k]! < 0) continue; + if (oldest < 0 || this.usedAt[k]! < this.usedAt[oldest]!) oldest = k; + } + this.drop(oldest); + } + } + + private drop(k: number): void { + this.filledAt[k] = -1; + this.held--; + } +} + +function slot(key: number): number { + return ((Math.floor(key) % KEYSPACE) + KEYSPACE) % KEYSPACE; +} diff --git a/src/sim/engine.ts b/src/sim/engine.ts index ec5febb..2b1f336 100644 --- a/src/sim/engine.ts +++ b/src/sim/engine.ts @@ -2057,6 +2057,10 @@ export class Engine implements BehaviourCtx { state.lostInLastCrash = memory.crash(this.now, this.landWrite, this.loseWrite); } + // What the process held in memory is gone with it: a cache comes back + // cold, and every read it would have answered goes to the store. + state.behaviour.onMemoryLost?.(state); + const waiting: Req[] = []; for (let i = state.waitHead; i < state.waiting.length; i++) { const req = state.waiting[i]; diff --git a/src/sim/types.ts b/src/sim/types.ts index 08be98a..6f225a7 100644 --- a/src/sim/types.ts +++ b/src/sim/types.ts @@ -121,6 +121,22 @@ export interface NodeConfig { * component that reads keys downstream sees the same hot key. */ keySkew?: number; + /** + * Cache and CDN only: how many of the 64 keys it holds, 1..64. Absent or 0 + * keeps the old model, where every request rolls `hitRate` on its own. + * Set, the cache fills a key when the call behind it answers a read, evicts + * the key used least recently when full, and forgets everything when it + * crashes or restarts, so its hit rate comes from the traffic's keys + * instead of a setting, and a second cache behind it sees only the keys + * the first one could not keep. A write passing through forgets its key. + */ + cacheKeys?: number; + /** + * Cache and CDN with `cacheKeys` only: ms a filled key stays good before + * the next read of it goes to the store again, 0..60000. Absent or 0 keeps + * a key until it is evicted. + */ + cacheTtlMs?: number; /** * Client only, `bursty` traffic: the average number of requests that arrive * together in one clump, 1..50. Clumps are spaced so the average rate stays @@ -1044,6 +1060,11 @@ export interface NodeStats { * fraction is reported in the shared `hitRate` field above. */ originFetchRate?: number; + /** + * Cache and CDN with `cacheKeys` only: keys it holds right now, out of + * `cacheKeys`. Absent on a cache that rolls `hitRate`. + */ + cachedKeys?: number; /* ---- ratelimiter readouts ---------------------------------------- */