From 052c9481f30d98e34ed995e73acb78681511c141 Mon Sep 17 00:00:00 2001 From: Marc Gravell Date: Thu, 3 Dec 2026 14:18:49 +0000 Subject: [PATCH 1/5] design: generated scripts and functions (exploratory) A shape for declaring server-side code as partial methods: binding by name, shared call shape, per-kind provisioning; facts checked against Redis 8.12. --- design/generated-scripts-and-functions.md | 308 ++++++++++++++++++++++ 1 file changed, 308 insertions(+) create mode 100644 design/generated-scripts-and-functions.md diff --git a/design/generated-scripts-and-functions.md b/design/generated-scripts-and-functions.md new file mode 100644 index 000000000..b3f6ff102 --- /dev/null +++ b/design/generated-scripts-and-functions.md @@ -0,0 +1,308 @@ +# Generated server-side code: scripts and functions + +**Exploratory notes: ideas, not decisions.** Nothing here is agreed or committed to. It sets out a shape, +the facts it rests on (checked against a real server where marked), and the questions still open. No code +yet; a spike would follow once the shape is agreed. + +The idea comes from the discussion on #3364. Rather than give callers lower-level knobs for scripts (a +caller-built request frame, a caller-held hash), let them *declare* a server-side operation as a C# +method, and have a source generator write the other half: + +```csharp +[RedisScript(""" + local i = tonumber(@count) + local res + math.randomseed(tonumber(@seed)) + while (i > 0) do + res = redis.call('LPUSH', @key, math.random()) + i = i-1 + end + return res + """)] +public static partial ValueTask RandomPushAsync(this SomeContext ctx, + RedisKey key, int count, int seed, CancellationToken cancellationToken = default); +``` + +The caller never sees `EVAL`, `EVALSHA`, `SCRIPT LOAD`, `NOSCRIPT`, `KEYS[n]` or `ARGV[n]`, and the +generated code can do things a hand-written call can't, such as hashing at build time. + +--- + +## 1. Goals and non-goals + +**Goals** + +- One declaration gives a strongly-typed method that is correct by construction: argument order, key/arg + split, `numkeys`, routing, read-only command choice and reply parsing are all derived, not hand-written. +- Parameters bound **by name**, checked at build time: an unknown or unused name is a build error. +- The send path does no more work than a hand-written `EVALSHA`: no argument arrays, hash computed at build + time, no per-call allocation beyond what the frame itself needs. +- Keys always go through the same path as every other command (`AppendFormatted(RedisKey)`), so the + key prefix, cluster slot and **client-side-cache key marks** are right automatically. That last one is + the reason not to allow caller-built frames (see #3364): a frame whose key marks are wrong doesn't fail, + it silently leaves stale cache entries. +- **The same declaration model for every kind of server-side code.** Scripts and functions differ only in + how the code gets onto the server and what the call is named; the binding and calling half should be + shared, so that anything else of the same shape later (see §9) is a new provisioning strategy, not a + new feature. + +**Non-goals** + +- Parsing or validating Lua beyond what binding needs (§4). The server compiles it; we report its errors. +- Replacing the string-based `Scripts.EvaluateAsync`. That stays for dynamic scripts. +- Managing server-side code outside the generated methods (a "functions admin" API is a separate topic). + +## 2. Two halves: the call, and provisioning + +Every variant has the same **call shape**: + +> a named callable · its keys (which route the command) · its other arguments · whether it is read-only +> · how to read the reply + +What differs is **provisioning**, i.e. how the code comes to exist on the server, and what the call command +is: + +| | Provisioned by | Called by | Missing on the server | Persistence | +|---|---|---|---|---| +| Script | `SCRIPT LOAD ` (or `EVAL `) | `EVALSHA numkeys keys... args...` / `EVALSHA_RO` | `NOSCRIPT ...` | none: lost on restart, `SCRIPT FLUSH` | +| Function | `FUNCTION LOAD [REPLACE] ` | `FCALL numkeys keys... args...` / `FCALL_RO` | `ERR Function not found` | persisted (AOF), replicated to replicas, **not** propagated across cluster shards | + +So the generator should be two layers: + +1. **Binding** (shared): read the method signature, bind parameters to keys/args by name, rewrite the body, + pick the reply handler, emit the method body that renders ` numkeys keys... args...`. +2. **Provisioning** (per kind): what `` and `` are, what the provisioning payload is, and how a + "missing" error is recognised and repaired. + +Function libraries already name their engine in the payload (`#!lua name=mylib`); the server docs say only +that "currently, `` must be `lua`". So the provisioning layer is keyed by kind and engine, not +hard-wired to Lua. + +## 3. Declaration + +```csharp +// a script: provisioned by its body, called by its hash +[RedisScript("", ReadOnly = true)] +public static partial ValueTask CountAsync(this SomeContext ctx, RedisKey key, CancellationToken cancellationToken = default); + +// a function: provisioned by its library, called by its name +[RedisFunction("mylib", "", Flags = RedisFunctionFlags.NoWrites)] +public static partial ValueTask CountFnAsync(this SomeContext ctx, RedisKey key, CancellationToken cancellationToken = default); +``` + +- **The target type is specific, not generic** (`SomeContext`, not ` where T : IRespKeyspaceTarget`): an + `IRespKeyspaceTarget`, or something convertible to one. The aim is for the method to show up in one + chosen place, not on every target. +- **`ValueTask` / `ValueTask`**, matching the rest of the v4 surface. Sync callers use the existing + blocking-context mechanism rather than a generated twin. +- **`CancellationToken` is optional on the generated public method**, following the public surface's + convention, but always passed through internally. +- **Read-only** is a named argument on the attribute (`ReadOnly = true` for scripts; `NoWrites` among the + function flags), not `System.ComponentModel.ReadOnlyAttribute`, which is about designers and property + grids. It selects `EVALSHA_RO` / `FCALL_RO`, and the read-only retry category, exactly as + `Scripts.EvaluateReadOnlyAsync` does today (including the command-map fallback in `ForReadOnlyScript`). + +## 4. Binding by name + +**`@name` in the body refers to the parameter `name`.** `@` is not a token in Lua, so outside string literals +and comments an `@identifier` can't be anything else. The generator needs a minimal lexer, not a parser: it must +skip + +- short strings `'...'` and `"..."`, with backslash escapes; +- long strings `[[...]]`, `[==[...]==]` (any level); +- comments `--...` and long comments `--[[...]]` / `--[==[...]==]`. + +Everything else is copied through; `@name` is rewritten. The rewrite is done at build time, so the hash of the +rewritten body is a compile-time constant. + +**Which parameters are keys.** A `RedisKey` parameter is a key: it goes into `KEYS`, routes the command and is +marked for cache invalidation. Everything else is an argument. A parameter of another type that is really a key +(`string`, `byte[]`) is marked with an attribute, for example `[RedisKey] string name`, and converted. + +**Rewrite target.** For a fixed parameter list the positions are constants: the *i*-th key is `KEYS[i]` and the +*j*-th argument is `ARGV[j]`, so `@key` becomes `KEYS[1]`, and so on. + +**Variable-length lists**, which is the main thing that keeps this from being "simple scripts only": allow at most +one key list (`ReadOnlySpan` / `RedisKey[]`) and one argument list, each **after** the fixed parameters of +its kind. Fixed positions then stay constant, and the list starts at a known offset. In the body, `@keys` (a list) +would need to be a Lua value, not an index expression, so the generator adds a prologue line, +`local __keys = { unpack(KEYS, 2) }` (`table.unpack` vs `unpack`: the server's Lua is 5.1, so `unpack`), and +rewrites `@keys` to `__keys`. Fixed parameters don't need a prologue. Open: whether list parameters should allow +`params`. + +**Diagnostics** (build errors unless noted): + +| Case | Example | +|---|---| +| `@name` with no such parameter | `@cuont` | +| parameter never referenced | `int seed` with no `@seed`, which is an error because it almost always means a typo | +| more than one key list, or a list before a fixed parameter of the same kind | | +| unterminated string or long bracket | the lexer can't tell code from text, so it refuses rather than guesses | +| `[RedisKey]` on a type that can't be a key | | +| body is not a constant | the attribute argument must be a compile-time string | +| a script that references `KEYS`/`ARGV` directly *and* uses `@names` (warning) | mixing makes the positions the reader sees wrong | + +**Functions use the same body text.** A function's callback receives its keys and arguments as parameters, and +`KEYS`/`ARGV` are not available as globals in functions. But naming the callback's parameters `KEYS` and `ARGV` +makes the same body text work unchanged: + +```lua +#!lua name=mylib +redis.register_function{function_name='count', callback=function(KEYS, ARGV) end, flags={'no-writes'}} +``` + +Checked against Redis 8.12: a callback declared `function(KEYS, ARGV)` sees `KEYS[1]`, `ARGV[1]`, `#KEYS` and +`#ARGV` as expected. So binding and rewriting are identical for both kinds; only the wrapping differs. + +## 5. What the generator emits + +For each method: + +- a **static descriptor** holding what is constant: the rewritten body or library payload, the call id (the SHA1 + hex for a script, the function name for a function), the read-only flag, and a lazily-rendered provisioning + frame (the cached `SCRIPT LOAD` frame, much as `RespScriptCache` holds one today); +- the **method body**: build ` numkeys`, append each key with `AppendFormatted(RedisKey)` and each + argument with the matching `AppendFormatted` overload, then hand the frame and descriptor to a runtime entry + point that sends it. + +```csharp +public static partial ValueTask RandomPushAsync(this SomeContext ctx, RedisKey key, int count, int seed, CancellationToken cancellationToken) +{ + var context = ctx.Context; + var frame = __RandomPush.Begin(context, keyCount: 1, argCount: 2); // EVALSHA 1 + frame.AppendFormatted(key); + frame.AppendFormatted(count); + frame.AppendFormatted(seed); + return __RandomPush.SendAsync(context, ref frame, RespHandlers.Int64, cancellationToken); +} +``` + +No argument arrays at any point. That depends on the repair being able to work from the rendered frame rather +than from the caller's arguments, which is what #3398 does for `Scripts.EvaluateAsync`: on `NOSCRIPT`, the +`EVAL` is re-rendered from the arguments of the `EVALSHA` frame already sent. The same mechanism serves generated +calls, so the generated method never captures its parameters. + +**The runtime entry point is new public API**, because generated code lives in the consumer's assembly. +Something like a public `RespScript` / `RespFunction` descriptor type plus a send method on `RespScripts`, taking +the descriptor and a builder. It needs to be usable by hand too, rather than `EditorBrowsable(Never)` scaffolding, +and it is the main API-review surface of this work. It reuses what exists internally: the per-endpoint +`ScriptLoadGate`, the preamble pairing, `ForReadOnlyScript`, and the frame-based repair. + +**Reply type to handler**, by `T` in `ValueTask`: + +| `T` | Handler | +|---|---| +| (none, `ValueTask`) | `RespHandlers.Success` | +| `long`, `long?` | `Int64`, `NullableInt64` | +| `double` | `Double` | +| `bool` | `Boolean` | +| `string?` | `String` | +| `RedisValue` | `Value` | +| `RespResult` | `Result` (the caller reads it, and owns disposal) | +| `RedisResult` | the internal `RedisResultHandler`, which would need exposing; or don't support it | + +Anything else is a build error that lists the supported types, unless and until there's a way to name a +user-supplied `IRespHandler` on the attribute. + +## 6. Provisioning: scripts + +As today, with the hash now known at build time: + +- First call per endpoint: `SCRIPT LOAD` paired ahead of `EVALSHA`. After that, the endpoint's belief + (`IsScriptLoaded`, reset when the server's `RunId` changes) skips it. +- `NOSCRIPT` (flush, restart, failover to a node that never saw the load): the belief is dropped and the call is + re-sent as `EVAL ` built from the sent frame (#3398). +- Inside a transaction or batch, the body is sent as `EVAL`, exactly as now, because a paired preamble would + shift the `EXEC` results. +- `CommandFlags.NoScriptCache`, or a command map without `SCRIPT`, means `EVAL` every time. + +## 7. Provisioning: functions + +Facts (from the server docs, and checked against Redis 8.12 where marked): + +- `FUNCTION LOAD [REPLACE] `; the payload starts `#!lua name=`. A library is loaded and replaced + **as a whole**: selective updates of its functions aren't allowed. +- Loading a library that already exists without `REPLACE` fails: `ERR Library 'probe' already exists` (8.12). +- **Function names are global across libraries**: loading a second library that defines an existing name fails, + even with `REPLACE`, with `ERR Function probe_get already exists` (8.12). +- Calling a function that isn't loaded: `ERR Function not found` (8.12). This is a plain `ERR`, so it needs + recognising by message, and a new `RedisErrorKind` (say `FunctionNotFound`) if we want to classify it. +- `FCALL_RO` on a function without `no-writes`: `ERR Can not execute a script with write flag using *_ro + command.` (8.12). +- Functions are persisted (AOF) and replicated to replicas, but **not propagated across cluster shards**: each + primary needs its own load. +- Redis 7.0 or later. + +**Grouping.** Every `[RedisFunction]` in a compilation with the same library name is generated into **one** +library payload, since that's the unit the server loads. Each method contributes one `register_function` +entry. Diagnostics: two methods with the same function name; a library split across inconsistent attributes. + +**Flags.** A `[Flags] enum RedisFunctionFlags { None, NoWrites, AllowOom, AllowStale, NoCluster, AllowCrossSlotKeys }`, +mapped to the server's flag names. `NoWrites` also selects `FCALL_RO`. + +**Loading strategy.** Lazy, like scripts: send `FCALL`, and on `ERR Function not found`, load the library on +the node that answered, then retry. The difference from scripts: a function call can't be repaired by sending the +body inline (there's no `EVAL` equivalent), so the repair is load-then-retry, two round trips, once per primary. + +- Cluster: the call already went to the right shard's primary, so loading there is exactly the per-shard load + the docs ask for. +- `FCALL_RO` served by a **replica**: a replica can't take `FUNCTION LOAD`. The load has to go to its primary and + replicate down, so the retry may race replication. Options: retry the call against the primary; or wait for + replication (`WAIT`); or treat "not found on a replica" as "go to the primary this once". Open. +- A per-endpoint belief, as for scripts, so a known-loaded library skips nothing at all (there's no preamble to + skip; the belief only matters for deciding whether a "not found" is surprising). +- An explicit, eager "provision now" entry point (load on every primary) is worth having for deployment + scripts, but isn't the default. + +**Versioning: the hard part.** Functions persist and are shared by every client of the server, so two +deployed versions of an application can disagree about a library's contents. + +- *Replace in place* (`FUNCTION LOAD REPLACE`, library and function names as declared): simple, and the names are + readable in `FUNCTION LIST`. But during a rolling deploy, old and new instances keep replacing each other's + library, and an old instance can call a new function with old arguments. +- *Content-addressed* (library and function names suffixed with a short hash of the library payload, such as + `mylib_3f2a9c1e` and `count_3f2a9c1e`): versions coexist safely, and the generated code only ever calls its + own. But every version persists until somebody deletes it, and `FUNCTION LIST` fills up. +- Possibly both, chosen on the attribute (`Versioning = Replace | ContentHash`), with content hash as the default + and an explicit cleanup call that deletes `mylib_*` libraries other than the current one, opt-in only, since + it is a destructive server-wide operation. + +This needs a decision before any code. + +**Transactions.** `FCALL` inside `MULTI` works if the function exists; the load-and-retry repair can't run inside +a transaction (the same constraint that makes scripts send `EVAL` there). So inside a transaction a missing +function is an error, unless the library is provisioned first. Document it, or have the transaction pre-check. + +## 8. Lexer and rewriting: where it lives + +The generator already ships to consumers (`eng/StackExchange.Redis.Build` is packed into `analyzers/dotnet/cs`), +and `RespFragmentGenerator` is the precedent for a consumer-facing generator that emits code against public +protocol types. The Lua lexer is small and self-contained, so it belongs in that project with its own unit tests +(strings, long brackets of every level, comments, `@` inside each, unterminated forms). + +## 9. Further engines + +Keeping provisioning separate from binding (§2) means another engine of the same shape ("load named code, call +it by name with keys and arguments") is a new provisioning strategy plus whatever the payload header needs. The +binding, keys, routing, reply handling and generated method shape stay as they are. That's the main argument +for doing the split now, while there are two cases to generalise from, rather than adding a second case to code +written for one. + +## 10. Open questions + +1. Versioning for functions: replace, content-hash, or both (§7)? +2. Read-only function calls served by replicas: how to provision (§7)? +3. The public runtime surface (§5): shape and naming of the descriptor types and the send method. Should + `RespScript` also be a supported way to call a script by hand? +4. Variable-length lists (§4): is one key list plus one argument list enough? `params`? +5. `RedisResult` as a supported reply type, or `RespResult` only? +6. Unused parameter as error vs warning. +7. Should `Scripts.EvaluateAsync(string, ...)` move onto the same descriptor internally, so there is one path? + +## 11. Suggested spike order + +1. The Lua lexer and `@name` rewrite, with tests. No runtime dependency, and it settles §4. +2. The runtime descriptor and send path for scripts, reusing the existing gate and #3398's repair, called by hand. +3. The generator for `[RedisScript]`, against step 2. +4. Functions: descriptor, `FunctionNotFound` classification, load-and-retry, grouping into libraries. After §7's + versioning decision. From 9720e894a58a08eea8ab1d427656bce1fb907fbc Mon Sep 17 00:00:00 2001 From: Marc Gravell Date: Thu, 3 Dec 2026 14:23:24 +0000 Subject: [PATCH 2/5] design: functions are opaque names; administration on IServer, not in the pipeline --- design/generated-scripts-and-functions.md | 187 +++++++++++----------- 1 file changed, 94 insertions(+), 93 deletions(-) diff --git a/design/generated-scripts-and-functions.md b/design/generated-scripts-and-functions.md index b3f6ff102..4aecd8cae 100644 --- a/design/generated-scripts-and-functions.md +++ b/design/generated-scripts-and-functions.md @@ -34,7 +34,7 @@ generated code can do things a hand-written call can't, such as hashing at build - One declaration gives a strongly-typed method that is correct by construction: argument order, key/arg split, `numkeys`, routing, read-only command choice and reply parsing are all derived, not hand-written. -- Parameters bound **by name**, checked at build time: an unknown or unused name is a build error. +- Script parameters bound **by name**, checked at build time: an unknown or unused name is a build error. - The send path does no more work than a hand-written `EVALSHA`: no argument arrays, hash computed at build time, no per-call allocation beyond what the frame itself needs. - Keys always go through the same path as every other command (`AppendFormatted(RedisKey)`), so the @@ -43,7 +43,7 @@ generated code can do things a hand-written call can't, such as hashing at build it silently leaves stale cache entries. - **The same declaration model for every kind of server-side code.** Scripts and functions differ only in how the code gets onto the server and what the call is named; the binding and calling half should be - shared, so that anything else of the same shape later (see §9) is a new provisioning strategy, not a + shared, so that anything else of the same shape later (see §9) is a new kind, not a new feature. **Non-goals** @@ -59,24 +59,25 @@ Every variant has the same **call shape**: > a named callable · its keys (which route the command) · its other arguments · whether it is read-only > · how to read the reply -What differs is **provisioning**, i.e. how the code comes to exist on the server, and what the call command -is: +What differs is **who provisions the code**, and what the call command is: | | Provisioned by | Called by | Missing on the server | Persistence | |---|---|---|---|---| -| Script | `SCRIPT LOAD ` (or `EVAL `) | `EVALSHA numkeys keys... args...` / `EVALSHA_RO` | `NOSCRIPT ...` | none: lost on restart, `SCRIPT FLUSH` | -| Function | `FUNCTION LOAD [REPLACE] ` | `FCALL numkeys keys... args...` / `FCALL_RO` | `ERR Function not found` | persisted (AOF), replicated to replicas, **not** propagated across cluster shards | +| Script | **the client**, on demand: `SCRIPT LOAD ` (or `EVAL `) | `EVALSHA numkeys keys... args...` / `EVALSHA_RO` | `NOSCRIPT ...`, repaired by the client | none: lost on restart, `SCRIPT FLUSH` | +| Function | **whoever deploys the server**: `FUNCTION LOAD`, outside the execution pipeline | `FCALL numkeys keys... args...` / `FCALL_RO` | `ERR Function not found`, reported, not repaired | persisted (AOF), replicated to replicas, **not** propagated across cluster shards | -So the generator should be two layers: +So the generator has two layers: -1. **Binding** (shared): read the method signature, bind parameters to keys/args by name, rewrite the body, - pick the reply handler, emit the method body that renders ` numkeys keys... args...`. -2. **Provisioning** (per kind): what `` and `` are, what the provisioning payload is, and how a - "missing" error is recognised and repaired. +1. **Binding** (shared): read the method signature, bind parameters to keys and arguments, pick the reply + handler, and emit the method body that renders ` numkeys keys... args...`. +2. **Kind** (per kind): what `` and `` are, and what happens when the server doesn't have the code. + For a script the client can always repair that, because it holds the body. For a function it can't and + shouldn't (§7), so the function is an **opaque name**. -Function libraries already name their engine in the payload (`#!lua name=mylib`); the server docs say only -that "currently, `` must be `lua`". So the provisioning layer is keyed by kind and engine, not -hard-wired to Lua. +That makes "an opaque named callable with keys and arguments" the general case, and scripts the one kind the +client also provisions. Anything else of the same shape (function libraries already name their engine, +`#!lua name=mylib`, and the server docs say only that "currently, `` must be `lua`") is a new kind +at most, and needs nothing from the binding layer. ## 3. Declaration @@ -85,9 +86,9 @@ hard-wired to Lua. [RedisScript("", ReadOnly = true)] public static partial ValueTask CountAsync(this SomeContext ctx, RedisKey key, CancellationToken cancellationToken = default); -// a function: provisioned by its library, called by its name -[RedisFunction("mylib", "", Flags = RedisFunctionFlags.NoWrites)] -public static partial ValueTask CountFnAsync(this SomeContext ctx, RedisKey key, CancellationToken cancellationToken = default); +// a function: an opaque name, deployed by someone else; no body +[RedisFunction("count", ReadOnly = true)] +public static partial ValueTask CountFnAsync(this SomeContext ctx, RedisKey key, long max, CancellationToken cancellationToken = default); ``` - **The target type is specific, not generic** (`SomeContext`, not ` where T : IRespKeyspaceTarget`): an @@ -97,14 +98,21 @@ public static partial ValueTask CountFnAsync(this SomeContext ctx, RedisKe blocking-context mechanism rather than a generated twin. - **`CancellationToken` is optional on the generated public method**, following the public surface's convention, but always passed through internally. -- **Read-only** is a named argument on the attribute (`ReadOnly = true` for scripts; `NoWrites` among the - function flags), not `System.ComponentModel.ReadOnlyAttribute`, which is about designers and property - grids. It selects `EVALSHA_RO` / `FCALL_RO`, and the read-only retry category, exactly as - `Scripts.EvaluateReadOnlyAsync` does today (including the command-map fallback in `ForReadOnlyScript`). +- **Read-only** is a named argument on the attribute (`ReadOnly = true`), not + `System.ComponentModel.ReadOnlyAttribute`, which is about designers and property grids. It selects + `EVALSHA_RO` / `FCALL_RO` and the read-only retry category, exactly as `Scripts.EvaluateReadOnlyAsync` does + today (including the command-map fallback in `ForReadOnlyScript`). For a function it is a promise the server + checks: `FCALL_RO` against a function deployed without `no-writes` fails with an explicit error (§7), so a wrong + promise is caught, not acted on. -## 4. Binding by name +## 4. Binding -**`@name` in the body refers to the parameter `name`.** `@` is not a token in Lua, so outside string literals +**Functions bind positionally**, because there's no body to name things in: the `RedisKey` (or `[RedisKey]`) +parameters, in declaration order, are the keys; the rest, in order, are the arguments. Nothing at build time can +check that against the deployed function; a mismatch shows up when it runs, as with any stored-procedure client. +The variable-length list rules below apply to functions too. Everything else in this section is about scripts. + +**For scripts, `@name` in the body refers to the parameter `name`.** `@` is not a token in Lua, so outside string literals and comments an `@identifier` can't be anything else. The generator needs a minimal lexer, not a parser: it must skip @@ -142,25 +150,18 @@ rewrites `@keys` to `__keys`. Fixed parameters don't need a prologue. Open: whet | body is not a constant | the attribute argument must be a compile-time string | | a script that references `KEYS`/`ARGV` directly *and* uses `@names` (warning) | mixing makes the positions the reader sees wrong | -**Functions use the same body text.** A function's callback receives its keys and arguments as parameters, and -`KEYS`/`ARGV` are not available as globals in functions. But naming the callback's parameters `KEYS` and `ARGV` -makes the same body text work unchanged: - -```lua -#!lua name=mylib -redis.register_function{function_name='count', callback=function(KEYS, ARGV) end, flags={'no-writes'}} -``` - -Checked against Redis 8.12: a callback declared `function(KEYS, ARGV)` sees `KEYS[1]`, `ARGV[1]`, `#KEYS` and -`#ARGV` as expected. So binding and rewriting are identical for both kinds; only the wrapping differs. +An aside, in case generating function libraries is ever wanted as tooling (§7): a function's callback +receives its keys and arguments as parameters, and `KEYS`/`ARGV` are not available as globals in functions, but +declaring the callback as `function(KEYS, ARGV)` lets a script body run unchanged as a function. Checked against +Redis 8.12: such a callback sees `KEYS[1]`, `ARGV[1]`, `#KEYS` and `#ARGV` as expected. ## 5. What the generator emits For each method: -- a **static descriptor** holding what is constant: the rewritten body or library payload, the call id (the SHA1 - hex for a script, the function name for a function), the read-only flag, and a lazily-rendered provisioning - frame (the cached `SCRIPT LOAD` frame, much as `RespScriptCache` holds one today); +- a **static descriptor** holding what is constant: the call id (the SHA1 hex for a script, the function name + for a function) and the read-only flag; and, for a script only, the rewritten body and a lazily-rendered + `SCRIPT LOAD` frame (much as `RespScriptCache` holds one today); - the **method body**: build ` numkeys`, append each key with `AppendFormatted(RedisKey)` and each argument with the matching `AppendFormatted` overload, then hand the frame and descriptor to a runtime entry point that sends it. @@ -216,9 +217,45 @@ As today, with the hash now known at build time: shift the `EXEC` results. - `CommandFlags.NoScriptCache`, or a command map without `SCRIPT`, means `EVAL` every time. -## 7. Provisioning: functions +## 7. Functions: called, not provisioned + +**The execution pipeline never loads a function.** A function is an opaque name: the generated method sends +`FCALL` / `FCALL_RO`, and if the server doesn't have it, that's reported, not repaired. Deploying functions is +for whoever runs the server. + +Why: + +- **Functions are deployment artefacts, not client state.** They persist, replicate, and are shared by every + client of the server. The server docs already treat loading as an operational step: `redis-cli --cluster call + ... FUNCTION LOAD` across primaries, `--functions-rdb` for fresh nodes. It's the stored-procedure model: the + application calls procedures; it doesn't deploy them. +- **Application credentials often can't load them.** `FUNCTION LOAD` is an administrative command that a + locked-down ACL denies to application users, so a client-side loader would fail exactly where it matters. +- **Client-owned loading has no good answer to versioning.** Libraries are replaced as a whole and function + names are global, so two deployed versions of an application would either fight over `FUNCTION LOAD REPLACE` + during a rolling deploy, or need content-hashed names that persist until someone deletes them. A read-only call + served by a replica can't be repaired at all (a replica can't take a load), and neither can a call inside + `MULTI`. + +**What the client does:** + +- recognise `ERR Function not found` (a plain `ERR`, so by message) as a new `RedisErrorKind`, say + `FunctionNotFound`, with a message that says the function has to be deployed, rather than the server's bare + text; +- send `FCALL_RO` for a read-only declaration and let the server enforce `no-writes`. + +**Administration goes on `IServer`**, outside the execution pipeline and alongside `ScriptLoad` / `ScriptFlush`, +behind the same admin-mode guard: `FUNCTION LOAD [REPLACE]`, `DELETE`, `LIST`, `FLUSH`, `DUMP` / `RESTORE`, +`STATS`, `KILL`. Each is a single server's operation, by design (functions don't propagate across shards, and +`IServer` is per node), so deploying to a cluster is a loop over primaries in the caller's code, explicitly. +This also settles the `FUNCTION *` rows in `docs/CommandCoverage.md`, currently deferred pending exactly this +design (tracked from #2055). + +**Maybe, later: emitting a library from declarations.** If a declaration did carry a body, the generator could +emit the library payload (using the `function(KEYS, ARGV)` wrapping from §4) as a constant or file for an admin +to deploy. Tooling only, never loaded at runtime. Parked. -Facts (from the server docs, and checked against Redis 8.12 where marked): +Server facts this rests on (from the server docs, and checked against Redis 8.12 where marked): - `FUNCTION LOAD [REPLACE] `; the payload starts `#!lua name=`. A library is loaded and replaced **as a whole**: selective updates of its functions aren't allowed. @@ -233,45 +270,8 @@ Facts (from the server docs, and checked against Redis 8.12 where marked): primary needs its own load. - Redis 7.0 or later. -**Grouping.** Every `[RedisFunction]` in a compilation with the same library name is generated into **one** -library payload, since that's the unit the server loads. Each method contributes one `register_function` -entry. Diagnostics: two methods with the same function name; a library split across inconsistent attributes. - -**Flags.** A `[Flags] enum RedisFunctionFlags { None, NoWrites, AllowOom, AllowStale, NoCluster, AllowCrossSlotKeys }`, -mapped to the server's flag names. `NoWrites` also selects `FCALL_RO`. - -**Loading strategy.** Lazy, like scripts: send `FCALL`, and on `ERR Function not found`, load the library on -the node that answered, then retry. The difference from scripts: a function call can't be repaired by sending the -body inline (there's no `EVAL` equivalent), so the repair is load-then-retry, two round trips, once per primary. - -- Cluster: the call already went to the right shard's primary, so loading there is exactly the per-shard load - the docs ask for. -- `FCALL_RO` served by a **replica**: a replica can't take `FUNCTION LOAD`. The load has to go to its primary and - replicate down, so the retry may race replication. Options: retry the call against the primary; or wait for - replication (`WAIT`); or treat "not found on a replica" as "go to the primary this once". Open. -- A per-endpoint belief, as for scripts, so a known-loaded library skips nothing at all (there's no preamble to - skip; the belief only matters for deciding whether a "not found" is surprising). -- An explicit, eager "provision now" entry point (load on every primary) is worth having for deployment - scripts, but isn't the default. - -**Versioning: the hard part.** Functions persist and are shared by every client of the server, so two -deployed versions of an application can disagree about a library's contents. - -- *Replace in place* (`FUNCTION LOAD REPLACE`, library and function names as declared): simple, and the names are - readable in `FUNCTION LIST`. But during a rolling deploy, old and new instances keep replacing each other's - library, and an old instance can call a new function with old arguments. -- *Content-addressed* (library and function names suffixed with a short hash of the library payload, such as - `mylib_3f2a9c1e` and `count_3f2a9c1e`): versions coexist safely, and the generated code only ever calls its - own. But every version persists until somebody deletes it, and `FUNCTION LIST` fills up. -- Possibly both, chosen on the attribute (`Versioning = Replace | ContentHash`), with content hash as the default - and an explicit cleanup call that deletes `mylib_*` libraries other than the current one, opt-in only, since - it is a destructive server-wide operation. - -This needs a decision before any code. - -**Transactions.** `FCALL` inside `MULTI` works if the function exists; the load-and-retry repair can't run inside -a transaction (the same constraint that makes scripts send `EVAL` there). So inside a transaction a missing -function is an error, unless the library is provisioned first. Document it, or have the transaction pre-check. +**Transactions.** `FCALL` inside `MULTI` is just another command; with no repair to run, there is nothing that +can't happen inside a transaction (unlike scripts, which send `EVAL` there for that reason). ## 8. Lexer and rewriting: where it lives @@ -282,27 +282,28 @@ protocol types. The Lua lexer is small and self-contained, so it belongs in that ## 9. Further engines -Keeping provisioning separate from binding (§2) means another engine of the same shape ("load named code, call -it by name with keys and arguments") is a new provisioning strategy plus whatever the payload header needs. The -binding, keys, routing, reply handling and generated method shape stay as they are. That's the main argument -for doing the split now, while there are two cases to generalise from, rather than adding a second case to code -written for one. +Separating binding from the kind (§2), with functions as opaque names, means other server-side code of the same +shape ("call named code with keys and arguments") needs at most a new kind: the binding, keys, routing, reply +handling and generated method stay as they are. That's the main argument for doing the split now, while there +are two cases to generalise from, rather than adding a second case to code written for one. ## 10. Open questions -1. Versioning for functions: replace, content-hash, or both (§7)? -2. Read-only function calls served by replicas: how to provision (§7)? -3. The public runtime surface (§5): shape and naming of the descriptor types and the send method. Should - `RespScript` also be a supported way to call a script by hand? -4. Variable-length lists (§4): is one key list plus one argument list enough? `params`? -5. `RedisResult` as a supported reply type, or `RespResult` only? -6. Unused parameter as error vs warning. -7. Should `Scripts.EvaluateAsync(string, ...)` move onto the same descriptor internally, so there is one path? +1. The public runtime surface (§5): shape and naming of the descriptor types and the send method. Should + `RespScript` also be a supported way to call a script by hand, and is there a hand-callable `FCALL` too? +2. Variable-length lists (§4): is one key list plus one argument list enough? `params`? +3. `RedisResult` as a supported reply type, or `RespResult` only? +4. Unused script parameter as error vs warning. +5. Should `Scripts.EvaluateAsync(string, ...)` move onto the same descriptor internally, so there is one path? +6. The `IServer` function-administration surface (§7): method names and return shapes (`FUNCTION LIST` and + `STATS` replies want types of their own), and the v4 context-surface equivalent. ## 11. Suggested spike order 1. The Lua lexer and `@name` rewrite, with tests. No runtime dependency, and it settles §4. 2. The runtime descriptor and send path for scripts, reusing the existing gate and #3398's repair, called by hand. 3. The generator for `[RedisScript]`, against step 2. -4. Functions: descriptor, `FunctionNotFound` classification, load-and-retry, grouping into libraries. After §7's - versioning decision. +4. `[RedisFunction]`: positional binding, `FCALL` / `FCALL_RO`, `FunctionNotFound` classification. Small once 1–3 + exist. +5. Independently of 1–4: the `IServer` function-administration commands, as ordinary commands (the + `implement-resp-command` skill), and the coverage-ledger update. From 76cc9207d8eabcb3509e9095a39f12d35be62fc1 Mon Sep 17 00:00:00 2001 From: Marc Gravell Date: Thu, 3 Dec 2026 14:33:27 +0000 Subject: [PATCH 3/5] design: lists of keys and arguments, and how a script sees them --- design/generated-scripts-and-functions.md | 85 ++++++++++++++++++++--- 1 file changed, 76 insertions(+), 9 deletions(-) diff --git a/design/generated-scripts-and-functions.md b/design/generated-scripts-and-functions.md index 4aecd8cae..bd7499def 100644 --- a/design/generated-scripts-and-functions.md +++ b/design/generated-scripts-and-functions.md @@ -130,13 +130,77 @@ marked for cache invalidation. Everything else is an argument. A parameter of an **Rewrite target.** For a fixed parameter list the positions are constants: the *i*-th key is `KEYS[i]` and the *j*-th argument is `ARGV[j]`, so `@key` becomes `KEYS[1]`, and so on. -**Variable-length lists**, which is the main thing that keeps this from being "simple scripts only": allow at most -one key list (`ReadOnlySpan` / `RedisKey[]`) and one argument list, each **after** the fixed parameters of -its kind. Fixed positions then stay constant, and the list starts at a known offset. In the body, `@keys` (a list) -would need to be a Lua value, not an index expression, so the generator adds a prologue line, -`local __keys = { unpack(KEYS, 2) }` (`table.unpack` vs `unpack`: the server's Lua is 5.1, so `unpack`), and -rewrites `@keys` to `__keys`. Fixed parameters don't need a prologue. Open: whether list parameters should allow -`params`. +### Lists + +Without lists this really is "simple scripts only": batch reads, multi-key checks, and "apply these N values" +all need them. + +**On the C# side**, a list parameter is anything with a count known before rendering: `ReadOnlySpan`, `T[]`, +`IReadOnlyList` / `IReadOnlyCollection`. The count is needed up front for `numkeys` and the frame header. +A bare `IEnumerable` is not accepted (a diagnostic says to materialise it), because enumerating twice or +buffering silently are both wrong defaults. **Spans work even though the method returns a `ValueTask`**, +because the generated method isn't `async`: it renders the frame synchronously and returns the send's task. That +only holds because nothing captures the arguments for later; the `NOSCRIPT` repair works from the sent frame +(#3398), not from the parameters. + +- `ReadOnlySpan` (or a `[RedisKey]`-marked list of `string` / `byte[]`) contributes keys: each element is + appended with `AppendFormatted(RedisKey)`, so every one is prefixed, slot-folded and marked for cache invalidation. + In a cluster they must all hash to one slot, as for any multi-key command; the existing routing reports a + cross-slot request before it is sent. +- Any other element type contributes arguments, each formatted as a scalar parameter of that type would be. +- **Pair types flatten**: `ReadOnlySpan`, `ReadOnlySpan`, or a span of a 2-tuple each + contribute two arguments per element, in declaration order (name then value, element then score). The script + sees a flat list. +- An empty list is fine: zero elements, and `numkeys` counts only what was sent. A script with no keys at all + routes to any primary (or any node, when read-only), as `EVAL` does today. + +**On the Lua side**, the problem is that `KEYS` and `ARGV` are flat. A list has to become something the body can +iterate, without the body knowing where it starts. `@items` for a list parameter rewrites to a local table, built +in a generated prologue: + +```lua +-- generated prologue, ahead of the user's body +local __items = {} +for __i = 3, #ARGV do __items[#__items + 1] = ARGV[__i] end +-- the body then reads naturally +for _, v in ipairs(@items) do ... end -- @items is rewritten to __items +local n = #@items +``` + +A loop, not `{ unpack(ARGV, 3) }`. `unpack` pushes every element onto the Lua stack, and on Redis 8.12 +`return #{unpack(ARGV, 2)}` fails with `too many results to unpack` somewhere between 100 and 8,000 elements, +where the loop copied 49,999 elements without complaint (checked). The prologue is part of the rewritten body, so +it is in the hash; it costs a copy proportional to the list, in a script that is about to touch every element +anyway. + +**Where each list starts** is the real design question. Two layouts: + +1. **One list per kind, after that kind's fixed parameters.** Every fixed position stays a compile-time constant, + and the list's start is too: with keys `a, b` then a key list, the list is `KEYS[3..#KEYS]`. Nothing is added + to the command. `KEYS` and `ARGV` hold exactly what the method declared, which is also what `MONITOR` and the + slow log show. +2. **Any number of lists, in any order.** The generator adds each list's length as a hidden leading argument + (`ARGV[1]` = length of the first list, and so on), and the prologue slices with them. All fixed positions are + still constants, just shifted by the number of hidden counts. It costs one small argument per list, and makes + `ARGV` include values the caller didn't write. + +Suggestion: **layout 1 whenever it fits, layout 2 only when the declaration needs it.** The common case (one list, +or one of each kind) pays nothing and stays readable on the wire; a declaration with two key lists, or a list ahead +of a fixed parameter, gets the counts automatically. The generator knows which applies from the signature alone, +so it is never a runtime decision. + +**Not proposed: encoding a list into one argument** (`cjson.encode` on our side, `cjson.decode(@items)` in the +script). It can't work for keys, which have to be real keys to route and to be invalidated, and for arguments it +adds an encoding step for no gain over the flat form. A caller who wants structured data can pass a JSON string +explicitly. + +**Functions** get the flattening but no prologue and no hidden counts, because the body isn't ours: lists are +appended in declaration order, and the deployed function has to know how to split them. More than one list of the +same kind is a warning on a function declaration (the callee can't tell where one ends), unless the method also +declares the lengths as ordinary parameters itself. + +`params` on the last list parameter: probably yes, for `params ReadOnlySpan` (C# 13), since it reads well at +call sites (`SumAsync(key, 1, 2, 3)`). Open. **Diagnostics** (build errors unless noted): @@ -144,7 +208,8 @@ rewrites `@keys` to `__keys`. Fixed parameters don't need a prologue. Open: whet |---|---| | `@name` with no such parameter | `@cuont` | | parameter never referenced | `int seed` with no `@seed`, which is an error because it almost always means a typo | -| more than one key list, or a list before a fixed parameter of the same kind | | +| a list parameter of a type without a known count | `IEnumerable`: materialise it first | +| more than one list of the same kind on a **function** (warning) | the callee can't split them | | unterminated string or long bracket | the lexer can't tell code from text, so it refuses rather than guesses | | `[RedisKey]` on a type that can't be a key | | | body is not a constant | the attribute argument must be a compile-time string | @@ -291,7 +356,9 @@ are two cases to generalise from, rather than adding a second case to code writt 1. The public runtime surface (§5): shape and naming of the descriptor types and the send method. Should `RespScript` also be a supported way to call a script by hand, and is there a hand-callable `FCALL` too? -2. Variable-length lists (§4): is one key list plus one argument list enough? `params`? +2. Lists (§4): layout 1 by default with hidden counts only when needed, or always one layout? `params`? Should + the prologue variable be exposed under the parameter's own name (`local items`), so the body could use `items` + without the `@`? 3. `RedisResult` as a supported reply type, or `RespResult` only? 4. Unused script parameter as error vs warning. 5. Should `Scripts.EvaluateAsync(string, ...)` move onto the same descriptor internally, so there is one path? From 6a865c93ebd353b1f75f08c97820529e7d12cc75 Mon Sep 17 00:00:00 2001 From: Marc Gravell Date: Thu, 3 Dec 2026 14:51:09 +0000 Subject: [PATCH 4/5] design: the general case - declared commands, after the marc/respite RespCommandGenerator --- design/generated-scripts-and-functions.md | 96 ++++++++++++++++++++--- 1 file changed, 84 insertions(+), 12 deletions(-) diff --git a/design/generated-scripts-and-functions.md b/design/generated-scripts-and-functions.md index bd7499def..d5431ddfe 100644 --- a/design/generated-scripts-and-functions.md +++ b/design/generated-scripts-and-functions.md @@ -43,7 +43,7 @@ generated code can do things a hand-written call can't, such as hashing at build it silently leaves stale cache entries. - **The same declaration model for every kind of server-side code.** Scripts and functions differ only in how the code gets onto the server and what the call is named; the binding and calling half should be - shared, so that anything else of the same shape later (see §9) is a new kind, not a + shared, so that anything else of the same shape later (see §10) is a new kind, not a new feature. **Non-goals** @@ -345,14 +345,82 @@ and `RespFragmentGenerator` is the precedent for a consumer-facing generator tha protocol types. The Lua lexer is small and self-contained, so it belongs in that project with its own unit tests (strings, long brackets of every level, comments, `@` inside each, unterminated forms). -## 9. Further engines +## 9. The general case: declared commands + +The `marc/respite` branch (the v3 spike that became v4) had a general generator for **every** command, not just +scripts: `eng/StackExchange.Redis.Build/RespCommandGenerator.cs` (about 1,400 lines), driving about 260 declarations in +`src/RESPite.StackExchange.Redis`. The declaration model: + +```csharp +[RespCommand] +public static partial RespOperation HDel(this in HashCommands context, RedisKey key, RedisValue[] fields); + +[RespCommand(Parser = "ExpireResultParser.Default")] +private static partial RespOperation HExpire(this in HashCommands context, + RedisKey key, long seconds, + [RespIgnore(ExpireWhen.Always)] ExpireWhen when, // omitted from the command when it has this value + [RespPrefix("FIELDS"), RespPrefix] RedisValue[] fields); // "FIELDS", then the count, then the fields +``` + +- the command name comes from the method name, or from `[RespCommand("NAME")]`; +- a `RedisKey` parameter (or `[RespKey]`) is a key; everything else is an argument; +- `[RespPrefix("TOKEN")]` writes a literal ahead of a parameter, and `[RespPrefix]` with no token writes a + collection's **count**: exactly the `numkeys` / `FIELDS n` shape; +- `[RespIgnore(value)]` drops a parameter, and its prefixes, when it has that value; null and empty collections + are always dropped. So optional clauses are declared, not branched; +- `Parser =` names the reply parser, and `Formatter =` is an escape hatch for shapes the attributes can't express. + +What it emitted: one formatter per distinct parameter shape (shared across methods with the same shape), which +computes the argument count as constants plus each optional or collection parameter's contribution, writes literals +and parameters in order, and honours the command map. + +**This is the same binding layer this note needs (§2, §4), already worked out for the general case.** A function +call is just a declared command: + +```csharp +// what [RedisFunction("count")] would mean, spelled as a declared command +[RespCommand("FCALL")] +partial ValueTask CountAsync(this SomeContext ctx, + [RespPrefix("count"), RespPrefix] ReadOnlySpan keys, long max); +``` + +`EVALSHA` is the same shape, plus the script-only provisioning and repair (§6). So the suggestion is to **build +one generator for declared commands, and make `[RedisScript]` and `[RedisFunction]` specialisations of it**: the +function attribute supplies the command and the leading literal; the script attribute adds the body, the +`@name` rewrite and the provisioning. Lists (§4), key handling, reply handlers and the generated method shape are +then defined once. + +**For external callers** this is the bigger prize. Today an ad-hoc or module command is `Execute(string, ...)` +returning `RedisResult`, or a hand-written call through the interpolated builder (`docs/Execute.md`). A public +`[RespCommand]` gives a third option: declare the command once, as a typed method, and get correct framing, key +handling (prefix, slot, cache invalidation marks), command-map handling and typed replies without touching the +protocol. That covers module commands as well as functions, and it targets the same public builder the library +itself uses. + +**What to bring over, and what not to:** + +- *Bring:* the declaration model and its attributes (renamed to fit v4), the shared-formatter idea, the + count/optional/literal rules and their diagnostics. +- *Retarget:* emit calls through v4's `RespRequestBuilder` (the interpolated writer that replaced the spike's manual + `RespWriter`), returning `ValueTask` with `IRespHandler` handlers, rather than `RespOperation` and + parsers. The retry category and cache flags already follow from the command, as they do for hand-written + methods. +- *Reconsider:* the spike's attributes are `[Conditional("DEBUG")]`, which suited a library generating its own + code. For consumers they need to be ordinary public attributes, part of the API review. +- *Don't* mass-convert v4's hand-written group methods. They are already one-liners through the builder + (`$"{RedisCommand.HDEL}{key}{fields}"`), they carry documentation and edge cases (empty-list short-circuits, + command-map fallbacks, version gates), and they are tested. The generator earns its place on new commands with + option-heavy shapes, where hand-written counting is where mistakes happen, and on everything external. + Converting a sample of the existing methods is still worth doing as a test of the model's coverage. + +## 10. Further engines Separating binding from the kind (§2), with functions as opaque names, means other server-side code of the same shape ("call named code with keys and arguments") needs at most a new kind: the binding, keys, routing, reply handling and generated method stay as they are. That's the main argument for doing the split now, while there are two cases to generalise from, rather than adding a second case to code written for one. -## 10. Open questions +## 11. Open questions 1. The public runtime surface (§5): shape and naming of the descriptor types and the send method. Should `RespScript` also be a supported way to call a script by hand, and is there a hand-callable `FCALL` too? @@ -364,13 +432,17 @@ are two cases to generalise from, rather than adding a second case to code writt 5. Should `Scripts.EvaluateAsync(string, ...)` move onto the same descriptor internally, so there is one path? 6. The `IServer` function-administration surface (§7): method names and return shapes (`FUNCTION LIST` and `STATS` replies want types of their own), and the v4 context-surface equivalent. - -## 11. Suggested spike order - -1. The Lua lexer and `@name` rewrite, with tests. No runtime dependency, and it settles §4. -2. The runtime descriptor and send path for scripts, reusing the existing gate and #3398's repair, called by hand. -3. The generator for `[RedisScript]`, against step 2. -4. `[RedisFunction]`: positional binding, `FCALL` / `FCALL_RO`, `FunctionNotFound` classification. Small once 1–3 - exist. -5. Independently of 1–4: the `IServer` function-administration commands, as ordinary commands (the +7. A general `[RespCommand]` generator (§9): agreed as the base for scripts and functions? Public for consumers + from the start, or internal first? + +## 12. Suggested spike order + +1. The declared-command generator (§9), retargeted at v4's builder, proven on a sample of existing commands and on + `FCALL`. +2. The Lua lexer and `@name` rewrite, with tests. No runtime dependency, and it settles §4. +3. The runtime descriptor and send path for scripts, reusing the existing gate and #3398's repair, called by hand. +4. `[RedisScript]`, as a specialisation of step 1, against step 3. +5. `[RedisFunction]`, as a specialisation of step 1: positional binding, `FCALL` / `FCALL_RO`, `FunctionNotFound` + classification. Small once step 1 exists. +6. Independently of the rest: the `IServer` function-administration commands, as ordinary commands (the `implement-resp-command` skill), and the coverage-ledger update. From a4a6ea049f25b772936bba3786b6970622429fcf Mon Sep 17 00:00:00 2001 From: Marc Gravell Date: Thu, 3 Dec 2026 14:51:58 +0000 Subject: [PATCH 5/5] design: keyword clauses (prefix, suffix, count, ignore-when) as the core of the declared-command model --- design/generated-scripts-and-functions.md | 30 ++++++++++++++++++----- 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/design/generated-scripts-and-functions.md b/design/generated-scripts-and-functions.md index d5431ddfe..f12bdaf3f 100644 --- a/design/generated-scripts-and-functions.md +++ b/design/generated-scripts-and-functions.md @@ -364,12 +364,30 @@ private static partial RespOperation HExpire(this in HashCommand - the command name comes from the method name, or from `[RespCommand("NAME")]`; - a `RedisKey` parameter (or `[RespKey]`) is a key; everything else is an argument; -- `[RespPrefix("TOKEN")]` writes a literal ahead of a parameter, and `[RespPrefix]` with no token writes a - collection's **count**: exactly the `numkeys` / `FIELDS n` shape; -- `[RespIgnore(value)]` drops a parameter, and its prefixes, when it has that value; null and empty collections - are always dropped. So optional clauses are declared, not branched; - `Parser =` names the reply parser, and `Formatter =` is an escape hatch for shapes the attributes can't express. +**The strongest part is keywords.** Most commands are a key or two plus a collection of keyword clauses, and that +is exactly where hand-written counting and branching goes wrong. The spike made each clause part of the +parameter it belongs to: + +| Attribute | Writes | Example | +|---|---|---| +| `[RespPrefix("TOKEN")]` | a literal before the parameter | `[RespPrefix("WEIGHTS")] double[]? weights` → `WEIGHTS 1 2` | +| `[RespPrefix]` (no token) | the collection's **count** before it | `[RespPrefix("FIELDS"), RespPrefix] RedisValue[] fields` → `FIELDS 2 f1 f2` | +| `[RespSuffix("TOKEN")]` | a literal after the parameter | `[RespSuffix("WITHSCORES")] RedisKey[] keys` → `k1 k2 WITHSCORES` | +| `[RespIgnore(value)]` | nothing, parameter and its literals included, when it has that value | `[RespIgnore(ExpireWhen.Always)] ExpireWhen when` | +| nullable type / empty collection | nothing, likewise | `[RespPrefix("AGGREGATE")] Aggregate? aggregate = null` | + +- the ignore value can be a bool, string, integer or enum value; for `RedisValue` / `RedisKey`, `null` means "has + no value"; +- enum values are written as their tokens (`AGGREGATE SUM`); +- several literals can stack on one parameter (`FIELDS`, then the count); +- the argument count follows automatically: constants, plus each optional parameter's contribution only when it + is present, including its literals. + +So an optional clause is declared once, next to its value, instead of being an `if` in the method body plus a +matching adjustment to the argument count. + What it emitted: one formatter per distinct parameter shape (shared across methods with the same shape), which computes the argument count as constants plus each optional or collection parameter's contribution, writes literals and parameters in order, and honours the command map. @@ -399,8 +417,8 @@ itself uses. **What to bring over, and what not to:** -- *Bring:* the declaration model and its attributes (renamed to fit v4), the shared-formatter idea, the - count/optional/literal rules and their diagnostics. +- *Bring:* the declaration model and its attributes (renamed to fit v4), above all the keyword rules (prefix, + suffix, count, ignore-when, nullable-means-optional), the shared-formatter idea, and their diagnostics. - *Retarget:* emit calls through v4's `RespRequestBuilder` (the interpolated writer that replaced the spike's manual `RespWriter`), returning `ValueTask` with `IRespHandler` handlers, rather than `RespOperation` and parsers. The retry category and cache flags already follow from the command, as they do for hand-written