Skip to content

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

Draft
mgravell wants to merge 863 commits into
mainfrom
v4
Draft

mgravell wants to merge 863 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)

The 311-test family is fully green under the coupled move - 36 failures in 6m30s to 0 in 4s -
but it was not representative, and the full suite says 126. Recording that plainly, because
optimising against a slice made the position look much better than it is.

Grouped, it is one piece rather than a scatter: maintenance notifications are 70 of the 126
across six test classes, and they are a coherent feature - the opt-in is sent only by the
shipped handshake, and the pushes, relaxation windows, retention and replay all hang off a
connection that has opted in. This core neither opts in nor would recognise the pushes.

That reframes the census in 9o: the connect path was 82% of remaining Message traffic by
volume, but by test weight maintenance is the largest thing still on the shipped bridge.

One run of this build was killed at the 25-minute timeout where neighbours took 3.5 minutes,
so 126 is from a run that completed rather than a stable average.
The opt-in is the feature's gate: the windows, retention, replay and migration handling all
hang off a connection that has asked, and one that has not asked is never told. With this
core carrying the commands and only the shipped bridge opting in, the client was being warned
on a connection it no longer used.

Sends CLIENT MAINT_NOTIFICATIONS ON [moving-endpoint-type <t>] and reads the reply, which is
why it is asked from here rather than written blind - "agreed" and "declined, because X" are
different facts. Both decisions are borrowed rather than restated: the shipped
ShouldRequestMaintenanceNotifications and MaintenanceMovingEndpointTypeLiteral gained
overloads this core can call, and the shipped callers delegate to them.

moving-endpoint-type needed real plumbing rather than an approximation. For Auto the type is
derived from the address actually reached and whether the connection is encrypted - not the
endpoint dialled, which is usually a name - and only whoever built the transport knows
either, with encryption sometimes the tunnel's decision. RespTransportFactory.ConnectAsync
now reports both. Guessing internal where it is external sends a client to an address it
cannot reach when a shard moves.

Fixes ~11 maintenance failures; 58 remain and all need the push path. Design notes 9s records
its shape: lift PhysicalConnection.OnMaintenanceNotification's ~270 lines of deliberately
tolerant parsing out so both dispatchers call it, rather than writing a second copy of rules
that exist for go-redis compatibility.
9s said the 58 remaining failures wanted the push path and that the move was to lift the
parse rather than copy it. It was a smaller refactor than it looked: eight of the eleven
members were already static, and the three that touched 'this' wanted exactly four facts -
the server, whether the connection is established, the address it reached, and a trace sink.

So OnMaintenanceNotification becomes ReadMaintenanceNotification taking those, the instance
method is a four-line wrapper, and RespPushDispatch calls the same routine. The ~270 lines of
deliberately tolerant parsing are untouched: no second spelling of the optional sequence id,
the movable time, SMIGRATED's nested triplets or the explicit nulls.

It returns void rather than OutOfBandResult, which is private to PhysicalConnection and a
different enum from the new core's: a maintenance notification is never a reply, so the frame
is consumed either way and there is nothing to signal.

OnMovingAnnounced took a PhysicalConnection and used it for one thing - the address the
announcing connection reached - so it now takes the address. That is the third time this
session that 'the address we actually reached' turned out to be the real parameter hiding
behind a connection.

Maintenance failures 58 to 17. Shipped suite fully green.
ReconcileMaintenanceNotifications decides whether an unavailable-but-Enabled feature should
fail the connection. The rule and its wording are now an internal overload returning the
failure message; the shipped caller turns it into RecordConnectionFailed and this core throws
out of its handshake, which is the same thing in its terms - a handshake that throws fails the
connect, and "Enabled means required: no notifications, no connection" is exactly that.

And a correction. This core had been asking for the opt-in only when RESP3 was actually
negotiated, rather than on intent as the shipped core does - strictly fewer round trips, same
end state, apparently better. It is not better:
MaintenanceOptInClientTests.AutoIsOffWhenTheServerDowngradesToResp2 requires the server to
have SEEN the opt-in and the client to disbelieve the acceptance anyway. That sequence is
observable, deliberate and covered, so skipping it is an unflagged behaviour change dressed
up as an optimisation. Now asks on intent, with the reasoning written where the temptation is.

Also: a group member never asks but must warn that it is not asking, because a caller who
wrote maintNotifications=Enabled asked for a guarantee - silently suppressing it is the gap
the warning exists to close. And the suppressed path still reconciles, since Enabled over
RESP2 never gets as far as asking and failing it is the point.

Maintenance 70 to 8; the flagged suite is at 3, shipped fully green.
A MOVING handoff exists to stop using a connection before the server closes it, and under the
flag that connection is this core's - so recycling only the shipped bridges replaced the
sockets nobody was using and left the one carrying commands to be cut mid-flight.

Both halves of DrainThenRecycleAsync now span cores. HasCallerWork sums this core too, and
deliberately coarsely: the question is whether recycling now would lose somebody's work, and
over-counting costs a short wait where under-counting costs the command. The recycle itself is
DropConnection(reconnectImmediately: true), which already existed for the failure simulation.

And it has to be reported, which is the half the test judges. The first attempt recycled
correctly and still failed, the assertion saying so in its own words: "the recycle should be
reported as a MaintenanceHandoff rather than silently". The replacement raises
ConnectionRestored, so a silent drop leaves a consumer with an unpaired restore, and the
failure type is what says it was deliberate rather than a fault.

Maintenance 8 to 6; flagged suite at 4, shipped fully green. What remains is retention/replay
(where the two cores disagree about what "established" means for a catch-up copy), the
cross-node event dedup, and two relaxation-side tests - design notes 9v.
The three retention tests were not about what "established" means - that was the wrong guess
in 9v. They were an ordering bug, and the same one the configuration channel hit at the other
end of this method: DiscoverServerConfigAsync sends the maintenance opt-in, which makes the
server replay whatever it retained for the shard immediately, and OnPush was not wired until
afterwards. The replay arrived at a connection with no dispatcher and was dropped as
unrecognised, so the "(catch-up)" line the tests look for never appeared.

Moving the OnPush and DeliversArrays assignment above the discovery block fixes all three.
The rule was already written a few lines further on for the configuration channel subscribe;
the opt-in is the other thing that asks a server to start talking, and both now sit below the
wiring.

Maintenance 6 to 3; flagged suite 4, shipped fully green.
With everything from the connect path through maintenance landed, the coupled move is at 59
failures, down from 126. Maintenance was 56% of the first number and is 3 of this one.

Recording the shape as well as the count, because it has changed: there is no dominant
cluster left - 25 classes, the largest 8. Every step from the connect verdict through the
push ordering was one thing blocking many tests and paid for itself several times over; a
25-class tail with no cluster above 8 will not behave that way, and the honest expectation is
that it costs roughly its length.

Two entries are known not to be work: RetirementUnderMaintenanceTests is the premise question
already analysed in 9h/9i, and SentinelTests keeps its own bridge by design.

Design notes 9x, including which of the remaining groups look like one cause rather than
several.
All seven ExceptionFactoryTests failures under the coupled move were one cause: the socket
and pipe byte counts were missing from the message. They were missing correctly. These tests
hand in a DETACHED ServerEndPoint with no bridge, so GetBridgeStatus falls through to
whichever core has an executor for that endpoint - and this core reports -1 for
BytesAvailableOnSocket, BytesInReadPipe and BytesInWritePipe on purpose: it polls no socket
and has no pipe, so there is no number to give. ExceptionFactory omits a negative rather than
printing it, which is the honest outcome; filling them with zeroes would be inventing data in
the one message people read when diagnosing a timeout. That core reports the equivalent in
its own words, as the outbound/inbound figures on its timeouts.

So the counters that exist on every core are asserted unconditionally, and the three that
belong to a socket-and-pipe implementation are asserted only when that implementation
supplied the status - asking the same question GetBridgeStatus asks, which is whether the
other core has an executor for the endpoint rather than whether it is connected: an endpoint
it tried and failed to reach still has one, and still supplies the status.

Green in both configurations.
Three parts of one gap: this core treated HELLO purely as the RESP3 negotiation, where the
shipped handshake treats it as discovery that happens to negotiate.

HELLO ON RESP2. The reply carries the server's version, mode and role, so asking is cheaper
than the INFO sections that are the alternative source for all three - which is why the
shipped handshake sends a bare HELLO even with no intention of speaking RESP3. The protover
asked for is the one actually wanted: asking for 3 while configured for RESP2 would be asking
to be upgraded against the caller's wishes, so RESP2 asks for 2, which cannot change the
protocol. HelloHandshakeTests asserts HELLO is issued for both, with the matching protover.

CREDENTIALS IN HELLO when AUTH is unavailable. A command map that disables AUTH is not a map
without credentials - a proxy can require them and refuse the command - and HELLO is then the
only thing that can authenticate the connection. This core sent AUTH unconditionally, so such
a deployment got a RedisCommandException out of the handshake and no connection at all. Now
it makes the same split as the shipped handshake, and never sends both.

AND WHETHER TO SEND IT AT ALL is ConfigurationOptions.TryHello's decision, not a command-map
check: a deployment also opts out by declaring an assumed server version older than 6.0
(defaultVersion=5.0), and TryHello is the one place that weighs both. Passed in rather than
re-derived.

HelloHandshakeTests 5 failures to 1 under the coupled move; the remainder is the SET replica
probe, which is its own gap. Shipped suite green.
…when nothing else can

A node that prefers hostnames and announces none reports "?", which parses perfectly well
into a DnsEndPoint nobody can dial. The redirect path already refused these - IsUnroutableTarget
exists for it - but ClusterSlotsHandler.TryReadHost only checked for an empty host, so the
placeholder went into the slot map and commands were routed at a server called ? and expired in
the backlog. UnroutableRedirectUnitTests reads that as a connection exception where a server
exception was expected: the client was dialling instead of letting the server's error stand.
Fixed by sharing the predicate rather than copying it - a server can name a placeholder anywhere
it names an endpoint, and the forms are identical in all of them.

Also adds the SET replica probe, the last of the four gaps itemised in 9k. With HELLO, INFO and
CONFIG all unavailable nothing will answer "are you a replica?", so the client asks by
attempting a write and reading the refusal: NX so it cannot overwrite, PX 1 so it cannot
persist, the client's own id as the key, and never in a cluster where the answer would be MOVED.

The probe needed a second fact to be right. Firing it whenever INFO was unavailable broke
NoReplicaProbeWhenHelloTellsUsTheRole, because HELLO carries the role and a server that
answered one has settled it. So HELLO's role field is now read - free, and it publishes
IsReplica directly - and the probe is skipped when the role is known, which matters because the
probe needs a key and an ACL can forbid that (#2968).

UnroutableRedirectUnitTests 6 to 0, HelloHandshakeTests 5 to 0. Shipped suite green.
CLIENT LIST was ported to the context some time ago; CLIENT KILL next to it
still built a Message, so under the engine flag it went down a pipeline with
nothing on the other end. ClientKillTests reads that as a cancelled task: the
command never reached a server, which is not something to report as a kill
count.

It lands in RespDiagnostics under protest, as ClientListArray's own remarks
predicted - killing a client is administration, not diagnosis. An admin group
is the eventual home, and inventing one for a single verb would decide the
shape of a public surface as a side effect of a port.

Both public spellings - the filter object and the four loose arguments - now
render through ClientKillFilter, which is where replica-vs-slave is decided for
this server; a second encoding would be free to disagree about that. The
positional CLIENT KILL <addr> form keeps a method of its own, because its wire
shape and its reply (+OK, not a count) genuinely differ, and it is the only
form the oldest servers accept.
…rser

Six things, all one thread: the facts this core discovers about a deployment
were staying inside it, so surfaces that answer from ServerEndPoint went stale
or empty.

Roles were a one-way push. RespTopology learns them from three places - a ROLE
reply, the owners in a CLUSTER SLOTS reply, and the primary a -MOVED names -
and recorded them nowhere else. But ServerEndPoint.IsReplica is what refuses a
write to a replica, read by both RespEndpointExecutor and the shipped selector,
so after a failover this core knew the truth and the flag stayed stale. The
consequence is worse than staleness: the refusal is client-side, before a byte
goes out, so no -MOVED comes back and nothing corrects it. RoleLearned is the
other half of the push ServerEndPoint.IsReplica already made inward; the bounce
back terminates on the first hop, because OnRole's existing "changed?" check
already matches by then.

RefreshTopologyAsync gives this core the topology refresh it never had.
Discovery happens at handshake, once per deployment, so every later change
arrived via the shipped AutoConfigureAsync sweep - and a core with live
connections had no way at all to learn the deployment had moved, because
nothing reconnects. It asks CLUSTER SLOTS once for the deployment and CLUSTER
NODES per connection, mirroring that sweep.

CLUSTER NODES is now asked at handshake too, per connection, which is the
deliberate opposite of the CLUSTER SLOTS rule immediately above it: SLOTS is a
fact about the deployment and one answer serves every connection, while NODES is
answered from the point of view of the node asked and `myself` is the part that
matters. ServerEndPoint.ClusterConfiguration is that per-server view, and
IServer.ClusterConfiguration, InventKey (via GetServableSlot) and the tracer key
are all nothing but a read of it. One SetClusterConfiguration call also drives
UpdateClusterRange, ApplyClusterRoles and UpdateNodeRelations.

Because of that last point the SLOTS view has to be held per core and handed to
every server, not just whichever node answered: SetClusterConfiguration reads
ServerEndPoint.ClusterTopology to decide which reply drives the shipped slot
map and falls back to the staler NODES view when a server has none, so a second
connection publishing its own NODES would clobber a migration that SLOTS alone
reported. ClusterTopologyUnitTests.SlotMapIsDrivenByTheSlotsView is built to
catch exactly that.

The CLUSTER SLOTS parser is now shared rather than duplicated. This core's
handler was ~90 lines producing a reduced shape that could route and nothing
else: it read past the node ids and discarded them, so ClusterTopology could
not be populated here and identity-merging - what stops one node becoming two
ServerEndPoints when a reply names it differently, the TLS/SNI case - had
nothing to work from. The shipped parser already reads all of it and all but one
line is pure RespReader work, so ClusterSlotsResult.Parse is exposed and the
handler is four lines over it. That also subsumes the placeholder check added
separately here: the shipped ResolveEndPoint had always refused null/""/"?" and
an out-of-range port, which is exactly RespRedirect.IsUnroutableTarget's
coverage. Two implementations of one rule was the real defect.

Finally, GetEndpointsFromClusterNodes lets this core do the reading when this
core owns the connection - refreshing first, then taking the published views,
instead of sending its own CLUSTER SLOTS and CLUSTER NODES. That matters beyond
the round trips: a shipped Message write calls GetBridge with `create` defaulted
to true, so those two commands were the only thing still dialling the shipped
interactive bridge, and every endpoint carried two sockets with one doing the
work (ClusterTests.ConnectUsesSingleSocket reads that off the counters).

Ownership is tested rather than assumed, and that is load-bearing: under the
flag alone this core connects lazily, so a deployment nobody has sent a command
to has no connection here and the shipped bridge is the only thing that can
answer. The published view is non-null regardless, because shipped autoconfigure
fills it, so without the IsInteractiveConnected check the cached path reads a
cache nothing is refreshing and sends nothing - which left a slot-migration
notification provoking a pass that re-read nothing at all, measured by
MaintenanceTopologyRefreshTests and PeriodicTopologyRefreshTests counting
CLUSTER commands at the server.

Connection state now answers from whichever core holds the connection, as
IsConnected and OperationCount already did.

Shipped: green. Flagged: 8, in its usual rotation band. ClusterTests with the
coupled patch: 18 -> 0, and 19m51s -> 17s.
Three things the shipped bridge does from its heartbeat that this core never
learned, all of which matter for a client that outlives a deployment change.

Nothing re-dialled a down endpoint. OnHeartbeat returned early when there was
no live connection, so this core only ever dialled on demand: a connection that
went away stayed away until a caller happened to need it again, and an endpoint
whose FIRST dial failed was never tried again at all.
ConnectFailureRefreshTests reads that as "expected the endpoint to be retried
repeatedly, but saw 0 attempts".

RetryConnectIfDue fixes it, and the gate is the load-bearing part: retry only
where a dial has already been attempted or one has already succeeded. Either
means the endpoint is wanted; an executor nobody has used has neither and is
left alone, so lazy connection is preserved exactly - RespConnectionStateTests
is the check on that.

Repeated connect failures provoked no topology read. The mechanism already
exists and is already well-reasoned - ServerEndPoint.OnRepeatedConnectFailure,
above a threshold, rate-limited to ConfigCheckSeconds, with the "37 hours across
a node replacement" story in its remarks - and this core simply never called it.
It now reports the count and leaves the restraint where it belongs.

A dying connection raised no ConnectionFailed, and this one has consequences
past the test suite: it is a documented public event and the thing callers wire
up to notice a deployment moving underneath them. This core raised it for a
tripped circuit breaker and a maintenance handoff, and for nothing else, so an
ordinary dead socket was silent. Now raised from RecordFault, where the fault is
already computed - with the same distinction shipped makes, since a retirement,
a maintenance recycle or a dispose is not a failure. RecordFault therefore takes
wasRequested exactly as PhysicalBridge.OnConnectionFailed does, and the recycle
path passes it: that path already announces its own MaintenanceHandoff, so a
socket failure beside it was both redundant and misleading, which
MaintenanceNotificationTests asserts directly.

ServerEndPoint.LastException now spans both cores. It is what ExceptionFactory
collects to explain WHY no connection was available, so reading only the shipped
bridges meant "unable to resolve physical connection" arrived with no inner
exception and nothing to act on. Same treatment as IsConnected, OperationCount
and the connection state.

RespProtocolTests.TryConnect asked the shipped bridge for its connection id,
which under the engine flag does not exist; it asks the multiplexer, which has
answered across both cores since GetConnectionId was taught to.

Also here, as a comment rather than a change: failing the handshake outright on
WRONGPASS/NOAUTH was tried and withdrawn. It is the shape SecureTests asks for
and fixed that case, but ConfigTests.MutableOptions changes the password at
runtime and needs the connection to survive the window in which it is wrong, so
it traded one test for two. Shipped gets both by continuing and letting the
first command fail with the auth suspicion attached; that is where this core has
to arrive too.

Closes ConnectFailureRefreshTests x2, MaintenanceRelaxationTests,
ConnectionFailureErrorsTests and MaintenanceNotificationTests under the coupled
patch, which goes 21 -> 16. Shipped green; flagged at 6, its usual band.
…wn sockets

Two diagnostics gaps, both of which matter to anyone debugging a deployment
rather than to a test.

A connect failure said nothing useful. ExceptionFactory.UnableToConnect builds
its message from the faulted per-endpoint tasks of a reconfiguration, so a
connection dialled outside that wait - which is how this core is started -
left it empty, and the caller got "Error connecting right now" with no inner
exception. The reason was already recorded: the core throws exactly the right
words for, say, a client cache on RESP2 ("Client-side caching requires RESP3:
invalidation arrives as an out-of-band push..."), and they were going nowhere.

It now falls back to what the servers themselves recorded, which LastException
already spans both cores for - so any core-side connect failure explains itself:
protocol refusals, refused handshakes, socket errors.
RespInProcTrackingTests.Resp2WithACacheRefusesLoudly asks for exactly that, and
asks for it in the right terms: the reason has to reach a human somewhere.

And this core opened sockets silently. The shipped bridge narrates its whole
lifecycle into the connect log, which is the artifact users paste into issues, so
a core that is invisible in it is a support problem on its own. Added: the dial,
the transport and whether it is encrypted, the completed handshake with protocol
and server type and connection id, what discovery learned (version, role, slot
coverage), and a connection being lost or closed - with "lost" and "closed"
distinguished, since those are different events.

That takes LoggerTests.BasicLoggerConfig from 21 lines to 25 against a threshold
of 30, and I stopped there deliberately. The rest of shipped's verbosity is
per-bridge narration a bridgeless core does not have, and writing log lines to
reach a number is the wrong motivation - the ones above earn their place.

Also records, at the point of decision, what SecureTests actually needs: two
levers were tried for it and both were wrong. Failing the handshake on
WRONGPASS/NOAUTH takes ConnectAsync down with it, which ConfigTests.MutableOptions
forbids - it requires the connect to succeed with AuthException set. Marking the
endpoint unselectable changed nothing, since a single-endpoint standalone is
still chosen. What is missing is the command path: shipped converts a
NOAUTH/WRONGPASS reply into auth suspicion plus a connection failure, and this
core passes the server's error through untouched.

Shipped green. Flagged at 4, the lowest it has been.
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.
…e) and Prefixes as RedisKey (#3304)

* client cache: configured once per connection group (MultiGroupOptions.ClientCache, inherited; a member's own is refused), and Prefixes as RedisKey over a private byte snapshot

- MultiGroupOptions.ClientCache / Builder.ClientCache: the one place a group's cache is set. Each member keeps a cache of its own and the group answers from the active one, so members must cache alike or a failover would change what callers get; a member whose ConfigurationOptions.ClientCache is set is refused (at connect and at AddAsync). Plumbed like the group circuit breaker: alongside the configuration, never written into it; a sentinel member gets a clone, since its cache is built with the connection, and a sentinel connection itself never builds a cache.
- CacheOptions.Prefixes is IReadOnlyList<RedisKey>: keys are bytes, and a prefix that is not valid UTF-8 had no spelling; a key made with WithKeyPrefix is taken whole. Rendered once to a private byte[][] that both the matcher and the handshake's PREFIX arguments read (no re-encoding on the way out); nothing of the caller's list or arrays is kept, and the getter hands out copies. Existing string call sites compile unchanged.
- GetClientCache remark: on a group it is the active member's cache at the time of the call.
- Tests: GroupCacheTests (group-level configuration, late joiner, member cache refused), prefix snapshot/bytes/prefixed-key tests. Docs: Failover.md row and section, ClientSideCaching.md "Connection groups", design ledger.

Main suite net10.0: 7898 passed, 0 failed, 167 skipped.

* docs: note the group-level cache in the caching overview and Configuration.md, and describe Prefixes as RedisKey values copied when set
…ng back to keyspace notifications (#3305)

* client cache: CacheTrackingMode.None and CacheTrackingMode.KeyspaceNotifications

Two invalidation strategies that do not use CLIENT TRACKING, and so do not
need RESP3:

- None: nothing is negotiated; entries are retired by TimeToLive and by
  local writes alone. Prefixes, if given, only bound what is cached.
- KeyspaceNotifications: the cache subscribes to __keyspace@*__:{prefix}*
  per prefix (or __keyspace@*__:* without prefixes) and invalidates the
  named key on any event. Multi-node channels, so cluster subscriptions go
  to every node, as keyspace notifications require. If the server has
  notifications disabled the subscription is silent and the cache behaves
  as None; that is documented, not checked. Prefixes are a hard boundary on
  what is cached (as under Broadcast) and must not contain glob characters.

The handshake skips CLIENT TRACKING (and its RESP3 requirement) for both.
The subscription is made after connect in both connect paths; a failure to
establish it is logged rather than failing the connect, since it is
registered first and restored with the subscription connection.

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

* client cache: CacheTrackingMode.None is the zero value

None = 0 and Default = 1, the rest shifted up one (all unshipped).
CacheOptions.TrackingMode is initialised to Default, so an unconfigured
cache still gets the library's choice; only a zeroed enum is None.

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

* client cache: Default falls back to keyspace notifications when tracking is unavailable

Under CacheTrackingMode.Default only, a cache that cannot get CLIENT TRACKING
switches to KeyspaceNotifications rather than failing the connection: no
RESP3, CLIENT disabled in the command map (known at construction), or any
server error answering CLIENT TRACKING. A named mode still fails loudly.

The switch is cache-wide, one-way and at most once: the mode-dependent state
(CLIENT CACHING frames, opt-in/by-prefix gates) is one immutable object
swapped by CAS, so the frames a non-tracking server would reject stop at
once. It flushes, starts the keyspace subscription (now idempotent and keyed
off the mode in force), and logs a warning (event 139). When CONFIG GET is
permitted and notify-keyspace-events raises nothing usable, a second warning
says so (event 140) - a diagnostic, never a refusal.

ClientCache.EffectiveTrackingMode (via GetClientCache()) reports the mode in
force. Resp2WithACacheRefusesLoudly now names Tracking explicitly, since an
unset mode over RESP2 falls back instead.

Claude-Session: https://claude.ai/code/session_01DUpQ8hTYNcGjwf1eA7R6Ss
mgravell and others added 9 commits October 29, 2026 14:59
…nge)

PR #3298 brought main's 19 commits to 2026-10-23 into v4 but was squash-merged (da8181e), so
git lost the merge parent and still counted those commits as unmerged. A trial three-way merge of
aa1e5c0 onto v4 reproduces v4's tree exactly, apart from re-adding BatchWriteFailureTests and
ConnectionFailureExceptionTests, which #3298 dropped on purpose (they drove v3 internals;
ConnectionDroppedExceptionTests covers both from the public surface). This commit takes v4's tree
and adds aa1e5c0 as a parent so future merges of main start from where they should.
…nore)

- #3303: the CycleBuffer fix itself was already in v4 (recycle resets StartTrimCount); only main's second
  test, DiscardDuringWriteKeepsLeasedBytesAfterARecycledTrimmedSegment, is new here.
- #3306: .claude/* ignored except .claude/skills/, superseding v4's .claude/worktrees/ line.
…d, the reply held until it validates (#3308)

* High-integrity mode restored: a sequence check (ECHO <token>) behind every command, the reply held until it validates

Lost with the old core: ConfigurationOptions.HighIntegrity, ResponseIntegrityFailure, the docs and the
HighIntegrity*Tests classes survived, but nothing assigned a token or validated a reply, and the test
classes passed vacuously because they only re-ran suites with the flag set.

Rebuilt as the dual of the prefix frame, at the same choke point. RESPite: RespConnection.SequenceCheckHead
makes Stage write the check (the owner's rendered ECHO head, a 4-byte little-endian per-connection counter,
CRLF) behind every request whose message is SequenceChecked, with one more pending entry naming
RespSequenceCheckSink; the reader holds a checked reply (a reservation on the receive buffer) until the
next in-band frame is the bulk string carrying the expected token, then delivers it - or faults it and
closes the connection with CreateSequenceCheckFault (a virtual). A handed-off reply (redirect, +QUEUED)
is not held but its check is still validated, so the counter stays in step across a MOVED. Close faults a
held reply like anything else pending.

SE.Redis: RespConnectionManager enables it after the handshake, interactive connections only, with ECHO
rendered through the command map (a map that disables ECHO refuses the connection rather than checking
nothing); RespClientConnection substitutes RedisConnectionException(ResponseIntegrityFailure), so the
failed command, the closed connection and ConnectionFailed all carry the shipped type; RespTransaction
marks MULTI, WATCH, the condition probes and the queued commands unchecked, so EXEC/UNWATCH validate the
span - v3's rule. The token lands in the operation's diagnostics (hi-token).

Tests the mode never had on either core: RespSequenceCheckTests (wire shape, the hold, wrong token,
missing frame, push between reply and check, split receive, buffer roll under a held reply, hand-off,
prefix + check, close while held, per-life reset) and HighIntegrityWireTests (EXEC-only checking in a
transaction, every member of a batch, the failure type and close); HighIntegrityMovedUnitTests now
asserts that checks happened on every interactive connection.

Docs: design/command-flow.md describes both framing extras (prefix, sequence check) in the trace and
adds end-to-end bullets for client-side caching (modes, opt-in/out, invalidation sources, groups) and
high-integrity mode; docs/Configuration.md says how the mode works and fails; ledger status entry.

* sequence check: test the mode before peeking the queue, so a connection without checks pays nothing per reply

* ledger: high-integrity mode measured (off path unchanged; the mode's cost on v4 and v3; the buffer-roll diagnosis and the look-ahead next step)

* sequence check: look ahead for the check before holding the reply, so the common case (reply and ECHO in one read) takes no buffer reservation

* sequence check: the checked bit rides in the request's pending entry (no second entry per command, no sink type), and the check is staged in one write

* ledger: the high-integrity mitigation measured (allocation per op back to the off path; the remaining cost is the mode's second frame each way)
…ebug builds compile (#3320)

* Parenthesize a Debug-only assertion that fails SA1407 (same as #3314 on main)

* Client cache: replace a TimeToLive-expired entry on the next fill

The fill path replaced a resident entry only when it was a refresh or the
entry had been invalidated. IsValid tracks invalidation generations only,
so an entry that had aged past TimeToLive still read as valid: TryAdd failed
against it, the fill was written off as redundant, and the key could not be
re-cached until the sweep (10s by default) removed the corpse. A steadily
read key therefore missed on every read from expiry until the sweep; with a
5s TimeToLive that is half of every ten seconds at a 0% hit rate.

An expired entry is now treated as dead in the same way as an invalidated
one. Regression test runs with sweeping disabled so only the fill path can
make it pass.

Fixes #3318

* v4 Debug build: remove the string-to-RedisValue conversions the Debug-only self-check flags

All writes, so .AsRedisValue() where the value is computed (AUTH, HELLO,
CLIENT SETINFO/SETNAME, EVALSHA hash, CONFIG GET pattern) and RedisLiterals
where it is a literal (HOTKEYS START arguments; CPU, DURATION, METRICS, NET,
SAMPLE and START added to the table). CoreBench gets the same NoWarn as its
baseline. Release builds were unaffected; local Debug builds of v4 have been
red on this since early October.
…m the sequence check (#3319)

ASKING and CLIENT CACHING are both one-shot server flags meaning "the next
command", and each is the other's next command: the server clears either
after any command that is not the one that set it (resetClient, outside
MULTI), so no order keeps both. Measured on Redis 8.9 with a slot set
IMPORTING: ASKING, CLIENT CACHING YES, GET answers -MOVED (a second
redirect, so the command fails); CLIENT CACHING YES, ASKING, GET is served
but never tracked (a stored reply would be stale until eviction); and
ASKING, ECHO, GET answers -MOVED too, so high-integrity mode broke every
ASK redirect.

The redirect is the half that cannot be given up. TryResendAsking now drops
the operation's prefix (the operation remembers and stamps PrefixDropped on
its reply; the cache refuses such a reply and counts it as RefusedUntracked)
and marks the ASKING operation unchecked, so the pair's one check lands
behind the command as a transaction's does behind EXEC. MOVED is unaffected.

Tests assert the exact bytes on a fake transport for both cases, plus a
cache-level test; the in-process server cannot produce an ASK.
…, batch profiling, API promotion (#3322)

* 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 <[email protected]>

* 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.

---------

Co-authored-by: Mohsin Ali <[email protected]>
Co-authored-by: mohsinaliwork686-rgb <[email protected]>
… dead List<RedisValue> builders go (#3321)

The v4 model is the interpolated writer: conditional clauses belong in an
operand struct that writes straight into the frame, not in a RedisValue
list spliced in as an array. HOTKEYS START and CLIENT KILL were the last
two command paths still rendering the old way.

- HotKeysStartArgs becomes HotKeysStartOperand, with the tokens as
  pre-framed RespLiterals; the STOP/RESET/GET subcommands move to
  fragments too. HotKeysWireTests pins the clause order byte for byte.
- ClientKillFilter.ToList/ToArray become ClientKillFilter.Operand - still
  the one encoding both public spellings of CLIENT KILL share - and
  ClientKillCount takes the operand instead of a rendered span. The test
  that compared against ToList now asserts the rendered frame, which also
  covers the replica/slave spelling both ways.
- Dead since the old core was deleted, called by nothing: the List-based
  GeoSearchShape.AddArgs overloads, the GeoRadiusOptions.AddArgs
  extension, and StreamIdempotentId.WriteTo(RedisValue[], ref int).
…e; treat a client-side replica-write refusal as a slot-map staleness signal (#3324)

* The library's own topology refresh must not be refused by the AllowAdmin gate, and a write refused because its routed endpoint is a replica marks the slot map suspect

Found investigating #3323 (which does not reproduce on 2.x/3.x): after a cluster
failover, a v4 client without allowAdmin=true could never repair its slot map.
RefreshTopologyAsync re-reads CLUSTER SLOTS through the published endpoint
executor, whose Validate classes CLUSTER as admin - so every refresh refused
itself, and recovery depended on a -MOVED winning the race against the demoted
node's role being learned. Once the role landed first, writes were refused
client-side before any byte went out, so no redirect ever arrived to mark the
map suspect: stale map + fresh role = refused forever, exactly the deadlock
RespTopology.RoleLearned's remarks describe.

- Validate exempts requests carrying CommandFlagsInternal.InternalCallFlag from
  the AllowAdmin gate: the gate protects the caller-facing surface, and the
  handshake already escapes it by running on the bare connection (the same
  exemption the v3 handshake got from SetInternalCall). The flag had no
  consumers in v4, so this is v3 parity rather than new semantics.
- RefreshTopologyAsync's CLUSTER SLOTS and ROLE reads, and TryRefreshRole's
  ROLE, now carry that flag.
- The primary-only-refused-on-a-replica path tells the manager
  (OnWriteRefusedByRole): slot map suspect + ReconfigureIfNeeded, one
  reconfiguration per suspicion cycle, mirroring the unroutable-redirect path.

The new tests connect with AllowAdmin=false, which is how both halves hid from
every existing test: InProcessTestServer's client config defaults it to true,
so the refresh always repaired the map before the deadlock could be seen.

* A failover's write outage is detection-bounded, not ConnectTimeout-bounded: reconfigure when an established connection is lost, and read the topology before waiting on stragglers

The #3323 harness measured ~30s of failed writes on a failed-over shard where
2.x/3.x take ~7s, in two pieces:

- Nothing happened when the established connection died. RecordFault passed
  reconfigure: false always, so the first topology re-read waited for the
  THIRD consecutive dial failure (~15s later). The v3 bridge's contract was
  reconfigureNextFailure: armed only in OnFullyEstablished, consumed on the
  next failure - so an established connection's loss asks for one
  reconfiguration, while dial failures still don't (OnRepeatedConnectFailure
  keeps judging those, rate-limited; a lost established connection cannot
  loop, because it has to be re-established before it can be lost again).
  _reconfigureOnFailure restores that contract.
- The pass that then ran spent its whole wait dialling the node that is gone:
  RefreshTopologyAsync ran after WaitAllIgnoreErrorsAsync, so the healthy
  nodes were not asked where the slots went until ConnectTimeout expired.
  The refresh only uses connections that are already live, so it now runs
  before the wait; a pass that starts with nothing live still gets its answer
  from the handshakes the wait completes (a first connection asks CLUSTER
  SLOTS itself when there is no map or it is suspect), and the cluster second
  iteration refreshes again over whatever iteration one established.

LosingAnEstablishedConnectionPromptsATopologyRefresh pins the trigger: a
QUIET client (nothing in flight to redirect, nothing to refuse), the promoted-
away node refusing reconnects (so no restore-time reconfigure), AllowAdmin
off. Red at the poll timeout without both halves; the harness measures the
outage at 9.0s against a primary held dark for 90s (v2/v3: 7.0s, with the
rest being frozen-socket detection that a real failover's socket close does
not incur).
…3325)

A configuration channel makes the dedicated subscription connection part
of connecting (#3310): ActivateServer dials it eagerly, but the dial is
fire-and-forget by design, and the reconfigure connect wait covered the
interactive leg alone - so on a loaded machine ConnectAsync returned
while the library's own broadcast channel was still dialling.
ConfigurationChannelOpensSubscriptionConnectionEagerly (merged with the
3.4.29 sync) fails exactly there on CI, on both OSes, while fast local
machines win the race.

The wait itself broadens: when RequiresEagerSubscriptionConnection, the
endpoint's availability task also awaits the subscription executor's
ConnectNowAsync (short-circuits when up, joins the dial in flight,
declines onto a completed task under backoff, so the wait stays bounded
by the pass's budget), with a subscription-leg failure deliberately not
faulting the endpoint's availability - the interactive leg decides
selectability, and a refused subscription dial redials on demand.

Deliberately NOT by gating the connect monitors on the second leg, which
is how the v3 core does it (OnFullyEstablished): those monitors complete
on every reconnect, and gating them there re-times subscription
re-placement against one-shot publishes - Resp3DowngradeTests'
SubscribeQueuedBeforeDowngradeDoesNotPoisonInteractive fails
deterministically with the PUBLISH answered :0, the re-SUBSCRIBE a beat
behind it. The monitors keep their single-leg meaning; only the
reconfigure wait, which is what ConnectAsync means by connected, grows
the second leg.

The new test pins the race deterministically: an in-process server that
is slow to accept only the subscription leg (OnAcceptClientAsync now
has an overload seeing the declared connection type) must delay
ConnectAsync, not be escaped by it. Red on unfixed source with the CI
failure's exact shape; green with the fix, both protocols.
…nother call's reply (#3329) (#3332)

* The reader and Close take from the pending queue under one lock; a close with commands in flight no longer completes a call with another call's reply

RespConnection.Close drained _pending with a TryDequeue loop while the
reader, still matching replies from the receive buffer, dequeued from the
same ConcurrentQueue. The queue is safe for that; what it cannot promise
is which entry each side gets. Close took entries 0..N-1 and the reader
then took entry N for reply 0, so GET key N completed - successfully -
with key 0's value, and everything behind it was shifted the same way.
Measured with the reporter's loop against 4.0.155-alpha: 4,853 wrong
replies in 20,000 calls on CloseAsync(allowCommandsToComplete: false),
against 616 on main for the same race there.

TryTakePending checks closed and dequeues as one step under _pendingLock;
Close sets closed and then empties the queue under the same lock, failing
what it took outside it. Once a close has begun the reader takes nothing,
so a reply arriving late dies with the connection, and the command it
answered is failed by Close as before. Same run afterwards: 0.

The test is CloseInFlightTests from main (#3330): 20 rounds of 500
in-flight GETs against the real server, closed without waiting; no call
may complete with another call's value.

See #3329

* Commands failed by our own close get the RedisConnectionException v3 raised, not RESPite's InvalidOperationException

RespClientConnection already overrides CreateRemoteClosedFault so a server
close fails commands with RedisConnectionException(SocketClosed), as v3
did. Our own close - a dispose with commands in flight - went through
RespConnection's private fallback, a bare InvalidOperationException("The
connection is closed."), which is what CloseInFlightTests met and what a
caller catching RedisConnectionException around a shutdown would miss.
CreateClosedFault is the local-close counterpart, and the client
overrides it with ConnectionDisposed and a message naming the endpoint.
…s, and RenderedArgs goes (#3327)

The stragglers #3321 deliberately left: LatencyEventNames (the string[] ->
RedisValue[] copy) becomes an internal string[] overload on the Diagnostics
group writing through EventNamesOperand; the handshake's CLIENT TRACKING
broadcast splice becomes TrackingPrefixesOperand (nothing when prefix-less,
collapsing the two broadcast branches), with the tokens moving to pre-framed
RespLiterals fragments and the dead RedisValue literals - OFF included -
retired; and RenderedArgs + IRenderedArgsOwner (no implementers since the old
core went) are deleted along with their tests. Wire tests pin both operands
byte-for-byte.
…onnection core; CLIENT SETNAME/SETINFO get ledger rows (#3328)

First audit against v4's own surface (the ledger came over verbatim from
main in #3322). The subcommand heuristic only knew RedisLiterals members and
u8 literals, so v4's pre-framed [Resp] fragments made 39 implemented
subcommands look like gaps; it now parses RespLiterals.cs the same way. That
exposed four false RESOLVEDs from two handshake sends (CLUSTER INFO, whose
shared INFO token covered CLIENT INFO and COMMAND INFO too, and CLIENT
TRACKING): a command the library issues for itself is not one it exposes, so
use sites under Contexts/ no longer count, and bin/obj are skipped. An
implemented row is reported RESOLVED once the heuristic can see it, which
retires the HOTKEYS START and SCRIPT LOAD rows (fragments now; notes named v3
types). The two real omissions that uncovered: CLIENT SETNAME is
not-applicable (ClientName, no per-call API); CLIENT SETINFO is implemented
(handshake lib-name/lib-ver plus AddLibraryNameSuffix re-issuing lib-name
live - the whole command, as the server accepts nothing else). Final run
exits 0.
…hree stale comments it found

notes/v3-v4-behaviour-audit.md: every modified/deleted file between main (9d17974) and v4 reviewed,
with both branches' full suites run green against the same server. Release-note candidates, the
deliberately-unchanged list, and nine coverage debts where a contract lost its pin.

The comment fixes: BasicScalars/BasicAggregates said 'SUSPECTED REGRESSION ... skipped' for two
behaviours that are fixed in RespHandlers and asserted unskipped; TestBase.GetDatabase claimed a
StringTests override that does not exist.
…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 <[email protected]>

* 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 <[email protected]>
Co-authored-by: mohsinaliwork686-rgb <[email protected]>
Co-authored-by: Nikolay Zdravkov <[email protected]>
…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.
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.

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