// THE KERNEL'S REDIS LIBRARY: THE COMMAND CORE — a real, stateful Redis data model folded out of the World's tree. // `GET` returns what `SET` actually wrote, `INCR` on a non-numeric string raises Redis's own // "ERR value is not an integer or out of range", `LPUSH` against a string raises `WRONGTYPE`, and // a key with a TTL stops existing once the request clock passes its deadline. // // A KERNEL LIBRARY, as the git plane is (docs/contributing/architecture.md, "The engine slot" and "Other wires: // lanes, headers and line protocols"): Redis's semantics are shared by every pack that serves a Redis — the upstash // pack over Upstash's REST envelope, the redis pack over Redis's own protocol — and no pack imports another (A3). // What a wire answers differently is its DIALECT (`RedisDialect`): its refusals, the commands it adds, its Lua // libraries and how its keys sit in the tree. The kernel names no vendor; each pack passes its own. // // Redis wire semantics follow redis.io's command pages and Upstash Redis 8.2.0's wire responses. // // ── STATE LIVES IN THE KERNEL, NOT IN A MAP ─────────────────────────────────────────────────── // Every Redis key is a subject of the dialect's service (by default ONE subject per key, `type:'key'`, id // `key:`; a dialect may lay collections out one subject per member), written through `applyTwinWrite` and // read back through `projectResources`. There is no side-store: kill the process, point a new one at the same // root, and `GET` still answers. // // ── THE CLOCK IS INJECTED, NEVER READ FROM THE WALL ─────────────────────────────────────────── // Expiry is computed against the CURRENT REQUEST'S `occurredAt` — the same timestamp the kernel stamps the action // with (a server passes `worldNow()`). A verify pins `occurredAt` and gets deterministic TTL arithmetic; to test // EXPIRY it issues the next request with a LATER pinned `occurredAt`, a clock advance expressed as data. // // Expiration is LAZY, exactly like Redis: an expired key is not erased by a sweep, it simply stops // being visible to every read and is overwritten by the next write. `DBSIZE`, `KEYS`, `SCAN`, // `EXISTS`, `TTL` and `TYPE` all agree with `GET` about which keys are alive at a given instant. // // ── ONE REQUEST = ONE SYNCHRONOUS RUN OVER A KEYSPACE SNAPSHOT ──────────────────────────────── // `execRedisRun` takes the keyspace's image (folded once per World state and patched by what each write touched), // executes every command in the request against a `KeySpace` over it, then flushes the keys that were actually // touched back into the kernel. Two things fall out of that shape and both matter: // • `EVAL` becomes possible at all. `redis.call` is SYNCHRONOUS in Lua and cannot await a kernel // append; because the command core is synchronous over the snapshot, a script's calls run // inline and its writes are visible to its own later reads. // • A script's writes only reach the log at flush time; whether a script that raises part-way keeps what it // wrote (Redis) or leaves nothing behind (Upstash) is the dialect's `scriptErrorsKeepWrites`. // The DISCLOSED cost: within one request, N writes to the same key collapse into ONE kernel action // carrying the final value, so the action log records the request's net effect rather than every // intermediate. State is identical either way; only the granularity of the audit trail differs. // // Nothing here ever invents a success for an operation it does not implement: a command neither the core nor the // dialect serves answers the dialect's own refusal. import { createHash } from 'node:crypto'; import { projectResources } from '../actions.ts'; import { treeChangesSince, treeStamp } from '../log.ts'; import { redisServiceTimes as times } from './service-times.ts'; import { applyTwinWrites, type TwinResource, type TwinWriteInput } from '../serve.ts'; import { getActiveWorldStore } from '../world-store.ts'; import { LUA_NULL, luaScriptSha1, LuaError, LuaTable, runLua, type LuaHost, type LuaValue } from './lua.ts'; import { inlineCommand } from './frames.ts'; /** * A Redis SIMPLE STATUS reply, kept distinct from a bulk string. * * This is not pedantry — it is required for `Upstash-Encoding: base64` fidelity. LIVE-PROBED rule: * with that header on, Upstash base64-encodes every string in `result` at any array depth EXCEPT * the simple-status reply `OK`, which is passed through raw. `PING`'s status `PONG` IS encoded * (`UE9ORw==`), and so is a BULK STRING whose value happens to be `OK` (`GET okkey` → `T0s=`). So * the exemption is scoped to the status reply `OK` specifically, and a twin that exempted any * string equal to `"OK"` would send raw bytes for `GET okkey`. Hence this wrapper. */ export class RedisStatus { constructor(readonly value: string) {} } export const OK = new RedisStatus('OK'); /** The JSON projection of a RESP reply — what Upstash puts in `{"result": …}`. */ // Redis integers are signed 64-bit on RESP; JSON clients read them as JSON numbers. export class RedisInteger { constructor(readonly integer: string) {} } const integerReply = (n: bigint): number | RedisInteger => n >= -9007199254740991n && n <= 9007199254740991n ? Number(n) : new RedisInteger(String(n)); export type RedisValue = null | number | string | RedisStatus | RedisInteger | RedisValue[]; /** A command-level failure. `message` is the vendor's literal error string. Maps to HTTP 400. */ export class RedisCommandError extends Error { constructor(message: string) { super(message); this.name = 'RedisCommandError'; } } /** Thrown when a write is attempted against a read-only twin. Mapped to HTTP 405 by the handler. */ export class ReadOnlyError extends Error { constructor() { super('read_only: this twin was started read-only; omit readOnly to accept writes'); this.name = 'ReadOnlyError'; } } /** Redis's type name for a stream, as TYPE answers it (a Redis type, not a pack name: scripts/architecture-auto.ts A2). */ const STREAM = 'stream' as const; export const KEY_TYPES = ['string', 'list', 'set', 'hash', 'zset', STREAM] as const; export type KeyType = typeof KEY_TYPES[number]; export type HashPairs = Array<[string, string]>; export type ZSetPairs = Array<[string, number]>; /** * How a zset is STORED. Scores persist as the STRING Redis itself would print, never as raw JSON * numbers — because `JSON.stringify(Infinity)` is `null`, and `ZADD key +inf member` is ordinary * Redis (leaderboard sentinels, "pin this to the top" idioms). §9 round 1 caught the bug this * prevents: an in-memory `+inf` survived within one request and came back as the literal bulk * string "null" on the next, whereupon `ZRANGEBYSCORE key 0 100` cheerfully returned the member — * a plausible-looking WRONG answer over persisted state, which is the exact failure mode this pack * forbids. `fmtScore`/`toFloat` round-trip inf, -inf and every finite double faithfully. */ type StoredZSet = Array<[string, string]>; export type StreamEntries = Array<[string, HashPairs]>; /** A point-in-time copy of a run's whole mutable state, for script rollback. */ type Snapshot = { rows: OverlayState; touched: Map; scripts: OverlayState; touchedScripts: Map }; export type KeyRow = { name: string; kind: KeyType; /** string → string; list/set → string[]; hash → [f,v][]; zset → [member,score][]; stream → [id,[f,v][]][] */ v: string | string[] | HashPairs | ZSetPairs | StreamEntries; /** Exact absolute expiry deadline in epoch ms, persisted as decimal digits, or null for "no TTL". */ pexpireAt: string | null; /** Stream only: the last id this stream minted, so `*` stays monotonic. */ lastId?: string; /** Stream only: its consumer groups and counters, as the dialect that serves them keeps them (the redis pack's XGROUP). */ meta?: unknown; /** * A per-key WRITE ORDINAL, incremented on every flush. No command ever reads it and it never * leaves this module — it exists solely to defeat the kernel's action dedupe. * * THE BUG IT FIXES (found by self-attack after §9 round 1): `applyTwinWrite` dedupes by * (content + occurredAt millisecond), so writing a key back to a value it ALREADY HELD at the * same instant produced an actionId identical to the earlier action and was silently dropped as * `replayed`. The projection then folded to the LATER surviving action, so the key kept the * WRONG value while the command's reply reported the right one — reply and state disagreeing, * which is the worst shape a wrong answer can take. Concretely, with a pinned clock: * ZADD e 10 m ; ZADD e INCR 5 m → 15 ; ZADD e XX INCR 5 m → 20 ; ZADD e GT INCR 5 m → 25 ; * ZADD e LT INCR -5 m → answered 20, but ZSCORE still said 25 * because a `[["m","20"]]` action already existed at that instant. The same hazard reaches any * `SET k a ; SET k b ; SET k a` landing inside one millisecond. Bumping an ordinal makes every * write's content unique, so nothing can be mistaken for a replay. */ _rev?: number; }; /** Everything a run needs. `root` scopes the kernel state; `occurredAt` IS the clock. */ export type RedisContext = { root?: string; occurredAt: string; /** When true, any write command raises `ReadOnlyError` (the wire answers its read-only refusal). */ readOnly?: boolean; /** Commands queued in a wire transaction, rather than an ordinary pipeline. */ transaction?: boolean; /** A database other than the service's first (Redis's SELECT n, a vendor's database id), whose keys and scripts * are its own: subjects `db::key:` and `db::script:`. Absent: `key:`, `script:`. */ database?: string; /** The World service whose tree holds the keys: the pack's own. */ service: string; /** The wire the core answers for: its refusals, its commands, its Lua, its layout. */ dialect: RedisDialect; }; /** * WHAT A WIRE ANSWERS DIFFERENTLY. Stock Redis and Upstash's REST envelope serve one set of Redis semantics and * differ in what they refuse and what they add; a dialect carries exactly those differences. */ export type RedisDialect = { /** The refusal for a command neither the core nor the dialect serves. */ unknownCommand: (argv: string[]) => string; /** The refusal for an option of a served command the core does not model (`ZRANGE BYLEX`, `XADD MAXLEN trimming`): * a loud refusal, never a success, in the wire's words. */ unmodeled: (what: string) => string; /** The whole queue-time check, when the wire has its own (Upstash's REST-restricted commands, its table's arity); * absent, a command is checked against the dialect's commands, then the core's, by arity. */ shapeError?: (argv: string[]) => string | null; /** The dialect's own commands, `[min, max]` arguments after the name as `SERVED_COMMANDS`, run before the core. */ commands: Record; exec: (space: KeySpace, argv: string[]) => RedisValue; /** Which of the dialect's commands write. */ writes: ReadonlySet; /** The script environment (`extend`: the command API's name, runtime libraries) and how a Lua number becomes a * command argument (Redis 7: the shortest round-tripping form; Upstash: truncated). */ lua: Required>; /** Whether a script that fails part-way keeps what it wrote (Redis) or leaves nothing (Upstash). */ scriptErrorsKeepWrites: boolean; /** Wire-specific Lua flags. A flag installs a restriction before each command; the core owns `no-writes`. * Flags absent here are refused, never ignored. A transaction is passed explicitly by the wire. */ scriptFlags?: Record (argv: string[]) => void>; /** How the dialect's keys are laid out in the tree, when not one subject per key (`keyspaceImageOf`, `flushKeySpace`). */ storage?: { image: (ctx: RedisContext) => KeyspaceImage; flush: (space: KeySpace) => Promise }; }; /** The subject-id prefix of a context's database. */ const scopeOf = (ctx: RedisContext): string => (ctx.database === undefined ? '' : `db:${ctx.database}:`); // ───────────────────────────────────────────────────────────────────────────────────────────── // ERROR STRINGS — Redis's own, byte for byte (live-probed off a real Upstash database, redis_version 8.2.0). // ───────────────────────────────────────────────────────────────────────────────────────────── export const WRONGTYPE = 'WRONGTYPE Operation against a key holding the wrong kind of value'; export const NOT_INT = 'ERR value is not an integer or out of range'; export const NOT_FLOAT = 'ERR value is not a valid float'; export const SYNTAX = 'ERR syntax error'; export const NO_SUCH_KEY = 'ERR no such key'; const NOSCRIPT = 'NOSCRIPT No matching script. Please use EVAL.'; export function wrongArity(name: string): string { return `ERR wrong number of arguments for '${name.toLowerCase()}' command`; } /** * The commands the core serves, each with the most arguments (after the name) its own parsing takes, * `-1` for no bound: `[min, max]`, where `min` is Redis's table arity and `max` is what the command itself * refuses past, with the same "wrong number of arguments". One table for both callers, `execOne` and * `commandShapeError` (which lets a transaction reject a malformed batch at QUEUE time, as Redis's `EXECABORT` * does). SCRIPT is a container: its subcommands are LOAD, EXISTS and FLUSH. SELECT is the dialect's: a database is * a connection's (Redis) or a URL's (Upstash). */ export const SERVED_COMMANDS: Record = { PING: [0, 1], ECHO: [1, 1], DBSIZE: [0, 0], TYPE: [1, 1], FLUSHDB: [0, 1], FLUSHALL: [0, 1], KEYS: [1, 1], RANDOMKEY: [0, 0], SCAN: [1, -1], EXISTS: [1, -1], TOUCH: [1, -1], DEL: [1, -1], UNLINK: [1, -1], EXPIRE: [2, -1], PEXPIRE: [2, -1], EXPIREAT: [2, -1], PEXPIREAT: [2, -1], TTL: [1, 1], PTTL: [1, 1], PERSIST: [1, 1], RENAME: [2, 2], RENAMENX: [2, 2], GET: [1, 1], GETDEL: [1, 1], GETSET: [2, 2], GETEX: [1, 3], SET: [2, -1], SETNX: [2, 2], SETEX: [3, 3], PSETEX: [3, 3], MGET: [1, -1], MSET: [2, -1], MSETNX: [2, -1], APPEND: [2, 2], STRLEN: [1, 1], INCR: [1, 1], DECR: [1, 1], INCRBY: [2, 2], DECRBY: [2, 2], INCRBYFLOAT: [2, 2], HSET: [3, -1], HMSET: [3, -1], HSETNX: [3, 3], HGET: [2, 2], HMGET: [2, -1], HGETALL: [1, 1], HKEYS: [1, 1], HVALS: [1, 1], HLEN: [1, 1], HEXISTS: [2, 2], HDEL: [2, -1], HINCRBY: [3, 3], HINCRBYFLOAT: [3, 3], SADD: [2, -1], SREM: [2, -1], SMEMBERS: [1, 1], SCARD: [1, 1], SISMEMBER: [2, 2], SMISMEMBER: [2, -1], SPOP: [1, 2], SRANDMEMBER: [1, 2], LPUSH: [2, -1], RPUSH: [2, -1], LPOP: [1, 2], RPOP: [1, 2], LLEN: [1, 1], LINDEX: [2, 2], LSET: [3, 3], LRANGE: [3, 3], LTRIM: [3, 3], LREM: [3, 3], ZADD: [3, -1], ZINCRBY: [3, 3], ZSCORE: [2, 2], ZCARD: [1, 1], ZCOUNT: [3, 3], ZRANK: [2, 3], ZREVRANK: [2, 3], ZREM: [2, -1], ZREMRANGEBYSCORE: [3, 3], ZREMRANGEBYRANK: [3, 3], ZRANGE: [3, -1], ZREVRANGE: [3, -1], ZRANGEBYSCORE: [3, -1], ZREVRANGEBYSCORE: [3, -1], LPOS: [2, -1], RPOPLPUSH: [2, 2], ZPOPMIN: [1, 2], XTRIM: [3, -1], XADD: [4, -1], XLEN: [1, 1], XRANGE: [3, -1], XREVRANGE: [3, -1], XDEL: [2, -1], SCRIPT: [1, -1], EVAL: [2, -1], EVAL_RO: [2, -1], EVALSHA: [2, -1], EVALSHA_RO: [2, -1], }; /** Redis hash tag: the first nonempty {...} pair, otherwise the entire key (an empty first pair is invalid). */ export function redisHashTag(key: string): string { const start = key.indexOf('{'); const end = start < 0 ? -1 : key.indexOf('}', start + 1); return end > start + 1 && start >= 0 ? key.slice(start + 1, end) : key; } /** Key positions of the shared core's commands. Undefined means database-wide access, a script, or an unknown * command; callers must refuse an unsupported restriction rather than guess that the command has no keys. */ export function redisCommandKeys(argv: readonly string[]): string[] | undefined { const name = (argv[0] ?? '').toUpperCase(); if (['PING', 'ECHO', 'SCRIPT'].includes(name)) return []; if (['EXISTS', 'TOUCH', 'DEL', 'UNLINK', 'MGET'].includes(name)) return argv.slice(1); if (name === 'MSET' || name === 'MSETNX') return argv.slice(1).filter((_, i) => i % 2 === 0); if (['RENAME', 'RENAMENX', 'RPOPLPUSH'].includes(name)) return argv.slice(1, 3); if (['DBSIZE', 'FLUSHDB', 'FLUSHALL', 'KEYS', 'RANDOMKEY', 'SCAN', 'EVAL', 'EVALSHA', 'EVAL_RO', 'EVALSHA_RO'].includes(name)) return undefined; return SERVED_COMMANDS[name] && argv[1] !== undefined ? [argv[1]] : undefined; } /** EVAL shebang metadata: keep the newline for Lua line numbers and the original script for cache identity. * source: https://raw.githubusercontent.com/redis/redis/c9d29f6a918c335bc1778d9f68e521c1bbb36a0f/src/eval.c (evalExtractShebangFlags). */ function redisScript(script: string, dialect: RedisDialect): { body: string; flags: Set } { const flags = new Set(); if (!script.startsWith('#!')) return { body: script, flags }; const newline = script.indexOf('\n'); if (newline < 0) throw new RedisCommandError('ERR Invalid script shebang'); let parts: string[]; try { parts = inlineCommand(script.slice(0, newline)); } catch { throw new RedisCommandError('ERR Invalid engine in script shebang'); } if (parts[0] !== '#!lua') throw new RedisCommandError(`ERR Unexpected engine in script shebang: ${parts[0] ?? ''}`); for (const option of parts.slice(1)) { if (!option.startsWith('flags=')) throw new RedisCommandError(`ERR Unknown lua shebang option: ${option}`); for (const flag of option.slice(6).split(',')) { if (!flag && option === 'flags=') continue; if (flag !== 'no-writes' && !Object.hasOwn(dialect.scriptFlags ?? {}, flag)) { throw new RedisCommandError(dialect.unmodeled(`Lua script flag ${flag}`)); } flags.add(flag); } } return { body: script.slice(newline), flags }; } /** Commands that mutate state — refused by a read-only twin and inside `EVAL_RO`/`EVALSHA_RO`. */ const WRITE_COMMANDS = new Set([ 'SET', 'SETEX', 'PSETEX', 'SETNX', 'MSET', 'MSETNX', 'GETSET', 'GETDEL', 'GETEX', 'APPEND', 'DEL', 'UNLINK', 'INCR', 'DECR', 'INCRBY', 'DECRBY', 'INCRBYFLOAT', 'EXPIRE', 'PEXPIRE', 'EXPIREAT', 'PEXPIREAT', 'PERSIST', 'RENAME', 'RENAMENX', 'FLUSHDB', 'FLUSHALL', 'HSET', 'HSETNX', 'HMSET', 'HDEL', 'HINCRBY', 'HINCRBYFLOAT', 'SADD', 'SREM', 'SPOP', 'LPUSH', 'RPUSH', 'LPOP', 'RPOP', 'LREM', 'LSET', 'LTRIM', 'RPOPLPUSH', 'ZPOPMIN', 'XTRIM', 'ZADD', 'ZINCRBY', 'ZREM', 'ZREMRANGEBYSCORE', 'ZREMRANGEBYRANK', 'XADD', 'XDEL', // NB: 'SCRIPT' is deliberately ABSENT — it is classified per SUBCOMMAND below, because // `SCRIPT EXISTS` is a pure read and a read-only twin must serve every read (§9 round 1 found // it answering 405). Likewise `EVAL_RO`/`EVALSHA_RO` are reads by definition. 'EVAL', 'EVALSHA', ]); /** * Does this command MUTATE? Takes the whole argv, not just the name, because two commands are * only writes for some of their subcommands. A read-only twin and `EVAL_RO` both key off this, * and getting it wrong in either direction is a bug: too broad refuses legitimate reads (§9 round * 1), too narrow lets a write through a read-only twin. */ export function isWriteCommand(name: string, args: readonly string[] | undefined, dialect: RedisDialect): boolean { const cmd = name.toUpperCase(); if (dialect.commands[cmd] !== undefined) return dialect.writes.has(cmd); if (cmd === 'SCRIPT') { // FAIL SAFE when the caller gave no subcommand. §9 round 2: with `args` defaulting to `[]`, // `isWriteCommand('SCRIPT')` answered FALSE — so a consumer building their own read-only gate // on this exported function would classify `SCRIPT LOAD` as a read. An unknown subcommand is // treated as a write for the same reason: the cost of being wrong is asymmetric. if (args === undefined || args.length === 0) return true; const sub = String(args[0]).toUpperCase(); return sub !== 'EXISTS'; // EXISTS is the only read subcommand this twin serves } return WRITE_COMMANDS.has(cmd); } /** * QUEUE-TIME validation: is this command well-formed enough to accept into a transaction? Returns the wire's * error string, or `null` when the command is fine. Only structural faults live here (unknown command, wrong * arity) — a WRONGTYPE or a bad integer is a RUNTIME error, which does NOT abort a transaction. */ export function commandShapeError(argv: unknown[], dialect: RedisDialect): string | null { if (argv.length === 0) return 'ERR empty command'; const line = argv.map(String); if (dialect.shapeError) return dialect.shapeError(line); const name = line[0]!.toUpperCase(); const arity = dialect.commands[name] ?? SERVED_COMMANDS[name]; if (arity === undefined) return dialect.unknownCommand(line); const n = line.length - 1; if (n < arity[0] || (arity[1] !== -1 && n > arity[1])) return wrongArity(name); return null; } // ───────────────────────────────────────────────────────────────────────────────────────────── // THE KEYSPACE SNAPSHOT // ───────────────────────────────────────────────────────────────────────────────────────────── /** A database's keys, scripts and write ordinals as the tree holds them. Rows past their deadline are kept: a read * asks `live` at its own instant (Redis's `keyIsExpired` is `now > when`, so a key is still ALIVE at exactly its * deadline — §9 round 1 found the twin one millisecond early). */ export type KeyspaceImage = { rows: Map; scripts: Map; revs: Map }; // cache: the image folded once per World state and patched by the subjects each write touched (planetscale-store.ts's // loadState): a fold per command made every command's cost grow with the whole keyspace. Keyed by store, then by // service, root and database; the rows are shared and never changed in place (every command writes a new row). const imageMemos = new WeakMap>(); function keyspaceImageOf(ctx: RedisContext): KeyspaceImage { const service = ctx.service; const store = getActiveWorldStore(); const memos = imageMemos.get(store) ?? imageMemos.set(store, new Map()).get(store)!; const key = `${service}\u0000${ctx.root ?? ''}\u0000${scopeOf(ctx)}`; let held = memos.get(key); const delta = held ? treeChangesSince(service, ctx.root, held.stamp) : undefined; if (held && delta && patchImage(held.image, delta.changed, delta.removed, scopeOf(ctx))) held.stamp = delta.stamp; else { // the stamp is read before the fold: a write between them leaves a newer fold under an older stamp, refolded next time const stamp = treeStamp(service, ctx.root); if (!held || held.stamp !== stamp) { held = { stamp, image: { rows: new Map(), scripts: new Map(), revs: new Map() } }; patchImage(held.image, projectResources(service, ctx.root), [], scopeOf(ctx)); memos.set(key, held); } } return held.image; } /** Fold subjects into an image; false (the caller refolds) when a subject left the tree, which only a fold decides. */ function patchImage(image: KeyspaceImage, changed: readonly TwinResource[], removed: readonly string[], scope: string): boolean { if (removed.length > 0) return false; const scriptPrefix = `${scope}script:`; const keyPrefix = `${scope}key:`; for (const r of changed) { const rec = r as unknown as Record; if (r.type === 'script' && r.id.startsWith(scriptPrefix)) { const sha = r.id.slice(scriptPrefix.length); if (rec.gone !== true && typeof rec.body === 'string') image.scripts.set(sha, rec.body); else image.scripts.delete(sha); continue; } if (r.type !== 'key' || !r.id.startsWith(keyPrefix)) continue; const name = r.id.slice(keyPrefix.length); // Record the ordinal FIRST, for deleted and expired rows too: a key that is later recreated // must CONTINUE the sequence rather than restart it, or the collision could simply recur. if (typeof rec._rev === 'number') image.revs.set(name, rec._rev); if (rec.gone === true) { image.rows.delete(name); continue; } image.rows.set(name, { name, kind: rec.kind as KeyType, v: rec.v as KeyRow['v'], pexpireAt: typeof rec.pexpire_at === 'string' || typeof rec.pexpire_at === 'number' ? String(rec.pexpire_at) : null, ...(typeof rec.last_id === 'string' && rec.last_id !== '' ? { lastId: rec.last_id } : {}), ...(typeof rec._rev === 'number' ? { _rev: rec._rev } : {}), ...(rec.meta !== undefined && rec.meta !== null ? { meta: rec.meta } : {}), }); } return true; } const GONE: unique symbol = Symbol('gone'); type OverlayState = { own: Map; moved: Set }; /** * A run overlays its changed keys over the shared image. Iteration preserves the base's order with changed * values, then added keys. A base key deleted and set again moves to the added keys at its new set position. */ class Overlay { private own = new Map(); private moved = new Set(); constructor(private readonly base: ReadonlyMap) {} get(key: string): V | undefined { const mine = this.own.get(key); return mine === GONE ? undefined : mine !== undefined || this.own.has(key) ? mine as V : this.base.get(key); } has(key: string): boolean { return this.own.has(key) ? this.own.get(key) !== GONE : this.base.has(key); } set(key: string, value: V): void { if (this.own.get(key) === GONE) { this.own.delete(key); this.moved.add(key); } this.own.set(key, value); } delete(key: string): void { this.own.delete(key); this.moved.delete(key); if (this.base.has(key)) this.own.set(key, GONE); } *entries(): IterableIterator<[string, V]> { for (const [key, value] of this.base) { if (this.moved.has(key)) continue; if (!this.own.has(key)) { yield [key, value]; continue; } const mine = this.own.get(key)!; if (mine !== GONE) yield [key, mine]; } for (const [key, mine] of this.own) if (mine !== GONE && (!this.base.has(key) || this.moved.has(key))) yield [key, mine]; } *keys(): IterableIterator { for (const [key] of this.entries()) yield key; } *values(): IterableIterator { for (const [, value] of this.entries()) yield value; } /** What the run changed, copied: a rollback point the size of the changes, not of the keyspace. */ save(): OverlayState { return { own: new Map(this.own), moved: new Set(this.moved) }; } load(state: OverlayState): void { this.own = new Map(state.own); this.moved = new Set(state.moved); } } /** * A synchronous, in-memory image of the keyspace for the duration of ONE request. * * Seeded from the keyspace's image (the tree folded by `projectResources`, memoized per World state — the kernel IS * the source of truth); every mutation records the key name in `touched`, and the flush writes exactly those keys * back. This run owns its overlays: nothing a run changes reaches the image or a later request except * through the tree. */ export class KeySpace { private readonly rows: Overlay; private readonly touched = new Map(); // key → the operation label to record private readonly scripts: Overlay; // sha1 → script source (a SEPARATE namespace) private readonly touchedScripts = new Map(); /** name → the last write ordinal seen, INCLUDING for keys currently deleted or expired. */ private readonly revs: Overlay; /** The shared base maps are patched by the next image(); a KeySpace must finish reading its base before it yields. */ readonly image: KeyspaceImage; constructor(readonly ctx: RedisContext, readonly nowMs: number) { // The base maps are patched by the next image(); finish reading this run's base before yielding. const image = this.image = ctx.dialect.storage?.image(ctx) ?? keyspaceImageOf(ctx); this.rows = new Overlay(image.rows); this.scripts = new Overlay(image.scripts); this.revs = new Overlay(image.revs); } /** * Is this row expired AS OF NOW? Checked on every read, not merely when the snapshot was built. * * §9 round 2: a deadline set INTO THE PAST inside a batch (`SET k v PXAT 1`, `GETEX k EXAT 1`) * stayed visible for the rest of that batch, and `TTL` answered a huge negative number that real * Redis can never return. Filtering only at construction time made the twin disagree with itself * within one request; re-checking here makes every read path agree at every instant. */ private live(row: KeyRow | undefined): KeyRow | undefined { if (!row) return undefined; return row.pexpireAt !== null && BigInt(row.pexpireAt) < BigInt(this.nowMs) ? undefined : row; } all(): KeyRow[] { return [...this.rows.values()].filter((r) => this.live(r) !== undefined); } // ── the EVAL script cache ──────────────────────────────────────────────────────────────── // Kept in its OWN kernel subject type ('script'), NOT under a magic key prefix in the keyspace. // An earlier draft stored it as a key named ` twin:script:` and filtered that prefix out of // KEYS/SCAN/DBSIZE, which was a real collision bug: a caller who wrote a key with that exact name // (a legal Redis key — a leading space is fine) had it silently vanish from every listing AND // became able to run it as a script via EVALSHA. Separate subject types make the collision // impossible rather than filtered, so no keyspace command needs to know scripts exist. scriptFor(sha: string): string | undefined { return this.scripts.get(sha); } hasScript(sha: string): boolean { return this.scripts.has(sha); } putScript(sha: string, body: string): void { if (this.ctx.readOnly) throw new ReadOnlyError(); this.scripts.set(sha, body); this.touchedScripts.set(sha, 'script.load'); } flushScripts(): void { if (this.ctx.readOnly) throw new ReadOnlyError(); for (const sha of [...this.scripts.keys()]) { this.scripts.delete(sha); this.touchedScripts.set(sha, 'script.flush'); } } pendingScriptWrites(): Array<{ sha: string; operation: string; body: string | null }> { return [...this.touchedScripts.entries()].map(([sha, operation]) => ({ sha, operation, body: this.scripts.get(sha) ?? null })); } get(name: string): KeyRow | undefined { return this.live(this.rows.get(name)); } put(row: KeyRow, operation: string): void { if (this.ctx.readOnly) throw new ReadOnlyError(); this.rows.set(row.name, row); this.touched.set(row.name, operation); } remove(name: string, operation: string): void { if (this.ctx.readOnly) throw new ReadOnlyError(); this.rows.delete(name); this.touched.set(name, operation); } /** A point-in-time copy, so a failed script can be rolled back to exactly where it started. */ snapshot(): Snapshot { return { rows: this.rows.save(), touched: new Map(this.touched), scripts: this.scripts.save(), touchedScripts: new Map(this.touchedScripts) }; } restore(s: Snapshot): void { this.rows.load(s.rows); this.touched.clear(); for (const [k, v] of s.touched) this.touched.set(k, v); this.scripts.load(s.scripts); this.touchedScripts.clear(); for (const [k, v] of s.touchedScripts) this.touchedScripts.set(k, v); } pendingWrites(): Array<{ name: string; operation: string; row: KeyRow | null }> { return [...this.touched.entries()].map(([name, operation]) => ({ name, operation, row: this.rows.get(name) ?? null })); } /** The next write ordinal for a key — see `KeyRow._rev`. Survives deletes and expiry. */ nextRev(name: string): number { const next = (this.revs.get(name) ?? 0) + 1; this.revs.set(name, next); return next; } /** A key's write ordinal as the tree holds it, 0 for a key never written: what a WATCH compares. */ revOf(name: string): number { return this.revs.get(name) ?? 0; } /** The keys this run has written so far. */ touchedNames(): string[] { return [...this.touched.keys()]; } /** Did this run write anything? Used to decide whether the sync token advances. */ get dirty(): boolean { return this.touched.size > 0 || this.touchedScripts.size > 0; } } /** One key as a backup holds it: its name, type, value, deadline and a stream's last id. */ export type KeyImage = { name: string; kind: string; v: unknown; pexpireAt: string | null; lastId?: string }; /** A database's live keys as they stand at `ctx.occurredAt`: what a backup of it holds (the Developer API lane's * backups, ../api/src/semantics/backups.ts). */ export function keyspaceImage(ctx: RedisContext): KeyImage[] { return new KeySpace(ctx, Date.parse(ctx.occurredAt)).all().map((r) => ({ name: r.name, kind: r.kind, v: r.v, pexpireAt: r.pexpireAt, ...(r.lastId ? { lastId: r.lastId } : {}) })); } /** Read a database as it stands at `ctx.occurredAt`, writing nothing: what the redis pack's WATCH records and compares. */ export function readKeySpace(ctx: RedisContext, read: (space: KeySpace) => T): T { return read(new KeySpace(ctx, Date.parse(ctx.occurredAt))); } /** Replace a database's keys with a backup's: every live key is deleted, then the image's keys are written ("All * existing data in the target database will be deleted before the restore operation begins", * https://upstash.com/docs/redis/features/backup). */ export async function restoreKeyspace(image: readonly KeyImage[], ctx: RedisContext): Promise { const space = new KeySpace(ctx, Date.parse(ctx.occurredAt)); for (const r of space.all()) space.remove(r.name, 'key.restore'); for (const k of image) space.put({ name: k.name, kind: k.kind as KeyType, v: k.v as KeyRow['v'], pexpireAt: k.pexpireAt, ...(k.lastId ? { lastId: k.lastId } : {}) }, 'key.restore'); await flushKeySpace(space); } async function flushKeySpace(space: KeySpace): Promise { // a run's writes land together, in this order, as they landed one at a time (serve.ts applyTwinWrites) const writes: TwinWriteInput[] = []; for (const { name, operation, row } of space.pendingWrites()) { writes.push({ operation, subjectType: 'key', subjectId: `${scopeOf(space.ctx)}key:${name}`, // The kernel MERGES fields, so a delete must write EVERY field back to its "nothing here" // value — leaving `v`/`pexpire_at` behind would let a later recreate inherit a dead value // or a dead TTL. fields: row === null ? { name, kind: 'string', v: '', pexpire_at: null, last_id: '', gone: true, _rev: space.nextRev(name) } : { name, kind: row.kind, v: row.v as never, pexpire_at: row.pexpireAt, last_id: row.lastId ?? '', gone: false, _rev: space.nextRev(name) }, occurredAt: space.ctx.occurredAt, actor: { kind: 'agent' }, }); } for (const { sha, operation, body } of space.pendingScriptWrites()) { writes.push({ operation, subjectType: 'script', subjectId: `${scopeOf(space.ctx)}script:${sha}`, fields: body === null ? { sha, body: '', gone: true } : { sha, body, gone: false }, occurredAt: space.ctx.occurredAt, actor: { kind: 'agent' }, }); } await applyTwinWrites(space.ctx.service, writes, space.ctx.root); } // ── typed value accessors (each asserts the key's type first) ───────────────────────────────── export function expectType(row: KeyRow | undefined, kind: KeyType): void { if (row && row.kind !== kind) throw new RedisCommandError(WRONGTYPE); } export const asString = (row: KeyRow | undefined): string | undefined => { expectType(row, 'string'); expectShape(row, typeof row?.v === 'string'); return row ? (row.v as string) : undefined; }; /** * Every accessor below asserts the STORED SHAPE, not just the declared type. * * §9 round 2: a connector-pulled stream was stored with `kind:'stream'` but a JSON STRING body, * so `asStream`'s `.map` threw a raw `TypeError` that escaped `handleUpstashRedisTwinRequest` * entirely (it only catches `RedisCommandError`/`ReadOnlyError`) and surfaced as an unhandled * rejection instead of any HTTP response. A twin must fail like the vendor even when its own * stored state is wrong. */ function expectShape(row: KeyRow | undefined, ok: boolean): void { if (row && !ok) throw new RedisCommandError(`ERR twin: key '${row.name}' is stored as ${row.kind} but its value is malformed — the state it was written from is not usable`); } export const asList = (row: KeyRow | undefined): string[] => { expectType(row, 'list'); expectShape(row, Array.isArray(row?.v)); return row ? [...(row.v as string[])] : []; }; export const asSet = (row: KeyRow | undefined): string[] => { expectType(row, 'set'); expectShape(row, Array.isArray(row?.v)); return row ? [...(row.v as string[])] : []; }; export const asHash = (row: KeyRow | undefined): HashPairs => { expectType(row, 'hash'); expectShape(row, Array.isArray(row?.v)); return row ? (row.v as HashPairs).map(([f, v]) => [f, v] as [string, string]) : []; }; export const asZSet = (row: KeyRow | undefined): ZSetPairs => { expectType(row, 'zset'); expectShape(row, Array.isArray(row?.v)); // Tolerates a raw number too, so a connector-pulled or hand-written row still loads. return row ? (row.v as StoredZSet).map(([m, sc]) => [m, typeof sc === 'number' ? sc : toFloat(sc)] as [string, number]) : []; }; /** Serialize for the kernel. The inverse of `asZSet` — see `StoredZSet`. */ export const storeZSet = (pairs: ZSetPairs): StoredZSet => pairs.map(([m, sc]) => [m, fmtScore(sc)] as [string, string]); export const asStream = (row: KeyRow | undefined): StreamEntries => { expectType(row, STREAM); expectShape(row, Array.isArray(row?.v)); return row ? (row.v as StreamEntries).map(([id, f]) => [id, f.map(([field, value]) => [field, value] as [string, string])] as [string, HashPairs]) : []; }; // ── numeric parsing (Redis's exact acceptance rules) ────────────────────────────────────────── // source: https://raw.githubusercontent.com/redis/redis/c9d29f6a918c335bc1778d9f68e521c1bbb36a0f/src/util.c "Convert a string into a long long." export function integerArgument(raw: string, message = NOT_INT, unsigned = false): bigint { // source: https://raw.githubusercontent.com/redis/redis/c9d29f6a918c335bc1778d9f68e521c1bbb36a0f/src/util.c "strtoull() is used instead." if (unsigned) { const canonical = /^(0|[1-9]\d*|-[1-9]\d*)$/.test(raw); if (!canonical && !/^[ \t\r\n\v\f]*[+-]?\d+$/.test(raw)) throw new RedisCommandError(message); const n = BigInt(raw.trim()); if (n > 18446744073709551615n || n < -18446744073709551615n || canonical && n < 0n) throw new RedisCommandError(message); return BigInt.asUintN(64, n); } if (!/^(0|[1-9]\d*|-[1-9]\d*)$/.test(raw)) throw new RedisCommandError(message); const n = BigInt(raw); if (n < -9223372036854775808n || n > 9223372036854775807n) throw new RedisCommandError(message); return n; } // Collection positions/counts are bounded by their actual arrays, not by Number.MAX_SAFE_INTEGER. export const commandInteger = (raw: string, message = NOT_INT): number => Number(integerArgument(raw, message)); export const toInt = commandInteger; export const unsignedArgument = (raw: string, message: string): bigint => integerArgument(raw, message, true); // source: https://raw.githubusercontent.com/redis/redis/c9d29f6a918c335bc1778d9f68e521c1bbb36a0f/src/object.c "value is out of range, must be positive" export function positiveInteger(raw: string, message = 'ERR value is out of range, must be positive'): number { const n = integerArgument(raw, message); if (n < 0) throw new RedisCommandError(message); return Number(n); } export function toFloat(raw: string): number { if (raw !== raw.trim() || raw === '') throw new RedisCommandError(NOT_FLOAT); if (/^[+-]?inf(inity)?$/i.test(raw)) return raw.startsWith('-') ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY; const n = Number(raw); if (!Number.isFinite(n)) throw new RedisCommandError(NOT_FLOAT); return n; } /** * Redis's float-increment guard. `t_string.c` and `t_hash.c` both do * `if (isnan(value) || isinf(value)) addReplyError(c,"increment would produce NaN or Infinity")`. * * §9 round 2 found this missing on the string and hash paths (it had only been added to the sorted * set): `INCRBYFLOAT f inf` answered 200 with "inf", `INCRBYFLOAT f -inf` then persisted the * literal "NaN", and the very next `INCRBYFLOAT f 1` answered "not a valid float" — the twin had * written a value it could no longer read. A fake success that poisons its own key. */ export function guardFloatResult(next: number): number { if (Number.isNaN(next) || !Number.isFinite(next)) throw new RedisCommandError('ERR increment would produce NaN or Infinity'); return next; } /** Redis renders a score as a bulk string; infinities spell out. */ export function fmtScore(n: number): string { if (n === Number.POSITIVE_INFINITY) return 'inf'; if (n === Number.NEGATIVE_INFINITY) return '-inf'; return String(n); } /** Redis sorts a zset by (score, then member lexicographically). */ export function sortZSet(pairs: ZSetPairs): ZSetPairs { return [...pairs].sort((a, b) => (a[1] - b[1]) || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)); } /** Redis's start/stop index normalisation (negatives count from the end, ends clamp). */ export function normalizeRange(startRaw: number, stopRaw: number, length: number): [number, number] { let start = startRaw < 0 ? length + startRaw : startRaw; let stop = stopRaw < 0 ? length + stopRaw : stopRaw; if (start < 0) start = 0; if (stop >= length) stop = length - 1; return [start, stop]; } /** Redis glob-style key matching (`*`, `?`, `[abc]`, `[a-c]`, `[^a]`, `\` escape). */ export function globMatch(pattern: string, subject: string): boolean { let re = ''; const esc = (c: string) => c.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); for (let i = 0; i < pattern.length; i++) { const c = pattern[i]!; if (c === '\\' && i + 1 < pattern.length) { re += esc(pattern[++i]!); continue; } if (c === '*') { re += '[\\s\\S]*'; continue; } if (c === '?') { re += '[\\s\\S]'; continue; } if (c === '[') { const close = pattern.indexOf(']', i + 1); if (close < 0) { re += '\\['; continue; } let cls = pattern.slice(i + 1, close); const negate = cls.startsWith('^'); if (negate) cls = cls.slice(1); re += `[${negate ? '^' : ''}${cls.replace(/\\/g, '\\\\')}]`; i = close; continue; } re += esc(c); } return new RegExp(`^${re}$`).test(subject); } // ── TTL option parsing, shared by SET and GETEX ──────────────────────────────────────────────── function ttlFromToken(token: string, value: string, nowMs: number, cmd: string): string { const n = integerArgument(value); const millis = token === 'ex' || token === 'exat' ? n * 1000n : n; const at = token === 'ex' || token === 'px' ? BigInt(Math.trunc(nowMs)) + millis : millis; // source: https://raw.githubusercontent.com/redis/redis/c9d29f6a918c335bc1778d9f68e521c1bbb36a0f/src/t_string.c "Overflow detected." if (n <= 0n || millis > 9223372036854775807n || at > 9223372036854775807n) throw new RedisCommandError(`ERR invalid expire time in '${cmd}' command`); return String(at); } // ───────────────────────────────────────────────────────────────────────────────────────────── // COMMAND DISPATCH — fully synchronous over the snapshot (see the file header for why). // ───────────────────────────────────────────────────────────────────────────────────────────── export function execOne(space: KeySpace, argv: string[]): RedisValue { const dialect = space.ctx.dialect; const shapeError = commandShapeError(argv, dialect); if (shapeError !== null) throw new RedisCommandError(shapeError); const name = argv[0]!.toUpperCase(); const a = argv.slice(1); const nowMs = space.nowMs; if (space.ctx.readOnly && isWriteCommand(name, a, dialect)) throw new ReadOnlyError(); if (dialect.commands[name] !== undefined) return dialect.exec(space, argv); switch (name) { // ── connection / server ────────────────────────────────────────────────────────────────── // https://redis.io/docs/latest/commands/rpoplpush/: atomically moves the last element to the destination's head. case 'RPOPLPUSH': { const sourceRow = space.get(a[0]!); const source = asList(sourceRow); asList(space.get(a[1]!)); const value = source.pop(); if (value === undefined) return null; // source: https://raw.githubusercontent.com/redis/redis/c9d29f6a918c335bc1778d9f68e521c1bbb36a0f/src/t_list.c "listTypePush(dstobj,value,where);" // A rotation rewrites the existing list, including a singleton, without deleting its key or expiry. if (a[0] === a[1]) { source.unshift(value); space.put({ ...sourceRow!, v: source }, 'list.move'); return value; } if (source.length) space.put({ ...space.get(a[0]!)!, v: source }, 'list.move'); else space.remove(a[0]!, 'list.move'); const dest = space.get(a[1]!); const values = asList(dest); values.unshift(value); space.put({ name: a[1]!, kind: 'list', v: values, pexpireAt: dest?.pexpireAt ?? null }, 'list.move'); return value; } // https://redis.io/docs/latest/commands/lpos/: rank, count and maxlen apply to matching positions. case 'LPOS': { const values = asList(space.get(a[0]!)); let rank = 1, count: number | undefined, max = values.length; // source: https://raw.githubusercontent.com/redis/redis/c9d29f6a918c335bc1778d9f68e521c1bbb36a0f/src/t_list.c "COUNT can't be negative" for (let i = 2; i < a.length; i += 2) { const option = a[i]!.toUpperCase(); if (!['RANK', 'COUNT', 'MAXLEN'].includes(option) || i + 1 >= a.length) throw new RedisCommandError(SYNTAX); let value: number; try { value = commandInteger(a[i + 1]!); } catch (error) { if (option === 'RANK') throw error; throw new RedisCommandError(`ERR ${option} can't be negative`); } if (option === 'RANK') { if (a[i + 1] === '-9223372036854775808') throw new RedisCommandError('ERR value is out of range, value must between -9223372036854775807 and 9223372036854775807'); if (value === 0) throw new RedisCommandError("ERR RANK can't be zero: use 1 to start from the first match, 2 from the second ... or use negative to start from the end of the list"); rank = value; } else { if (value < 0) throw new RedisCommandError(`ERR ${option} can't be negative`); if (option === 'COUNT') count = value; else max = value || values.length; } } const matches = Array.from({ length: values.length }, (_, i) => i); if (rank < 0) matches.reverse(); const hits = matches.slice(0, max).filter((i) => values[i] === a[1]).slice(Math.abs(rank) - 1); return count === undefined ? hits[0] ?? null : hits.slice(0, count === 0 ? undefined : count); } // https://redis.io/docs/latest/commands/zpopmin/: lowest score first; ties by member. case 'ZPOPMIN': { const row = space.get(a[0]!); const pairs = sortZSet(asZSet(row)); let count = 1; // source: https://raw.githubusercontent.com/redis/redis/c9d29f6a918c335bc1778d9f68e521c1bbb36a0f/src/object.c "value is out of range, must be positive" try { if (a[1] !== undefined) count = commandInteger(a[1]); } catch { throw new RedisCommandError('ERR value is out of range, must be positive'); } if (count < 0) throw new RedisCommandError('ERR value is out of range, must be positive'); const popped = pairs.splice(0, count); if (popped.length) { if (pairs.length) space.put({ ...row!, v: storeZSet(sortZSet(pairs)) }, 'zset.pop'); else space.remove(a[0]!, 'zset.pop'); } return popped.flatMap(([m, score]) => [m, fmtScore(score)]); } // https://redis.io/docs/latest/commands/xtrim/: exact trimming also satisfies the approximate upper bound. case 'XTRIM': { const row = space.get(a[0]!); const entries = asStream(row); const spec = trimSpec(a, 1); if (spec.next !== a.length) throw new RedisCommandError(SYNTAX); const kept = trimEntries(entries, spec); if (row && kept.length !== entries.length) space.put({ ...row, v: kept }, 'stream.trim'); return entries.length - kept.length; } case 'PING': return a.length === 0 ? new RedisStatus('PONG') : a[0]!; case 'ECHO': return a[0]!; case 'DBSIZE': return visibleKeys(space).length; case 'TYPE': { const r = space.get(a[0]!); return new RedisStatus(r ? r.kind : 'none'); } case 'FLUSHDB': case 'FLUSHALL': { for (const r of space.all()) space.remove(r.name, 'key.flush'); return OK; } case 'KEYS': return visibleKeys(space).filter((k) => globMatch(a[0]!, k)).sort(); case 'RANDOMKEY': { // DETERMINISTIC by design: a twin that returned a genuinely random key could not be verified // offline. Disclosed in the manifest (`upstash.keyspace.randomkey_deterministic`). const keys = visibleKeys(space).sort(); return keys.length === 0 ? null : keys[0]!; } case 'SCAN': { // SCAN uses Redis's unsigned cursor parser, unlike signed COUNT. const cursor = Number(unsignedArgument(a[0]!, 'ERR invalid cursor')); let match: string | null = null; let count = 10; let typeFilter: string | null = null; for (let i = 1; i < a.length; i++) { const tok = a[i]!.toLowerCase(); if (tok === 'match') { if (i + 1 >= a.length) throw new RedisCommandError(SYNTAX); match = a[++i]!; continue; } if (tok === 'count') { if (i + 1 >= a.length) throw new RedisCommandError(SYNTAX); count = toInt(a[++i]!); if (count < 1) throw new RedisCommandError(SYNTAX); continue; } if (tok === 'type') { if (i + 1 >= a.length) throw new RedisCommandError(SYNTAX); typeFilter = a[++i]!.toLowerCase(); continue; } throw new RedisCommandError(SYNTAX); } // THE CURSOR CONTRACT. Redis's only guarantee is: 0 starts, a returned 0 ends, and a key // present for the WHOLE iteration is returned at least once (keys added or removed mid-scan // may or may not appear). §9 round 1 refuted the first design, an INDEX into a sorted list: // deleting a lower-sorted key shifts the list left under the cursor and a key that was // present throughout is skipped entirely — // MSET a1..a5 ; SCAN 0 COUNT 2 → ["2",[a1,a2]] ; DEL a1 ; SCAN 2 COUNT 2 → ["4",[a4,a5]] // and a3 is never returned. That breaks the entire contract. // // So the cursor is now a POSITION IN A STABLE KEY-DERIVED ORDER, not a position in a list: // each key gets a fixed 32-bit value from its own name, and the cursor is the next such value // to resume from. A key's position therefore never moves when a DIFFERENT key is added or // removed, which is precisely what makes the guarantee hold. This mirrors what real Redis // does (its cursor is a reverse-binary index into hash buckets, and a key's bucket is derived // from the key too) while staying reproducible, which the real one is not. const all = visibleKeys(space) .filter((k) => typeFilter === null || space.get(k)!.kind === typeFilter) .map((k) => ({ k, c: scanCursorFor(k) })) .sort((l, r) => (l.c - r.c) || (l.k < r.k ? -1 : l.k > r.k ? 1 : 0)); const from = all.filter((e) => e.c >= cursor); let take = from.slice(0, Math.max(1, count)); // Never split a group of keys sharing a cursor value across pages: the resume point is a // cursor VALUE, so a key left behind in a half-emitted group could never be reached again. if (take.length > 0 && take.length < from.length) { const lastC = take[take.length - 1]!.c; take = from.filter((e) => e.c <= lastC); } const remaining = from.length - take.length; const next = remaining === 0 ? 0 : take[take.length - 1]!.c + 1; return [String(next), take.map((e) => e.k).filter((k) => match === null || globMatch(match, k))]; } // ── generic keyspace ───────────────────────────────────────────────────────────────────── case 'EXISTS': case 'TOUCH': { let n = 0; for (const k of a) if (space.get(k)) n++; return n; } case 'DEL': case 'UNLINK': { let n = 0; for (const k of a) if (space.get(k)) { space.remove(k, 'key.del'); n++; } return n; } case 'EXPIRE': case 'PEXPIRE': case 'EXPIREAT': case 'PEXPIREAT': { const row = space.get(a[0]!); const n = integerArgument(a[1]!); // Redis 7.0's options (redis.io/docs/latest/commands/expire/, "Options"): NX sets only a key with no expiry, XX // only one with an expiry, GT only a later deadline, LT only an earlier one, a key with no expiry counting as // one that never expires; NX with any other, and GT with LT, are refused const opts = new Set(a.slice(2).map((o) => { const u = o.toUpperCase(); if (!['NX', 'XX', 'GT', 'LT'].includes(u)) throw new RedisCommandError(`ERR Unsupported option ${o}`); return u; })); if (opts.has('NX') && (opts.has('XX') || opts.has('GT') || opts.has('LT'))) throw new RedisCommandError('ERR NX and XX, GT or LT options at the same time are not compatible'); if (opts.has('GT') && opts.has('LT')) throw new RedisCommandError('ERR GT and LT options at the same time are not compatible'); // source: https://raw.githubusercontent.com/redis/redis/c9d29f6a918c335bc1778d9f68e521c1bbb36a0f/src/expire.c "overflow by either unit conversion or basetime addition." const millis = name === 'EXPIRE' || name === 'EXPIREAT' ? n * 1000n : n; const deadline = name === 'EXPIRE' || name === 'PEXPIRE' ? BigInt(Math.trunc(nowMs)) + millis : millis; if (millis < -9223372036854775808n || millis > 9223372036854775807n || deadline > 9223372036854775807n) throw new RedisCommandError(`ERR invalid expire time in '${name.toLowerCase()}' command`); if (!row) return 0; if (opts.has('NX') && row.pexpireAt !== null) return 0; if (opts.has('XX') && row.pexpireAt === null) return 0; if (opts.has('GT') && (row.pexpireAt === null || deadline <= BigInt(row.pexpireAt))) return 0; if (opts.has('LT') && row.pexpireAt !== null && deadline >= BigInt(row.pexpireAt)) return 0; // A deadline already in the past DELETES the key, exactly as Redis does. if (deadline <= BigInt(nowMs)) { space.remove(a[0]!, 'key.expire_now'); return 1; } space.put({ ...row, pexpireAt: String(deadline) }, 'key.expire'); return 1; } case 'TTL': case 'PTTL': { const row = space.get(a[0]!); if (!row) return -2; if (row.pexpireAt === null) return -1; const remainingMs = BigInt(row.pexpireAt) - BigInt(nowMs); // Redis computes `(ttl+500)/1000` in integer arithmetic — round HALF-UP, not ceil. With ceil, // a key set `EX 10` and read 600ms later still reported 10 where the vendor says 9 (§9 round // 1); every earlier verify happened to land on an exact second boundary, where they agree. return integerReply(name === 'TTL' ? (remainingMs + 500n) / 1000n : remainingMs); } case 'PERSIST': { const row = space.get(a[0]!); if (!row || row.pexpireAt === null) return 0; space.put({ ...row, pexpireAt: null }, 'key.persist'); return 1; } // source: https://redis.io/docs/latest/commands/expire/ "the associated time to live is transferred to the new key name" case 'RENAME': case 'RENAMENX': { const row = space.get(a[0]!); if (!row) throw new RedisCommandError(NO_SUCH_KEY); if (a[0] === a[1]) return name === 'RENAME' ? OK : 0; if (name === 'RENAMENX' && space.get(a[1]!)) return 0; space.put({ ...row, name: a[1]! }, 'key.rename'); space.remove(a[0]!, 'key.rename_src'); return name === 'RENAME' ? OK : 1; } // ── strings ────────────────────────────────────────────────────────────────────────────── case 'GET': { const v = asString(space.get(a[0]!)); return v === undefined ? null : v; } case 'GETDEL': { const row = space.get(a[0]!); const v = asString(row); if (row) space.remove(a[0]!, 'string.getdel'); return v === undefined ? null : v; } // source: https://redis.io/docs/latest/commands/getset/ "Any previous time to live associated with the key is discarded" case 'GETSET': { const old = asString(space.get(a[0]!)); space.put({ name: a[0]!, kind: 'string', v: a[1]!, pexpireAt: null }, 'string.getset'); return old === undefined ? null : old; } case 'GETEX': { const row = space.get(a[0]!); const v = asString(row); if (!row) return null; if (a.length === 1) return v ?? null; const tok = a[1]!.toLowerCase(); if (tok === 'persist') { space.put({ ...row, pexpireAt: null }, 'string.getex'); return v ?? null; } if (!['ex', 'px', 'exat', 'pxat'].includes(tok) || a.length < 3) throw new RedisCommandError(SYNTAX); space.put({ ...row, pexpireAt: ttlFromToken(tok, a[2]!, nowMs, 'getex') }, 'string.getex'); return v ?? null; } case 'SET': { const [key, value] = [a[0]!, a[1]!]; let nx = false; let xx = false; let get = false; let keepTtl = false; let expiryFlag: string | null = null; let pexpireAt: string | null = null; for (let i = 2; i < a.length; i++) { // Case-INSENSITIVE by necessity: the official SDK emits the TTL/flag tokens lowercase and // pushes `keepTtl` in literal camelCase (`pkg/commands/set.ts`), which the real server // accepts. A case-sensitive parser here would reject the vendor's own client. const tok = a[i]!.toLowerCase(); if (tok === 'nx') { nx = true; continue; } if (tok === 'xx') { xx = true; continue; } if (tok === 'get') { get = true; continue; } if (tok === 'keepttl') { if (expiryFlag !== null && expiryFlag !== 'keepttl') throw new RedisCommandError(SYNTAX); keepTtl = true; expiryFlag = 'keepttl'; continue; } if (['ex', 'px', 'exat', 'pxat'].includes(tok)) { // t_string.c parseExtendedStringArgumentsOrReply: EX, PX, EXAT, PXAT and KEEPTTL exclude each other; the same // one repeated is taken again (the last value wins) if (i + 1 >= a.length || (expiryFlag !== null && expiryFlag !== tok)) throw new RedisCommandError(SYNTAX); expiryFlag = tok; pexpireAt = ttlFromToken(tok, a[++i]!, nowMs, 'set'); continue; } throw new RedisCommandError(SYNTAX); } if (nx && xx) throw new RedisCommandError(SYNTAX); const existing = space.get(key); if (get && existing && existing.kind !== 'string') throw new RedisCommandError(WRONGTYPE); const old = existing?.kind === 'string' ? (existing.v as string) : undefined; // THE `null` RETURN THAT MATTERS: a failed NX/XX answers nil, NOT "OK". dub branches on // `res === null` in a dozen lock/dedupe paths (lib/upstash/redis-lock.ts, track-lead.ts, // track-sale.ts, …), so getting this wrong turns every distributed lock into a no-op. if (nx && existing) return get ? (old ?? null) : null; if (xx && !existing) return get ? (old ?? null) : null; // source: https://redis.io/docs/latest/commands/set/ "Retain the time to live associated with the key" space.put({ name: key, kind: 'string', v: value, pexpireAt: keepTtl ? (existing?.pexpireAt ?? null) : pexpireAt }, 'string.set'); return get ? (old ?? null) : OK; } case 'SETNX': { if (space.get(a[0]!)) return 0; space.put({ name: a[0]!, kind: 'string', v: a[1]!, pexpireAt: null }, 'string.setnx'); return 1; } case 'SETEX': case 'PSETEX': { const pexpireAt = ttlFromToken(name === 'SETEX' ? 'ex' : 'px', a[1]!, nowMs, name.toLowerCase()); space.put({ name: a[0]!, kind: 'string', v: a[2]!, pexpireAt }, 'string.setex'); return OK; } case 'MGET': return a.map((k) => { const r = space.get(k); return r && r.kind === 'string' ? (r.v as string) : null; }); case 'MSET': case 'MSETNX': { if (a.length % 2 !== 0) throw new RedisCommandError(wrongArity(name)); if (name === 'MSETNX') { for (let i = 0; i < a.length; i += 2) if (space.get(a[i]!)) return 0; } for (let i = 0; i < a.length; i += 2) space.put({ name: a[i]!, kind: 'string', v: a[i + 1]!, pexpireAt: null }, 'string.mset'); return name === 'MSET' ? OK : 1; } case 'APPEND': { const row = space.get(a[0]!); const next = (asString(row) ?? '') + a[1]!; space.put({ name: a[0]!, kind: 'string', v: next, pexpireAt: row?.pexpireAt ?? null }, 'string.append'); return next.length; } case 'STRLEN': return (asString(space.get(a[0]!)) ?? '').length; case 'INCR': case 'DECR': case 'INCRBY': case 'DECRBY': { const by = name === 'INCR' ? 1n : name === 'DECR' ? -1n : integerArgument(a[1]!) * (name === 'DECRBY' ? -1n : 1n); const row = space.get(a[0]!); const current = asString(row); const next = (current === undefined ? 0n : integerArgument(current)) + by; if (next < -9223372036854775808n || next > 9223372036854775807n) throw new RedisCommandError('ERR increment or decrement would overflow'); // INCR PRESERVES the key's TTL (real Redis semantics). This is exactly what makes // @upstash/ratelimit's fixed-window script correct: the PEXPIRE is armed on the first // increment and every later INCRBY must leave it alone, or the window would never close. space.put({ name: a[0]!, kind: 'string', v: String(next), pexpireAt: row?.pexpireAt ?? null }, 'string.incr'); return integerReply(next); } case 'INCRBYFLOAT': { const row = space.get(a[0]!); const current = asString(row); const text = fmtScore(guardFloatResult((current === undefined ? 0 : toFloat(current)) + toFloat(a[1]!))); space.put({ name: a[0]!, kind: 'string', v: text, pexpireAt: row?.pexpireAt ?? null }, 'string.incrbyfloat'); return text; } // ── hashes ─────────────────────────────────────────────────────────────────────────────── case 'HSET': case 'HMSET': { if ((a.length - 1) % 2 !== 0) throw new RedisCommandError(wrongArity(name)); const row = space.get(a[0]!); const pairs = asHash(row); let added = 0; for (let i = 1; i < a.length; i += 2) { const idx = pairs.findIndex(([f]) => f === a[i]); if (idx < 0) { pairs.push([a[i]!, a[i + 1]!]); added++; } else pairs[idx] = [a[i]!, a[i + 1]!]; } space.put({ name: a[0]!, kind: 'hash', v: pairs, pexpireAt: row?.pexpireAt ?? null }, 'hash.set'); return name === 'HMSET' ? OK : added; } case 'HSETNX': { const row = space.get(a[0]!); const pairs = asHash(row); if (pairs.some(([f]) => f === a[1])) return 0; pairs.push([a[1]!, a[2]!]); space.put({ name: a[0]!, kind: 'hash', v: pairs, pexpireAt: row?.pexpireAt ?? null }, 'hash.setnx'); return 1; } case 'HGET': { const p = asHash(space.get(a[0]!)).find(([f]) => f === a[1]); return p ? p[1] : null; } case 'HMGET': { const pairs = asHash(space.get(a[0]!)); return a.slice(1).map((f) => pairs.find(([k]) => k === f)?.[1] ?? null); } case 'HGETALL': return asHash(space.get(a[0]!)).flat(); case 'HKEYS': return asHash(space.get(a[0]!)).map(([f]) => f); case 'HVALS': return asHash(space.get(a[0]!)).map(([, v]) => v); case 'HLEN': return asHash(space.get(a[0]!)).length; case 'HEXISTS': return asHash(space.get(a[0]!)).some(([f]) => f === a[1]) ? 1 : 0; case 'HDEL': { const row = space.get(a[0]!); const pairs = asHash(row); const doomed = a.slice(1); const kept = pairs.filter(([f]) => !doomed.includes(f)); if (row) { if (kept.length === 0) space.remove(a[0]!, 'hash.del_empty'); // Redis drops an emptied key else space.put({ ...row, kind: 'hash', v: kept }, 'hash.del'); } return pairs.length - kept.length; } case 'HINCRBY': case 'HINCRBYFLOAT': { const isFloat = name === 'HINCRBYFLOAT'; const row = space.get(a[0]!); const pairs = asHash(row); const idx = pairs.findIndex(([f]) => f === a[1]); const current = idx < 0 ? undefined : pairs[idx]![1]; const by = isFloat ? toFloat(a[2]!) : integerArgument(a[2]!); const base = current === undefined ? (isFloat ? 0 : 0n) : isFloat ? toFloat(current) : integerArgument(current, 'ERR hash value is not an integer'); const next = isFloat ? guardFloatResult((base as number) + (by as number)) : (base as bigint) + (by as bigint); if (!isFloat && ((next as bigint) < -9223372036854775808n || (next as bigint) > 9223372036854775807n)) throw new RedisCommandError('ERR increment or decrement would overflow'); const text = isFloat ? fmtScore(next as number) : String(next); if (idx < 0) pairs.push([a[1]!, text]); else pairs[idx] = [a[1]!, text]; space.put({ name: a[0]!, kind: 'hash', v: pairs, pexpireAt: row?.pexpireAt ?? null }, 'hash.incrby'); return isFloat ? text : integerReply(next as bigint); } // ── sets ───────────────────────────────────────────────────────────────────────────────── case 'SADD': { const row = space.get(a[0]!); const members = asSet(row); let added = 0; for (const m of a.slice(1)) if (!members.includes(m)) { members.push(m); added++; } space.put({ name: a[0]!, kind: 'set', v: members, pexpireAt: row?.pexpireAt ?? null }, 'set.add'); return added; } case 'SREM': { const row = space.get(a[0]!); const members = asSet(row); const doomed = a.slice(1); const kept = members.filter((m) => !doomed.includes(m)); if (row) { if (kept.length === 0) space.remove(a[0]!, 'set.rem_empty'); else space.put({ ...row, kind: 'set', v: kept }, 'set.rem'); } return members.length - kept.length; } case 'SMEMBERS': return asSet(space.get(a[0]!)); case 'SCARD': return asSet(space.get(a[0]!)).length; case 'SISMEMBER': return asSet(space.get(a[0]!)).includes(a[1]!) ? 1 : 0; case 'SMISMEMBER': { const members = asSet(space.get(a[0]!)); return a.slice(1).map((m) => (members.includes(m) ? 1 : 0)); } case 'SRANDMEMBER': case 'SPOP': { const row = space.get(a[0]!); const members = asSet(row); const count = a.length >= 2 ? toInt(a[1]!) : null; // SPOP's count must be positive; SRANDMEMBER's may be negative, and then "the command is allowed to return the // same element multiple times", |count| of them (redis.io/docs/latest/commands/srandmember/) if (name === 'SPOP' && count !== null && count < 0) throw new RedisCommandError('ERR value is out of range, must be positive'); if (name === 'SRANDMEMBER' && count !== null && count < 0) return members.length === 0 ? [] : Array.from({ length: -count }, (_, i) => members[i % members.length]!); // DETERMINISTIC: takes from the FRONT of insertion order rather than at random, for the same // reason RANDOMKEY does. Disclosed (`upstash.sets.spop_deterministic`). const taken = members.slice(0, count === null ? 1 : Math.max(0, count)); if (name === 'SPOP' && taken.length > 0) { const kept = members.slice(taken.length); if (kept.length === 0) space.remove(a[0]!, 'set.pop_empty'); else space.put({ ...row!, kind: 'set', v: kept }, 'set.pop'); } return count === null ? (taken[0] ?? null) : taken; } // ── lists ──────────────────────────────────────────────────────────────────────────────── case 'LPUSH': case 'RPUSH': { const row = space.get(a[0]!); const items = asList(row); // LPUSH inserts each element at the head IN TURN, so `LPUSH k a b` leaves [b, a]. if (name === 'LPUSH') for (const v of a.slice(1)) items.unshift(v); else items.push(...a.slice(1)); space.put({ name: a[0]!, kind: 'list', v: items, pexpireAt: row?.pexpireAt ?? null }, 'list.push'); return items.length; } case 'LPOP': case 'RPOP': { const count = a.length >= 2 ? positiveInteger(a[1]!) : null; const row = space.get(a[0]!); const items = asList(row); if (items.length === 0) return null; const n = count === null ? 1 : count; const taken = name === 'LPOP' ? items.splice(0, n) : items.splice(Math.max(0, items.length - n)).reverse(); if (items.length === 0) space.remove(a[0]!, 'list.pop_empty'); else space.put({ ...row!, kind: 'list', v: items }, 'list.pop'); return count === null ? (taken[0] ?? null) : taken; } case 'LLEN': return asList(space.get(a[0]!)).length; case 'LINDEX': { const items = asList(space.get(a[0]!)); const i = toInt(a[1]!); return items[i < 0 ? items.length + i : i] ?? null; } case 'LSET': { const row = space.get(a[0]!); if (!row) throw new RedisCommandError(NO_SUCH_KEY); const items = asList(row); const raw = toInt(a[1]!); const i = raw < 0 ? items.length + raw : raw; if (i < 0 || i >= items.length) throw new RedisCommandError('ERR index out of range'); items[i] = a[2]!; space.put({ ...row, kind: 'list', v: items }, 'list.set'); return OK; } case 'LRANGE': { const items = asList(space.get(a[0]!)); const [start, stop] = normalizeRange(toInt(a[1]!), toInt(a[2]!), items.length); return start > stop ? [] : items.slice(start, stop + 1); } case 'LTRIM': { const row = space.get(a[0]!); const items = asList(row); const [start, stop] = normalizeRange(toInt(a[1]!), toInt(a[2]!), items.length); if (!row) return OK; const kept = start > stop ? [] : items.slice(start, stop + 1); if (kept.length === 0) space.remove(a[0]!, 'list.trim_empty'); else space.put({ ...row, kind: 'list', v: kept }, 'list.trim'); return OK; } case 'LREM': { const row = space.get(a[0]!); const items = asList(row); const count = toInt(a[1]!); const target = a[2]!; const limit = Math.abs(count); const source = count < 0 ? [...items].reverse() : items; const kept: string[] = []; let removed = 0; for (const item of source) { if (item === target && (limit === 0 || removed < limit)) { removed++; continue; } kept.push(item); } const result = count < 0 ? kept.reverse() : kept; if (row) { if (result.length === 0) space.remove(a[0]!, 'list.rem_empty'); else space.put({ ...row, kind: 'list', v: result }, 'list.rem'); } return removed; } // ── sorted sets ────────────────────────────────────────────────────────────────────────── case 'ZADD': return zadd(space, a); case 'ZINCRBY': { const row = space.get(a[0]!); const pairs = asZSet(row); const by = toFloat(a[1]!); const idx = pairs.findIndex(([m]) => m === a[2]); const next = (idx < 0 ? 0 : pairs[idx]![1]) + by; if (Number.isNaN(next)) throw new RedisCommandError('ERR resulting score is not a number (NaN)'); if (idx < 0) pairs.push([a[2]!, next]); else pairs[idx] = [a[2]!, next]; space.put({ name: a[0]!, kind: 'zset', v: storeZSet(sortZSet(pairs)), pexpireAt: row?.pexpireAt ?? null }, 'zset.incrby'); return fmtScore(next); } case 'ZSCORE': { const p = asZSet(space.get(a[0]!)).find(([m]) => m === a[1]); return p ? fmtScore(p[1]) : null; } case 'ZCARD': return asZSet(space.get(a[0]!)).length; case 'ZCOUNT': { const lo = parseScoreBound(a[1]!); const hi = parseScoreBound(a[2]!); return asZSet(space.get(a[0]!)).filter(([, s]) => inScoreRange(s, lo, hi)).length; } case 'ZRANK': case 'ZREVRANK': { const sorted = sortZSet(asZSet(space.get(a[0]!))); const ordered = name === 'ZREVRANK' ? [...sorted].reverse() : sorted; const i = ordered.findIndex(([m]) => m === a[1]); // WITHSCORE (Redis 7.2): the rank and the member's score if (a.length === 3 && a[2]!.toUpperCase() !== 'WITHSCORE') throw new RedisCommandError(SYNTAX); if (a.length === 3) return i < 0 ? null : [i, fmtScore(ordered[i]![1])]; return i < 0 ? null : i; } case 'ZREM': { const row = space.get(a[0]!); const pairs = asZSet(row); const doomed = a.slice(1); const kept = pairs.filter(([m]) => !doomed.includes(m)); if (row) { if (kept.length === 0) space.remove(a[0]!, 'zset.rem_empty'); else space.put({ ...row, kind: 'zset', v: storeZSet(kept) }, 'zset.rem'); } return pairs.length - kept.length; } case 'ZREMRANGEBYSCORE': { const row = space.get(a[0]!); const pairs = asZSet(row); const lo = parseScoreBound(a[1]!); const hi = parseScoreBound(a[2]!); const kept = pairs.filter(([, s]) => !inScoreRange(s, lo, hi)); if (row) { if (kept.length === 0) space.remove(a[0]!, 'zset.remrange_empty'); else space.put({ ...row, kind: 'zset', v: storeZSet(kept) }, 'zset.remrange'); } return pairs.length - kept.length; } case 'ZREMRANGEBYRANK': { const row = space.get(a[0]!); const sorted = sortZSet(asZSet(row)); const [start, stop] = normalizeRange(toInt(a[1]!), toInt(a[2]!), sorted.length); const doomed = start > stop ? [] : sorted.slice(start, stop + 1).map(([m]) => m); const kept = sorted.filter(([m]) => !doomed.includes(m)); if (row) { if (kept.length === 0) space.remove(a[0]!, 'zset.remrank_empty'); else space.put({ ...row, kind: 'zset', v: storeZSet(kept) }, 'zset.remrank'); } return doomed.length; } case 'ZRANGE': case 'ZREVRANGE': case 'ZRANGEBYSCORE': case 'ZREVRANGEBYSCORE': return zrange(space, name, a); // ── streams (dub's lib/upstash/redis-streams client uses exactly these five) ────────────── case 'XADD': return xadd(space, a, nowMs); case 'XLEN': return asStream(space.get(a[0]!)).length; case 'XRANGE': case 'XREVRANGE': { const entries = asStream(space.get(a[0]!)); const _rev = name === 'XREVRANGE'; // XREVRANGE takes its bounds in REVERSE order (`XREVRANGE key + -`). const [startRaw, endRaw] = _rev ? [a[2]!, a[1]!] : [a[1]!, a[2]!]; let count: number | null = null; if (a.length >= 5) { if (a[3]!.toLowerCase() !== 'count') throw new RedisCommandError(SYNTAX); count = toInt(a[4]!); } else if (a.length === 4) throw new RedisCommandError(SYNTAX); const lo = parseStreamBound(startRaw, 'min'); const hi = parseStreamBound(endRaw, 'max'); // a bound prefixed `(` is exclusive (XRANGE: "Exclusive ranges", redis.io/docs/latest/commands/xrange) const loOpen = startRaw.startsWith('('); const hiOpen = endRaw.startsWith('('); let selected = entries.filter(([id]) => { const fromLo = compareStreamIds(id, lo); const toHi = compareStreamIds(id, hi); return (loOpen ? fromLo > 0 : fromLo >= 0) && (hiOpen ? toHi < 0 : toHi <= 0); }); if (_rev) selected = selected.reverse(); if (count !== null) selected = selected.slice(0, Math.max(0, count)); return selected.map(([id, fields]) => [id, fields.flat()] as RedisValue); } case 'XDEL': { const row = space.get(a[0]!); const entries = asStream(row); const doomed = a.slice(1); const kept = entries.filter(([id]) => !doomed.includes(id)); if (row) space.put({ ...row, kind: STREAM, v: kept }, 'stream.del'); return entries.length - kept.length; } // ── scripting ──────────────────────────────────────────────────────────────────────────── case 'SCRIPT': { const sub = a[0]!.toUpperCase(); if (sub === 'LOAD') { if (a.length !== 2) throw new RedisCommandError(wrongArity('script')); redisScript(a[1]!, dialect); return storeScript(space, a[1]!); } if (sub === 'EXISTS') return a.slice(1).map((sha) => (space.hasScript(sha.toLowerCase()) ? 1 : 0)); if (sub === 'FLUSH') { space.flushScripts(); return OK; } throw new RedisCommandError(`ERR Unknown SCRIPT subcommand or wrong number of arguments for '${a[0]}'`); } case 'EVAL': case 'EVAL_RO': case 'EVALSHA': case 'EVALSHA_RO': { // source: https://raw.githubusercontent.com/redis/redis/c9d29f6a918c335bc1778d9f68e521c1bbb36a0f/src/eval.c "Get the number of arguments that are keys" const numKeys = toInt(a[1]!); if (numKeys < 0) throw new RedisCommandError("ERR Number of keys can't be negative"); if (numKeys > a.length - 2) throw new RedisCommandError("ERR Number of keys can't be greater than number of args"); const bySha = name.startsWith('EVALSHA'); let script: string; if (bySha) { const found = space.scriptFor(a[0]!.toLowerCase()); // THE `NOSCRIPT` CONTRACT: @upstash/ratelimit ALWAYS tries EVALSHA first and only falls back // to EVAL when the error text contains "NOSCRIPT" (its `safeEval`, src/hash.ts). Answering // anything else here — above all a fake success — breaks every rate limiter pointed at this // twin, silently. This is the single most load-bearing error string in the pack. if (found === undefined) throw new RedisCommandError(NOSCRIPT); script = found; } else { script = a[0]!; redisScript(script, dialect); // an invalid/unsupported header must not enter the script cache // Caching is a WRITE, so a read-only twin must not attempt it — otherwise `EVAL_RO`, which // is a read by definition, would 405 on the cache rather than on anything it does (§9 // round 1). The cost is that a read-only twin cannot serve a later EVALSHA for this // script, which is the correct read-only outcome rather than a silent write. if (!space.ctx.readOnly) storeScript(space, script); } return evalScript(space, script, a.slice(2, 2 + numKeys), a.slice(2 + numKeys), name.endsWith('_RO')); } default: // Unreachable: `commandShapeError` above already rejected anything not in SERVED_COMMANDS. throw new RedisCommandError(dialect.unknownCommand(argv)); } } /** * A key's fixed position in SCAN's iteration order: the low 31 bits of its own SHA-1. * * Deriving it from the KEY NAME is the whole point — the position is a property of the key, so * adding or deleting any OTHER key cannot move it, and a key present for the whole scan is * therefore returned exactly once. `+1` keeps every value strictly positive so that cursor 0 * unambiguously means "start"/"done" and can never also mean "resume at the first key". */ export function scanCursorFor(key: string): number { return (Number.parseInt(createHash('sha1').update(key).digest('hex').slice(0, 8), 16) >>> 1) + 1; } /** Live key names, with the internal script-cache keys filtered out of the keyspace entirely. */ /** Every live key name. No filtering: the script cache lives in a different subject type entirely, * so there is no internal name for a caller's key to collide with or be hidden by. */ export function visibleKeys(space: KeySpace): string[] { return space.all().map((r) => r.name); } export type ScoreBound = { value: number; exclusive: boolean }; export function parseScoreBound(raw: string): ScoreBound { const exclusive = raw.startsWith('('); return { value: toFloat(exclusive ? raw.slice(1) : raw), exclusive }; } export function inScoreRange(score: number, lo: ScoreBound, hi: ScoreBound): boolean { return (lo.exclusive ? score > lo.value : score >= lo.value) && (hi.exclusive ? score < hi.value : score <= hi.value); } function zadd(space: KeySpace, a: string[]): RedisValue { let nx = false; let xx = false; let gt = false; let lt = false; let ch = false; let incr = false; let i = 1; for (; i < a.length; i++) { const tok = a[i]!.toLowerCase(); if (tok === 'nx') { nx = true; continue; } if (tok === 'xx') { xx = true; continue; } if (tok === 'gt') { gt = true; continue; } if (tok === 'lt') { lt = true; continue; } if (tok === 'ch') { ch = true; continue; } if (tok === 'incr') { incr = true; continue; } break; } if (nx && xx) throw new RedisCommandError('ERR XX and NX options at the same time are not compatible'); if ((nx && (gt || lt)) || (gt && lt)) throw new RedisCommandError('ERR GT, LT, and/or NX options at the same time are not compatible'); const rest = a.slice(i); if (rest.length === 0 || rest.length % 2 !== 0) throw new RedisCommandError(SYNTAX); if (incr && rest.length !== 2) throw new RedisCommandError('ERR INCR option supports a single increment-element pair'); const row = space.get(a[0]!); const pairs = asZSet(row); let added = 0; let changed = 0; let incrResult: number | null = null; for (let j = 0; j < rest.length; j += 2) { const score = toFloat(rest[j]!); const member = rest[j + 1]!; const idx = pairs.findIndex(([m]) => m === member); if (idx < 0) { if (xx) { incrResult = null; continue; } pairs.push([member, score]); added++; changed++; incrResult = score; continue; } if (nx) { incrResult = null; continue; } const current = pairs[idx]![1]; const next = incr ? current + score : score; // Redis refuses a score that computes to NaN (e.g. +inf added to -inf) by name. if (Number.isNaN(next)) throw new RedisCommandError('ERR resulting score is not a number (NaN)'); // A GT/LT that REFUSES the move answers nil under INCR — real Redis marks ZADD_OUT_NOP and // replies null, which is how a caller distinguishes "applied" from "refused" (the same // distinction `SET … NX` relies on). Answering the current score would silently read as success. if ((gt && next <= current) || (lt && next >= current)) { incrResult = null; continue; } if (next !== current) changed++; pairs[idx] = [member, next]; incrResult = next; } // THE HUSK GUARD (§9 round 1): `ZADD missing XX 1 m` adds nothing, and real Redis creates no key // at all. An unconditional write here materialised an EMPTY zset that EXISTS/TYPE/DBSIZE/KEYS all // reported and that made a later LPUSH on the same name raise WRONGTYPE. Only write when there is // something to write, or when the key already existed. if (pairs.length > 0 || row !== undefined) { space.put({ name: a[0]!, kind: 'zset', v: storeZSet(sortZSet(pairs)), pexpireAt: row?.pexpireAt ?? null }, 'zset.add'); } if (incr) return incrResult === null ? null : fmtScore(incrResult); return ch ? changed : added; } export function zrange(space: KeySpace, name: string, a: string[]): RedisValue { let byScore = name === 'ZRANGEBYSCORE' || name === 'ZREVRANGEBYSCORE'; let _rev = name === 'ZREVRANGE' || name === 'ZREVRANGEBYSCORE'; let withScores = false; let limit: { offset: number; count: number } | null = null; for (let i = 3; i < a.length; i++) { const tok = a[i]!.toLowerCase(); if (tok === 'withscores') { withScores = true; continue; } if (tok === 'byscore') { byScore = true; continue; } if (tok === 'rev') { _rev = true; continue; } // Refused BY NAME rather than quietly treated as BYSCORE — a wrong ordering returned as a // success is exactly the fake success this pack forbids. Filed as a todo in the manifest. if (tok === 'bylex') throw new RedisCommandError(space.ctx.dialect.unmodeled('ZRANGE BYLEX')); if (tok === 'limit') { if (i + 2 >= a.length) throw new RedisCommandError(SYNTAX); limit = { offset: toInt(a[++i]!), count: toInt(a[++i]!) }; continue; } throw new RedisCommandError(SYNTAX); } if (limit && !byScore) throw new RedisCommandError('ERR syntax error, LIMIT is only supported in combination with either BYSCORE or BYLEX'); const sorted = sortZSet(asZSet(space.get(a[0]!))); let selected: ZSetPairs; if (byScore) { // The REV byscore forms take (max, min); the forward forms take (min, max). const [loRaw, hiRaw] = _rev ? [a[2]!, a[1]!] : [a[1]!, a[2]!]; const lo = parseScoreBound(loRaw); const hi = parseScoreBound(hiRaw); selected = sorted.filter(([, s]) => inScoreRange(s, lo, hi)); if (_rev) selected = selected.reverse(); if (limit) selected = limit.offset < 0 ? [] : limit.count < 0 ? selected.slice(limit.offset) : selected.slice(limit.offset, limit.offset + limit.count); } else { const ordered = _rev ? [...sorted].reverse() : sorted; const [start, stop] = normalizeRange(toInt(a[1]!), toInt(a[2]!), ordered.length); selected = start > stop ? [] : ordered.slice(start, stop + 1); } return withScores ? selected.flatMap(([m, s]) => [m, fmtScore(s)]) : selected.map(([m]) => m); } // ── streams ──────────────────────────────────────────────────────────────────────────────────── export function compareStreamIds(left: string, right: string): number { const [lms = 0n, lseq = 0n] = left.split('-').map(BigInt); const [rms = 0n, rseq = 0n] = right.split('-').map(BigInt); if (lms !== rms) return lms < rms ? -1 : 1; return lseq === rseq ? 0 : lseq < rseq ? -1 : 1; } export function parseStreamBound(raw: string, side: 'min' | 'max'): string { if (raw === '-') return '0-0'; if (raw === '+') return '18446744073709551615-18446744073709551615'; const bare = raw.startsWith('(') ? raw.slice(1) : raw; if (!/^\d+(-\d+)?$/.test(bare)) throw new RedisCommandError('ERR Invalid stream ID specified as stream command argument'); return bare.includes('-') ? bare : `${bare}-${side === 'min' ? '0' : '18446744073709551615'}`; } // source: https://raw.githubusercontent.com/redis/redis/c9d29f6a918c335bc1778d9f68e521c1bbb36a0f/src/util.c "strtoull() is used instead." // Stream components are uint64; Redis's fallback also accepts a leading plus or zeroes. function streamArgument(raw: string, wildcard = false): string { const at = raw.indexOf('-'); const ms = at < 0 ? raw : raw.slice(0, at), seq = at < 0 ? '0' : raw.slice(at + 1); const part = (v: string): string => String(unsignedArgument(v, 'ERR Invalid stream ID specified as stream command argument')); return `${part(ms)}-${wildcard && seq === '*' ? '*' : part(seq)}`; } // source: https://raw.githubusercontent.com/redis/redis/c9d29f6a918c335bc1778d9f68e521c1bbb36a0f/src/t_stream.c "The LIMIT argument must be >= 0." // MAXLEN/MINID use a strict unsigned threshold; LIMIT is allowed only with approximate trimming. function trimSpec(a: string[], start: number): { strategy: string; threshold: string; limit: number; next: number } { let i = start; const strategy = a[i++]!.toUpperCase(); if (!['MAXLEN', 'MINID'].includes(strategy)) throw new RedisCommandError(SYNTAX); const approximate = a[i] === '~'; if (['~', '='].includes(a[i] ?? '')) i++; if (i >= a.length) throw new RedisCommandError(SYNTAX); let threshold = a[i++]!; if (strategy === 'MAXLEN') { if (commandInteger(threshold) < 0) throw new RedisCommandError('ERR The MAXLEN argument must be >= 0.'); } else threshold = streamArgument(threshold); let limit = Infinity; if (a[i]?.toUpperCase() === 'LIMIT') { if (i + 1 >= a.length) throw new RedisCommandError(SYNTAX); i++; limit = commandInteger(a[i++]!); if (limit < 0) throw new RedisCommandError('ERR The LIMIT argument must be >= 0.'); // source: https://raw.githubusercontent.com/redis/redis/c9d29f6a918c335bc1778d9f68e521c1bbb36a0f/src/t_stream.c "syntax error, LIMIT cannot be used without the special ~ option" if (!approximate) throw new RedisCommandError('ERR syntax error, LIMIT cannot be used without the special ~ option'); if (limit === 0) limit = Infinity; } return { strategy, threshold, limit, next: i }; } function trimEntries(entries: StreamEntries, spec: ReturnType): StreamEntries { const remove = spec.strategy === 'MAXLEN' ? Math.max(0, entries.length - Number(spec.threshold)) : entries.filter(([id]) => compareStreamIds(id, parseStreamBound(spec.threshold, 'min')) < 0).length; return entries.slice(Math.min(remove, spec.limit)); } function xadd(space: KeySpace, a: string[], nowMs: number): RedisValue { let i = 1; let noMkStream = false; let trim: ReturnType | undefined; for (; i < a.length; i++) { const tok = a[i]!.toLowerCase(); if (tok === 'nomkstream') { noMkStream = true; continue; } if (tok === 'maxlen' || tok === 'minid') { if (trim) throw new RedisCommandError('ERR syntax error, MAXLEN and MINID options at the same time are not compatible'); trim = trimSpec(a, i); i = trim.next - 1; continue; } break; } const row = space.get(a[0]!); if (!row && noMkStream) return null; const entries = asStream(row); if (row?.lastId === '18446744073709551615-18446744073709551615') throw new RedisCommandError('ERR The stream has exhausted the last possible ID, unable to add more items'); const rawId = a[i]; if (rawId === undefined) throw new RedisCommandError(wrongArity('xadd')); const fields = a.slice(i + 1); if (fields.length === 0 || fields.length % 2 !== 0) throw new RedisCommandError(wrongArity('xadd')); const idSpec = rawId === '*' ? rawId : streamArgument(rawId, true); let id: string; if (idSpec === '*') { // The id's ms part is the REQUEST CLOCK (`occurredAt`), never `Date.now()`. Two entries added // in the same pinned millisecond get sequence 0, 1, 2 … exactly as Redis does — which is what // makes a stream verify reproducible. const [lastMs = 0n, lastSeq = 0n] = (row?.lastId ?? '0-0').split('-').map(BigInt); id = BigInt(nowMs) > lastMs ? `${nowMs}-0` : `${lastMs}-${lastSeq + 1n}`; } else if (/^(0|[1-9]\d*)-\*$/.test(idSpec) && BigInt(idSpec.split('-')[0]!) <= 18446744073709551615n) { const ms = BigInt(idSpec.split('-')[0]!); const [lastMs = 0n, lastSeq = 0n] = (row?.lastId ?? '0-0').split('-').map(BigInt); if (ms < lastMs) throw new RedisCommandError('ERR The ID specified in XADD is equal or smaller than the target stream top item'); id = `${ms}-${ms === lastMs ? lastSeq + 1n : 0n}`; } else { id = idSpec.includes('-') ? idSpec : `${idSpec}-0`; if (!/^(0|[1-9]\d*)-(0|[1-9]\d*)$/.test(id) || id.split('-').some((v) => BigInt(v) > 18446744073709551615n)) throw new RedisCommandError('ERR Invalid stream ID specified as stream command argument'); // Compare against the RETAINED last-id, not merely the last surviving entry: Redis keeps // `last_id` past an XDEL, so an id that was used and then deleted stays refused forever. §9 // round 1 found the entries-only comparison re-accepting `5-5` after `XDEL st 5-5`. if (id === '0-0') throw new RedisCommandError('ERR The ID specified in XADD must be greater than 0-0'); const top = row?.lastId ?? (entries.length > 0 ? entries[entries.length - 1]![0] : '0-0'); if (compareStreamIds(id, top) <= 0) { throw new RedisCommandError('ERR The ID specified in XADD is equal or smaller than the target stream top item'); } } if (id === '0-0') throw new RedisCommandError('ERR The ID specified in XADD must be greater than 0-0'); if (id.split('-').some((v) => BigInt(v) > 18446744073709551615n)) throw new RedisCommandError('ERR The stream has exhausted the last possible ID, unable to add more items'); const pairs: HashPairs = []; for (let j = 0; j < fields.length; j += 2) pairs.push([fields[j]!, fields[j + 1]!]); entries.push([id, pairs]); space.put({ name: a[0]!, kind: STREAM, v: trim ? trimEntries(entries, trim) : entries, pexpireAt: row?.pexpireAt ?? null, lastId: id }, 'stream.add'); return id; } // ── the script cache ─────────────────────────────────────────────────────────────────────────── // // Real Redis keeps the EVAL script cache in server memory (a restart or `SCRIPT FLUSH` empties it). // This twin persists it in the kernel under its OWN subject type ('script'), so EVALSHA keeps // working across a twin restart. Two things follow, and both are deliberate: // • A DISCLOSED divergence from the vendor — strictly more forgiving, never less — which is what // lets a persistent world's rate limiters survive a restart without a NOSCRIPT round trip. // • ZERO collision surface with the keyspace. An earlier draft stored scripts as keys under a // magic ` twin:script:` prefix and filtered that prefix out of KEYS/SCAN/DBSIZE; a caller // who wrote a key with that exact name (perfectly legal — Redis keys may begin with a space) // had it silently disappear from every listing and could then execute it via EVALSHA. Separate // subject types make that impossible instead of merely filtered. function storeScript(space: KeySpace, script: string): string { const sha = luaScriptSha1(script); if (!space.hasScript(sha)) space.putScript(sha, script); return sha; } // ── Lua ↔ Redis value conversion (real Redis's rules — see the Lua module header) ───────────── function redisToLua(v: RedisValue): LuaValue { if (v === null) return false; // nil bulk reply → Lua `false` if (typeof v === 'number' || typeof v === 'string') return v; if (v instanceof RedisInteger) return Number(v.integer); if (v instanceof RedisStatus) { const t = new LuaTable(); t.set('ok', v.value); // status reply → Lua table {ok=…} return t; } return LuaTable.fromArray(v.map(redisToLua)); } function luaToRedis(v: LuaValue): RedisValue { if (v === null || v === false || v === LUA_NULL) return null; if (v === true) return 1; // Lua `true` → integer 1 if (typeof v === 'number') return Math.trunc(v); // Lua number → integer, TRUNCATED toward zero if (typeof v === 'string') return v; if (v instanceof LuaTable) { const err = v.get('err'); if (typeof err === 'string') throw new RedisCommandError(err); const ok = v.get('ok'); if (typeof ok === 'string') return new RedisStatus(ok); const out: RedisValue[] = []; for (let i = 1; ; i++) { const item = v.get(i); if (item === null) break; // an array reply STOPS at the first nil out.push(luaToRedis(item)); } return out; } throw new RedisCommandError('ERR twin: script returned a function value, which has no Redis representation'); } /** * Run a Lua script over this twin's real command core, ATOMICALLY. * * `redis.call` re-enters `execOne` on the SAME `KeySpace`, so a script's writes are visible to its * own later reads — which every @upstash/ratelimit script depends on — and there is no second, * script-only implementation of `INCRBY` to drift from the real one. A script that raises part-way * is rolled back to the snapshot taken before it started, which is what "a script is one indivisible * unit" means. */ function evalScript(space: KeySpace, script: string, keys: string[], args: string[], readOnly: boolean): RedisValue { const before = space.snapshot(); try { const { body, flags } = redisScript(script, space.ctx.dialect); const guards = [...flags].filter(flag => flag !== 'no-writes') .map(flag => space.ctx.dialect.scriptFlags![flag]!(keys, space.ctx.transaction === true)); const result = runLua(body, { keys, argv: args, call: (callArgs, line) => { const cmd = String(callArgs[0] ?? '').toUpperCase(); // Redis's refusal, as EVAL_RO's page prints it (redis.io/docs/latest/commands/eval_ro/): the script by its SHA1 // and the line of the call if ((readOnly || flags.has('no-writes')) && isWriteCommand(cmd, callArgs.slice(1), space.ctx.dialect)) throw new RedisCommandError(`ERR Error running script (call to ${luaScriptSha1(script)}): @user_script:${line}: @user_script: ${line}: Write commands are not allowed from read-only scripts.`); const shape = commandShapeError(callArgs, space.ctx.dialect); if (shape !== null) throw new RedisCommandError(shape); for (const guard of guards) guard(callArgs); return redisToLua(execOne(space, callArgs)); }, ...space.ctx.dialect.lua, }); return luaToRedis(result); } catch (e) { if (!space.ctx.dialect.scriptErrorsKeepWrites) space.restore(before); // atomicity: a failed script leaves NOTHING behind if (e instanceof RedisCommandError || e instanceof ReadOnlyError) throw e; if (e instanceof LuaError) throw new RedisCommandError(`ERR Error running script: ${e.message}`); throw e; } } // ───────────────────────────────────────────────────────────────────────────────────────────── // THE RUN // ───────────────────────────────────────────────────────────────────────────────────────────── export type RunItem = { result: RedisValue } | { error: string }; /** * Execute a whole request's worth of commands against one root, then flush. * * Each element comes back as `{result}` or `{error}` — the exact per-command envelope Upstash's * `/pipeline` and `/multi-exec` endpoints return and the SDK's `Pipeline.exec` destructures. * * RUNTIME ERRORS DO NOT ABORT — not in a pipeline and (LIVE-PROBED, contrary to the intuition that * a "transaction" rolls back) NOT in `/multi-exec` either: Upstash's own docs say "all commands * will be executed. Upstash Redis will not stop the processing of commands. This is to provide same * semantics with Redis when there are errors inside a transaction." A probe of the real service * confirmed a `SET` after a failing `INCR` in a `/multi-exec` batch is applied. Structural faults — * an unavailable command or a bad arity — are QUEUE-time and DO discard the whole batch, but the * caller (`upstash-twin.ts`) rejects those before this function is ever reached. */ export async function execRedisRun(commands: string[][], ctx: RedisContext): Promise<{ items: RunItem[]; wrote: boolean; instant: number; touched: string[] }> { const nowMs = Date.parse(ctx.occurredAt); if (!Number.isFinite(nowMs)) throw new RedisCommandError(`ERR twin: unparseable occurredAt '${ctx.occurredAt}'`); // The phases a served command's time is counted in (service-times.ts): the image, the commands, their writes. const space = times.timed('image', () => new KeySpace(ctx, nowMs)); const items: RunItem[] = []; const began = times.now(); try { for (const argv of commands) { try { items.push({ result: execOne(space, argv) }); } catch (e) { if (e instanceof ReadOnlyError) throw e; // surfaces as HTTP 405 for the whole request if (e instanceof RedisCommandError) { items.push({ error: e.message }); continue; } throw e; } } } finally { times.add('execute', times.now() - began); } const wrote = space.dirty; // The keys this run wrote, by name, read before the flush clears them: a stream wakes only the clients blocked on one. const touched = space.touchedNames(); const flushing = times.now(); try { await (space.ctx.dialect.storage?.flush(space) ?? flushKeySpace(space)); } finally { times.add('flush', times.now() - flushing); } return { items, wrote, instant: nowMs, touched }; }