Skip to content

v4: the 4.0 core, surface and alpha branch (tracking) - #3262

Draft
mgravell wants to merge 880 commits into
mainfrom
v4
Draft

mgravell wants to merge 880 commits into
mainfrom
v4

Conversation

@mgravell

@mgravell mgravell commented Oct 6, 2026 •

Copy link
Copy Markdown
Member

Tracking PR, not for immediate merge. v4 is the long-lived 4.0 branch; this PR exists to show its
diff against main and to collect review. It supersedes #3219, which was the spike this grew from.
When it lands it must be a real merge, not a squash: main is merged into v4 as it moves, so the
final merge stays small. Pending work and open decisions are in design/v4-ledger.md.

What 4.0 is

A new core, with the old one deleted. Message, ResultProcessor, PhysicalBridge,
PhysicalConnection and RedisDatabase are gone. Commands are rendered by an interpolated-string RESP
writer and sent through executors over the RESPite transport. Reconnect, backlog, resubscribe, redirects,
maintenance events, sentinel and logging (shipped event ids preserved) were ported and checked against
the old core before it was deleted.

IDatabase stays, served by the new core. Existing code keeps compiling and working; see
docs/LegacyApi.md. The old API is not deprecated.

A grouped, async-first command surface alongside it:

await db.Strings.SetAsync("k", "v");
using var members = await db.SortedSets.RangeByScoreAsync(key, 0, 10);   // a lease over the reply buffer

Commands are extension members on group types (Strings, Hashes, Keys, ...), so adding one - ours or a
third party's - is never a binary break to an interface. Replies can be leased rather than allocated, and
every call takes a CancellationToken.

Highlights

  • Less work on the IO loop. Commands are formatted on the caller's thread, straight into pooled
    buffers, and replies are parsed on the caller's continuation rather than by the reader. The core's IO
    loop now only frames bytes in and out, so one slow or large reply no longer holds up everyone else's.
  • A much more efficient API for ad-hoc commands and extension libraries (NRedisStack and similar).
    Instead of building object[] argument arrays for Execute/ExecuteAsync and picking through a
    RedisResult, a library writes ctx.SendAsync<T>($"FT.SEARCH {index} {query}") with a typed reply
    handler, getting the same zero-copy formatting, cluster slot routing, key prefixing and caching as the
    built-in commands, and can hang its own command groups off the same targets as extension members.
  • Client-side caching (ConfigurationOptions.ClientCache, RESP3, opt-in) driven by the library itself
    (CLIENT TRACKING), keyed by the rendered frame, with invalidation that cannot race the send; in a connection
    group, our own writes reach every member's cache. See docs/ClientSideCaching.md.
  • Batches and transactions on the new surface (SER014): db.BeginBatch() / db.BeginTransaction()
    return structs that are ordinary keyspace targets, with explicit ExecuteAsync, discard-on-dispose, and
    conditions via the existing Condition type.
  • Sync without the thread pool: Blocking() contexts send and wait on the calling thread, so a group
    method returns an already-completed ValueTask; the synchronous IDatabase methods are built on it, and
    so can a library's. DedicatedThreads connections connect and handshake synchronously, so on Linux their
    sockets never need a pool thread either.
  • For library authors: one generic accessor per group, Blocking() for sync forms, IDatabaseAsync.AsTask(...)
    for Task forms (async state and observed faults), and context.Multiplexer for connection-level settings
    such as AddLibraryNameSuffix. See docs/Extending.md.
  • Cluster: routing by CLUSTER SLOTS, batches split per slot, MOVED/ASK handled in the executor.

Compatibility

  • Package and assembly version 4.0; prereleases publish from this branch as 4.0.N-alpha.
  • Newer surfaces are gated behind [Experimental] IDs (SER011, SER012, SER014; see docs/exp/).
  • Additions to the IDatabase family are deliberate and expected in a major version; removals and
    signature changes to shipped members are not.

Status

The full suite runs on Ubuntu (net10.0) and Windows (net10.0, net481). At the branch head (0d18c57):
Ubuntu green; Windows red on ExceptionFactoryTests.ServerTakesPrecendenceOverSnapshot — both push
runs since the 3.4.31 merge, though the same commits' PR runs were green on both platforms; under
diagnosis, see the ledger. Latest prerelease: 4.0.165-alpha (2026-11-13).

Recent landings: #3338 (the method-replaying retry/prefix/group decorators replaced by context/executor
composition), #3349 (cache hits reuse the deserialized result for provably-shareable types, plus #3350's
per-key removal notifications), #3354 (per-command cache serve/store flags; CachePolicy.Storage = External),
#3355 (intent-merge of main to 3.4.31), #3356 (overload minimalism: SortedSetRange, Expiration on
RESTORE, GeoCenter). An independent v3 → v4 behaviour audit for release notes is in
notes/v3-v4-behaviour-audit.md.

Pending

Mirrors design/v4-ledger.md (last updated 2026-11-17), which has the detail; ticked here as items close.

Decisions

Work

Watch (flakes, not yet reproducible)

  • GetServerByKeyMemoization (RESP3, Windows net481) - dropped: not seen since the speculative fix d45eadf (2026-10-09)
  • "Nothing inbound" timeouts in RespCacheChurnTests - three sightings in October; take a dump mid-stall next time
  • BacklogTests.TotalOutstandingIncludesBacklogQueue and SentinelTests.AbortOnConnectFailFalseRecoversOnceSentinelsAppear - intermittent, pre-existing
  • net8.0 cluster tests timing out at 10s under the full suite
  • QueuedResultTests.RetryTransactionFireAndForgetSharesOneCompletedTask - twice now (2026-10-08 net8.0; 2026-11-13 Windows)
  • MaintenanceOptInServerTests.SequenceIdsAdvanceAndCanBeRepeated fails when its class runs alone
  • CancellationTests.WithCancellation_CancelledToken_ThrowsOperationCanceledException - a race in the test (Task.WaitAsync returns an already-completed task as-is); should cancel through the API's own token
  • Known flakes: TouchIdleTime, RespAggregateTiming, ADeferredWalkNeedsNoStorageAtAll, ADeferredWalkAgainstMaterialiseThenRead (again 2026-11-13), and the pub/sub-under-load pair (listed in the ledger)

Backlog (after the alpha)

  • Client-side cache across a geo/active-active failover - our own writes stamp every member's cache, so a failback cannot serve a value we replaced; an inactive member is kept honest by the heartbeat consistency checks groups force on (746a065; live run under Work)
  • Replace the method-replaying retry/prefix/group decorators with executor decorators - done: WithRetry, WithKeyPrefix and the group database ride the context/executor core #3338 plus the tx-retry work; KeyPrefixed*, RetryDatabase, RetryTransaction, the [AutoDatabase] generator and CapturedArgs are deleted, and retrying transactions replay frames per attempt (RespRetryTransactionExecutor), now carrying asyncState
  • Per-command cache opt-in/out - serve/store CommandFlags and CachePolicy (v4: per-command cache serve/store flags, and an external-storage policy mode #3354), including CachePolicy.Storage = External for layered caches such as HybridCache
  • Alternative client-side-cache invalidation sources - keyspace notifications (__keyspace@<db>__:*; needs notify-keyspace-events, no RESP3 requirement) and explicit pub/sub (an application-defined channel the writer publishes to), for deployments without usable CLIENT TRACKING (proxies, older servers, some managed offerings)
  • ... and the policy when the chosen invalidation source is unavailable: refuse loudly, as RESP2 + cache does today, or degrade to no caching
  • Client-side cache: public counters / metrics (hits, misses, stored, refused, invalidations, stale-served) - internal today
  • Client-side cache performance, still to explore: the gap to Lettuce's 79% hit rate (model frequency-vs-victim admission and second-chance eviction first), typed parsing on the cached miss, per-send route resolution in CanWritePreamble, RespKeyTable node lifetime, the parked builder-inlining patch
  • Operation pool size at batch depth (128 slots vs thousands in flight) - the lever the batch profile points at; then batch/transaction buffer packing
  • Unobserved faults on the new ValueTask surface (non-pooled async ValueTask only; low priority)
  • Performance: remaining ideas (each single-digit percent; parked)
  • Trusted-callback completion: inline completion measured and ruled out as a default; the one variant left is batching pool wakes per parse pass
  • Non-nullable AppendFormatted(long)/(double) overloads (NRedisStack; needs an overload-resolution sweep)
  • IServer overload audit - deliberately not examined by the overload-minimalism audit (notes/api-surface/overload-audit.md)
  • .NET 11 TFM: try runtime async; prototype caller-driven TLS (TlsBufferSession); run the suite and RespFest on 11 early (the RC2 thread-pool regression lands mostly on our own hops - dedicated reader/writer by default on net11+ is the likely answer)

A reply of NOAUTH or WRONGPASS is a statement about the connection, not about
the command: a caller whose PING comes back "NOAUTH Authentication required" has
not written a bad PING, their credentials are wrong, and the useful error says so
and says which knob to turn. Shipped does this in ResultProcessor's common error
handling, recording the suspicion against the multiplexer so
ExceptionFactory.UnableToConnect can explain it; this core passed the server's
words straight through and left the diagnosis to the reader.

Shipped's synthesised wording for NOAUTH is kept deliberately, and not only
because SecureTests reads it: "connection has not yet authenticated" names the
cause where the server's "authentication required" names only the symptom.
WRONGPASS keeps the server's own message, which is already precise. And since
SetAuthSuspect keeps the FIRST report, a refusal recorded during the handshake
wins over the NOAUTH that follows - which is what makes a wrong password read as
WRONGPASS rather than as its consequence.

Two earlier attempts at this are worth knowing about, because both tried to make
the CONNECTION refuse and both were wrong. Failing the handshake takes
ConnectAsync down with it, which ConfigTests.MutableOptions forbids outright -
it requires the connect to succeed with AuthException set. Marking the endpoint
unselectable changed nothing, because a single-endpoint standalone is still
chosen. Putting it on the reply gets both: the connect succeeds, and the command
is the thing that fails.

The plumbing is three layers, each of which answered null and swallowed the
conversion in silence: RespExecutorBase gains a Multiplexer (virtual and null by
default, since an executor built straight over a transport has none and nothing
may depend on having one), RespDatabaseExecutor delegates it, and
RespMultiplexerExecutor is given one - it is built from delegates and knows
nothing else about the client, so the one thing it is told is where to report a
fault that is not about the command.

Shipped green. Flagged 4-6, its usual band. Coupled 11 -> 10.
…st it

A failed connect already arms the policy-driven retry loop - ArmConnectRetry,
consulting DueForConnectRetry, with the code saying so in its own words: "A
FAILED attempt has to lead to another one". RetryConnectIfDue was a second
trigger for a loop that was already running. Removing it, every test it was
added for still passes: ConnectFailureRefreshTests x2,
MaintenanceRelaxationTests, ConnectionFailureErrorsTests, and
RespConnectionStateTests as the check on lazy connection.

The test it was written for was misread. ConnectFailureRefreshTests does not
count dials; it counts the "Re-reading topology after {N} consecutive connect
failures" log line, which only ServerEndPoint.OnRepeatedConnectFailure writes.
The dials were happening and nothing was reporting them. The fix that mattered
was the OnRepeatedConnectFailure call made in the same commit, which stays.

And the claim that the retry multiplied work queued at a dead node was noise.
It rested on one sample (832 outstanding, no retry) against 5,981 with it. Five
runs without the retry gave 1,872 / 5,757 / 5,800 / 5,694 / 5,044, so 5,981 is
squarely inside the distribution. The backoff added on the strength of that
comparison goes with the retry it modified. What remains true, and open: work
does accumulate against a node that is never coming back, retry or no retry.

Design note 9aj rewritten accordingly, and section 10 added: the deletion
checklist, with the compiler-measured distance (335 error sites when the old
core is removed, 137 of them real decoupling in surviving infrastructure).

Shipped green; flagged 6, its usual band; coupled 10, unchanged.
On RESP3 one connection carries commands and subscriptions together. The push
dispatcher marks a (s)subscribe confirmation MatchToCommand, and
RespClientConnection.OnOutOfBand then handed it to whatever operation was at the
head of the pending queue - whatever command that was. Instrumented, it caught
one red-handed: an ssubscribe confirmation arriving with a PING at the head.
Unguarded, the PING is answered with a push frame and every reply after it is
off by one. A desync returns wrong answers rather than failing, which is the
most dangerous thing a client can do.

The class's own remarks already stated the rule - matching a push "would answer
somebody's command with an unrelated frame and every reply after it would be
off by one" - but applied it only to unrecognised pushes. MatchToCommand
bypassed it.

The guard is conservative on purpose: it drops a confirmation only when the
head is KNOWN to be some other command, and matches as before whenever it cannot
tell. The first version asked the opposite question ("is a subscribe waiting?"),
and because not every operation records its command (RedisCommand.NONE) it
dropped the handshake's own configuration-channel SUBSCRIBE confirmation and
stalled every connect for its full timeout.

RESPite gains an internal TryPeekPending to support it. The peek is safe because
only the reader loop dequeues, and this runs on it, so the head cannot change
between the peek and the match. RespConnection is internal, so there is no
public API change.

Also: design note 9ak records a slot-map gate tried alongside this and withdrawn
- it passed 5/5 in isolation and failed 3/3 under full-suite load, at exactly the
assertion it governed. And the plan's first item is re-scoped: MOVED to the same
endpoint was already fixed in 7506591, and had been planned from a stale memory.

Shipped green; flagged 5, its usual band; coupled 11, known items only.
ClusterShardedTests.KeepSubscribedThroughSlotMigrationAsync (RESP3) remains open.
Traced on RetirementUnderMaintenanceTests: 4,579 SSUBSCRIBEs and 3,772
reconfigurations in about three seconds - roughly 1,200 a second - against a
cluster in which one node had gone away. The loop:

  SSUBSCRIBE -> -MOVED to the dead node (the server still assigns it the slot)
  -> OnSlotMoved -> ReconfigureIfNeeded("MOVED encountered") -> ReconfigureAsync
  -> EnsureSubscriptions -> SSUBSCRIBE -> ...

ReconfigureIfNeeded only coalesces while a reconfiguration is in flight, so
nothing capped the rate. In production that is CPU and cluster load at whatever
speed the loop can spin, for as long as a slot points somewhere unreachable.

A redirect to a node this core already knows is down no longer triggers a
reconfiguration. Nothing is lost: a redirect to an unreachable node cannot be
acted on, so re-reading only relearns the same unusable answer, and re-reading
BECAUSE a node is unreachable already has an owner with the restraint this
lacked - ServerEndPoint.OnRepeatedConnectFailure, rate-limited to
ConfigCheckSeconds.

And a subscribe is no longer followed to a known-down node, so it is not queued
where nobody will deliver on it; it fails, stays unplaced, and the next pass
places it somewhere live. Ordinary commands still follow and queue, deliberately:
IsKnownDown is also true for the length of a brief reconnect, and turning "wait
for it" into "fail now" for those is a separate decision.

Work outstanding at the dead node: thousands -> 0, in 5 of 5 runs.

The test still fails, one layer further on: the node is never retired, because
a tracer left on a connection being replaced waits out a relaxed timeout (9s)
while holding the reconfiguration lock, and 39 of 40 later reconfigurations are
declined. That shares a signature with ClusterShardedTests' SPUBLISH dying with
`bw: SpinningDown`, and is now the plan's next item. Design note 9al records
the layers, including a fix to the wrong wait that was made, measured, and
reverted within the same cycle.

Shipped green. Coupled 10/11/10 over three runs, known items only; flagged 11
then 8 with the set reshuffling between runs, which is load rather than this.
The root behind two failing tests, and a reply desync along the way.

RespPushDispatch decided whether a `sunsubscribe` was the server's spontaneous
notice (a slot migrating away) or the reply to our own SUNSUBSCRIBE using
Subscription.HasSendInFlight - which is only ever set for SUBSCRIBE sends. So
the reply to our own unsubscribe looked unsolicited and was consumed, and every
reply after it on that connection went to the wrong command. Traced frame by
frame, with every enqueue logged beside every reply:

  queued:  SUNSUBSCRIBE, SSUBSCRIBE, PING, SSUBSCRIBE   (wire order; never wrong)
  sunsubscribe  head=SUNSUBSCRIBE  consumed as unsolicited   <- the bug
  ssubscribe    head=SUNSUBSCRIBE  matched to the wrong command
  +PONG         head=SSUBSCRIBE    matched to the wrong command
  ssubscribe    head=PING          refused; the PING is stranded

In the tests it surfaced only indirectly: the stranded PING was a
reconfiguration's tracer, which then held the reconfiguration lock for a
nine-second relaxed timeout, so the topology was never re-read and a dead node
was never retired.

The fix uses the ground truth the shipped core already uses
(PhysicalConnection.Read peeks its outstanding commands before calling a
`sunsubscribe` unsolicited): the server answers in wire order and the queue is in
wire order, so a subscription push whose kind matches the command at the head of
the queue IS that command's reply. Only otherwise does the dispatcher's
classification apply.

That exposed a second bug the first had been cancelling. After a slot
migration, Subscription.RemoveIncorrectRouting asked the SHIPPED selector whether
the new owner could serve the slot. Its map is refreshed only by a full
reconfiguration, so it still named the old owner, and a correct subscription was
unsubscribed - and the misread reply to that unsubscribe triggered a resubscribe
on the same node, undoing it. Two wrongs made a right; correcting one made the
"RESP2" sharded test fail every time. It now asks this core's map, which the
-MOVED that announced the migration corrects directly (RespNewCore.CanServe),
falling back to the shipped check where this core has no view.

Measured across three configurations:
  engine flags only: 3, down from a 5-8 band - only the known rotators remain
  coupled: 7 / 13 / 9 over three runs, against 10 / 11 / 10;
    RetirementUnderMaintenanceTests and ClusterShardedTests.KeepSubscribed* are
    absent from all three, in both protocols
  shipped: green

Every remaining coupled failure is on the triaged list or is a timing flake that
passes 5/5 in isolation. Design note 9am records the trace.
Under the engine flags the new core owns the connections outright: the shipped
bridges no longer dial, ConnectionRestored is raised from OnNewCoreConnected,
and the "coupled" experiment and "flag-only" are now one configuration.

Landing fixes:
- eager connect skips inert cluster nodes (discovered, serving no slots), via
  RespTopology.ServesAnySlot;
- SlotLessNodesAreKnownButNotConnected asserts on the node without activating it;
- DefaultOptionsTests count sockets for one core, with a grace loop for teardown.

Verified: multi-TFM analyzer build; engine flags 7 / 9 / 6 over three runs, every
failure on the triaged list or a known flake; shipped green.
Measured first: a connect, a simulated failure and a reconnect, event ids
counted per core. The engine path was missing 31 shipped ids; it is now
missing 9, each a deliberate difference (bridge-pipeline mechanics, facts
learned from a different command, no reconfigure after a plain socket loss,
and the raw reply dump - recorded as a decision in the plan).

- connect lifecycle, TLS (in the shared transport factory), connect failed,
  connection lost and requested close, all under their shipped ids;
- the auto-configure facts logged in the handshake where each is learned;
- Resurrecting re-typed from PhysicalBridge to its name, same id and text;
- the interpolated topology-refresh lines become generated events 124-126.

Two side-effects the audit turned up:
- CONFIG GET timeout was never read, so WriteEverySeconds kept its default
  under the engine flag; now read, with the shipped rule;
- LatencyTicks was never sampled, so multi-group ranking saw every server as
  unmeasured; now sampled from the handshake's CLIENT ID and the keep-alive.

LoggerTests now passes under the engine flags. Verified: multi-TFM analyzer
build; engine flags 4 / 5 over two runs (a third had a one-off 6s stall on the
shared 6379 connection that did not recur), every failure triaged; shipped green.
ClusterNodes, ClusterNodesRaw and ClusterSlots, ScriptLoad, ReplicaOf, and
ConfigSet's read-back now go through the RESP context, so under the engine
flag they reach the connection that carries everything else instead of a
shipped bridge that no longer dials.

Each keeps the side-effect its shipped processor had:
- CLUSTER NODES records the configuration on the server (SetClusterConfiguration);
- SCRIPT LOAD records the script as loaded on the server (AddScript);
- REPLICAOF gives up the tie-breaker first and broadcasts on the
  configuration channel after - with the channel prefix, which the server
  context deliberately does not carry (ConfigurationChannelUnitTests);
- CONFIG SET reads the setting back and applies it through
  RespHandshake.ApplySetting, now the one copy of the rules discovery uses.

Found on the way, by bisecting HeartbeatTests: KeepAlive decides whether
discovery ASKS for the server's timeout, never whether a reply is applied -
the shipped processor applies it regardless, and the new rule now does too.

The cluster verbs are internal on the diagnostics group so the port does not
decide a public surface. The 14 Sentinel methods stay with D2.7.

Verified: multi-TFM analyzer build; engine flags 6 / 4 / 6, every failure
triaged or a known flake (two run-3 timeouts match an open stall signature
now recorded in the plan); shipped green.
…socket

Sentinel (D2.7): the 14 IServer sentinel methods now run on the RESP context
(SentinelCommands, internal), so a sentinel is asked over the connection the
new core holds rather than through a shipped bridge dialled on demand. Two
recovery bugs surfaced by AbortOnConnectFailFalseRecoversOnceSentinelsAppear:
- retiring a server left its new-core executor alive, and the executor's
  reconnect re-created the server: RespNewCore.RetireEndpointAsync now drops
  the executors and their database views when the multiplexer retires one;
- a restore-triggered primary switch that failed - the seed was a sentinel,
  restored before the sentinel connection had relearned its types - stopped
  the retry timer and never re-armed it. It now re-arms, as a failure does.

ReconnectRetryPolicy: the policy was asked before anything had failed, and
given a failure count where it expects the number of retries already made.
Both now match the shipped bridge.

DefaultOptions / GetClients: not decision 2's trade-off after all. Reading
GetConnectionId created - and so dialled - a shipped bridge, putting a whole
extra handshake on a third socket. It now asks without creating.

MovedProfiling: EnqueuedToSending can be a real interval under TimeSpan's
100ns resolution, as ResponseToCompletion already can; asserted >= 0.

Verified: multi-TFM analyzer build; engine flags 0 / 0 / 6 - the first fully
green engine runs; the 6 are the open stall signature plus a timing unit
test. Shipped: one failure, a client-cache timing unit test this does not touch.
Replies arrive in order, so a timeout with nothing inbound is usually waiting
behind somebody else's command. The report now names the oldest pending
command on the connection and its age, when that is not the command that
timed out - the capture the open 5s-stall flake needs, and a lasting
diagnostic for blocking commands on a shared connection.

Plan: the list of library paths that still construct (and so dial) a shipped
bridge under the engine flag, measured by a probe over one full run - the
work between here and flipping the default.
… tests

A probe on ServerEndPoint.CreateBridge over one full engine-flag run counted
179 shipped bridges still being built - each of which dials - from library
code. Every path now goes through the new core instead:

- AutoConfigureAsync returns at once under the engine flag: the handshake and
  RefreshTopologyAsync own those facts. It was also what renewed each node's
  CLUSTER NODES view, which GetEndpointsFromClusterNodes trusted as "renewed by
  the refresh above"; it now re-reads NODES on the new core, once per pass, as
  the shipped path did (bisected from NodeThatLeavesTheClusterIsRetired);
- ISubscriber.Ping with no subscriptions on the server pings this core's own
  connection instead of falling back to a Message;
- HOTKEYS START/STOP/RESET/GET on the context;
- HashImport's DISCARD goes out on the new core, and releases the field-set's
  connection-local claim, which would otherwise outlive it;
- AddLibraryNameSuffix stops after renaming the new core's connections;
- GetEndpointsFromClusterNodes reads both views on the new core when it has
  nothing cached, recording the SLOTS view as the shipped processor did;
- MakePrimaryAsync writes its tie-breaker, broadcasts and REPLICAOFs through
  each node's own context.

The 20 left are tests that drive RedisDatabase or bridges on purpose.

Found by it: DedicatedThreads is implemented only by PhysicalConnection, and
its tests passed under the engine flag by inspecting a bridge built on the
side. They now skip there and say why; recorded as decision 6 in the plan.

Verified: multi-TFM analyzer build; engine flags 0 / 1 / 0 (a known
key-notification count flake); shipped green.
Both flags are now on unless SEREDIS_NEW_CORE_ENGINE=0 or
SEREDIS_NEW_DATABASE_SURFACE=0 (or SetFeatureFlag) turns them off, which
returns the shipped core - kept only as a way back while the alpha is proven,
and scheduled for deletion. This is the shape the alpha can ship in: the old
core present, unreachable by default.

Made default once the suite passed on it and no library path still built a
shipped bridge (c7a6e76).

Verified on net10.0: default (new core) 0 / 2 / 0 over three runs - the two
are known flakes - and legacy (both flags off) green. Not verified locally:
net481, which CI runs on Windows; the new core has not been exercised on .NET
Framework in this work.
NewCoreEngine and NewDatabaseSurface are now always true. Neither the
environment nor SetFeatureFlag can put a multiplexer back on the old core, so
it is unreachable by any configuration ahead of its deletion. The enum values
stay so existing SetFeatureFlag calls still parse; they have no effect.

The properties survive only so the branches still testing them compile until
the deletion removes them.

Verified: multi-TFM analyzer build; full net10.0 suite green.
Pure relocations, no behaviour change - the old core keeps compiling through
aliases until it goes:

- MaintenanceNotificationReader: the static maintenance-notification parse
  both cores share, out of PhysicalConnection.Maintenance.cs;
- PushKind / PushKindMetadata: top-level in Protocol/PushKind.cs;
- the ambient TLS certificate callbacks: into RespTransportFactory, the TLS
  boundary that already called them;
- CommandFlagsInternal: Message's internal flag bits, masks and routing rules
  (CommandServerSpecific, MaskRetryCategory, RequiresDatabase, DemandPrimary,
  ...), with Message keeping aliases; 134 references repointed.

Verified: multi-TFM analyzer build (src and tests); full net10.0 suite, two
known flakes.
…anches

The "try the new core, else fall back to a Message" pattern was where a
multiplexer could still slip onto the old core with the engine hard-wired: the
try returned null for a subscription the old core held, and the only way to
get one of those was through the same fallbacks. With them gone the state is
unreachable, so Subscription.SendViaNewCore is now non-nullable and every
fallback goes - subscribe, unsubscribe, re-route, multi-node, resubscribe.

The Message was also what ROUTED, so routing is now explicit and identical to
what Select(Message) did: Subscription.SelectServer takes the command for the
channel's kind, a slot only for a key-routed channel, and the subscription's
primary/replica preference. IdentifyEndpoint and the subscriber ping route the
same way and, where nothing is selectable, fail with the NoConnectionAvailable
the old path produced. (Hashing a plain channel anyway pinned it to one node:
ClusterTests.ClusterPubSub caught that.)

Also: Publish, RedisServer's executor and IsConnected, the default ConnectMode,
HashImport's discard and the library-name loop lose their old-core branches.

Verified: multi-TFM analyzer build; full net10.0 suite 0 / 1 (a known
key-notification flake) after the fix; pub/sub subset 3x green.
Message, ResultProcessor, PhysicalBridge, PhysicalConnection, RedisDatabase, RedisBatch,
RedisTransaction, RespMessageExecutor, MessageWriter, the per-command *Message classes and
CursorEnumerable are gone; the new core is the only core, so nothing can select the old one.

What they owned and something still needed moved: reply parsing to Protocol/RespParsers*.cs, raw RESP
writing to Protocol/RespWire.cs (also used by the toy server), admin-command metadata to
Protocol/AdminCommands.cs, and the status enums the logging events take to ConnectionStatus.cs (event
ids unchanged). The NewCoreEngine/NewDatabaseSurface properties and their branches are removed; the
enum values remain so SetFeatureFlag still parses them.

Fixes found on the way:
- an endpoint's connect fault is cleared on a successful connect, as the old bridge did, so
  LastException stops reporting a failure the endpoint has recovered from
- SimulateConnectionFailure demands AllowAdmin again
- RespScanEnumerable reports its initial offset before the first page is fetched

Tests: suites that drove the deleted types are parked via Compile Remove (listed in the plan, to be
retargeted); the NewCore*Tests re-runs are removed, since they built a second core per multiplexer.

CI: Windows replicas never synced (the sync RDB fails to load from the /mnt mount), which went unseen
while replicas were read from CLUSTER NODES; start them with diskless load, and fail fast unless every
replica syncs and CLUSTER SLOTS lists all six cluster nodes.
… parity tests

ResultProcessorUnitTest now parses through RespExecutor.ParseFromSpan, the funnel the core itself
uses; the folder's Compile Remove is split per file so each can be re-enabled as it is retargeted. The
surface parity tests compared the new surface with RedisDatabase, which no longer exists.
…ts at IRespHandler

Each test now parses with the handler the command actually sends (the private group handlers are
reached by reflection rather than copied). Where the new handler answers differently the test pins
the new answer with a comment: malformed XAUTOCLAIM/XINFO STREAM/XPENDING replies now become a
default/Null result instead of a fault, a nil GEOPOS array becomes empty, and a nil VLINKS becomes
null rather than an empty lease.
…y lease again

Found retargeting the parser tests. XAUTOCLAIM, XINFO STREAM and XPENDING (both forms) turned a reply
they could not parse into an empty result; a missing key or group is an error reply and never reaches
a handler, so that passed a protocol violation off as a real answer. They throw, as v3 did.

VLINKS answers nil for a missing member, which v3 returned to IDatabase callers as an empty lease; the
new handler returned null. Restored on the Lease<T> forms the IDatabase surface uses.
…sks them for

db75a6f added both to CI with --logger GitHubActions, which neither referenced, so the Ubuntu job
failed after its tests had passed.
…lers

Unparks BasicScalars, BasicAggregates, DateTime, TimeSpan, DemandZeroOrOne,
ExpectBasicString, Lease, LeaseRedisValue, RedisValueFromArray, InterleavedPairs,
Misc, RespResultProcessor and Timing; drops TracerProcessor (no equivalent).
Behaviour differences are pinned with comments; two suspected regressions
(nil/empty TYPE -> Unknown, scalar reply to an array read) are kept at the
shipped expectation and skipped. Group handlers the tests target are made
internal rather than private.
… element, as v3 did

Both found retargeting the parser tests. LMOVEM's NullableValues stays strict, as v3's was.
… at the new core

RoundTripUnitTests now drive IDatabase over a fake executor and assert the
captured frame bytes; ResultBoxTests is deleted (ResultBox is no longer on any
live path). Two retry-category regressions are pinned as skipped tests.
…ain; SINTERCARD-family omits LIMIT 0

Found retargeting the retry-category tests: v3 raised COPY ... REPLACE to last-wins, and demoted an
XREADGROUP whose positions are all explicit ids (no CLAIM) to a read; the new surface did neither.
IDatabase.SetCombineLength passed its default limit of 0 to the wire as LIMIT 0; omitted again, as
SetIntersectionLength already did.
…here callers would null-check, so the change is nearly unobservable at the public surface

Verified live: SMEMBERS/SORT/the RANDMEMBER-with-count family/GEOPOS/LATENCY answer *0 for missing
keys, HEXPIRE answers per-field -2, and the two genuine nil senders were already handled (XREAD's
nil mapped to empty by v3's SingleStreamProcessor; EXEC's nil is the unchanged transaction path).
RedisResult keeps IsNull. Residual exposure: third-party servers/proxies answering *-1 where Redis
answers *0, which now read as empty rather than null-into-a-non-nullable array.
…ypes (#3349)

* spike: cache hits reuse the deserialized result for provably-shareable types

An Entry memoizes ONE parsed result with the handler that produced it (first writer wins,
handler-identity keyed, carried across slab compaction); the hit funnel serves the memo
before touching the reader. Core auto-enrolls strings and no-reference value types
(IsReferenceOrContainsReferences, conservative down-level); richer rules opt in through
the new public IRespResultReuse<TResult> on the handler - the HybridCache integration seam.

* A memoized result charges the cache budget: IRespResultReuse gains SizeOf, and the core sizes what it enrolls

The charge is paired with the Memo object itself - set wins charge, whoever takes the memo
(removal, replacement, slab move via ownership transfer, with a tombstone closing the slot)
credits exactly what was charged - so MaxBytes cannot drift under the discard/late-set race.
Strings are header+UTF-16, boxed no-ref structs are header+Unsafe.SizeOf; handler-opted
results volunteer an estimate, 0 meaning uncounted.

* Per-key removal notification for the client-side cache (#3350)

* Per-key removal notification for the client-side cache

A context enrolled via RespDatabaseContext.WithRemovalHandler is told - with
the key and a reason - when a key it read stops being servable from the
client-side cache, so layers above (HybridCache tag memos, backplane
adapters) can keep derived state coherent without polling.

Observers hang on the key-table NODE, the one object every death already
touches: invalidation fires promptly while the corpse is still resident,
flush walks the nodes it already walks, and slab compaction is not a
removal. Enrollment is one-shot - armed by a serve, consumed by the first
removal at or after it, re-armed by reading again - which makes exactly-once
structural (an Interlocked take, as the result memo does) and bounds
dangling handlers. Arm-then-recheck closes the serve/death race, and a value
handed out already dead (a fill that raced an invalidation, a stale-grace
serve) is announced immediately rather than silently.

Dispatch is the library's existing model: never on the caller's thread -
the socket reader, the table's locks, the evictor - but queued to the
thread pool like pub/sub and connection events, with exceptions swallowed
per handler. No key copy: Node.Key is already immortal.

Reasons separate value-changed (Invalidated, LocalWrite, Replaced) from
cache hygiene (Evicted, Expired) and the bulk case (Flushed); a
correctness-only consumer treats them all as drop. A fill whose tracking
prefix was dropped enrolls nothing: no invalidation is coming for it to
hear.

* Per-caller cache behaviour is one policy, not a wither per knob

WithMaxCacheAge and WithRemovalHandler are gone; the context carries a
whole CachePolicy (WithCachePolicy, on both public context types), and
CachePolicy - now a record, so callers derive with 'policy with {...}' -
gains RemovalHandler. The surface stops growing contexts-times-knobs:
a new read-time knob is one init property, and the first ship had
already dropped a cell of that matrix (no WithRemovalHandler on
RespServerContext).

A per-read policy replaces the default wholesale and narrows, never
widens: the default TimeToLive stays a ceiling, reclamation follows the
default policy alone, and a per-read grace window only functions when
the default policy enabled stamping. RefreshAfter is now genuinely
per-caller. A RemovalHandler on the DefaultPolicy is connection-wide
enrollment - every read arms it, including background refresh
completions - which is what a backplane-style consumer wants, and has a
new test.

The policy's tick conversions are memoised at construction (the old
MaxCacheAgeService did this; now the default-policy hit path gets it
too), which surfaced a static-ordering trap: Default must be declared
after the field its construction reads.
mgravell and others added 4 commits November 13, 2026 11:51
…utor core (#3338)

* WithRetry, WithKeyPrefix and the group database ride the context/executor core: RetryDatabase and the KeyPrefixed* family go

- WithRetry(IDatabaseAsync) re-contexts via RespRetryExecutor (asyncState now carried; foreign database passes through unchanged); RetryTransaction stays, built by CreateTransaction when the chain retries
- MultiGroupDatabase is a slim RedisDatabase over RespGroupExecutor; the 628 generated members go, scans pin to the active member, GetDatabase(-1) resolves from configuration
- WithKeyPrefix(IDatabase) re-contexts via AppendKeyPrefix + AppendChannelPrefix and THROWS for a foreign database (silently not prefixing is the wrong keyspace); KeyPrefixed*/KeyPrefixedBatch/KeyPrefixedTransaction deleted
- gaps closed: RANDOMKEY refuses under a prefix; SORT BY/GET patterns map (nosort/# exempt); Lua @key ARGV copies prefix via extraction over a WithoutKeyPrefix view; routing questions ask about the prefixed key; AppendKeyPrefix carries topology + cache resolver
- the member-by-member wrapper tests (~4,100 lines) become KeyPrefixContextTests over the FakeExecutor RESP-measuring harness

* A retrying transaction replays rendered frames, like everything else: RetryTransaction and the [AutoDatabase] generator go (#3339)

RespRetryTransactionExecutor records each queued command's rendered RespRequest plus a durable
caller proxy, then replays the frames into a fresh one-shot RespTransactionExecutor per attempt,
sharing the database's RetryController. Fresh attempt operations per replay are what dodge the
real blocker: enrolled pooled operations are faulted directly by connection teardown, so
re-enrolling one races pool recycling.

With its last consumer gone, the capture-and-replay tier is deleted whole: RetryTransaction,
AutoDatabase.cs, CapturedArgs.cs, the AutoDatabaseGenerator, SER352, and IInternalTransaction.
Nothing on IDatabase is source-generated any more.

Deliberate behavior changes: a retrying transaction now carries asyncState (previously refused)
and exposes a working context that queues into the recorded unit (previously threw). Reuse after
execute is still refused. Fire-and-forget parity is now real rather than claimed: both transaction
executors hand every declined reply the one shared completed-default task, and TaskBridge passes a
completed fire-and-forget task through untouched instead of rewrapping it.
…ode (#3354)

CacheNoLocalServe (bit 23): always a round trip - no probe, no attaching to
an in-flight twin - while the reply stays eligible to store and a removal
handler still arms. CacheNoLocalStore (bit 24): serve if present, but the
reply begins no fill at all - no store, no enrollment, no single-flight
leadership for waiters to lose time on. Together: full non-participation
for that call. Both inert on non-participating commands, both in
UserSelectableFlags, no wire half in any tracking mode.

The external cache layer (FusionCache, IDistributedCache-based HybridCache)
wants the OPPOSITE of the store flag - nothing kept, everything watched -
and overloading one flag with both meanings would poison each, so that is
a policy instead: CachePolicy.Storage = CacheStorage.External. Fills run
and refuse only the store (tracked stays true, the handler arms), the read
implies CacheOptIn so the doorkeeper and the opt-in modes cannot silently
drop an enrollment, and no in-flight registration is made since a waiter
would wake to find nothing. Serving from entries others stored stays: it
is current per the same invalidation stream, and the serve re-arms.

Declaring the new members beside the bit 20-22 cluster flipped which of
the duplicate-valued names (DemandSlave/DemandReplica) ToString() picks -
the exact trap the enum's warning comment describes - so they are declared
at the end, a position verified against the formatting expectations on
net8.0 and net10.0 by brute force over all insertion points.
…eyed routing tests, SER1xx experiment block (#3355)

* Make the dedicated subscription connection lazy (#3310)

The dedicated pub/sub connection (always under RESP2; under RESP3 unless
SharedSubscriptionConnection is enabled) was opened eagerly as part of
activating every endpoint, so a client that never subscribes to anything
still paid for a second socket per node, and a second reconnect per node
on every failover. Seen on AMR, whose options provider disables the
configuration channel: 3.4.x showed two RESP3 connections where 3.0.x
showed one.

ActivateServer now opens that connection only when there is something to
subscribe to straight away: a configuration channel, or subscriptions that
already exist (and may need to move to this endpoint). Otherwise it is
created on first use, via the existing GetBridge paths; with the default
backlog policy the first SUBSCRIBE queues until it is up.

The connect wait ("second leg") and the maintenance handoff deadline
treated an absent subscription bridge as a disconnected one, which would
have left connects hanging; they now consider a connection that has not
been asked for as not required. The endpoint-state connect log says
"NotRequired" for that case instead of "Disconnected".

Tests: AzureManagedRedisConnectionCount now asserts one connection before
pub/sub and the expected count after; a new test covers the eager case
when a configuration channel is set; two tests that relied on the eager
subscription connection now subscribe first.

* Command coverage ledger and audit skill (#3311)

* Command coverage ledger and audit skill

Adds docs/CommandCoverage.md: every upstream Redis command the library does
not expose as a typed API, grouped and with a recorded decision (policy,
not applicable, deferred, todo, deprecated, enum-only, implemented). Seeded
from a diff of redis/redis src/commands (477 specs, @6a5fee67) against the
RedisCommand enum and source; it carries forward the dispositions from
#2055 (blocking is policy, Functions and ACL are deferred) and replaces
that hand-maintained list.

Adds the audit-command-coverage skill and its script, which re-runs the
diff on request and reports only what changed: new upstream commands with
no decision, ledger rows the code now covers, rows the spec no longer has,
and enum members the spec does not know. The script exits non-zero when
the ledger needs editing.

Closes #2055.

* Ledger: CLIENT TRACKING is v4, cluster/COMMAND introspection is administration, CLUSTER SHARDS note corrected

* Ledger: CLIENT PAUSE/UNPAUSE are operator tooling, not applicable

* Update RedisType.Bitmap and the keyspace-event tokens to reflect current server values (#3312)

* Object-type metadata for native bitmaps (redis/redis#15331), plus the tokens that diff turned up

RedisType gains Bitmap ("bitmap", the TYPE reply for a native roaring
bitmap, 8.12) and Gcra ("gcra", already in the server's type-name table).
KeyNotificationType gains SetBit (emitted under class $ for string bitmaps
and class b for native ones) and the other event names the server emits
that the enum lacked: arinsert, armset, arring, arseek, gcra, pfadd,
sexpire, spersist, sinterstore, zrangestore, and keymiss (class m, side
effect group).

Fixes the Copy token: the server has only ever emitted "copy_to", so the
"copy" token never parsed and a RedisChannel.KeyEvent(KeyNotificationType.Copy)
subscription never fired. The member and its value are unchanged.

Both parsers are generated from [AsciiHash]; tests extend the token tables.

* Drop Gcra: the type was withdrawn before release, so there is nothing for the token to match

* Add sunionstore/sdiffstore events (from the keyspace-notifications docs); drop the history comment on Copy

* Fix ConnectionGroupMember string-ctor dropping the name (#3314)

* Forward the name argument in ConnectionGroupMember's string constructor

The string overload chained to the ConfigurationOptions constructor without passing `name`, so every
member built from a configuration string (the idiom used throughout docs/Failover.md) was named after
its first endpoint by Init() instead of the name the caller gave it. Regression test added.

* Parenthesize a Debug-only assertion that trips SA1407

`endSegmentLength == 0 & endSegmentCommitted == 0` in DebugAssertValid sits inside `#if DEBUG`, so CI
(Release) never compiles it and never saw the StyleCop error; any local Debug build of RESPite failed
with TreatWarningsAsErrors. Introduced by ee47e53 after the StyleCop bump in aa1e5c0.

* Parse unbracketed IPv6 ip:port from the server (#1422) (#3307)

* Parse unbracketed IPv6 ip:port from the server (#1422)

CLUSTER NODES, MOVED/ASK and CLIENT LIST write IPv6 addresses without
brackets, i.e. "2a06:4e80:3:a::a:7000". The RFC 3986 parser used for
configuration strings reads that as a (valid!) eight-group address with
no port, so cluster nodes ended up as "[2a06:4e80:3:a::a:7000]:0" and
redirections and client addresses were equally wrong.

Add Format.TryParseServerEndPoint for the server's "ip:port" form: when
there is no ']' and more than one ':', split at the last colon and
require both halves to parse; anything else goes to the existing parser
unchanged, so configuration parsing is not touched. Use it at the three
sites that receive server-emitted text.

The sentinel +switch-master handler gets host and port as separate
tokens and was gluing them back together with ':' before parsing; pass
them to the (host, port) overload instead.

* Parse unbracketed IPv6 in MOVING/SMIGRATED endpoints

ParseMigrationEndPoint used the configuration-string parser, so an unbracketed IPv6 address parsed as an address with port 0, which the placeholder check then discarded. Use TryParseServerEndPoint, as the other server-emitted sites do; tests for the MOVING successor and SMIGRATED source/target.

* Profile commands sent in a batch (#2175) (#3313)

Co-authored-by: mohsinaliwork686-rgb <229973101+mohsinaliwork686-rgb@users.noreply.github.com>

* public-api.py: apply *REMOVED* at promotion; promote the API surface since 3.4.0 (#3316)

* public-api.py: apply *REMOVED* entries at promotion instead of copying them

The analyzer records a vanished shipped signature as a *REMOVED* line in
the unshipped file. Promotion moved every unshipped line across verbatim,
so a promotion after any such change would have left the shipped file
with both the dead signature and a *REMOVED* copy of it, and the analyzer
would then fail the build on the dead one (RS0017).

Promotion now consumes the marker: the named signature is dropped from the
shipped file, the marker is not carried over, and a marker that names
nothing shipped is an error. A *REMOVED* line already sitting in a shipped
file is also reported. The "+N promoted" note gains "-N removed", and an
unshipped file holding only removals is still emptied.

* Promote the shipped API surface: everything since 3.4.0

eng/public-api.py --promote. Fifty-two StackExchange.Redis entries (the
lag-aware availability surface, FailbackHealthCheck, HealthCheckProbeScope,
the 8.12-independent RedisType and KeyNotificationType tokens) and the
net6.0 SetUserPemCertificate overload move to shipped; the three parameter
renames from #3296 (muxer -> multiplexer on the Azure providers'
AfterConnectAsync, other -> obj on RESPite AsciiHash.Equals) are applied
rather than copied. Every unshipped file is now empty.

* Split third-party notices out of LICENSE so GitHub detects MIT (#3317)

* Split third-party notices out of LICENSE so GitHub detects MIT

The LICENSE file carried ~1.1KB of third-party notes after the MIT text,
which drops it below licensee's similarity threshold; GitHub reports the
repo license as "Other" (SPDX NOASSERTION). Keep LICENSE as the bare MIT
text and move the notes, verbatim, to THIRD-PARTY-NOTICES.md.

* Correct the third-party notices

- Redis: BSD-3 only through 7.2; RSALv2/SSPLv1 from 7.4, AGPLv3 added in
  8.0; point at redis.io/legal/licenses (the old /topics/license URL now
  redirects to the docs landing page).
- redis-doc: repo is archived under redis/redis-doc; note that redis/docs,
  its successor, is CC BY-NC-SA for newer content.
- Drop the Redis-64 and BookSleeve notes: neither is part of the
  development solution any more.
- Add the code actually incorporated from other projects (dotnet/runtime,
  dotnet/corefx, aspnet/BasicMiddleware) and the test-only redis-sharp copy,
  none of which the old notes mentioned.

* The read loop stops matching replies once teardown owns the response queue; a close with commands in flight no longer completes a call with the previous call's reply (#3330)

RecordConnectionFailed drains _writtenAwaitingResponse one message at a
time, completing each outside the lock, while the read loop can still be
matching replies that were already in the receive buffer. Each reply the
loop matched after the drain had taken a message went to the message
*after* the one it answered: GET key N completed, successfully, with key
N-1's value, and every reply behind it was off by one. Reproduced on
main with the reporter's loop: 616 wrong replies in 20,000 calls.

_isShutdown was already set under the queue's lock before the drain, and
the loop already consulted it - but only once the queue was empty.
Checking it before the dequeue closes the race: a reply arriving after
teardown has begun is dropped with the connection, and the message it
answered is failed by the drain as before.

The test re-creates the scenario against the real server (20 rounds of
500 in-flight GETs closed with allowCommandsToComplete: false) and
asserts that no call completes with another call's value; without the
fix it sees ~200 in a run.

Fixes #3329

* CLUSTER SLOT-STATS (8.2): per-slot usage statistics on IServer, experimental SER012 (#3341)

* CLUSTER SLOT-STATS (8.2): per-slot usage statistics on IServer, experimental SER012

IServer.ClusterSlotStatsBySlotRange(Async) and ClusterSlotStatsOrderBy(Async), modelled
on the CLUSTER SLOTS file layout and the HOTKEYS field handling: node-local read, lenient
nominal parsing, config-gated metrics as nullable properties (absent != zero), unknown
metrics preserved as Metadata, cpu-usec surfaced as TimeSpan. RedisFeatures.ClusterSlotStats
gates on 8.2 RC1. Promotes the CommandCoverage 'deferred' row.

* The storage-kind tripwire acknowledges SLOT-STATS and SLOTSRANGE: two new >8-byte literals, 28 -> 30

* Check the maximum operation count in HeartbeatConsistencyCheckPingsAsync (#3342)

* In-repo links follow the org move to seredis (#3326): github.com/StackExchange/StackExchange.Redis -> github.com/seredis/StackExchange.Redis everywhere, including the nupkg RepositoryUrl/PackageReleaseNotes metadata (#3344)

* MOVING handoff: hold new work in the backlog while the in-flight commands drain, so the recycle happens within a round trip instead of at the window end (#3347)

* MOVING handoff: hold new work in the backlog while the in-flight commands drain, so the recycle happens within a round trip instead of at the window end

The drain waited for "no caller work", which under steady traffic never comes: there is always a command in flight, so the recycle waited out the whole announced window and failed whatever was in flight at that instant. Measured live (endpoint rebind, single proxy, ~900 ops/s): recycle at +20.0s against a MOVING at +6.0s, 16 failed commands, missed-deadline warning.

While a handoff drains, the bridge holds a caller's work in the backlog instead of writing it to the connection about to be replaced; the backlog processor does not flush while the hold stands; the drain waits only for what is already written, capped at half the relaxed timeout (bounded by half the remaining window, floor one second); the connection is then recycled as before, the hold cleared, and the held work flushed to the replacement by the ordinary reconnect path. Timeouts are relaxed for the hold and the reconnect. A FailFast policy does not abandon held work for the handoff's own disconnect. Same scenario on this branch: recycle at +6.2s against a MOVING at +5.9s, 0 failed of 97k.

Deliberately a flag and nothing more: no per-message timeout cover (with relaxation off and a timeout shorter than the hold, held commands can time out in the backlog, as on any reconnect), and no retire under the write lock (a writer that reaches the lock after the recycle gets a write fault, as before). Also: the drain budget is recomputed after the DNS poll, a second MOVING during a handoff updates the successor pin rather than being dropped, and the pin lasts the window so the second bridge dials the same successor.

Tests: steady load (with and without relaxation), slow command inside the cap, blocking command past the cap; plus a fault-injector tier measurement that records the live timeline.

* OneLogicalEventFromEveryNodeRaisesOneEvent: wait for the one event rather than counting at the instant the second node relaxed; the callback is dispatched after the relaxation, so the count could be read as zero (flaked on main at ~1 in 6)

* INCREX and ARGREP are routed by key on a cluster (#3352)

IncrexMessageBase (#3065) and ArrayGrepMessage (#3076) derived from Message
directly, held a key, and never overrode GetHashSlot, so they reported
NoSlot. On a cluster that sends the command to an arbitrary node and leans
on -MOVED: an extra round trip for most calls, and a RedisServerException
under CommandFlags.NoRedirect.

Both now derive from Message.CommandKeyBase, as their single-key siblings
do, which supplies the slot (and the key in CommandAndKey).

Affects the StringIncrement overloads that take an Expiration (INCREX) and
ArrayGrep. No public API change.

---------

Co-authored-by: Mohsin Ali <mohsin.ali.work686@gmail.com>
Co-authored-by: mohsinaliwork686-rgb <229973101+mohsinaliwork686-rgb@users.noreply.github.com>
Co-authored-by: Nikolay Zdravkov <unsafeptr@gmail.com>
…ter (#3356)

The three findings from the v4 group-surface overload audit
(notes/api-surface/overload-audit.md):

- SortedSets: one method per operation - RangeAsync, RangeWithScoresAsync,
  RangeAndStoreAsync, RemoveRangeAsync, RangeLengthAsync - each taking a
  SortedSetRange operand (ByRank/ByScore/ByValue) instead of eleven per-axis
  methods; LengthAsync slims to bare ZCARD. The per-axis methods demote to
  internal, keeping the wire spelling and the legacy IDatabase adapter. Cells
  the server cannot spell (WITHSCORES over BYLEX, LIMIT or a count over ranks)
  throw rather than quietly answering a different question; a by-rank
  exclusivity is no longer representable at all. The operand store path also
  gains open lexical bounds and descending bound-swapping, which the
  SortedSetOrder-shaped legacy method left to the caller.
- Keys.RestoreAsync takes an Expiration: relative stays positional
  milliseconds, absolute adds ABSTTL, KEEPTTL/PERSIST/ENX are rejected, and
  the TimeSpan.MaxValue-means-none wart survives only in the internal legacy
  sibling.
- Geospatial: a GeoCenter operand (implicit from RedisValue/string/GeoPosition;
  deliberately not from a tuple - ValueTupleNotReferenced pins that) folds the
  member/lon-lat SearchAsync and SearchAndStoreAsync pairs 4 -> 2.

En route: RangeByScoreCore and CombineCore accepted a CancellationToken from
their public callers and dropped it before SendAsync; both now forward it.
Geo's SearchCore has the same drop, left for a sweep of its own.
mgravell and others added 22 commits November 17, 2026 14:06
The ledger had not been updated since 2026-10-13, so a month of landings
left it claiming work that is done (the method-replaying decorators, the
stale retry comments that went with the deleted files) and missing work
that is new. Per its own rule, closed entries are deleted - this file's
git history holds them - and the long shipped-history narratives are
condensed to their conclusions with pointers to the commits and design
docs that carry the detail.

New open items recorded:

- Windows CI is red at the branch head: ServerTakesPrecendenceOverSnapshot
  failed on both v4 push runs since the 3.4.31 merge (the same commits'
  PR runs were green), expecting "connection was closed" but getting
  "Aborting (AllowConnect: False)".
- The drift-check command overstates: #3298 and #3355 were intent-ports
  squash-merged onto v4, so ancestry is not joined and rev-list answers
  15 where the true drift is one commit (#3333, announce hostname).
- The CancellationToken drop in geo SearchCore (#3356's sweep candidate),
  the Twemproxy gap, and the nine test-coverage debts and IServer
  overload audit surfaced by the November audits, with pointers into
  notes/.

GetServerByKeyMemoization is dropped from Watch (not seen since its
speculative fix on 2026-10-09); the RetryTransaction and DeferredWalk
flakes gained their 2026-11-13 sightings.

The notes index now lists all four topics, not just lag-aware. The
tracking PR #3262's body is updated to mirror.
) (#3359)

The one main commit v4 had not absorbed (ca51eb6). The shadow-topology
machinery is shared between the branches - ClusterTopology.cs is
identical and ApplyTopologyGenerationAsync / ReconfigureAsync carry the
same structure - so the cherry-pick applied without conflict; verified
that the hunks landed inside v4's live ReconfigureAsync path and that
the re-home runs on every applied topology here too.

As on main: ClusterTopologyNode gains PreferredDialEndPoint (the form
the deployment announced first); topology application re-homes a node
held by a companion address onto its announced hostname (adopted at the
exact form so the repair does not resolve through the alias being
repaired, retired through the existing duplicate-merge machinery;
configured seeds exempt); and discovery creates a SLOTS-listed node at
its announced form in the first place, so the common path never creates
the companion server at all.

Tests ported with it: PreferredDialEndPointFollowsAnnouncedForm,
HostnameAnnouncedShardIsDiscoveredByHostname and
ShardHeldByAddressMovesToItsAnnouncedHostname, plus the ApplyTopologyAsync
helper. ClusterTopologyUnitTests 17/17 and EndpointResolutionUnitTests
5/5 green on net10.0.
…t fault (#3360)

Both v4 push runs since the 3.4.31 merge failed
ExceptionFactoryTests.ServerTakesPrecendenceOverSnapshot on Windows:
expected LastException to be "The connection ... was closed", got
"Aborting (AllowConnect: False)". The sequence: SimulateConnectionFailure
records the genuine SocketClosed fault (RecordFault), the failure
provokes a reconfigure whose DialEndpointSoon redial is refused by the
test-only AllowConnect gate, and the executor's connect catch recorded
that refusal over the real fault. The test reads LastException twice -
once inside ExceptionFactory.NoConnectionAvailable, once in its final
assert - so whenever the overwrite landed between the two reads it
failed; pure timing, which Windows push runs kept losing and Linux kept
winning.

A dial the gate refused was DECLINED, not failed: nothing was learned
about the endpoint, so the executor now skips recording the refusal as
_lastConnectFault (and skips the repeated-failure report - a refusal is
not worth a topology re-read). The backlog and retry timer are still
serviced, so the endpoint revives when the gate reopens. The gate is
test-only (IInternalConnectionMultiplexer.AllowConnect), so the guard
keys off the live flag rather than fingerprinting the exception.

New regression test DeclinedDialDoesNotOverwriteLastException makes the
race deterministic by forcing the declined redial through
ConnectNowAsync: it fails on the unguarded code on any OS, and passes
with the guard. ExceptionFactoryTests green 5x; the AllowConnect-using
classes (ConnectingFailDetection, AbortOnConnectFail,
ConnectionFailureErrors, ConnectionDropped, ConnectionShutdown, Backlog)
green, with TotalOutstandingIncludesBacklogQueue showing only its known
pre-existing intermittency (6/6 alone, 2/2 class reruns).
…ionToken

Both accepted a token and dropped it: the private Evaluate had no token parameter, so neither the EVALSHA pair, the EVAL fallback nor the NOSCRIPT re-send could be cancelled. The token now reaches all three. The classic IDatabase shim has no token and passes default.
… builds compile

The implicit string -> RedisValue operator is [Experimental(StringToRedisValue)] in DEBUG only, so Release (and CI) built while a local DEBUG build failed on this line.
* 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: functions are opaque names; administration on IServer, not in the pipeline

* design: lists of keys and arguments, and how a script sees them

* design: the general case - declared commands, after the marc/respite RespCommandGenerator

* design: keyword clauses (prefix, suffix, count, ignore-when) as the core of the declared-command model
…cates), from main's #3343 (#3399)

* CI (Windows): let Redis 8.12 start the cluster nodes

8.12 refuses a cluster node with an unauthenticated bus port unless cluster-bus-port-protected-mode is off; older servers reject the option, so it is passed only to 8.12 and later.

* Redis 8.12 test topology, ported from main's #3343: cluster-bus-port-protected-mode in the cluster confs, client-libs-test:8.12.0, and ZSCAN may return duplicates

Replaces the version-gated CI.yml option: main already solves this in the cluster confs, and v4 follows it.
…he caller's spans (#3398)

* Scripts: build the NOSCRIPT retry from the rendered EVALSHA, not the caller's spans

The repair captured keys/args with ToArray() whenever the send had not completed synchronously. That copied the RedisValues but not the memory under them, so a caller who returned a pooled buffer after the call returned had the retry send whatever was there by the time NOSCRIPT arrived; and it cost two arrays on almost every real call.

The retry now holds a reference to the rendered EVALSHA (a reference count, no copy) and re-renders EVAL from its arguments through the command map, without re-applying the key prefix the keys already carry.

* SendWithPreambleAsync: the gate and cancellation token are required, not defaulted

Internal, so correctness wins over convenience: a caller that forgets to pass its token should not compile.
* Docs: why WithRetry has no retrying batch, and what to use instead (#3388)

A batch's one guarantee is an uninterrupted run, which a retry would break:
a batch cannot be replayed as a unit (some of it may have applied), and
re-issuing just the failed element would reorder it. Document that, and the
alternatives: pipelined commands on the retrying database for independent
work (each retried by its own category), a retrying transaction for
all-or-nothing, and a plain batch where the uninterrupted run is what matters.

Closes #3370.

(cherry picked from commit 5e2e8e4)

* Stabilize two racy tests: keyspace notification counting, and the drain-cap MOVING test (#3393)

PubSubKeyNotificationTests counted an event in the total before counting its key. Multi-node
notifications arrive on several reader threads, so the last event could complete the run while
another, already in the total, had not yet counted its key: the per-key check came up one short
(expected 51, actual 50). Count the key first.

MovingWaitsForSlowCommandsThatFitInsideTheDrainCap needs exactly one 3s command in flight, but
SetLatency slowed every command, and the in-process server answers one at a time: a background
INFO ahead of the PING pushed the PING's reply to ~6s, past the 5s drain cap, so the recycle
failed it. Add a SetLatency overload that holds a single command, and slow only the PING.

(cherry picked from commit f5bf0c3)

* Resp3DowngradeTests: keep publishing until the restored subscription receives (#3396)

The test published once, straight after the interactive connection came back as RESP2. The subscription is
restored separately (with a dedicated connection, on a connection of its own), and a message published before
that SUBSCRIBE lands is not delivered, so on a slow runner the test waited 10s for a message that was never coming.
It now publishes every 250ms until one arrives, still within 10s, so a subscription that is never restored still
fails it.

(cherry picked from commit e56835e)

* Port main's small 3.5.0 fixes and test hardening to v4

- #3374 (+#3376): v4 already had the inverted-check fix; its regression test comes over
  (as #3374 shipped it - #3376's TryAdoptEndpoint rename belongs with #3353)
- #3361: v4 already disposes socketless tunnel streams; its regression test comes over
- #3386: the toy server's CLUSTER SLOTS snapshot fix; the other two windows are in
  code v4 replaced (QuitAllServers, PhysicalBridge creation; v4 executors connect lazily)
- #3395: already the v4 behaviour (GetConnectionId does not dial)
- #3394: not applicable; the test it fixes went with the old core
…mary-only work, and are profiled as EXEC (#3404)

Port of main #3381 by intent. RespTransaction resolved its target with no flags, so every
transaction went to the primary: a read-only transaction sent with PreferReplica never reached
a replica. It now routes with the caller's preference, and goes to the primary when any queued
command is primary-only (DemandReplica is left alone, as in main). Queued operations now record
their command, which the escalation reads.

The transaction is also profiled again, as one EXEC record, which is what the v3 core reported;
the v4 run was unprofiled. RespExecOperation carries the record the way RespPayloadOperation
does, through a small IProfiledOperation view of Diagnostics.HostState.
…ait for queued tasks rather than peek (#3405)

A queued command's task in v4 is completed off the reader, through the thread pool, so it can
trail ExecuteAsync by a moment - unlike v3, which set every queued task complete before EXEC's
result. Awaiting is unaffected; IsCompleted straight after ExecuteAsync is not. That is the
race behind #3402's example, which net481 reproduced on every run.

- RespRetryTransactionExecutor notes its proxy task (NoteDispatchedTask), so TaskBridge returns it
  as-is rather than wrapping it in a second completion source completed from a pool continuation.
- QueuedResultTests: RetryTransactionFireAndForgetSharesOneCompletedTask waits, bounded, instead
  of asserting IsCompleted; QueuedTaskCompletesPromptlyAfterExecute covers plain and retry
  transactions, with and without an async state.
- docs/Transactions.md: fetch queued results by awaiting, not by peeking; note the change from v3.
…outing, subscribe/unsubscribe race (#3406)

* Expose `HashSlot(RedisChannel)` on `IConnectionMultiplexer` (#3366)

Fixes #3365.

There was no public way to ask which hash slot a `RedisChannel` is routed by. The usual workaround is `HashSlot(new RedisKey(channel))`, which hashes the channel's name as a key. It gets two cases wrong: a configured `ChannelPrefix`, and single-key keyspace channels, which are routed by their key. This exposes the existing `ServerSelectionStrategy.HashSlot(in RedisChannel)`, which is what routing actually uses and handles both.

- **New `IConnectionMultiplexer.HashSlot(RedisChannel)`**, implemented by `ConnectionMultiplexer` (delegating to `ServerSelectionStrategy.HashSlot(in RedisChannel)`). Also forwarded by `MultiGroupMultiplexer` and the test fixture's `NonDisposingConnection`.
- **`ServerSelectionStrategy.HashSlot(in RedisChannel)` now returns `NoSlot` (`-1`) for multi-node channels** (`IsMultiNode`, e.g. `KeySpacePattern`/`KeySpacePrefix`), which are subscribed on every node rather than routed by slot. Internally, slot-based routing is unaffected: the maintenance migration check only considers sharded channels, and multi-node subscriptions never select a server by slot.
- **`[OverloadResolutionPriority(1)]` on the existing `HashSlot(RedisKey)`**, on both the interface and `ConnectionMultiplexer`. `string` and `byte[]` convert implicitly to both `RedisKey` and `RedisChannel`; the channel conversions are `[Obsolete]`, but that doesn't remove them from overload resolution. Without the attribute, `HashSlot("key")` becomes ambiguous (CS0121). I checked this: removing it breaks existing calls in `ClusterTests` and `HotKeysTests`. This follows the precedent of `RedisChannel.KeySpacePrefix`, including the framework shim for older TFMs.
- **`PublicAPI.Unshipped.txt`** entries.

- **A new interface member.** This adds a member to `IConnectionMultiplexer`, which is a break for anyone implementing it outside the library. Happy to change the shape (e.g. an extension method) if you'd rather avoid that.
- **The priority attribute on an existing member.** Adding it doesn't change any signature, so it isn't a binary break. Compilers that don't understand the attribute would still see the ambiguity for `string`/`byte[]` arguments.
- **Plain literal and pattern channels.** These return the slot of the (prefixed) name: that's the slot this client routes them by, which decides the node it subscribes on, rather than a server-side slot constraint. Multi-node channels return `-1`. As with `HashSlot(RedisKey)`, it returns `-1` when not connected to a cluster.

- **New `ChannelHashSlotUnitTests`**, against the in-process server in cluster mode:
  - a sharded channel has the same slot as the same-named key;
  - with a `ChannelPrefix`, its slot is the prefixed name's;
  - a `KeySpaceSingleKey` channel has its key's slot;
  - a plain literal channel on a cluster has its name's slot;
  - multi-node channels (`KeySpacePattern`, `KeySpacePrefix`) return `-1`;
  - standalone returns `-1`;
  - `string` and `byte[]` arguments still bind to the key overload, both through `ConnectionMultiplexer` and through the interface.
- **Builds** for all of `StackExchange.Redis`'s TFMs with no warnings.
- **Existing tests:** all `*UnitTests` classes pass on `net10.0`, and CI is green on Ubuntu and Windows.

(cherry picked from commit f80bdd4)

* A publish that demands a primary does not follow a subscription onto a replica (port of main #3380 / #3357)

v4's publish used the server the channel is subscribed on whenever there was one
(ResolveForChannel). After a promotion that server can be a replica, and a DemandMaster
publish then failed with the new primary known. ResolveForChannel now carries the publish's
flags, and the subscribed server is used only when it satisfies the primary/replica demand
(GetPublishServer, as main). Main's PublishRoutingUnitTests come over unchanged: 6 of 8 fail
without this change.

(cherry picked from commit 97d17b7, by intent)

* Pub/sub: don't orphan a subscribe that races the last unsubscribe of the same channel (port of main #3363)

v4 had main's race: adding a handler and retiring the channel's last one were not atomic, so a
handler could land on a subscription being removed and never fire.
SubscriptionRegistrationRaceUnitTests failed on v4 before this; it passes now.

The patch applied to v4's RedisSubscriber as-is. In Subscription, the multi-node
UnsubscribeFromServerAsync now issues every UNSUBSCRIBE through v4's SendAsync before awaiting
any of them, so all are written while the registration lock is held, as main's version does.

(cherry picked from commit d278bf6, by intent)

---------

Co-authored-by: Arad Alvand <aradalvand@gmail.com>
…vers (port of main #3353, #3376) (#3407)

v4 already keeps overlapping restores apart while one is in flight (HasSendInFlight, standing in for
main's claim), but recorded every acknowledgement unconditionally. A restore acknowledged by a second
server after the in-flight window (it is bounded by time) replaced the recorded server while the first
registration stayed live, delivering every message twice (#3336).

- TryAdoptEndpoint: a single-node subscription refuses an ack from a different server while its
  recorded one is live; the settle path then unsubscribes the stray (fire-and-forget, pinned to that
  server). Multi-node subscriptions adopt every ack.
- Only an internal restore defers to the attempt in flight, and counts as a pending change (1, not 0);
  a user subscribe sends its own and returns once that is acknowledged, as main's review follow-up.
- Clearing a stale recorded server is a compare-and-swap (EnsureSubscribedToServer[Async],
  RemoveIncorrectRouting, RemoveDisconnectedEndpoints), so a live server recorded by a concurrent ack
  is not wiped.

Main's SubscriptionRestoreRaceTests come across with the old-core sends replaced by v4's; all 16
failed on v4 before this. The fire-and-forget overlap case expects 0 rather than 1 from the deferred
restore, because v4 records a fire-and-forget subscribe's server when it is sent. Main's
MultiNodeSubscriptionTrackingTests (#3376's rename) applies as-is.
… restore and the heartbeat (port of main #3368) (#3408)

Unsubscribing a channel's last handler retires its subscription on the client whether or not the
server-side unsubscribe succeeds. v4 had main's gap: a declined (BUSY, LOADING, MASTERDOWN) or
timed-out UNSUBSCRIBE, or one sent while the SUBSCRIBE was still unacknowledged, left the server
subscribed with nothing left to clean it up until the connection was replaced.

- Subscription: a retiring state readable without the registration lock, plus a retry-needed flag
  consumed before re-issuing, so a slow reply is not re-sent on every heartbeat. Restore paths skip
  retired subscriptions.
- The UNSUBSCRIBE is never sent as fire-and-forget, though a caller who asked for that still does
  not wait, so a declined one is always observed. An incomplete one records the server and is
  tracked by the multiplexer, which re-issues it from the heartbeat and from EnsureSubscriptions
  unless a newer subscription owns, or may yet claim, that server.
- An unsubscribe while the subscribe is in flight goes out behind it on the same connection, so
  the caller does not return with the server still subscribed. An ack for a retired subscription,
  or a stray for a live one, is unsubscribed as a tracked retirement.
- Self-correction: an older UNSUBSCRIBE that lands after a newer subscription for the channel was
  restored onto the same server re-subscribes that one.
- The synchronous Unsubscribe surfaces the server's exception rather than an AggregateException.

Also from main's SubscriptionRestorationTests, which #3353 created and #3407 missed:
- a timed-out subscribe's server is tracked as a possible stray, since its late ack reaches nobody
  in v4;
- an internal restore that deferred to an in-flight attempt is re-driven when that attempt fails;
- UnsubscribeAsync's task carries the subscriber's async state (an existing v4 bug).

Main's FailedUnsubscribeUnitTests (14 of 18 failed on v4) and SubscriptionRestorationTests come
across with old-core sends replaced by v4's; the bridge-identity test keeps its intent (restored
on the new connection, and delivers) without the PhysicalBridge assertions.
…tion stays up (port of main #3387) (#3409)

A subscribe that fails (declined with BUSY, timed out, or never written) keeps its handler
registered, so the subscription is restored when the subscription connection is replaced. Until
then nothing retried it, so with the connection up the caller stayed deaf indefinitely (#3371).
v4 had the same gap.

- A subscribe is never sent as fire-and-forget on the wire. A caller who asked for that, including
  the restore after a reconnect, still does not wait, but a declined subscribe is now observed
  rather than completing when written.
- A failure that can pass (a timeout, a connection failure, or a refusal reflecting the server's
  own state: FaultContext.NotApplied) records a retry owed (IsTransientSubscribeFault, as main).
- The heartbeat consumes that and re-drives each wanted subscription that has no server, on a
  server whose subscription connection is up; one that is down asks for another look next time.
  An exception in the sweep is reported once until it runs clean.
- docs/Basics.md: what happens when subscribing fails, and what SubscribedEndpoint returns.

A fire-and-forget subscribe now records its server on the acknowledgement rather than on send, so
the overlapping-restore test's fire-and-forget case goes back to main's expectation (the deferred
restore counts as a pending change).

Main's FailedSubscribeUnitTests (44 cases) apply as-is; with the retry stubbed out, 14 fail.
…port of main #3301) (#3410)

Main's sentinel rework applies to v4 almost unchanged: the sentinel file is main's, with the role
re-read for a reported primary that is still a replica going through v4's TryRefreshRole (ROLE)
rather than main's CheckInfoReplicationAsync (INFO via the old bridge).

- READONLY on a sentinel-managed connection: main hooks ResultProcessor's common error handling;
  v4 does the same in RespClientConnection.TryHandOff, which sees every reply. It only marks the
  node as a replica; the sentinel heartbeat resolves the primary.
- ConnectImplAsync gains main's endpoints and synchronousConnect parameters alongside v4's
  groupClientCache.

Two v4 core bugs the new tests exposed:

- RespTopology.WantsRoles was decided from the configured endpoints. A sentinel-managed connection
  is configured with the sentinel and handed the primary and replicas separately, so it never
  re-read roles on a reconfigure, and a switch to a primary it had not seen left the demoted node
  recorded as a primary for good (SwitchRequestedDuringDiscoveryIsReplayed). It now uses the
  multiplexer's own endpoints, and is always on for a sentinel-managed (non-sentinel) multiplexer.
- The core's per-endpoint callbacks created a ServerEndPoint when asked for one. A heartbeat role
  read that captured an executor just before its endpoint was retired failed with "no connection",
  and describing that failure re-created the retired server, which then kept the client on the node
  sentinel had told it to leave (SeededClientLeavesTheSentinelHost..., intermittently, under load).
  ModelledServer, and the no-connection message, now only look the server up.

Test adjustments for v4:
- HandlerSubscribedWhileStuckReceivesMessagesAfterRecovery: v4 does not queue a subscribe with no
  server; it registers the handler and completes, and the subscription is restored on connect.
  The test's point (the handler receives messages after recovery) holds.
- FailedInfoWriteDoesNotCountAsAReplicationCheck asks TryRefreshRole.
- ConnectionsTo counts the dedicated subscription socket via the core: v4's IsSubscriberConnected
  says subscriptions are available, not that their lazily dialled socket is open.

Co-authored-by: rebaseandpanic <rebaseandpanic@proton.me>
…role re-read (#3385, #3391, #3384) (#3411)

* Sentinel: follow the replicas sentinel lists, not only on a switch to a new primary (#3385)

* Sentinel: follow the replicas sentinel lists, not only on a switch to a new primary

A managed connection read SENTINEL REPLICAS only at connect and when a switch
named a primary at an address it had never seen. A replica that left stayed
held, its bridge reconnecting for the life of the connection; one that joined
was never used (#3378).

The managed connection's replicas are now reconciled every ConfigCheckSeconds
from the sentinel connection's heartbeat, and at the next heartbeat after
+slave or +reset-master:

- a listed replica we do not hold is added once sentinel does not hold it down
  (s_down/o_down/disconnected), so a replica down during a rolling restart joins
  on a later run;
- a node is retired only when it is not the sentinel-reported primary, is
  disconnected, and three consecutive periodic replies leave it out or hold it
  down. A connected node is kept whatever sentinel says; an empty reply, or a
  run an event started, retires nothing.

It stands aside while a switch, reconnect or reconfigure is running, and holds
the reconfigure gate while it changes the endpoint set.

Claude-Session: https://claude.ai/code/session_01DUpQ8dy8FLBwADei2VzLmZ

* Move the replica log event beside the server-retirement one

Claude-Session: https://claude.ai/code/session_01DUpQ8dy8FLBwADei2VzLmZ

* Update #3301's sentinel tests for the replica reconcile

Three tests asserted that a dead replica stays held, or that a newly listed one is not added, with no change of
primary. That is the behaviour #3378 changes: with ConfigCheckSeconds = 1 the reconcile retires such a replica
after about three seconds, so the assertions raced it (and lost on net481 in CI). They now wait for the replica
set to follow sentinel, and keep their checks that primary recovery is not kept alive.

Claude-Session: https://claude.ai/code/session_01DUpQ8dy8FLBwADei2VzLmZ

* Sentinel: don't re-read topology after repeated connect failures (#3391) (#3392)

Under sentinel, the connect-failure refresh re-read the endpoints we already hold, dialling the
dead node while holding the reconfigure gate. Repeated every interval, that starved the replica
reconcile (which stands aside while the gate is held), so a dead replica sentinel had dropped was
never retired. Sentinel is what follows the topology there, so a sentinel-managed connection now
skips the refresh, as it already defers READONLY handling to the sentinel owner.

* Re-read server roles promptly when a primary answers READONLY, without sentinel (port of main #3384)

A primary demoted in place (REPLICAOF, or a sentinel failover whose +switch-master was missed)
drops no connection, so writes kept going to it until the next periodic role check. A READONLY
reply from a node still treated as a primary now re-reads the role of every connected node, at
most once a second per multiplexer (main's OnReadOnlyReply / TryClaimReadOnlyRoleCheck).

On v4 the hook is the READONLY check in RespClientConnection.TryHandOff (added for #3301), which
now splits as main's ResultProcessor does: sentinel-managed marks the node as a replica,
otherwise OnReadOnlyReply. The re-read is TryRefreshRole (ROLE) rather than INFO replication.

Test adjustments: ReadOnlyReplyUnitTests counts ROLE as a role read too; and in the window
between the demotion being noticed and the new primary elected, v4 refuses the write client-side
(the node is now known to be a replica) where v3 had no connection, so both count as "no
writable server yet".
…3382) (#3412)

A replica answering -LOADING is left out of selection for a probe interval, and a
command the router placed is re-issued from the read loop to the next eligible server,
the way -MOVED is followed. Routed sends are stamped with an internal RoutedFlag so
IServer-pinned commands keep the server's answer. Also: DemandReplica no longer falls
through to the primary when replicas are known but none is selectable.
ReauthenticateAsync and its options/failure type are taken from main; the connection walk
moves to RespConnectionManager: AUTH on every live ordinary connection and on dedicated
subscription connections that can take it, recycling (AllowReconnect) a RESP2 one in
subscriber mode. IServer ad-hoc AUTH is mirrored onto the subscription connection.
Ports BITRANGEINTARRAY, set-member expiry (SADDEX, S[P]EXPIRE[AT], SPTTL,
SPEXPIRETIME, SPERSIST), BLESS and ZMOVE/ZMOVEMEMBER onto the v4 core as
group methods (Bitmaps.PositionsAsync, Sets.AddWithExpiryAsync /
ExpireAsync / PersistAsync / GetTimeToLiveAsync / GetExpireDateTimeAsync,
Keys.BlessAsync / UnblessAsync / BlessFlagsAsync, SortedSets.MoveAsync /
MoveByScoreAsync / MoveMembersAsync), with main's IDatabase/IServer
signatures delegating to them, plus CommandTrace.CpuTime, BlessFlags,
the RedisFeatures/KeyNotificationType additions and SER011.

Round-trip and reply tests move to the v4 harness with main's bytes;
the new commands get retry categories, which v4 requires of every command.
…3415)

Moves the 71 entries main promoted for 3.5.0 from PublicAPI.Unshipped.txt to
PublicAPI.Shipped.txt. v4's own unshipped surface stays where it is, and main's
version.json bump does not apply to v4.
… on demand (#3416)

* v4: honour RequestBufferPool for request staging; hash requests on demand

A request held by an operation until it is written (anything past the 512-byte inline
buffer) is now copied into the configured RequestBufferPool rather than ArrayPool.Shared,
as v3 buffered every request there. With no pool configured nothing changes.

RespRequest no longer hashes its payload at construction: GetHashCode computes it when
asked, which only the client-side cache does, so uncached sends - and every write, cache
or not - never hash the value.

* v4: hash a request once on the cache path, not once per key copy

The frame - the one instance the cache path passes by reference - computes the hash on first
use and every request derived from it carries it: lookup views, the detached fill key, the
stored copy. A miss-and-store hashed 7 times with on-demand hashing alone; now once, as does
a hit. 0 marks 'not computed', so a real 0 maps to 1.

A DEBUG-only per-thread counter lets tests pin the counts; they skip in Release. AGENTS.md
now steers local test runs to Debug, where DEBUG-only checks actually run.

This branch was successfully deployed

1 active (outdated) deployment
release — 0d18c571 Deployed Nov 13, 2026 by mgravell via publish #27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants